diff --git a/.agents/skills/native-trigger/SKILL.md b/.agents/skills/native-trigger/SKILL.md index ae38f70b32..a4ff8e121a 100644 --- a/.agents/skills/native-trigger/SKILL.md +++ b/.agents/skills/native-trigger/SKILL.md @@ -84,7 +84,7 @@ pub trait External: Send + Sync + 'static { async fn prepare_webhook(&self, db, w_id, headers, body, script_path, is_flow) -> Result; fn service_config_from_create_response(&self, data, resp) -> Option; fn additional_routes(&self) -> axum::Router; - async fn http_client_request(&self, url, method, workspace_id, tx, db, headers, body) -> Result; + async fn http_client_request(&self, url, method, workspace_id, connection_path, db, headers, body) -> Result; } ``` @@ -115,28 +115,47 @@ Use this when the external_id is known before the create call (e.g., Google gene Use this when the external_id is assigned by the remote service and the webhook URL needs to be corrected after creation. -### OAuth Token Storage (Three-Table Pattern) +### OAuth App and Connections -OAuth tokens are stored across three tables, NOT in `workspace_integrations.oauth_data` directly: +The OAuth **app** (client) is configured per workspace and service; **connections** (connected +accounts) are many per service. Each trigger acts through one connection, named by +`native_trigger.connection_path`: | Table | What's Stored | |-------|---------------| -| `workspace_integrations` | `oauth_data` JSON with `base_url`, `client_id`, `client_secret`, `instance_shared` flag; `resource_path` pointing to the variable | -| `variable` | Encrypted `access_token` (at the path stored in `resource_path`), linked to `account` via `account` column | -| `account` | `refresh_token`, keyed by `workspace_id` + `client` (service name) + `is_workspace_integration = true` | +| `workspace_integrations` | `oauth_data` JSON with `base_url`, `client_id`, `client_secret`, `instance_shared` flag. One row per (workspace, service); it must exist for every connection, since token refresh reads the client from it | +| `variable` | Encrypted `access_token` at the connection path, linked to `account` via its `account` column | +| `account` | `refresh_token`, with `client` = service name and `is_workspace_integration = true` | +| `resource` | The connection's resource at the same path, `{ "token": "$var:" }` | -The `decrypt_oauth_data()` function in `lib.rs` assembles these into a unified struct: +A user may use a connection when they can read its variable (checked with a user transaction, +so the variable's row-level security decides): `resolve_usable_connection` / +`list_usable_connections` in `lib.rs`. The exception is the **workspace connection**: an admin +may share one connection per service (`workspace_integrations.resource_path`, set by +`POST .../workspace_connection`), and every member may then use it without reading its token. +Renames carry the marker along; disconnecting clears it. Background work (sync, renewal, rename re-registration, +webhook handling) uses the stored `connection_path` directly. + +`decrypt_oauth_data(db, w_id, service, connection_path)` assembles these into one struct, and +every service's `OAuthData` carries `connection_path` so `http_client_request` can refresh and +write back the right connection: ```rust pub struct OAuthConfig { pub base_url: String, - pub access_token: String, // decrypted from variable - pub refresh_token: Option, // from account table + pub access_token: String, // decrypted from the connection's variable + pub refresh_token: Option, // from its account pub client_id: String, // from oauth_data or instance settings pub client_secret: String, // from oauth_data or instance settings + pub connection_path: String, } ``` -Instance-level sharing: when `oauth_data.instance_shared == true`, `client_id` and `client_secret` are read from global settings instead of workspace_integrations. +A refreshed token is written back by connection path and account id, never by service: providers +like Nextcloud rotate refresh tokens, so writing one onto another account breaks its next refresh. + +Instance-level sharing: when the workspace has no OAuth app of its own and the instance admin +shares one (`share_with_workspaces` in the `oauths` setting; not available for Nextcloud), the +connect flow uses it and records `{"instance_shared": true}` in `workspace_integrations`. ### URL Resolution @@ -311,7 +330,7 @@ impl External for NewService { }); let response: CreateTriggerResponse = self - .http_client_request(&url, Method::POST, w_id, tx, db, None, Some(&payload)) + .http_client_request(&url, Method::POST, w_id, &oauth_data.connection_path, db, None, Some(&payload)) .await?; Ok(response) @@ -343,7 +362,7 @@ impl External for NewService { }); let _: serde_json::Value = self - .http_client_request(&url, Method::PUT, w_id, tx, db, None, Some(&payload)) + .http_client_request(&url, Method::PUT, w_id, &oauth_data.connection_path, db, None, Some(&payload)) .await?; // Fetch back the updated state to get the resolved config @@ -361,7 +380,7 @@ impl External for NewService { tx: &mut PgConnection, ) -> Result { let url = format!("{}/api/webhooks/{}", oauth_data.base_url, external_id); - self.http_client_request::<_, ()>(&url, Method::GET, w_id, tx, db, None, None).await + self.http_client_request::<_, ()>(&url, Method::GET, w_id, &oauth_data.connection_path, db, None, None).await } async fn delete( @@ -374,7 +393,7 @@ impl External for NewService { ) -> Result<()> { let url = format!("{}/api/webhooks/{}", oauth_data.base_url, external_id); let _: serde_json::Value = self - .http_client_request::<_, ()>(&url, Method::DELETE, w_id, tx, db, None, None) + .http_client_request::<_, ()>(&url, Method::DELETE, w_id, &oauth_data.connection_path, db, None, None) .await .or_else(|e| match &e { Error::InternalErr(msg) if msg.contains("404") => Ok(serde_json::Value::Null), @@ -749,7 +768,7 @@ pub async fn prepare_native_trigger_args(service_name, db, w_id, headers, body) When `workspace_integrations.oauth_data.instance_shared == true`, `decrypt_oauth_data()` reads `client_id` and `client_secret` from instance-level global settings instead of workspace-level. This allows admins to share OAuth app credentials across workspaces. -The frontend handles this via the `generate_instance_connect_url` endpoint in `workspace_integrations.rs`. +`generate_connect_url` picks the client (`resolve_oauth_client`): the workspace's own app when configured, the instance's otherwise. A GitHub OAuth app only redirects below its single registered callback, so connections made with the instance GitHub app land on `/oauth/callback/github/native_trigger` instead of the workspace settings page. --- diff --git a/.github/DockerfileBackendTests b/.github/DockerfileBackendTests index 2ce47ea714..e41a7bbff9 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.0/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.4/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.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /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 de0133dac0..564a621380 100644 --- a/.github/actions/sign-attest-image/action.yml +++ b/.github/actions/sign-attest-image/action.yml @@ -46,7 +46,15 @@ runs: env: IMAGE: ${{ inputs.image }} DIGEST: ${{ inputs.digest }} - run: cosign sign --yes --recursive "${IMAGE}@${DIGEST}" + # Fulcio and Rekor return transient 5xx often enough to fail a release; + # re-signing the same digest only adds a signature, so retrying is safe. + run: | + for attempt in 1 2 3 4 5; do + cosign sign --yes --recursive "${IMAGE}@${DIGEST}" && exit 0 + echo "::warning::cosign sign failed (attempt $attempt/5)" + [ "$attempt" -lt 5 ] && sleep $((attempt * 30)) + done + exit 1 - name: SLSA provenance (GitHub artifact attestation) uses: actions/attest-build-provenance@v4 diff --git a/.github/workflows/ai-agent-tests.yml b/.github/workflows/ai-agent-tests.yml index 8a3e9e6dbc..255f07e253 100644 --- a/.github/workflows/ai-agent-tests.yml +++ b/.github/workflows/ai-agent-tests.yml @@ -61,7 +61,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/ai-evals-scheduled.yml b/.github/workflows/ai-evals-scheduled.yml index 580a757c21..2bd8cdb181 100644 --- a/.github/workflows/ai-evals-scheduled.yml +++ b/.github/workflows/ai-evals-scheduled.yml @@ -46,7 +46,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - id: matrix env: @@ -93,7 +93,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/ai-evals-test.yml b/.github/workflows/ai-evals-test.yml index 84b488ae46..4dd266c364 100644 --- a/.github/workflows/ai-evals-test.yml +++ b/.github/workflows/ai-evals-test.yml @@ -75,7 +75,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/backend-test-windows.yml b/.github/workflows/backend-test-windows.yml index 9fa13bca58..8bbb73d379 100644 --- a/.github/workflows/backend-test-windows.yml +++ b/.github/workflows/backend-test-windows.yml @@ -73,7 +73,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: @@ -81,7 +81,7 @@ jobs: - uses: astral-sh/setup-uv@v7 with: - version: "0.13.0" + version: "0.13.4" - uses: shivammathur/setup-php@v2 with: diff --git a/.github/workflows/backend-test.yml b/.github/workflows/backend-test.yml index b01e99a696..f2dedd8c69 100644 --- a/.github/workflows/backend-test.yml +++ b/.github/workflows/backend-test.yml @@ -58,13 +58,13 @@ jobs: go-version: 1.21.5 - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: node-version: "24" - uses: astral-sh/setup-uv@v7 with: - version: "0.13.0" + version: "0.13.4" - uses: shivammathur/setup-php@v2 with: php-version: "8.3" diff --git a/.github/workflows/codex-pr-review.yml b/.github/workflows/codex-pr-review.yml index 2d70ad7f7a..e1628729d8 100644 --- a/.github/workflows/codex-pr-review.yml +++ b/.github/workflows/codex-pr-review.yml @@ -42,12 +42,14 @@ jobs: # skips auto-review for every private member. # Dependabot-triggered runs get a separate secret scope, so this job has no API # key and cannot review. workflow_call stays open for an explicit request. + # `[skip-ai-review]` in the PR body opts out of the automatic run only. if: | github.event_name == 'workflow_call' || ( github.event.pull_request.draft == false && github.event.pull_request.head.repo.fork == false && - github.event.pull_request.user.login != 'dependabot[bot]' + github.event.pull_request.user.login != 'dependabot[bot]' && + !contains(github.event.pull_request.body, '[skip-ai-review]') ) permissions: contents: read diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 51da953ab0..c046a7d101 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -197,47 +197,41 @@ jobs: ARCH: amd64 steps: - uses: actions/checkout@v4 - - run: | - # pulling docker image with desired arch so that actions-docker-extract doesn't do it - docker pull --platform "linux/$ARCH" ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - docker pull --platform "linux/$ARCH" ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} - - run: | - # Checks the image is in docker prior to running actions-docker-extract. It fails if not - # Also useful to visually check that the arch is the right opencontainers - docker image inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - docker image inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} - - - uses: shrink/actions-docker-extract@v3 - id: extract - with: - image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - path: "/usr/src/app/windmill" - - - uses: shrink/actions-docker-extract@v3 - id: extract-duckdb-ffi-internal - with: - image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - path: "/usr/src/app/windmill_duckdb_runner" - - - uses: shrink/actions-docker-extract@v3 - id: extract-ee - with: - image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} - path: "/usr/src/app/windmill" - - - name: Rename binary with corresponding architecture + # 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. + - name: Extract binaries + env: + CE_IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} + EE_IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} run: | - mv "${{ steps.extract.outputs.destination }}/windmill" "${{ steps.extract.outputs.destination }}/windmill-${ARCH}" - mv "${{ steps.extract-ee.outputs.destination }}/windmill" "${{ steps.extract-ee.outputs.destination }}/windmill-ee-${ARCH}" + set -euo pipefail + mkdir -p release + # extract ( )... + extract() { + local image=$1 cid + shift + docker pull --platform "linux/$ARCH" "$image" + docker image inspect --format '{{.Os}}/{{.Architecture}}' "$image" + cid=$(docker create --platform "linux/$ARCH" "$image") + while [ $# -gt 0 ]; do + docker cp "$cid:$1" "release/$2" + shift 2 + done + docker rm "$cid" + docker rmi "$image" + df -h / + } + extract "$CE_IMAGE" \ + /usr/src/app/windmill "windmill-$ARCH" \ + /usr/src/app/windmill_duckdb_runner windmill_duckdb_runner + extract "$EE_IMAGE" /usr/src/app/windmill "windmill-ee-$ARCH" + ls -la release - name: Attach binary to release uses: softprops/action-gh-release@v2 with: - files: | - ${{ steps.extract.outputs.destination }}/* - ${{ steps.extract-ee.outputs.destination }}/* - ${{ steps.extract-duckdb-ffi-internal.outputs.destination }}/* + files: release/* upload_ee_debug_to_s3: needs: [build_ee] diff --git a/.github/workflows/git-sync-test.yml b/.github/workflows/git-sync-test.yml index b19f899a20..7d26392dee 100644 --- a/.github/workflows/git-sync-test.yml +++ b/.github/workflows/git-sync-test.yml @@ -135,7 +135,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: denoland/setup-deno@v2 with: diff --git a/.github/workflows/pi-pr-review.yml b/.github/workflows/pi-pr-review.yml index a18dc28ff2..4b57db7b78 100644 --- a/.github/workflows/pi-pr-review.yml +++ b/.github/workflows/pi-pr-review.yml @@ -40,12 +40,14 @@ jobs: # skips auto-review for every private member. # Dependabot-triggered runs get a separate secret scope, so this job has no API # key and cannot review. workflow_call stays open for an explicit request. + # `[skip-ai-review]` in the PR body opts out of the automatic run only. if: | github.event_name == 'workflow_call' || ( github.event.pull_request.draft == false && github.event.pull_request.head.repo.fork == false && - github.event.pull_request.user.login != 'dependabot[bot]' + github.event.pull_request.user.login != 'dependabot[bot]' && + !contains(github.event.pull_request.body, '[skip-ai-review]') ) permissions: contents: read diff --git a/.github/workflows/pr-ready-review.yml b/.github/workflows/pr-ready-review.yml index 90714cba53..4b88273cad 100644 --- a/.github/workflows/pr-ready-review.yml +++ b/.github/workflows/pr-ready-review.yml @@ -39,12 +39,14 @@ jobs: # skips auto-review for every private member. # Dependabot-triggered runs get a separate secret scope, so this job has no API # key and cannot review. workflow_call stays open for an explicit request. + # `[skip-ai-review]` in the PR body opts out of the automatic run only. if: | github.event_name == 'workflow_call' || ( (github.event.pull_request.draft == false || github.event.pull_request.ready_for_review == true) && github.event.pull_request.head.repo.fork == false && - github.event.pull_request.user.login != 'dependabot[bot]' + github.event.pull_request.user.login != 'dependabot[bot]' && + !contains(github.event.pull_request.body, '[skip-ai-review]') ) permissions: contents: read diff --git a/.github/workflows/weekly-pr-summary.yml b/.github/workflows/weekly-pr-summary.yml index 9d1f0631fb..14551e9943 100644 --- a/.github/workflows/weekly-pr-summary.yml +++ b/.github/workflows/weekly-pr-summary.yml @@ -39,9 +39,10 @@ jobs: - This gives you the exact 7-day window (store these in variables for use in commands) 2. **Fetch ONLY Merged PRs from Past Week**: - - Command: `gh pr list --repo ${{ github.repository }} --state merged --search "merged:>=$CUTOFF_DATE" --limit 100 --json number,title,author,mergedAt,url` + - Command: `gh pr list --repo ${{ github.repository }} --state merged --search "merged:>=$CUTOFF_DATE" --limit 100 --json number,title,author,mergedAt,url,body --jq '[.[] | select((.body // "") | contains("[skip-ai-review]") | not) | del(.body)]'` - This returns ONLY PRs that were merged in the last 7 days - The --search flag filters by merge date using GitHub's search syntax + - The --jq filter drops PRs whose body contains `[skip-ai-review]`; never fetch or mention those PRs - **FILTER OUT** any PRs with titles starting with "chore: release" or "chore(release)" 3. **Categorize PRs**: Group PRs into three categories by analyzing titles and labels: diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3714717023..9edb1a8e87 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.841.0" + ".": "1.849.0" } diff --git a/AGENTS.md b/AGENTS.md index 6516e0e095..ef87f1c4dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,11 +41,14 @@ Open-source platform for internal tools, workflows, API integrations, background for an inline app runnable that opts in), why an admin's roles are not added, the per-role-set logins and the order their rows and logins are written in - **Enterprise**: `docs/enterprise.md` — EE file conventions and PR workflow +- **Workspace roles**: `docs/workspace-roles.md` — instance-defined roles with per-workspace + overrides, the capabilities a role holds, why `ApiAuthed::is_operator` must be derived from the + role, and the `role_seat` table billing reads - **Operator write rights**: `docs/operator-write-rights.md` — which `operator_settings` flags are enforced rather than cosmetic, and why a right that is granted-unless-withdrawn needs `Option` fields and a jsonb merge rather than a serde default - **Operator builder rights**: `docs/operator-builder-rights.md` — the workspace settings that let - operators compose flows and full-code apps, what the composition check must cover, which + 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 - **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 @@ -63,6 +66,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/mcp/session/`), 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, 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). What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/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). What a tool *does* is written twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). - **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 659adb9e25..d0fccb9912 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,163 @@ # Changelog +## [1.849.0](https://github.com/windmill-labs/windmill/compare/v1.848.3...v1.849.0) (2026-10-25) + + +### Features + +* per-user Anthropic Workload Identity Federation for Windmill AI ([#11998](https://github.com/windmill-labs/windmill/issues/11998)) ([6c8fd6c](https://github.com/windmill-labs/windmill/commit/6c8fd6cfe2057f2822230bdf9ad2058f537df996)) + +## [1.848.3](https://github.com/windmill-labs/windmill/compare/v1.848.2...v1.848.3) (2026-10-25) + + +### Bug Fixes + +* pin node to 24.22.1 in the worker image for CVE-2026-111497 ([#11995](https://github.com/windmill-labs/windmill/issues/11995)) ([0e79e93](https://github.com/windmill-labs/windmill/commit/0e79e934b6342150ee31de08a19400de482b1969)) + +## [1.848.2](https://github.com/windmill-labs/windmill/compare/v1.848.1...v1.848.2) (2026-10-24) + + +### Bug Fixes + +* tighten file handling in deno/bun, stricter codebase tarball,executor isolation ([#11990](https://github.com/windmill-labs/windmill/issues/11990)) ([ccf8892](https://github.com/windmill-labs/windmill/commit/ccf889269b8897be707cde639b2531d522c286c9)) + +## [1.848.1](https://github.com/windmill-labs/windmill/compare/v1.848.0...v1.848.1) (2026-10-23) + + +### Bug Fixes + +* restore workspace pg_dump changes reverted by 812ff6ea5e ([#11988](https://github.com/windmill-labs/windmill/issues/11988)) ([45d3c95](https://github.com/windmill-labs/windmill/commit/45d3c951bb8827c67daaaf75ed52f3c3e1215911)) +* use linkedin openid connect default scopes ([#11953](https://github.com/windmill-labs/windmill/issues/11953)) ([001313a](https://github.com/windmill-labs/windmill/commit/001313aa242c6de053a9deb0c6cdb64580ce1cee)) + +## [1.848.0](https://github.com/windmill-labs/windmill/compare/v1.847.0...v1.848.0) (2026-10-23) + + +### Features + +* add a use/plan/build mode picker and read-only prod sessions ([#11940](https://github.com/windmill-labs/windmill/issues/11940)) ([d6c2b2c](https://github.com/windmill-labs/windmill/commit/d6c2b2c68344bb95939701c418116b2e7d4715a3)) +* composer pills that teach Windmill from the workspace ([#11889](https://github.com/windmill-labs/windmill/issues/11889)) ([ebeea51](https://github.com/windmill-labs/windmill/commit/ebeea514926f60295f3f11f516f4ccda3448f829)) +* fill docusign, salesforce and quickbooks fields on connect ([#11960](https://github.com/windmill-labs/windmill/issues/11960)) ([11f2a4c](https://github.com/windmill-labs/windmill/commit/11f2a4c7ffac980036f839759ae93da6ff3f22e4)) +* group home row menus and open them at their final height ([#11949](https://github.com/windmill-labs/windmill/issues/11949)) ([91bf9b6](https://github.com/windmill-labs/windmill/commit/91bf9b67a74afb419659719949484f1cfd5338c0)) +* let flow builder operators build AI agents ([#11898](https://github.com/windmill-labs/windmill/issues/11898)) ([e5dedd1](https://github.com/windmill-labs/windmill/commit/e5dedd147e1db0c4f36796ba292188bcdb0efc5a)) +* manage and create folders from the home tree view ([#11943](https://github.com/windmill-labs/windmill/issues/11943)) ([da443d2](https://github.com/windmill-labs/windmill/commit/da443d2fb263ecaf90320809b1bb2fc8a4f65b20)) +* run a workspace handler when a variable's value expires ([#10837](https://github.com/windmill-labs/windmill/issues/10837)) ([7a29abc](https://github.com/windmill-labs/windmill/commit/7a29abc7eec491c35217445c1c08486ff030a22c)) + + +### Bug Fixes + +* change an app's access mode under the deploy row lock ([#11965](https://github.com/windmill-labs/windmill/issues/11965)) ([725b15f](https://github.com/windmill-labs/windmill/commit/725b15f546cf20c2e5908acffb105d73fe907558)) +* fork a raw app into the raw app builder, in its session when there ([#11978](https://github.com/windmill-labs/windmill/issues/11978)) ([3d6a2bc](https://github.com/windmill-labs/windmill/commit/3d6a2bcef2e284d64690db04db32a2326a4b0670)) +* home's acting-on follows the workspace home switches to ([#11946](https://github.com/windmill-labs/windmill/issues/11946)) ([18c6936](https://github.com/windmill-labs/windmill/commit/18c69360c9a8e9a9fe4c7c1d9e825a2b7be403a9)) +* keep a staged flow path across reloads and follow moves in session tabs ([#11967](https://github.com/windmill-labs/windmill/issues/11967)) ([6b56656](https://github.com/windmill-labs/windmill/commit/6b56656bd650f2db5fbd74e23b55b926c6f69dd7)) +* keep the log indexer starting when a stored day chunk is broken ([#11979](https://github.com/windmill-labs/windmill/issues/11979)) ([79fe8ab](https://github.com/windmill-labs/windmill/commit/79fe8ab03f6f052bf7fe763b6f8a0a23fe922611)) +* list usr columns explicitly in whoami's user lookup ([#11970](https://github.com/windmill-labs/windmill/issues/11970)) ([fb193d7](https://github.com/windmill-labs/windmill/commit/fb193d7a816ae97fa8fc60608270296e159dfd3c)) +* make the autoscaling Test scaling button run the integration ([#11972](https://github.com/windmill-labs/windmill/issues/11972)) ([72c6b10](https://github.com/windmill-labs/windmill/commit/72c6b10821cfa35ff3deb3a3ecc729ed75a9dbc6)) +* return variable.value as text so widening it changes no result type ([#11976](https://github.com/windmill-labs/windmill/issues/11976)) ([f6f3a0a](https://github.com/windmill-labs/windmill/commit/f6f3a0a1f24cd9ea0d78207d6848147ebd73bea0)) +* run unstamped git auto-pulls as a superadmin when no admin ([#11973](https://github.com/windmill-labs/windmill/issues/11973)) ([c89a827](https://github.com/windmill-labs/windmill/commit/c89a82750ed0a461d8d4f1502f019bc0da4ed58c)) +* send app editor inspector picks to a new AI session as a chip ([#11966](https://github.com/windmill-labs/windmill/issues/11966)) ([28d2556](https://github.com/windmill-labs/windmill/commit/28d2556c941f66cad353eca3809f43e8d8cf3c05)) +* share settings.yaml's git sync block between a fork and its parent ([#11974](https://github.com/windmill-labs/windmill/issues/11974)) ([fe38a1d](https://github.com/windmill-labs/windmill/commit/fe38a1d3763a11f8b0bc4b07d61824d3a7b51850)) + +## [1.847.0](https://github.com/windmill-labs/windmill/compare/v1.846.1...v1.847.0) (2026-10-22) + + +### Features + +* add job_id and flow_path to flow step error objects ([#11941](https://github.com/windmill-labs/windmill/issues/11941)) ([eeb48f0](https://github.com/windmill-labs/windmill/commit/eeb48f0c26ccc5162430eddec24adc2601eb5f99)) +* chat with a saved agent from a raw app through an agent runnable ([#11921](https://github.com/windmill-labs/windmill/issues/11921)) ([c6a93a9](https://github.com/windmill-labs/windmill/commit/c6a93a9b565752da6c8b55d383e5bee88f00f229)) +* let native triggers act through per-user or shared connections ([#11352](https://github.com/windmill-labs/windmill/issues/11352)) ([dc1fb50](https://github.com/windmill-labs/windmill/commit/dc1fb5087be7169045aad57e955dabe3e29de82e)) +* slack agents through a workspace's own slack app ([#11912](https://github.com/windmill-labs/windmill/issues/11912)) ([34de8bc](https://github.com/windmill-labs/windmill/commit/34de8bc06d2b04f7929bb8cf35f9a34d0e0071fa)) +* worker group toggle to keep the worker's proxy out of jobs ([#11958](https://github.com/windmill-labs/windmill/issues/11958)) ([8a0318a](https://github.com/windmill-labs/windmill/commit/8a0318a28f5cfda7557b0f94db20ef17b0664ee4)) + + +### Bug Fixes + +* compare a null resource description as empty ([#11947](https://github.com/windmill-labs/windmill/issues/11947)) ([8a7b148](https://github.com/windmill-labs/windmill/commit/8a7b1481bd270df3a98c9db5e7824d13b8cd37b6)) +* compare fork secret variables by decrypted value ([#11952](https://github.com/windmill-labs/windmill/issues/11952)) ([0dd131b](https://github.com/windmill-labs/windmill/commit/0dd131b38074423de5c769cae478c6ea0ae365c2)) +* hold home's ai composer space with a matching placeholder ([#11936](https://github.com/windmill-labs/windmill/issues/11936)) ([9202a74](https://github.com/windmill-labs/windmill/commit/9202a74071ba424ad6cfc1cfded518ee7db002dc)) +* link a variable to its OAuth account only in the connect flow ([#11361](https://github.com/windmill-labs/windmill/issues/11361)) ([d6adac8](https://github.com/windmill-labs/windmill/commit/d6adac8b7579ad6c3df5caab9a735451c1ddd896)) +* stop audit inserts from silently rolling back saves ([#11938](https://github.com/windmill-labs/windmill/issues/11938)) ([5ef19a8](https://github.com/windmill-labs/windmill/commit/5ef19a88a90b3a4fe05a78547416082dc51763f5)) + +## [1.846.1](https://github.com/windmill-labs/windmill/compare/v1.846.0...v1.846.1) (2026-10-21) + + +### Bug Fixes + +* home recent cards include items opened on their own page ([#11934](https://github.com/windmill-labs/windmill/issues/11934)) ([5019fab](https://github.com/windmill-labs/windmill/commit/5019fab5a5f996796a07524c770f86309a7a3500)) +* home search suggests filters whose name matches the typed text ([#11933](https://github.com/windmill-labs/windmill/issues/11933)) ([bf1eb85](https://github.com/windmill-labs/windmill/commit/bf1eb85577419cc08482158c1835d5262ebb87d2)) + +## [1.846.0](https://github.com/windmill-labs/windmill/compare/v1.845.0...v1.846.0) (2026-10-21) + + +### Features + +* home list settings menu with sort, library and user-folder toggles ([#11928](https://github.com/windmill-labs/windmill/issues/11928)) ([73f655d](https://github.com/windmill-labs/windmill/commit/73f655db98dd0f0fd03881c36e6c9310fb2687a2)) + + +### Bug Fixes + +* home's acting-on pick switches the current workspace ([#11929](https://github.com/windmill-labs/windmill/issues/11929)) ([cdaddcc](https://github.com/windmill-labs/windmill/commit/cdaddcce594378bf502f80e8f225f16b5def5eb4)) + +## [1.845.0](https://github.com/windmill-labs/windmill/compare/v1.844.0...v1.845.0) (2026-10-21) + + +### Features + +* home and empty ai sessions share one session composer ([#11635](https://github.com/windmill-labs/windmill/issues/11635)) ([56b2e10](https://github.com/windmill-labs/windmill/commit/56b2e106daedb5ae381052d3116346a88ba3f206)) + +## [1.844.0](https://github.com/windmill-labs/windmill/compare/v1.843.0...v1.844.0) (2026-10-21) + + +### Features + +* serve the ai session toolset over mcp at /api/mcp ([#11738](https://github.com/windmill-labs/windmill/issues/11738)) ([892334f](https://github.com/windmill-labs/windmill/commit/892334f008d5b6b73de38fdf2831b1a63eeb0a51)) + +## [1.843.0](https://github.com/windmill-labs/windmill/compare/v1.842.0...v1.843.0) (2026-10-21) + + +### Features + +* configurable workspace roles with per-workspace overrides ([#11821](https://github.com/windmill-labs/windmill/issues/11821)) ([21d2a49](https://github.com/windmill-labs/windmill/commit/21d2a49971b858ff8aef2776a36989b57ba49415)) +* move the open in AI session button to the page header ([#11888](https://github.com/windmill-labs/windmill/issues/11888)) ([34db239](https://github.com/windmill-labs/windmill/commit/34db23952a765bbb9c912d74d2a37092703f50f7)) +* ship php only on the full images ([#11922](https://github.com/windmill-labs/windmill/issues/11922)) ([b874861](https://github.com/windmill-labs/windmill/commit/b87486141df5b4f9b93900c0ee3264cf4b4610ec)) +* workspace roles settings UI and capability-based gating ([#11824](https://github.com/windmill-labs/windmill/issues/11824)) ([8dbdfa1](https://github.com/windmill-labs/windmill/commit/8dbdfa194912bf36a705392899b9f84b5a54fd55)) + + +### Bug Fixes + +* compact the AI chat history between tool iterations ([#11911](https://github.com/windmill-labs/windmill/issues/11911)) ([17de2ba](https://github.com/windmill-labs/windmill/commit/17de2ba983bee5cb7df700476ec8a0169c97ecbd)) +* refuse restarting a flow past an approval that was never granted ([#11920](https://github.com/windmill-labs/windmill/issues/11920)) ([2c6bcc0](https://github.com/windmill-labs/windmill/commit/2c6bcc09c9b6f768592b31ec540d727263a807cc)) +* remove horizontal scroll in the new workspace form ([#11909](https://github.com/windmill-labs/windmill/issues/11909)) ([d35c868](https://github.com/windmill-labs/windmill/commit/d35c86896fa4f5f9936a9f61735553e2ff42b218)) +* revoke mcp oauth grants on password change and reset ([#11908](https://github.com/windmill-labs/windmill/issues/11908)) ([c044777](https://github.com/windmill-labs/windmill/commit/c04477723c9d7544ea9c595e33fdcff5cce0c79d)) +* **worker:** render TEMP_SCRIPT_REFS placeholder in Python runner-group loader.py ([#11915](https://github.com/windmill-labs/windmill/issues/11915)) ([78fb800](https://github.com/windmill-labs/windmill/commit/78fb800904351f6b549b8b2227cb9c0d5dafd55d)) + +## [1.842.0](https://github.com/windmill-labs/windmill/compare/v1.841.0...v1.842.0) (2026-10-20) + + +### Features + +* let AI agents answer in Slack ([#11630](https://github.com/windmill-labs/windmill/issues/11630)) ([35b250e](https://github.com/windmill-labs/windmill/commit/35b250e76739a1e6f543971b099d5796a44d0c89)) +* name the action on chat tool confirmation buttons ([#11795](https://github.com/windmill-labs/windmill/issues/11795)) ([7d01d25](https://github.com/windmill-labs/windmill/commit/7d01d252b526987f8f0b86695de2f9c90de64519)) + + +### Bug Fixes + +* align collapsed conversations sidebar chat icon with the buttons above ([#11873](https://github.com/windmill-labs/windmill/issues/11873)) ([24238d4](https://github.com/windmill-labs/windmill/commit/24238d4062801558f90728b17e3d70e980c733dd)) +* align sidebar home with the header when ai sessions is off ([#11882](https://github.com/windmill-labs/windmill/issues/11882)) ([1874808](https://github.com/windmill-labs/windmill/commit/18748084705dc48994b7378217e0df1e8bfbfe3f)) +* give the agent page's API and Slack sections tabs on small screens ([#11901](https://github.com/windmill-labs/windmill/issues/11901)) ([394d345](https://github.com/windmill-labs/windmill/commit/394d345e0c8d9d7da87371e8da090d3becc77ce7)) +* keep schedule push, flow advance, wac approval and scim on one pool connection ([#11904](https://github.com/windmill-labs/windmill/issues/11904)) ([8afe060](https://github.com/windmill-labs/windmill/commit/8afe0607abd6bb689a0644916fcdc39fb7df2fe3)) +* keep the flow chat mounted when leaving the chat tab ([#11872](https://github.com/windmill-labs/windmill/issues/11872)) ([ed58996](https://github.com/windmill-labs/windmill/commit/ed589963f4d7b7d50a69cacdede443f2bb7efd18)) +* let devops users reach instance pages without a workspace ([#11876](https://github.com/windmill-labs/windmill/issues/11876)) ([a3a4fa5](https://github.com/windmill-labs/windmill/commit/a3a4fa503804eb9f031699b60e00a196d223cbe6)) +* **mcp:** escape JSON inlined in the MCP OAuth callback page ([#11880](https://github.com/windmill-labs/windmill/issues/11880)) ([5d0a8a9](https://github.com/windmill-labs/windmill/commit/5d0a8a9c15cd54032f930f8a21a0c2c3b517d60d)) +* refresh oauth tokens without holding a pool connection ([#11905](https://github.com/windmill-labs/windmill/issues/11905)) ([8ddb358](https://github.com/windmill-labs/windmill/commit/8ddb358198e834642f259197aa5f6d96bd7740d3)) +* spell the schedule pause time the way the picker writes it ([#11875](https://github.com/windmill-labs/windmill/issues/11875)) ([4186fff](https://github.com/windmill-labs/windmill/commit/4186ffff841d5905d308aa6bae8159aba3794c1c)) +* stop holding a pool connection while waiting for another ([#11902](https://github.com/windmill-labs/windmill/issues/11902)) ([2c559b4](https://github.com/windmill-labs/windmill/commit/2c559b452f38cc86fe45bcdb98574245fd2cf187)) +* write a push's runnable settings before it opens its transaction ([#11897](https://github.com/windmill-labs/windmill/issues/11897)) ([e6c8ef1](https://github.com/windmill-labs/windmill/commit/e6c8ef18a11f079083138a991543f7e273d4e511)) + + +### Performance Improvements + +* show the AI sessions composer before the chat code loads ([#11886](https://github.com/windmill-labs/windmill/issues/11886)) ([613adb5](https://github.com/windmill-labs/windmill/commit/613adb5287812cf428a74b10e1ef9362d78751b8)) + ## [1.841.0](https://github.com/windmill-labs/windmill/compare/v1.840.0...v1.841.0) (2026-10-18) diff --git a/Dockerfile b/Dockerfile index 79f9d05734..7d53a5a58a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -144,6 +144,9 @@ ARG KUBECTL_VERSION=1.37.1 ARG HELM_VERSION=3.21.4 # NOTE: If changing, also change go version in workspace dependencies template at WorkspaceDependenciesEditor.svelte ARG GO_VERSION=1.27.1 +# Pinned to the patch: an unpinned install is cached by the image build and stops picking up +# security releases. +ARG NODE_VERSION=24.22.1 ARG APP=/usr/src/app ARG WITH_POWERSHELL=true ARG WITH_KUBECTL=true @@ -166,8 +169,12 @@ ENV UV_TOOL_DIR=/usr/local/uv ENV PATH /usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH - -RUN apt-get update \ +# 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 +RUN echo "apt refresh ${APT_REFRESH}" \ + && apt-get update \ && apt-get upgrade -y \ && apt-get install -y --no-install-recommends netbase tzdata ca-certificates wget curl jq unzip build-essential unixodbc xmlsec1 tini gnupg libargon2-1 \ && if echo "$features" | grep -q "ee"; then apt-get install -y --no-install-recommends libsasl2-modules-gssapi-mit krb5-user; fi \ @@ -241,7 +248,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.0/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.4/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 @@ -252,8 +259,8 @@ RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_r RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $NEW_INSTANCE_PY --compile-bytecode -RUN curl -sL https://deb.nodesource.com/setup_24.x | bash - -RUN apt-get -y update && apt-get install -y --no-install-recommends curl procps nodejs awscli && apt-get clean \ +RUN curl -sL https://deb.nodesource.com/setup_${NODE_VERSION%%.*}.x | bash - +RUN apt-get -y update && apt-get install -y --no-install-recommends curl procps nodejs=${NODE_VERSION}-1nodesource1 awscli && apt-get clean \ && rm -rf /var/lib/apt/lists/* # The npm bundled with nodejs is replaced by a pinned one: it is what `//npm` scripts install with @@ -293,7 +300,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.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI RUN bun install -g windmill-cli \ @@ -305,9 +312,6 @@ RUN bun install -g windmill-cli \ RUN curl -fsSL https://claude.ai/install.sh | bash \ && cp /root/.local/share/claude/versions/* /usr/bin/claude -COPY --from=php:8.3.33-cli-trixie /usr/local/bin/php /usr/bin/php -COPY --from=composer:2.9.5 /usr/bin/composer /usr/bin/composer - # add the docker client to call docker from a worker if enabled COPY --from=docker:29-dind /usr/local/bin/docker /usr/local/bin/ diff --git a/LICENSE b/LICENSE index aea6c58c6f..7e682e7dd1 100644 --- a/LICENSE +++ b/LICENSE @@ -30,5 +30,18 @@ quotas set in the software and a right to distribute the community edition as is but not to sell, resell, serve as a managed service, modify or wrap under any form without an explicit agreement. +To re-expose directly any Windmill parts to your users (see +https://www.windmill.dev/docs/misc/white_labelling) as a feature of your +product, with the exception of iframed public Windmill "apps", or to build a +feature on top of "Windmill Community Edition" that you sell commercially or +embed in a distributable product or binary, you must get a commercial license. +Contact us at sales@windmill.dev if you have any questions. To do the same from +the binary compiled from the source code in this repository without the +"enterprise" feature flag, you must comply with the AGPLv3 license terms and +conditions or get a commercial license from Windmill Labs, Inc. + +To use Windmill "Community Edition" as is internally in your organization, or to +use its APIs as is, you do NOT need a commercial license. + All third party components incorporated into the Windmill Software are licensed under the original license provided by the owner of the applicable component. diff --git a/README.md b/README.md index e9ed6381f1..df877e2c0f 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@

-Open-source developer platform for internal code: APIs, background jobs, workflows and UIs. Self-hostable alternative to Retool, Pipedream, Superblocks and a simplified Temporal with autogenerated UIs and custom UIs to trigger workflows and scripts as internal apps. +Open-source, self-hostable code-first platform for workflows, apps and AI agents, running on the fastest self-hostable orchestrator. Engineers write code in 20+ languages and sync it with Git. Business teams build on the same platform with AI, while review, promotion between environments and isolated workers keep engineers in control of what ships. Self-hostable alternative to Lovable, Retool, n8n and a simplified Temporal.

-Scripts are turned into sharable UIs automatically, and can be composed together into flows or used into richer apps built with low-code. Supported languages: Python, TypeScript, Go, Bash, SQL, GraphQL, PowerShell, Rust, and more. +Scripts are turned into sharable UIs, APIs and cron jobs automatically, and can be composed together into flows, data pipelines, AI agents or full-code React and Svelte apps. Supported languages: Python, TypeScript, Go, Bash, SQL, GraphQL, PowerShell, Rust, and more.

@@ -34,7 +34,7 @@ Scripts are turned into sharable UIs automatically, and can be composed together Try it - Website - Docs - Discord - Hub - Contributing

-# Windmill - Developer platform for APIs, background jobs, workflows and UIs +# Windmill - Code-first platform for workflows, apps and AI agents Windmill is fully open-sourced (AGPLv3) and Windmill Labs offers dedicated instances and commercial support and licenses. @@ -42,10 +42,12 @@ Windmill is fully open-sourced (AGPLv3) and Windmill Labs offers dedicated insta https://github.com/user-attachments/assets/d80de1d9-64de-4d89-aacd-6df23fa81fc4 -- [Windmill - Developer platform for APIs, background jobs, workflows and UIs](#windmill---developer-platform-for-apis-background-jobs-workflows-and-uis) +- [Windmill - Code-first platform for workflows, apps and AI agents](#windmill---code-first-platform-for-workflows-apps-and-ai-agents) + - [Build with AI, ship with review](#build-with-ai-ship-with-review) - [Main Concepts](#main-concepts) - - [Show me some actual script code](#show-me-some-actual-script-code) - - [Local Development](#local-development) + - [What the code looks like](#what-the-code-looks-like) + - [Data: data tables, DuckDB and DuckLake](#data-data-tables-duckdb-and-ducklake) + - [Develop locally or in the browser](#develop-locally-or-in-the-browser) - [Stack](#stack) - [Fastest Self-Hostable Workflow Engine](#fastest-self-hostable-workflow-engine) - [Security](#security) @@ -59,13 +61,21 @@ https://github.com/user-attachments/assets/d80de1d9-64de-4d89-aacd-6df23fa81fc4 - [License](#license) - [Integrations](#integrations) - [Environment Variables](#environment-variables) - - [Run a local dev setup](#run-a-local-dev-setup) - - [Frontend only](#frontend-only) - - [Backend + Frontend](#backend--frontend) - [Contributing](#contributing) - - [Contributors](#contributors) - [Copyright](#copyright) +## Build with AI, ship with review + +Business teams and engineers build on the same Windmill instance. What the AI builds is an ordinary script, flow or app, and goes through the same review as code written by engineers: + +- [AI sessions](https://www.windmill.dev/docs/core_concepts/ai_sessions) build scripts, flows and apps with AI in a workspace fork, with a live preview and a diff to review before deploying. +- [Workspace roles](https://www.windmill.dev/docs/core_concepts/roles_and_permissions#workspace-roles) decide what each team can author, and [folders](https://www.windmill.dev/docs/core_concepts/groups_and_folders) scope the resources, skills and MCP servers its AI can reach. +- [Protection rulesets](https://www.windmill.dev/docs/core_concepts/protection_rulesets) block direct deployment, so changes reach production only after an engineer reviews and deploys them. +- [Dev workspaces](https://www.windmill.dev/docs/advanced/dev_workspaces) keep their own credentials, and promote to prod through Compare & Deploy or a Git pull request. +- [Worker groups](https://www.windmill.dev/docs/core_concepts/worker_groups) run AI-built code on its own workers, or on a [separate instance](https://www.windmill.dev/docs/core_concepts/staging_prod#deploy-to-a-workspace-on-another-instance). + +See [let business teams build with AI safely](https://www.windmill.dev/docs/advanced/ai_guardrails) for the full setup. Engineers keep writing code locally with the [CLI](https://www.windmill.dev/docs/advanced/cli), the [VS Code extension](https://www.windmill.dev/docs/cli_local_dev/vscode-extension) and their coding agent, synced with [Git](https://www.windmill.dev/docs/advanced/git_sync). + ## 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): @@ -90,54 +100,93 @@ Scripts and flows can be triggered by [schedules](https://www.windmill.dev/docs/ Build your entire infra on top of Windmill! -## Show me some actual script code +## What the code looks like + +A script is a plain function. Its typed arguments become a generated form, an HTTP endpoint and a CLI command: ```typescript -//import any dependency from npm import * as wmill from "windmill-client"; -import * as cowsay from "cowsay@1.5.0"; - -// fill the type, or use the +Resource type to get a type-safe reference to a resource -type Postgresql = { - host: string; - port: number; - user: string; - dbname: string; - sslmode: string; - password: string; -}; +import dayjs from "dayjs"; // any npm package, resolved and pinned automatically export async function main( - a: number, - b: "my" | "enum", - c: Postgresql, - d = "inferred type string from default arg", - e = { nested: "object" } - //f: wmill.Base64 + customerId: string, + plan: "starter" | "pro", // a union of strings becomes a dropdown + trialDays = 14 // defaults infer the type ) { - const email = process.env["WM_EMAIL"]; - // variables are permissioned and by path - let variable = await wmill.getVariable("f/company-folder/my_secret"); - const lastTimeRun = await wmill.getState(); - // logs are printed and always inspectable - console.log(cowsay.say({ text: "hello " + email + " " + lastTimeRun })); - await wmill.setState(Date.now()); + const trialEnd = dayjs().add(trialDays, "day").toISOString(); - // return is serialized as JSON - return { foo: d, variable }; + // a data table: the workspace's Postgres, queried without a connection string + const sql = wmill.datatable(); + await sql`INSERT INTO trials (customer_id, plan, trial_end) VALUES (${customerId}, ${plan}, ${trialEnd})`.fetch(); + + // secrets are permissioned by path + const slackToken = await wmill.getVariable("f/sales/slack_token"); + await fetch("https://slack.com/api/chat.postMessage", { + method: "POST", + headers: { Authorization: `Bearer ${slackToken}`, "Content-Type": "application/json" }, + body: JSON.stringify({ channel: "#sales", text: `New ${plan} trial: ${customerId}` }), + }); + + console.log(`Trial started for ${customerId}`); // logs stream live in the UI + return { customerId, plan, trialEnd }; // returned as JSON } ``` -## Local Development +Workflows are code too. Each task runs as its own job with its own logs, and waiting for an approval releases the worker: -Windmill supports multiple ways to develop locally and sync with your instance: +```typescript +import { task, waitForApproval, workflow } from "windmill-client"; + +async function plan(env: string) { + return { env, changes: 3 }; +} + +async function apply(plan: { env: string; changes: number }) { + return `applied ${plan.changes} changes to ${plan.env}`; +} + +export const main = workflow(async (env: string) => { + const changes = await task(plan)(env); + const approval = await waitForApproval({ timeout: 3600 }); + if (!approval.approved) { + return `rejected by ${approval.approver}`; + } + return await task(apply)(changes); +}); +``` + +Flows can also be built in the visual [flow editor](https://www.windmill.dev/docs/flows/flow_editor) or as YAML, with scripts like the first one as steps. See [workflows as code](https://www.windmill.dev/docs/core_concepts/workflows_as_code). + +## Data: data tables, DuckDB and DuckLake + +- [Data tables](https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables) give each workspace managed Postgres tables, queried with type-checked SQL from TypeScript, Python and DuckDB scripts without exposing a connection string. +- [DuckDB](https://www.windmill.dev/docs/integrations/duckdb) scripts query S3 and Azure Blob files (CSV, Parquet, JSON), data tables, Postgres, MySQL and BigQuery in SQL, on your workers. +- [DuckLake](https://www.windmill.dev/docs/core_concepts/persistent_storage/ducklake) stores large datasets as lakehouse tables in your workspace object storage, queried in plain SQL. +- [Pipelines](https://www.windmill.dev/docs/core_concepts/pipelines) (alpha) wire scripts by the data they read and write instead of a hand-drawn DAG. This script runs whenever `events` is materialized, and materializes its own table: + +```sql +-- pipeline +-- on ducklake://main/events +-- materialize ducklake://main/events_by_kind +ATTACH 'ducklake://main' AS dl; +SELECT kind, count(*) AS n +FROM dl.events +GROUP BY kind; +``` + +Existing [dbt projects](https://www.windmill.dev/docs/getting_started/scripts_quickstart/dbt) run unmodified as scripts. See the [pipelines quickstart](https://www.windmill.dev/docs/getting_started/pipeline_quickstart). + +## Develop locally or in the browser + +Engineers work from their editor and coding agent, business teams build with AI in the browser, and both land in the same workspace: | Tool | Description | |------|-------------| -| **[CLI](https://www.windmill.dev/docs/advanced/cli)** | Sync scripts from local files or GitHub, run scripts/flows from the command line | -| **[VS Code Extension](https://www.windmill.dev/docs/cli_local_dev/vscode-extension)** | Edit and test scripts & flows directly from VS Code / Cursor with full IDE support | -| **[Git Sync](https://www.windmill.dev/docs/advanced/git_sync)** | Two-way sync between Windmill and your Git repository | -| **[Claude Code](https://www.windmill.dev/docs/core_concepts/ai_generation)** | AI-assisted development with Claude for scripts, flows, and apps | +| **[CLI](https://www.windmill.dev/docs/advanced/cli)** | Sync a workspace with local files and Git, run scripts and flows from the command line. `wmill init` generates `AGENTS.md` and [skill files](https://www.windmill.dev/docs/misc/guides/local_dev_with_ai) for Claude Code, Cursor and other AI tools | +| **[VS Code extension](https://www.windmill.dev/docs/cli_local_dev/vscode-extension)** | Edit and test scripts and flows from VS Code or Cursor with full IDE support | +| **[Git sync](https://www.windmill.dev/docs/advanced/git_sync)** | Two-way sync between a workspace and your Git repository | +| **[MCP server](https://www.windmill.dev/docs/core_concepts/mcp)** | Let coding agents and AI clients run scripts, manage resources and monitor jobs in a workspace | +| **[AI sessions](https://www.windmill.dev/docs/core_concepts/ai_sessions)** | The same agent loop in the browser, with nothing to install: plan mode, skills and MCP servers, a live preview, and a diff to review before deploying, in a fork of the workspace | https://github.com/user-attachments/assets/c541c326-e9ae-4602-a09a-1989aaded1e9 @@ -152,7 +201,8 @@ You can run scripts locally by passing the right environment variables for the ` - **Runtimes**: - TypeScript/JavaScript: Bun (default); Deno only on the `windmill-full` images - Python: python3 with uv for dependency management - - Go, Bash, PowerShell, PHP, Rust, C#, Java, Ansible + - PHP: only on the `windmill-full` images + - Go, Bash, PowerShell, Rust, C#, Java, Ansible ## Fastest Self-Hostable Workflow Engine @@ -184,11 +234,12 @@ back to the database is ~50ms. A typical lightweight deno job will take around ## Architecture -

+Stateless API servers and workers share a PostgreSQL database that holds the job queue and all workspace state (remote agent workers go through the API servers instead). Workers pull jobs by tag, so each worker group can run in its own network, for example dev workers that only reach dev systems and prod workers that only run reviewed code. - - -

+ + + Windmill architecture: business teams and engineers build through stateless API servers into workspaces, where changes move from dev and forks to prod after review. PostgreSQL holds the job queue and state. Worker groups for dev and prod, native workers and remote agent workers pull jobs by tag and reach your databases, APIs and AI model providers. + ## How to self-host @@ -229,15 +280,11 @@ Configure OAuth and SSO (Google Workspace, Microsoft/Azure, Okta) directly from ### License -The Community Edition is free to use internally. For commercial redistribution or managed services, contact . See [LICENSE](./LICENSE) and [Pricing](https://www.windmill.dev/pricing) for details. +- Using the Community Edition as is, internally or through its APIs, is free and needs no commercial license, within the limits and quotas set in the software. +- Selling, reselling or serving the Community Edition as a managed service, modifying or wrapping it, or re-exposing it to your users as a feature of your product (iframed public apps excepted) requires a commercial license: contact . +- The binary built from this repository without the `enterprise` feature flag is open source under [AGPLv3](./LICENSE-AGPL): the same uses are then allowed under the AGPLv3 terms, or with a commercial license. The API clients and the OpenAPI spec are [Apache 2.0](./LICENSE-APACHE). -The "Community Edition" of Windmill available in the docker images hosted under ghcr.io/windmill-labs/windmill and the github binary releases contains the files under the AGPLv3 and Apache 2 sources but also includes proprietary and non-public code and features which are not open source and under the following terms: Windmill Labs, Inc. grants a right to use all the features of the "Community Edition" for free without restrictions other than the limits and quotas set in the software and a right to distribute the community edition as is but not to sell, resell, serve Windmill as a managed service, modify or wrap under any form without an explicit agreement. - -The binary compilable from source code in this repository without the "enterprise" feature flag is open-source under the [LICENSE-AGPLv3](https://github.com/windmill-labs/windmill/blob/main/LICENSE-AGPL) License terms and conditions. - -To [re-expose directly any Windmill parts to your users](https://www.windmill.dev/docs/misc/white_labelling) as a feature of your product, with the exception of iframed public Windmill "apps", or to build a feature on top of "Windmill Community Edition" that you sell commercially or embed in a distributable product or binary, you must get a commercial license. Contact us at if you have any questions. To do the same from the binary compiled from the source code in this repository without the "enterprise" feature flag, you must comply with the AGPLv3 license terms and conditions or get a commercial license from Windmill Labs, Inc. - -To use Windmill "Community Edition" as is internally in your organization, or to use its APIs as is, you do NOT need a commercial license. +See [LICENSE](./LICENSE) for the full terms and [Pricing](https://www.windmill.dev/pricing) for plans. ### Integrations @@ -248,88 +295,17 @@ On self-hosted instances, you might want to import all the approved resource typ ## Environment Variables -| Environment Variable name | Default | Description | Api Server/Worker/All | -| ----------------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| DATABASE_URL | | The Postgres database url. | All | -| WORKER_GROUP | default | The worker group the worker belongs to and get its configuration pulled from | Worker | -| MODE | standalone | The mode if the binary. Possible values: standalone, worker, server, agent | All | -| METRICS_ADDR | None | (ee only) The socket addr at which to expose Prometheus metrics at the /metrics path. Set to "true" to expose it on port 8001 | All | -| JSON_FMT | false | Output the logs in json format instead of logfmt | All | -| BASE_URL | http://localhost:8000 | The base url that is exposed publicly to access your instance. Is overriden by the instance settings if any. | Server | -| ZOMBIE_JOB_TIMEOUT | 30 | The timeout after which a job is considered to be zombie if the worker did not send pings about processing the job (every server check for zombie jobs every 30s) | Server | -| RESTART_ZOMBIE_JOBS | true | If true then a zombie job is restarted (in-place with the same uuid and some logs), if false the zombie job is failed | Server | -| NATIVE_MODE | false | Enable native mode: sets NUM_WORKERS=8, rejects non-native jobs (nativets, postgresql, mysql, etc.) | Worker | -| SLEEP_QUEUE | 50 | The number of ms to sleep in between the last check for new jobs in the DB. It is multiplied by NUM_WORKERS such that in average, for one worker instance, there is one pull every SLEEP_QUEUE ms. | Worker | -| KEEP_JOB_DIR | false | Keep the job directory after the job is done. Useful for debugging. | Worker | -| EXIT_AFTER_N_JOBS | None | Exit the worker process after it has executed that many jobs, so that a supervisor restarts it and no process runs more than that many, bar the steps of a same-worker flow it has started, which it always finishes (set it to 1 for a process per job; jobs handed to a dedicated worker, and the worker's own init and periodic scripts, do not count). Not counting the init and periodic scripts means they run again on every restart: an init script's runtime is added to the latency of every batch of that many jobs, and a periodic script fires once per process start whatever its interval says. The worker's shell in the workers page also starts backed off rather than after the two minutes it otherwise takes, since a process due to be recycled cannot count on living that long: the first command of a session can wait up to 15s, later ones are immediate. For deployments that isolate executions by process lifetime rather than with nsjail; note that a container restart resets the process, not the container filesystem, so caches and `/tmp` survive it. The worker name is then derived from the hostname instead of being random, so the restarted worker keeps its row in the workers list (an agent worker keeps the row but restarts its job count). Use one worker per process: workers of one process share its environment, so the first to reach the limit shuts the others down too. | Worker | -| WORKER_SUFFIX | None | Pins the last part of the worker name, which is otherwise random, so that a restarted worker keeps its row in the workers list. Only needed when several worker processes of the same worker group run on one host, since the name is derived from the hostname: give each of them a distinct value, as two processes sharing one must never happen. At most 64 letters, digits and underscores; anything else is refused at startup. | Worker | -| LICENSE_KEY (EE only) | None | License key checked at startup for the Enterprise Edition of Windmill | Worker | -| SLACK_SIGNING_SECRET | None | The signing secret of your Slack app. See [Slack documentation](https://api.slack.com/authentication/verifying-requests-from-slack) | Server | -| COOKIE_DOMAIN | None | The domain of the cookie. If not set, the cookie will be set by the browser based on the full origin | Server | -| DENO_PATH | /usr/bin/deno | The path to the deno binary. | Worker | -| PYTHON_PATH | | The path to the python binary if wanting to not have it managed by uv. | Worker | -| GO_PATH | /usr/bin/go | The path to the go binary. | Worker | -| GOPRIVATE | | The GOPRIVATE env variable to use private go modules | Worker | -| GOPROXY | | The GOPROXY env variable to use | Worker | -| NETRC | | The netrc content to use a private go registry | Worker | -| PY_CONCURRENT_DOWNLOADS | 20 | Sets the maximum number of in-flight concurrent python downloads that windmill will perform at any given time. | Worker | -| PATH | None | The path environment variable, usually inherited | Worker | -| HOME | None | The home directory to use for Go and Bash , usually inherited | Worker | -| DATABASE_CONNECTIONS | 50 (Server)/3 (Worker) | The max number of connections in the database connection pool | All | -| SUPERADMIN_SECRET | None | A token that would let the caller act as a virtual superadmin superadmin@windmill.dev | Server | -| TIMEOUT_WAIT_RESULT | 20 | The number of seconds to wait before timeout on the 'run_wait_result' endpoint | Worker | -| QUEUE_LIMIT_WAIT_RESULT | None | The number of max jobs in the queue before rejecting immediately the request in 'run_wait_result' endpoint. Takes precedence on the query arg. If none is specified, there are no limit. | Worker | -| DENO_AUTH_TOKENS | None | Custom DENO_AUTH_TOKENS to pass to worker to allow the use of private modules | Worker | -| DISABLE_RESPONSE_LOGS | false | Disable response logs | Server | -| CREATE_WORKSPACE_REQUIRE_SUPERADMIN | true | If true, only superadmins can create new workspaces | Server | -| MIN_FREE_DISK_SPACE_MB | 15000 | Minimum amount of free space on worker. Sends critical alert if worker has less free space. | Worker | -| RUN_UPDATE_CA_CERTIFICATE_AT_START | false | If true, runs CA certificate update command at startup before other initialization | All | -| RUN_UPDATE_CA_CERTIFICATE_PATH | /usr/sbin/update-ca-certificates | Path to the CA certificate update command/script to run when RUN_UPDATE_CA_CERTIFICATE_AT_START is true | All | -| GOOGLE_APPLICATION_CREDENTIALS | None | (ee only) Credentials file for GCP Pub/Sub triggers that authenticate as the instance rather than through a `gcloud` resource (workspace admins only). Application default credentials also resolve the gcloud well-known file and the GCE metadata server. Workload Identity Federation files work with the `file`, `url` and `aws` credential sources; the `executable` source is not supported. | Server | +The variables most deployments set: -## Run a local dev setup +| Environment Variable name | Default | Description | Api Server/Worker/All | +| ------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------- | +| DATABASE_URL | | The Postgres database url. | All | +| MODE | standalone | The mode of the binary: standalone, server, worker, agent (EE), indexer (EE image, full-text search), mcp | All | +| WORKER_GROUP | default | The worker group the worker belongs to and gets its configuration pulled from | Worker | +| BASE_URL | http://localhost:8000 | The base url that is exposed publicly to access your instance. Is overriden by the instance settings if any. | Server | +| LICENSE_KEY (EE only) | None | License key checked at startup for the Enterprise Edition of Windmill | Worker | -We recommend using [Nix](./frontend/README_DEV.md#nix). See [./frontend/README_DEV.md](./frontend/README_DEV.md) for all options. - -### Frontend only - -Uses the backend of with local frontend (hot-reload): - -```bash -cd frontend -npm install -npm run generate-backend-client # or generate-backend-client-mac on Mac -npm run dev -``` - -Windmill available at `http://localhost/` - -### Backend + Frontend - -See the [./frontend/README_DEV.md](./frontend/README_DEV.md) file for all -running options. - -1. Start a local Postgres database using for instance the `start-dev-db.sh` script which will make a database available at `postgres://postgres:changeme@localhost:5432/windmill` - Then run the migrations using the following command: - ``` - cargo install sqlx-cli - env DATABASE_URL= sqlx migrate run - ``` - This will also avoid compile time issue with sqlx's `query!` macro. -2. (optional, linux only) Install [nsjail](https://github.com/google/nsjail) and have it accessible in - your PATH -3. Install bun and python3 (+ any languages you want to use), have the bins at `/usr/bin/bun` and - `/usr/local/bin/python3` or set the corresponding environment variables. -4. (optional) Install the [lld linker](https://lld.llvm.org/) -5. Go to `frontend/`: - 1. `npm install`, `npm run generate-backend-client` then `REMOTE=http://localhost:8000 npm run dev` - 2. You might need to set some extra heap space for the node runtime - `export NODE_OPTIONS="--max-old-space-size=4096"` - 3. Create an empty `frontend/build` folder using `mkdir frontend/build` -6. Go to `backend/`: - 1. `env DATABASE_URL= RUST_LOG=info cargo run` - 2. You can specify any feature flag you want to enable, for example `cargo run --features python` to enable the python executor. -7. Windmill should be available at `http://localhost:3000` +All other variables (database pool, queue, runtimes, private registries, certificates, zombie jobs and more) are documented in the [environment variables reference](https://www.windmill.dev/docs/core_concepts/environment_variables). ## Contributing @@ -337,11 +313,7 @@ At this time, we are not seeking outside contribution. Bug reports and feature r welcome, and small, trivially-verified PRs that fix a problem are still accepted. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full policy. -## Contributors - - - - +To run Windmill from source, see [frontend/README_DEV.md](./frontend/README_DEV.md). ## Copyright diff --git a/ai_evals/README.md b/ai_evals/README.md index d458e019d0..67592daee4 100644 --- a/ai_evals/README.md +++ b/ai_evals/README.md @@ -195,6 +195,15 @@ profile: operatorSettings: { builder_apps: true } # also builder_flows, manage_schedules, manage_triggers ``` +A role that builds nothing (no builder rights, `manage_schedules` and `manage_triggers` both +`false`) holds the session in Use, as the chat does in production: the toolset is the +read-only one and the prompt carries the session section that names the role as the reason. + +`judgeAssistantText: true` hands the judge what the assistant said alongside the mode's +output. Use it when the deliverable is the answer itself, such as a refusal and where to go +instead: the `global` judge otherwise reads only the drafts, and a substring check cannot tell +"you can't create it yourself" from "create it yourself". + `toolExpect.toolCallArgs` entries support `sharedByAtLeast: `: at least `n` recorded calls to that tool must carry the same non-blank string in the field. Use it for calls that have to share an identifier, like two test runs of one chat conversation. diff --git a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts index e70dbfcfe5..c648848387 100644 --- a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts +++ b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts @@ -5,9 +5,17 @@ import type { ChatCompletionMessageParam } from "openai/resources/chat/completio import type { AIProvider, OperatorSettings } from "$lib/gen/types.gen"; import { globalToolsFor, - prepareGlobalSystemMessage, prepareGlobalUserMessage, } from "../../../../../frontend/src/lib/components/copilot/chat/global/core"; +import { assembleGlobalSystemMessage } from "../../../../../frontend/src/lib/components/copilot/chat/global/globalAssembly"; +import { + canBuild, + USE_MODE_ACCESS, +} from "../../../../../frontend/src/lib/components/copilot/chat/sessionCapabilities"; +import { + FULL_CAPABILITIES, + legacyOperatorCapabilities, +} from "../../../../../frontend/src/lib/roleCapabilities"; import { clearGlobalDrafts, getGlobalDraft, @@ -155,15 +163,24 @@ export async function runGlobalEval( options.workspaceFixtures ?? {}, ); seedLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []); - // No deploy rules in the mock workspace, so they always pass. - const access = + // No deploy rules in the mock workspace, so they always pass. The role is read as a server + // that predates workspace roles describes it, from `operator_settings`. + const roleAccess = options.profile && capabilitiesForRole({ isAdmin: false, - operator: options.profile.operator, deployRulesPass: true, - operatorSettings: options.profile.operatorSettings as OperatorSettings, + capabilities: options.profile.operator + ? legacyOperatorCapabilities( + options.profile.operatorSettings as OperatorSettings, + ) + : FULL_CAPABILITIES, }); + // A session whose role builds nothing is held in Use, as the chat manager holds it: the + // read-only toolset, and the session section that names the role as the reason. + const heldInUse = + !!options.sessionChat && !!roleAccess && !canBuild(roleAccess); + const access = heldInUse ? USE_MODE_ACCESS : roleAccess; seedOperatorSettings(workspaceRoot, options.profile); // Declared out here only so `finally` can reach it; a malformed fixture throws while // building it, and everything seeded above still has to be torn down. @@ -179,7 +196,7 @@ export async function runGlobalEval( ); } // Production resolves a profile for session chats only; elsewhere every tool ships. - if (!options.sessionChat && access) { + if (!options.sessionChat && roleAccess) { throw new Error( "This case sets runtime.profile, which only a session chat applies — set runtime.sessionChat: true on the case.", ); @@ -203,10 +220,13 @@ export async function runGlobalEval( : undefined; // Pass the seeded identity straight to the prompt builder rather than mutating // the process-global `userStore`, so concurrent cases never race on it. - const baseSystemMessage = prepareGlobalSystemMessage(undefined, { + const baseSystemMessage = assembleGlobalSystemMessage(undefined, { user: options.user, previewTools: options.sessionChat ?? false, access, + ...(heldInUse && { + sessionContext: { workspaceId: workspaceRoot, useMode: "role" as const }, + }), }); const helpers = { ...evalArtifacts.helpers, diff --git a/ai_evals/adapters/frontend/mockBackend.ts b/ai_evals/adapters/frontend/mockBackend.ts index 69398555f0..1de463690b 100644 --- a/ai_evals/adapters/frontend/mockBackend.ts +++ b/ai_evals/adapters/frontend/mockBackend.ts @@ -11,8 +11,13 @@ import type { ListableApp, ListableResource, ListableVariable, + Folder, + Group, + QueuedJob, Resource, - Script + Schedule, + Script, + WorkerPing } from '../../../frontend/src/lib/gen' import type { DataMetric, @@ -97,6 +102,14 @@ export interface BenchmarkWorkspaceResource { resource_type: string value?: Record description?: string + /** A database's tables, as `get_db_schema` reads them: schema, table, then column. */ + dbSchema?: Record>> +} + +export interface BenchmarkDbColumn { + type: string + required: boolean + default?: string } /** A resource type the instance holds. */ @@ -117,6 +130,48 @@ export interface BenchmarkWorkspaceJob { logs?: string args?: Record result?: unknown + /** Defaults to `completed`. `suspended` is a running flow parked on an approval step. */ + state?: 'completed' | 'queued' | 'running' | 'suspended' + tag?: string + schedulePath?: string + /** When the run was created, relative to the case start. Unset = now. */ + createdMinutesAgo?: number + /** Completed runs only: how long the run took. */ + durationMs?: number +} + +/** A worker of the instance, as `list_workers` reports it. */ +export interface BenchmarkWorkspaceWorker { + worker: string + worker_group: string + custom_tags?: string[] + lastPingSecondsAgo?: number + jobs_executed?: number +} + +/** A folder of the benchmark workspace, as `read_workspace_item` reads it. */ +export interface BenchmarkWorkspaceFolder { + name: string + summary?: string + owners?: string[] + /** Who else may use the folder, as `u/` or `g/`: `true` grants write. */ + extra_perms?: Record +} + +export interface BenchmarkWorkspaceGroup { + name: string + summary?: string + members?: string[] +} + +export interface BenchmarkWorkspaceSchedule { + path: string + /** Six-field cron. */ + schedule: string + script_path: string + is_flow?: boolean + enabled?: boolean + summary?: string } export interface BenchmarkWorkspaceRunnables { @@ -133,15 +188,28 @@ export interface BenchmarkWorkspaceRunnables { ducklakes?: string[] dataMetrics?: DataMetric[] jobs?: BenchmarkWorkspaceJob[] + /** The instance's workers. Unset falls through to the real backend's; `[]` is none. */ + workers?: BenchmarkWorkspaceWorker[] + schedules?: BenchmarkWorkspaceSchedule[] + folders?: BenchmarkWorkspaceFolder[] + groups?: BenchmarkWorkspaceGroup[] + /** The workspace settings document (`get_workspace_settings` reads it). */ + workspaceSettings?: Record } type BenchmarkCompletedJob = CompletedJob & { type: 'CompletedJob' } +type BenchmarkQueuedJob = QueuedJob & { type: 'QueuedJob' } const benchmarkWorkspaces = new Set() const benchmarkWorkspaceRunnables = new Map() // Keyed by `${workspace}::${jobId}` so concurrent attempts (or distinct cases) // can seed the same fixed job id without clobbering each other's entry. -const benchmarkJobs = new Map() +const benchmarkJobs = new Map< + string, + { workspace: string; job: BenchmarkCompletedJob | BenchmarkQueuedJob } +>() +// What set_workspace_settings applied, per workspace, so get_workspace_settings reads it back. +const benchmarkWorkspaceSettings = new Map>() function benchmarkJobKey(workspace: string, jobId: string): string { return `${workspace}::${jobId}` @@ -152,11 +220,12 @@ export function resetBenchmarkMockBackend(): void { benchmarkWorkspaceRunnables.clear() benchmarkJobs.clear() benchmarkDrafts.clear() + benchmarkWorkspaceSettings.clear() } // Stand-in for FolderService.createFolder so the global create_folder tool runs in -// memory instead of mutating the real backend. Folders aren't otherwise modelled -// (no folder-listing in evals), so this just echoes the created name. +// memory instead of mutating the real backend. It echoes the name without adding the +// folder to the fixture folders that `listBenchmarkFolders` reads. export function createBenchmarkFolder(_workspace: string, name: string): string { return name } @@ -180,6 +249,14 @@ export function registerBenchmarkWorkspaceRunnables( }) // Seed any fixture jobs so list_runs / get_run have data to return. for (const seed of runnables.jobs ?? []) { + const createdAt = + seed.createdMinutesAgo === undefined + ? undefined + : new Date(Date.now() - seed.createdMinutesAgo * 60_000).toISOString() + if (seed.state && seed.state !== 'completed') { + createBenchmarkQueuedJob(workspace, seed, createdAt) + continue + } createBenchmarkCompletedJob({ workspace, id: seed.id, @@ -190,14 +267,24 @@ export function registerBenchmarkWorkspaceRunnables( label: seed.label, logs: seed.logs, args: seed.args, - result: seed.result + result: seed.result, + tag: seed.tag, + schedulePath: seed.schedulePath, + createdAt, + durationMs: seed.durationMs }) } + if (runnables.workspaceSettings) { + benchmarkWorkspaceSettings.set(workspace, structuredClone(runnables.workspaceSettings)) + } else { + benchmarkWorkspaceSettings.delete(workspace) + } } export function unregisterBenchmarkWorkspace(workspace: string): void { benchmarkWorkspaces.delete(workspace) benchmarkWorkspaceRunnables.delete(workspace) + benchmarkWorkspaceSettings.delete(workspace) clearBenchmarkDrafts(workspace) for (const [jobId, entry] of benchmarkJobs.entries()) { if (entry.workspace === workspace) { @@ -389,6 +476,15 @@ export function queryBenchmarkResourceTypes( .slice(0, limit) } +/** The tables a fixture seeds for a database resource; `null` when it seeds none. */ +export function getBenchmarkDbSchemaSeed( + workspace: string, + path: string +): { resourceType: string; schema: NonNullable } | null { + const seed = benchmarkWorkspaceRunnables.get(workspace)?.resources?.find((r) => r.path === path) + return seed?.dbSchema ? { resourceType: seed.resource_type, schema: seed.dbSchema } : null +} + /** A seeded resource with its value, as `ResourceService.getResource` returns it. Covers both * seed kinds, so it agrees with `existsResource` and `listResource` — both of those report AI * providers too, and a case that lists resources and then reads one by path would otherwise get @@ -481,18 +577,24 @@ export function createBenchmarkCompletedJob(input: { id?: string createdBy?: string label?: string + tag?: string + schedulePath?: string + createdAt?: string + durationMs?: number }): string { const jobId = input.id ?? `benchmark-job-${randomUUID()}` - const now = new Date().toISOString() + const createdAt = input.createdAt ?? new Date().toISOString() + const durationMs = input.durationMs ?? 0 const job: BenchmarkCompletedJob = { type: 'CompletedJob', id: jobId, workspace_id: input.workspace, created_by: input.createdBy ?? 'ai-evals', - created_at: now, - started_at: now, - completed_at: now, - duration_ms: 0, + created_at: createdAt, + started_at: createdAt, + completed_at: new Date(Date.parse(createdAt) + durationMs).toISOString(), + duration_ms: durationMs, + schedule_path: input.schedulePath, success: input.success ?? true, script_path: input.scriptPath, script_hash: input.scriptHash, @@ -506,7 +608,7 @@ export function createBenchmarkCompletedJob(input: { is_skipped: false, email: 'ai-evals@local', visible_to_owner: true, - tag: 'benchmark', + tag: input.tag ?? 'benchmark', labels: input.label ? [input.label] : undefined } @@ -517,17 +619,58 @@ export function createBenchmarkCompletedJob(input: { return jobId } +/** A run still in the queue: waiting for a worker, running, or a flow parked on an + * approval step (running with a suspend outstanding, as the backend reports it). */ +function createBenchmarkQueuedJob( + workspace: string, + seed: BenchmarkWorkspaceJob, + createdAt = new Date().toISOString() +): string { + const jobId = seed.id ?? `benchmark-job-${randomUUID()}` + const started = seed.state === 'running' || seed.state === 'suspended' + const job: BenchmarkQueuedJob = { + type: 'QueuedJob', + id: jobId, + workspace_id: workspace, + created_by: seed.createdBy ?? 'ai-evals', + created_at: createdAt, + scheduled_for: createdAt, + started_at: started ? createdAt : undefined, + running: started, + suspend: seed.state === 'suspended' ? 1 : undefined, + script_path: seed.scriptPath, + schedule_path: seed.schedulePath, + args: seed.args, + logs: seed.logs, + canceled: false, + job_kind: seed.jobKind ?? 'script', + permissioned_as: 'u/ai-evals', + is_flow_step: false, + email: 'ai-evals@local', + visible_to_owner: true, + tag: seed.tag ?? 'benchmark' + } + benchmarkJobs.set(benchmarkJobKey(workspace, jobId), { workspace, job }) + return jobId +} + export function getBenchmarkCompletedJob( workspace: string, jobId: string ): BenchmarkCompletedJob | null { const entry = benchmarkJobs.get(benchmarkJobKey(workspace, jobId)) - if (!entry) { + if (!entry || entry.job.type !== 'CompletedJob') { return null } return structuredClone(entry.job) } +/** Any seeded run, finished or not, as `JobService.getJob` returns it. */ +export function getBenchmarkJob(workspace: string, jobId: string): Job | null { + const entry = benchmarkJobs.get(benchmarkJobKey(workspace, jobId)) + return entry ? (structuredClone(entry.job) as Job) : null +} + /** * List seeded/recorded jobs for a benchmark workspace, most recent first — * the shape `JobService.listJobs` returns. Returns `null` for a non-benchmark @@ -550,7 +693,7 @@ export function listBenchmarkJobs(workspace: string): Job[] | null { * "not found" error for an unknown id, matching the backend 404. */ export function getBenchmarkJobLogs(workspace: string, jobId: string): string { - const job = getBenchmarkCompletedJob(workspace, jobId) + const job = getBenchmarkJob(workspace, jobId) if (!job) { throw new Error(`Job Logs not found for "${jobId}"`) } @@ -562,7 +705,7 @@ export function getBenchmarkJobLogs(workspace: string, jobId: string): string { * tree. Fixture jobs are single runs with no steps, so only the root entry. */ export function getBenchmarkFlowAllResults(workspace: string, jobId: string) { - const job = getBenchmarkCompletedJob(workspace, jobId) + const job = getBenchmarkJob(workspace, jobId) if (!job) { throw new Error(`Job "${jobId}" not found in benchmark workspace`) } @@ -575,8 +718,9 @@ export function getBenchmarkFlowAllResults(workspace: string, jobId: string) { depth: 0, sibling_index: 1, sibling_count: 1, - status: job.success ? 'success' : 'failure', - success: job.success + ...('success' in job + ? { status: job.success ? 'success' : 'failure', success: job.success } + : { status: job.suspend ? 'suspended' : job.running ? 'running' : 'queued' }) } ], truncated: false, @@ -584,6 +728,156 @@ export function getBenchmarkFlowAllResults(workspace: string, jobId: string) { } } +// ============= Workers, schedules ============= + +/** Mirror `WorkerService.listWorkers`; `null` when no case seeded workers. Workers name no + * workspace, so this answers from whichever case seeded them: run cases whose worker seeds + * differ one at a time. */ +export function listBenchmarkWorkers(): WorkerPing[] | null { + let workers: BenchmarkWorkspaceWorker[] | undefined + for (const workspace of benchmarkWorkspaces) { + workers ??= benchmarkWorkspaceRunnables.get(workspace)?.workers + } + if (!workers) return null + return workers.map((w) => ({ + worker: w.worker, + worker_instance: `${w.worker}-instance`, + worker_group: w.worker_group, + custom_tags: w.custom_tags, + last_ping: w.lastPingSecondsAgo ?? 2, + started_at: BENCHMARK_TIMESTAMP, + ip: '10.0.0.1', + jobs_executed: w.jobs_executed ?? 0, + wm_version: 'benchmark' + })) +} + +function buildBenchmarkSchedule(workspace: string, s: BenchmarkWorkspaceSchedule): Schedule { + return { + path: s.path, + edited_by: 'benchmark', + edited_at: BENCHMARK_TIMESTAMP, + schedule: s.schedule, + timezone: 'Etc/UTC', + enabled: s.enabled ?? true, + script_path: s.script_path, + is_flow: s.is_flow ?? false, + extra_perms: {}, + email: 'ai-evals@local', + summary: s.summary, + workspace_id: workspace + } as unknown as Schedule +} + +export function listBenchmarkSchedules(workspace: string): Schedule[] { + return (benchmarkWorkspaceRunnables.get(workspace)?.schedules ?? []).map((s) => + buildBenchmarkSchedule(workspace, s) + ) +} + +export function getBenchmarkSchedule(workspace: string, path: string): Schedule | null { + const s = benchmarkWorkspaceRunnables.get(workspace)?.schedules?.find((e) => e.path === path) + return s ? buildBenchmarkSchedule(workspace, s) : null +} + +// ============= Folders, groups, workspace settings ============= + +function buildBenchmarkFolder(workspace: string, f: BenchmarkWorkspaceFolder): Folder { + return { + workspace_id: workspace, + name: f.name, + summary: f.summary, + owners: f.owners ?? [], + extra_perms: f.extra_perms ?? {} + } as Folder +} + +export function listBenchmarkFolders(workspace: string): Folder[] { + return (benchmarkWorkspaceRunnables.get(workspace)?.folders ?? []).map((f) => + buildBenchmarkFolder(workspace, f) + ) +} + +export function getBenchmarkFolder(workspace: string, name: string): Folder | null { + const f = benchmarkWorkspaceRunnables.get(workspace)?.folders?.find((e) => e.name === name) + return f ? buildBenchmarkFolder(workspace, f) : null +} + +export function listBenchmarkGroups(workspace: string): Group[] { + return (benchmarkWorkspaceRunnables.get(workspace)?.groups ?? []).flatMap((g) => { + const group = getBenchmarkGroup(workspace, g.name) + return group ? [group] : [] + }) +} + +export function getBenchmarkGroup(workspace: string, name: string): Group | null { + const g = benchmarkWorkspaceRunnables.get(workspace)?.groups?.find((e) => e.name === name) + return g + ? ({ + workspace_id: workspace, + name: g.name, + summary: g.summary, + members: g.members ?? [], + extra_perms: {} + } as Group) + : null +} + +const DATA_TABLE_DATABASE_TYPES = ['postgresql', 'instance', 'external_instance'] + +/** Refuse a data table entry the backend's `DataTableDatabase` would not deserialize. */ +function assertBenchmarkDataTables(value: unknown): void { + if (value === undefined || value === null) return + const datatables = (value as { datatables?: Record }).datatables ?? {} + for (const [name, entry] of Object.entries(datatables)) { + const { database, reference } = (entry ?? {}) as { + database?: { resource_type?: unknown; resource_path?: unknown } + reference?: unknown + } + // A fork's pointer at its parent's entry owns no database. + if (reference && !database) continue + if (!DATA_TABLE_DATABASE_TYPES.includes(String(database?.resource_type))) { + throw new Error( + `datatable.datatables.${name}.database.resource_type must be one of ${DATA_TABLE_DATABASE_TYPES.join(', ')}` + ) + } + if (typeof database?.resource_path !== 'string' || database.resource_path === '') { + throw new Error(`datatable.datatables.${name}.database.resource_path is required`) + } + } +} + +/** Mirror `WorkspaceService.getWorkspaceSettingsDocument`; an unseeded workspace has an + * empty document. */ +export function getBenchmarkWorkspaceSettingsDocument(workspace: string): Record { + return structuredClone(benchmarkWorkspaceSettings.get(workspace) ?? {}) +} + +/** Mirror `WorkspaceService.applyWorkspaceSettingsDocument` for a partial document: each + * top-level key replaces the stored one, `null` clears it. */ +export function applyBenchmarkWorkspaceSettingsDocument(input: { + workspace: string + requestBody: { document: Record; dry_run?: boolean } +}): { + changes: Array<{ key: string; before: unknown; after: unknown }> + applied: boolean +} { + assertBenchmarkDataTables(input.requestBody.document.datatable) + const current = benchmarkWorkspaceSettings.get(input.workspace) ?? {} + const changes = Object.entries(input.requestBody.document) + .filter(([key, after]) => JSON.stringify(current[key] ?? null) !== JSON.stringify(after ?? null)) + .map(([key, after]) => ({ key, before: current[key] ?? null, after: after ?? null })) + if (!input.requestBody.dry_run) { + const next = { ...current } + for (const { key, after } of changes) { + if (after === null) delete next[key] + else next[key] = structuredClone(after) + } + benchmarkWorkspaceSettings.set(input.workspace, next) + } + return { changes, applied: !input.requestBody.dry_run } +} + // ============= Drafts (per-user, DB-backed in production) ============= /** diff --git a/ai_evals/adapters/frontend/vitestAdapter.test.ts b/ai_evals/adapters/frontend/vitestAdapter.test.ts index b24ccbe5e4..754de224ac 100644 --- a/ai_evals/adapters/frontend/vitestAdapter.test.ts +++ b/ai_evals/adapters/frontend/vitestAdapter.test.ts @@ -85,12 +85,52 @@ vi.mock('@codingame/monaco-vscode-languages-service-override', () => ({ vi.mock('$lib/components/vscode', () => ({})) +// get_db_schema reads a database's tables by running a query job; a benchmark database +// answers with the tables its fixture seeds instead. +vi.mock('$lib/components/apps/components/display/dbtable/metadata', async () => { + const actual = await vi.importActual( + '$lib/components/apps/components/display/dbtable/metadata' + ) + const { getBenchmarkDbSchemaSeed } = await import('./mockBackend') + const { stringifySchema } = await import('$lib/components/copilot/lib') + const { resourceTypeToLang } = await import( + '$lib/components/apps/components/display/dbtable/utils' + ) + return { + ...actual, + getDbSchemas: async ( + resourceType: string, + resourcePath: string, + workspace: string | undefined, + ...rest: unknown[] + ) => { + const seed = workspace ? getBenchmarkDbSchemaSeed(workspace, resourcePath) : null + if (!seed) return actual.getDbSchemas(resourceType, resourcePath, workspace, ...rest) + const dbSchema = { + lang: resourceTypeToLang(seed.resourceType), + schema: seed.schema, + publicOnly: !!seed.schema.public + } + return { ...dbSchema, stringified: stringifySchema(dbSchema) } + } + } +}) + vi.mock('$lib/gen', async () => { const actual = await vi.importActual('$lib/gen') const { getBenchmarkAppByPath, - getBenchmarkCompletedJob, + getBenchmarkJob, getBenchmarkCompletedJobResultMaybe, + listBenchmarkWorkers, + listBenchmarkSchedules, + getBenchmarkSchedule, + listBenchmarkFolders, + getBenchmarkFolder, + getBenchmarkGroup, + listBenchmarkGroups, + getBenchmarkWorkspaceSettingsDocument, + applyBenchmarkWorkspaceSettingsDocument, getBenchmarkDatatableSchema, getBenchmarkDatatableMigrationsStatus, createBenchmarkDatatableMigration, @@ -175,7 +215,29 @@ vi.mock('$lib/gen', async () => { createFolder: async (data: { workspace: string; requestBody: { name: string } }) => hasBenchmarkWorkspace(data.workspace) ? createBenchmarkFolder(data.workspace, data.requestBody.name) - : actual.FolderService.createFolder(data) + : actual.FolderService.createFolder(data), + listFolders: async (data: { workspace: string }) => + hasBenchmarkWorkspace(data.workspace) + ? listBenchmarkFolders(data.workspace) + : actual.FolderService.listFolders(data), + getFolder: async (data: { workspace: string; name: string }) => { + if (!hasBenchmarkWorkspace(data.workspace)) return actual.FolderService.getFolder(data) + const folder = getBenchmarkFolder(data.workspace, data.name) + if (!folder) throw new Error(`Folder "${data.name}" not found in benchmark workspace`) + return folder + } + }), + GroupService: wrapService(actual.GroupService, { + listGroups: async (data: { workspace: string }) => + hasBenchmarkWorkspace(data.workspace) + ? listBenchmarkGroups(data.workspace) + : actual.GroupService.listGroups(data), + getGroup: async (data: { workspace: string; name: string }) => { + if (!hasBenchmarkWorkspace(data.workspace)) return actual.GroupService.getGroup(data) + const group = getBenchmarkGroup(data.workspace, data.name) + if (!group) throw new Error(`Group "${data.name}" not found in benchmark workspace`) + return group + } }), ScriptService: wrapService(actual.ScriptService, { listScripts: async (data: { workspace: string }) => @@ -357,7 +419,7 @@ vi.mock('$lib/gen', async () => { : actual.JobService.runFlowByPath(data), getJob: async (data: { workspace: string; id: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { - const job = getBenchmarkCompletedJob(data.workspace, data.id) + const job = getBenchmarkJob(data.workspace, data.id) if (!job) { throw new Error(`Job "${data.id}" not found in benchmark workspace`) } @@ -383,6 +445,14 @@ vi.mock('$lib/gen', async () => { : actual.JobService.getFlowAllResults(data) }), WorkspaceService: wrapService(actual.WorkspaceService, { + getWorkspaceSettingsDocument: async (data: { workspace: string }) => + hasBenchmarkWorkspace(data.workspace) + ? getBenchmarkWorkspaceSettingsDocument(data.workspace) + : actual.WorkspaceService.getWorkspaceSettingsDocument(data), + applyWorkspaceSettingsDocument: async (data: any) => + hasBenchmarkWorkspace(data.workspace) + ? applyBenchmarkWorkspaceSettingsDocument(data) + : actual.WorkspaceService.applyWorkspaceSettingsDocument(data), getCopilotInfo: async (data: { workspace: string }) => hasBenchmarkWorkspace(data.workspace) ? (getBenchmarkAiConfig(data.workspace) ?? {}) @@ -436,13 +506,21 @@ vi.mock('$lib/gen', async () => { ? { metrics: listBenchmarkDataMetrics(data.workspace) ?? [] } : actual.DataMetricService.listDataMetrics(data) }), + WorkerService: wrapService(actual.WorkerService, { + listWorkers: async (data: Record) => + listBenchmarkWorkers() ?? actual.WorkerService.listWorkers(data) + }), ScheduleService: wrapService(actual.ScheduleService, { existsSchedule: async (data: { workspace: string; path: string }) => hasBenchmarkWorkspace(data.workspace) ? false : actual.ScheduleService.existsSchedule(data), listSchedules: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.ScheduleService.listSchedules(data), + hasBenchmarkWorkspace(data.workspace) + ? listBenchmarkSchedules(data.workspace) + : actual.ScheduleService.listSchedules(data), getSchedule: async (data: { workspace: string; path: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { + const schedule = getBenchmarkSchedule(data.workspace, data.path) + if (schedule) return schedule throw new Error(`Schedule "${data.path}" not found in benchmark workspace`) } return actual.ScheduleService.getSchedule(data) diff --git a/ai_evals/cases/global.yaml b/ai_evals/cases/global.yaml index 136f125e59..f0df4ae6e3 100644 --- a/ai_evals/cases/global.yaml +++ b/ai_evals/cases/global.yaml @@ -3231,6 +3231,33 @@ - - admin skipJudge: true +# A role with schedules and triggers withdrawn builds nothing, which holds the session in Use. +# Its user cannot create a script by hand either, so the way forward is an admin, not steps. +- id: global-use-role-script-goes-to-admin + prompt: |- + Write a Python script that checks whether https://status.example.com is up and returns + true or false. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 6 + sessionChat: true + profile: + operator: true + operatorSettings: + manage_schedules: false + manage_triggers: false + validate: + draftCountExactly: 0 + assistantExpect: + requiredMentionsAnyOf: + - - admin + judgeAssistantText: true + judgeChecklist: + - the reply puts the refusal on the user's role in this workspace, not only on this session or its mode + - the reply suggests asking a workspace admin, who can create the script or give the role more rights + - the reply does not tell or invite the user to create the script themselves with the role they have now, with steps or with code offered for them to paste in; code offered for an admin to add, or saying they could once an admin grants their role more, is fine + - the reply does not suggest switching this session to Use & build or Plan; saying a role with more rights could build is fine + # An agent from the Agents page is an `ai_agent` resource. Asked about one by name, the model # has to read it as a resource rather than look for a flow or script of that name. - id: global-agent-read-as-resource @@ -3283,3 +3310,626 @@ - Agents page - agent editor skipJudge: true + +# --- Composer suggestions --- +# The prompts the pills under Home's composer put in the box +# (frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts), word for word. +# A pill is only worth offering if the session chat can act on its prompt, so each one is +# pinned here against a workspace where the prompt has something to find. + +- id: global-composer-run-queue + prompt: |- + Is anything stuck in this workspace's queue? Which jobs are waiting or suspended, and why? + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 10 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_runs + - list_workers + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - gpu-renderer + - - refund_approval + - approval + - approve + skipJudge: true + judgeChecklist: + - finds the 12 gpu_render runs queued on the gpu-renderer tag that no connected worker serves + - finds the refund_approval flow suspended on its approval step, and says approving it unblocks it + +- id: global-composer-worker-health + prompt: |- + Are the workers healthy and keeping up with the queue? Compare how long jobs wait before they start with how busy each worker group is. + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 10 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_workers + - list_runs + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - gpu-renderer + skipJudge: true + judgeChecklist: + - reads the connected workers and the queued runs instead of guessing + - points out that the gpu-renderer runs wait because no worker serves that tag + +- id: global-composer-schedules + prompt: |- + Do any schedules in this workspace keep failing? If so, which ones and why? + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 10 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_runs + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - charge_cards_every_minute + - - insufficient funds + - declined + skipJudge: true + judgeChecklist: + - names f/billing/charge_cards_every_minute as the failing schedule, not import_orders_hourly + - gives the cause from its runs' logs (card declined, insufficient funds) + +- id: global-composer-recent-runs + prompt: |- + Look at the recent runs in this workspace: did any fail, and why? Is anything getting slower? + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_runs + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - charge_cards + - - insufficient funds + - declined + skipJudge: true + judgeChecklist: + - names charge_cards as the failing script and gives the cause from its logs + - does not invent a slowdown the run durations do not show + +# The empty-workspace examples, sent as the composer sends them. The workspace holds nothing, +# so the model has to stage what it needs; one answer covers a question about the Slack setup. +- id: global-composer-example-daily-metrics + prompt: |- + Every weekday at 9am, query postgres for yesterday's signups and revenue and post a summary to the #metrics Slack channel + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Use placeholders for the postgres and Slack connections, I'll fill them in later + validate: + draftCountAtLeast: 1 + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - stages a script or flow that queries postgres for the previous day's signups and revenue + - posts the summary to the #metrics Slack channel + - runs it on a schedule at 9am on weekdays only + +- id: global-composer-example-refund-approval + prompt: |- + Build a flow that asks for approval in Slack before issuing a refund in Stripe, and only refunds if someone approves + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Use placeholders for the Stripe and Slack connections, I'll fill them in later + validate: + requiredDrafts: + - type: flow + valueIncludes: + - suspend + toolExpect: + requiredToolsUsed: + - write_flow + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - posts an approval request to Slack before any refund is issued + - suspends the flow on an approval step and continues only once someone approves + - issues the refund through Stripe only on approval, never when it is rejected + +- id: global-composer-example-ticket-triage + prompt: |- + When a support ticket arrives by webhook, classify its urgency with an LLM and post the urgent ones to the #support Slack channel + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Use placeholders for the LLM and Slack connections, I'll fill them in later + validate: + draftCountAtLeast: 1 + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - stages a script or flow that takes the ticket as the input a webhook delivers + - classifies the ticket's urgency with an LLM call; an `aidecision` step (Windmill's built-in LLM decision, with `choice` or `noul` questions) counts + - posts only the urgent tickets to the #support Slack channel + +# The pills that name what an established workspace holds: a teammate's flow, a starred +# script, a connected database and channel. +- id: global-composer-walk-through-flow + prompt: |- + Walk me through what the flow f/billing/charge_customers does, step by step. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - read_workspace_item + forbiddenToolsUsed: + - write_flow + - patch_flow_json + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - due today + - invoices due + - fetch_due + - - receipt + skipJudge: true + judgeChecklist: + - reads the flow and describes its three steps in order + +- id: global-composer-run-favorite + prompt: |- + Run the script f/ops/check_ssl_expiry for me. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + userAnswers: + - windmill.dev + validate: + draftCountExactly: 0 + # The script needs a domain the prompt does not give. Opening the run form for the user to + # fill and asking for the domain in chat are both right, so neither is pinned; what is pinned + # is that the deployed script is read and nothing is previewed or written. + toolExpect: + requiredToolsUsed: + - read_workspace_item + forbiddenToolsUsed: + - test_run_script + - write_script + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - domain + # Running produces no draft, and the judge cannot observe runs; validate via tool use. + skipJudge: true + judgeChecklist: + - reads the deployed script and either opens its run form or asks for the domain it needs + +- id: global-composer-daily-summary + prompt: |- + Every weekday at 9am, summarize yesterday's activity in the Postgres database f/data/warehouse and post it to Slack with the resource f/team/slack + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Post it in #metrics, with new signups, new invoices and what they add up to + validate: + draftCountAtLeast: 1 + toolExpect: + # "Yesterday's activity" means whatever the tables hold, so they are read first. + requiredToolsUsed: + - get_db_schema + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - queries the warehouse's real tables (signups, invoices) for the previous day through f/data/warehouse + - posts the summary to Slack through the resource f/team/slack; a channel parameter with a default is fine, since the prompt names none + - runs on a schedule at 9am on weekdays only + +# Pills that teach the piece a workspace is missing. +- id: global-composer-setup-datatable + prompt: |- + This workspace has no data table yet. Walk me through setting one up in the workspace settings, then show me how a script writes to it. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 20 + sessionChat: true + userAnswers: + - Back it with the Postgres resource f/data/warehouse and call it main + # Opening the data table settings for the admin and writing them after a confirmation are + # both a way through; either way the script example is what teaches the concept. + toolExpect: + requiredToolsAnyOf: + - - open_page + - set_workspace_settings + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - datatable( + - datatable() + skipJudge: true + judgeChecklist: + - shows where data tables are set up and a script writing to one with wmill.datatable() + +- id: global-composer-store-data + prompt: |- + How should my scripts store data in Windmill? Explain data tables and show me how a script reads and writes one. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + # The pill is for developers: an admin is offered "Set up a data table" instead. + profile: + operator: false + toolExpect: + forbiddenToolsUsed: + - set_workspace_settings + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - datatable( + - datatable() + skipJudge: true + judgeChecklist: + - explains data tables and shows a script reading and writing one with wmill.datatable() + +- id: global-composer-connect-slack + prompt: |- + Help me connect Slack to this workspace so my scripts can post messages. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 12 + sessionChat: true + userAnswers: + - Use a bot token, I will paste it myself + # A Slack resource whose token is a secret variable, or the workspace's own Slack connection + # in settings: both connect Slack, so either path is accepted. + toolExpect: + requiredToolsAnyOf: + - - write_resource + - open_page + forbiddenToolsUsed: + - deploy_workspace_item + skipJudge: true + judgeChecklist: + - stages a Slack resource with its token in a secret variable, or opens the workspace's Slack settings + +- id: global-composer-store-secret + prompt: |- + I have an API key my scripts need. Store it as a secret and show me how a script reads it with wmill.getVariable. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 10 + sessionChat: true + userAnswers: + - It is for the Stripe API; I will paste the value myself + validate: + requiredDrafts: + - type: variable + valueIncludes: + - '"is_secret": true' + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - getVariable + - get_variable + - "$var:" + judgeChecklist: + - stages a secret variable with a placeholder value instead of inventing the key + - any example script reads the variable rather than embedding the key; an example given only in the chat is checked separately, so do not score its absence here + +# Pills that name what an established workspace holds, read from composer_connected_workspace. +- id: global-composer-explore-datatable + prompt: |- + List the tables in the data table main and tell me what each one holds. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsAnyOf: + - - list_datatables + - get_datatable_table_schema + assistantExpect: + requiredMentionsAnyOf: + - - feedback + - - onboarding_tasks + skipJudge: true + judgeChecklist: + - names the feedback and onboarding_tasks tables and what each holds + +- id: global-composer-app-on-datatable + prompt: |- + Build a full-code app to browse and edit the rows of a table in the data table main. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 30 + sessionChat: true + userAnswers: + - The feedback table + validate: + requiredDrafts: + - type: app + toolExpect: + requiredToolsUsed: + - init_app + forbiddenToolsUsed: + - deploy_workspace_item + judgeChecklist: + - builds a full-code app whose backend reads the rows of a table in the main data table through wmill.datatable(); `sql.raw` is the documented way to inline a table or column name + - lets the user edit a row and saves the change back to the table + +- id: global-composer-add-app-page + prompt: |- + Add a page to the app f/ops/console, and ask me what it should show. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 24 + sessionChat: true + userAnswers: + - A page listing the latest feedback from the main data table + # The pill asks the chat to ask: in chat or through askUserQuestion. A question in chat ends + # the run before the page is written, so the page itself is not pinned. + toolExpect: + requiredToolsAnyOf: + - - read_app_file + - read_workspace_item + forbiddenToolsUsed: + - init_app + - deploy_workspace_item + skipJudge: true + judgeChecklist: + - reads the app, then asks what the new page should show before writing it + +- id: global-composer-walk-through-agent + prompt: |- + Walk me through what the AI agent f/support/triage_agent does and which tools it can use. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - read_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - billing + - - no tools + - any tools + - no tool + skipJudge: true + judgeChecklist: + - explains that the agent labels tickets as billing, bug or question and has no tools + +- id: global-composer-channel-in-script + prompt: |- + Show me how a script uses the resource f/team/slack to post a Slack message, with a short example. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - chat.postMessage + skipJudge: true + judgeChecklist: + - shows a script that takes the f/team/slack resource and posts a message with chat.postMessage + +- id: global-composer-postgres-trigger + prompt: |- + Run a script whenever a row is inserted into a table of the Postgres database f/data/warehouse, and explain how Postgres triggers work. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 20 + sessionChat: true + userAnswers: + - The signups table + validate: + requiredDrafts: + - type: trigger + triggerKind: postgres + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - publication + - replication + judgeChecklist: + - stages a Postgres trigger on f/data/warehouse that fires on inserts, limited to one table rather than every table + - the triggered script takes the inserted row as its input + +- id: global-composer-http-endpoint + prompt: |- + Expose the script f/ops/check_ssl_expiry as an HTTP API endpoint that requires a Windmill token, and show me how to call it. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 12 + sessionChat: true + # "Expose" asks for a live route, so deploying it, behind the user's confirmation, is right. + validate: + requiredDrafts: + - type: trigger + triggerKind: http + valueIncludes: + - f/ops/check_ssl_expiry + assistantExpect: + requiredMentionsAnyOf: + - - curl + - fetch( + judgeChecklist: + - stages an HTTP route that runs f/ops/check_ssl_expiry and passes it the domain + - the route requires a Windmill token (authentication_method windmill), so it is not public + - how to call it is explained in the chat, which is checked separately; do not score it + +- id: global-composer-schedule-script + prompt: |- + Run the script f/ops/check_ssl_expiry every weekday at 9am. Ask me for any input it needs, and explain how schedules work. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 12 + sessionChat: true + userAnswers: + - windmill.dev + # The script needs a domain the prompt does not give, so the chat reads the script and asks + # for it: in chat, which ends the run, or with askUserQuestion, which goes on to the schedule. + toolExpect: + requiredToolsUsed: + - read_workspace_item + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - domain + - - cron + - schedule + skipJudge: true + judgeChecklist: + - reads the script, asks for the domain it needs, and explains how schedules work + +- id: global-composer-webhook + prompt: |- + How do I start the flow f/billing/charge_customers from another app with its webhook? Show me the URL and an example request. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + assistantExpect: + requiredMentionsAnyOf: + - - jobs/run + - - token + - Authorization + skipJudge: true + judgeChecklist: + - gives the flow's webhook URL and an example request with a token + +- id: global-composer-who-can-see + prompt: |- + Who can see and edit the flow f/billing/charge_customers, and why? + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - read_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - finance + - - bob + skipJudge: true + judgeChecklist: + - explains that access comes from the billing folder - its owner ada, bob with write, the finance group with read + +- id: global-composer-operator-what-can-i-run + prompt: |- + Which scripts and flows can I run in this workspace, and what does each one do? + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 6 + sessionChat: true + profile: + operator: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_workspace_items + assistantExpect: + requiredMentionsAnyOf: + - - list_open_orders + - List open orders + skipJudge: true + judgeChecklist: + - lists the runnable scripts and flows with what each does + +- id: global-composer-hub-scripts + prompt: |- + Find scripts on the Windmill Hub for Slack that I could use with the resource f/team/slack. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsAnyOf: + - - search_hub_scripts + - get_hub_integration + skipJudge: true + judgeChecklist: + - lists Slack scripts from the Hub that take a Slack resource + +- id: global-composer-mcp + prompt: |- + How do I connect Claude to this workspace with MCP so it can run my scripts and flows? + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsAnyOf: + - - search_docs + - read_docs_page + assistantExpect: + requiredMentionsAnyOf: + - - token + - MCP URL + skipJudge: true + judgeChecklist: + - explains the MCP setup from the docs: the MCP URL with a token, added to Claude diff --git a/ai_evals/core/cases.ts b/ai_evals/core/cases.ts index c745f36a15..0e9e400a74 100644 --- a/ai_evals/core/cases.ts +++ b/ai_evals/core/cases.ts @@ -24,6 +24,7 @@ interface RawEvalCase { assistantExpect?: EvalCase["assistantExpect"]; judgeChecklist?: string[]; skipJudge?: boolean; + judgeAssistantText?: boolean; runtime?: EvalCaseRuntimeSpec; } export function getRepoRoot(): string { @@ -54,6 +55,7 @@ export async function loadCases(mode: EvalMode): Promise { assistantExpect: entry.assistantExpect, judgeChecklist: entry.judgeChecklist, skipJudge: entry.skipJudge, + judgeAssistantText: entry.judgeAssistantText, runtime: entry.runtime, })); } diff --git a/ai_evals/core/models.ts b/ai_evals/core/models.ts index cf131337fd..3c469c4fd3 100644 --- a/ai_evals/core/models.ts +++ b/ai_evals/core/models.ts @@ -82,6 +82,19 @@ export const EVAL_MODELS: EvalModelSpec[] = [ model: "opus", }, }, + { + id: "sonnet-5", + label: "Claude Sonnet 5", + aliases: ["sonnet-5", "claude-sonnet-5"], + frontend: { + provider: "anthropic", + model: "claude-sonnet-5", + }, + cli: { + runtime: "claude-code", + model: "claude-sonnet-5", + }, + }, { id: "sonnet-5.5", label: "Claude Sonnet 5.5", diff --git a/ai_evals/core/runSuite.ts b/ai_evals/core/runSuite.ts index c2d80e5d6e..831cac1f05 100644 --- a/ai_evals/core/runSuite.ts +++ b/ai_evals/core/runSuite.ts @@ -245,15 +245,18 @@ async function runCaseAttempts(input: { input.judgeModel !== null && !input.evalCase.skipJudge ) { + const output = input.modeRunner.prepareJudgeActual + ? input.modeRunner.prepareJudgeActual(run.actual) + : run.actual; const judge = await judgeOutput({ mode: input.modeRunner.mode, prompt: input.evalCase.prompt, checklist: input.evalCase.judgeChecklist, initial, expected: input.modeRunner.mode === "cli" ? undefined : expected, - actual: input.modeRunner.prepareJudgeActual - ? input.modeRunner.prepareJudgeActual(run.actual) - : run.actual, + actual: input.evalCase.judgeAssistantText + ? { assistantReply: run.assistantText, output } + : output, model: input.judgeModel, }); diff --git a/ai_evals/core/types.ts b/ai_evals/core/types.ts index 192a0c7ac7..b13f6264ac 100644 --- a/ai_evals/core/types.ts +++ b/ai_evals/core/types.ts @@ -41,7 +41,8 @@ export interface EvalCaseRuntimeSpec { // refused until the model hands over a plan with exit_plan_mode. planMode?: boolean; // Global session chats: the user's rights in the workspace, as production resolves them for - // a session from a non-admin role. Unset means full access. + // a session from a non-admin role. Unset means full access. A role that builds nothing holds + // the session in Use, with the read-only toolset and the session section that says why. profile?: EvalCaseProfile; } @@ -273,6 +274,12 @@ export interface EvalCase { assistantExpect?: AssistantValidationSpec; judgeChecklist?: string[]; skipJudge?: boolean; + /** + * The judge also reads what the assistant said, for a case whose deliverable is the answer + * itself: the `global` judge otherwise sees only the drafts. Needs a mode whose runner + * reports `assistantText`. + */ + judgeAssistantText?: boolean; runtime?: EvalCaseRuntimeSpec; } diff --git a/ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json b/ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json new file mode 100644 index 0000000000..db30ec00e8 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json @@ -0,0 +1,313 @@ +{ + "user": { + "username": "admin", + "is_admin": true + }, + "workspace": { + "flows": [ + { + "path": "f/billing/charge_customers", + "summary": "Charge customers with due invoices", + "description": "Every night, charges each customer whose invoice is due and emails a receipt.", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "dry_run": { + "type": "boolean", + "default": false + } + }, + "required": [] + }, + "value": { + "modules": [ + { + "id": "fetch_due", + "summary": "Fetch invoices due today from the warehouse", + "value": { + "type": "rawscript", + "language": "postgresql", + "content": "-- database f/data/warehouse\nSELECT id, customer_id, amount_cents FROM invoices WHERE due_date = current_date AND paid = false;", + "input_transforms": { + "database": { + "type": "static", + "value": "$res:f/data/warehouse" + } + } + } + }, + { + "id": "charge", + "summary": "Charge each invoice", + "value": { + "type": "forloopflow", + "iterator": { + "type": "javascript", + "expr": "results.fetch_due" + }, + "skip_failures": false, + "modules": [ + { + "id": "charge_one", + "summary": "Charge one invoice through the payment API", + "value": { + "type": "rawscript", + "language": "bun", + "content": "export async function main(invoice: { id: number; amount_cents: number }) {\n const res = await fetch('https://payments.example.com/charge', { method: 'POST', body: JSON.stringify(invoice) })\n if (!res.ok) throw new Error(`charge failed for invoice ${invoice.id}`)\n return await res.json()\n}\n", + "input_transforms": { + "invoice": { + "type": "javascript", + "expr": "flow_input.iter.value" + } + } + } + } + ] + } + }, + { + "id": "email_receipts", + "summary": "Email a receipt to each charged customer", + "value": { + "type": "rawscript", + "language": "bun", + "content": "// Each charge is what the payment API answered, which carries the customer to email.\nexport async function main(charges: { id: string; customer_id: number }[]) {\n for (const charge of charges) {\n const res = await fetch('https://mail.example.com/receipts', { method: 'POST', body: JSON.stringify(charge) })\n if (!res.ok) throw new Error(`receipt failed for charge ${charge.id}`)\n }\n return { sent: charges.length }\n}\n", + "input_transforms": { + "charges": { + "type": "javascript", + "expr": "results.charge" + } + } + } + } + ] + } + } + ], + "scripts": [ + { + "path": "f/ops/check_ssl_expiry", + "summary": "Check SSL certificate expiry", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": "The domain whose certificate to check" + } + }, + "required": [ + "domain" + ] + }, + "content": "export async function main(domain: string) {\n const res = await fetch(`https://ssl-check.example.com/${domain}`)\n return await res.json()\n}\n" + } + ], + "resources": [ + { + "path": "f/data/warehouse", + "resource_type": "postgresql", + "description": "Production warehouse", + "value": { + "host": "db.internal", + "port": 5432, + "dbname": "warehouse", + "user": "windmill", + "password": "$var:f/data/warehouse_password" + }, + "dbSchema": { + "public": { + "customers": { + "id": { + "type": "integer", + "required": true + }, + "email": { + "type": "text", + "required": true + }, + "plan": { + "type": "text", + "required": false + }, + "created_at": { + "type": "timestamp", + "required": true, + "default": "now()" + } + }, + "invoices": { + "id": { + "type": "integer", + "required": true + }, + "customer_id": { + "type": "integer", + "required": true + }, + "amount_cents": { + "type": "integer", + "required": true + }, + "due_date": { + "type": "date", + "required": true + }, + "paid": { + "type": "boolean", + "required": true, + "default": "false" + }, + "created_at": { + "type": "timestamp", + "required": true, + "default": "now()" + } + }, + "signups": { + "id": { + "type": "integer", + "required": true + }, + "email": { + "type": "text", + "required": true + }, + "source": { + "type": "text", + "required": false + }, + "created_at": { + "type": "timestamp", + "required": true, + "default": "now()" + } + } + } + } + }, + { + "path": "f/team/slack", + "resource_type": "slack", + "description": "Team Slack bot", + "value": { + "token": "$var:f/team/slack_token" + } + }, + { + "path": "f/support/triage_agent", + "resource_type": "ai_agent", + "description": "Labels incoming support tickets", + "value": { + "provider": { + "kind": "anthropic", + "model": "claude-sonnet-5", + "resource": "" + }, + "output_type": "text", + "system_prompt": "Read the support ticket and answer with one label: billing, bug or question.", + "memory": { + "kind": "off" + }, + "tools": [] + } + } + ], + "apps": [ + { + "path": "f/ops/console", + "summary": "Ops console", + "value": { + "files": { + "/App.tsx": "import { useState } from 'react'\nimport { backend } from './wmill'\n\nexport default function App() {\n\tconst [domain, setDomain] = useState('')\n\tconst [result, setResult] = useState()\n\treturn (\n\t\t
\n\t\t\t

Ops console

\n\t\t\t setDomain(e.target.value)} />\n\t\t\t\n\t\t\t
{JSON.stringify(result, null, 2)}
\n\t\t
\n\t)\n}\n" + }, + "runnables": { + "check_ssl": { + "type": "path", + "runType": "script", + "path": "f/ops/check_ssl_expiry", + "fields": {} + } + } + } + } + ], + "datatables": [ + { + "datatable_name": "main", + "schemas": { + "public": { + "feedback": { + "columns": { + "id": "int4", + "customer_email": "text", + "rating": "int4", + "comment": "text", + "created_at": "timestamptz" + }, + "rows": [ + { + "id": 1, + "customer_email": "ada@example.com", + "rating": 5, + "comment": "Fast support", + "created_at": "2026-10-01T09:00:00Z" + } + ] + }, + "onboarding_tasks": { + "columns": { + "id": "int4", + "customer_email": "text", + "task": "text", + "done": "bool" + }, + "rows": [ + { + "id": 1, + "customer_email": "ada@example.com", + "task": "Connect billing", + "done": false + } + ] + } + } + } + } + ], + "folders": [ + { + "name": "billing", + "summary": "Billing jobs", + "owners": [ + "u/ada" + ], + "extra_perms": { + "g/finance": false, + "u/bob": true + } + }, + { + "name": "ops", + "summary": "Operations", + "owners": [ + "u/admin" + ], + "extra_perms": {} + } + ], + "groups": [ + { + "name": "finance", + "summary": "Finance team", + "members": [ + "carol", + "dan" + ] + } + ] + } +} diff --git a/ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json b/ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json new file mode 100644 index 0000000000..b719ba0751 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json @@ -0,0 +1,22 @@ +{ + "user": { + "username": "admin", + "is_admin": true + }, + "workspace": { + "resources": [ + { + "path": "f/data/warehouse", + "resource_type": "postgresql", + "description": "Production warehouse", + "value": { + "host": "db.internal", + "port": 5432, + "dbname": "warehouse", + "user": "windmill", + "password": "$var:f/data/warehouse_password" + } + } + ] + } +} diff --git a/ai_evals/fixtures/frontend/global/initial/composer_incidents.json b/ai_evals/fixtures/frontend/global/initial/composer_incidents.json new file mode 100644 index 0000000000..4799b895ea --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/composer_incidents.json @@ -0,0 +1,83 @@ +{ + "workspace": { + "scripts": [ + { + "path": "f/billing/charge_cards", + "summary": "Charge cards", + "language": "bash", + "content": "echo \"charging card for customer $1\"\ncurl -sf https://payments.example.com/charge || { echo \"card declined: insufficient funds\" >&2; exit 1; }\n" + }, + { + "path": "f/sales/import_orders", + "summary": "Import orders", + "language": "bash", + "content": "echo \"imported $(date +%s) orders\"\n" + }, + { + "path": "f/media/gpu_render", + "summary": "GPU render", + "language": "bash", + "content": "echo \"rendering frame\"\n" + } + ], + "flows": [ + { + "path": "f/billing/refund_approval", + "summary": "Refund approval", + "value": { + "modules": [ + { + "id": "a", + "summary": "Ask a manager to approve the refund", + "value": { "type": "rawscript", "language": "bash", "content": "echo \"refund requested\"", "input_transforms": {} }, + "suspend": { "required_events": 1, "timeout": 86400 } + }, + { + "id": "b", + "summary": "Issue the refund", + "value": { "type": "rawscript", "language": "bash", "content": "echo \"refunded\"", "input_transforms": {} } + } + ] + } + } + ], + "schedules": [ + { "path": "f/billing/charge_cards_every_minute", "schedule": "0 * * * * *", "script_path": "f/billing/charge_cards", "summary": "Charge pending cards every minute" }, + { "path": "f/sales/import_orders_hourly", "schedule": "0 0 * * * *", "script_path": "f/sales/import_orders", "summary": "Import orders every hour" } + ], + "workers": [ + { + "worker": "wk-default-7f3a2", + "worker_group": "default", + "custom_tags": ["bash", "python3", "bun", "deno", "go", "flow", "dependency"], + "lastPingSecondsAgo": 3, + "jobs_executed": 214 + } + ], + "jobs": [ + { "id": "01930000-0000-7000-8000-00000000c001", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 1, "durationMs": 41, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c002", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 2, "durationMs": 38, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c003", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 3, "durationMs": 44, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c004", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 4, "durationMs": 40, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c005", "scriptPath": "f/billing/charge_cards", "createdBy": "alice", "success": false, "createdMinutesAgo": 30, "durationMs": 52, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c006", "scriptPath": "f/billing/charge_cards", "createdBy": "alice", "success": false, "createdMinutesAgo": 31, "durationMs": 47, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000d001", "scriptPath": "f/sales/import_orders", "schedulePath": "f/sales/import_orders_hourly", "createdBy": "schedule", "success": true, "createdMinutesAgo": 10, "durationMs": 820, "tag": "bash", "logs": "imported 112 orders" }, + { "id": "01930000-0000-7000-8000-00000000d002", "scriptPath": "f/sales/import_orders", "schedulePath": "f/sales/import_orders_hourly", "createdBy": "schedule", "success": true, "createdMinutesAgo": 70, "durationMs": 790, "tag": "bash", "logs": "imported 98 orders" }, + { "id": "01930000-0000-7000-8000-00000000d003", "scriptPath": "f/sales/import_orders", "schedulePath": "f/sales/import_orders_hourly", "createdBy": "schedule", "success": true, "createdMinutesAgo": 130, "durationMs": 805, "tag": "bash", "logs": "imported 104 orders" }, + { "id": "01930000-0000-7000-8000-00000000d004", "scriptPath": "f/sales/import_orders", "createdBy": "bob", "success": true, "createdMinutesAgo": 45, "durationMs": 811, "tag": "bash", "logs": "imported 3 orders" }, + { "id": "01930000-0000-7000-8000-00000000e001", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 22, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e002", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 22, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e003", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 22, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e004", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 21, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e005", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 21, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e006", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 21, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e007", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 20, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e008", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 20, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e009", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 20, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e010", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 19, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e011", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 19, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e012", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 19, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000f001", "scriptPath": "f/billing/refund_approval", "jobKind": "flow", "createdBy": "bob", "state": "suspended", "createdMinutesAgo": 40, "tag": "flow", "logs": "refund requested" } + ] + } +} diff --git a/backend/.sqlx/query-00ac2ddf7c3f6b2c4e9a47c6a237ef9e7e6b6b793147b1752ff07e800415bfa9.json b/backend/.sqlx/query-00ac2ddf7c3f6b2c4e9a47c6a237ef9e7e6b6b793147b1752ff07e800415bfa9.json new file mode 100644 index 0000000000..900023094d --- /dev/null +++ b/backend/.sqlx/query-00ac2ddf7c3f6b2c4e9a47c6a237ef9e7e6b6b793147b1752ff07e800415bfa9.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE native_trigger SET connection_path = $1 WHERE workspace_id = $2 AND connection_path = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "00ac2ddf7c3f6b2c4e9a47c6a237ef9e7e6b6b793147b1752ff07e800415bfa9" +} diff --git a/backend/.sqlx/query-020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json b/backend/.sqlx/query-00b32f6cd59154d9e529c8577072f000ae6cf37928508a82f51d3b3a325f3d1a.json similarity index 53% rename from backend/.sqlx/query-020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json rename to backend/.sqlx/query-00b32f6cd59154d9e529c8577072f000ae6cf37928508a82f51d3b3a325f3d1a.json index e8edd87bda..ce07d4fada 100644 --- a/backend/.sqlx/query-020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json +++ b/backend/.sqlx/query-00b32f6cd59154d9e529c8577072f000ae6cf37928508a82f51d3b3a325f3d1a.json @@ -1,23 +1,23 @@ { "db_name": "PostgreSQL", - "query": "SELECT value FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", + "query": "DELETE FROM variable WHERE workspace_id = $1 AND account = ANY($2) RETURNING path", "describe": { "columns": [ { "ordinal": 0, - "name": "value", + "name": "path", "type_info": "Varchar" } ], "parameters": { "Left": [ "Text", - "Text" + "Int4Array" ] }, "nullable": [ false ] }, - "hash": "020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c" + "hash": "00b32f6cd59154d9e529c8577072f000ae6cf37928508a82f51d3b3a325f3d1a" } diff --git a/backend/.sqlx/query-086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d.json b/backend/.sqlx/query-086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d.json new file mode 100644 index 0000000000..e9183fe2d4 --- /dev/null +++ b/backend/.sqlx/query-086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2 AND account = $3)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int4" + ] + }, + "nullable": [ + null + ] + }, + "hash": "086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d" +} diff --git a/backend/.sqlx/query-7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71.json b/backend/.sqlx/query-08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7.json similarity index 62% rename from backend/.sqlx/query-7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71.json rename to backend/.sqlx/query-08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7.json index 331816c897..4031b62a9e 100644 --- a/backend/.sqlx/query-7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71.json +++ b/backend/.sqlx/query-08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, account, (now() > account.expires_at) as is_expired, is_secret, path from variable\n LEFT JOIN account ON variable.account = account.id WHERE variable.path = $1 AND variable.workspace_id = $2", + "query": "SELECT value::text AS \"value!\", account, (now() > account.expires_at) as is_expired, is_secret, path from variable\n LEFT JOIN account ON variable.account = account.id WHERE variable.path = $1 AND variable.workspace_id = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -36,12 +36,12 @@ ] }, "nullable": [ - false, + null, true, null, false, false ] }, - "hash": "7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71" + "hash": "08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7" } diff --git a/backend/.sqlx/query-09e2a19435068f9e9bfd5bcb44b4e283c71729f81550f6f7156ce4970345cc07.json b/backend/.sqlx/query-09e2a19435068f9e9bfd5bcb44b4e283c71729f81550f6f7156ce4970345cc07.json deleted file mode 100644 index 8ece28ff8f..0000000000 --- a/backend/.sqlx/query-09e2a19435068f9e9bfd5bcb44b4e283c71729f81550f6f7156ce4970345cc07.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE account SET refresh_error = $1 WHERE workspace_id = $2 AND id = $3", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Text", - "Int4" - ] - }, - "nullable": [] - }, - "hash": "09e2a19435068f9e9bfd5bcb44b4e283c71729f81550f6f7156ce4970345cc07" -} diff --git a/backend/.sqlx/query-0d419f09cce9f33fecfabc62b17e8848ac8184d61d3f7cde126a56080aef643c.json b/backend/.sqlx/query-0d419f09cce9f33fecfabc62b17e8848ac8184d61d3f7cde126a56080aef643c.json new file mode 100644 index 0000000000..1dd5c1042c --- /dev/null +++ b/backend/.sqlx/query-0d419f09cce9f33fecfabc62b17e8848ac8184d61d3f7cde126a56080aef643c.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM workspace_settings WHERE ($1::text IS NULL OR workspace_id = $1) AND (\n jsonb_typeof(auto_invite) = 'object' AND COALESCE(auto_invite->>'role',\n CASE WHEN (auto_invite->>'operator')::boolean THEN 'operator' ELSE 'developer' END) = $2\n OR EXISTS (SELECT 1 FROM jsonb_each_text(\n CASE WHEN jsonb_typeof(auto_invite->'instance_groups_roles') = 'object'\n THEN auto_invite->'instance_groups_roles' ELSE '{}'::jsonb END) g\n WHERE g.value = $2))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "0d419f09cce9f33fecfabc62b17e8848ac8184d61d3f7cde126a56080aef643c" +} diff --git a/backend/.sqlx/query-0d69f5f6d2e3a4b7b801c6feea92a383e841fa7c3f1c5e2849481c6057ab1e84.json b/backend/.sqlx/query-0d69f5f6d2e3a4b7b801c6feea92a383e841fa7c3f1c5e2849481c6057ab1e84.json new file mode 100644 index 0000000000..56caf2108d --- /dev/null +++ b/backend/.sqlx/query-0d69f5f6d2e3a4b7b801c6feea92a383e841fa7c3f1c5e2849481c6057ab1e84.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM workspace_settings WHERE ($1::text IS NOT NULL AND workspace_id = $1\n OR $1::text IS NULL AND NOT COALESCE(role_overrides ? $2, false)) AND (\n auto_invite->>'role' = $2\n OR EXISTS (SELECT 1 FROM jsonb_each_text(\n CASE WHEN jsonb_typeof(auto_invite->'instance_groups_roles') = 'object'\n THEN auto_invite->'instance_groups_roles' ELSE '{}'::jsonb END) g\n WHERE g.value = $2))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "0d69f5f6d2e3a4b7b801c6feea92a383e841fa7c3f1c5e2849481c6057ab1e84" +} diff --git a/backend/.sqlx/query-0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa.json b/backend/.sqlx/query-0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa.json new file mode 100644 index 0000000000..07a85d9004 --- /dev/null +++ b/backend/.sqlx/query-0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET role_overrides =\n (SELECT role_overrides FROM workspace_settings WHERE workspace_id = $2)\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa" +} diff --git a/backend/.sqlx/query-104b8d267f8f904122973d20629473ac77fad069e7c805cf3c2352bd72f8ffb6.json b/backend/.sqlx/query-104b8d267f8f904122973d20629473ac77fad069e7c805cf3c2352bd72f8ffb6.json new file mode 100644 index 0000000000..e9fb7a6b3b --- /dev/null +++ b/backend/.sqlx/query-104b8d267f8f904122973d20629473ac77fad069e7c805cf3c2352bd72f8ffb6.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT role_overrides FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "role_overrides", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "104b8d267f8f904122973d20629473ac77fad069e7c805cf3c2352bd72f8ffb6" +} diff --git a/backend/.sqlx/query-1966a1c4776492599de66d6d189d399c37957f832485156f703f59bd39cdc2bb.json b/backend/.sqlx/query-1966a1c4776492599de66d6d189d399c37957f832485156f703f59bd39cdc2bb.json new file mode 100644 index 0000000000..7f1ebcf9dc --- /dev/null +++ b/backend/.sqlx/query-1966a1c4776492599de66d6d189d399c37957f832485156f703f59bd39cdc2bb.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM variable v\n JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n WHERE v.workspace_id = $1 AND v.path = $2 AND a.client = $3\n AND a.is_workspace_integration = true)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "1966a1c4776492599de66d6d189d399c37957f832485156f703f59bd39cdc2bb" +} diff --git a/backend/.sqlx/query-44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f.json b/backend/.sqlx/query-19b9173fad68c2bde71a70d1ce947c20773dd4c44f19b47e73e24438f5c78ab3.json similarity index 78% rename from backend/.sqlx/query-44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f.json rename to backend/.sqlx/query-19b9173fad68c2bde71a70d1ce947c20773dd4c44f19b47e73e24438f5c78ab3.json index 212f6f067b..e66aabbcfb 100644 --- a/backend/.sqlx/query-44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f.json +++ b/backend/.sqlx/query-19b9173fad68c2bde71a70d1ce947c20773dd4c44f19b47e73e24438f5c78ab3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT c.workspace_id, c.agent_path, c.is_default FROM slack_agent_channel c\n JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id\n AND ws.slack_team_id = c.slack_team_id\n WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path", + "query": "SELECT c.workspace_id, c.agent_path, c.is_default FROM slack_agent_channel c\n JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id\n AND ws.slack_team_id = c.slack_team_id\n WHERE c.slack_team_id = $1 AND c.channel_id = $2\n AND ws.workspace_id = ANY($3)\n ORDER BY c.agent_path", "describe": { "columns": [ { @@ -22,7 +22,8 @@ "parameters": { "Left": [ "Text", - "Text" + "Text", + "TextArray" ] }, "nullable": [ @@ -31,5 +32,5 @@ false ] }, - "hash": "44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f" + "hash": "19b9173fad68c2bde71a70d1ce947c20773dd4c44f19b47e73e24438f5c78ab3" } diff --git a/backend/.sqlx/query-1c97bf1af258b43fb8dedd3417d0e086996d5fcc3c270e5c1cc9824c30d82726.json b/backend/.sqlx/query-1c97bf1af258b43fb8dedd3417d0e086996d5fcc3c270e5c1cc9824c30d82726.json new file mode 100644 index 0000000000..bc0ce67103 --- /dev/null +++ b/backend/.sqlx/query-1c97bf1af258b43fb8dedd3417d0e086996d5fcc3c270e5c1cc9824c30d82726.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE usr SET workspace_role = $1, operator = $2 WHERE username = $3 AND workspace_id = $4", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Bool", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "1c97bf1af258b43fb8dedd3417d0e086996d5fcc3c270e5c1cc9824c30d82726" +} diff --git a/backend/.sqlx/query-61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08.json b/backend/.sqlx/query-1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e.json similarity index 56% rename from backend/.sqlx/query-61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08.json rename to backend/.sqlx/query-1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e.json index f97d5e310a..da40d27d9f 100644 --- a/backend/.sqlx/query-61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08.json +++ b/backend/.sqlx/query-1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret\n FROM variable\n WHERE path = $1 AND workspace_id = $2", + "query": "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -21,9 +21,9 @@ ] }, "nullable": [ - false, + null, false ] }, - "hash": "61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08" + "hash": "1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e" } diff --git a/backend/.sqlx/query-1e0751bef92b5628b8d54448da171d56af87b5b263f8484c886e7f51e0198409.json b/backend/.sqlx/query-1e0751bef92b5628b8d54448da171d56af87b5b263f8484c886e7f51e0198409.json new file mode 100644 index 0000000000..963ca738f2 --- /dev/null +++ b/backend/.sqlx/query-1e0751bef92b5628b8d54448da171d56af87b5b263f8484c886e7f51e0198409.json @@ -0,0 +1,47 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.path, r.created_by AS \"owner?\", true AS \"workspace!\"\n FROM workspace_integrations wi\n JOIN variable v ON v.workspace_id = wi.workspace_id AND v.path = wi.resource_path\n JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n LEFT JOIN resource r ON r.workspace_id = v.workspace_id AND r.path = v.path\n WHERE wi.workspace_id = $1 AND wi.service_name = $2\n AND a.client = $3 AND a.is_workspace_integration = true", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "owner?", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "workspace!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "Text" + ] + }, + "nullable": [ + false, + true, + null + ] + }, + "hash": "1e0751bef92b5628b8d54448da171d56af87b5b263f8484c886e7f51e0198409" +} diff --git a/backend/.sqlx/query-1fbb8493d20eacea2ac78c4473a85f96bd91de548185238f9fd66ac2b4a1e0a0.json b/backend/.sqlx/query-1fbb8493d20eacea2ac78c4473a85f96bd91de548185238f9fd66ac2b4a1e0a0.json new file mode 100644 index 0000000000..084ae3562e --- /dev/null +++ b/backend/.sqlx/query-1fbb8493d20eacea2ac78c4473a85f96bd91de548185238f9fd66ac2b4a1e0a0.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT\n workspace_invite.workspace_id,\n workspace_invite.email,\n workspace_invite.is_admin,\n workspace_invite.operator,\n COALESCE(workspace_invite.workspace_role, CASE WHEN workspace_invite.operator THEN 'operator' ELSE 'developer' END) AS \"role!\",\n workspace.parent_workspace_id\n FROM workspace_invite JOIN workspace ON workspace_invite.workspace_id = workspace.id\n WHERE workspace_id = $1\n ORDER BY workspace_invite.email", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "role!", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "parent_workspace_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + null, + true + ] + }, + "hash": "1fbb8493d20eacea2ac78c4473a85f96bd91de548185238f9fd66ac2b4a1e0a0" +} diff --git a/backend/.sqlx/query-205f2fb7629382294e53869aa5d2f722f631882929086c453b5825ab4b9c1cb8.json b/backend/.sqlx/query-205f2fb7629382294e53869aa5d2f722f631882929086c453b5825ab4b9c1cb8.json new file mode 100644 index 0000000000..e7b50bb89a --- /dev/null +++ b/backend/.sqlx/query-205f2fb7629382294e53869aa5d2f722f631882929086c453b5825ab4b9c1cb8.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM usr t WHERE ($1::text IS NULL OR t.workspace_id = $1) AND\n COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END) = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "205f2fb7629382294e53869aa5d2f722f631882929086c453b5825ab4b9c1cb8" +} diff --git a/backend/.sqlx/query-22e14fc3bb5d8cf3006f0002e8522b8cc0b2fece43f03c0f025e7acefa0d4f32.json b/backend/.sqlx/query-22e14fc3bb5d8cf3006f0002e8522b8cc0b2fece43f03c0f025e7acefa0d4f32.json index 3df72f8955..6e8e17ddf2 100644 --- a/backend/.sqlx/query-22e14fc3bb5d8cf3006f0002e8522b8cc0b2fece43f03c0f025e7acefa0d4f32.json +++ b/backend/.sqlx/query-22e14fc3bb5d8cf3006f0002e8522b8cc0b2fece43f03c0f025e7acefa0d4f32.json @@ -17,7 +17,8 @@ "script", "flow", "raw_app", - "asset" + "asset", + "agent" ] } } diff --git a/backend/.sqlx/query-23b2a39e37e93ca9367e954eba94b1a6f432edb76320c50e0d07088937c17a01.json b/backend/.sqlx/query-23b2a39e37e93ca9367e954eba94b1a6f432edb76320c50e0d07088937c17a01.json new file mode 100644 index 0000000000..de6cf870b5 --- /dev/null +++ b/backend/.sqlx/query-23b2a39e37e93ca9367e954eba94b1a6f432edb76320c50e0d07088937c17a01.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT expires_at FROM account WHERE workspace_id = $1 AND id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "expires_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [ + false + ] + }, + "hash": "23b2a39e37e93ca9367e954eba94b1a6f432edb76320c50e0d07088937c17a01" +} diff --git a/backend/.sqlx/query-257b3bc19f738fe36e3c995c5ba239e1f2855cf39f9fe7a92d722732653fd98b.json b/backend/.sqlx/query-257b3bc19f738fe36e3c995c5ba239e1f2855cf39f9fe7a92d722732653fd98b.json new file mode 100644 index 0000000000..82a4b1377b --- /dev/null +++ b/backend/.sqlx/query-257b3bc19f738fe36e3c995c5ba239e1f2855cf39f9fe7a92d722732653fd98b.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT user_email FROM mcp_oauth_refresh_token WHERE refresh_token = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "user_email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "257b3bc19f738fe36e3c995c5ba239e1f2855cf39f9fe7a92d722732653fd98b" +} diff --git a/backend/.sqlx/query-25b09b592b6917214fd7cfabfece48d266b2d5dc11236c2bb41b1a927ede63d8.json b/backend/.sqlx/query-25b09b592b6917214fd7cfabfece48d266b2d5dc11236c2bb41b1a927ede63d8.json new file mode 100644 index 0000000000..ed1e19e7e0 --- /dev/null +++ b/backend/.sqlx/query-25b09b592b6917214fd7cfabfece48d266b2d5dc11236c2bb41b1a927ede63d8.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO usr (workspace_id, username, email, is_admin, created_at, operator, disabled, role, workspace_role) SELECT $1, username, email, is_admin, created_at, operator, disabled, role, workspace_role FROM usr WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "25b09b592b6917214fd7cfabfece48d266b2d5dc11236c2bb41b1a927ede63d8" +} diff --git a/backend/.sqlx/query-a588f4caa014008b50eccd09122b09f8a098e58791893bacaaf2ff67a30c031c.json b/backend/.sqlx/query-2602402bedcdbc45cdc0d64a76ce075c6ae51404037b0a7d4d33faf6a7d6a6d8.json similarity index 55% rename from backend/.sqlx/query-a588f4caa014008b50eccd09122b09f8a098e58791893bacaaf2ff67a30c031c.json rename to backend/.sqlx/query-2602402bedcdbc45cdc0d64a76ce075c6ae51404037b0a7d4d33faf6a7d6a6d8.json index 2412e1f5ee..8a131d8465 100644 --- a/backend/.sqlx/query-a588f4caa014008b50eccd09122b09f8a098e58791893bacaaf2ff67a30c031c.json +++ b/backend/.sqlx/query-2602402bedcdbc45cdc0d64a76ce075c6ae51404037b0a7d4d33faf6a7d6a6d8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n INSERT INTO workspace_integrations (\n workspace_id,\n service_name,\n oauth_data,\n resource_path,\n created_by,\n created_at,\n updated_at\n ) VALUES (\n $1, $2, $3, $4, $5, now(), now()\n )\n ON CONFLICT (workspace_id, service_name)\n DO UPDATE SET\n oauth_data = $3,\n resource_path = $4,\n updated_at = now()\n ", + "query": "\n INSERT INTO workspace_integrations (\n workspace_id,\n service_name,\n oauth_data,\n created_by,\n created_at,\n updated_at\n ) VALUES (\n $1, $2, $3, $4, now(), now()\n )\n ON CONFLICT (workspace_id, service_name)\n DO UPDATE SET\n oauth_data = $3,\n updated_at = now()\n ", "describe": { "columns": [], "parameters": { @@ -19,11 +19,10 @@ } }, "Jsonb", - "Text", "Varchar" ] }, "nullable": [] }, - "hash": "a588f4caa014008b50eccd09122b09f8a098e58791893bacaaf2ff67a30c031c" + "hash": "2602402bedcdbc45cdc0d64a76ce075c6ae51404037b0a7d4d33faf6a7d6a6d8" } diff --git a/backend/.sqlx/query-2e8a53e73c3b5c2662efd0e2876f168c2f79258fb900199e8575973d5b3d32bb.json b/backend/.sqlx/query-2e8a53e73c3b5c2662efd0e2876f168c2f79258fb900199e8575973d5b3d32bb.json new file mode 100644 index 0000000000..d55c6ebb51 --- /dev/null +++ b/backend/.sqlx/query-2e8a53e73c3b5c2662efd0e2876f168c2f79258fb900199e8575973d5b3d32bb.json @@ -0,0 +1,94 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace.id, workspace.name, usr.username, workspace_settings.color, workspace.parent_workspace_id,\n workspace.is_dev_workspace, workspace.dev_workspace_label,\n workspace.owner AS \"created_by?\",\n usr.is_admin, usr.operator, usr.workspace_role,\n usr.disabled, usr.is_service_account\n FROM workspace\n JOIN usr ON usr.workspace_id = workspace.id\n JOIN workspace_settings ON workspace_settings.workspace_id = workspace.id\n WHERE usr.email = $1 AND workspace.deleted = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "color", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "parent_workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "is_dev_workspace", + "type_info": "Bool" + }, + { + "ordinal": 6, + "name": "dev_workspace_label", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "created_by?", + "type_info": "Varchar" + }, + { + "ordinal": 8, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 9, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 10, + "name": "workspace_role", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "disabled", + "type_info": "Bool" + }, + { + "ordinal": 12, + "name": "is_service_account", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + false, + true, + false, + false, + false, + true, + false, + false + ] + }, + "hash": "2e8a53e73c3b5c2662efd0e2876f168c2f79258fb900199e8575973d5b3d32bb" +} diff --git a/backend/.sqlx/query-0010ef26da16facd1c2c832601ac687c4c27de46a90f45496b8446af1a9d0578.json b/backend/.sqlx/query-30b1021260b5ec83a04be1f3dbea08cc81ee85cf98696d9e29a34557587eaf86.json similarity index 67% rename from backend/.sqlx/query-0010ef26da16facd1c2c832601ac687c4c27de46a90f45496b8446af1a9d0578.json rename to backend/.sqlx/query-30b1021260b5ec83a04be1f3dbea08cc81ee85cf98696d9e29a34557587eaf86.json index cf0754d720..4c0cbba06c 100644 --- a/backend/.sqlx/query-0010ef26da16facd1c2c832601ac687c4c27de46a90f45496b8446af1a9d0578.json +++ b/backend/.sqlx/query-30b1021260b5ec83a04be1f3dbea08cc81ee85cf98696d9e29a34557587eaf86.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n oauth_data as \"oauth_data: sqlx::types::Json\",\n service_name as \"service_name!: ServiceName\",\n resource_path\n FROM\n workspace_integrations\n WHERE\n workspace_id = $1\n ", + "query": "\n SELECT\n oauth_data as \"oauth_data: sqlx::types::Json\",\n service_name as \"service_name!: ServiceName\"\n FROM\n workspace_integrations\n WHERE\n workspace_id = $1\n ", "describe": { "columns": [ { @@ -23,11 +23,6 @@ } } } - }, - { - "ordinal": 2, - "name": "resource_path", - "type_info": "Text" } ], "parameters": { @@ -37,9 +32,8 @@ }, "nullable": [ true, - false, - true + false ] }, - "hash": "0010ef26da16facd1c2c832601ac687c4c27de46a90f45496b8446af1a9d0578" + "hash": "30b1021260b5ec83a04be1f3dbea08cc81ee85cf98696d9e29a34557587eaf86" } diff --git a/backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json b/backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json new file mode 100644 index 0000000000..3933b5e6a2 --- /dev/null +++ b/backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value::text AS \"value!\", is_secret, description, value_valid_until\n FROM variable\n WHERE workspace_id = $1 AND path = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "is_secret", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "description", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "value_valid_until", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null, + false, + false, + true + ] + }, + "hash": "30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b" +} diff --git a/backend/.sqlx/query-32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a.json b/backend/.sqlx/query-32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a.json new file mode 100644 index 0000000000..0e2bcbd955 --- /dev/null +++ b/backend/.sqlx/query-32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO variable\n (workspace_id, path, value, is_secret, description, account, is_oauth, expires_at, value_valid_until, labels, edited_by)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Bool", + "Varchar", + "Int4", + "Bool", + "Timestamptz", + "Timestamptz", + "TextArray", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a" +} diff --git a/backend/.sqlx/query-b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd.json b/backend/.sqlx/query-3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361.json similarity index 63% rename from backend/.sqlx/query-b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd.json rename to backend/.sqlx/query-3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361.json index 6ad2fc0ae1..b7b2516d40 100644 --- a/backend/.sqlx/query-b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd.json +++ b/backend/.sqlx/query-3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT path, value, is_secret FROM variable WHERE workspace_id = $1", + "query": "SELECT path, value::text AS \"value!\", is_secret FROM variable WHERE workspace_id = $1", "describe": { "columns": [ { @@ -10,8 +10,8 @@ }, { "ordinal": 1, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 2, @@ -26,9 +26,9 @@ }, "nullable": [ false, - false, + null, false ] }, - "hash": "b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd" + "hash": "3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361" } diff --git a/backend/.sqlx/query-35238a186adbe0583010dbe8e298a907f16d9e88f648705f2372dfe7c0523879.json b/backend/.sqlx/query-35238a186adbe0583010dbe8e298a907f16d9e88f648705f2372dfe7c0523879.json new file mode 100644 index 0000000000..027085c2a7 --- /dev/null +++ b/backend/.sqlx/query-35238a186adbe0583010dbe8e298a907f16d9e88f648705f2372dfe7c0523879.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, slack_oauth_client_id IS NOT NULL AS \"own_app!\",\n slack_signing_secret\n FROM workspace_settings WHERE slack_team_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "own_app!", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "slack_signing_secret", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + null, + true + ] + }, + "hash": "35238a186adbe0583010dbe8e298a907f16d9e88f648705f2372dfe7c0523879" +} diff --git a/backend/.sqlx/query-36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51.json b/backend/.sqlx/query-36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51.json new file mode 100644 index 0000000000..8d7e440538 --- /dev/null +++ b/backend/.sqlx/query-36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51.json @@ -0,0 +1,36 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.value::text AS \"value!\", a.id AS account_id, a.refresh_token\n FROM variable v\n JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n WHERE v.workspace_id = $1 AND v.path = $2\n AND a.client = $3 AND a.is_workspace_integration = true", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "account_id", + "type_info": "Int4" + }, + { + "ordinal": 2, + "name": "refresh_token", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + null, + false, + false + ] + }, + "hash": "36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51" +} diff --git a/backend/.sqlx/query-369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4.json b/backend/.sqlx/query-369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4.json index 501e149fc4..20689e1f0a 100644 --- a/backend/.sqlx/query-369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4.json +++ b/backend/.sqlx/query-369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4.json @@ -53,7 +53,7 @@ false, false, false, - false, + true, false, false, true, diff --git a/backend/.sqlx/query-63c48fde8c0c0fff9abffc3be27e9948556b636b70b818cc31c2d50921a27366.json b/backend/.sqlx/query-3829559733fa087201f935ee10a5cecf2cec4f1646015ed7cf476efaba67707f.json similarity index 53% rename from backend/.sqlx/query-63c48fde8c0c0fff9abffc3be27e9948556b636b70b818cc31c2d50921a27366.json rename to backend/.sqlx/query-3829559733fa087201f935ee10a5cecf2cec4f1646015ed7cf476efaba67707f.json index 0ba2d18257..af7a60664d 100644 --- a/backend/.sqlx/query-63c48fde8c0c0fff9abffc3be27e9948556b636b70b818cc31c2d50921a27366.json +++ b/backend/.sqlx/query-3829559733fa087201f935ee10a5cecf2cec4f1646015ed7cf476efaba67707f.json @@ -1,42 +1,62 @@ { "db_name": "PostgreSQL", - "query": "SELECT client, refresh_token, grant_type, cc_client_id, cc_client_secret, cc_token_url, scopes FROM account WHERE workspace_id = $1 AND id = $2", + "query": "SELECT mcp_server_url, is_workspace_integration, client, refresh_token, grant_type,\n cc_client_id, cc_client_secret, cc_token_url, scopes, expires_at,\n now() > expires_at AS \"expired!\"\n FROM account WHERE workspace_id = $1 AND id = $2", "describe": { "columns": [ { "ordinal": 0, + "name": "mcp_server_url", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "is_workspace_integration", + "type_info": "Bool" + }, + { + "ordinal": 2, "name": "client", "type_info": "Varchar" }, { - "ordinal": 1, + "ordinal": 3, "name": "refresh_token", "type_info": "Varchar" }, { - "ordinal": 2, + "ordinal": 4, "name": "grant_type", "type_info": "Varchar" }, { - "ordinal": 3, + "ordinal": 5, "name": "cc_client_id", "type_info": "Varchar" }, { - "ordinal": 4, + "ordinal": 6, "name": "cc_client_secret", "type_info": "Varchar" }, { - "ordinal": 5, + "ordinal": 7, "name": "cc_token_url", "type_info": "Varchar" }, { - "ordinal": 6, + "ordinal": 8, "name": "scopes", "type_info": "TextArray" + }, + { + "ordinal": 9, + "name": "expires_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 10, + "name": "expired!", + "type_info": "Bool" } ], "parameters": { @@ -46,14 +66,18 @@ ] }, "nullable": [ + true, + false, false, false, false, true, true, true, - true + true, + false, + null ] }, - "hash": "63c48fde8c0c0fff9abffc3be27e9948556b636b70b818cc31c2d50921a27366" + "hash": "3829559733fa087201f935ee10a5cecf2cec4f1646015ed7cf476efaba67707f" } diff --git a/backend/.sqlx/query-392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3.json b/backend/.sqlx/query-392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3.json new file mode 100644 index 0000000000..1b5aa1bd1f --- /dev/null +++ b/backend/.sqlx/query-392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3" +} diff --git a/backend/.sqlx/query-3b01c43a828ec5d61ed92a27bdb16b526db8e60887d6279b0e66197da686fbf8.json b/backend/.sqlx/query-3b01c43a828ec5d61ed92a27bdb16b526db8e60887d6279b0e66197da686fbf8.json new file mode 100644 index 0000000000..02871b22f1 --- /dev/null +++ b/backend/.sqlx/query-3b01c43a828ec5d61ed92a27bdb16b526db8e60887d6279b0e66197da686fbf8.json @@ -0,0 +1,19 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO usr (workspace_id, username, email, is_admin, operator, added_via, workspace_role) VALUES ($1, $2, $3, false, $4, $5, $6) ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Bool", + "Jsonb", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "3b01c43a828ec5d61ed92a27bdb16b526db8e60887d6279b0e66197da686fbf8" +} diff --git a/backend/.sqlx/query-3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853.json b/backend/.sqlx/query-3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853.json new file mode 100644 index 0000000000..a41e413243 --- /dev/null +++ b/backend/.sqlx/query-3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND archived = false AND deleted = false)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853" +} diff --git a/backend/.sqlx/query-7443ba1f922e190bb9a0ca313847f8d27c35a6ee3aff20157d6285e73aa923ef.json b/backend/.sqlx/query-3e5bdc2e071fc2f1e3c7971736272f20bb5a0aa921a614bd02898d3f162660c2.json similarity index 76% rename from backend/.sqlx/query-7443ba1f922e190bb9a0ca313847f8d27c35a6ee3aff20157d6285e73aa923ef.json rename to backend/.sqlx/query-3e5bdc2e071fc2f1e3c7971736272f20bb5a0aa921a614bd02898d3f162660c2.json index 4ac58627e7..984c702467 100644 --- a/backend/.sqlx/query-7443ba1f922e190bb9a0ca313847f8d27c35a6ee3aff20157d6285e73aa923ef.json +++ b/backend/.sqlx/query-3e5bdc2e071fc2f1e3c7971736272f20bb5a0aa921a614bd02898d3f162660c2.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n workspace_id,\n service_name AS \"service_name!: ServiceName\",\n oauth_data,\n resource_path,\n created_at,\n updated_at,\n created_by\n FROM\n workspace_integrations\n WHERE\n workspace_id = $1\n AND service_name = $2\n ", + "query": "\n SELECT\n workspace_id,\n service_name AS \"service_name!: ServiceName\",\n oauth_data,\n created_at,\n updated_at,\n created_by\n FROM\n workspace_integrations\n WHERE\n workspace_id = $1\n AND service_name = $2\n ", "describe": { "columns": [ { @@ -31,21 +31,16 @@ }, { "ordinal": 3, - "name": "resource_path", - "type_info": "Text" - }, - { - "ordinal": 4, "name": "created_at", "type_info": "Timestamptz" }, { - "ordinal": 5, + "ordinal": 4, "name": "updated_at", "type_info": "Timestamptz" }, { - "ordinal": 6, + "ordinal": 5, "name": "created_by", "type_info": "Varchar" } @@ -71,11 +66,10 @@ false, false, true, - true, false, false, false ] }, - "hash": "7443ba1f922e190bb9a0ca313847f8d27c35a6ee3aff20157d6285e73aa923ef" + "hash": "3e5bdc2e071fc2f1e3c7971736272f20bb5a0aa921a614bd02898d3f162660c2" } diff --git a/backend/.sqlx/query-40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec.json b/backend/.sqlx/query-40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec.json new file mode 100644 index 0000000000..ab8bc4e241 --- /dev/null +++ b/backend/.sqlx/query-40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value::text AS \"value!\" FROM variable WHERE workspace_id = $1 AND path = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec" +} diff --git a/backend/.sqlx/query-420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210.json b/backend/.sqlx/query-420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210.json new file mode 100644 index 0000000000..2b0a574473 --- /dev/null +++ b/backend/.sqlx/query-420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM workspace_diff\n WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script'\n AND path = 'u/admin/inline' AND fork_last_event_kind = 'write')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210" +} diff --git a/backend/.sqlx/query-464286216add454cb64dba810d964c4b6a41d96df223b6d3d1d1bc972ab10d42.json b/backend/.sqlx/query-464286216add454cb64dba810d964c4b6a41d96df223b6d3d1d1bc972ab10d42.json new file mode 100644 index 0000000000..43bb3da025 --- /dev/null +++ b/backend/.sqlx/query-464286216add454cb64dba810d964c4b6a41d96df223b6d3d1d1bc972ab10d42.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO usr (workspace_id, username, email, is_admin, created_at, operator, disabled, role, is_service_account, added_via, workspace_role)\n SELECT $1, username, email, is_admin, created_at, operator, disabled, role, is_service_account,\n CASE WHEN $3 THEN NULL ELSE added_via END, workspace_role\n FROM usr WHERE workspace_id = $2\n AND (NOT $3 OR (NOT operator AND NOT disabled AND NOT is_service_account))\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "464286216add454cb64dba810d964c4b6a41d96df223b6d3d1d1bc972ab10d42" +} diff --git a/backend/.sqlx/query-4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484.json b/backend/.sqlx/query-4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484.json new file mode 100644 index 0000000000..8cead5cb8e --- /dev/null +++ b/backend/.sqlx/query-4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_failed_at = NULL\n WHERE workspace_id = $1 AND variable_expiration_failed_at IS NOT NULL\n RETURNING 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484" +} diff --git a/backend/.sqlx/query-6c75c89fb215c646f54f2036c40a86a4f4ea8880cc5d0b511aa70b6fd50072c5.json b/backend/.sqlx/query-4c12e63ddcf4e8cfe2227421db8869c4fb77e2fa3b98d6b054995875f3fd5a10.json similarity index 68% rename from backend/.sqlx/query-6c75c89fb215c646f54f2036c40a86a4f4ea8880cc5d0b511aa70b6fd50072c5.json rename to backend/.sqlx/query-4c12e63ddcf4e8cfe2227421db8869c4fb77e2fa3b98d6b054995875f3fd5a10.json index 45605c04dd..b07b2ae6b5 100644 --- a/backend/.sqlx/query-6c75c89fb215c646f54f2036c40a86a4f4ea8880cc5d0b511aa70b6fd50072c5.json +++ b/backend/.sqlx/query-4c12e63ddcf4e8cfe2227421db8869c4fb77e2fa3b98d6b054995875f3fd5a10.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT external_id, webhook_token_hash FROM native_trigger WHERE workspace_id = $1 AND service_name = $2", + "query": "SELECT external_id, script_path FROM native_trigger\n WHERE workspace_id = $1 AND service_name = $2 AND connection_path = $3", "describe": { "columns": [ { @@ -10,7 +10,7 @@ }, { "ordinal": 1, - "name": "webhook_token_hash", + "name": "script_path", "type_info": "Varchar" } ], @@ -28,7 +28,8 @@ ] } } - } + }, + "Text" ] }, "nullable": [ @@ -36,5 +37,5 @@ false ] }, - "hash": "6c75c89fb215c646f54f2036c40a86a4f4ea8880cc5d0b511aa70b6fd50072c5" + "hash": "4c12e63ddcf4e8cfe2227421db8869c4fb77e2fa3b98d6b054995875f3fd5a10" } diff --git a/backend/.sqlx/query-4c74a75d99f8d6689470da1d57d3db8bf47f11969a0c026a35a6673574e074d8.json b/backend/.sqlx/query-4c74a75d99f8d6689470da1d57d3db8bf47f11969a0c026a35a6673574e074d8.json new file mode 100644 index 0000000000..fd576892db --- /dev/null +++ b/backend/.sqlx/query-4c74a75d99f8d6689470da1d57d3db8bf47f11969a0c026a35a6673574e074d8.json @@ -0,0 +1,19 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO usr\n (workspace_id, email, username, is_admin, operator, workspace_role)\n VALUES ($1, $2, $3, $4, $5, $6)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Bool", + "Bool", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "4c74a75d99f8d6689470da1d57d3db8bf47f11969a0c026a35a6673574e074d8" +} diff --git a/backend/.sqlx/query-4d48a34016cc642fe3b3b24220615a59165009048a7c93942ee2ecd78524fb5a.json b/backend/.sqlx/query-4d48a34016cc642fe3b3b24220615a59165009048a7c93942ee2ecd78524fb5a.json new file mode 100644 index 0000000000..430c45c995 --- /dev/null +++ b/backend/.sqlx/query-4d48a34016cc642fe3b3b24220615a59165009048a7c93942ee2ecd78524fb5a.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM resource WHERE workspace_id = $1 AND path = ANY($2)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "4d48a34016cc642fe3b3b24220615a59165009048a7c93942ee2ecd78524fb5a" +} diff --git a/backend/.sqlx/query-51a30b84aedb4852ea78a4bf6a9f7c5090f6ed3b4d9d03fa5b5a827ffa39c635.json b/backend/.sqlx/query-51a30b84aedb4852ea78a4bf6a9f7c5090f6ed3b4d9d03fa5b5a827ffa39c635.json new file mode 100644 index 0000000000..e6194747b2 --- /dev/null +++ b/backend/.sqlx/query-51a30b84aedb4852ea78a4bf6a9f7c5090f6ed3b4d9d03fa5b5a827ffa39c635.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM account WHERE workspace_id = $1 AND id = $2 AND is_workspace_integration = true\n AND NOT EXISTS (SELECT 1 FROM variable WHERE workspace_id = $1 AND account = $2)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "51a30b84aedb4852ea78a4bf6a9f7c5090f6ed3b4d9d03fa5b5a827ffa39c635" +} diff --git a/backend/.sqlx/query-5294237a0bb6b23aed6915f430ac595c6f0d6f215725132fb7ef33bb1847831d.json b/backend/.sqlx/query-5294237a0bb6b23aed6915f430ac595c6f0d6f215725132fb7ef33bb1847831d.json new file mode 100644 index 0000000000..3c3870611e --- /dev/null +++ b/backend/.sqlx/query-5294237a0bb6b23aed6915f430ac595c6f0d6f215725132fb7ef33bb1847831d.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_integrations (workspace_id, service_name, oauth_data, created_by)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (workspace_id, service_name) DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "Jsonb", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "5294237a0bb6b23aed6915f430ac595c6f0d6f215725132fb7ef33bb1847831d" +} diff --git a/backend/.sqlx/query-56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c.json b/backend/.sqlx/query-56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c.json new file mode 100644 index 0000000000..17a9650d3e --- /dev/null +++ b/backend/.sqlx/query-56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value AS \"value: sqlx::types::Json\"\n FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value: sqlx::types::Json", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c" +} diff --git a/backend/.sqlx/query-59e359ec5307da46b7fb75d0a2ada7abd1836ec53fdc8086aa160735843f62b9.json b/backend/.sqlx/query-59e359ec5307da46b7fb75d0a2ada7abd1836ec53fdc8086aa160735843f62b9.json new file mode 100644 index 0000000000..802c83dd7f --- /dev/null +++ b/backend/.sqlx/query-59e359ec5307da46b7fb75d0a2ada7abd1836ec53fdc8086aa160735843f62b9.json @@ -0,0 +1,36 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM native_trigger\n WHERE workspace_id = $1 AND service_name = $2 AND ($3::text[] IS NULL\n OR (external_id, script_path) IN (SELECT * FROM unnest($3::text[], $4::text[])))\n RETURNING webhook_token_hash", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "webhook_token_hash", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "59e359ec5307da46b7fb75d0a2ada7abd1836ec53fdc8086aa160735843f62b9" +} diff --git a/backend/.sqlx/query-5a219a2532517869578c4504ff3153c43903f929ae5d62fbba12610f89c36d55.json b/backend/.sqlx/query-5a219a2532517869578c4504ff3153c43903f929ae5d62fbba12610f89c36d55.json index 713ccb9dd3..36ddb8ab9f 100644 --- a/backend/.sqlx/query-5a219a2532517869578c4504ff3153c43903f929ae5d62fbba12610f89c36d55.json +++ b/backend/.sqlx/query-5a219a2532517869578c4504ff3153c43903f929ae5d62fbba12610f89c36d55.json @@ -15,7 +15,7 @@ ] }, "nullable": [ - null + true ] }, "hash": "5a219a2532517869578c4504ff3153c43903f929ae5d62fbba12610f89c36d55" diff --git a/backend/.sqlx/query-5af4e97b30d968e2b55f9560c6bb1c3f543964d2c05d2f44f0a7716f890a3fce.json b/backend/.sqlx/query-5af4e97b30d968e2b55f9560c6bb1c3f543964d2c05d2f44f0a7716f890a3fce.json new file mode 100644 index 0000000000..113d1d6ce0 --- /dev/null +++ b/backend/.sqlx/query-5af4e97b30d968e2b55f9560c6bb1c3f543964d2c05d2f44f0a7716f890a3fce.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT\n (SELECT created_by FROM resource WHERE workspace_id = $1 AND path = $2) AS \"owner?\",\n EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2)\n OR EXISTS(SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2) AS \"taken!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "owner?", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "taken!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "5af4e97b30d968e2b55f9560c6bb1c3f543964d2c05d2f44f0a7716f890a3fce" +} diff --git a/backend/.sqlx/query-1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4.json b/backend/.sqlx/query-5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f.json similarity index 61% rename from backend/.sqlx/query-1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4.json rename to backend/.sqlx/query-5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f.json index 0ed678d485..386435e806 100644 --- a/backend/.sqlx/query-1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4.json +++ b/backend/.sqlx/query-5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", + "query": "SELECT value::text AS \"value!\", is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -26,10 +26,10 @@ ] }, "nullable": [ - false, + null, false, false ] }, - "hash": "1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4" + "hash": "5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f" } diff --git a/backend/.sqlx/query-61c4b826e90badc1307eadfe0c117efc6c8c87ba5542bce9c5f85b1da07e9a4b.json b/backend/.sqlx/query-61c4b826e90badc1307eadfe0c117efc6c8c87ba5542bce9c5f85b1da07e9a4b.json new file mode 100644 index 0000000000..17347df159 --- /dev/null +++ b/backend/.sqlx/query-61c4b826e90badc1307eadfe0c117efc6c8c87ba5542bce9c5f85b1da07e9a4b.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE account SET\n refresh_token = COALESCE($1, refresh_token),\n expires_at = now() + interval '1 hour',\n refresh_error = NULL\n WHERE workspace_id = $2 AND id = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "61c4b826e90badc1307eadfe0c117efc6c8c87ba5542bce9c5f85b1da07e9a4b" +} diff --git a/backend/.sqlx/query-649ef6b8facee43bb9ba5e6413099322f13a7db686176c4a717651c1671b1bae.json b/backend/.sqlx/query-649ef6b8facee43bb9ba5e6413099322f13a7db686176c4a717651c1671b1bae.json new file mode 100644 index 0000000000..7113138dd7 --- /dev/null +++ b/backend/.sqlx/query-649ef6b8facee43bb9ba5e6413099322f13a7db686176c4a717651c1671b1bae.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_integrations SET resource_path = NULL\n WHERE workspace_id = $1 AND service_name = $2 AND resource_path = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "Text" + ] + }, + "nullable": [] + }, + "hash": "649ef6b8facee43bb9ba5e6413099322f13a7db686176c4a717651c1671b1bae" +} diff --git a/backend/.sqlx/query-653685b39d93008762818d0518b953632040122a9af98332d3fd1d12244b1b80.json b/backend/.sqlx/query-653685b39d93008762818d0518b953632040122a9af98332d3fd1d12244b1b80.json index e3ef8a7f0a..82604817a0 100644 --- a/backend/.sqlx/query-653685b39d93008762818d0518b953632040122a9af98332d3fd1d12244b1b80.json +++ b/backend/.sqlx/query-653685b39d93008762818d0518b953632040122a9af98332d3fd1d12244b1b80.json @@ -17,7 +17,8 @@ "script", "flow", "raw_app", - "asset" + "asset", + "agent" ] } } diff --git a/backend/.sqlx/query-65acc5b9322f03266079ea6051535168e2cd0e627e3bbff413e38f8a3c616aa0.json b/backend/.sqlx/query-65acc5b9322f03266079ea6051535168e2cd0e627e3bbff413e38f8a3c616aa0.json new file mode 100644 index 0000000000..213fb4a5d6 --- /dev/null +++ b/backend/.sqlx/query-65acc5b9322f03266079ea6051535168e2cd0e627e3bbff413e38f8a3c616aa0.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM workspace_settings WHERE ($1::text IS NULL OR workspace_id = $1) AND (\n auto_invite->>'role' = $2\n OR EXISTS (SELECT 1 FROM jsonb_each_text(\n CASE WHEN jsonb_typeof(auto_invite->'instance_groups_roles') = 'object'\n THEN auto_invite->'instance_groups_roles' ELSE '{}'::jsonb END) g\n WHERE g.value = $2))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "65acc5b9322f03266079ea6051535168e2cd0e627e3bbff413e38f8a3c616aa0" +} diff --git a/backend/.sqlx/query-68d95ce32653dece237bbf21459b571b8b67d26ffb60dd21e558dfa10612a0ed.json b/backend/.sqlx/query-68d95ce32653dece237bbf21459b571b8b67d26ffb60dd21e558dfa10612a0ed.json new file mode 100644 index 0000000000..6c40f884ef --- /dev/null +++ b/backend/.sqlx/query-68d95ce32653dece237bbf21459b571b8b67d26ffb60dd21e558dfa10612a0ed.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT slack_oauth_client_id IS NOT NULL AS \"own_app!\",\n slack_signing_secret IS NOT NULL AS \"own_secret!\"\n FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "own_app!", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "own_secret!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "68d95ce32653dece237bbf21459b571b8b67d26ffb60dd21e558dfa10612a0ed" +} diff --git a/backend/.sqlx/query-0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13.json b/backend/.sqlx/query-698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16.json similarity index 57% rename from backend/.sqlx/query-0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13.json rename to backend/.sqlx/query-698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16.json index 5c33539878..17e8d20bb5 100644 --- a/backend/.sqlx/query-0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13.json +++ b/backend/.sqlx/query-698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret FROM variable WHERE path = $1", + "query": "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -20,9 +20,9 @@ ] }, "nullable": [ - false, + null, false ] }, - "hash": "0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13" + "hash": "698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16" } diff --git a/backend/.sqlx/query-7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf.json b/backend/.sqlx/query-6be4bf59c404d2f557d1106c48c320bb3eff65255a44bd66799ae14288312ba4.json similarity index 59% rename from backend/.sqlx/query-7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf.json rename to backend/.sqlx/query-6be4bf59c404d2f557d1106c48c320bb3eff65255a44bd66799ae14288312ba4.json index b2101cc0d4..0a39db6822 100644 --- a/backend/.sqlx/query-7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf.json +++ b/backend/.sqlx/query-6be4bf59c404d2f557d1106c48c320bb3eff65255a44bd66799ae14288312ba4.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT EXISTS(SELECT 1 FROM variable WHERE account = $1 AND workspace_id = $2)", + "query": "SELECT EXISTS(SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2)", "describe": { "columns": [ { @@ -11,7 +11,7 @@ ], "parameters": { "Left": [ - "Int4", + "Text", "Text" ] }, @@ -19,5 +19,5 @@ null ] }, - "hash": "7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf" + "hash": "6be4bf59c404d2f557d1106c48c320bb3eff65255a44bd66799ae14288312ba4" } diff --git a/backend/.sqlx/query-6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1.json b/backend/.sqlx/query-6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1.json new file mode 100644 index 0000000000..8cfd36abd6 --- /dev/null +++ b/backend/.sqlx/query-6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_diff\n (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes)\n VALUES\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/same', 'variable', 1, 1, NULL),\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL)\n ON CONFLICT (source_workspace_id, fork_workspace_id, path, kind)\n DO UPDATE SET ahead = 1, behind = 1, has_changes = NULL", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1" +} diff --git a/backend/.sqlx/query-6e83478011a8f65bf294ad7886139369e386f6a552c6626be48ecaa0e5ab78a7.json b/backend/.sqlx/query-6e83478011a8f65bf294ad7886139369e386f6a552c6626be48ecaa0e5ab78a7.json deleted file mode 100644 index b765a5eb28..0000000000 --- a/backend/.sqlx/query-6e83478011a8f65bf294ad7886139369e386f6a552c6626be48ecaa0e5ab78a7.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE account SET\n refresh_token = $1,\n expires_at = now() + interval '1 hour',\n refresh_error = NULL\n WHERE workspace_id = $2 AND client = $3 AND is_workspace_integration = true", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text", - "Text" - ] - }, - "nullable": [] - }, - "hash": "6e83478011a8f65bf294ad7886139369e386f6a552c6626be48ecaa0e5ab78a7" -} diff --git a/backend/.sqlx/query-706872f05247a7d26fcd1b40b129f2defef86f8139dc4e38ae3bf63db039c48b.json b/backend/.sqlx/query-706872f05247a7d26fcd1b40b129f2defef86f8139dc4e38ae3bf63db039c48b.json new file mode 100644 index 0000000000..aad2908ef5 --- /dev/null +++ b/backend/.sqlx/query-706872f05247a7d26fcd1b40b129f2defef86f8139dc4e38ae3bf63db039c48b.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT user_email FROM mcp_oauth_server_code WHERE code = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "user_email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "706872f05247a7d26fcd1b40b129f2defef86f8139dc4e38ae3bf63db039c48b" +} diff --git a/backend/.sqlx/query-729852e65e4cf22c474850d46a2065a203ca86b40e8388db963c183ac8fb4fd6.json b/backend/.sqlx/query-729852e65e4cf22c474850d46a2065a203ca86b40e8388db963c183ac8fb4fd6.json new file mode 100644 index 0000000000..6d4c707f08 --- /dev/null +++ b/backend/.sqlx/query-729852e65e4cf22c474850d46a2065a203ca86b40e8388db963c183ac8fb4fd6.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM workspace_invite WHERE\n workspace_id = $1 AND email = $2 AND is_admin = $3\n AND ($5::text IS NOT NULL OR operator = $4)\n AND ($5::text IS NULL OR $5 = COALESCE(workspace_role, CASE WHEN operator THEN 'operator' ELSE 'developer' END))", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Bool", + "Bool", + "Text" + ] + }, + "nullable": [] + }, + "hash": "729852e65e4cf22c474850d46a2065a203ca86b40e8388db963c183ac8fb4fd6" +} diff --git a/backend/.sqlx/query-2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e.json b/backend/.sqlx/query-72bc3795182333d203b4731defb400a6fa59e8a88bebd6e63437e9cb4c491333.json similarity index 53% rename from backend/.sqlx/query-2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e.json rename to backend/.sqlx/query-72bc3795182333d203b4731defb400a6fa59e8a88bebd6e63437e9cb4c491333.json index 2939d5ac88..9450642e5f 100644 --- a/backend/.sqlx/query-2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e.json +++ b/backend/.sqlx/query-72bc3795182333d203b4731defb400a6fa59e8a88bebd6e63437e9cb4c491333.json @@ -1,21 +1,21 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret, description\n FROM variable\n WHERE workspace_id = $1 AND path = $2", + "query": "DELETE FROM workspace_invite WHERE workspace_id = $1 AND email = $2 RETURNING is_admin, operator, workspace_role", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "is_admin", + "type_info": "Bool" }, { "ordinal": 1, - "name": "is_secret", + "name": "operator", "type_info": "Bool" }, { "ordinal": 2, - "name": "description", + "name": "workspace_role", "type_info": "Varchar" } ], @@ -28,8 +28,8 @@ "nullable": [ false, false, - false + true ] }, - "hash": "2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e" + "hash": "72bc3795182333d203b4731defb400a6fa59e8a88bebd6e63437e9cb4c491333" } diff --git a/backend/.sqlx/query-7341d832643627cdc33a6eefbca5844a0fbb10fb79e25a604eeb0d83d2122d96.json b/backend/.sqlx/query-7341d832643627cdc33a6eefbca5844a0fbb10fb79e25a604eeb0d83d2122d96.json new file mode 100644 index 0000000000..a5181dd0a2 --- /dev/null +++ b/backend/.sqlx/query-7341d832643627cdc33a6eefbca5844a0fbb10fb79e25a604eeb0d83d2122d96.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT username, is_admin, operator, workspace_role FROM usr WHERE\n email = $1 AND workspace_id = $2 AND disabled = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "workspace_role", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + true + ] + }, + "hash": "7341d832643627cdc33a6eefbca5844a0fbb10fb79e25a604eeb0d83d2122d96" +} diff --git a/backend/.sqlx/query-74190dc8f1049b61adfcefe19df069204bfc974a55da927658947f3e335da3f5.json b/backend/.sqlx/query-74190dc8f1049b61adfcefe19df069204bfc974a55da927658947f3e335da3f5.json new file mode 100644 index 0000000000..8a68c6364e --- /dev/null +++ b/backend/.sqlx/query-74190dc8f1049b61adfcefe19df069204bfc974a55da927658947f3e335da3f5.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM workspace_invite t WHERE ($1::text IS NOT NULL AND t.workspace_id = $1\n OR $1::text IS NULL AND NOT EXISTS (SELECT 1 FROM workspace_settings ws\n WHERE ws.workspace_id = t.workspace_id AND ws.role_overrides ? $2)) AND\n COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END) = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "74190dc8f1049b61adfcefe19df069204bfc974a55da927658947f3e335da3f5" +} diff --git a/backend/.sqlx/query-74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593.json b/backend/.sqlx/query-74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593.json new file mode 100644 index 0000000000..5bf83d1b33 --- /dev/null +++ b/backend/.sqlx/query-74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593.json @@ -0,0 +1,214 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT\n workspace_id,\n slack_team_id,\n teams_team_id,\n teams_team_name,\n teams_team_guid,\n slack_name,\n slack_command_script,\n teams_command_script,\n slack_email,\n slack_oauth_client_id,\n slack_oauth_client_secret,\n customer_id,\n plan,\n webhook,\n ai_config,\n dbt_warehouses,\n large_file_storage,\n datatable,\n ducklake,\n git_sync,\n deploy_ui,\n default_app,\n default_scripts,\n mute_critical_alerts,\n color,\n operator_settings,\n git_app_installations,\n auto_invite,\n error_handler,\n success_handler,\n variable_expiration_handler,\n public_app_execution_limit_per_minute,\n error_handler_fallback_to_instance_alerts\n FROM\n workspace_settings\n WHERE\n workspace_id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "slack_team_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "teams_team_id", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "teams_team_name", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "teams_team_guid", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "slack_name", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "slack_command_script", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "teams_command_script", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "slack_email", + "type_info": "Varchar" + }, + { + "ordinal": 9, + "name": "slack_oauth_client_id", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "slack_oauth_client_secret", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "customer_id", + "type_info": "Varchar" + }, + { + "ordinal": 12, + "name": "plan", + "type_info": "Varchar" + }, + { + "ordinal": 13, + "name": "webhook", + "type_info": "Text" + }, + { + "ordinal": 14, + "name": "ai_config", + "type_info": "Jsonb" + }, + { + "ordinal": 15, + "name": "dbt_warehouses", + "type_info": "Jsonb" + }, + { + "ordinal": 16, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 17, + "name": "datatable", + "type_info": "Jsonb" + }, + { + "ordinal": 18, + "name": "ducklake", + "type_info": "Jsonb" + }, + { + "ordinal": 19, + "name": "git_sync", + "type_info": "Jsonb" + }, + { + "ordinal": 20, + "name": "deploy_ui", + "type_info": "Jsonb" + }, + { + "ordinal": 21, + "name": "default_app", + "type_info": "Varchar" + }, + { + "ordinal": 22, + "name": "default_scripts", + "type_info": "Jsonb" + }, + { + "ordinal": 23, + "name": "mute_critical_alerts", + "type_info": "Bool" + }, + { + "ordinal": 24, + "name": "color", + "type_info": "Varchar" + }, + { + "ordinal": 25, + "name": "operator_settings", + "type_info": "Jsonb" + }, + { + "ordinal": 26, + "name": "git_app_installations", + "type_info": "Jsonb" + }, + { + "ordinal": 27, + "name": "auto_invite", + "type_info": "Jsonb" + }, + { + "ordinal": 28, + "name": "error_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 29, + "name": "success_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 30, + "name": "variable_expiration_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 31, + "name": "public_app_execution_limit_per_minute", + "type_info": "Int4" + }, + { + "ordinal": 32, + "name": "error_handler_fallback_to_instance_alerts", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false + ] + }, + "hash": "74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593" +} diff --git a/backend/.sqlx/query-74e6d61f31897d8102fe75bbe44781a71aeba34da94b9b1aa9893c2837d5cb05.json b/backend/.sqlx/query-74e6d61f31897d8102fe75bbe44781a71aeba34da94b9b1aa9893c2837d5cb05.json new file mode 100644 index 0000000000..a173674b29 --- /dev/null +++ b/backend/.sqlx/query-74e6d61f31897d8102fe75bbe44781a71aeba34da94b9b1aa9893c2837d5cb05.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT slack_oauth_client_id IS NOT NULL AS \"own_app!\", slack_signing_secret\n FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "own_app!", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "slack_signing_secret", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + true + ] + }, + "hash": "74e6d61f31897d8102fe75bbe44781a71aeba34da94b9b1aa9893c2837d5cb05" +} diff --git a/backend/.sqlx/query-74f9031593b6c55819508fa32310e465c202fa3784fd179bcd8963217327a03b.json b/backend/.sqlx/query-74f9031593b6c55819508fa32310e465c202fa3784fd179bcd8963217327a03b.json new file mode 100644 index 0000000000..7440566057 --- /dev/null +++ b/backend/.sqlx/query-74f9031593b6c55819508fa32310e465c202fa3784fd179bcd8963217327a03b.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM native_trigger\n WHERE workspace_id = $1 AND service_name = $2 AND connection_path = $3)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "74f9031593b6c55819508fa32310e465c202fa3784fd179bcd8963217327a03b" +} diff --git a/backend/.sqlx/query-77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json b/backend/.sqlx/query-77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json deleted file mode 100644 index f504d7a809..0000000000 --- a/backend/.sqlx/query-77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url FROM workspace_settings WHERE workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1" -} diff --git a/backend/.sqlx/query-993e514229a1d508a44ef07b4399f9697cdefaa1f45ca665f72bc6fcf2797c7e.json b/backend/.sqlx/query-78954c7a6d38ae9d094f77bb255ae235c9b3083b4c179f819c927342bc58651f.json similarity index 64% rename from backend/.sqlx/query-993e514229a1d508a44ef07b4399f9697cdefaa1f45ca665f72bc6fcf2797c7e.json rename to backend/.sqlx/query-78954c7a6d38ae9d094f77bb255ae235c9b3083b4c179f819c927342bc58651f.json index 25a4d5b723..a8e33b105a 100644 --- a/backend/.sqlx/query-993e514229a1d508a44ef07b4399f9697cdefaa1f45ca665f72bc6fcf2797c7e.json +++ b/backend/.sqlx/query-78954c7a6d38ae9d094f77bb255ae235c9b3083b4c179f819c927342bc58651f.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT resource_path FROM workspace_integrations WHERE workspace_id = $1 AND service_name = $2", + "query": "SELECT EXISTS(SELECT 1 FROM native_trigger WHERE workspace_id = $1 AND service_name = $2)", "describe": { "columns": [ { "ordinal": 0, - "name": "resource_path", - "type_info": "Text" + "name": "exists", + "type_info": "Bool" } ], "parameters": { @@ -27,8 +27,8 @@ ] }, "nullable": [ - true + null ] }, - "hash": "993e514229a1d508a44ef07b4399f9697cdefaa1f45ca665f72bc6fcf2797c7e" + "hash": "78954c7a6d38ae9d094f77bb255ae235c9b3083b4c179f819c927342bc58651f" } diff --git a/backend/.sqlx/query-79ac4fcf66d90ad793ecdc0906203654e796f71a876ea6d6ebf08c4f65b2156e.json b/backend/.sqlx/query-79ac4fcf66d90ad793ecdc0906203654e796f71a876ea6d6ebf08c4f65b2156e.json new file mode 100644 index 0000000000..158f49102d --- /dev/null +++ b/backend/.sqlx/query-79ac4fcf66d90ad793ecdc0906203654e796f71a876ea6d6ebf08c4f65b2156e.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.path, r.created_by AS \"owner?\", false AS \"workspace!\"\n FROM variable v\n JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n LEFT JOIN resource r ON r.workspace_id = v.workspace_id AND r.path = v.path\n WHERE v.workspace_id = $1 AND a.client = $2 AND a.is_workspace_integration = true\n ORDER BY v.path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "owner?", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "workspace!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + true, + null + ] + }, + "hash": "79ac4fcf66d90ad793ecdc0906203654e796f71a876ea6d6ebf08c4f65b2156e" +} diff --git a/backend/.sqlx/query-7b1d29170c9c4ad4e3a15c4e8acbeb6769dc6fc97269beee607a5625a495a121.json b/backend/.sqlx/query-7b1d29170c9c4ad4e3a15c4e8acbeb6769dc6fc97269beee607a5625a495a121.json deleted file mode 100644 index 97ab6a03d5..0000000000 --- a/backend/.sqlx/query-7b1d29170c9c4ad4e3a15c4e8acbeb6769dc6fc97269beee607a5625a495a121.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE account SET\n expires_at = now() + interval '1 hour',\n refresh_error = NULL\n WHERE workspace_id = $1 AND client = $2 AND is_workspace_integration = true", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [] - }, - "hash": "7b1d29170c9c4ad4e3a15c4e8acbeb6769dc6fc97269beee607a5625a495a121" -} diff --git a/backend/.sqlx/query-d537182f8c8931427f2cf175bd850ce2581a33c8678212de99edb6f823f38994.json b/backend/.sqlx/query-7c481a2cf03e7f80e7170a5165b5225e4e0828d82f5c6ddca9b059f4a876d137.json similarity index 79% rename from backend/.sqlx/query-d537182f8c8931427f2cf175bd850ce2581a33c8678212de99edb6f823f38994.json rename to backend/.sqlx/query-7c481a2cf03e7f80e7170a5165b5225e4e0828d82f5c6ddca9b059f4a876d137.json index 8c2a7716fd..e637b8c87d 100644 --- a/backend/.sqlx/query-d537182f8c8931427f2cf175bd850ce2581a33c8678212de99edb6f823f38994.json +++ b/backend/.sqlx/query-7c481a2cf03e7f80e7170a5165b5225e4e0828d82f5c6ddca9b059f4a876d137.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT (status = 'success' OR EXISTS (\n SELECT 1 FROM native_retry_attempt nra\n JOIN v2_job jc ON jc.id = nra.job_id\n JOIN v2_job_completed cc ON cc.id = nra.job_id\n WHERE jc.parent_job = j.id AND cc.status = 'success'\n )) AS \"success!\"\n FROM v2_job j JOIN v2_job_completed USING (id)\n WHERE j.workspace_id = $1 AND trigger_kind = 'schedule' AND trigger = $2\n AND parent_job IS NULL\n AND runnable_path = $3\n AND j.id != $4\n ORDER BY created_at DESC\n LIMIT $5", + "query": "SELECT (status = 'success' OR EXISTS (\n SELECT 1 FROM native_retry_attempt nra\n JOIN v2_job jc ON jc.id = nra.job_id\n JOIN v2_job_completed cc ON cc.id = nra.job_id\n WHERE jc.parent_job = j.id AND cc.status = 'success'\n )) AS \"success!\"\n FROM v2_job j JOIN v2_job_completed USING (id)\n WHERE j.workspace_id = $1 AND trigger_kind = 'schedule' AND trigger = $2\n AND parent_job IS NULL\n AND runnable_path = $3\n AND j.created_at < (SELECT created_at FROM v2_job WHERE id = $4)\n ORDER BY created_at DESC\n LIMIT $5", "describe": { "columns": [ { @@ -22,5 +22,5 @@ null ] }, - "hash": "d537182f8c8931427f2cf175bd850ce2581a33c8678212de99edb6f823f38994" + "hash": "7c481a2cf03e7f80e7170a5165b5225e4e0828d82f5c6ddca9b059f4a876d137" } diff --git a/backend/.sqlx/query-7e71cb88613a78b1b6bd0327970e7c732775949f92e1f099ff997d385b025f55.json b/backend/.sqlx/query-7e71cb88613a78b1b6bd0327970e7c732775949f92e1f099ff997d385b025f55.json new file mode 100644 index 0000000000..787342ca47 --- /dev/null +++ b/backend/.sqlx/query-7e71cb88613a78b1b6bd0327970e7c732775949f92e1f099ff997d385b025f55.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT username, is_admin, operator, workspace_role FROM usr\n WHERE workspace_id = $1 AND email = $2 AND disabled = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "workspace_role", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + true + ] + }, + "hash": "7e71cb88613a78b1b6bd0327970e7c732775949f92e1f099ff997d385b025f55" +} diff --git a/backend/.sqlx/query-80977e90833b63da4cdde111db80d78c8e577dbce51f8571a9ffe3e8e1e652a1.json b/backend/.sqlx/query-80977e90833b63da4cdde111db80d78c8e577dbce51f8571a9ffe3e8e1e652a1.json new file mode 100644 index 0000000000..24144fdbdb --- /dev/null +++ b/backend/.sqlx/query-80977e90833b63da4cdde111db80d78c8e577dbce51f8571a9ffe3e8e1e652a1.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings\n SET operator_settings = COALESCE(operator_settings, '{}'::jsonb) || $1\n WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Text" + ] + }, + "nullable": [] + }, + "hash": "80977e90833b63da4cdde111db80d78c8e577dbce51f8571a9ffe3e8e1e652a1" +} diff --git a/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json b/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json new file mode 100644 index 0000000000..cb33edacdf --- /dev/null +++ b/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until)\n SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until\n FROM variable\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8" +} diff --git a/backend/.sqlx/query-80d62bd0f372a322d9c2a548a66669551ed6860b0839dd019967569e2325b0bc.json b/backend/.sqlx/query-80d62bd0f372a322d9c2a548a66669551ed6860b0839dd019967569e2325b0bc.json new file mode 100644 index 0000000000..5b59198fd9 --- /dev/null +++ b/backend/.sqlx/query-80d62bd0f372a322d9c2a548a66669551ed6860b0839dd019967569e2325b0bc.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_invite\n (workspace_id, email, is_admin, operator, workspace_role)\n VALUES ($1, $2, $3, $4, $5) ON CONFLICT (workspace_id, email)\n DO UPDATE SET is_admin = EXCLUDED.is_admin, operator = EXCLUDED.operator,\n workspace_role = EXCLUDED.workspace_role", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Bool", + "Bool", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "80d62bd0f372a322d9c2a548a66669551ed6860b0839dd019967569e2325b0bc" +} diff --git a/backend/.sqlx/query-884dd7d41713a964a0fbb854d6e54cff4538e230b3cd72dd2e840a08b2a178d9.json b/backend/.sqlx/query-884dd7d41713a964a0fbb854d6e54cff4538e230b3cd72dd2e840a08b2a178d9.json new file mode 100644 index 0000000000..1823f66c53 --- /dev/null +++ b/backend/.sqlx/query-884dd7d41713a964a0fbb854d6e54cff4538e230b3cd72dd2e840a08b2a178d9.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT is_admin, operator, workspace_role, email FROM usr where username = $1 AND workspace_id = $2 AND disabled = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "workspace_role", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + true, + false + ] + }, + "hash": "884dd7d41713a964a0fbb854d6e54cff4538e230b3cd72dd2e840a08b2a178d9" +} diff --git a/backend/.sqlx/query-8a0287e5b8f37c86d989a39516188484d036e2106acab33f6c459d9b9c9ba3be.json b/backend/.sqlx/query-8a0287e5b8f37c86d989a39516188484d036e2106acab33f6c459d9b9c9ba3be.json new file mode 100644 index 0000000000..c90368a92f --- /dev/null +++ b/backend/.sqlx/query-8a0287e5b8f37c86d989a39516188484d036e2106acab33f6c459d9b9c9ba3be.json @@ -0,0 +1,19 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE account SET refresh_token = COALESCE($1, refresh_token),\n expires_at = CASE WHEN $2 THEN $3 ELSE expires_at END,\n refresh_error = CASE WHEN $2 THEN NULL ELSE refresh_error END\n WHERE workspace_id = $4 AND id = $5 AND refresh_token = $6", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Bool", + "Timestamptz", + "Text", + "Int4", + "Text" + ] + }, + "nullable": [] + }, + "hash": "8a0287e5b8f37c86d989a39516188484d036e2106acab33f6c459d9b9c9ba3be" +} diff --git a/backend/.sqlx/query-b731208c3e98f8fb15bf0c72e2ab1d4c61566c3cedf31596efe084ef7dc9985a.json b/backend/.sqlx/query-8b8b605d656d88e1fe77f936500cec9cb3388b7232a96bfc287f751d1e0092da.json similarity index 63% rename from backend/.sqlx/query-b731208c3e98f8fb15bf0c72e2ab1d4c61566c3cedf31596efe084ef7dc9985a.json rename to backend/.sqlx/query-8b8b605d656d88e1fe77f936500cec9cb3388b7232a96bfc287f751d1e0092da.json index 04b960b81a..0481fb751c 100644 --- a/backend/.sqlx/query-b731208c3e98f8fb15bf0c72e2ab1d4c61566c3cedf31596efe084ef7dc9985a.json +++ b/backend/.sqlx/query-8b8b605d656d88e1fe77f936500cec9cb3388b7232a96bfc287f751d1e0092da.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT workspace_id, slack_command_script, slack_email FROM workspace_settings WHERE slack_team_id = $1 AND slack_command_script IS NOT NULL", + "query": "SELECT workspace_id, slack_command_script, slack_email FROM workspace_settings\n WHERE slack_team_id = $1 AND slack_command_script IS NOT NULL\n AND workspace_id = ANY($2)\n ORDER BY workspace_id = ANY($3) DESC LIMIT 1", "describe": { "columns": [ { @@ -21,7 +21,9 @@ ], "parameters": { "Left": [ - "Text" + "Text", + "TextArray", + "TextArray" ] }, "nullable": [ @@ -30,5 +32,5 @@ false ] }, - "hash": "b731208c3e98f8fb15bf0c72e2ab1d4c61566c3cedf31596efe084ef7dc9985a" + "hash": "8b8b605d656d88e1fe77f936500cec9cb3388b7232a96bfc287f751d1e0092da" } diff --git a/backend/.sqlx/query-8c2fcd9385931cfba49bcbe67a14cbfbb042a5930d406ec60939791a1d1d723b.json b/backend/.sqlx/query-8c2fcd9385931cfba49bcbe67a14cbfbb042a5930d406ec60939791a1d1d723b.json new file mode 100644 index 0000000000..bbf54e23b8 --- /dev/null +++ b/backend/.sqlx/query-8c2fcd9385931cfba49bcbe67a14cbfbb042a5930d406ec60939791a1d1d723b.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT path FROM variable WHERE workspace_id = $1 AND account = $2 AND is_secret", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [ + false + ] + }, + "hash": "8c2fcd9385931cfba49bcbe67a14cbfbb042a5930d406ec60939791a1d1d723b" +} diff --git a/backend/.sqlx/query-64dce306efc0d9989542dba5bf003dc94b9337a8d3b69805308258d1fa145e63.json b/backend/.sqlx/query-8ec380ed48a8366e8869c6d1aa06ba774a6ded50ab047d0b0302c7430cee5b70.json similarity index 61% rename from backend/.sqlx/query-64dce306efc0d9989542dba5bf003dc94b9337a8d3b69805308258d1fa145e63.json rename to backend/.sqlx/query-8ec380ed48a8366e8869c6d1aa06ba774a6ded50ab047d0b0302c7430cee5b70.json index d234750140..9416cd684c 100644 --- a/backend/.sqlx/query-64dce306efc0d9989542dba5bf003dc94b9337a8d3b69805308258d1fa145e63.json +++ b/backend/.sqlx/query-8ec380ed48a8366e8869c6d1aa06ba774a6ded50ab047d0b0302c7430cee5b70.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n INSERT INTO native_trigger (\n external_id,\n workspace_id,\n service_name,\n script_path,\n is_flow,\n webhook_token_hash,\n service_config,\n summary,\n enabled\n ) VALUES (\n $1, $2, $3, $4, $5, $6, $7, $8, $9\n )\n ON CONFLICT (external_id, workspace_id, service_name)\n DO UPDATE SET script_path = $4, is_flow = $5, webhook_token_hash = $6, service_config = $7, summary = $8, error = NULL, updated_at = NOW()\n ", + "query": "\n INSERT INTO native_trigger (\n external_id,\n workspace_id,\n service_name,\n script_path,\n is_flow,\n webhook_token_hash,\n service_config,\n summary,\n enabled,\n connection_path\n ) VALUES (\n $1, $2, $3, $4, $5, $6, $7, $8, $9, $10\n )\n ON CONFLICT (external_id, workspace_id, service_name)\n DO UPDATE SET script_path = $4, is_flow = $5, webhook_token_hash = $6, service_config = $7, summary = $8, connection_path = $10, error = NULL, updated_at = NOW()\n ", "describe": { "columns": [], "parameters": { @@ -24,10 +24,11 @@ "Varchar", "Jsonb", "Varchar", - "Bool" + "Bool", + "Varchar" ] }, "nullable": [] }, - "hash": "64dce306efc0d9989542dba5bf003dc94b9337a8d3b69805308258d1fa145e63" + "hash": "8ec380ed48a8366e8869c6d1aa06ba774a6ded50ab047d0b0302c7430cee5b70" } diff --git a/backend/.sqlx/query-907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782.json b/backend/.sqlx/query-907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782.json new file mode 100644 index 0000000000..97f3bd7567 --- /dev/null +++ b/backend/.sqlx/query-907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM slack_agent_channel WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782" +} diff --git a/backend/.sqlx/query-5b0847d2b95a128a5b648dd4847af44ed0992ced76286a08a33134140a454391.json b/backend/.sqlx/query-92710770a07d9cc622fd36bde7114fe6f508293f3334e4e17e7d396b52012a7d.json similarity index 84% rename from backend/.sqlx/query-5b0847d2b95a128a5b648dd4847af44ed0992ced76286a08a33134140a454391.json rename to backend/.sqlx/query-92710770a07d9cc622fd36bde7114fe6f508293f3334e4e17e7d396b52012a7d.json index 28c09ca528..514793704f 100644 --- a/backend/.sqlx/query-5b0847d2b95a128a5b648dd4847af44ed0992ced76286a08a33134140a454391.json +++ b/backend/.sqlx/query-92710770a07d9cc622fd36bde7114fe6f508293f3334e4e17e7d396b52012a7d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT (status = 'success' OR EXISTS (\n SELECT 1 FROM native_retry_attempt nra\n JOIN v2_job jc ON jc.id = nra.job_id\n JOIN v2_job_completed cc ON cc.id = nra.job_id\n WHERE jc.parent_job = j.id AND cc.status = 'success'\n )) AS \"success!\",\n result AS \"result: Json>\",\n started_at AS \"started_at!\"FROM v2_job j JOIN v2_job_completed USING (id)\n WHERE j.workspace_id = $1 AND trigger_kind = 'schedule' AND trigger = $2\n AND parent_job IS NULL\n AND runnable_path = $3\n AND j.id != $4\n ORDER BY created_at DESC\n LIMIT $5", + "query": "SELECT (status = 'success' OR EXISTS (\n SELECT 1 FROM native_retry_attempt nra\n JOIN v2_job jc ON jc.id = nra.job_id\n JOIN v2_job_completed cc ON cc.id = nra.job_id\n WHERE jc.parent_job = j.id AND cc.status = 'success'\n )) AS \"success!\",\n result AS \"result: Json>\",\n started_at AS \"started_at!\"FROM v2_job j JOIN v2_job_completed USING (id)\n WHERE j.workspace_id = $1 AND trigger_kind = 'schedule' AND trigger = $2\n AND parent_job IS NULL\n AND runnable_path = $3\n AND j.created_at < (SELECT created_at FROM v2_job WHERE id = $4)\n ORDER BY created_at DESC\n LIMIT $5", "describe": { "columns": [ { @@ -34,5 +34,5 @@ true ] }, - "hash": "5b0847d2b95a128a5b648dd4847af44ed0992ced76286a08a33134140a454391" + "hash": "92710770a07d9cc622fd36bde7114fe6f508293f3334e4e17e7d396b52012a7d" } diff --git a/backend/.sqlx/query-9784d19363fa14b9d7cc49e208967000a7bc8e56adddcd9304b05daf814e5246.json b/backend/.sqlx/query-9784d19363fa14b9d7cc49e208967000a7bc8e56adddcd9304b05daf814e5246.json new file mode 100644 index 0000000000..9ad7df84ba --- /dev/null +++ b/backend/.sqlx/query-9784d19363fa14b9d7cc49e208967000a7bc8e56adddcd9304b05daf814e5246.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM workspace_settings WHERE COALESCE(role_overrides ? $1, false)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "9784d19363fa14b9d7cc49e208967000a7bc8e56adddcd9304b05daf814e5246" +} diff --git a/backend/.sqlx/query-988c720384e4e2d70bfa11196f3a3514e0756722762fabe49e1d291ce5c09a19.json b/backend/.sqlx/query-988c720384e4e2d70bfa11196f3a3514e0756722762fabe49e1d291ce5c09a19.json new file mode 100644 index 0000000000..0ffc66a8b7 --- /dev/null +++ b/backend/.sqlx/query-988c720384e4e2d70bfa11196f3a3514e0756722762fabe49e1d291ce5c09a19.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE usr SET workspace_role = $1 WHERE workspace_id = $2 AND username = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "988c720384e4e2d70bfa11196f3a3514e0756722762fabe49e1d291ce5c09a19" +} diff --git a/backend/.sqlx/query-9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30.json b/backend/.sqlx/query-9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30.json new file mode 100644 index 0000000000..db0e11a62b --- /dev/null +++ b/backend/.sqlx/query-9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable SET expiration_dispatched_for = $3, expiration_notified_at = now()\n WHERE workspace_id = $1 AND path = $2 AND value_valid_until = $3\n AND expiration_dispatched_for IS NOT DISTINCT FROM $4\n AND expiration_notified_at IS NOT DISTINCT FROM $5\n RETURNING 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Timestamptz", + "Timestamptz", + "Timestamptz" + ] + }, + "nullable": [ + null + ] + }, + "hash": "9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30" +} diff --git a/backend/.sqlx/query-9aaee16823c7d3fc0954274ba71bc2eae7d950f759d146339c30df039cf10fd8.json b/backend/.sqlx/query-9aaee16823c7d3fc0954274ba71bc2eae7d950f759d146339c30df039cf10fd8.json new file mode 100644 index 0000000000..38bad3fcde --- /dev/null +++ b/backend/.sqlx/query-9aaee16823c7d3fc0954274ba71bc2eae7d950f759d146339c30df039cf10fd8.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT p.email FROM password p LEFT JOIN usr m ON m.workspace_id = $1 AND m.email = p.email WHERE p.super_admin AND NOT p.disabled AND (m.email IS NOT NULL AND NOT m.disabled OR m.email IS NULL AND NOT EXISTS (SELECT 1 FROM usr c WHERE c.workspace_id = $1 AND c.username = COALESCE(p.username, p.email))) ORDER BY m.email IS NULL, p.email LIMIT 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "9aaee16823c7d3fc0954274ba71bc2eae7d950f759d146339c30df039cf10fd8" +} diff --git a/backend/.sqlx/query-9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6.json b/backend/.sqlx/query-9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6.json new file mode 100644 index 0000000000..ab555a2efd --- /dev/null +++ b/backend/.sqlx/query-9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until)\n VALUES ('test-workspace', 'u/admin/expiring', 'v', false, 'same', '2027-01-01T00:00:00Z')", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6" +} diff --git a/backend/.sqlx/query-9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6.json b/backend/.sqlx/query-9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6.json new file mode 100644 index 0000000000..ecb5eb2c4b --- /dev/null +++ b/backend/.sqlx/query-9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_handler = NULL WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6" +} diff --git a/backend/.sqlx/query-c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f.json b/backend/.sqlx/query-9d7416a5458bb3d4a145cc1d2d35fa8e032a4ccdd23d7ed9a6c58d791b7bbd08.json similarity index 62% rename from backend/.sqlx/query-c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f.json rename to backend/.sqlx/query-9d7416a5458bb3d4a145cc1d2d35fa8e032a4ccdd23d7ed9a6c58d791b7bbd08.json index 37025d99d8..bb3d0d83b9 100644 --- a/backend/.sqlx/query-c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f.json +++ b/backend/.sqlx/query-9d7416a5458bb3d4a145cc1d2d35fa8e032a4ccdd23d7ed9a6c58d791b7bbd08.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT account FROM variable WHERE path = $1 AND workspace_id = $2", + "query": "DELETE FROM variable WHERE workspace_id = $1 AND path = $2 RETURNING account", "describe": { "columns": [ { @@ -19,5 +19,5 @@ true ] }, - "hash": "c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f" + "hash": "9d7416a5458bb3d4a145cc1d2d35fa8e032a4ccdd23d7ed9a6c58d791b7bbd08" } diff --git a/backend/.sqlx/query-9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894.json b/backend/.sqlx/query-9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894.json new file mode 100644 index 0000000000..6557494459 --- /dev/null +++ b/backend/.sqlx/query-9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894" +} diff --git a/backend/.sqlx/query-a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a.json b/backend/.sqlx/query-a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a.json new file mode 100644 index 0000000000..5ac876fa73 --- /dev/null +++ b/backend/.sqlx/query-a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value::text AS \"value!\", is_secret\n FROM variable\n WHERE path = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "is_secret", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null, + false + ] + }, + "hash": "a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a" +} diff --git a/backend/.sqlx/query-a32aea24f8cc6e0aed80dfa1f0928fab0f26ee5a0b9550ea4ab04e2857bebeda.json b/backend/.sqlx/query-a32aea24f8cc6e0aed80dfa1f0928fab0f26ee5a0b9550ea4ab04e2857bebeda.json new file mode 100644 index 0000000000..1e8970290f --- /dev/null +++ b/backend/.sqlx/query-a32aea24f8cc6e0aed80dfa1f0928fab0f26ee5a0b9550ea4ab04e2857bebeda.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET role_overrides = $1 WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Text" + ] + }, + "nullable": [] + }, + "hash": "a32aea24f8cc6e0aed80dfa1f0928fab0f26ee5a0b9550ea4ab04e2857bebeda" +} diff --git a/backend/.sqlx/query-a37bd72bb1a151e859b4a37a447887e613debd842e575cc740502144bb279bb3.json b/backend/.sqlx/query-a37bd72bb1a151e859b4a37a447887e613debd842e575cc740502144bb279bb3.json new file mode 100644 index 0000000000..5eb7d45dd4 --- /dev/null +++ b/backend/.sqlx/query-a37bd72bb1a151e859b4a37a447887e613debd842e575cc740502144bb279bb3.json @@ -0,0 +1,76 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT workspace_id, username, email, is_admin, created_at, operator, disabled,\n COALESCE(workspace_role, CASE WHEN operator THEN 'operator' ELSE 'developer' END) AS role,\n added_via, is_service_account\n FROM usr\n WHERE workspace_id = $1\n ORDER BY email\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "created_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 6, + "name": "disabled", + "type_info": "Bool" + }, + { + "ordinal": 7, + "name": "role", + "type_info": "Varchar" + }, + { + "ordinal": 8, + "name": "added_via", + "type_info": "Jsonb" + }, + { + "ordinal": 9, + "name": "is_service_account", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + null, + true, + false + ] + }, + "hash": "a37bd72bb1a151e859b4a37a447887e613debd842e575cc740502144bb279bb3" +} diff --git a/backend/.sqlx/query-a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515.json b/backend/.sqlx/query-a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515.json new file mode 100644 index 0000000000..828e5ba470 --- /dev/null +++ b/backend/.sqlx/query-a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value::text AS \"value!\" FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515" +} diff --git a/backend/.sqlx/query-acd87efeb1e92f6c5f04f8482fde597611be96a8f2c6a8ea884c39b11620be57.json b/backend/.sqlx/query-acd87efeb1e92f6c5f04f8482fde597611be96a8f2c6a8ea884c39b11620be57.json new file mode 100644 index 0000000000..f9ef3977e7 --- /dev/null +++ b/backend/.sqlx/query-acd87efeb1e92f6c5f04f8482fde597611be96a8f2c6a8ea884c39b11620be57.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id,\n (auto_invite->>'operator')::boolean as \"is_operator: bool\",\n auto_invite->>'role' as \"role: String\",\n (auto_invite->>'mode') = 'add' as \"is_auto_add: bool\"\n FROM workspace_settings ws\n WHERE (auto_invite->>'domain' = $1 OR auto_invite->>'domain' = '*')\n AND (auto_invite->>'enabled')::boolean = true\n AND NOT EXISTS (SELECT 1 FROM usr WHERE workspace_id = ws.workspace_id AND email = $2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "is_operator: bool", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "role: String", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "is_auto_add: bool", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + null, + null, + null + ] + }, + "hash": "acd87efeb1e92f6c5f04f8482fde597611be96a8f2c6a8ea884c39b11620be57" +} diff --git a/backend/.sqlx/query-af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc.json b/backend/.sqlx/query-acda97a0d2ebb10942b1049cafe3fc9c997dd9427659ff15f6850be861000bdf.json similarity index 65% rename from backend/.sqlx/query-af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc.json rename to backend/.sqlx/query-acda97a0d2ebb10942b1049cafe3fc9c997dd9427659ff15f6850be861000bdf.json index c15c64b3cc..c8c440ac5f 100644 --- a/backend/.sqlx/query-af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc.json +++ b/backend/.sqlx/query-acda97a0d2ebb10942b1049cafe3fc9c997dd9427659ff15f6850be861000bdf.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT c.agent_path FROM slack_agent_channel c\n JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id\n AND ws.slack_team_id = c.slack_team_id\n WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path LIMIT 11", + "query": "SELECT c.agent_path FROM slack_agent_channel c\n JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id\n AND ws.slack_team_id = c.slack_team_id\n WHERE c.slack_team_id = $1 AND c.channel_id = $2\n AND ws.workspace_id = ANY($3)\n ORDER BY c.agent_path LIMIT 11", "describe": { "columns": [ { @@ -12,12 +12,13 @@ "parameters": { "Left": [ "Text", - "Text" + "Text", + "TextArray" ] }, "nullable": [ false ] }, - "hash": "af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc" + "hash": "acda97a0d2ebb10942b1049cafe3fc9c997dd9427659ff15f6850be861000bdf" } diff --git a/backend/.sqlx/query-ad218040fc53b063508774c6f04d5f82cc2121ea8519311add88f23f0ea0dae9.json b/backend/.sqlx/query-ad218040fc53b063508774c6f04d5f82cc2121ea8519311add88f23f0ea0dae9.json new file mode 100644 index 0000000000..87a4b3e764 --- /dev/null +++ b/backend/.sqlx/query-ad218040fc53b063508774c6f04d5f82cc2121ea8519311add88f23f0ea0dae9.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE usr SET added_via = $1, is_admin = $2 WHERE username = $3 AND workspace_id = $4", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Bool", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "ad218040fc53b063508774c6f04d5f82cc2121ea8519311add88f23f0ea0dae9" +} diff --git a/backend/.sqlx/query-af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb.json b/backend/.sqlx/query-af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb.json new file mode 100644 index 0000000000..c832fdeeda --- /dev/null +++ b/backend/.sqlx/query-af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb.json @@ -0,0 +1,238 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT\n workspace_id,\n slack_team_id,\n teams_team_id,\n teams_team_name,\n teams_team_guid,\n slack_name,\n slack_command_script,\n teams_command_script,\n slack_email,\n slack_oauth_client_id,\n slack_oauth_client_secret,\n customer_id,\n plan,\n webhook,\n ai_config,\n dbt_warehouses,\n large_file_storage,\n datatable,\n ducklake,\n git_sync,\n deploy_ui,\n default_app,\n default_scripts,\n mute_critical_alerts,\n color,\n operator_settings,\n git_app_installations,\n auto_invite,\n error_handler,\n success_handler,\n variable_expiration_handler,\n public_app_execution_limit_per_minute,\n error_handler_fallback_to_instance_alerts,\n guest_access_enabled,\n guest_jwt_public_key,\n guest_jwt_jwks_url,\n add_admins_and_developers_to_forks\n FROM\n workspace_settings\n WHERE\n workspace_id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "slack_team_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "teams_team_id", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "teams_team_name", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "teams_team_guid", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "slack_name", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "slack_command_script", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "teams_command_script", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "slack_email", + "type_info": "Varchar" + }, + { + "ordinal": 9, + "name": "slack_oauth_client_id", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "slack_oauth_client_secret", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "customer_id", + "type_info": "Varchar" + }, + { + "ordinal": 12, + "name": "plan", + "type_info": "Varchar" + }, + { + "ordinal": 13, + "name": "webhook", + "type_info": "Text" + }, + { + "ordinal": 14, + "name": "ai_config", + "type_info": "Jsonb" + }, + { + "ordinal": 15, + "name": "dbt_warehouses", + "type_info": "Jsonb" + }, + { + "ordinal": 16, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 17, + "name": "datatable", + "type_info": "Jsonb" + }, + { + "ordinal": 18, + "name": "ducklake", + "type_info": "Jsonb" + }, + { + "ordinal": 19, + "name": "git_sync", + "type_info": "Jsonb" + }, + { + "ordinal": 20, + "name": "deploy_ui", + "type_info": "Jsonb" + }, + { + "ordinal": 21, + "name": "default_app", + "type_info": "Varchar" + }, + { + "ordinal": 22, + "name": "default_scripts", + "type_info": "Jsonb" + }, + { + "ordinal": 23, + "name": "mute_critical_alerts", + "type_info": "Bool" + }, + { + "ordinal": 24, + "name": "color", + "type_info": "Varchar" + }, + { + "ordinal": 25, + "name": "operator_settings", + "type_info": "Jsonb" + }, + { + "ordinal": 26, + "name": "git_app_installations", + "type_info": "Jsonb" + }, + { + "ordinal": 27, + "name": "auto_invite", + "type_info": "Jsonb" + }, + { + "ordinal": 28, + "name": "error_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 29, + "name": "success_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 30, + "name": "variable_expiration_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 31, + "name": "public_app_execution_limit_per_minute", + "type_info": "Int4" + }, + { + "ordinal": 32, + "name": "error_handler_fallback_to_instance_alerts", + "type_info": "Bool" + }, + { + "ordinal": 33, + "name": "guest_access_enabled", + "type_info": "Bool" + }, + { + "ordinal": 34, + "name": "guest_jwt_public_key", + "type_info": "Text" + }, + { + "ordinal": 35, + "name": "guest_jwt_jwks_url", + "type_info": "Text" + }, + { + "ordinal": 36, + "name": "add_admins_and_developers_to_forks", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + false, + true, + true, + false + ] + }, + "hash": "af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb" +} diff --git a/backend/.sqlx/query-b0e56637096b48867401967ad5ddc509bbd1e322788789a913d5148c1113643c.json b/backend/.sqlx/query-b0e56637096b48867401967ad5ddc509bbd1e322788789a913d5148c1113643c.json new file mode 100644 index 0000000000..2478a6c7eb --- /dev/null +++ b/backend/.sqlx/query-b0e56637096b48867401967ad5ddc509bbd1e322788789a913d5148c1113643c.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT username, email, is_admin, operator, workspace_role,\n added_via->>'group' as granting_group\n FROM usr\n WHERE workspace_id = $1 AND added_via->>'source' = 'instance_group'\n ORDER BY email", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "workspace_role", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "granting_group", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + null + ] + }, + "hash": "b0e56637096b48867401967ad5ddc509bbd1e322788789a913d5148c1113643c" +} diff --git a/backend/.sqlx/query-b19f5156b3e36b5e831ce792637bf54a3f182c03cef0aef06a1c75b45992cd39.json b/backend/.sqlx/query-b19f5156b3e36b5e831ce792637bf54a3f182c03cef0aef06a1c75b45992cd39.json index 10adc6e68d..4db5bc6e3c 100644 --- a/backend/.sqlx/query-b19f5156b3e36b5e831ce792637bf54a3f182c03cef0aef06a1c75b45992cd39.json +++ b/backend/.sqlx/query-b19f5156b3e36b5e831ce792637bf54a3f182c03cef0aef06a1c75b45992cd39.json @@ -11,7 +11,7 @@ ], "parameters": { "Left": [ - "Varchar", + "Text", "Int8" ] }, diff --git a/backend/.sqlx/query-44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b.json b/backend/.sqlx/query-b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed.json similarity index 63% rename from backend/.sqlx/query-44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b.json rename to backend/.sqlx/query-b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed.json index 18c572b1fb..44dcca2457 100644 --- a/backend/.sqlx/query-44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b.json +++ b/backend/.sqlx/query-b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret, expires_at FROM variable WHERE path = $1", + "query": "SELECT value::text AS \"value!\", is_secret, expires_at FROM variable WHERE path = $1", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -25,10 +25,10 @@ ] }, "nullable": [ - false, + null, false, true ] }, - "hash": "44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b" + "hash": "b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed" } diff --git a/backend/.sqlx/query-b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4.json b/backend/.sqlx/query-b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4.json new file mode 100644 index 0000000000..aee28fd8b6 --- /dev/null +++ b/backend/.sqlx/query-b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable SET value_valid_until = '2029-12-31T00:00:00Z'\n WHERE workspace_id = 'wm-fork-expiry' AND path = 'u/admin/expiring'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4" +} diff --git a/backend/.sqlx/query-b57b038384e48f2e6f288056e7261459604a093a74e22770ccdc14207cacbfb0.json b/backend/.sqlx/query-b57b038384e48f2e6f288056e7261459604a093a74e22770ccdc14207cacbfb0.json new file mode 100644 index 0000000000..b344aa8d0e --- /dev/null +++ b/backend/.sqlx/query-b57b038384e48f2e6f288056e7261459604a093a74e22770ccdc14207cacbfb0.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT\n workspace_invite.workspace_id,\n workspace_invite.email,\n workspace_invite.is_admin,\n workspace_invite.operator,\n COALESCE(workspace_invite.workspace_role, CASE WHEN workspace_invite.operator THEN 'operator' ELSE 'developer' END) AS \"role!\",\n workspace.parent_workspace_id\n FROM workspace_invite JOIN workspace ON workspace_invite.workspace_id = workspace.id WHERE email = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "role!", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "parent_workspace_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + null, + true + ] + }, + "hash": "b57b038384e48f2e6f288056e7261459604a093a74e22770ccdc14207cacbfb0" +} diff --git a/backend/.sqlx/query-b7c7384b335a51f7d1abd2c627ea62ec651c5c6eee947540e7ee5dcea4780b37.json b/backend/.sqlx/query-b7c7384b335a51f7d1abd2c627ea62ec651c5c6eee947540e7ee5dcea4780b37.json new file mode 100644 index 0000000000..2b930845d2 --- /dev/null +++ b/backend/.sqlx/query-b7c7384b335a51f7d1abd2c627ea62ec651c5c6eee947540e7ee5dcea4780b37.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH revoked AS (\n DELETE FROM token WHERE email = $1 AND label LIKE 'mcp-oauth-%' RETURNING token_prefix\n ), refresh AS (\n DELETE FROM mcp_oauth_refresh_token WHERE user_email = $1\n ), code AS (\n DELETE FROM mcp_oauth_server_code WHERE user_email = $1\n )\n INSERT INTO notify_event (channel, payload)\n SELECT 'notify_token_invalidation', token_prefix FROM revoked", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "b7c7384b335a51f7d1abd2c627ea62ec651c5c6eee947540e7ee5dcea4780b37" +} diff --git a/backend/.sqlx/query-b8b89624212f32fb6e994b7488fa7152c190bab532406fd26d17dfbd2355c764.json b/backend/.sqlx/query-b8b89624212f32fb6e994b7488fa7152c190bab532406fd26d17dfbd2355c764.json new file mode 100644 index 0000000000..cdd594c8df --- /dev/null +++ b/backend/.sqlx/query-b8b89624212f32fb6e994b7488fa7152c190bab532406fd26d17dfbd2355c764.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT is_admin, operator, workspace_role FROM usr where username = $1 AND workspace_id = $2 AND disabled = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "workspace_role", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + true + ] + }, + "hash": "b8b89624212f32fb6e994b7488fa7152c190bab532406fd26d17dfbd2355c764" +} diff --git a/backend/.sqlx/query-1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1.json b/backend/.sqlx/query-bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json similarity index 72% rename from backend/.sqlx/query-1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1.json rename to backend/.sqlx/query-bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json index b4a9f19f45..af2c944342 100644 --- a/backend/.sqlx/query-1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1.json +++ b/backend/.sqlx/query-bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT usr.*, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2\n ", + "query": "SELECT usr.workspace_id, usr.email, usr.username, usr.is_admin, usr.created_at, usr.operator, usr.disabled, usr.role, usr.added_via, usr.is_service_account, usr.workspace_role, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2\n ", "describe": { "columns": [ { @@ -10,12 +10,12 @@ }, { "ordinal": 1, - "name": "username", + "name": "email", "type_info": "Varchar" }, { "ordinal": 2, - "name": "email", + "name": "username", "type_info": "Varchar" }, { @@ -55,11 +55,16 @@ }, { "ordinal": 10, + "name": "workspace_role", + "type_info": "Varchar" + }, + { + "ordinal": 11, "name": "super_admin!", "type_info": "Bool" }, { - "ordinal": 11, + "ordinal": 12, "name": "name", "type_info": "Varchar" } @@ -81,9 +86,10 @@ true, true, false, + true, null, true ] }, - "hash": "1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1" + "hash": "bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4" } diff --git a/backend/.sqlx/query-ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81.json b/backend/.sqlx/query-bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576.json similarity index 58% rename from backend/.sqlx/query-ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81.json rename to backend/.sqlx/query-bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576.json index 3fe61f6f8e..09fa4b0b11 100644 --- a/backend/.sqlx/query-ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81.json +++ b/backend/.sqlx/query-bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT workspace_id, path, value FROM variable WHERE is_secret = true AND value IS NOT NULL AND value != ''", + "query": "SELECT workspace_id, path, value::text AS \"value!\" FROM variable WHERE is_secret = true AND value IS NOT NULL AND value != ''", "describe": { "columns": [ { @@ -15,8 +15,8 @@ }, { "ordinal": 2, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" } ], "parameters": { @@ -25,8 +25,8 @@ "nullable": [ false, false, - false + null ] }, - "hash": "ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81" + "hash": "bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576" } diff --git a/backend/.sqlx/query-bd2812c7510d2e448c3218dfe3261272c2916540062d57d36c8471c40a398727.json b/backend/.sqlx/query-bd2812c7510d2e448c3218dfe3261272c2916540062d57d36c8471c40a398727.json new file mode 100644 index 0000000000..381f5ba491 --- /dev/null +++ b/backend/.sqlx/query-bd2812c7510d2e448c3218dfe3261272c2916540062d57d36c8471c40a398727.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_integrations SET resource_path = $3, updated_at = now()\n WHERE workspace_id = $1 AND service_name = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "Text" + ] + }, + "nullable": [] + }, + "hash": "bd2812c7510d2e448c3218dfe3261272c2916540062d57d36c8471c40a398727" +} diff --git a/backend/.sqlx/query-bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b.json b/backend/.sqlx/query-bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b.json deleted file mode 100644 index 02a979f32f..0000000000 --- a/backend/.sqlx/query-bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT path, value FROM variable\n WHERE path LIKE ('u/' || $1 || '/%')\n AND workspace_id = $2\n AND is_secret = true\n AND (value LIKE '$vault:%' OR value LIKE '$azure_kv:%')", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "path", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "value", - "type_info": "Varchar" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - false, - false - ] - }, - "hash": "bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b" -} diff --git a/backend/.sqlx/query-c01d2853ab35a404e0cce34c273c7ad58cd9add49f45fd50f4fcf909703d01a2.json b/backend/.sqlx/query-c01d2853ab35a404e0cce34c273c7ad58cd9add49f45fd50f4fcf909703d01a2.json new file mode 100644 index 0000000000..dfa1689d15 --- /dev/null +++ b/backend/.sqlx/query-c01d2853ab35a404e0cce34c273c7ad58cd9add49f45fd50f4fcf909703d01a2.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret\n FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "slack_oauth_client_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "slack_oauth_client_secret", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "slack_signing_secret", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true, + true, + true + ] + }, + "hash": "c01d2853ab35a404e0cce34c273c7ad58cd9add49f45fd50f4fcf909703d01a2" +} diff --git a/backend/.sqlx/query-c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a.json b/backend/.sqlx/query-c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a.json deleted file mode 100644 index 74a9d24135..0000000000 --- a/backend/.sqlx/query-c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT value, account FROM variable WHERE workspace_id = $1 AND path = $2", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "value", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "account", - "type_info": "Int4" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - false, - true - ] - }, - "hash": "c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a" -} diff --git a/backend/.sqlx/query-c17ac5cf890831ede0811263a0f35e8cb2fe4df224e2ab633a1e69c4bcfa6cd1.json b/backend/.sqlx/query-c17ac5cf890831ede0811263a0f35e8cb2fe4df224e2ab633a1e69c4bcfa6cd1.json new file mode 100644 index 0000000000..f468c212dd --- /dev/null +++ b/backend/.sqlx/query-c17ac5cf890831ede0811263a0f35e8cb2fe4df224e2ab633a1e69c4bcfa6cd1.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE native_trigger SET connection_path = REGEXP_REPLACE(connection_path, 'u/' || $2 || '/(.*)', $1 || '/\\1') WHERE connection_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c17ac5cf890831ede0811263a0f35e8cb2fe4df224e2ab633a1e69c4bcfa6cd1" +} diff --git a/backend/.sqlx/query-146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e.json b/backend/.sqlx/query-c1be495552d1bd4c38e378016324b3bc473599c4cb1b2181144988eb88e9fa17.json similarity index 57% rename from backend/.sqlx/query-146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e.json rename to backend/.sqlx/query-c1be495552d1bd4c38e378016324b3bc473599c4cb1b2181144988eb88e9fa17.json index 9fd6daded5..72f509fc57 100644 --- a/backend/.sqlx/query-146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e.json +++ b/backend/.sqlx/query-c1be495552d1bd4c38e378016324b3bc473599c4cb1b2181144988eb88e9fa17.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + "query": "SELECT workspace_role, operator FROM usr WHERE workspace_id = $1 AND username = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", + "name": "workspace_role", "type_info": "Varchar" }, { "ordinal": 1, - "name": "is_secret", + "name": "operator", "type_info": "Bool" } ], @@ -21,9 +21,9 @@ ] }, "nullable": [ - false, + true, false ] }, - "hash": "146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e" + "hash": "c1be495552d1bd4c38e378016324b3bc473599c4cb1b2181144988eb88e9fa17" } diff --git a/backend/.sqlx/query-c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da.json b/backend/.sqlx/query-c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da.json index ee946012b2..5791e1ca31 100644 --- a/backend/.sqlx/query-c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da.json +++ b/backend/.sqlx/query-c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da.json @@ -76,7 +76,7 @@ false, false, false, - false, + true, false, false, false, diff --git a/backend/.sqlx/query-c427c9dad3de3acc361c341b359453197d7683bc8fd5a96be462e3493e957cee.json b/backend/.sqlx/query-c427c9dad3de3acc361c341b359453197d7683bc8fd5a96be462e3493e957cee.json new file mode 100644 index 0000000000..f851507f4e --- /dev/null +++ b/backend/.sqlx/query-c427c9dad3de3acc361c341b359453197d7683bc8fd5a96be462e3493e957cee.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable SET value = $1 WHERE workspace_id = $2 AND account = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "c427c9dad3de3acc361c341b359453197d7683bc8fd5a96be462e3493e957cee" +} diff --git a/backend/.sqlx/query-f3cd54017710536747b8aca797a8b983774ee2127dceb790181ed91b987f44ff.json b/backend/.sqlx/query-c5a7f56bed61174904d3bb1b7be704a4d1a3a4da8c995319f3cc3ce96d8ef5cc.json similarity index 65% rename from backend/.sqlx/query-f3cd54017710536747b8aca797a8b983774ee2127dceb790181ed91b987f44ff.json rename to backend/.sqlx/query-c5a7f56bed61174904d3bb1b7be704a4d1a3a4da8c995319f3cc3ce96d8ef5cc.json index 6964dfa8d6..48435310f8 100644 --- a/backend/.sqlx/query-f3cd54017710536747b8aca797a8b983774ee2127dceb790181ed91b987f44ff.json +++ b/backend/.sqlx/query-c5a7f56bed61174904d3bb1b7be704a4d1a3a4da8c995319f3cc3ce96d8ef5cc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n nt.external_id,\n nt.workspace_id,\n nt.service_name AS \"service_name!: ServiceName\",\n nt.script_path,\n nt.is_flow,\n nt.webhook_token_hash,\n nt.service_config,\n nt.error,\n nt.created_at,\n nt.updated_at,\n nt.summary,\n nt.enabled\n FROM\n native_trigger nt\n WHERE\n nt.workspace_id = $1 AND\n nt.service_name = $2 AND\n ($5::text IS NULL OR nt.script_path = $5) AND\n ($6::bool IS NULL OR nt.is_flow = $6) AND\n (\n (nt.is_flow = false AND EXISTS (\n SELECT 1 FROM script s\n WHERE s.workspace_id = nt.workspace_id\n AND s.path = nt.script_path\n ))\n OR\n (nt.is_flow = true AND EXISTS (\n SELECT 1 FROM flow f\n WHERE f.workspace_id = nt.workspace_id\n AND f.path = nt.script_path\n ))\n ) AND\n ( $7\n OR nt.script_path = ANY($8)\n OR EXISTS ( SELECT 1 FROM unnest($9::text[]) AS pfx\n WHERE nt.script_path = pfx\n OR left(nt.script_path, length(pfx) + 1) = pfx || '/' ) )\n LIMIT $3\n OFFSET $4\n ", + "query": "\n SELECT\n nt.external_id,\n nt.workspace_id,\n nt.service_name AS \"service_name!: ServiceName\",\n nt.script_path,\n nt.is_flow,\n nt.webhook_token_hash,\n nt.service_config,\n nt.error,\n nt.created_at,\n nt.updated_at,\n nt.summary,\n nt.enabled,\n nt.connection_path\n FROM\n native_trigger nt\n WHERE\n nt.workspace_id = $1 AND\n nt.service_name = $2 AND\n ($5::text IS NULL OR nt.script_path = $5) AND\n ($6::bool IS NULL OR nt.is_flow = $6) AND\n (\n (nt.is_flow = false AND EXISTS (\n SELECT 1 FROM script s\n WHERE s.workspace_id = nt.workspace_id\n AND s.path = nt.script_path\n ))\n OR\n (nt.is_flow = true AND EXISTS (\n SELECT 1 FROM flow f\n WHERE f.workspace_id = nt.workspace_id\n AND f.path = nt.script_path\n ))\n ) AND\n ( $7\n OR nt.script_path = ANY($8)\n OR EXISTS ( SELECT 1 FROM unnest($9::text[]) AS pfx\n WHERE nt.script_path = pfx\n OR left(nt.script_path, length(pfx) + 1) = pfx || '/' ) )\n LIMIT $3\n OFFSET $4\n ", "describe": { "columns": [ { @@ -73,6 +73,11 @@ "ordinal": 11, "name": "enabled", "type_info": "Bool" + }, + { + "ordinal": 12, + "name": "connection_path", + "type_info": "Varchar" } ], "parameters": { @@ -111,8 +116,9 @@ false, false, true, - false + false, + true ] }, - "hash": "f3cd54017710536747b8aca797a8b983774ee2127dceb790181ed91b987f44ff" + "hash": "c5a7f56bed61174904d3bb1b7be704a4d1a3a4da8c995319f3cc3ce96d8ef5cc" } diff --git a/backend/.sqlx/query-c7a1a350f95523df4e2012d2d21ec87a0016b1949cfe2d901aacc281d9442738.json b/backend/.sqlx/query-c7a1a350f95523df4e2012d2d21ec87a0016b1949cfe2d901aacc281d9442738.json new file mode 100644 index 0000000000..01baaa7c57 --- /dev/null +++ b/backend/.sqlx/query-c7a1a350f95523df4e2012d2d21ec87a0016b1949cfe2d901aacc281d9442738.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO role_seat (workspace_id, role, author)\n SELECT $1, role, author FROM role_seat WHERE workspace_id = $2\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c7a1a350f95523df4e2012d2d21ec87a0016b1949cfe2d901aacc281d9442738" +} diff --git a/backend/.sqlx/query-ca4c2768d111fbd653f1a73afc669b58a0016bfb4f0dad133ef2c25b8cd8b4b6.json b/backend/.sqlx/query-ca4c2768d111fbd653f1a73afc669b58a0016bfb4f0dad133ef2c25b8cd8b4b6.json new file mode 100644 index 0000000000..c84a500f29 --- /dev/null +++ b/backend/.sqlx/query-ca4c2768d111fbd653f1a73afc669b58a0016bfb4f0dad133ef2c25b8cd8b4b6.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_invite\n (workspace_id, email, is_admin, operator, workspace_role)\n VALUES ($1, $2, false, $3, $4)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Bool", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "ca4c2768d111fbd653f1a73afc669b58a0016bfb4f0dad133ef2c25b8cd8b4b6" +} diff --git a/backend/.sqlx/query-cbc0edfcdda98420e728e35508e46d9b9ecb504cbea4976c8f45fc089cb81977.json b/backend/.sqlx/query-cbc0edfcdda98420e728e35508e46d9b9ecb504cbea4976c8f45fc089cb81977.json new file mode 100644 index 0000000000..d109e62811 --- /dev/null +++ b/backend/.sqlx/query-cbc0edfcdda98420e728e35508e46d9b9ecb504cbea4976c8f45fc089cb81977.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE role_seat SET workspace_id = $1 WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "cbc0edfcdda98420e728e35508e46d9b9ecb504cbea4976c8f45fc089cb81977" +} diff --git a/backend/.sqlx/query-cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3.json b/backend/.sqlx/query-cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3.json new file mode 100644 index 0000000000..5abf2efb76 --- /dev/null +++ b/backend/.sqlx/query-cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3.json @@ -0,0 +1,71 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.workspace_id, v.path, v.description, v.value_valid_until AS \"value_valid_until!\",\n v.is_secret, v.expiration_dispatched_for, v.expiration_notified_at,\n ws.variable_expiration_handler->>'path' AS \"handler_path!\",\n (ws.variable_expiration_handler->'extra_args')::text::json\n AS \"extra_args: Json>\"\n FROM variable v\n JOIN workspace_settings ws ON ws.workspace_id = v.workspace_id\n JOIN workspace w ON w.id = v.workspace_id\n WHERE NOT w.deleted\n AND v.value_valid_until IS NOT NULL\n AND (v.value_valid_until IS DISTINCT FROM v.expiration_dispatched_for\n OR (v.value_valid_until > now()\n AND v.expiration_notified_at <= now() - make_interval(secs =>\n NULLIF((ws.variable_expiration_handler->>'remind_every_secs')::bigint, 0) - $2)))\n AND v.value_valid_until <= now() + make_interval(secs =>\n COALESCE((ws.variable_expiration_handler->>'notify_before_secs')::bigint, $1))\n AND ws.variable_expiration_handler->>'path' IS NOT NULL\n AND (NOT COALESCE((ws.variable_expiration_handler->>'muted_on_user_path')::boolean, false)\n OR v.path NOT LIKE 'u/%')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "description", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "value_valid_until!", + "type_info": "Timestamptz" + }, + { + "ordinal": 4, + "name": "is_secret", + "type_info": "Bool" + }, + { + "ordinal": 5, + "name": "expiration_dispatched_for", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "expiration_notified_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 7, + "name": "handler_path!", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "extra_args: Json>", + "type_info": "Json" + } + ], + "parameters": { + "Left": [ + "Int8", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + true, + true, + null, + null + ] + }, + "hash": "cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3" +} diff --git a/backend/.sqlx/query-cce5e3e639faed8e42574730cc66f0322a83c01cc465742f54a21f8fe5f4f037.json b/backend/.sqlx/query-cce5e3e639faed8e42574730cc66f0322a83c01cc465742f54a21f8fe5f4f037.json index 29f31c62eb..59ee111e89 100644 --- a/backend/.sqlx/query-cce5e3e639faed8e42574730cc66f0322a83c01cc465742f54a21f8fe5f4f037.json +++ b/backend/.sqlx/query-cce5e3e639faed8e42574730cc66f0322a83c01cc465742f54a21f8fe5f4f037.json @@ -39,7 +39,8 @@ "java", "duckdb", "ruby", - "rlang" + "rlang", + "dbt" ] } } diff --git a/backend/.sqlx/query-72076c1c210c57ef5db26620063c750c4a7eef6dcb2f4a91c7a3ddc2d367e3ba.json b/backend/.sqlx/query-cd829b96e6d8f4ed9a0283d9141ce8588ad36379991e71b10e49211891219a92.json similarity index 51% rename from backend/.sqlx/query-72076c1c210c57ef5db26620063c750c4a7eef6dcb2f4a91c7a3ddc2d367e3ba.json rename to backend/.sqlx/query-cd829b96e6d8f4ed9a0283d9141ce8588ad36379991e71b10e49211891219a92.json index b3482a1535..fa44c1e169 100644 --- a/backend/.sqlx/query-72076c1c210c57ef5db26620063c750c4a7eef6dcb2f4a91c7a3ddc2d367e3ba.json +++ b/backend/.sqlx/query-cd829b96e6d8f4ed9a0283d9141ce8588ad36379991e71b10e49211891219a92.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE workspace_settings\n SET slack_oauth_client_id = NULL, slack_oauth_client_secret = NULL\n WHERE workspace_id = $1", + "query": "UPDATE workspace_settings\n SET slack_oauth_client_id = NULL, slack_oauth_client_secret = NULL,\n slack_signing_secret = NULL\n WHERE workspace_id = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "72076c1c210c57ef5db26620063c750c4a7eef6dcb2f4a91c7a3ddc2d367e3ba" + "hash": "cd829b96e6d8f4ed9a0283d9141ce8588ad36379991e71b10e49211891219a92" } diff --git a/backend/.sqlx/query-ce033ee4db97c0f9ae643d287f1a3f1578a6be8686e02c3faa55100eb8fa3700.json b/backend/.sqlx/query-ce033ee4db97c0f9ae643d287f1a3f1578a6be8686e02c3faa55100eb8fa3700.json new file mode 100644 index 0000000000..3e44f3ab42 --- /dev/null +++ b/backend/.sqlx/query-ce033ee4db97c0f9ae643d287f1a3f1578a6be8686e02c3faa55100eb8fa3700.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_invite\n (workspace_id, email, is_admin, operator, workspace_role)\n SELECT $1::text, email, false, $3, $4 FROM password WHERE ($2::text = '*' OR email LIKE CONCAT('%@', $2::text)) AND NOT EXISTS (\n SELECT 1 FROM usr WHERE workspace_id = $1::text AND email = password.email\n )\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Bool", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "ce033ee4db97c0f9ae643d287f1a3f1578a6be8686e02c3faa55100eb8fa3700" +} diff --git a/backend/.sqlx/query-d46f75bb9d7144d571a31ddbb3c986ea2bfd561943ff512ac20f93203e02c3d8.json b/backend/.sqlx/query-d46f75bb9d7144d571a31ddbb3c986ea2bfd561943ff512ac20f93203e02c3d8.json new file mode 100644 index 0000000000..f70dff1f07 --- /dev/null +++ b/backend/.sqlx/query-d46f75bb9d7144d571a31ddbb3c986ea2bfd561943ff512ac20f93203e02c3d8.json @@ -0,0 +1,77 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, username, email, is_admin, created_at, operator, disabled,\n COALESCE(workspace_role, CASE WHEN operator THEN 'operator' ELSE 'developer' END) AS role,\n added_via, is_service_account\n FROM usr WHERE username = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "created_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 6, + "name": "disabled", + "type_info": "Bool" + }, + { + "ordinal": 7, + "name": "role", + "type_info": "Varchar" + }, + { + "ordinal": 8, + "name": "added_via", + "type_info": "Jsonb" + }, + { + "ordinal": 9, + "name": "is_service_account", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + null, + true, + false + ] + }, + "hash": "d46f75bb9d7144d571a31ddbb3c986ea2bfd561943ff512ac20f93203e02c3d8" +} diff --git a/backend/.sqlx/query-d79ba22a53c9f96c96fcd4b4cf0e6cc17f767055de943709192ef1ff5106eac5.json b/backend/.sqlx/query-d79ba22a53c9f96c96fcd4b4cf0e6cc17f767055de943709192ef1ff5106eac5.json new file mode 100644 index 0000000000..3f3a3f20e4 --- /dev/null +++ b/backend/.sqlx/query-d79ba22a53c9f96c96fcd4b4cf0e6cc17f767055de943709192ef1ff5106eac5.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.path FROM variable v\n JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n WHERE v.workspace_id = $1 AND a.client = $2 AND a.is_workspace_integration = true", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "d79ba22a53c9f96c96fcd4b4cf0e6cc17f767055de943709192ef1ff5106eac5" +} diff --git a/backend/.sqlx/query-0987f164fe3d64bf0a6a4e9699c2d1f339670da3ed1c08203d54d45798d022dd.json b/backend/.sqlx/query-d976c78db15dac2c70edcea6d7d9ceed91c54f592d0e1f5139d5e111241ca451.json similarity index 82% rename from backend/.sqlx/query-0987f164fe3d64bf0a6a4e9699c2d1f339670da3ed1c08203d54d45798d022dd.json rename to backend/.sqlx/query-d976c78db15dac2c70edcea6d7d9ceed91c54f592d0e1f5139d5e111241ca451.json index 8aecbed333..0fe46de01d 100644 --- a/backend/.sqlx/query-0987f164fe3d64bf0a6a4e9699c2d1f339670da3ed1c08203d54d45798d022dd.json +++ b/backend/.sqlx/query-d976c78db15dac2c70edcea6d7d9ceed91c54f592d0e1f5139d5e111241ca451.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n external_id,\n workspace_id,\n service_name AS \"service_name!: ServiceName\",\n script_path,\n is_flow,\n webhook_token_hash,\n service_config,\n error,\n created_at,\n updated_at,\n summary,\n enabled\n FROM\n native_trigger\n WHERE\n workspace_id = $1\n AND service_name = $2\n AND script_path = $3\n AND is_flow = $4\n LIMIT 1\n ", + "query": "\n SELECT\n external_id,\n workspace_id,\n service_name AS \"service_name!: ServiceName\",\n script_path,\n is_flow,\n webhook_token_hash,\n service_config,\n error,\n created_at,\n updated_at,\n summary,\n enabled,\n connection_path\n FROM\n native_trigger\n WHERE\n workspace_id = $1\n AND service_name = $2\n AND script_path = $3\n AND is_flow = $4\n LIMIT 1\n ", "describe": { "columns": [ { @@ -73,6 +73,11 @@ "ordinal": 11, "name": "enabled", "type_info": "Bool" + }, + { + "ordinal": 12, + "name": "connection_path", + "type_info": "Varchar" } ], "parameters": { @@ -106,8 +111,9 @@ false, false, true, - false + false, + true ] }, - "hash": "0987f164fe3d64bf0a6a4e9699c2d1f339670da3ed1c08203d54d45798d022dd" + "hash": "d976c78db15dac2c70edcea6d7d9ceed91c54f592d0e1f5139d5e111241ca451" } diff --git a/backend/.sqlx/query-daaaa027338cd77d6400658667351a4d3bbe6d1309cd8205e853097c9f81a471.json b/backend/.sqlx/query-daaaa027338cd77d6400658667351a4d3bbe6d1309cd8205e853097c9f81a471.json new file mode 100644 index 0000000000..b2e7a8668c --- /dev/null +++ b/backend/.sqlx/query-daaaa027338cd77d6400658667351a4d3bbe6d1309cd8205e853097c9f81a471.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE native_trigger SET connection_path = REGEXP_REPLACE(connection_path, 'u/' || $2 || '/(.*)', 'u/' || $1 || '/\\1') WHERE connection_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "daaaa027338cd77d6400658667351a4d3bbe6d1309cd8205e853097c9f81a471" +} diff --git a/backend/.sqlx/query-db9831a3218b36c32b305b9f2ba21abceec74c9c277f27231dba12868e68126b.json b/backend/.sqlx/query-db9831a3218b36c32b305b9f2ba21abceec74c9c277f27231dba12868e68126b.json deleted file mode 100644 index 3562a6f345..0000000000 --- a/backend/.sqlx/query-db9831a3218b36c32b305b9f2ba21abceec74c9c277f27231dba12868e68126b.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE account SET refresh_token = $1, expires_at = $2, refresh_error = NULL WHERE workspace_id = $3 AND id = $4", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Timestamptz", - "Text", - "Int4" - ] - }, - "nullable": [] - }, - "hash": "db9831a3218b36c32b305b9f2ba21abceec74c9c277f27231dba12868e68126b" -} diff --git a/backend/.sqlx/query-dcb5053bdae0a2d141f7e7cb16988f5bc2c40c098558d92ab768281f4e9664c5.json b/backend/.sqlx/query-dcb5053bdae0a2d141f7e7cb16988f5bc2c40c098558d92ab768281f4e9664c5.json new file mode 100644 index 0000000000..12e32dfe45 --- /dev/null +++ b/backend/.sqlx/query-dcb5053bdae0a2d141f7e7cb16988f5bc2c40c098558d92ab768281f4e9664c5.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM usr t WHERE ($1::text IS NOT NULL AND t.workspace_id = $1\n OR $1::text IS NULL AND NOT EXISTS (SELECT 1 FROM workspace_settings ws\n WHERE ws.workspace_id = t.workspace_id AND ws.role_overrides ? $2)) AND\n COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END) = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "dcb5053bdae0a2d141f7e7cb16988f5bc2c40c098558d92ab768281f4e9664c5" +} diff --git a/backend/.sqlx/query-dda346e3e9d2cab64532948de09cf6dea2537923a987be5584fbcb1c0dc69b7f.json b/backend/.sqlx/query-dda346e3e9d2cab64532948de09cf6dea2537923a987be5584fbcb1c0dc69b7f.json new file mode 100644 index 0000000000..189593b34c --- /dev/null +++ b/backend/.sqlx/query-dda346e3e9d2cab64532948de09cf6dea2537923a987be5584fbcb1c0dc69b7f.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings\n SET slack_oauth_client_id = $1, slack_oauth_client_secret = $2,\n slack_signing_secret = CASE WHEN slack_oauth_client_id = $1::varchar\n THEN slack_signing_secret END\n WHERE workspace_id = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "dda346e3e9d2cab64532948de09cf6dea2537923a987be5584fbcb1c0dc69b7f" +} diff --git a/backend/.sqlx/query-ddd41de79b23b0436bbc7997751c90d7d82bd20ea30f1dc08f2e2066fb8d6f4b.json b/backend/.sqlx/query-ddd41de79b23b0436bbc7997751c90d7d82bd20ea30f1dc08f2e2066fb8d6f4b.json index 9622e63a56..02c50b1e45 100644 --- a/backend/.sqlx/query-ddd41de79b23b0436bbc7997751c90d7d82bd20ea30f1dc08f2e2066fb8d6f4b.json +++ b/backend/.sqlx/query-ddd41de79b23b0436bbc7997751c90d7d82bd20ea30f1dc08f2e2066fb8d6f4b.json @@ -23,4 +23,4 @@ ] }, "hash": "ddd41de79b23b0436bbc7997751c90d7d82bd20ea30f1dc08f2e2066fb8d6f4b" -} \ No newline at end of file +} diff --git a/backend/.sqlx/query-bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c.json b/backend/.sqlx/query-de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256.json similarity index 74% rename from backend/.sqlx/query-bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c.json rename to backend/.sqlx/query-de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256.json index d77682a4ea..e2145fc10a 100644 --- a/backend/.sqlx/query-bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c.json +++ b/backend/.sqlx/query-de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers'", + "query": "SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers' AND name != 'variable_expiration_handler'", "describe": { "columns": [ { @@ -16,5 +16,5 @@ null ] }, - "hash": "bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c" + "hash": "de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256" } diff --git a/backend/.sqlx/query-dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e.json b/backend/.sqlx/query-dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e.json new file mode 100644 index 0000000000..6f1cc55c51 --- /dev/null +++ b/backend/.sqlx/query-dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT path, value::text AS \"value!\" FROM variable\n WHERE path LIKE ('u/' || $1 || '/%')\n AND workspace_id = $2\n AND is_secret = true\n AND (value LIKE '$vault:%' OR value LIKE '$azure_kv:%')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "value!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e" +} diff --git a/backend/.sqlx/query-f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807.json b/backend/.sqlx/query-df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98.json similarity index 81% rename from backend/.sqlx/query-f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807.json rename to backend/.sqlx/query-df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98.json index 912db1a932..ed386844d4 100644 --- a/backend/.sqlx/query-f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807.json +++ b/backend/.sqlx/query-df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT fork_last_event_kind, fork_last_event_origin FROM workspace_diff\n WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script'\n AND path = 'u/admin/inline' AND fork_last_event_kind IS NOT NULL", + "query": "SELECT fork_last_event_kind, fork_last_event_origin FROM workspace_diff\n WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script'\n AND path = 'u/admin/inline' AND fork_last_event_kind <> 'write'", "describe": { "columns": [ { @@ -22,5 +22,5 @@ true ] }, - "hash": "f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807" + "hash": "df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98" } diff --git a/backend/.sqlx/query-e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f.json b/backend/.sqlx/query-e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f.json new file mode 100644 index 0000000000..90a3f9c7f2 --- /dev/null +++ b/backend/.sqlx/query-e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM workspace_diff WHERE fork_workspace_id = 'wm-fork-secrets'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f" +} diff --git a/backend/.sqlx/query-e43b178e40ef39908def1746f7f2a6a2ad960a7b5e9536d15efae31bd2431742.json b/backend/.sqlx/query-e43b178e40ef39908def1746f7f2a6a2ad960a7b5e9536d15efae31bd2431742.json new file mode 100644 index 0000000000..2319cf80f7 --- /dev/null +++ b/backend/.sqlx/query-e43b178e40ef39908def1746f7f2a6a2ad960a7b5e9536d15efae31bd2431742.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE account SET refresh_error = $1\n WHERE workspace_id = $2 AND id = $3 AND refresh_token = $4", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Int4", + "Text" + ] + }, + "nullable": [] + }, + "hash": "e43b178e40ef39908def1746f7f2a6a2ad960a7b5e9536d15efae31bd2431742" +} diff --git a/backend/.sqlx/query-f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397.json b/backend/.sqlx/query-e497205c8654cc0ba1b9c88aa1c253f5823cb10016330b317257c8c668d951c2.json similarity index 58% rename from backend/.sqlx/query-f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397.json rename to backend/.sqlx/query-e497205c8654cc0ba1b9c88aa1c253f5823cb10016330b317257c8c668d951c2.json index 30ec07404b..58f404a64d 100644 --- a/backend/.sqlx/query-f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397.json +++ b/backend/.sqlx/query-e497205c8654cc0ba1b9c88aa1c253f5823cb10016330b317257c8c668d951c2.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT workspace_id, slack_command_script IS NOT NULL AS \"has_script!\"\n FROM workspace_settings WHERE slack_team_id = $1\n ORDER BY slack_command_script IS NOT NULL DESC LIMIT 2", + "query": "SELECT workspace_id, slack_command_script IS NOT NULL AS \"has_script!\"\n FROM workspace_settings ws WHERE slack_team_id = $1\n AND ws.workspace_id = ANY($2)\n ORDER BY slack_command_script IS NOT NULL DESC LIMIT 2", "describe": { "columns": [ { @@ -16,7 +16,8 @@ ], "parameters": { "Left": [ - "Text" + "Text", + "TextArray" ] }, "nullable": [ @@ -24,5 +25,5 @@ null ] }, - "hash": "f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397" + "hash": "e497205c8654cc0ba1b9c88aa1c253f5823cb10016330b317257c8c668d951c2" } diff --git a/backend/.sqlx/query-b9686c115e83ad0725503e2c076960914f825eaa2b44281a4e147cea6e886e7a.json b/backend/.sqlx/query-e6d49c3186419c726cc6ed771548c72164b36ccb5434bcc4babefa7f3363c675.json similarity index 68% rename from backend/.sqlx/query-b9686c115e83ad0725503e2c076960914f825eaa2b44281a4e147cea6e886e7a.json rename to backend/.sqlx/query-e6d49c3186419c726cc6ed771548c72164b36ccb5434bcc4babefa7f3363c675.json index ebb5cee72c..99ec12fd85 100644 --- a/backend/.sqlx/query-b9686c115e83ad0725503e2c076960914f825eaa2b44281a4e147cea6e886e7a.json +++ b/backend/.sqlx/query-e6d49c3186419c726cc6ed771548c72164b36ccb5434bcc4babefa7f3363c675.json @@ -1,11 +1,11 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM native_trigger WHERE workspace_id = $1 AND service_name = $2 RETURNING webhook_token_hash", + "query": "SELECT script_path FROM native_trigger WHERE workspace_id = $1 AND service_name = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "webhook_token_hash", + "name": "script_path", "type_info": "Varchar" } ], @@ -30,5 +30,5 @@ false ] }, - "hash": "b9686c115e83ad0725503e2c076960914f825eaa2b44281a4e147cea6e886e7a" + "hash": "e6d49c3186419c726cc6ed771548c72164b36ccb5434bcc4babefa7f3363c675" } diff --git a/backend/.sqlx/query-e78a06c0ea4d46ec2d55417a81d0c7ed15b7bf962ba19fcd09b23f8e982fa1c9.json b/backend/.sqlx/query-e78a06c0ea4d46ec2d55417a81d0c7ed15b7bf962ba19fcd09b23f8e982fa1c9.json new file mode 100644 index 0000000000..032d104253 --- /dev/null +++ b/backend/.sqlx/query-e78a06c0ea4d46ec2d55417a81d0c7ed15b7bf962ba19fcd09b23f8e982fa1c9.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM role_seat WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "e78a06c0ea4d46ec2d55417a81d0c7ed15b7bf962ba19fcd09b23f8e982fa1c9" +} diff --git a/backend/.sqlx/query-e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c.json b/backend/.sqlx/query-e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c.json new file mode 100644 index 0000000000..b3dd32073d --- /dev/null +++ b/backend/.sqlx/query-e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_handler = $1 WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Text" + ] + }, + "nullable": [] + }, + "hash": "e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c" +} diff --git a/backend/.sqlx/query-eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c.json b/backend/.sqlx/query-eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c.json new file mode 100644 index 0000000000..736b176227 --- /dev/null +++ b/backend/.sqlx/query-eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_failed_at = now()\n WHERE workspace_id = $1 AND variable_expiration_failed_at IS NULL\n RETURNING 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c" +} diff --git a/backend/.sqlx/query-eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079.json b/backend/.sqlx/query-eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079.json new file mode 100644 index 0000000000..f0ced3e76b --- /dev/null +++ b/backend/.sqlx/query-eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_failed_at = NULL\n WHERE variable_expiration_failed_at IS NOT NULL AND variable_expiration_handler IS NULL\n RETURNING workspace_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false + ] + }, + "hash": "eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079" +} diff --git a/backend/.sqlx/query-eaed64e9c1b4b13ba97b394a9b17adac931366debe890df5b25e4110e47e4f87.json b/backend/.sqlx/query-eaed64e9c1b4b13ba97b394a9b17adac931366debe890df5b25e4110e47e4f87.json new file mode 100644 index 0000000000..a654f614bd --- /dev/null +++ b/backend/.sqlx/query-eaed64e9c1b4b13ba97b394a9b17adac931366debe890df5b25e4110e47e4f87.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET slack_signing_secret = $1 WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "eaed64e9c1b4b13ba97b394a9b17adac931366debe890df5b25e4110e47e4f87" +} diff --git a/backend/.sqlx/query-ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae.json b/backend/.sqlx/query-ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae.json new file mode 100644 index 0000000000..db600a495e --- /dev/null +++ b/backend/.sqlx/query-ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(DISTINCT value) FROM variable WHERE path = 'u/test-user/same'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae" +} diff --git a/backend/.sqlx/query-ee3ed82783b5b7d2f41f16a1d94f006687bd9de4611203b5dd0c28eacee02842.json b/backend/.sqlx/query-ee3ed82783b5b7d2f41f16a1d94f006687bd9de4611203b5dd0c28eacee02842.json deleted file mode 100644 index a1d873778f..0000000000 --- a/backend/.sqlx/query-ee3ed82783b5b7d2f41f16a1d94f006687bd9de4611203b5dd0c28eacee02842.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at FROM workspace_settings WHERE workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "ee3ed82783b5b7d2f41f16a1d94f006687bd9de4611203b5dd0c28eacee02842" -} diff --git a/backend/.sqlx/query-ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c.json b/backend/.sqlx/query-ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c.json new file mode 100644 index 0000000000..d101f5ec0a --- /dev/null +++ b/backend/.sqlx/query-ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_diff\n (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes)\n VALUES ('test-workspace', 'wm-fork-expiry', 'u/admin/expiring', 'variable', 0, 1, NULL)", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c" +} diff --git a/backend/.sqlx/query-c7766afaea3e187824698cae2b090af9f49ded98cd1824f1ac91cc5dbe709bc1.json b/backend/.sqlx/query-efae221cbce1c9d4b96f9990a012b3efce1740b7037cac9983529bc052cf2dd9.json similarity index 83% rename from backend/.sqlx/query-c7766afaea3e187824698cae2b090af9f49ded98cd1824f1ac91cc5dbe709bc1.json rename to backend/.sqlx/query-efae221cbce1c9d4b96f9990a012b3efce1740b7037cac9983529bc052cf2dd9.json index 6a9de7e35b..66edee8f0b 100644 --- a/backend/.sqlx/query-c7766afaea3e187824698cae2b090af9f49ded98cd1824f1ac91cc5dbe709bc1.json +++ b/backend/.sqlx/query-efae221cbce1c9d4b96f9990a012b3efce1740b7037cac9983529bc052cf2dd9.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n external_id,\n workspace_id,\n service_name AS \"service_name!: ServiceName\",\n script_path,\n is_flow,\n webhook_token_hash,\n service_config,\n error,\n created_at,\n updated_at,\n summary,\n enabled\n FROM\n native_trigger\n WHERE\n workspace_id = $1\n AND service_name = $2\n AND external_id = $3\n ", + "query": "\n SELECT\n external_id,\n workspace_id,\n service_name AS \"service_name!: ServiceName\",\n script_path,\n is_flow,\n webhook_token_hash,\n service_config,\n error,\n created_at,\n updated_at,\n summary,\n enabled,\n connection_path\n FROM\n native_trigger\n WHERE\n workspace_id = $1\n AND service_name = $2\n AND external_id = $3\n ", "describe": { "columns": [ { @@ -73,6 +73,11 @@ "ordinal": 11, "name": "enabled", "type_info": "Bool" + }, + { + "ordinal": 12, + "name": "connection_path", + "type_info": "Varchar" } ], "parameters": { @@ -105,8 +110,9 @@ false, false, true, - false + false, + true ] }, - "hash": "c7766afaea3e187824698cae2b090af9f49ded98cd1824f1ac91cc5dbe709bc1" + "hash": "efae221cbce1c9d4b96f9990a012b3efce1740b7037cac9983529bc052cf2dd9" } diff --git a/backend/.sqlx/query-f4af0affaed3b1d30f5c6f4ddf4114718468fbf75ef13c6087c2f57fbbe0b82f.json b/backend/.sqlx/query-f4af0affaed3b1d30f5c6f4ddf4114718468fbf75ef13c6087c2f57fbbe0b82f.json index e52ddcf21f..dfcaa29208 100644 --- a/backend/.sqlx/query-f4af0affaed3b1d30f5c6f4ddf4114718468fbf75ef13c6087c2f57fbbe0b82f.json +++ b/backend/.sqlx/query-f4af0affaed3b1d30f5c6f4ddf4114718468fbf75ef13c6087c2f57fbbe0b82f.json @@ -34,7 +34,8 @@ "java", "duckdb", "ruby", - "rlang" + "rlang", + "dbt" ] } } diff --git a/backend/.sqlx/query-f5022831ab610ab22ef1af1441753aba57d5e8f19a316f76e01922559425d81b.json b/backend/.sqlx/query-f5022831ab610ab22ef1af1441753aba57d5e8f19a316f76e01922559425d81b.json new file mode 100644 index 0000000000..3b0dbb2f41 --- /dev/null +++ b/backend/.sqlx/query-f5022831ab610ab22ef1af1441753aba57d5e8f19a316f76e01922559425d81b.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at FROM workspace_settings WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "f5022831ab610ab22ef1af1441753aba57d5e8f19a316f76e01922559425d81b" +} diff --git a/backend/.sqlx/query-f54795cfa04ef4d0f6ed05aee09513d23e8ef5412d030a172f81dd9a9be0bf2f.json b/backend/.sqlx/query-f54795cfa04ef4d0f6ed05aee09513d23e8ef5412d030a172f81dd9a9be0bf2f.json new file mode 100644 index 0000000000..bb2808083c --- /dev/null +++ b/backend/.sqlx/query-f54795cfa04ef4d0f6ed05aee09513d23e8ef5412d030a172f81dd9a9be0bf2f.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(*) FROM workspace_invite t WHERE ($1::text IS NULL OR t.workspace_id = $1) AND\n COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END) = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "f54795cfa04ef4d0f6ed05aee09513d23e8ef5412d030a172f81dd9a9be0bf2f" +} diff --git a/backend/.sqlx/query-f59c0f10c2dc7c0b578c764545e2ceee71c5f0ed6aca603e7ec7aae47f7cdade.json b/backend/.sqlx/query-f59c0f10c2dc7c0b578c764545e2ceee71c5f0ed6aca603e7ec7aae47f7cdade.json new file mode 100644 index 0000000000..da21731ae1 --- /dev/null +++ b/backend/.sqlx/query-f59c0f10c2dc7c0b578c764545e2ceee71c5f0ed6aca603e7ec7aae47f7cdade.json @@ -0,0 +1,42 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT external_id, connection_path FROM native_trigger\n WHERE workspace_id = $1 AND service_name = $2 AND ($3::text[] IS NULL\n OR (external_id, script_path) IN (SELECT * FROM unnest($3::text[], $4::text[])))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "external_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "connection_path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "f59c0f10c2dc7c0b578c764545e2ceee71c5f0ed6aca603e7ec7aae47f7cdade" +} diff --git a/backend/.sqlx/query-f830e934b43a83f857f682383f36ed56df6518e3035778e4e3b95182d2504e00.json b/backend/.sqlx/query-f830e934b43a83f857f682383f36ed56df6518e3035778e4e3b95182d2504e00.json deleted file mode 100644 index 8025c7654c..0000000000 --- a/backend/.sqlx/query-f830e934b43a83f857f682383f36ed56df6518e3035778e4e3b95182d2504e00.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE workspace_settings\n SET slack_oauth_client_id = $1, slack_oauth_client_secret = $2\n WHERE workspace_id = $3", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "f830e934b43a83f857f682383f36ed56df6518e3035778e4e3b95182d2504e00" -} diff --git a/backend/.sqlx/query-fa9cba875690fa5568a7bb3f33464ccea31da990bb66d6c29b48d39f714c7c8b.json b/backend/.sqlx/query-fa9cba875690fa5568a7bb3f33464ccea31da990bb66d6c29b48d39f714c7c8b.json new file mode 100644 index 0000000000..8515006507 --- /dev/null +++ b/backend/.sqlx/query-fa9cba875690fa5568a7bb3f33464ccea31da990bb66d6c29b48d39f714c7c8b.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT now() > expires_at AS \"expired!\" FROM account\n WHERE workspace_id = $1 AND id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "expired!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [ + null + ] + }, + "hash": "fa9cba875690fa5568a7bb3f33464ccea31da990bb66d6c29b48d39f714c7c8b" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 3f2dfbffec..3ae4630fe5 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -1336,9 +1336,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "1.3.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f02e407fb3b54891734224b9ffac8a71fdd35f542500fa1af95754a6b2beb316" +checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" dependencies = [ "futures-util", "pin-project-lite", @@ -1992,18 +1992,18 @@ dependencies = [ [[package]] name = "bon" -version = "3.10.2" +version = "3.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "214f5df094ce551a10a30ffb9c70243d61f121a3d985a6495933e181dee6a7d2" +checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6" dependencies = [ "bon-macros", ] [[package]] name = "bon-macros" -version = "3.10.2" +version = "3.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2706da6c749998cc555d04184909608956a69ad3f8ab1a076fbc867b4a3c3ce5" +checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6" dependencies = [ "darling 0.24.1", "ident_case", @@ -2366,9 +2366,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.8.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", "jobserver", @@ -2695,9 +2695,9 @@ checksum = "3618cccc083bb987a415d85c02ca6c9994ea5b44731ec28b9ecf09658655fba9" [[package]] name = "const_format" -version = "0.2.36" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +checksum = "a3decb4d6965448659923544a634a0571ba44cede4e11ef15a5a317126840454" dependencies = [ "const_format_proc_macros", "konst", @@ -2705,9 +2705,9 @@ dependencies = [ [[package]] name = "const_format_proc_macros" -version = "0.2.34" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +checksum = "941b570269a642506f08cb5b688c04bfa6cfd41a26f8bcdc49db8fd00c0ab659" dependencies = [ "proc-macro2", "quote", @@ -2858,9 +2858,9 @@ checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ "cfg-if", ] @@ -2964,9 +2964,9 @@ dependencies = [ [[package]] name = "crypto-bigint" -version = "0.7.5" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +checksum = "d726facc8b27e604391b232b970cdc19b5468c69f08b466b9734c759216c7415" dependencies = [ "cpubits", "ctutils", @@ -3055,9 +3055,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0" dependencies = [ "cmov", "subtle", @@ -4156,7 +4156,7 @@ dependencies = [ "hyper-util", "ipnet", "percent-encoding", - "rustls-webpki 0.103.15", + "rustls-webpki 0.103.16", "serde_json", "thiserror 2.0.21", "tokio", @@ -4427,7 +4427,7 @@ dependencies = [ "rustls 0.23.40", "rustls-pemfile 2.2.0", "rustls-tokio-stream", - "rustls-webpki 0.103.15", + "rustls-webpki 0.103.16", "serde", "thiserror 2.0.21", "tokio", @@ -4777,9 +4777,9 @@ dependencies = [ [[package]] name = "diplomat-runtime" -version = "0.16.0" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae517853d9f82b2d144393b1c32c34c46c2e361de2b6c44a8fdfce23beb211cd" +checksum = "d9d981121ba76150987fda68185b37853c0b928a55dfdc28897348cd068440be" [[package]] name = "diplomat_core" @@ -5070,7 +5070,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b805154de2e68f59874ec217ca36790dcffe500cd872c60fe509d28d0814a74d" dependencies = [ "ed448", - "elliptic-curve 0.14.1", + "elliptic-curve 0.14.2", "hash2curve", "rand_core 0.10.1", "serdect 0.4.3", @@ -5126,12 +5126,12 @@ dependencies = [ [[package]] name = "elliptic-curve" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" +checksum = "0ad4496221fcfc21015fd8c0e26fcfab00504832dc0604f52acdd7bad2a8dc81" dependencies = [ "base16ct 1.0.0", - "crypto-bigint 0.7.5", + "crypto-bigint 0.7.8", "crypto-common 0.2.2", "ff 0.14.0", "group 0.14.0", @@ -5218,9 +5218,9 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "erased-serde" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" dependencies = [ "serde", "serde_core", @@ -5408,9 +5408,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "fips203" @@ -6241,7 +6241,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1eaf40612d7d854743e7189228a6d528f0f6e8502cf6a0cb831d28a218b7f3f6" dependencies = [ "digest 0.11.3", - "elliptic-curve 0.14.1", + "elliptic-curve 0.14.2", ] [[package]] @@ -6745,7 +6745,7 @@ dependencies = [ "tokio", "tokio-rustls 0.26.6", "tower-service", - "webpki-roots 1.0.9", + "webpki-roots 1.0.11", ] [[package]] @@ -6859,9 +6859,9 @@ dependencies = [ [[package]] name = "icu_calendar" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +checksum = "a68ffb801cc7acb8dcae62da7c692c47934698d2dd4f479ddee1eb442763dea1" dependencies = [ "calendrical_calculations", "displaydoc", @@ -6875,15 +6875,15 @@ dependencies = [ [[package]] name = "icu_calendar_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc00caaa3fb3201ff7a18aa458e8c3ab042b9da154cfdf948bdde3936c31c36e" +checksum = "514da54e79efa36b5976232d5b3d1d8ee1b47b19ab658f1b1ebe39221696c2d8" [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -6895,9 +6895,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -6909,9 +6909,9 @@ dependencies = [ [[package]] name = "icu_locale_fallback" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" dependencies = [ "icu_locale_core", "icu_locale_fallback_data", @@ -6923,15 +6923,15 @@ dependencies = [ [[package]] name = "icu_locale_fallback_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -6943,15 +6943,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -6964,15 +6964,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -6987,9 +6987,9 @@ dependencies = [ [[package]] name = "icu_segmenter" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" dependencies = [ "icu_collections", "icu_locale_fallback", @@ -6998,14 +6998,15 @@ dependencies = [ "potential_utf", "smallvec", "utf8_iter", + "zerotrie", "zerovec", ] [[package]] name = "icu_segmenter_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" [[package]] name = "ident_case" @@ -7223,9 +7224,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "ixdtf" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d3667095d64c3ecffc96463a21157b04bf3e252f6e8d5750b20c02e33c194e3" +checksum = "4754a1731458af0443709c9667302793d3f63cc90ec4ba4c8259f2b9515478e5" [[package]] name = "jiff" @@ -8155,9 +8156,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", "stable_deref_trait", @@ -10826,11 +10827,11 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "relative-path" -version = "2.0.2" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2a073568cd8b9c4825429d3e9fc5f52851b4f97cc1348800689408921e6b8f8" +checksum = "38540a682c6e9bca04a8bca9e5ec5a6ba168dfbb04c9998fe517a9befb92eb68" dependencies = [ - "serde", + "serde_core", ] [[package]] @@ -10888,7 +10889,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.9", + "webpki-roots 1.0.11", ] [[package]] @@ -11101,9 +11102,9 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "3.5.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1da498700030856ba63114bceefa30ba21f5e278cb975e5b9de3529fe842b40" +checksum = "967fa7f7935d7d6217d593df0e8e5c9307bcaf256974a5a9ee64476c97735389" dependencies = [ "darling 0.24.1", "proc-macro2", @@ -11460,7 +11461,7 @@ dependencies = [ "once_cell", "ring 0.17.14", "rustls-pki-types", - "rustls-webpki 0.103.15", + "rustls-webpki 0.103.16", "subtle", "zeroize", ] @@ -11475,7 +11476,7 @@ dependencies = [ "rustls 0.23.40", "rustls-native-certs 0.7.3", "rustls-pki-types", - "rustls-webpki 0.103.15", + "rustls-webpki 0.103.16", ] [[package]] @@ -11557,7 +11558,7 @@ dependencies = [ "rustls 0.23.40", "rustls-native-certs 0.8.5", "rustls-platform-verifier-android", - "rustls-webpki 0.103.15", + "rustls-webpki 0.103.16", "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", @@ -11606,9 +11607,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring 0.17.14", @@ -12407,9 +12408,9 @@ checksum = "1b6709c7b6754dca1311b3c73e79fcce40dd414c782c66d88e8823030093b02b" [[package]] name = "sketches-ddsketch" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513c3f5f732bfd6fbb187619c2dfe9d2f25f1a2976f01d575f0fd329d565df56" +checksum = "e53e2f8d4e9c692f23a90208fad6a64862f413e286d533f1f649f160e2d5caee" dependencies = [ "serde", ] @@ -12422,9 +12423,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" dependencies = [ "serde", ] @@ -13965,9 +13966,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "serde_core", @@ -14745,9 +14746,9 @@ checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" [[package]] name = "typed-path" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" [[package]] name = "typeid" @@ -15051,9 +15052,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.28.0" +version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -15368,9 +15369,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" dependencies = [ "rustls-pki-types", ] @@ -15381,14 +15382,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.9", + "webpki-roots 1.0.11", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" dependencies = [ "rustls-pki-types", ] @@ -15486,7 +15487,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-nats", @@ -15576,7 +15577,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.841.0" +version = "1.849.0" dependencies = [ "async-stream", "async-trait", @@ -15611,7 +15612,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15624,7 +15625,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "argon2", @@ -15767,7 +15768,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15791,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15808,7 +15809,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -15834,7 +15835,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.841.0" +version = "1.849.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15844,7 +15845,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15861,7 +15862,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "base64 0.22.1", @@ -15883,7 +15884,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -15906,7 +15907,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15922,7 +15923,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15944,7 +15945,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15966,7 +15967,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15980,7 +15981,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-nats", @@ -16016,7 +16017,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16042,7 +16043,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16070,7 +16071,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16092,7 +16093,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16112,7 +16113,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16154,7 +16155,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16184,7 +16185,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.841.0" +version = "1.849.0" dependencies = [ "lazy_static", "serde", @@ -16196,7 +16197,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.841.0" +version = "1.849.0" dependencies = [ "argon2", "axum", @@ -16220,7 +16221,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16235,7 +16236,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.841.0" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16274,7 +16275,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.841.0" +version = "1.849.0" dependencies = [ "chrono", "lazy_static", @@ -16289,7 +16290,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16308,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.841.0" +version = "1.849.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16414,7 +16415,7 @@ dependencies = [ "url", "urlencoding", "uuid", - "webpki-roots 1.0.9", + "webpki-roots 1.0.11", "windmill-macros", "windmill-parser", "windmill-parser-py", @@ -16426,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.841.0" +version = "1.849.0" dependencies = [ "chrono", "futures", @@ -16446,7 +16447,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.841.0" +version = "1.849.0" dependencies = [ "regex", "serde", @@ -16463,7 +16464,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16490,7 +16491,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "futures", @@ -16507,7 +16508,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.841.0" +version = "1.849.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16523,7 +16524,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -16545,7 +16546,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -16576,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "arc-swap", @@ -16601,7 +16602,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-stream", @@ -16637,7 +16638,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "futures", @@ -16656,7 +16657,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.841.0" +version = "1.849.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16665,7 +16666,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16677,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -16689,7 +16690,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "gosyn", @@ -16701,7 +16702,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16713,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -16725,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "nu-parser", @@ -16736,7 +16737,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16747,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16759,7 +16760,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16770,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -16793,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -16805,7 +16806,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16819,7 +16820,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16836,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16849,7 +16850,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde", @@ -16861,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16879,7 +16880,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16895,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16912,7 +16913,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16926,7 +16927,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -16965,7 +16966,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "const_format", @@ -17003,7 +17004,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.841.0" +version = "1.849.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17014,7 +17015,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -17049,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17073,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17106,7 +17107,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17133,7 +17134,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17166,7 +17167,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17186,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17220,7 +17221,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17257,7 +17258,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17280,7 +17281,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17304,7 +17305,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-nats", @@ -17328,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17363,7 +17364,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17391,7 +17392,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17416,7 +17417,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17435,7 +17436,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-once-cell", @@ -17553,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.841.0" +version = "1.849.0" dependencies = [ "bytes", "futures", @@ -18256,9 +18257,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -18352,9 +18353,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "serde", "yoke", @@ -18364,9 +18365,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 1851f386c2..b42cac10f0 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.841.0" +version = "1.849.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.841.0" +version = "1.849.0" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 615a468f70..991ab7238e 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -1a47ebf405774527e3b79c0591897ace3e22a739 +e9eec74860968201207e710979ddbeba29bcc290 diff --git a/backend/migrations/20260824180615_variable_value_valid_until.down.sql b/backend/migrations/20260824180615_variable_value_valid_until.down.sql new file mode 100644 index 0000000000..963fd00f8e --- /dev/null +++ b/backend/migrations/20260824180615_variable_value_valid_until.down.sql @@ -0,0 +1,9 @@ +ALTER TABLE variable DROP CONSTRAINT IF EXISTS variable_oauth_no_value_expiry; +DROP INDEX IF EXISTS idx_variable_expiration_due; + +COMMENT ON COLUMN variable.expires_at IS NULL; + +ALTER TABLE variable + DROP COLUMN IF EXISTS value_valid_until, + DROP COLUMN IF EXISTS expiration_dispatched_for, + DROP COLUMN IF EXISTS expiration_notified_at; diff --git a/backend/migrations/20260824180615_variable_value_valid_until.up.sql b/backend/migrations/20260824180615_variable_value_valid_until.up.sql new file mode 100644 index 0000000000..308394d7e0 --- /dev/null +++ b/backend/migrations/20260824180615_variable_value_valid_until.up.sql @@ -0,0 +1,30 @@ +-- `value_valid_until` is when the value stored in the variable stops working; the row itself +-- lives on. `expires_at` keeps its unrelated meaning — delete the row — so no existing writer +-- changes meaning under a rolling deploy and no data is rewritten here. +ALTER TABLE variable ADD COLUMN IF NOT EXISTS value_valid_until TIMESTAMP WITH TIME ZONE; + +COMMENT ON COLUMN variable.expires_at IS + 'Garbage collection deadline: the row is deleted once passed. Set by the ephemeral secret_arg mint. Not the value''s expiry — see value_valid_until.'; +COMMENT ON COLUMN variable.value_valid_until IS + 'When the value stops working. Drives the workspace variable expiration handler; never deletes the row.'; + +-- Holds the `value_valid_until` that was dispatched, rather than a plain "was dispatched" flag, +-- so that moving the date re-arms the handler by construction — no writer has to remember to +-- clear anything. +ALTER TABLE variable + ADD COLUMN IF NOT EXISTS expiration_dispatched_for TIMESTAMP WITH TIME ZONE; + +-- When the handler last ran for this variable, which paces its reminders. +ALTER TABLE variable + ADD COLUMN IF NOT EXISTS expiration_notified_at TIMESTAMP WITH TIME ZONE; + +-- Serves the sweep's due predicate. Partial so it stays the size of the opted-in set rather +-- than the whole variable table. Not partial on `expiration_dispatched_for`: reminders keep a +-- dispatched variable due until it expires. +CREATE INDEX IF NOT EXISTS idx_variable_expiration_due ON variable (value_valid_until) + WHERE value_valid_until IS NOT NULL; + +-- An OAuth-linked value is refreshed by Windmill itself, so a rotation date on it would only +-- announce an expiry that never comes. +ALTER TABLE variable ADD CONSTRAINT variable_oauth_no_value_expiry + CHECK (account IS NULL OR value_valid_until IS NULL); diff --git a/backend/migrations/20260824180616_workspace_variable_expiration_handler.down.sql b/backend/migrations/20260824180616_workspace_variable_expiration_handler.down.sql new file mode 100644 index 0000000000..92c048bd52 --- /dev/null +++ b/backend/migrations/20260824180616_workspace_variable_expiration_handler.down.sql @@ -0,0 +1,3 @@ +ALTER TABLE workspace_settings + DROP COLUMN IF EXISTS variable_expiration_handler, + DROP COLUMN IF EXISTS variable_expiration_failed_at; diff --git a/backend/migrations/20260824180616_workspace_variable_expiration_handler.up.sql b/backend/migrations/20260824180616_workspace_variable_expiration_handler.up.sql new file mode 100644 index 0000000000..8e6cb03938 --- /dev/null +++ b/backend/migrations/20260824180616_workspace_variable_expiration_handler.up.sql @@ -0,0 +1,6 @@ +-- Shape mirrors `error_handler` / `success_handler` as grouped by 20260124172000: +-- {"path": ..., "extra_args": ..., "muted_on_user_path": ...} +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS variable_expiration_handler JSONB; + +-- When the handler last failed to start; the sweep skips the workspace for a while after it. +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS variable_expiration_failed_at TIMESTAMP WITH TIME ZONE; diff --git a/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.down.sql b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.down.sql new file mode 100644 index 0000000000..40443fc999 --- /dev/null +++ b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.down.sql @@ -0,0 +1 @@ +UPDATE folder SET extra_perms = extra_perms - 'g/variable_expiration_handler' WHERE name = 'slack_bot'; diff --git a/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.up.sql b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.up.sql new file mode 100644 index 0000000000..25adde9d36 --- /dev/null +++ b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.up.sql @@ -0,0 +1,7 @@ +-- Windmill never created this group before this release, so one present now was made by a user, +-- who would otherwise keep it as it gains read on the Slack bot token below. +DELETE FROM usr_to_group WHERE group_ = 'variable_expiration_handler'; +UPDATE group_ SET extra_perms = '{}'::jsonb WHERE name = 'variable_expiration_handler'; + +-- Backfill for slack_bot folders created before this grant (see create_slack_workspace_artifacts). +UPDATE folder SET extra_perms = JSONB_SET(extra_perms, '{g/variable_expiration_handler}', 'false', true) WHERE name = 'slack_bot'; diff --git a/backend/migrations/20261015140602_mcp_oauth_grant_without_workspace.down.sql b/backend/migrations/20261015140602_mcp_oauth_grant_without_workspace.down.sql new file mode 100644 index 0000000000..6e9587579b --- /dev/null +++ b/backend/migrations/20261015140602_mcp_oauth_grant_without_workspace.down.sql @@ -0,0 +1,18 @@ +-- A server without these scopes ignores them, which would widen every token carrying one: +-- a narrowed `mcp:all` to full access, a workspace list to all of the owner's workspaces. +DELETE FROM token WHERE EXISTS ( + SELECT 1 FROM unnest(scopes) s + WHERE s IN ('mcp:read_only', 'mcp:read_run', 'mcp:runnables_as_tools') OR s LIKE 'mcp:workspaces:%' +); +DELETE FROM mcp_oauth_refresh_token WHERE EXISTS ( + SELECT 1 FROM unnest(scopes) s + WHERE s IN ('mcp:read_only', 'mcp:read_run', 'mcp:runnables_as_tools') OR s LIKE 'mcp:workspaces:%' +); +DELETE FROM mcp_oauth_server_code WHERE EXISTS ( + SELECT 1 FROM unnest(scopes) s + WHERE s IN ('mcp:read_only', 'mcp:read_run', 'mcp:runnables_as_tools') OR s LIKE 'mcp:workspaces:%' +); +DELETE FROM mcp_oauth_server_code WHERE workspace_id IS NULL; +DELETE FROM mcp_oauth_refresh_token WHERE workspace_id IS NULL; +ALTER TABLE mcp_oauth_server_code ALTER COLUMN workspace_id SET NOT NULL; +ALTER TABLE mcp_oauth_refresh_token ALTER COLUMN workspace_id SET NOT NULL; diff --git a/backend/migrations/20261015140602_mcp_oauth_grant_without_workspace.up.sql b/backend/migrations/20261015140602_mcp_oauth_grant_without_workspace.up.sql new file mode 100644 index 0000000000..efd4bdc283 --- /dev/null +++ b/backend/migrations/20261015140602_mcp_oauth_grant_without_workspace.up.sql @@ -0,0 +1,4 @@ +-- An MCP OAuth grant can span several workspaces (listed in its scopes) or all of the +-- user's, in which case the token it mints is bound to none. +ALTER TABLE mcp_oauth_server_code ALTER COLUMN workspace_id DROP NOT NULL; +ALTER TABLE mcp_oauth_refresh_token ALTER COLUMN workspace_id DROP NOT NULL; diff --git a/backend/migrations/20261016072241_workspace_roles.down.sql b/backend/migrations/20261016072241_workspace_roles.down.sql new file mode 100644 index 0000000000..6cc9a3cbef --- /dev/null +++ b/backend/migrations/20261016072241_workspace_roles.down.sql @@ -0,0 +1,4 @@ +DROP TABLE IF EXISTS role_seat; +ALTER TABLE workspace_settings DROP COLUMN IF EXISTS role_overrides; +ALTER TABLE workspace_invite DROP COLUMN IF EXISTS workspace_role; +ALTER TABLE usr DROP COLUMN IF EXISTS workspace_role; diff --git a/backend/migrations/20261016072241_workspace_roles.up.sql b/backend/migrations/20261016072241_workspace_roles.up.sql new file mode 100644 index 0000000000..8cd96628a0 --- /dev/null +++ b/backend/migrations/20261016072241_workspace_roles.up.sql @@ -0,0 +1,68 @@ +-- A member's role by name. NULL keeps the legacy reading of `operator` (`operator` / `developer`), +-- so rows written by code that predates roles stay meaningful. +ALTER TABLE usr ADD COLUMN IF NOT EXISTS workspace_role VARCHAR(50); +ALTER TABLE workspace_invite ADD COLUMN IF NOT EXISTS workspace_role VARCHAR(50); + +-- Per-workspace role overrides, keyed by role name: `{"": {"label"?, "capabilities": {..}}}`. +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS role_overrides JSONB; + +-- The operator settings a workspace changed from their default become its override of the +-- `operator` role. Keys left at their default stay unset, so they follow the instance definition. +-- A value that is not a boolean reads as unset: one hand-edited row must not abort the upgrade. +CREATE OR REPLACE FUNCTION wm_try_bool(v TEXT) RETURNS BOOLEAN AS $$ +BEGIN + RETURN v::boolean; +EXCEPTION WHEN invalid_text_representation THEN + RETURN NULL; +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +WITH caps AS ( + SELECT workspace_id, jsonb_strip_nulls(jsonb_build_object( + 'flows', CASE WHEN wm_try_bool(operator_settings->>'builder_flows') THEN 'compose' END, + 'apps', CASE WHEN wm_try_bool(operator_settings->>'builder_apps') THEN 'compose' END, + 'manage_schedules', CASE WHEN wm_try_bool(operator_settings->>'manage_schedules') IS false THEN false END, + 'manage_triggers', CASE WHEN wm_try_bool(operator_settings->>'manage_triggers') IS false THEN false END, + 'visibility', NULLIF(jsonb_strip_nulls(jsonb_build_object( + 'runs', CASE WHEN wm_try_bool(operator_settings->>'runs') IS false THEN false END, + 'schedules', CASE WHEN wm_try_bool(operator_settings->>'schedules') IS false THEN false END, + 'resources', CASE WHEN wm_try_bool(operator_settings->>'resources') IS false THEN false END, + 'variables', CASE WHEN wm_try_bool(operator_settings->>'variables') IS false THEN false END, + 'assets', CASE WHEN wm_try_bool(operator_settings->>'assets') IS false THEN false END, + 'triggers', CASE WHEN wm_try_bool(operator_settings->>'triggers') IS false THEN false END, + 'audit_logs', CASE WHEN wm_try_bool(operator_settings->>'audit_logs') IS false THEN false END, + 'groups', CASE WHEN wm_try_bool(operator_settings->>'groups') IS false THEN false END, + 'folders', CASE WHEN wm_try_bool(operator_settings->>'folders') IS false THEN false END, + 'workers', CASE WHEN wm_try_bool(operator_settings->>'workers') IS false THEN false END + )), '{}'::jsonb) + )) AS caps + FROM workspace_settings + WHERE operator_settings IS NOT NULL AND jsonb_typeof(operator_settings) = 'object' +) +UPDATE workspace_settings ws +SET role_overrides = jsonb_build_object('operator', jsonb_build_object('capabilities', caps.caps)) +FROM caps +WHERE ws.workspace_id = caps.workspace_id AND caps.caps <> '{}'::jsonb; + +DROP FUNCTION wm_try_bool(TEXT); + +-- Whether a role costs a full (author) seat, materialized from the role configuration so billing +-- SQL needs no copy of the capability merge. `workspace_id = ''` holds the instance roles; a +-- workspace row exists only for a role that workspace overrides or adds. +CREATE TABLE IF NOT EXISTS role_seat ( + workspace_id VARCHAR(50) NOT NULL, + role VARCHAR(50) NOT NULL, + author BOOLEAN NOT NULL, + PRIMARY KEY (workspace_id, role) +); +INSERT INTO role_seat (workspace_id, role, author) +VALUES ('', 'developer', true), ('', 'operator', false) +ON CONFLICT DO NOTHING; +INSERT INTO role_seat (workspace_id, role, author) +SELECT workspace_id, + 'operator', + (role_overrides->'operator'->'capabilities'->>'flows') IS NOT NULL + OR (role_overrides->'operator'->'capabilities'->>'apps') IS NOT NULL +FROM workspace_settings +WHERE role_overrides ? 'operator' +ON CONFLICT DO NOTHING; diff --git a/backend/migrations/20261020155618_workspace_slack_signing_secret.down.sql b/backend/migrations/20261020155618_workspace_slack_signing_secret.down.sql new file mode 100644 index 0000000000..a93bfaa916 --- /dev/null +++ b/backend/migrations/20261020155618_workspace_slack_signing_secret.down.sql @@ -0,0 +1 @@ +ALTER TABLE workspace_settings DROP COLUMN IF EXISTS slack_signing_secret; diff --git a/backend/migrations/20261020155618_workspace_slack_signing_secret.up.sql b/backend/migrations/20261020155618_workspace_slack_signing_secret.up.sql new file mode 100644 index 0000000000..2bd78fa59b --- /dev/null +++ b/backend/migrations/20261020155618_workspace_slack_signing_secret.up.sql @@ -0,0 +1 @@ +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS slack_signing_secret TEXT; diff --git a/backend/migrations/20261022000335_audit_insert_policy_windmill_user.down.sql b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.down.sql new file mode 100644 index 0000000000..2e7bb84888 --- /dev/null +++ b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.down.sql @@ -0,0 +1,7 @@ +DROP POLICY IF EXISTS insert_any ON audit_partitioned; +CREATE POLICY schedule ON audit_partitioned FOR INSERT TO windmill_user + WITH CHECK ((username)::text ~~ 'schedule-%'::text); +CREATE POLICY schedule_audit ON audit_partitioned FOR INSERT TO windmill_user + WITH CHECK ((parameters ->> 'end_user'::text) ~~ 'schedule-%'::text); +CREATE POLICY webhook ON audit_partitioned FOR INSERT TO windmill_user + WITH CHECK ((username)::text ~~ 'webhook-%'::text); diff --git a/backend/migrations/20261022000335_audit_insert_policy_windmill_user.up.sql b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.up.sql new file mode 100644 index 0000000000..ab6b376663 --- /dev/null +++ b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.up.sql @@ -0,0 +1,7 @@ +-- Only the server writes audit rows, so insert policies guard nothing. They did reject rows +-- whose username is not the caller, such as a job pushed as another user by a non-admin, and +-- that failed insert aborted the caller's transaction. Reads stay restricted by `see_own`. +DROP POLICY IF EXISTS schedule ON audit_partitioned; +DROP POLICY IF EXISTS schedule_audit ON audit_partitioned; +DROP POLICY IF EXISTS webhook ON audit_partitioned; +CREATE POLICY insert_any ON audit_partitioned FOR INSERT TO windmill_user WITH CHECK (true); diff --git a/backend/migrations/20261022125411_native_trigger_connection.down.sql b/backend/migrations/20261022125411_native_trigger_connection.down.sql new file mode 100644 index 0000000000..3951ab2a64 --- /dev/null +++ b/backend/migrations/20261022125411_native_trigger_connection.down.sql @@ -0,0 +1 @@ +ALTER TABLE native_trigger DROP COLUMN IF EXISTS connection_path; diff --git a/backend/migrations/20261022125411_native_trigger_connection.up.sql b/backend/migrations/20261022125411_native_trigger_connection.up.sql new file mode 100644 index 0000000000..3b235a8d4d --- /dev/null +++ b/backend/migrations/20261022125411_native_trigger_connection.up.sql @@ -0,0 +1,24 @@ +-- Each native trigger names the connection (OAuth resource) it acts through, instead of every +-- trigger of a service sharing the single workspace connection. +ALTER TABLE native_trigger ADD COLUMN connection_path VARCHAR(255); + +-- Saving the OAuth app, or starting a connect with the instance app, used to clear +-- resource_path while the connection itself stayed. A service then had at most one connection, +-- so when exactly one is found it is the one its triggers used. +UPDATE workspace_integrations wi +SET resource_path = ( + SELECT CASE WHEN count(*) = 1 THEN min(v.path) END + FROM variable v + JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account + WHERE v.workspace_id = wi.workspace_id + AND a.client = wi.service_name::text + AND a.is_workspace_integration = true +) +WHERE wi.resource_path IS NULL; + +UPDATE native_trigger nt +SET connection_path = wi.resource_path +FROM workspace_integrations wi +WHERE wi.workspace_id = nt.workspace_id + AND wi.service_name = nt.service_name + AND wi.resource_path IS NOT NULL; diff --git a/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.down.sql b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.down.sql new file mode 100644 index 0000000000..d2f607c5b8 --- /dev/null +++ b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.down.sql @@ -0,0 +1 @@ +-- Add down migration script here diff --git a/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.up.sql b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.up.sql new file mode 100644 index 0000000000..c531389793 --- /dev/null +++ b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.up.sql @@ -0,0 +1,3 @@ +-- Secrets compared by ciphertext were cached as changed even when both sides held the same value, +-- and a cached verdict is trusted until the next write. Re-evaluate every variable row once. +UPDATE workspace_diff SET has_changes = NULL WHERE kind = 'variable'; diff --git a/backend/oauth_connect.json b/backend/oauth_connect.json index 611e3f7c17..48957fee2f 100644 --- a/backend/oauth_connect.json +++ b/backend/oauth_connect.json @@ -337,12 +337,29 @@ "auth_url": "https://www.linkedin.com/oauth/v2/authorization", "token_url": "https://www.linkedin.com/oauth/v2/accessToken", "grant_types": ["authorization_code", "client_credentials"], - "scopes": ["w_member_social", "r_liteprofile", "r_emailaddress"], + "scopes": ["openid", "profile", "email", "w_member_social"], + "scope_options": [ + "openid", + "profile", + "email", + "w_member_social", + "r_member_social", + "w_organization_social", + "r_organization_social", + "r_organization_admin", + "rw_organization_admin", + "r_ads", + "r_basicprofile" + ], "req_body_auth": true }, "quickbooks": { "auth_url": "https://appcenter.intuit.com/connect/oauth2", "token_url": "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer", + "connect_fields": { + "realmId": "callback.realmId" + }, + "resource_fields": ["realmId", "isSandBox"], "scopes": ["com.intuit.quickbooks.accounting"] }, "visma": { @@ -468,15 +485,26 @@ "docusign": { "auth_url": "https://account.docusign.com/oauth/auth", "token_url": "https://account.docusign.com/oauth/token", + "userinfo_url": "https://account.docusign.com/oauth/userinfo", + "connect_fields": { + "account_id": "userinfo.accounts[is_default=true].account_id", + "base_uri": "userinfo.accounts[is_default=true].base_uri" + }, + "resource_fields": ["account_id", "base_uri"], "scopes": ["signature"], "sandbox": { "auth_url": "https://account-d.docusign.com/oauth/auth", - "token_url": "https://account-d.docusign.com/oauth/token" + "token_url": "https://account-d.docusign.com/oauth/token", + "userinfo_url": "https://account-d.docusign.com/oauth/userinfo" } }, "salesforce": { "auth_url": "https://login.salesforce.com/services/oauth2/authorize", "token_url": "https://login.salesforce.com/services/oauth2/token", + "connect_fields": { + "instance_url": "token.instance_url" + }, + "resource_fields": ["instance_url"], "scopes": ["api", "refresh_token", "offline_access"], "sandbox": { "auth_url": "https://test.salesforce.com/services/oauth2/authorize", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index f89fa1d49a..ba2d483531 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.841.0" +version = "1.849.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.841.0" +version = "1.849.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.841.0" +version = "1.849.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.841.0" +version = "1.849.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index d6c0389840..0d0697c3fd 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.841.0" +version = "1.849.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/src/main.rs b/backend/src/main.rs index ef9961ba57..1035a0549f 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1680,12 +1680,15 @@ async fn process_notify_event( ); windmill_common::variables::CUSTOM_ENVS_CACHE.remove(payload); } - "notify_operator_settings_change" => { + // Written by the legacy operator settings mirror, always alongside a role override. + c if c == "notify_operator_settings_change" + || c == windmill_common::roles::ROLE_OVERRIDES_CHANGE_CHANNEL => + { tracing::info!( - "Operator settings change detected, invalidating operator rights cache: {}", + "Role overrides change detected, invalidating workspace roles cache: {}", payload ); - windmill_common::workspaces::invalidate_operator_rights_cache(payload); + windmill_common::roles::invalidate_workspace_roles_cache(payload); } "notify_asset_producer_change" => { tracing::debug!( @@ -2042,6 +2045,9 @@ async fn process_notify_event( DISABLE_PASSWORD_LOGIN_SETTING => { load_disable_password_login(db).await; } + windmill_common::global_settings::WORKSPACE_ROLES_SETTING => { + windmill_common::roles::invalidate_all_roles_cache(); + } MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING => { load_mcp_disable_token_query_param(db).await; } diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 827c092529..868e558f8d 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -129,6 +129,7 @@ use windmill_object_store::reload_object_store_setting; use windmill_queue::{ add_completed_job_error, cancel_job, canceled_result, get_queued_job_v2, schedule::{find_unarmed_schedules, rearm_schedule, RearmOutcome}, + variable_expiration::dispatch_expiring_variables, CanceledBy, MiniCompletedJob, SameWorkerPayload, }; use windmill_store::resources::MAX_RESOURCE_VERSIONS; @@ -441,6 +442,7 @@ pub async fn initial_load( cache_clear: None, additional_python_paths: None, pip_local_dependencies: None, + disable_job_proxy: false, native_mode, // an agent worker never reads its group's config, only its token object_store_cache_config: None, @@ -4410,6 +4412,15 @@ pub async fn monitor_db( } }; + // Run every 5 minutes (10 iterations * 30s) + let dispatch_expiring_variables_f = async { + if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(10) { + if let Some(db) = conn.as_sql() { + dispatch_expiring_variables(&db).await; + } + } + }; + // run every hour (120 iterations * 30s = 3600s) let cleanup_stale_server_heartbeats_f = async { if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(120) { @@ -4616,6 +4627,7 @@ pub async fn monitor_db( native_triggers_sync_f, cleanup_notify_events_f, check_expiring_tokens_f, + dispatch_expiring_variables_f, cleanup_stale_server_heartbeats_f, manage_audit_partitions_f, export_audit_logs_to_object_store_f, diff --git a/backend/summarized_schema.txt b/backend/summarized_schema.txt index 2bf6b0188f..418108cd30 100644 --- a/backend/summarized_schema.txt +++ b/backend/summarized_schema.txt @@ -220,7 +220,7 @@ v2_job_runtime: id(uuid), ping(ts), memory_peak(int) FK: (id) -> v2_job_queue(id) v2_job_status: id(uuid), flow_status(jsonb), flow_leaf_jobs(jsonb), workflow_as_code_status(jsonb) FK: (id) -> v2_job_queue(id) -variable: workspace_id(char), path(char), value(char), is_secret(bool), description(char), extra_perms(jsonb), account(int), is_oauth(bool), expires_at(ts), labels(text[]) +variable: workspace_id(char), path(char), value(char), is_secret(bool), description(char), extra_perms(jsonb), account(int), is_oauth(bool), expires_at(ts), labels(text[]), value_valid_until(timestamptz), expiration_dispatched_for(timestamptz), expiration_notified_at(timestamptz) FK: (workspace_id) -> workspace(id) websocket_trigger: path(char), url(char), script_path(char), is_flow(bool), workspace_id(char), edited_by(char), email(char), edited_at(ts), extra_perms(jsonb), server_id(char), last_server_ping(ts), error(text), filters(jsonb[]), initial_messages(jsonb[]), url_runnable_args(jsonb), can_return_message(bool), error_handler_path(char), error_handler_args(jsonb), retry(jsonb), can_return_error_result(bool), mode(trigger_mode), labels(text[]) windmill_migrations: name(text), created_at(ts) @@ -244,7 +244,7 @@ workspace_protection_rule: workspace_id(char), name(char), rules(int), bypass_gr FK: (workspace_id) -> workspace(id) workspace_runnable_dependencies: flow_path(char), runnable_path(char), script_hash(bigint), runnable_is_flow(bool), workspace_id(char), app_path(char), id(bigint), runnable_is_agent(bool) FK: (app_path, workspace_id) -> app(path, workspace_id) | (flow_path, workspace_id) -> flow(path, workspace_id) -workspace_settings: workspace_id(char), slack_team_id(char), slack_name(char), slack_command_script(char), slack_email(char), customer_id(char), plan(char), webhook(text), ai_config(jsonb), large_file_storage(jsonb), git_sync(jsonb), default_app(char), default_scripts(jsonb), deploy_ui(jsonb), mute_critical_alerts(bool), color(char), operator_settings(jsonb), teams_command_script(text), teams_team_id(text), teams_team_name(text), git_app_installations(jsonb), ducklake(jsonb), slack_oauth_client_id(char), slack_oauth_client_secret(char), datatable(jsonb), teams_team_guid(text), auto_invite(jsonb), error_handler(jsonb), success_handler(jsonb), public_app_execution_limit_per_minute(int), dbt_warehouses(jsonb), guest_access_enabled(bool), guest_jwt_public_key(text), guest_jwt_jwks_url(text), ai_sessions_backup_generation(int), add_admins_and_developers_to_forks(bool), remote_deploy_target(jsonb), remote_deploy_target_changed_at(ts) +workspace_settings: workspace_id(char), slack_team_id(char), slack_name(char), slack_command_script(char), slack_email(char), customer_id(char), plan(char), webhook(text), ai_config(jsonb), large_file_storage(jsonb), git_sync(jsonb), default_app(char), default_scripts(jsonb), deploy_ui(jsonb), mute_critical_alerts(bool), color(char), operator_settings(jsonb), teams_command_script(text), teams_team_id(text), teams_team_name(text), git_app_installations(jsonb), ducklake(jsonb), slack_oauth_client_id(char), slack_oauth_client_secret(char), datatable(jsonb), teams_team_guid(text), auto_invite(jsonb), error_handler(jsonb), success_handler(jsonb), public_app_execution_limit_per_minute(int), dbt_warehouses(jsonb), guest_access_enabled(bool), guest_jwt_public_key(text), guest_jwt_jwks_url(text), ai_sessions_backup_generation(int), add_admins_and_developers_to_forks(bool), remote_deploy_target(jsonb), remote_deploy_target_changed_at(ts), variable_expiration_handler(jsonb), variable_expiration_failed_at(ts) FK: (workspace_id) -> workspace(id) zombie_job_counter: job_id(uuid), counter(int) FK: (job_id) -> v2_job(id) diff --git a/backend/tests/ai_agent_linked.rs b/backend/tests/ai_agent_linked.rs new file mode 100644 index 0000000000..8b7f328213 --- /dev/null +++ b/backend/tests/ai_agent_linked.rs @@ -0,0 +1,55 @@ +use serde_json::json; +use sqlx::{Pool, Postgres}; +use std::time::Duration; +use windmill_common::{flows::FlowValue, jobs::JobPayload}; +use windmill_test_utils::{ + completed_job, in_test_worker, listen_for_completed_jobs, ApiServer, RunJob, StreamFind, +}; + +/// Only writes of an agent are checked for operators, so a linked step must refuse a path whose +/// resource is no longer an agent rather than run the `tools` it now holds. +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn linked_agent_step_refuses_a_resource_of_another_type( + db: Pool, +) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type) + VALUES ('test-workspace', 'u/test-user/agent', $1, 'object')", + ) + .bind( + json!({"tools": [{"id": "t", "value": {"tool_type": "flowmodule", + "type": "rawscript", "language": "bun", "input_transforms": {}, + "content": "export async function main() { return 1 }"}}]}), + ) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let flow: FlowValue = serde_json::from_value(json!({"modules": [{"id": "agent", "value": { + "type": "aiagent", "tools": [], "agent": "$res:u/test-user/agent", + "input_transforms": {"user_message": {"type": "static", "value": "hi"}} + }}]}))?; + let id = RunJob::from(JobPayload::RawFlow { + value: flow, + path: Some("u/test-user/linked".into()), + restarted_from: None, + }) + .push(&db) + .await; + let notifications = listen_for_completed_jobs(&db).await; + tokio::time::timeout( + Duration::from_secs(45), + in_test_worker(&db, notifications.find(&id), server.addr.port()), + ) + .await?; + let job = completed_job(id, &db).await; + server.close().await?; + assert!(!job.success); + assert!( + format!("{:?}", job.result).contains("not an AI agent"), + "{:?}", + job.result + ); + Ok(()) +} diff --git a/backend/tests/app_access_mode_only.rs b/backend/tests/app_access_mode_only.rs new file mode 100644 index 0000000000..b113e9de9a --- /dev/null +++ b/backend/tests/app_access_mode_only.rs @@ -0,0 +1,311 @@ +//! `EditApp.execution_mode`: changing who may open an app without sending its policy. +//! +//! The change is applied to the deployed policy under the row lock a deploy takes, so it keeps +//! every other field a concurrent deploy wrote. It is held to the rules a policy write is held +//! to, and it is refused to a caller who could not keep the app's run-as user, since a policy +//! write from them would rebind it. +//! +//! One test: the protection rules and the workspace roles are cached per workspace id across +//! the process, and every test here uses `test-workspace`. +//! +//! Users from the `base` fixture: +//! test-user (admin, token SECRET_TOKEN) +//! test-user-2 (non-admin, token SECRET_TOKEN_2) +//! test-user-3 (made a compose-only operator below, token SECRET_TOKEN_3) + +use reqwest::multipart; +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_common::workspaces::invalidate_protection_rules_cache; +use windmill_test_utils::*; + +const ADMIN: &str = "SECRET_TOKEN"; +const USER: &str = "SECRET_TOKEN_2"; +const BUILDER: &str = "SECRET_TOKEN_3"; + +fn client() -> reqwest::Client { + reqwest::Client::new() +} + +async fn update(ws: &str, path: &str, token: &str, body: Value) -> anyhow::Result<(u16, String)> { + let resp = client() + .post(format!("{ws}/apps/update/{path}")) + .bearer_auth(token) + .json(&body) + .send() + .await?; + Ok((resp.status().as_u16(), resp.text().await?)) +} + +async fn create(ws: &str, token: &str, path: &str, policy: Value) -> anyhow::Result<()> { + let resp = client() + .post(format!("{ws}/apps/create")) + .bearer_auth(token) + .json(&json!({ "path": path, "summary": "", "value": {}, "policy": policy })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create {path}: {}", resp.text().await?); + Ok(()) +} + +/// An anonymous, sandboxed raw app with no runnables, as a builder may deploy one. +async fn create_raw(ws: &str, token: &str, path: &str) -> anyhow::Result<()> { + let app = json!({ + "path": path, + "summary": "", + "value": { "files": {}, "runnables": {} }, + "policy": { "execution_mode": "anonymous", "sandbox": true, "triggerables_v2": {} }, + }); + let form = multipart::Form::new() + .part( + "app", + multipart::Part::text(app.to_string()).mime_str("application/json")?, + ) + .part("js", multipart::Part::text("console.log('app')")); + let resp = client() + .post(format!("{ws}/apps/create_raw")) + .bearer_auth(token) + .multipart(form) + .send() + .await?; + assert_eq!( + resp.status(), + 201, + "create_raw {path}: {}", + resp.text().await? + ); + Ok(()) +} + +async fn policy(db: &Pool, path: &str) -> anyhow::Result { + Ok(sqlx::query_scalar( + "SELECT policy FROM app WHERE path = $1 AND workspace_id = 'test-workspace'", + ) + .bind(path) + .fetch_one(db) + .await?) +} + +fn triggerable(key: &str) -> Value { + json!({ key: { "static_inputs": {}, "one_of_inputs": {} } }) +} + +#[sqlx::test(fixtures("base"))] +async fn test_access_mode_only_update(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + invalidate_protection_rules_cache("test-workspace"); + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + + // ======================================== + // 1. The mode alone changes; every other field of the deployed policy stays. + // ======================================== + const SHARED: &str = "u/test-user-2/shared"; + create( + &ws, + ADMIN, + SHARED, + json!({ + "execution_mode": "publisher", + "triggerables_v2": triggerable("c:script/u/test-user/noop"), + "sandbox": true, + "allowed_s3_keys": [{ "s3_path": "a/b.txt" }], + }), + ) + .await?; + let before = policy(&db, SHARED).await?; + assert_eq!(before["on_behalf_of"], "u/test-user"); + + let (status, body) = + update(&ws, SHARED, ADMIN, json!({ "execution_mode": "anonymous" })).await?; + assert_eq!(status, 200, "{body}"); + let mut after = policy(&db, SHARED).await?; + assert_eq!(after["execution_mode"], "anonymous"); + after["execution_mode"] = before["execution_mode"].clone(); + assert_eq!( + after, before, + "a mode-only change must keep every other policy field" + ); + + // Sending a policy too is ambiguous about which mode wins. + let (status, _) = update( + &ws, + SHARED, + ADMIN, + json!({ "execution_mode": "publisher", "policy": { "execution_mode": "anonymous" } }), + ) + .await?; + assert_eq!(status, 400); + + // ======================================== + // 2. Someone who cannot keep the run-as user cannot change the mode of an app that runs + // as someone else, even with write access to it. + // ======================================== + let (status, body) = + update(&ws, SHARED, USER, json!({ "execution_mode": "publisher" })).await?; + assert_eq!(status, 403, "{body}"); + assert!(body.contains("wm_deployers"), "{body}"); + assert_eq!(policy(&db, SHARED).await?["execution_mode"], "anonymous"); + + // ======================================== + // 3. A policy without a mode keeps the deployed one. + // ======================================== + const OWN: &str = "u/test-user-2/own"; + create(&ws, USER, OWN, json!({ "execution_mode": "publisher" })).await?; + sqlx::query( + "INSERT INTO draft (workspace_id, path, typ, value, email) + VALUES ('test-workspace', $1, 'app', '{}', 'test2@windmill.dev')", + ) + .bind(OWN) + .execute(&db) + .await?; + let (status, body) = update(&ws, OWN, USER, json!({ "execution_mode": "anonymous" })).await?; + assert_eq!(status, 200, "{body}"); + let drafts: i64 = sqlx::query_scalar( + "SELECT count(*) FROM draft WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(OWN) + .fetch_one(&db) + .await?; + assert_eq!(drafts, 1, "a mode-only change must keep the caller's draft"); + let (status, body) = update( + &ws, + OWN, + USER, + json!({ "value": { "v": 2 }, "policy": { "triggerables_v2": triggerable("c:script/f/x/new") } }), + ) + .await?; + assert_eq!(status, 200, "{body}"); + let p = policy(&db, OWN).await?; + assert_eq!(p["execution_mode"], "anonymous"); + assert!( + p["triggerables_v2"].get("c:script/f/x/new").is_some(), + "{p}" + ); + + // ======================================== + // 4. A compose-only operator: an omitted mode inherits the deployed one unless it is Viewer. + // ======================================== + sqlx::query("UPDATE usr SET operator = true WHERE workspace_id = 'test-workspace' AND username = 'test-user-3'") + .execute(&db) + .await?; + sqlx::query( + r#"UPDATE workspace_settings SET role_overrides = '{"operator": {"capabilities": {"apps": "compose"}}}' + WHERE workspace_id = 'test-workspace'"#, + ) + .execute(&db) + .await?; + // In wm_deployers, so the refusal in the last step below holds for a builder who may keep + // another user's identity on deploy. + sqlx::query( + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('test-workspace', 'wm_deployers', '', '{}')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO usr_to_group (workspace_id, group_, usr) VALUES ('test-workspace', 'wm_deployers', 'test-user-3')", + ) + .execute(&db) + .await?; + windmill_common::roles::invalidate_workspace_roles_cache("test-workspace"); + windmill_common::roles::invalidate_member_role_cache("test-workspace", "test-user-3"); + + const BUILT: &str = "u/test-user-3/built"; + create_raw(&ws, BUILDER, BUILT).await?; + + let settings_only = json!({ "policy": { "sandbox": true, "triggerables_v2": {} } }); + let (status, body) = update(&ws, BUILT, BUILDER, settings_only.clone()).await?; + assert_eq!(status, 200, "{body}"); + assert_eq!( + policy(&db, BUILT).await?["execution_mode"], + "anonymous", + "a builder's policy without a mode must keep a non-Viewer deployed mode" + ); + + // Viewer stays refused to a builder, alone as in a policy. + let (status, body) = update(&ws, BUILT, BUILDER, json!({ "execution_mode": "viewer" })).await?; + assert_eq!(status, 403, "{body}"); + + // An admin may put the builder's app in Viewer; the builder's next policy without a mode + // then cannot inherit it. + let (status, body) = update(&ws, BUILT, ADMIN, json!({ "execution_mode": "viewer" })).await?; + assert_eq!(status, 200, "{body}"); + let (status, body) = update(&ws, BUILT, BUILDER, settings_only).await?; + assert_eq!(status, 200, "{body}"); + assert_eq!(policy(&db, BUILT).await?["execution_mode"], "publisher"); + + let (status, body) = update( + &ws, + BUILT, + BUILDER, + json!({ "execution_mode": "anonymous" }), + ) + .await?; + assert_eq!( + status, 200, + "a builder may change the mode of its own app: {body}" + ); + assert_eq!(policy(&db, BUILT).await?["execution_mode"], "anonymous"); + + // A builder's deploy would sandbox an app whose policy leaves it unset, which a mode-only + // change must not do. + sqlx::query( + "UPDATE app SET policy = policy - 'sandbox' WHERE path = $1 AND workspace_id = 'test-workspace'", + ) + .bind(BUILT) + .execute(&db) + .await?; + let (status, body) = update( + &ws, + BUILT, + BUILDER, + json!({ "execution_mode": "publisher" }), + ) + .await?; + assert_eq!(status, 403, "{body}"); + let p = policy(&db, BUILT).await?; + assert!(p.get("sandbox").is_none(), "{p}"); + assert_eq!(p["execution_mode"], "anonymous"); + + // Changing the mode alone skips the check of the triggerables against the builder's RLS, so + // it stays refused on an app that runs as someone else; deploying it is the way. + const ADMIN_RUN: &str = "u/test-user-3/admin_run"; + create_raw(&ws, ADMIN, ADMIN_RUN).await?; + let (status, body) = update( + &ws, + ADMIN_RUN, + BUILDER, + json!({ "execution_mode": "publisher" }), + ) + .await?; + assert_eq!(status, 403, "{body}"); + assert!(body.contains("by deploying it"), "{body}"); + + // ======================================== + // 5. Widening is gated by the protection rule; narrowing is not. + // ======================================== + let resp = client() + .post(format!("{ws}/workspaces/protection_rules")) + .bearer_auth(ADMIN) + .json(&json!({ + "name": "no-public-apps", + "rules": ["RestrictAnonymousAppDeployment"], + "bypass_users": [], + "bypass_groups": [] + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let (status, body) = update(&ws, OWN, USER, json!({ "execution_mode": "publisher" })).await?; + assert_eq!(status, 200, "narrowing stays open: {body}"); + let (status, body) = update(&ws, OWN, USER, json!({ "execution_mode": "anonymous" })).await?; + assert_eq!(status, 403, "{body}"); + assert!(body.contains("no-public-apps"), "{body}"); + assert_eq!(policy(&db, OWN).await?["execution_mode"], "publisher"); + + Ok(()) +} diff --git a/backend/tests/app_preview_auth.rs b/backend/tests/app_preview_auth.rs index f8e90ce144..9f6e77f61c 100644 --- a/backend/tests/app_preview_auth.rs +++ b/backend/tests/app_preview_auth.rs @@ -75,12 +75,12 @@ async fn test_app_preview_authorization(db: Pool) -> anyhow::Result<() let status = resp.status(); let body = resp.text().await?; assert_eq!( - status, 401, + status, 403, "Operator must be rejected from app preview (got {status}): {body}" ); assert!( - body.contains("Operators cannot run preview jobs"), - "rejection must be the operator guard, got: {body}" + body.contains("Your role cannot run preview jobs"), + "rejection must be the role guard, got: {body}" ); // 2. The fix must NOT over-block the legitimate editor flow: a regular diff --git a/backend/tests/app_run_mode_lock_strip.rs b/backend/tests/app_run_mode_lock_strip.rs index 7a1bba75f6..77265f2bcd 100644 --- a/backend/tests/app_run_mode_lock_strip.rs +++ b/backend/tests/app_run_mode_lock_strip.rs @@ -110,10 +110,13 @@ async fn test_run_mode_strips_caller_lock_and_modules(db: Pool) -> any .json(&json!({ // The args map is the other injection channel: an inline run is a // `JobKind::Preview` job, so the worker/executors read `_MODULES` and - // `_TEMP_SCRIPT_REFS` back out of the job args. Both must be stripped. + // `_TEMP_SCRIPT_REFS` back out of the job args. Both must be stripped — + // including the NUL spellings, which `push` stores under the plain name. "args": { "_MODULES": { "m.py": { "content": "print('evil')\n", "language": "python3" } }, - "_TEMP_SCRIPT_REFS": { "../evil": "deadbeef" } + "_MODULES\u{0}": { "m.py": { "content": "print('evil')\n", "language": "python3" } }, + "_TEMP_SCRIPT_REFS": { "../evil": "deadbeef" }, + "_TEMP_SCRIPT_REFS\u{0}": { "../evil": "deadbeef" } }, "component": "comp", "raw_code": inline_raw_code(Some(CALLER_HASH), true) diff --git a/backend/tests/audit_rls.rs b/backend/tests/audit_rls.rs new file mode 100644 index 0000000000..2aca3051ab --- /dev/null +++ b/backend/tests/audit_rls.rs @@ -0,0 +1,37 @@ +//! A non-admin's transaction must accept an audit row recorded under another username, as a +//! job pushed to run as someone else writes one. A rejected insert aborts the transaction and +//! takes the caller's own write down with it. + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::ensure_today_audit_partition; + +#[sqlx::test] +async fn non_admin_writes_an_audit_row_for_another_user(db: Pool) -> anyhow::Result<()> { + ensure_today_audit_partition(&db).await; + + let mut tx = db.begin().await?; + sqlx::query("SET LOCAL ROLE windmill_user") + .execute(&mut *tx) + .await?; + sqlx::query("SELECT set_config('session.user', 'bob', true)") + .execute(&mut *tx) + .await?; + // The shape a schedule run as alice records without an Enterprise license: parameters + // redacted, so no `end_user` names the schedule. + sqlx::query( + "INSERT INTO audit_partitioned + (workspace_id, username, operation, action_kind, resource, parameters, email) + VALUES ('admins', 'alice', 'redacted', 'execute', 'EE only', '{\"redacted\": \"-\"}', 'alice@windmill.dev')", + ) + .execute(&mut *tx) + .await?; + tx.commit().await?; + + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM audit_partitioned WHERE username = 'alice'") + .fetch_one(&db) + .await?; + assert_eq!(count, 1); + Ok(()) +} diff --git a/backend/tests/caller_modules_strip.rs b/backend/tests/caller_modules_strip.rs index a65ca22d1b..bf4a096ee1 100644 --- a/backend/tests/caller_modules_strip.rs +++ b/backend/tests/caller_modules_strip.rs @@ -20,10 +20,16 @@ fn modules(v: &str) -> serde_json::Value { /// Pushes `payload` with a caller `_MODULES` both in `args` and in `extra` (where webhook /// query and headers land), and returns the stored `_MODULES`. +/// +/// Every spelling `push` stores as `_MODULES` is sent, not just the exact name: it writes +/// the args with their `\u0000` escapes removed, keys included, so `_MODULES\0` lands in +/// the job as `_MODULES` unless the removal compares the name that will be stored. async fn stored_modules(db: &Pool, payload: JobPayload) -> Option { let caller: Box = serde_json::value::to_raw_value(&modules("caller")).unwrap(); - let args = HashMap::from([("_MODULES".to_string(), caller.clone())]); - let extra = HashMap::from([("_MODULES".to_string(), caller)]); + let spellings = + || ["_MODULES", "_MODULES\0", "_MOD\0ULES"].map(|k| (k.to_string(), caller.clone())); + let args = HashMap::from(spellings()); + let extra = HashMap::from(spellings()); let (id, tx) = windmill_queue::push( db, PushIsolationLevel::IsolatedRoot(db.clone()), diff --git a/backend/tests/dedicated_workers.rs b/backend/tests/dedicated_workers.rs index d0ba3e5e63..fc4ff77bb3 100644 --- a/backend/tests/dedicated_workers.rs +++ b/backend/tests/dedicated_workers.rs @@ -843,7 +843,8 @@ mod dedicated_worker_tests { let job_a = completed_job(uuid_a, &db).await; let job_b = completed_job(uuid_b, &db).await; - assert_eq!(job_a.json_result().unwrap(), json!(105)); + // helper(5) = 50, + 100 + assert_eq!(job_a.json_result().unwrap(), json!(150)); assert_eq!(job_b.json_result().unwrap(), json!(205)); assert_ran_on_dedicated_worker(&db, uuid_a, "python3").await; assert_ran_on_dedicated_worker(&db, uuid_b, "python3").await; diff --git a/backend/tests/dependency_map.rs b/backend/tests/dependency_map.rs index dad6c86aa3..e68828fe24 100644 --- a/backend/tests/dependency_map.rs +++ b/backend/tests/dependency_map.rs @@ -511,6 +511,7 @@ def main(): ) .unwrap(), policy: None, + execution_mode: None, deployment_message: None, custom_path: None, preserve_on_behalf_of: None, diff --git a/backend/tests/fixtures/dedicated_flows.sql b/backend/tests/fixtures/dedicated_flows.sql index b3b63685df..e81cd32556 100644 --- a/backend/tests/fixtures/dedicated_flows.sql +++ b/backend/tests/fixtures/dedicated_flows.sql @@ -321,12 +321,13 @@ E'{"modules":[{"id":"a","value":{"type":"forloopflow","iterator":{"type":"javasc -- ============================================================ -- Test: Python runner group --- Two Python scripts sharing a workspace dependency annotation. +-- Two Python scripts sharing a workspace dependency annotation. Script a has a +-- relative import (helper defined below), so the group's loader.py is written. -- ============================================================ INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock, dedicated_worker) VALUES ( 'test-workspace', 'system', -E'# extra_requirements: f/system/dedicated_double\ndef main(x: int):\n return x + 100', +E'# extra_requirements: f/system/dedicated_double\nfrom .py_dedicated_helper import helper\n\ndef main(x: int):\n return helper(x) + 100', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"x":{"type":"number","description":""}},"required":["x"],"type":"object"}', '', '', 'f/system/py_rg_script_a', 300050, 'python3', '', true); diff --git a/backend/tests/git_sync_autopull_identity.rs b/backend/tests/git_sync_autopull_identity.rs index 4e7562c3f3..bc76e4c1cb 100644 --- a/backend/tests/git_sync_autopull_identity.rs +++ b/backend/tests/git_sync_autopull_identity.rs @@ -192,3 +192,25 @@ async fn unstamped_fork_pull_runs_as_the_parents_first_admin( assert_eq!(pull_identities(&db, FORK).await?, vec![identity("aaron")]); Ok(()) } + +/// A workspace with no admin and no stamp runs its pulls as an instance superadmin, skipping +/// sam, whose instance username a member holds, and the deactivated seeded superadmin. +#[sqlx::test(fixtures("git_sync_autopull_identity"))] +async fn unstamped_pull_without_admins_runs_as_a_superadmin( + db: Pool, +) -> anyhow::Result<()> { + sqlx::query("UPDATE usr SET is_admin = false WHERE workspace_id = $1") + .bind(PARENT) + .execute(&db) + .await?; + sqlx::query("UPDATE password SET disabled = true WHERE email = 'admin@windmill.dev'") + .execute(&db) + .await?; + let mut repo = repo_enabled_by("alice@windmill.dev"); + repo.auto_pull.as_mut().unwrap().enabled_by = None; + + let job = reconcile_and_enqueue_pull(&db, PARENT, &repo, "main", "abc123", None).await?; + assert!(job.is_some(), "{}", recorded_pull_error(&db, PARENT).await?); + assert_eq!(pull_identities(&db, PARENT).await?, vec![identity("sue")]); + Ok(()) +} diff --git a/backend/tests/inline_preview_auth.rs b/backend/tests/inline_preview_auth.rs index acf511c26c..231e71e92a 100644 --- a/backend/tests/inline_preview_auth.rs +++ b/backend/tests/inline_preview_auth.rs @@ -91,7 +91,7 @@ async fn operator_job_token(job_id: uuid::Uuid) -> String { .expect("mint operator job token") } -const OPERATOR_GUARD_MSG: &str = "Operators cannot run preview jobs"; +const OPERATOR_GUARD_MSG: &str = "Your role cannot run preview jobs"; /// The fixture's deployed-script jobs of the operator: one running, one queued. const RUNNING_JOB_ID: &str = "2aa0c0de-0000-4000-8000-000000000001"; diff --git a/backend/tests/pool_hold_and_wait.rs b/backend/tests/pool_hold_and_wait.rs new file mode 100644 index 0000000000..44af05ab39 --- /dev/null +++ b/backend/tests/pool_hold_and_wait.rs @@ -0,0 +1,200 @@ +//! Paths that hold a pool connection (an open transaction or an acquired connection) must not +//! wait for a second one from the same pool: a burst the size of the pool would have every +//! holder wait for another until the acquire timeout. On a one-connection pool any such second +//! checkout hangs. + +use std::time::Duration; + +use serde_json::json; +use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; +use windmill_common::{ + db::{AuthedRef, UserDB, UserDbWithAuthed}, + error::Error, + jobs::JobPayload, + worker::Connection, +}; +use windmill_test_utils::*; + +async fn one_connection_pool(db: &Pool) -> Pool { + PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(Duration::from_secs(5)) + .connect_with((*db.connect_options()).clone()) + .await + .unwrap() +} + +#[sqlx::test(fixtures("base"))] +async fn run_by_path_of_a_missing_script_uses_one_connection(db: Pool) { + let one = one_connection_pool(&db).await; + let groups = vec![]; + let folders = vec![]; + let authed = AuthedRef { + email: "test2@windmill.dev", + username: "test-user-2", + is_admin: &false, + is_operator: &false, + groups: &groups, + folders: &folders, + scopes: &None, + token_prefix: &None, + }; + let lookup = windmill_common::get_latest_deployed_hash_for_path( + Some(UserDbWithAuthed { authed: &authed, db: UserDB::new(one.clone()) }), + one.clone(), + "test-workspace", + "f/missing/script", + ); + let res = tokio::time::timeout(Duration::from_secs(15), lookup) + .await + .unwrap(); + assert!(matches!(res, Err(Error::NotFound(_))), "{:?}", res.err()); +} + +#[sqlx::test(fixtures("base"))] +async fn for_loop_flow_runs_on_one_connection(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let flow = serde_json::from_value(json!({ + "modules": [{ + "id": "loop", + "value": { + "type": "forloopflow", + "iterator": { "type": "static", "value": [1, 2] }, + "skip_failures": false, + "parallel": false, + "modules": [{ "id": "inner", "value": { "type": "identity" } }] + } + }] + }))?; + let job = RunJob::from(JobPayload::RawFlow { value: flow, path: None, restarted_from: None }) + .push(&db) + .await; + + let one = one_connection_pool(&db).await; + let db2 = db.clone(); + in_test_worker( + Connection::Sql(one), + async move { + while sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM v2_job_completed WHERE id = $1)", + ) + .bind(job) + .fetch_one(&db2) + .await + .unwrap() + == false + { + tokio::time::sleep(Duration::from_millis(100)).await; + } + }, + server.addr.port(), + ) + .await; + + let status: String = + sqlx::query_scalar("SELECT status::text FROM v2_job_completed WHERE id = $1") + .bind(job) + .fetch_one(&db) + .await?; + assert_eq!(status, "success"); + Ok(()) +} + +#[cfg(all(feature = "enterprise", feature = "private"))] +#[sqlx::test(fixtures("base", "schedule"))] +async fn schedule_handlers_run_on_one_connection(db: Pool) -> anyhow::Result<()> { + use windmill_queue::{add_completed_job, get_mini_completed_job}; + + const SCHEDULE: &str = "f/system/handled_schedule"; + const HANDLER: &str = "script/f/system/schedule_recovery_handler"; + sqlx::query( + "INSERT INTO schedule (workspace_id, path, edited_by, schedule, enabled, script_path, args, + is_flow, email, timezone, permissioned_as, on_success, on_recovery) + VALUES ('test-workspace', $1, 'test-user', '0 0 0 1 1 *', true, 'f/system/failing_script', + '{}', false, 'test@windmill.dev', 'UTC', 'u/test-user', $2, $2)", + ) + .bind(SCHEDULE) + .bind(HANDLER) + .execute(&db) + .await?; + + // The previous occurrence failed, so this successful one is a recovery. The handlers run + // once the completion has committed, when the next tick may already have completed: a + // later occurrence must not count as history, or its success would hide the recovery. + let insert_job = + "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, trigger, trigger_kind) + VALUES ($1, 'test-workspace', 'test-user', now() - $2 * interval '1 minute', 'u/test-user', + 'test@windmill.dev', 'script', 12349, 'f/system/failing_script', 'bun', 'bun', true, + $3, 'schedule')"; + for (minutes_ago, status) in [(1.0, "failure"), (-1.0, "success")] { + let id = uuid::Uuid::new_v4(); + sqlx::query(insert_job) + .bind(id) + .bind(minutes_ago) + .bind(SCHEDULE) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_completed (id, workspace_id, duration_ms, result, started_at, + completed_at, status) + VALUES ($1, 'test-workspace', 1, '{}', now(), now(), $2::job_status)", + ) + .bind(id) + .bind(status) + .execute(&db) + .await?; + } + + let running = uuid::Uuid::new_v4(); + sqlx::query(insert_job) + .bind(running) + .bind(0.0) + .bind(SCHEDULE) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, started_at, tag) + VALUES ($1, 'test-workspace', now(), true, now(), 'bun')", + ) + .bind(running) + .execute(&db) + .await?; + sqlx::query("INSERT INTO v2_job_runtime (id, ping) VALUES ($1, now())") + .bind(running) + .execute(&db) + .await?; + + let one = one_connection_pool(&db).await; + let job = get_mini_completed_job(&running, "test-workspace", &db) + .await? + .unwrap(); + let result = json!("OK"); + let complete = add_completed_job( + &one, + &job, + true, + false, + sqlx::types::Json(&result), + None, + 0, + None, + false, + None, + false, + ); + tokio::time::timeout(Duration::from_secs(30), complete).await??; + + // One on_success job and one on_recovery job. + let handlers: i64 = sqlx::query_scalar( + "SELECT count(*) FROM v2_job WHERE runnable_path = 'f/system/schedule_recovery_handler' + AND parent_job = $1", + ) + .bind(running) + .fetch_one(&db) + .await?; + assert_eq!(handlers, 2); + Ok(()) +} diff --git a/backend/tests/push_pool_connections.rs b/backend/tests/push_pool_connections.rs new file mode 100644 index 0000000000..006340cf8a --- /dev/null +++ b/backend/tests/push_pool_connections.rs @@ -0,0 +1,63 @@ +//! `push` must not need a second pool connection while it holds its transaction: a burst of +//! pushes the size of the pool would each hold one and wait for another until the acquire +//! timeout. On a one-connection pool any such second checkout hangs. + +use std::time::Duration; + +use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; +use windmill_common::jobs::JobPayload; +use windmill_test_utils::RunJob; + +#[sqlx::test(fixtures("base"))] +async fn concurrency_limited_flow_pushes_on_one_connection(db: Pool) { + // The flow and settings caches outlive the test database (they are on disk), so only a + // version and a limit no run has used yet make `push` read the flow and write its settings. + let limit = (uuid::Uuid::new_v4().as_u128() % 1_000_000_000) as i32 + 1; + let version = limit as i64; + let value = format!(r#"{{"modules":[],"concurrent_limit":{limit}}}"#); + sqlx::query( + "WITH f AS ( + INSERT INTO flow (workspace_id, path, summary, description, value, edited_by, schema, extra_perms, versions) + VALUES ('test-workspace', 'f/t/limited', '', '', $1::jsonb, 'test-user', '{}', '{}', ARRAY[$2]) + ) + INSERT INTO flow_version (id, workspace_id, path, value, schema, created_by) + VALUES ($2, 'test-workspace', 'f/t/limited', $1::jsonb, '{}', 'test-user')", + ) + .bind(&value) + .bind(version) + .execute(&db) + .await + .unwrap(); + + let one = PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(Duration::from_secs(5)) + .connect_with((*db.connect_options()).clone()) + .await + .unwrap(); + + let push = RunJob::from(JobPayload::Flow { + path: "f/t/limited".to_string(), + dedicated_worker: None, + apply_preprocessor: false, + version, + labels: None, + job_token_scopes: None, + }) + .push(&one); + let job = tokio::time::timeout(Duration::from_secs(15), push) + .await + .unwrap(); + + let stored: Option = sqlx::query_scalar( + "SELECT cs.concurrent_limit FROM v2_job_queue q + JOIN runnable_settings rs ON rs.hash = q.runnable_settings_handle + JOIN concurrency_settings cs ON cs.hash = rs.concurrency_settings + WHERE q.id = $1", + ) + .bind(job) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored, Some(limit)); +} diff --git a/backend/tests/reserved_control_args.rs b/backend/tests/reserved_control_args.rs new file mode 100644 index 0000000000..a733546e51 --- /dev/null +++ b/backend/tests/reserved_control_args.rs @@ -0,0 +1,436 @@ +//! `_ENTRYPOINT_OVERRIDE`, `_MODULES` and `_TEMP_SCRIPT_REFS` steer *how* a runnable runs: +//! which function the worker calls instead of `main`, what module files land in the job +//! directory, where its workspace imports resolve from. They are legitimate for a caller +//! running its own code under its own identity, and must not be settable by a third party +//! whose payload runs under somebody else's: an HTTP route body or native trigger message +//! (the job runs as the trigger's owner) and a public app viewer's inputs (as the +//! publisher). +//! +//! `push` stores the args with their `\u0000` escapes removed, keys included, so every +//! check also has to hold for a NUL-spelled key: `_ENTRYPOINT_OVERRIDE\0` is read back as +//! `_ENTRYPOINT_OVERRIDE`. The same rename is what lets a viewer's `tenant\0` land as +//! `tenant` over an app policy's pinned `tenant`. + +use std::collections::HashMap; + +use serde_json::{json, value::RawValue, Value}; +use sqlx::{Pool, Postgres}; +use windmill_common::{ + jobs::JobPayload, + runnable_settings::{ConcurrencySettings, DebouncingSettings}, + scripts::{ScriptHash, ScriptLang}, + triggers::TriggerMetadata, +}; +use windmill_queue::{PushArgs, PushArgsOwned, PushIsolationLevel}; +use windmill_test_utils::*; + +const SCRIPT_PATH: &str = "f/system/hello"; +const SCRIPT_HASH: i64 = 123412; +/// Two top-level functions, as in the report: `main` authenticates, `apply` acts. +const SCRIPT_CONTENT: &str = "export async function main(data: string) { return data }\n\ + export async function apply(action: string) { return action }\n"; + +fn client() -> reqwest::Client { + reqwest::Client::new() +} + +fn authed(b: reqwest::RequestBuilder, token: &str) -> reqwest::RequestBuilder { + b.header("Authorization", format!("Bearer {}", token)) +} + +fn raw(v: Value) -> Box { + serde_json::value::to_raw_value(&v).unwrap() +} + +fn modules() -> Value { + json!({ "bunfig.toml": { "content": "preload = [\"./x.ts\"]", "language": "bun" } }) +} + +/// Deploy `SCRIPT_PATH` (a non-null `lock` is what makes a script count as deployed). +async fn deploy_script(db: &Pool) -> anyhow::Result<()> { + sqlx::query( + r#"INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, + schema, summary, description, lock) + VALUES ('test-workspace', $1, $2, $3, 'bun', 'script', 'test-user', '{}', '', '', + E'{}\n//bun.lock\n')"#, + ) + .bind(SCRIPT_HASH) + .bind(SCRIPT_PATH) + .bind(SCRIPT_CONTENT) + .execute(db) + .await?; + Ok(()) +} + +async fn job_args_and_entrypoint( + db: &Pool, + id: uuid::Uuid, +) -> anyhow::Result<(Value, Option)> { + Ok( + sqlx::query_as("SELECT args, script_entrypoint_override FROM v2_job WHERE id = $1") + .bind(id) + .fetch_one(db) + .await?, + ) +} + +fn trigger_authed() -> windmill_api_auth::ApiAuthed { + windmill_api_auth::ApiAuthed { + email: "test@windmill.dev".to_string(), + username: "test-user".to_string(), + is_admin: true, + is_operator: false, + groups: vec![], + folders: vec![], + scopes: None, + username_override: None, + username_override_is_token_label: false, + is_session_token: false, + token_prefix: None, + read_only: false, + job_id: None, + credential_expiry: None, + } +} + +/// `trigger_runnable_inner` is the one funnel every trigger reaches `push` through, so it +/// stands in here for the HTTP route whose body keys become the job's top-level args. The +/// sender is anonymous on a `none`/`custom_script` route; the job runs as the route owner. +#[sqlx::test(fixtures("base"))] +async fn trigger_args_lose_every_reserved_control_key(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + deploy_script(&db).await?; + + let args = PushArgsOwned { + args: HashMap::from([ + // Picks `apply` instead of `main`, skipping whatever `main` authenticates. + ("_ENTRYPOINT_OVERRIDE".to_string(), raw(json!("apply"))), + ("_ENTRYPOINT_OVERRIDE\u{0}".to_string(), raw(json!("apply"))), + ("_ENTRY\u{0}POINT_OVERRIDE".to_string(), raw(json!("apply"))), + ("_MODULES\u{0}".to_string(), raw(modules())), + ( + "_TEMP_SCRIPT_REFS\u{0}".to_string(), + raw(json!({ "f/system/dep": "deadbeef" })), + ), + // An ordinary input must still get through, NUL-renamed or not. + ("data".to_string(), raw(json!("payload"))), + ("action\u{0}".to_string(), raw(json!("refund"))), + ]), + extra: None, + }; + + let (id, _, _, _, _) = windmill_trigger::trigger_helpers::trigger_runnable_inner( + &db, + None, + None, + trigger_authed(), + "test-workspace", + SCRIPT_PATH, + false, + args, + None, + None, + None, + "u/test-user/route".to_string(), + None, + TriggerMetadata::new( + Some("u/test-user/route".to_string()), + windmill_common::jobs::JobTriggerKind::Http, + ), + None, + ) + .await?; + + let (args, entrypoint) = job_args_and_entrypoint(&db, id).await?; + assert_eq!( + args, + json!({ "data": "payload", "action": "refund" }), + "a trigger payload may carry the runnable's inputs and nothing that steers how it runs" + ); + assert_eq!( + entrypoint, None, + "a trigger payload must not pick the function the worker calls instead of `main`" + ); + Ok(()) +} + +/// The counterpart: `_ENTRYPOINT_OVERRIDE` stays for a caller that runs the script under +/// its own identity with `jobs:run` — the script editor's preprocessor test, dynamic-select +/// helpers, the CLI and workflow-as-code all send it this way (GHSA-wxjq-w5pj-jqhx bounds +/// what it may contain, not who may set it). Stripping it in `push` would break them. +#[sqlx::test(fixtures("base"))] +async fn an_authenticated_push_keeps_the_entrypoint_override( + db: Pool, +) -> anyhow::Result<()> { + deploy_script(&db).await?; + + // Both spellings: `push` normalizes the names to what it stores, so the NUL-spelled one + // selects the function exactly like the plain one instead of being silently different. + for key in ["_ENTRYPOINT_OVERRIDE", "_ENTRYPOINT_OVERRIDE\u{0}"] { + let args = HashMap::from([ + (key.to_string(), raw(json!("apply"))), + ("action".to_string(), raw(json!("refund"))), + ]); + let (id, tx) = windmill_queue::push( + &db, + PushIsolationLevel::IsolatedRoot(db.clone()), + "test-workspace", + JobPayload::ScriptHash { + hash: ScriptHash(SCRIPT_HASH), + path: SCRIPT_PATH.to_string(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + language: ScriptLang::Bun, + priority: None, + apply_preprocessor: false, + concurrency_settings: ConcurrencySettings::default(), + debouncing_settings: DebouncingSettings::default(), + labels: None, + job_token_scopes: None, + }, + PushArgs { args: &args, extra: None }, + "test-user", + "test@windmill.dev", + "u/test-user".to_string(), + None, + None, + None, + None, + None, + None, + None, + None, + false, + false, + None, + true, + None, + None, + None, + None, + None, + false, + None, + None, + None, + None, + ) + .await?; + tx.commit().await?; + let (args, entrypoint) = job_args_and_entrypoint(&db, id).await?; + assert_eq!( + entrypoint.as_deref(), + Some("apply"), + "an authenticated caller running a script as itself may still pick the entrypoint \ + (sent as {key:?})" + ); + assert_eq!( + args, + json!({ "_ENTRYPOINT_OVERRIDE": "apply", "action": "refund" }), + "the stored name is the normalized one (sent as {key:?})" + ); + } + Ok(()) +} + +/// Create a public (anonymous) app whose single component is the deployed script, with the +/// given policy inputs, and return its path. +async fn create_public_app( + ws: &str, + path: &str, + static_inputs: Value, + one_of_inputs: Value, +) -> anyhow::Result<()> { + let resp = authed(client().post(format!("{ws}/apps/create")), "SECRET_TOKEN") + .json(&json!({ + "path": path, + "summary": "", + "value": {}, + "policy": { + "execution_mode": "anonymous", + "triggerables_v2": { + format!("comp:script/{SCRIPT_PATH}"): { + "static_inputs": static_inputs, + "one_of_inputs": one_of_inputs, + } + } + } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create app: {}", resp.text().await?); + Ok(()) +} + +/// A viewer of a public app runs the publisher's pinned script as the publisher: it may +/// fill in the inputs the policy leaves free and nothing else. +#[sqlx::test(fixtures("base"))] +async fn public_app_viewer_cannot_steer_the_pinned_runnable( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + deploy_script(&db).await?; + + let app_path = "u/test-user/reserved_args"; + create_public_app( + &ws, + app_path, + json!({ "tenant": "acme" }), + json!({ "greeting": ["Hello,", "Bonjour,"] }), + ) + .await?; + + // No `Authorization` header at all: the anonymous visitor of a public app. + let run = |args: &'static str| { + client() + .post(format!("{ws}/apps_u/execute_component/{app_path}")) + .header("content-type", "application/json") + .body(format!( + r#"{{"component": "comp", "path": "script/{SCRIPT_PATH}", "args": {args}}}"# + )) + .send() + }; + + // A name spelled with a NUL is the same name once stored, so the policy's pinned value + // must still win and the one-of list must still be enforced. + let resp = run(r#"{"tenant\u0000": "globex", "greeting": "Hello,"}"#).await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 200, "run must be accepted: {body}"); + let (args, _) = job_args_and_entrypoint(&db, uuid::Uuid::parse_str(body.trim())?).await?; + assert_eq!( + args["tenant"], + json!("acme"), + "a NUL-renamed arg must not override an input the policy pins: {args}" + ); + + let resp = run(r#"{"greeting\u0000": "anything"}"#).await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!( + status, 400, + "a NUL-renamed arg must still be held to the policy's one_of list: {body}" + ); + assert!( + body.contains("must be one of"), + "expected the one_of rejection, got: {body}" + ); + + // The control keys, in both spellings, in one request. + let resp = run( + r#"{"_ENTRYPOINT_OVERRIDE": "apply", "_ENTRYPOINT_OVERRIDE\u0000": "apply", + "_MODULES": {"bunfig.toml": {"content": "x", "language": "bun"}}, + "_MODULES\u0000": {"bunfig.toml": {"content": "x", "language": "bun"}}, + "_TEMP_SCRIPT_REFS": {"f/system/dep": "deadbeef"}, + "_TEMP_SCRIPT_REFS\u0000": {"f/system/dep": "deadbeef"}, + "greeting": "Hello,"}"#, + ) + .await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 200, "run must be accepted: {body}"); + let (args, entrypoint) = + job_args_and_entrypoint(&db, uuid::Uuid::parse_str(body.trim())?).await?; + assert_eq!( + entrypoint, None, + "a viewer must not pick the function the worker calls instead of `main`" + ); + assert_eq!( + args, + json!({ "tenant": "acme", "greeting": "Hello," }), + "only the policy's pinned input and the viewer's allowed one may reach the job: {args}" + ); + Ok(()) +} + +/// A deployed flow's dynamic-select code has no deployed runnable, so it is queued as a +/// `JobKind::Preview` job — the one kind on which the bun and python executors honor +/// `_TEMP_SCRIPT_REFS` and resolve the code's workspace imports from the temporary script +/// store, which any workspace member can write. The caller of this route only fills in that +/// code's inputs (it may be an operator, who is refused `jobs/run/preview` outright), so the +/// key must not reach the job, in either spelling. +#[sqlx::test(fixtures("base"))] +async fn flow_dynamic_select_strips_caller_control_args(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + + // Someone else's flow: `test-user-2` below can run it, not edit it. + let flow_path = "u/test-user/dynselect_control_args"; + let resp = authed(client().post(format!("{ws}/flows/create")), "SECRET_TOKEN") + .json(&json!({ + "path": flow_path, + "summary": "", + "description": "", + "value": { "modules": [] }, + "schema": { + "type": "object", + "properties": { "region": { "type": "object", "format": "dynselect-region" } }, + "x-windmill-dyn-select-lang": "bun", + "x-windmill-dyn-select-code": + "import { regions } from \"/f/system/regions\"\n\ + export async function region() { return regions() }\n" + } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create flow: {}", resp.text().await?); + + // Read-only for the caller below: running the dyn-select code is all it may do. + sqlx::query( + "UPDATE flow SET extra_perms = '{\"u/test-user-2\": false}' + WHERE path = $1 AND workspace_id = 'test-workspace'", + ) + .bind(flow_path) + .execute(&db) + .await?; + + let refs = json!({ "f/system/regions": "deadbeef" }); + let modules = json!({ "regions.ts": { "content": "export const v = 1", "language": "bun" } }); + let resp = authed( + client().post(format!("{ws}/jobs/run/dynamic_select")), + "SECRET_TOKEN_2", + ) + .json(&json!({ + "entrypoint_function": "region", + "runnable_ref": { "source": "deployed", "path": flow_path, "runnable_kind": "flow" }, + "args": { + "_TEMP_SCRIPT_REFS": refs, + "_TEMP_SCRIPT_REFS\u{0}": refs, + "_MODULES": modules, + "_MODULES\u{0}": modules, + "filterText": "eu" + } + })) + .send() + .await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 201, "dynamic select must be accepted: {body}"); + + let id = uuid::Uuid::parse_str(body.trim())?; + let kind: String = sqlx::query_scalar("SELECT kind::text FROM v2_job WHERE id = $1") + .bind(id) + .fetch_one(&db) + .await?; + assert_eq!( + kind, "preview", + "the premise of this test: a deployed flow's dyn-select code runs as a preview job" + ); + let (args, _) = job_args_and_entrypoint(&db, id).await?; + assert_eq!( + args, + json!({ "_ENTRYPOINT_OVERRIDE": "region", "filterText": "eu" }), + "only the caller's inputs and the server-set entrypoint may reach the job" + ); + Ok(()) +} diff --git a/backend/tests/untrusted_interpolation.rs b/backend/tests/untrusted_interpolation.rs new file mode 100644 index 0000000000..2171797e18 --- /dev/null +++ b/backend/tests/untrusted_interpolation.rs @@ -0,0 +1,441 @@ +//! Handler, public-app and agent tool jobs run with more rights than whoever wrote some of their +//! arguments, so nothing in those arguments may be resolved by the worker with the job's identity. + +use axum::{routing::post, Json as AxumJson, Router}; +use serde_json::{json, value::RawValue, Value}; +use sqlx::{types::Json, Pool, Postgres}; +use std::time::Duration; +use uuid::Uuid; +use windmill_common::{flows::FlowValue, jobs::JobPayload}; +use windmill_test_utils::*; + +const SECRET: &str = "s3cr3t-value"; +const ENV_SECRET: &str = "env-s3cr3t"; +const READERS: &str = + r#"{"g/error_handler": false, "g/success_handler": false, "g/publishers": false}"#; + +async fn seed(db: &Pool) -> anyhow::Result<()> { + // Every test of this file is serial: the workspace env cache is process-wide. + sqlx::query( + "INSERT INTO workspace_env (workspace_id, name, value) VALUES ('test-workspace', 'API_KEY', $1)", + ) + .bind(ENV_SECRET) + .execute(db) + .await?; + windmill_common::variables::CUSTOM_ENVS_CACHE.remove("test-workspace"); + // How an app run as its publisher reads a secret: through the publisher's groups. + sqlx::query( + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) + VALUES ('test-workspace', 'publishers', '', '{}')", + ) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO usr_to_group (workspace_id, group_, usr) + VALUES ('test-workspace', 'publishers', 'test-user')", + ) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms) + VALUES ('test-workspace', 'u/test-user/secret', $1, false, '', $2::jsonb)", + ) + .bind(format!("\"{SECRET}\"")) + .bind(READERS) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO resource_type (workspace_id, name, schema, description, created_by) + VALUES ('test-workspace', 'c_cfg', '{}', '', 'test-user')", + ) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', 'u/test-user/cfg', '{\"set_by\": \"admin\"}', 'c_cfg', $1::jsonb, + 'test-user')", + ) + .bind(READERS) + .execute(db) + .await?; + // The lock must be non-null for the script to count as deployed. + sqlx::query( + r#"INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, + summary, description, lock) + VALUES ('test-workspace', 1234, 'f/handlers/h', $1, 'bun', 'script', 'test-user', '{}', + '', '', E'{}\n//bun.lock\n')"#, + ) + .bind( + "export async function main(error: any, cfg: any, success_result: any, pipeline: any, + price: any, note: any, leak: any, log: any) { + return { error, cfg, success_result, pipeline, price, note, leak, log }; + }", + ) + .execute(db) + .await?; + Ok(()) +} + +async fn run(db: &Pool, port: u16, id: Uuid) -> Value { + let done = listen_for_completed_jobs(db).await.find(&id); + tokio::time::timeout(Duration::from_secs(60), in_test_worker(db, done, port)) + .await + .expect("job did not complete"); + let job = completed_job(id, db).await; + assert!(job.success, "{:?}", job.result); + job.json_result().unwrap() +} + +fn assert_omitted(v: &Value) { + let s = v.as_str().unwrap_or_default(); + assert!( + s.starts_with("The following variable has been omitted for security reasons"), + "{v}" + ); +} + +/// What a failed job sends its handler: references in its error, and the `$WM_TOKEN` the worker +/// replaces with the handler's token in an argument that holds one. +fn failed_result() -> Box { + // Raw text: a number survives only if nothing on the way parses it. + RawValue::from_string( + r#"{"error": {"message": "$var:u/test-user/secret", "name": "$WM_TOKEN", + "stack": "$jsonvar:u/test-user/secret"}, + "meta": {"code": 1.10, "id": 18446744073709551617}, "log": "a\u0000b"}"# + .to_string(), + ) + .unwrap() +} + +fn extra_args() -> Json> { + Json(serde_json::value::to_raw_value(&json!({"cfg": "$res:u/test-user/cfg"})).unwrap()) +} + +/// Stored as jsonb stores it: numbers exact, the NUL jsonb refuses stripped. +async fn assert_handled(db: &Pool, port: u16, id: Uuid) -> Value { + let stored: String = sqlx::query_scalar("SELECT args::text FROM v2_job WHERE id = $1") + .bind(id) + .fetch_one(db) + .await + .unwrap(); + assert!( + stored.contains("1.10") && stored.contains("18446744073709551617"), + "{stored}" + ); + let out = run(db, port, id).await; + assert_eq!(out["log"], json!("ab")); + assert!(!out.to_string().contains(SECRET), "{out}"); + for k in ["message", "name", "stack"] { + assert_omitted(&out["error"][k]); + } + // The handler's own settings, written by an admin. + assert_eq!(out["cfg"], json!({"set_by": "admin"})); + out +} + +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn error_handler_resolves_nothing_the_failed_job_wrote( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + seed(&db).await?; + let id = windmill_queue::push_error_handler( + &db, + Uuid::new_v4(), + None, + Some("u/test-user/failing".to_string()), + false, + "test-workspace", + "script/f/handlers/h", + Json(&failed_result()), + None, + None, + Some(extra_args()), + "test@windmill.dev", + None, + false, + None, + ) + .await?; + assert_handled(&db, server.addr.port(), id).await; + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn success_handler_resolves_nothing_the_job_returned( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + seed(&db).await?; + let result = json!({ + "pipeline": [{"$match": {"currency": "$USD", "$or": [{"a": "$category"}]}}], + "price": "$10.00", + "note": "cost $var:u/test-user/secret", + "leak": "\u{24}jsonvar:u/test-user/secret", + }); + let id = windmill_queue::push_success_handler( + &db, + Uuid::new_v4(), + None, + Some("u/test-user/succeeding".to_string()), + false, + "test-workspace", + "script/f/handlers/h", + Json(&result), + None, + Some(extra_args()), + "test@windmill.dev", + None, + ) + .await?; + let out = run(&db, server.addr.port(), id).await; + assert_omitted(&out["leak"]); + // Holds the prefix that makes the worker interpolate the whole argument. + assert!(out["note"] + .as_str() + .unwrap() + .starts_with("cost The following variable")); + for k in ["pipeline", "price"] { + assert_eq!(out[k], result[k], "{k}"); + } + assert_eq!(out["cfg"], json!({"set_by": "admin"})); + Ok(()) +} + +#[cfg(all(feature = "enterprise", feature = "private"))] +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn recovery_handler_resolves_nothing_the_schedule_jobs_wrote( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + seed(&db).await?; + let job_id = Uuid::new_v4(); + let failed = failed_result(); + let success = json!({"leak": "$var:u/test-user/secret", "ok": {"$match": "$USD"}}); + windmill_queue::jobs_ee::handle_recovered_schedule( + &db, + job_id, + "u/test-user/schedule", + "u/test-user/flaky", + false, + "test-workspace", + "script/f/handlers/h", + Some(&failed), + sqlx::types::chrono::Utc::now(), + Json(&success), + 1, + sqlx::types::chrono::Utc::now(), + Some(extra_args()), + "u/test-user", + ) + .await?; + let id: Uuid = sqlx::query_scalar("SELECT id FROM v2_job WHERE parent_job = $1") + .bind(job_id) + .fetch_one(&db) + .await?; + let out = assert_handled(&db, server.addr.port(), id).await; + assert_omitted(&out["success_result"]["leak"]); + assert_eq!(out["success_result"]["ok"], success["ok"]); + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn public_app_resolves_nothing_the_viewer_sent(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + seed(&db).await?; + let content = "export function main(a: any, b: any, c: any, d: any) { return { a, b, c, d } }"; + let ws = format!("http://localhost:{port}/api/w/test-workspace"); + let client = reqwest::Client::new(); + let resp = client + .post(format!("{ws}/apps/create")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ + "path": "u/test-user/app", + "summary": "", + "value": {"runnables": {"c": {"type": "inline", + "inlineScript": {"language": "bun", "content": content}}}}, + "policy": {"execution_mode": "anonymous", "triggerables_v2": { + format!("c:rawscript/{}", windmill_common::utils::calculate_hash(content)): + {"static_inputs": {}, "one_of_inputs": {}} + }}, + })) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + // `\u0024` passes a text match on `$var:` until jsonb decodes it. + let body = r#"{"component": "c", + "raw_code": {"language": "bun", "content": "CONTENT"}, + "args": {"a": "\u0024var:u/test-user/secret", "b": {"x": ["$jsonvar:u/test-user/secret"]}, + "c": {"pipeline": [{"$match": {"currency": "$USD"}}]}, + "d": {"key": "$API_KEY", "note": "cost $var:x"}}}"# + .replace("CONTENT", content); + let resp = client + .post(format!("{ws}/apps_u/execute_component/u/test-user/app")) + .bearer_auth("SECRET_TOKEN_2") + .header("content-type", "application/json") + .body(body) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + let id: Uuid = resp.text().await?.parse()?; + let out = run(&db, port, id).await; + assert!(!out.to_string().contains(SECRET), "{out}"); + assert!(!out.to_string().contains(ENV_SECRET), "{out}"); + assert_omitted(&out["a"]); + assert_omitted(&out["b"]["x"][0]); + assert_eq!( + out["c"], + json!({"pipeline": [{"$match": {"currency": "$USD"}}]}) + ); + assert_eq!(out["d"]["key"], json!("$API_KEY")); + Ok(()) +} + +/// Read as the jsonb args column holds it: whatever the worker's own test finds in the stored text, +/// the check finds too, and nothing more. +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn reads_an_argument_as_jsonb_stores_it(db: Pool) -> anyhow::Result<()> { + use windmill_common::{utils::strip_json_nul, variables::*}; + for arg in [ + r#""\u0024var:x""#, + r#""$va\u0072:x""#, + r#""$va\\u0072:x""#, + r#""$va\u0000r:x""#, + r#""\ud800 $var:x""#, + r#"{"a": "\u0024res:x", "a": "ok"}"#, + r#"{"a": "ok", "a": "\u0024var:x"}"#, + r#"{"n": 1e400, "n": 0, "r": "\u0024var:x"}"#, + r#"{"\u0024encrypted:k": 1}"#, + r#""cost \u0024var:x""#, + r#"{"$match": {"c": "$USD"}, "p": 1.10}"#, + r#""$10.00""#, + ] { + let stored: Option = match sqlx::query_scalar("SELECT $1::jsonb::text") + .bind(strip_json_nul(arg).as_ref()) + .fetch_one(&db) + .await + { + Ok(s) => Some(s), + Err(sqlx::Error::Database(e)) if e.code().as_deref() == Some("22P02") => None, + Err(e) => return Err(e.into()), + }; + assert_eq!( + untrusted_arg_interpolates(arg), + stored.as_deref().map_or(true, arg_needs_interpolation), + "{arg} stored as {stored:?}" + ); + } + Ok(()) +} + +/// One tool call with `arguments`, then a final answer once the tool's reply is in. +fn model(arguments: &'static str) -> Router { + Router::new().route( + "/v1/chat/completions", + post(move |AxumJson(body): AxumJson| async move { + let answered = body["messages"] + .as_array() + .unwrap() + .iter() + .any(|m| m["role"] == "tool"); + let delta = if answered { + json!({"role": "assistant", "content": "done"}) + } else { + json!({"role": "assistant", "tool_calls": [{"index": 0, "id": "call_0", + "type": "function", "function": {"name": "echo", "arguments": arguments}}]}) + }; + let event = json!({"choices": [{"index": 0, "delta": delta, "finish_reason": null}]}); + let end = json!({"choices": [{"index": 0, "delta": {}, + "finish_reason": if answered {"stop"} else {"tool_calls"}}]}); + ( + [("content-type", "text/event-stream")], + format!("data: {event}\n\ndata: {end}\n\ndata: [DONE]\n\n"), + ) + }), + ) +} + +/// What the tool replied to the model. +async fn tool_reply(db: &Pool, port: u16, arguments: &'static str) -> String { + std::env::set_var("ALLOW_PRIVATE_AI_BASE_URLS", "true"); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let stub = tokio::spawn(async move { axum::serve(listener, model(arguments)).await }); + let flow: FlowValue = serde_json::from_value(json!({"modules": [{"id": "agent", "value": { + "type": "aiagent", + "tools": [{"id": "echo", "summary": "echo", "value": { + "type": "rawscript", "language": "bun", "input_transforms": {}, + "content": "export async function main(x: any) { return x }"}}], + "input_transforms": { + "provider": {"type": "static", "value": {"kind": "customai", "model": "m", + "resource": {"base_url": format!("{base}/v1")}}}, + "user_message": {"type": "static", "value": "go"}, + "max_iterations": {"type": "static", "value": 2} + } + }}]})) + .unwrap(); + let id = RunJob::from(JobPayload::RawFlow { + value: flow, + path: Some("u/test-user/agent".into()), + restarted_from: None, + }) + .push(db) + .await; + let out = run(db, port, id).await; + stub.abort(); + out["messages"] + .as_array() + .unwrap() + .iter() + .find(|m| m["role"] == "tool") + .unwrap()["content"] + .as_str() + .unwrap() + .to_string() +} + +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn agent_tool_call_resolves_nothing_the_model_wrote( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + seed(&db).await?; + // jsonb keeps the last copy of a duplicate key, the one a Rust decode refuses to read past. + let reply = tool_reply( + &db, + port, + r#"{"x": {"n": 1e400, "n": 0, "r": "\u0024var:u/test-user/secret"}}"#, + ) + .await; + assert!(!reply.contains(SECRET), "{reply}"); + assert!(reply.contains("Tool call refused"), "{reply}"); + + // A tool the model calls without arguments, as Anthropic sends it. + let reply = tool_reply(&db, port, "").await; + assert!(!reply.contains("Tool call refused"), "{reply}"); + + let reply = tool_reply( + &db, + port, + r#"{"x": {"pipeline": [{"$match": {"currency": "$USD", "_id": "$category"}}]}}"#, + ) + .await; + assert_eq!( + serde_json::from_str::(&reply)?, + json!({"pipeline": [{"$match": {"currency": "$USD", "_id": "$category"}}]}) + ); + Ok(()) +} diff --git a/backend/tests/variable_expiration.rs b/backend/tests/variable_expiration.rs new file mode 100644 index 0000000000..94a4ed3f78 --- /dev/null +++ b/backend/tests/variable_expiration.rs @@ -0,0 +1,534 @@ +//! Tests for the variable expiration sweep. No worker: the sweep ends at the push, and the +//! queued job is what the tests assert on. + +use sqlx::{Pool, Postgres}; +use windmill_queue::variable_expiration::dispatch_expiring_variables; +use windmill_test_utils::{initialize_tracing, ApiServer}; + +const WS: &str = "test-workspace"; + +async fn configure_handler(db: &Pool, handler: &str) -> anyhow::Result<()> { + sqlx::query("UPDATE workspace_settings SET variable_expiration_handler = $2::jsonb WHERE workspace_id = $1") + .bind(WS) + .bind(handler) + .execute(db) + .await?; + Ok(()) +} + +/// Seed a deployed script the handler setting can point at. +async fn seed_handler_script(db: &Pool, path: &str) -> anyhow::Result<()> { + sqlx::query( + r#"INSERT INTO script (workspace_id, hash, path, summary, description, content, created_by, language, lock) + VALUES ($1, $2, $3, '', '', 'export function main() {}', 'test-user', 'bun', '')"#, + ) + .bind(WS) + .bind(path.bytes().fold(0i64, |h, b| h.wrapping_mul(31).wrapping_add(b as i64))) + .bind(path) + .execute(db) + .await?; + Ok(()) +} + +async fn seed_variable(db: &Pool, path: &str, expires_in: &str) -> anyhow::Result<()> { + sqlx::query(&format!( + r#"INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until) + VALUES ($1, $2, 'MUST_NOT_LEAK', true, 'a credential', now() + interval '{expires_in}')"# + )) + .bind(WS) + .bind(path) + .execute(db) + .await?; + Ok(()) +} + +async fn queued_handler_jobs(db: &Pool, path: &str) -> anyhow::Result { + Ok( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM v2_job WHERE runnable_path = $1") + .bind(path) + .fetch_one(db) + .await?, + ) +} + +/// The sweep dispatches inside the handler's `notify_before_secs`, leaves everything outside it +/// alone, and does not fire twice for the same expiry. +#[sqlx::test(fixtures("base"))] +async fn test_dispatch_within_lead_time_once(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "notify_before_secs": 3600}"#, + ) + .await?; + + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + seed_variable(&db, "u/test-user/far", "2 hours").await?; + + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "exactly the variable inside the lead window should dispatch" + ); + + // Admins grant this group access to the secrets it rotates, so the job must run as it. + let (path, is_secret, permissioned_as, permissioned_as_email): (String, bool, String, String) = + sqlx::query_as( + "SELECT args->>'variable_path', (args->>'is_secret')::boolean, permissioned_as, + permissioned_as_email FROM v2_job WHERE runnable_path = $1", + ) + .bind("u/test-user/expiry_handler") + .fetch_one(&db) + .await?; + assert_eq!(path, "u/test-user/due"); + assert!(is_secret); + assert_eq!(permissioned_as, "g/variable_expiration_handler"); + assert_eq!( + permissioned_as_email, + "variable_expiration_handler@windmill.dev" + ); + + let args: String = sqlx::query_scalar("SELECT args::text FROM v2_job WHERE runnable_path = $1") + .bind("u/test-user/expiry_handler") + .fetch_one(&db) + .await?; + assert!( + !args.contains("MUST_NOT_LEAK"), + "handler args leaked the value: {args}" + ); + + // The claim is what makes concurrent replicas safe. + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "a dispatched variable must not fire again" + ); + + Ok(()) +} + +/// A variable's writer must not get the handler to resolve a reference as its own identity; +/// the admin's `extra_args` still resolve. +#[sqlx::test(fixtures("base"))] +async fn test_variable_fields_do_not_resolve_in_handler(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "extra_args": {"slack": "$res:f/slack_bot/bot_token"}}"#, + ) + .await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + sqlx::query( + "UPDATE variable SET description = '$var:u/test-user/other' WHERE path = 'u/test-user/due'", + ) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + + let (description, slack): (String, String) = sqlx::query_as( + "SELECT args->>'description', args->>'slack' FROM v2_job WHERE runnable_path = $1", + ) + .bind("u/test-user/expiry_handler") + .fetch_one(&db) + .await?; + assert!( + !description.starts_with("$var:"), + "description still resolves: {description}" + ); + assert_eq!(slack, "$res:f/slack_bot/bot_token"); + Ok(()) +} + +/// `remind_every_secs` runs the handler again once the interval has elapsed, and not before. +#[sqlx::test(fixtures("base"))] +async fn test_remind_every_repeats_the_notice(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "remind_every_secs": 600}"#, + ) + .await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + + dispatch_expiring_variables(&db).await; + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "no reminder before the interval has elapsed" + ); + + // A sweep landing a few seconds short of the interval must still remind. + sqlx::query( + "UPDATE variable SET expiration_notified_at = now() - interval '9 minutes 50 seconds'", + ) + .execute(&db) + .await?; + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2 + ); + + sqlx::query( + "UPDATE variable SET value_valid_until = now() - interval '1 minute', + expiration_dispatched_for = now() - interval '1 minute', + expiration_notified_at = now() - interval '11 minutes'", + ) + .execute(&db) + .await?; + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2 + ); + Ok(()) +} + +/// Moving `value_valid_until` re-arms the variable; re-writing the same date does not. +#[sqlx::test(fixtures("base"))] +async fn test_rearm_on_date_change(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}", server.addr.port()); + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler(&db, r#"{"path": "script/u/test-user/expiry_handler"}"#).await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + + // Through the real endpoint: writing the column directly would assert nothing. + let update = async |body: serde_json::Value| -> anyhow::Result { + Ok(reqwest::Client::new() + .post(format!( + "{base_url}/api/w/{WS}/variables/update/u/test-user/due" + )) + .bearer_auth("SECRET_TOKEN") + .json(&body) + .send() + .await? + .status() + .as_u16()) + }; + + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1 + ); + + let stored: chrono::DateTime = sqlx::query_scalar( + "SELECT value_valid_until FROM variable WHERE workspace_id = $1 AND path = $2", + ) + .bind(WS) + .bind("u/test-user/due") + .fetch_one(&db) + .await?; + + // An unchanged `wmill sync push` rewrites the same date. + assert_eq!( + update(serde_json::json!({ "value_valid_until": stored })).await?, + 200 + ); + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "an unchanged expiry must not re-arm" + ); + + assert_eq!( + update(serde_json::json!({ "description": "touched" })).await?, + 200 + ); + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "an update that omits value_valid_until must not re-arm" + ); + + assert_eq!( + update(serde_json::json!({ "value_valid_until": stored + chrono::Duration::minutes(5) })) + .await?, + 200 + ); + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2, + "a moved expiry must re-arm the handler" + ); + + Ok(()) +} + +/// `muted_on_user_path` keeps personal-path variables out. +#[sqlx::test(fixtures("base"))] +async fn test_muted_user_paths(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + seed_variable(&db, "u/test-user/personal", "30 minutes").await?; + seed_variable(&db, "f/test_folder/shared", "30 minutes").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "muted_on_user_path": true}"#, + ) + .await?; + dispatch_expiring_variables(&db).await; + + let dispatched: Vec = + sqlx::query_scalar("SELECT args->>'variable_path' FROM v2_job WHERE runnable_path = $1") + .bind("u/test-user/expiry_handler") + .fetch_all(&db) + .await?; + assert_eq!( + dispatched, + vec!["f/test_folder/shared".to_string()], + "a muted personal path must not dispatch" + ); + + Ok(()) +} + +/// Broken workspaces' due rows must not hold back anyone else's first notice or reminder: every +/// due row is tried each pass, and a broken handler only once per pass. The broken rows go in +/// first, so a cap on the pass would cut off the working workspace. +#[sqlx::test(fixtures("base"))] +async fn test_broken_handlers_do_not_hold_back_others(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#"INSERT INTO workspace (id, name, owner) SELECT 'broken-' || i, 'broken-' || i, 'test-user' FROM generate_series(1, 100) i; + INSERT INTO workspace_key (workspace_id, kind, key) SELECT 'broken-' || i, 'cloud', 'k' FROM generate_series(1, 100) i; + INSERT INTO workspace_settings (workspace_id, variable_expiration_handler) + SELECT 'broken-' || i, '{"path": "script/u/test-user/does_not_exist"}'::jsonb FROM generate_series(1, 100) i; + INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until) + SELECT 'broken-' || i, 'f/creds/v' || j, 'v', false, '', now() - interval '1 day' + FROM generate_series(1, 100) i, generate_series(1, 2) j;"#, + ) + .execute(&db) + .await?; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "remind_every_secs": 60}"#, + ) + .await?; + seed_variable(&db, "u/test-user/fresh", "30 minutes").await?; + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until, + expiration_dispatched_for, expiration_notified_at) + VALUES ($1, 'u/test-user/reminded', 'v', false, '', now() + interval '10 minutes', + now() + interval '10 minutes', now() - interval '2 minutes')", + ) + .bind(WS) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2, + "the first notice and the reminder must both go out" + ); + assert_eq!( + queued_handler_jobs(&db, "u/test-user/does_not_exist").await?, + 0 + ); + Ok(()) +} + +/// A broken handler alerts once, however many passes it fails, runs on the first pass after +/// it is deployed, and that resolves its alert. +#[sqlx::test(fixtures("base"))] +async fn test_deploying_the_handler_ends_the_failure(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + configure_handler(&db, r#"{"path": "script/u/test-user/redeployed_handler"}"#).await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + let alerts = || async { + Ok::<_, anyhow::Error>(sqlx::query_as::<_, (i64, i64)>( + "SELECT count(*), count(*) FILTER (WHERE NOT acknowledged) FROM alerts + WHERE alert_type = 'critical_error' AND resource = 'variable_expiration_handler:test-workspace'", + ) + .fetch_one(&db) + .await?) + }; + + dispatch_expiring_variables(&db).await; + dispatch_expiring_variables(&db).await; + assert_eq!( + alerts().await?, + (1, 1), + "one alert per failure, not per pass" + ); + + seed_handler_script(&db, "u/test-user/redeployed_handler").await?; + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/redeployed_handler").await?, + 1, + "the deployed handler did not run on the next pass" + ); + assert_eq!(alerts().await?, (1, 0), "starting again resolves the alert"); + Ok(()) +} + +/// A handler script still waiting on its dependency job runs on the first pass after its lock +/// lands, though nothing about the script changes but the lock. +#[sqlx::test(fixtures("base"))] +async fn test_handler_runs_once_its_lock_lands(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + configure_handler( + &db, + r#"{"path": "script/u/test-user/pending_lock_handler"}"#, + ) + .await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + seed_handler_script(&db, "u/test-user/pending_lock_handler").await?; + sqlx::query("UPDATE script SET lock = NULL WHERE workspace_id = $1") + .bind(WS) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/pending_lock_handler").await?, + 0 + ); + sqlx::query("UPDATE script SET lock = '' WHERE workspace_id = $1") + .bind(WS) + .execute(&db) + .await?; + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/pending_lock_handler").await?, + 1, + "the handler did not run once its lock landed" + ); + Ok(()) +} + +/// A removed handler has nothing left to retry, so the next pass ends its failure and resolves +/// its alert. +#[sqlx::test(fixtures("base"))] +async fn test_removing_a_failing_handler_resolves_its_alert( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::query( + "UPDATE workspace_settings SET variable_expiration_handler = NULL, + variable_expiration_failed_at = now() WHERE workspace_id = $1", + ) + .bind(WS) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO alerts (alert_type, message, acknowledged, acknowledged_workspace, workspace_id, resource) + VALUES ('critical_error', 'failed', false, false, $1, 'variable_expiration_handler:' || $1)", + ) + .bind(WS) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + + let (failing, open_alerts): (bool, i64) = sqlx::query_as( + "SELECT ws.variable_expiration_failed_at IS NOT NULL, + (SELECT count(*) FROM alerts WHERE alert_type = 'critical_error' AND NOT acknowledged + AND workspace_id = $1) + FROM workspace_settings ws WHERE ws.workspace_id = $1", + ) + .bind(WS) + .fetch_one(&db) + .await?; + assert!(!failing, "the removed handler's failure must end"); + assert_eq!( + open_alerts, 0, + "the removed handler's alert must be resolved" + ); + Ok(()) +} + +/// The handler endpoint: admin-only, existence-checked, and clearing by omission, which +/// `wmill sync push` relies on to propagate an absent handler. +#[sqlx::test(fixtures("base"))] +async fn test_edit_handler_endpoint(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}", server.addr.port()); + + let edit = async |token: &str, body: serde_json::Value| -> anyhow::Result { + Ok(reqwest::Client::new() + .post(format!( + "{base_url}/api/w/{WS}/workspaces/edit_variable_expiration_handler" + )) + .bearer_auth(token) + .json(&body) + .send() + .await? + .status() + .as_u16()) + }; + let stored = async || -> anyhow::Result> { + Ok(sqlx::query_scalar( + "SELECT variable_expiration_handler FROM workspace_settings WHERE workspace_id = $1", + ) + .bind(WS) + .fetch_one(&db) + .await?) + }; + + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + let handler = serde_json::json!({ "path": "script/u/test-user/expiry_handler" }); + assert_eq!(edit("SECRET_TOKEN_2", handler.clone()).await?, 403); + assert!(stored().await?.is_none()); + + for path in [ + "u/test-user/expiry_handler", + "script/u/test-user/does_not_exist", + ] { + assert_eq!( + edit("SECRET_TOKEN", serde_json::json!({ "path": path })).await?, + 400, + "{path}" + ); + } + + // A recorded failure is the sweep's to end, so the endpoint leaves it alone either way. + sqlx::query("UPDATE workspace_settings SET variable_expiration_failed_at = now() WHERE workspace_id = $1") + .bind(WS) + .execute(&db) + .await?; + let failing = || async { + Ok::<_, anyhow::Error>(sqlx::query_scalar::<_, bool>( + "SELECT variable_expiration_failed_at IS NOT NULL FROM workspace_settings WHERE workspace_id = $1", + ) + .bind(WS) + .fetch_one(&db) + .await?) + }; + assert_eq!(edit("SECRET_TOKEN", handler).await?, 200); + assert_eq!( + stored() + .await? + .and_then(|h| h["path"].as_str().map(String::from)), + Some("script/u/test-user/expiry_handler".to_string()) + ); + assert!(failing().await?, "saving the handler must keep its failure"); + + assert_eq!(edit("SECRET_TOKEN", serde_json::json!({})).await?, 200); + assert!( + stored().await?.is_none(), + "an omitted path clears the handler" + ); + + Ok(()) +} diff --git a/backend/tests/workspace_export.rs b/backend/tests/workspace_export.rs index 5894ca8394..792d41b487 100644 --- a/backend/tests/workspace_export.rs +++ b/backend/tests/workspace_export.rs @@ -288,6 +288,48 @@ async fn test_tarball_export_gates_values_on_item_scopes(db: Pool) -> Ok(()) } +/// The tarball drops variables by `expires_at`, never `value_valid_until`, and the exported +/// entry carries the date, or a pull/push round-trip clears it. +#[sqlx::test(fixtures("base"))] +async fn test_tarball_export_excludes_only_gc_variables(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}", server.addr.port()); + + sqlx::query( + r#"INSERT INTO variable (workspace_id, path, value, is_secret, description, expires_at, value_valid_until) + VALUES ('test-workspace', 'u/test-user/expiring', 'v', false, '', NULL, '2030-01-15T08:00:00Z'), + ('test-workspace', 'u/test-user/ephemeral', 'v', false, '', now() + interval '7 days', NULL)"#, + ) + .execute(&db) + .await?; + + let resp = reqwest::Client::new() + .get(format!( + "{base_url}/api/w/test-workspace/workspaces/tarball" + )) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(resp.status().as_u16(), 200); + let body = String::from_utf8_lossy(&resp.bytes().await?).into_owned(); + + assert!( + body.contains("u/test-user/expiring.variable.json"), + "a variable with an expiry must still reach git sync" + ); + assert!( + body.contains("2030-01-15T08:00:00Z"), + "the exported entry must carry the expiry back" + ); + assert!( + !body.contains("u/test-user/ephemeral.variable.json"), + "a variable awaiting garbage collection must stay out of the export" + ); + + Ok(()) +} + /// `settings.json` carries the admin-managed integration config that `get_settings` /// is admin-only for (the webhook URL, ai_config, git_sync, handler extra_args), so /// `include_settings` takes the same admin check as `get_settings` rather than diff --git a/backend/tests/workspace_fairness.rs b/backend/tests/workspace_fairness.rs index f5922037e4..7f1e82782a 100644 --- a/backend/tests/workspace_fairness.rs +++ b/backend/tests/workspace_fairness.rs @@ -46,6 +46,7 @@ use windmill_common::worker::{ WORKSPACE_FAIRNESS_MIN_TOTAL, WORKSPACE_FAIRNESS_OVERLOADED, }; use windmill_queue::workspace_fairness::refresh_overloaded; +use windmill_test_utils::ensure_today_audit_partition; // --------------------------------------------------------------------------- // Shared helpers @@ -331,22 +332,6 @@ async fn fairness_lifts_when_load_drops(db: Pool) { assert!(overloaded_set().is_empty()); } -/// Ensure today's audit_partitioned partition exists — the migration only -/// creates partitions for the day it ran + 3 days, after which production -/// relies on `monitor::manage_audit_partitions` to roll new ones. That -/// maintenance task does not run in the test binary, so inserts silently -/// fail-and-warn without it. -async fn ensure_today_audit_partition(db: &Pool) { - let today: chrono::NaiveDate = chrono::Utc::now().date_naive(); - let next = today + chrono::Duration::days(1); - let partition = format!("audit_{}", today.format("%Y%m%d")); - let sql = format!( - "CREATE TABLE IF NOT EXISTS \"{partition}\" PARTITION OF audit_partitioned \ - FOR VALUES FROM ('{today}') TO ('{next}')" - ); - let _ = sqlx::query(&sql).execute(db).await; -} - /// Both cap AND uncap transitions must produce audit-log rows. This test /// drives a cap → uncap cycle and inspects `audit_partitioned` directly. #[sqlx::test(fixtures("base"))] diff --git a/backend/windmill-ai/src/ai_providers.rs b/backend/windmill-ai/src/ai_providers.rs index 311c8d3eb7..489a965ef1 100644 --- a/backend/windmill-ai/src/ai_providers.rs +++ b/backend/windmill-ai/src/ai_providers.rs @@ -213,7 +213,9 @@ impl AIProvider { AIProvider::Groq => Ok("https://api.groq.com/openai/v1".to_string()), AIProvider::OpenRouter => Ok("https://openrouter.ai/api/v1".to_string()), AIProvider::TogetherAI => Ok("https://api.together.xyz/v1".to_string()), - AIProvider::Anthropic => Ok("https://api.anthropic.com/v1".to_string()), + AIProvider::Anthropic => { + Ok(crate::providers::anthropic::ANTHROPIC_API_BASE_URL.to_string()) + } AIProvider::Mistral => Ok("https://api.mistral.ai/v1".to_string()), AIProvider::TypeSafe => Ok(TYPESAFE_BASE_URL.to_string()), AIProvider::Cloudflare => Err(Error::BadRequest( diff --git a/backend/windmill-ai/src/credentials.rs b/backend/windmill-ai/src/credentials.rs index 5a779938ed..f5489c5c30 100644 --- a/backend/windmill-ai/src/credentials.rs +++ b/backend/windmill-ai/src/credentials.rs @@ -32,6 +32,21 @@ pub struct ProviderCredentials { /// A role trust policy that conditions on `sub` has to admit both, or only /// one of the copilot and the AI agent step will be able to assume the role. pub oidc_role_arn: Option, + /// Anthropic Workload Identity Federation settings, from an `anthropic_federated` + /// 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, pub platform: AIPlatform, pub custom_headers: HashMap, } + +/// The identifiers a Claude Console federation rule needs in a token exchange. +/// None of them is a secret: what authorises the exchange is the OIDC token. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct AnthropicFederation { + pub federation_rule_id: String, + pub organization_id: String, + pub service_account_id: String, + /// Required by Anthropic only when the rule is enabled in several workspaces. + pub workspace_id: Option, +} diff --git a/backend/windmill-ai/src/providers/anthropic.rs b/backend/windmill-ai/src/providers/anthropic.rs index 7acd2db939..2a3417bc62 100644 --- a/backend/windmill-ai/src/providers/anthropic.rs +++ b/backend/windmill-ai/src/providers/anthropic.rs @@ -2,6 +2,7 @@ use super::{anthropic_model_rejects_sampling_params, REASONING_OFF_SENTINEL}; use crate::{ ai_google::parse_data_url, ai_providers::{AIPlatform, AIProvider, DISABLE_ANTHROPIC_PROMPT_CACHING}, + credentials::AnthropicFederation, image_handler::prepare_messages_for_api, proxy::{ add_user_to_body, common_outbound_headers, credential_header, ProxyBuildArgs, ProxyRequest, @@ -837,6 +838,169 @@ impl QueryBuilder for AnthropicQueryBuilder { } } +pub const ANTHROPIC_API_BASE_URL: &str = "https://api.anthropic.com/v1"; + +/// Audience of the OIDC token Windmill presents in an Anthropic token exchange, +/// which a federation rule can pin with its `audience` matcher. +pub const ANTHROPIC_OIDC_AUDIENCE: &str = "https://api.anthropic.com"; + +/// Lifetime of that OIDC token. A federation issuer refuses a token that lives +/// longer than its maximum (one hour by default), and Anthropic caps the access +/// token at twice the assertion's remaining life, so 30 minutes still lets a rule +/// mint its default one-hour token. +pub const ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS: i64 = 1800; + +/// 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: a rule may mint tokens for as little as a minute, and a +/// margin longer than that would exchange again on every request. +const FEDERATED_TOKEN_REFRESH_MARGIN: std::time::Duration = std::time::Duration::from_secs(300); + +/// A short-lived Anthropic access token minted by a federated token exchange. +#[derive(Clone, Debug)] +pub struct FederatedAccessToken { + pub access_token: String, + refresh_at: std::time::SystemTime, +} + +impl FederatedAccessToken { + fn new(access_token: String, lifetime: std::time::Duration) -> Self { + // Anthropic mints tokens for at most a day; the clamp keeps an out-of-range + // `expires_in` from overflowing the clock arithmetic. + let lifetime = lifetime.min(std::time::Duration::from_secs(86400)); + let margin = FEDERATED_TOKEN_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(Serialize)] +struct FederatedTokenRequest<'a> { + grant_type: &'static str, + assertion: &'a str, + federation_rule_id: &'a str, + organization_id: &'a str, + service_account_id: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + workspace_id: Option<&'a str>, +} + +#[derive(Deserialize)] +struct FederatedTokenResponse { + access_token: String, + expires_in: u64, +} + +/// Exchange an OIDC token for an Anthropic access token at `POST /v1/oauth/token` +/// (RFC 7523 `jwt-bearer` grant). `client` must already be pinned to the +/// validated address of `base_url`. +pub async fn exchange_federated_token( + client: &reqwest::Client, + base_url: &str, + federation: &AnthropicFederation, + assertion: &str, +) -> Result { + let exchanged = request_federated_token(client, base_url, federation, assertion).await; + windmill_common::feature_usage::log_feature_usage( + "anthropic_federation", + "token_exchange", + if exchanged.is_ok() { "ok" } else { "failed" }, + ); + exchanged +} + +async fn request_federated_token( + client: &reqwest::Client, + base_url: &str, + federation: &AnthropicFederation, + assertion: &str, +) -> Result { + let url = AIProvider::build_anthropic_api_url(base_url, "oauth/token"); + let response = client + .post(url) + .header("anthropic-version", ANTHROPIC_VERSION_STANDARD) + .json(&FederatedTokenRequest { + grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", + assertion, + federation_rule_id: &federation.federation_rule_id, + organization_id: &federation.organization_id, + service_account_id: &federation.service_account_id, + workspace_id: federation.workspace_id.as_deref(), + }) + .send() + .await + .map_err(|e| Error::internal_err(format!("Anthropic token exchange failed: {e}")))?; + + let status = response.status(); + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + // Anthropic answers every denied assertion with the same opaque 401; the + // reason is only recorded in the Console's authentication history. + let hint = if status == reqwest::StatusCode::UNAUTHORIZED { + " The reason the exchange was denied is in the authentication history of the Claude Console's Workload identity page." + } else { + "" + }; + return Err(Error::BadRequest(format!( + "Anthropic token exchange failed with status {status}: {body}.{hint}" + ))); + } + + let token = response + .json::() + .await + .map_err(|e| { + Error::internal_err(format!( + "Failed to parse the Anthropic token exchange response: {e}" + )) + })?; + Ok(FederatedAccessToken::new( + token.access_token, + std::time::Duration::from_secs(token.expires_in), + )) +} + +/// The access token of a federated 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_federated_access_token<'a>( + credentials: &crate::credentials::ProviderCredentials, + cached: &'a mut Option, + client: &AuthedClient, +) -> Result, Error> { + let Some(federation) = credentials.anthropic_federation.as_ref() else { + return Ok(None); + }; + if !cached.as_ref().is_some_and(FederatedAccessToken::is_fresh) { + // A worker holds no OIDC signing key, so it asks the API to mint the token for this job. + let assertion = client + .get_id_token_expiring_in( + ANTHROPIC_OIDC_AUDIENCE, + Some(ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS), + ) + .await + .map_err(|e| Error::ExecutionErr(format!("Failed to get an OIDC token: {e}")))?; + let http_client = crate::utils::pinned_ai_client_for(&credentials.base_url).await?; + *cached = Some( + exchange_federated_token(&http_client, &credentials.base_url, federation, &assertion) + .await?, + ); + } + Ok(cached.as_ref().map(|token| token.access_token.as_str())) +} + +/// Headers authenticating a request with a federated access token, which Anthropic +/// takes as a bearer token in place of `x-api-key`. +pub fn federated_auth_headers(access_token: &str) -> Vec<(&'static str, String)> { + vec![ + ("Authorization", format!("Bearer {access_token}")), + ("anthropic-version", ANTHROPIC_VERSION_STANDARD.to_string()), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -859,6 +1023,7 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform, custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/providers/google_ai.rs b/backend/windmill-ai/src/providers/google_ai.rs index bbf45e5e57..06a404e5a4 100644 --- a/backend/windmill-ai/src/providers/google_ai.rs +++ b/backend/windmill-ai/src/providers/google_ai.rs @@ -805,6 +805,7 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: 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 82dceaa02f..ffddd33d3a 100644 --- a/backend/windmill-ai/src/providers/mod.rs +++ b/backend/windmill-ai/src/providers/mod.rs @@ -370,6 +370,7 @@ mod parity_tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: kase.platform.clone(), custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/proxy.rs b/backend/windmill-ai/src/proxy.rs index ca6ee1b59b..66285437e4 100644 --- a/backend/windmill-ai/src/proxy.rs +++ b/backend/windmill-ai/src/proxy.rs @@ -285,6 +285,7 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: 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 59733e352c..3950576aed 100644 --- a/backend/windmill-ai/src/types.rs +++ b/backend/windmill-ai/src/types.rs @@ -19,7 +19,7 @@ pub struct McpToolSource { use crate::{ ai_google::sanitize_schema_for_google, ai_providers::{empty_string_as_none, AIProvider}, - credentials::ProviderCredentials, + credentials::{AnthropicFederation, ProviderCredentials}, }; use windmill_common::{db::DB, error::Error, flow_status::AgentAction, flows::FlowModule}; use windmill_parser::Typ; @@ -270,6 +270,16 @@ pub struct ProviderResource { /// credentials exchange this crate does not perform. #[serde(default, deserialize_with = "empty_string_as_none")] pub token_url: Option, + /// Set only by `anthropic_federated` resources, which authenticate through + /// Workload Identity Federation with an OIDC token minted for the job. + #[serde(default, deserialize_with = "empty_string_as_none")] + pub federation_rule_id: Option, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub organization_id: Option, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub service_account_id: Option, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub workspace_id: 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, @@ -323,8 +333,13 @@ impl ProviderWithResource { /// Callers must only pass resources that were already authorized for the /// 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 base_url = if self.kind == AIProvider::AWSBedrock { String::new() + } else if anthropic_federation.is_some() { + // The exchanged token is the job's identity, so it only ever goes to + // Anthropic: a resource cannot point it at another host. + crate::providers::anthropic::ANTHROPIC_API_BASE_URL.to_string() } else { self.get_base_url(db).await? }; @@ -348,11 +363,40 @@ impl ProviderWithResource { aws_secret_access_key: self.resource.aws_secret_access_key.clone(), 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(), custom_headers: self.resource.headers.clone(), }) } + /// The federation settings of an `anthropic_federated` resource, which only + /// `federation_rule_id` identifies; the other required fields are checked here. + fn anthropic_federation(&self) -> Result, Error> { + let resource = &self.resource; + let Some(federation_rule_id) = resource.federation_rule_id.clone() else { + return Ok(None); + }; + if self.kind != AIProvider::Anthropic { + return Err(Error::ExecutionErr(format!( + "An anthropic_federated resource can only be used with the Anthropic provider, not {:?}", + self.kind + ))); + } + let required = |value: &Option, name: &str| { + value.clone().ok_or_else(|| { + Error::ExecutionErr(format!( + "The anthropic_federated resource needs {name} to be set" + )) + }) + }; + Ok(Some(AnthropicFederation { + federation_rule_id, + organization_id: required(&resource.organization_id, "organization_id")?, + service_account_id: required(&resource.service_account_id, "service_account_id")?, + workspace_id: resource.workspace_id.clone(), + })) + } + #[cfg(feature = "bedrock")] pub fn get_region(&self) -> Option<&str> { self.resource.region.as_deref() @@ -983,6 +1027,47 @@ pub struct S3ObjectWithType { mod tests { use super::*; + #[test] + fn a_federated_resource_resolves_its_federation_and_names_a_missing_field() { + let provider = |kind: &str, resource: &str| -> ProviderWithResource { + serde_json::from_str(&format!( + r#"{{"kind":"{kind}","model":"m","resource":{resource}}}"# + )) + .unwrap() + }; + let federated = r#"{"federation_rule_id":"fdrl_x","organization_id":"org","service_account_id":"svac_x","workspace_id":""}"#; + + assert_eq!( + provider("anthropic", federated) + .anthropic_federation() + .unwrap(), + Some(AnthropicFederation { + federation_rule_id: "fdrl_x".to_string(), + organization_id: "org".to_string(), + service_account_id: "svac_x".to_string(), + workspace_id: None, + }) + ); + let incomplete = provider( + "anthropic", + r#"{"federation_rule_id":"fdrl_x","organization_id":"org"}"#, + ); + assert!(incomplete + .anthropic_federation() + .unwrap_err() + .to_string() + .contains("service_account_id")); + assert!(provider("openai", federated) + .anthropic_federation() + .is_err()); + assert_eq!( + provider("anthropic", r#"{"api_key":"k","organization_id":"org"}"#) + .anthropic_federation() + .unwrap(), + None + ); + } + /// The schema is part of the prompt prefix the provider caches on, so its keys must /// serialize in the same order on every request. #[test] diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 6bc9a930a4..e278b644d5 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -466,8 +466,8 @@ impl AuthCache { let lookup = if super_admin { Some((true, false)) } else { - sqlx::query!( - "SELECT is_admin, operator FROM usr where username = $1 AND \ + let row = sqlx::query!( + "SELECT is_admin, operator, workspace_role FROM usr where username = $1 AND \ workspace_id = $2 AND disabled = false", name, &w_id.as_ref().unwrap() @@ -475,8 +475,24 @@ impl AuthCache { .fetch_optional(&self.db) .await .ok() - .flatten() - .map(|r| (r.is_admin, r.operator)) + .flatten(); + match row { + Some(r) => { + // Fails closed: an unreadable role config + // gates the member rather than freeing it. + let restricted = + windmill_common::roles::member_is_restricted_db( + &self.db, + w_id.as_ref().unwrap(), + r.workspace_role, + r.operator, + ) + .await + .unwrap_or(true); + Some((r.is_admin, restricted && !r.is_admin)) + } + None => None, + } }; if let Some((is_admin, is_operator)) = lookup { @@ -596,15 +612,35 @@ impl AuthCache { username_override_from_label(label); if w_id.is_some() { let row_o = sqlx::query!( - "SELECT username, is_admin, operator FROM usr WHERE + "SELECT username, is_admin, operator, workspace_role FROM usr WHERE email = $1 AND workspace_id = $2 AND disabled = false", &email, w_id.as_ref().unwrap() ) - .map(|x| (x.username, x.is_admin, x.operator)) + .map(|x| (x.username, x.is_admin, x.operator, x.workspace_role)) .fetch_optional(&self.db) .await - .unwrap_or(Some(("error".to_string(), false, false))); + .unwrap_or(Some(("error".to_string(), false, false, None))); + let row_o = match row_o { + Some((username, is_admin, operator, workspace_role)) => { + // Fails closed, as above. + let restricted = + windmill_common::roles::member_is_restricted_db( + &self.db, + w_id.as_ref().unwrap(), + workspace_role, + operator, + ) + .await + .unwrap_or(true); + Some(( + username, + is_admin, + restricted && !is_admin && !super_admin, + )) + } + None => None, + }; match row_o { Some((username, is_admin, is_operator)) => { @@ -867,10 +903,9 @@ async fn admit_and_record_guest_jwt(db: &DB, w_id: &str, email: &str, app_path: return false; } GUEST_JWT_ACTIVITY_CACHE.insert(cache_key, ()); - // Audit last, best-effort, on its own connection: the EE writer swallows an - // `audit_partitioned` failure but that failing statement still aborts the - // transaction it runs in, so auditing before the commit would let the whole - // activity row roll back while this returned success, admitting an uncounted guest. + // Audit last, best-effort, on its own connection: a failed `audit_partitioned` + // insert aborts the transaction it runs in, so auditing before the commit would + // let an audit failure drop the activity row that counts this guest. if first_jwt { let author = windmill_common::audit::AuditAuthor { email: email.to_string(), @@ -1244,6 +1279,7 @@ pub async fn resolve_opt_job_authed( // could approve an OAuth flow that mints a new non-read-only // token. let is_mcp_transport = path == "/api/mcp/gateway" + || path == "/api/mcp" || (path.starts_with("/api/mcp/w/") && (path.ends_with("/mcp") || path.ends_with("/sse") diff --git a/backend/windmill-api-auth/src/composed.rs b/backend/windmill-api-auth/src/composed.rs new file mode 100644 index 0000000000..e9d79240dd --- /dev/null +++ b/backend/windmill-api-auth/src/composed.rs @@ -0,0 +1,171 @@ +//! 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. + +use sqlx::{Postgres, Transaction}; +use windmill_common::{ + error::{self, Error}, + flows::FlowValue, + roles::AuthorLevel, + workspaces::{check_operator_can_build, BuilderKind}, + DB, +}; + +use crate::{get_scope_tags, is_super_admin_authed, ApiAuthed}; + +/// `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. +pub async fn authorize_composed_flow( + value: &FlowValue, + flow_tag: &Option, + authed: &ApiAuthed, + db: &DB, + tx: &mut Transaction<'_, Postgres>, + w_id: &str, +) -> error::Result<()> { + let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?; + + // A builder links only an agent it can read, and binds only the tool inputs it leaves open. + for agent in &refs.agents { + let path = &agent.path; + let value = sqlx::query_scalar!( + "SELECT value AS \"value: sqlx::types::Json\" + FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + w_id, + path, + ) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| { + Error::PermissionDenied(format!( + "Agent {path} does not exist or is not readable by you" + )) + })?; + if agent.bound_inputs.is_empty() { + continue; + } + let tools: Vec = value + .and_then(|v| v.0.get("tools").cloned()) + .map(serde_json::from_value) + .transpose() + .map_err(|e| Error::BadRequest(format!("Invalid tools in agent {path}: {e}")))? + .unwrap_or_default(); + windmill_common::flows::check_bound_agent_inputs_are_open( + path, + &tools, + &agent.bound_inputs, + )?; + } + + // A tag is how a step picks the worker group it runs on: unauthorized, a builder could route + // a job onto a privileged one. + refs.tags.extend(flow_tag.clone().filter(|t| !t.is_empty())); + if !refs.tags.is_empty() { + // Job-aware: a WM_TOKEN running as a superadmin must not unlock restricted tags. + let is_super_admin = is_super_admin_authed(db, authed).await?; + for tag in &refs.tags { + windmill_common::jobs::check_tag_available_for_workspace_internal( + db, + w_id, + tag, + None, + std::future::ready(w_id.to_string()), + is_super_admin, + get_scope_tags(authed), + ) + .await?; + } + } + + if refs.runnables.is_empty() && refs.pinned_scripts.is_empty() { + return Ok(()); + } + // A flow can step through the same script thirty times; this runs on every write, preview and + // dependency job. + refs.runnables.sort(); + refs.runnables.dedup(); + refs.pinned_scripts + .sort_by_key(|(path, hash)| (path.clone(), hash.0)); + refs.pinned_scripts + .dedup_by_key(|(path, hash)| (path.clone(), hash.0)); + // The worker resolves a step's path with the root DB handle and runs it as that runnable's + // `on_behalf_of`, so composing an unreadable path would run code the builder cannot see. RLS + // on this transaction is the check. + for (is_flow, path) in &refs.runnables { + let readable = if *is_flow { + sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2)", + w_id, + path, + ) + } else { + sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2)", + w_id, + path, + ) + } + .fetch_one(&mut **tx) + .await? + .unwrap_or(false); + if !readable { + return Err(Error::PermissionDenied(format!( + "{} {path} does not exist or is not readable by you", + if *is_flow { "Flow" } else { "Script" } + ))); + } + } + // A pinned step is dispatched by its hash alone, ignoring the path beside it, so a readable + // path paired with another script's hash would still run that other script. + for (path, hash) in &refs.pinned_scripts { + let exists = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND hash = $3)", + w_id, + path, + hash.0, + ) + .fetch_one(&mut **tx) + .await? + .unwrap_or(false); + if !exists { + return Err(Error::PermissionDenied(format!( + "Version {hash} is not a readable version of {path}" + ))); + } + } + Ok(()) +} + +/// What a restricted role must pass to store an `ai_agent` resource, deployed or as a draft. Its +/// tools run in the agent's own runs and in every flow step linking it, so it is held to the rules +/// of a composed flow, under the same capability. `tx` is the write's own, begun as the caller. +pub async fn validate_operator_agent( + value: &serde_json::Value, + authed: &ApiAuthed, + db: &DB, + tx: &mut Transaction<'_, Postgres>, + w_id: &str, +) -> error::Result<()> { + if check_operator_can_build(db, w_id, authed, BuilderKind::Flows, "write AI agents").await? + == AuthorLevel::Full + { + return Ok(()); + } + let tools = value + .get("tools") + .cloned() + .unwrap_or_else(|| serde_json::json!([])); + let flow: FlowValue = serde_json::from_value(serde_json::json!({"modules": [{ + "id": "agent", + "value": {"type": "aiagent", "input_transforms": {}, "tools": tools} + }]})) + .map_err(|e| Error::BadRequest(format!("Invalid agent tools: {e}")))?; + authorize_composed_flow(&flow, &None, authed, db, tx, w_id) + .await + .map_err(|e| match e { + Error::PermissionDenied(msg) => { + Error::PermissionDenied(msg.replace("edit this flow", "edit this agent")) + } + e => e, + }) +} diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 30c3bb65af..6a09710b5e 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -7,6 +7,7 @@ */ pub mod auth; +pub mod composed; #[cfg(feature = "private")] pub mod ee; pub mod ee_oss; @@ -590,7 +591,9 @@ pub fn ensure_scopes_within_caller( for requested in requested_restrictions { if requested.starts_with("mcp:") { - if !caller_mcp.contains(requested.as_str()) { + // `mcp:session` (windmill_mcp's SESSION_SCOPE) grants nothing: it only picks + // the toolset an `mcp:all` token gets, and `mcp:all` is matched here itself. + if requested != "mcp:session" && !caller_mcp.contains(requested.as_str()) { return Err(Error::PermissionDenied(format!( "A scope-restricted token cannot grant MCP scope '{requested}' unless the \ caller holds the same scope verbatim" @@ -943,7 +946,7 @@ pub async fn gate_operator_writes( let w_id = params.get("workspace_id").ok_or_else(|| { Error::internal_err("operator write gate layered outside a workspaced router".to_string()) })?; - check_operator_can_manage(&db, w_id, authed.is_operator, kind).await?; + check_operator_can_manage(&db, w_id, &authed, kind).await?; Ok(next.run(Request::from_parts(parts, body)).await) } @@ -1963,6 +1966,11 @@ mod tests { opt_scopes(Some(vec!["mcp:scripts:*"])).as_deref() ) .is_err()); + assert!(ensure_scopes_within_caller( + &mcp_all, + opt_scopes(Some(vec!["mcp:all", "mcp:session"])).as_deref() + ) + .is_ok()); } #[test] diff --git a/backend/windmill-api-configs/src/lib.rs b/backend/windmill-api-configs/src/lib.rs index 890a561679..8336888088 100644 --- a/backend/windmill-api-configs/src/lib.rs +++ b/backend/windmill-api-configs/src/lib.rs @@ -35,6 +35,7 @@ pub fn global_service() -> Router { "/list_autoscaling_events/{worker_group}", get(list_autoscaling_events), ) + .route("/test_autoscaling/{worker_group}", post(test_autoscaling)) .route( "/native_kubernetes_autoscaling_healthcheck", get(native_kubernetes_autoscaling_healthcheck), @@ -224,13 +225,15 @@ async fn update_config( #[cfg(not(feature = "enterprise"))] let config = if name.starts_with("worker__") { - // In CE, only allow setting worker_tags, cache_clear, init_bash, native_mode and paused + // In CE, only allow setting worker_tags, cache_clear, init_bash, native_mode, paused and + // disable_job_proxy serde_json::json!({ "worker_tags": config.get("worker_tags"), "cache_clear": config.get("cache_clear"), "init_bash": config.get("init_bash"), "native_mode": config.get("native_mode"), - "paused": config.get("paused") + "paused": config.get("paused"), + "disable_job_proxy": config.get("disable_job_proxy") }) } else { config @@ -417,6 +420,48 @@ async fn native_kubernetes_autoscaling_healthcheck() -> Result<(), error::Error> )) } +#[derive(Serialize)] +struct TestAutoscalingResponse { + job_id: Option, +} + +#[cfg(all(feature = "enterprise", feature = "private"))] +async fn test_autoscaling( + authed: ApiAuthed, + Extension(db): Extension, + Path(worker_group): Path, + Json(test): Json, +) -> error::JsonResult { + require_devops_role(&db, &authed).await?; + audit_log( + &db, + &authed, + "worker_config.test_autoscaling", + ActionKind::Execute, + "global", + Some(&worker_group), + None, + ) + .await?; + let job_id = windmill_autoscaling::autoscaling_ee::test_autoscaling( + &db, + &worker_group, + test, + &authed.email, + ) + .await?; + Ok(Json(TestAutoscalingResponse { + job_id: job_id.map(|id| id.to_string()), + })) +} + +#[cfg(not(all(feature = "enterprise", feature = "private")))] +async fn test_autoscaling() -> error::JsonResult { + Err(error::Error::BadRequest( + "Autoscaling available only in the enterprise version".to_string(), + )) +} + async fn list_available_python_versions() -> error::JsonResult> { #[cfg(not(all(feature = "python", feature = "run_inline")))] return Err(error::Error::BadRequest( diff --git a/backend/windmill-api-flow-conversations/src/lib.rs b/backend/windmill-api-flow-conversations/src/lib.rs index 7320721ea5..2ed3531cca 100644 --- a/backend/windmill-api-flow-conversations/src/lib.rs +++ b/backend/windmill-api-flow-conversations/src/lib.rs @@ -14,7 +14,7 @@ pub use windmill_common::flow_conversations::FlowConversation; use windmill_common::{ db::{UserDB, DB}, error::{JsonResult, Result}, - flow_conversations::{running_turns, MessageType, RunningTurn}, + flow_conversations::{running_turns, MessageType, RunningTurn, ANONYMOUS_CONVERSATION_OWNER}, utils::{not_found_if_none, paginate, truncate_with_ellipsis, Pagination}, }; @@ -96,7 +96,8 @@ async fn list_conversations( "created_by", "is_test", ]) - .and_where_eq("workspace_id", "?".bind(&w_id)); + .and_where_eq("workspace_id", "?".bind(&w_id)) + .and_where_ne("created_by", "?".bind(&ANONYMOUS_CONVERSATION_OWNER)); if let Some(flow_path) = &query.flow_path { sqlb.and_where_eq("flow_path", "?".bind(flow_path)); diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index fe4d8c37d4..5d4268a93c 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -16,9 +16,10 @@ use axum::{ }; use windmill_api_auth::{ auth::{list_tokens_internal, TruncatedTokenWithEmail}, - build_scope_path_predicate, check_scopes, get_scope_tags, maybe_refresh_folders, - require_owner_of_path, ApiAuthed, + build_scope_path_predicate, check_scopes, maybe_refresh_folders, require_owner_of_path, + ApiAuthed, }; +use windmill_common::roles::AuthorLevel; use windmill_common::workspaces::{ check_deploy_rules, check_operator_can_build, operator_builder_rights, BuilderKind, RuleCheckResult, @@ -133,6 +134,17 @@ async fn list_search_flows( Ok(Json(rows)) } +/// `WHERE` condition matching one label, directly on the flow or inherited from its folder. +/// +/// The template has two `?`, so both are filled in a single `binds` pass. Chaining `bind` +/// would not work: `bind` replaces the first `?` of the string *as it is at that moment*, +/// so the second call would find the `?` that the first call inserted as part of the bound +/// value and substitute there, leaving the value partly outside its quotes. +fn label_condition(label: &str) -> String { + "(o.labels @> ARRAY[?] OR folder_labels(o.workspace_id, o.path) @> ARRAY[?])" + .binds(&[&label.trim()]) +} + async fn list_flows( authed: ApiAuthed, Extension(user_db): Extension, @@ -216,11 +228,7 @@ async fn list_flows( } if let Some(label) = &lq.label { for l in label.split(',') { - sqlb.and_where( - "(o.labels @> ARRAY[?] OR folder_labels(o.workspace_id, o.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), - ); + sqlb.and_where(label_condition(l)); } } @@ -244,7 +252,7 @@ async fn list_flows( // Append the authed user's drafts at paths with no deployed flow; see scripts.rs. if lq.include_draft_only.unwrap_or(false) - && (!authed.is_operator || operator_builder_rights(&db, &w_id).await?.flows) + && operator_builder_rights(&db, &w_id, &authed).await?.flows && offset == 0 && lq.path_start.is_none() && lq.path_exact.is_none() @@ -576,6 +584,7 @@ async fn list_paths_linking_agent( async fn validate_flow( new_flow: &NewFlow, + flows_level: AuthorLevel, authed: &ApiAuthed, db: &DB, user_db: &UserDB, @@ -591,7 +600,7 @@ async fn validate_flow( guard_flow_from_debounce_data(new_flow).await?; - if authed.is_operator { + if flows_level == AuthorLevel::Compose { validate_operator_flow( &new_flow.parse_flow_value()?, &new_flow.tag, @@ -641,85 +650,11 @@ pub async fn validate_operator_composed_flow( user_db: &UserDB, w_id: &str, ) -> error::Result<()> { - let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?; - - // A tag is how a step picks the worker group it runs on: unauthorized, a builder could route - // a job onto a privileged one. - refs.tags.extend(flow_tag.clone().filter(|t| !t.is_empty())); - if !refs.tags.is_empty() { - // Job-aware: a WM_TOKEN running as a superadmin must not unlock restricted tags. - let is_super_admin = windmill_api_auth::is_super_admin_authed(db, authed).await?; - for tag in &refs.tags { - windmill_common::jobs::check_tag_available_for_workspace_internal( - db, - w_id, - tag, - None, - std::future::ready(w_id.to_string()), - is_super_admin, - get_scope_tags(authed), - ) - .await?; - } - } - - if refs.runnables.is_empty() && refs.pinned_scripts.is_empty() { - return Ok(()); - } - // A flow can step through the same script thirty times; this runs on every write, preview and - // dependency job. - refs.runnables.sort(); - refs.runnables.dedup(); - refs.pinned_scripts - .sort_by_key(|(path, hash)| (path.clone(), hash.0)); - refs.pinned_scripts - .dedup_by_key(|(path, hash)| (path.clone(), hash.0)); - // The worker resolves a step's path with the root DB handle and runs it as that runnable's - // `on_behalf_of`, so composing an unreadable path would run code the builder cannot see. RLS - // on this transaction is the check. let mut tx = user_db.clone().begin(authed).await?; - for (is_flow, path) in &refs.runnables { - let readable = if *is_flow { - sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2)", - w_id, - path, - ) - } else { - sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2)", - w_id, - path, - ) - } - .fetch_one(&mut *tx) - .await? - .unwrap_or(false); - if !readable { - return Err(Error::PermissionDenied(format!( - "{} {path} does not exist or is not readable by you", - if *is_flow { "Flow" } else { "Script" } - ))); - } - } - // A pinned step is dispatched by its hash alone, ignoring the path beside it, so a readable - // path paired with another script's hash would still run that other script. - for (path, hash) in &refs.pinned_scripts { - let exists = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND hash = $3)", - w_id, - path, - hash.0, - ) - .fetch_one(&mut *tx) - .await? - .unwrap_or(false); - if !exists { - return Err(Error::PermissionDenied(format!( - "Version {hash} is not a readable version of {path}" - ))); - } - } + windmill_api_auth::composed::authorize_composed_flow( + value, flow_tag, authed, db, &mut tx, w_id, + ) + .await?; tx.commit().await?; Ok(()) } @@ -732,14 +667,8 @@ async fn create_flow( Path(w_id): Path, Json(mut nf): Json, ) -> Result<(StatusCode, String)> { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Flows, - "create flows", - ) - .await?; + let flows_level = + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Flows, "create flows").await?; check_scopes(&authed, || format!("flows:write:{}", nf.path))?; // A `<= 0` flow timeout is "unset", not a 0-second limit that kills every run instantly. @@ -759,7 +688,7 @@ async fn create_flow( return Err(Error::PermissionDenied(msg)); } - validate_flow(&nf, &authed, &db, &user_db, &w_id).await?; + validate_flow(&nf, flows_level, &authed, &db, &user_db, &w_id).await?; if *CLOUD_HOSTED { let nb_flows = sqlx::query_scalar!("SELECT COUNT(*) FROM flow WHERE workspace_id = $1", &w_id) @@ -1354,14 +1283,8 @@ async fn update_flow( Path((w_id, flow_path)): Path<(String, StripPath)>, Json(ef): Json, ) -> Result { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Flows, - "update flows", - ) - .await?; + let flows_level = + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Flows, "update flows").await?; let flow_path = flow_path.to_path(); // The URL identifies the flow being updated; the body path is only needed to rename. let mut nf = ef.into_new_flow(flow_path); @@ -1388,7 +1311,7 @@ async fn update_flow( return Err(Error::PermissionDenied(msg)); } - validate_flow(&nf, &authed, &db, &user_db, &w_id).await?; + validate_flow(&nf, flows_level, &authed, &db, &user_db, &w_id).await?; let authed = maybe_refresh_folders(&flow_path, &w_id, authed, &db).await; // Before `tx` opens, for the reason given in `create_flow`. @@ -2056,14 +1979,7 @@ async fn archive_flow_by_path( Path((w_id, path)): Path<(String, StripPath)>, Json(archived): Json, ) -> Result { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Flows, - "archive flows", - ) - .await?; + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Flows, "archive flows").await?; let path = path.to_path(); check_scopes(&authed, || format!("flows:write:{}", path))?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( @@ -2204,14 +2120,7 @@ async fn delete_flow_by_path( Path((w_id, path)): Path<(String, StripPath)>, Query(query): Query, ) -> Result { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Flows, - "delete flows", - ) - .await?; + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Flows, "delete flows").await?; let path = path.to_path(); check_scopes(&authed, || format!("flows:write:{}", path))?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( @@ -2382,6 +2291,31 @@ mod tests { const SECOND: Duration = Duration::from_secs(1); + #[test] + fn label_condition_fills_both_placeholders_in_one_pass() { + // Ordinary label: unchanged behaviour, the value appears quoted in both positions. + assert_eq!( + super::label_condition(" finance "), + "(o.labels @> ARRAY['finance'] OR folder_labels(o.workspace_id, o.path) @> ARRAY['finance'])" + ); + + // A `?` in the label must stay inside the quoted literal in both positions and must + // not leave a placeholder behind. With chained `bind`s this produced + // `ARRAY['a'a?b'b'] ... ARRAY[?]`, i.e. label text outside the quotes. + let cond = super::label_condition("a?b"); + assert_eq!( + cond, + "(o.labels @> ARRAY['a?b'] OR folder_labels(o.workspace_id, o.path) @> ARRAY['a?b'])" + ); + assert!(!cond.contains("ARRAY[?]")); + + // Single quotes keep being escaped by doubling. + assert_eq!( + super::label_condition("a'?b"), + "(o.labels @> ARRAY['a''?b'] OR folder_labels(o.workspace_id, o.path) @> ARRAY['a''?b'])" + ); + } + #[test] fn flowmodule_serde() { let fv = FlowValue { diff --git a/backend/windmill-api-groups/src/granular_acls.rs b/backend/windmill-api-groups/src/granular_acls.rs index f7c3398adc..c867e89a60 100644 --- a/backend/windmill-api-groups/src/granular_acls.rs +++ b/backend/windmill-api-groups/src/granular_acls.rs @@ -117,7 +117,7 @@ async fn add_granular_acl( } if let Some(manage_kind) = manage_kind_for_acl_kind(kind) { - check_operator_can_manage(&db, &w_id, authed.is_operator, manage_kind).await?; + check_operator_can_manage(&db, &w_id, &authed, manage_kind).await?; } let identifier = if kind == "group_" || kind == "folder" || kind == "volume" { @@ -368,7 +368,7 @@ async fn remove_granular_acl( } if let Some(manage_kind) = manage_kind_for_acl_kind(kind) { - check_operator_can_manage(&db, &w_id, authed.is_operator, manage_kind).await?; + check_operator_can_manage(&db, &w_id, &authed, manage_kind).await?; } if !authed.is_admin { diff --git a/backend/windmill-api-groups/src/groups.rs b/backend/windmill-api-groups/src/groups.rs index 860e486a75..0d3b5e360d 100644 --- a/backend/windmill-api-groups/src/groups.rs +++ b/backend/windmill-api-groups/src/groups.rs @@ -218,12 +218,13 @@ pub async fn require_is_owner( } async fn _check_nb_of_groups(db: &DB) -> Result<()> { - let nb_groups = sqlx::query_scalar!("SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers'",) + // Groups that back workspace settings do not count toward the limit. + let nb_groups = sqlx::query_scalar!("SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers' AND name != 'variable_expiration_handler'",) .fetch_one(db) .await?; if nb_groups.unwrap_or(0) >= 3 { return Err(Error::BadRequest( - "You have reached the maximum number of groups (3 outside of native groups 'all', 'slack', 'error_handler' and 'wm_deployers') without an enterprise license" + "You have reached the maximum number of groups (3 outside of native groups 'all', 'slack', 'error_handler', 'wm_deployers' and 'variable_expiration_handler') without an enterprise license" .to_string(), )); } diff --git a/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs index 628614056c..540282de9a 100644 --- a/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs +++ b/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs @@ -153,6 +153,10 @@ async fn test_agent_run_identity_and_needs_read(db: Pool) -> anyhow::R for raw in [ r#"{"user_message":"$var:u/test-user-3/secret"}"#, r#"{"user_message":"\u0024var:u/test-user-3/secret"}"#, + // Resolved once a step combines it with an argument holding a reference. + r#"{"user_message":"$WM_TOKEN"}"#, + // jsonb drops the undecodable duplicate and keeps the reference. + r#"{"user_message":{"n":1e400,"n":0,"r":"\u0024var:u/test-user-3/secret"}}"#, ] { let resp = reqwest::Client::new() .post(format!("{base_url}/w/test-workspace/{run}")) @@ -163,6 +167,14 @@ async fn test_agent_run_identity_and_needs_read(db: Pool) -> anyhow::R .await?; assert_eq!(resp.status().as_u16(), 400, "a reference in {raw}"); } + let (status, body) = post( + &base_url, + "SECRET_TOKEN_2", + &run, + json!({ "user_message": {"$match": {"currency": "$USD", "_id": "$category"}} }), + ) + .await?; + assert_eq!(status, 201, "nothing the worker resolves: {body}"); // The run takes its conversation outside the caller's row policy, so a reader must not // continue another user's conversation; an admin still may, as the policy allows. diff --git a/backend/windmill-api-integration-tests/tests/datatable_roles.rs b/backend/windmill-api-integration-tests/tests/datatable_roles.rs index 764cc3ac04..e1623ef901 100644 --- a/backend/windmill-api-integration-tests/tests/datatable_roles.rs +++ b/backend/windmill-api-integration-tests/tests/datatable_roles.rs @@ -1737,7 +1737,7 @@ async fn an_operator_neither_writes_nor_runs_a_migration(db: Pool) -> let status = resp.status(); let text = resp.text().await?; assert!( - status == 401 && text.contains("Operators cannot"), + status == 403 && text.contains("Your role cannot"), "{status}: {text}" ); } diff --git a/backend/windmill-api-integration-tests/tests/drafts.rs b/backend/windmill-api-integration-tests/tests/drafts.rs index f45ffb3f8e..0d1e3c9185 100644 --- a/backend/windmill-api-integration-tests/tests/drafts.rs +++ b/backend/windmill-api-integration-tests/tests/drafts.rs @@ -143,6 +143,12 @@ async fn test_update_draft_write_authorization(db: Pool) -> anyhow::Re .send() .await?; assert_eq!(r.status(), 200, "own namespace allowed"); + let r = user2 + .post(save_url(port, "data_pipeline", "u/test-user-2/pipeline")) + .json(&json!({ "value": { "a": 1 } })) + .send() + .await?; + assert_eq!(r.status(), 200, "a developer saves data pipeline drafts"); // Another user's namespace, no grant → rejected. let r = user2 @@ -166,6 +172,16 @@ async fn test_update_draft_write_authorization(db: Pool) -> anyhow::Re .send() .await?; assert_eq!(r.status(), 403, "operator rejected"); + let r = op + .post(save_url(port, "data_pipeline", "u/test-user-3/pipeline")) + .json(&json!({ "value": { "a": 1 } })) + .send() + .await?; + assert_eq!( + r.status(), + 403, + "a role that cannot code has no pipeline drafts" + ); Ok(()) } diff --git a/backend/windmill-api-integration-tests/tests/jobs_authed.rs b/backend/windmill-api-integration-tests/tests/jobs_authed.rs index 2c5d2ee78e..2592ecdf7a 100644 --- a/backend/windmill-api-integration-tests/tests/jobs_authed.rs +++ b/backend/windmill-api-integration-tests/tests/jobs_authed.rs @@ -626,10 +626,9 @@ async fn test_resolve_completed_jobs_scoping(db: Pool) -> anyhow::Resu .json(&json!({ "job_ids": [mine] })) .send() .await?; - // Error::NotAuthorized maps to 401 (403 is RequireAdmin/PermissionDenied). assert_eq!( resp.status().as_u16(), - 401, + 403, "operators must be refused: {}", resp.text().await? ); diff --git a/backend/windmill-api-integration-tests/tests/native_triggers.rs b/backend/windmill-api-integration-tests/tests/native_triggers.rs index e7f0147323..285d560588 100644 --- a/backend/windmill-api-integration-tests/tests/native_triggers.rs +++ b/backend/windmill-api-integration-tests/tests/native_triggers.rs @@ -14,6 +14,7 @@ use sqlx::{Pool, Postgres}; use axum::http::StatusCode; use windmill_api_auth::{ApiAuthed, ScopePathFilter}; use windmill_common::{ + db::UserDB, error::Error, variables::{build_crypt, encrypt}, }; @@ -22,12 +23,13 @@ use windmill_native_triggers::{ get_workspace_integration, github::GitHub, google::{parse_stop_channel_params, should_renew_channel}, - grant_refused, http_error_status, list_native_triggers, map_external_error, - native_trigger_is_enabled, + grant_refused, http_error_status, list_native_triggers, list_usable_connections, + map_external_error, native_trigger_is_enabled, nextcloud::NextCloud, - require_native_integration_use, set_native_trigger_enabled, store_native_trigger, - store_workspace_integration, update_native_trigger, External, ExternalReadFailure, - HttpRequestError, NativeTriggerConfig, OAuthConfig, ServiceName, + require_native_integration_use, resolve_usable_connection, set_native_trigger_enabled, + store_native_trigger, store_workspace_integration, update_native_trigger, + update_oauth_token_resource, External, ExternalReadFailure, HttpRequestError, + NativeTriggerConfig, OAuthConfig, ServiceName, }; // ============================================================================ @@ -133,7 +135,6 @@ async fn setup_oauth_integration( "test-workspace", service_name, oauth_data, - Some(resource_path), ) .await?; tx.commit().await?; @@ -149,73 +150,125 @@ fn now_ms() -> i64 { } // ============================================================================ -// 1. Resource Path Change +// 1. Several connections of one service // ============================================================================ +/// Each connection keeps its own tokens: a refresh written back for one, or disconnecting one, +/// must not touch another. Providers that rotate refresh tokens invalidate the old one, so a +/// refresh token copied onto the wrong account breaks that account's next refresh. #[sqlx::test(migrations = "../migrations", fixtures("base"))] -async fn test_resource_path_change(db: Pool) -> anyhow::Result<()> { - let path_a = "u/test-user/native_gworkspace"; - setup_oauth_integration( +async fn test_connections_are_isolated(db: Pool) -> anyhow::Result<()> { + let path_a = "u/test-user/native_nextcloud"; + let path_b = "u/other-user/native_nextcloud"; + let mut account_a = 0; + for (path, token) in [(path_a, "a"), (path_b, "b")] { + let account = setup_oauth_integration( + &db, + ServiceName::Nextcloud, + path, + &format!("access-{token}"), + &format!("refresh-{token}"), + None, + ) + .await?; + if path == path_a { + account_a = account; + } + } + + update_oauth_token_resource( &db, - ServiceName::Google, - path_a, - "token-a", - "refresh-a", - None, - ) - .await?; - - // Verify decrypt works at path A - let config: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Google).await?; - assert_eq!(config.access_token, "token-a"); - - // Cleanup old path - let mut tx = db.begin().await?; - windmill_native_triggers::workspace_integrations::cleanup_oauth_resource( - &mut *tx, "test-workspace", - ServiceName::Google, + account_a, + "access-a2", + Some("refresh-a2"), ) .await; - tx.commit().await?; - // Recreate at path B - let path_b = "u/test-user/native_gworkspace_v2"; - setup_oauth_integration( - &db, - ServiceName::Google, - path_b, - "token-b", - "refresh-b", - None, + let a: OAuthConfig = + decrypt_oauth_data(&db, "test-workspace", ServiceName::Nextcloud, Some(path_a)).await?; + let b: OAuthConfig = + decrypt_oauth_data(&db, "test-workspace", ServiceName::Nextcloud, Some(path_b)).await?; + assert_eq!( + (a.access_token.as_str(), a.refresh_token.as_deref()), + ("access-a2", Some("refresh-a2")) + ); + assert_eq!( + (b.access_token.as_str(), b.refresh_token.as_deref()), + ("access-b", Some("refresh-b")) + ); + + let mut tx = db.begin().await?; + windmill_native_triggers::workspace_integrations::cleanup_connection( + &mut *tx, + "test-workspace", + path_a, ) .await?; + tx.commit().await?; - // Path A resources should be gone - let var_count: i64 = sqlx::query_scalar!( - "SELECT count(*) FROM variable WHERE workspace_id = 'test-workspace' AND path = $1", - path_a, + assert!(decrypt_oauth_data::( + &db, + "test-workspace", + ServiceName::Nextcloud, + Some(path_a) ) - .fetch_one(&db) - .await? - .unwrap_or(0); - assert_eq!(var_count, 0, "variable at old path should be deleted"); + .await + .is_err()); + let b: OAuthConfig = + decrypt_oauth_data(&db, "test-workspace", ServiceName::Nextcloud, Some(path_b)).await?; + assert_eq!(b.refresh_token.as_deref(), Some("refresh-b")); - let res_count: i64 = sqlx::query_scalar!( - "SELECT count(*) FROM resource WHERE workspace_id = 'test-workspace' AND path = $1", - path_a, + Ok(()) +} + +/// A member who cannot read the admin's connection may still use it once it is shared as the +/// workspace connection. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_workspace_connection_usable_by_members(db: Pool) -> anyhow::Result<()> { + let path = "u/test-user/native_nextcloud"; + setup_oauth_integration(&db, ServiceName::Nextcloud, path, "a", "r", None).await?; + let member = ApiAuthed { + email: "test2@windmill.dev".to_string(), + username: "test-user-2".to_string(), + is_admin: false, + ..test_authed() + }; + let usable_paths = || async { + let mut tx = UserDB::new(db.clone()).begin(&member).await?; + let connections = + list_usable_connections(&db, &mut tx, "test-workspace", ServiceName::Nextcloud).await?; + tx.commit().await?; + anyhow::Ok( + connections + .into_iter() + .map(|c| (c.path, c.workspace)) + .collect::>(), + ) + }; + + assert!(usable_paths().await?.is_empty()); + + sqlx::query( + "UPDATE workspace_integrations SET resource_path = $1 + WHERE workspace_id = 'test-workspace' AND service_name = 'nextcloud'", ) - .fetch_one(&db) - .await? - .unwrap_or(0); - assert_eq!(res_count, 0, "resource at old path should be deleted"); + .bind(path) + .execute(&db) + .await?; + assert_eq!(usable_paths().await?, vec![(path.to_string(), true)]); - // Path B should work - let config: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Google).await?; - assert_eq!(config.access_token, "token-b"); - assert_eq!(config.refresh_token.as_deref(), Some("refresh-b")); + // Clients and specs that predate connections name none: they keep getting the shared + // account once the member also has their own. + let own = "u/test-user-2/native_nextcloud"; + setup_oauth_integration(&db, ServiceName::Nextcloud, own, "b", "s", None).await?; + let mut tx = UserDB::new(db.clone()).begin(&member).await?; + let default = + resolve_usable_connection(&db, &mut tx, "test-workspace", ServiceName::Nextcloud, None) + .await?; + tx.commit().await?; + assert_eq!(usable_paths().await?.len(), 2); + assert_eq!(default, path); Ok(()) } @@ -237,8 +290,13 @@ async fn test_decrypt_workspace_level(db: Pool) -> anyhow::Result<()> ) .await?; - let config: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Google).await?; + let config: OAuthConfig = decrypt_oauth_data( + &db, + "test-workspace", + ServiceName::Google, + Some(resource_path), + ) + .await?; assert_eq!(config.access_token, "ws-access-token"); assert_eq!(config.refresh_token.as_deref(), Some("ws-refresh-token")); @@ -282,8 +340,13 @@ async fn test_decrypt_instance_level(db: Pool) -> anyhow::Result<()> { ) .await?; - let config: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Google).await?; + let config: OAuthConfig = decrypt_oauth_data( + &db, + "test-workspace", + ServiceName::Google, + Some(resource_path), + ) + .await?; assert_eq!(config.client_id, "instance-client-id"); assert_eq!(config.client_secret, "instance-client-secret"); @@ -306,8 +369,13 @@ async fn test_token_update_persists(db: Pool) -> anyhow::Result<()> { .await?; // Verify old tokens - let config: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Google).await?; + let config: OAuthConfig = decrypt_oauth_data( + &db, + "test-workspace", + ServiceName::Google, + Some(resource_path), + ) + .await?; assert_eq!(config.access_token, "old-access-token"); // Simulate token refresh: update variable + account @@ -330,8 +398,13 @@ async fn test_token_update_persists(db: Pool) -> anyhow::Result<()> { .await?; // Verify new tokens - let config: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Google).await?; + let config: OAuthConfig = decrypt_oauth_data( + &db, + "test-workspace", + ServiceName::Google, + Some(resource_path), + ) + .await?; assert_eq!(config.access_token, "new-access-token"); assert_eq!(config.refresh_token.as_deref(), Some("new-refresh-token")); @@ -342,24 +415,57 @@ async fn test_token_update_persists(db: Pool) -> anyhow::Result<()> { // 3. Channel Expiration Renewal — should_renew_channel // ============================================================================ -#[test] -fn test_require_native_integration_use_blocks_operators() { - // Regression: the integration *use* routes (calendar/drive/repo/event pickers) - // must reject read-only operators, who cannot create native triggers and so - // must not be able to drive the admin-configured integration's upstream API. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +async fn test_require_native_integration_use_needs_code_and_manage_triggers( + db: Pool, +) -> anyhow::Result<()> { + // The pickers drive the admin-connected account's upstream API: the default operator, which + // may manage triggers but not write code, must stay locked out of them. + windmill_common::roles::invalidate_all_roles_cache(); let mut operator = test_authed(); + operator.username = "operator".to_string(); operator.is_admin = false; operator.is_operator = true; - assert!(require_native_integration_use(&operator).is_err()); + assert!( + require_native_integration_use(&db, "test-workspace", &operator) + .await + .is_err() + ); - // A regular non-admin author (the population that configures triggers) is allowed. - let mut author = test_authed(); - author.is_admin = false; - author.is_operator = false; - assert!(require_native_integration_use(&author).is_ok()); + let set_override = |caps: &'static str| { + let db = db.clone(); + async move { + sqlx::query( + "UPDATE workspace_settings SET role_overrides = jsonb_build_object('operator', + jsonb_build_object('capabilities', $1::jsonb)) + WHERE workspace_id = 'test-workspace'", + ) + .bind(caps) + .execute(&db) + .await + .unwrap(); + windmill_common::roles::invalidate_all_roles_cache(); + } + }; + set_override(r#"{"code": true}"#).await; + assert!( + require_native_integration_use(&db, "test-workspace", &operator) + .await + .is_ok() + ); + set_override(r#"{"code": true, "manage_triggers": false}"#).await; + assert!( + require_native_integration_use(&db, "test-workspace", &operator) + .await + .is_err() + ); - // Admins are allowed. - assert!(require_native_integration_use(&test_authed()).is_ok()); + assert!( + require_native_integration_use(&db, "test-workspace", &test_authed()) + .await + .is_ok() + ); + Ok(()) } #[test] @@ -458,6 +564,7 @@ async fn test_delete_integration_full_cascade(db: Pool) -> anyhow::Res json!({"triggerType": "drive"}), None, true, + "u/test-user/native_conn", ) .await?; @@ -468,12 +575,12 @@ async fn test_delete_integration_full_cascade(db: Pool) -> anyhow::Res // Step 2: Cleanup OAuth resources let mut tx = db.begin().await?; - windmill_native_triggers::workspace_integrations::cleanup_oauth_resource( + windmill_native_triggers::workspace_integrations::cleanup_service_connections( &mut *tx, "test-workspace", ServiceName::Google, ) - .await; + .await?; tx.commit().await?; // Step 3: Delete workspace integration @@ -549,17 +656,18 @@ async fn test_cleanup_preserves_triggers(db: Pool) -> anyhow::Result<( json!({"triggerType": "drive"}), None, true, + "u/test-user/native_conn", ) .await?; // Cleanup OAuth only — should NOT remove the trigger let mut tx = db.begin().await?; - windmill_native_triggers::workspace_integrations::cleanup_oauth_resource( + windmill_native_triggers::workspace_integrations::cleanup_connection( &mut *tx, "test-workspace", - ServiceName::Google, + resource_path, ) - .await; + .await?; tx.commit().await?; // OAuth resources gone @@ -607,6 +715,7 @@ async fn test_rename_moves_native_trigger(db: Pool) -> anyhow::Result< json!({"event": "OCP\\Files\\Events\\Node\\NodeCreatedEvent"}), None, true, + "u/test-user/native_conn", ) .await?; // An unrelated trigger already sitting on the target path must not be reported as moved. @@ -624,6 +733,7 @@ async fn test_rename_moves_native_trigger(db: Pool) -> anyhow::Result< json!({"event": "OCP\\Files\\Events\\Node\\NodeCreatedEvent"}), None, true, + "u/test-user/native_conn", ) .await?; @@ -696,6 +806,7 @@ async fn test_list_native_triggers_scope_filter(db: Pool) -> anyhow::R json!({"event": "OCP\\Files\\Events\\Node\\NodeCreatedEvent"}), None, true, + "u/test-user/native_conn", ) .await?; } @@ -801,7 +912,7 @@ fn test_provider_rejection_is_readable_and_not_internal() { "the envelope should not reach the user: {message}" ); assert!( - message.contains("Workspace settings > Integrations"), + message.contains("the workspace's shared account"), "the hint should say what to do: {message}" ); } @@ -931,6 +1042,7 @@ async fn test_native_trigger_enabled_toggle(db: Pool) -> anyhow::Resul json!({"event": "OCA\\Files\\Event\\LoadAdditionalScriptsEvent"}), None, true, + "u/test-user/native_conn", ) .await?; @@ -980,6 +1092,7 @@ async fn test_native_trigger_enabled_toggle(db: Pool) -> anyhow::Resul json!({}), None, false, + "u/test-user/native_conn", ) .await?; assert!( @@ -997,6 +1110,7 @@ async fn test_native_trigger_enabled_toggle(db: Pool) -> anyhow::Resul json!({}), None, true, + "u/test-user/native_conn", ) .await?; assert!( diff --git a/backend/windmill-api-integration-tests/tests/operator_builder_apps.rs b/backend/windmill-api-integration-tests/tests/operator_builder_apps.rs index 7033d093f2..71a7a2b8fa 100644 --- a/backend/windmill-api-integration-tests/tests/operator_builder_apps.rs +++ b/backend/windmill-api-integration-tests/tests/operator_builder_apps.rs @@ -1,7 +1,6 @@ use serde_json::json; use serial_test::serial; use sqlx::{Pool, Postgres}; -use windmill_common::workspaces::invalidate_operator_rights_cache; use windmill_test_utils::*; /// Every test here must be `#[serial]`: the rights cache is process-global and keyed by workspace id @@ -22,16 +21,18 @@ fn client(token: &str) -> reqwest::Client { async fn set_builder(db: &Pool, flows: bool, apps: bool) -> anyhow::Result<()> { sqlx::query( - "UPDATE workspace_settings SET operator_settings = $1::text::jsonb WHERE workspace_id = $2", + "UPDATE workspace_settings SET role_overrides = $1::text::jsonb WHERE workspace_id = $2", ) .bind(format!( - r#"{{"builder_flows": {flows}, "builder_apps": {apps}}}"# + r#"{{"operator": {{"capabilities": {{"flows": "{}", "apps": "{}"}}}}}}"#, + if flows { "compose" } else { "none" }, + if apps { "compose" } else { "none" }, )) .bind(WS) .execute(db) .await?; // The rights are read through a process-global 60s cache keyed by workspace id. - invalidate_operator_rights_cache(WS); + windmill_common::roles::invalidate_all_roles_cache(); Ok(()) } diff --git a/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs index 7be3920124..6bed27eca5 100644 --- a/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs +++ b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs @@ -1,6 +1,5 @@ use serde_json::json; use sqlx::{Pool, Postgres}; -use windmill_common::workspaces::invalidate_operator_rights_cache; use windmill_test_utils::*; const WS: &str = "test-workspace"; @@ -19,14 +18,17 @@ fn operator_client() -> reqwest::Client { async fn set_builder(db: &Pool, flows: bool) -> anyhow::Result<()> { sqlx::query( - "UPDATE workspace_settings SET operator_settings = $1::text::jsonb WHERE workspace_id = $2", + "UPDATE workspace_settings SET role_overrides = $1::text::jsonb WHERE workspace_id = $2", ) - .bind(format!(r#"{{"builder_flows": {flows}}}"#)) + .bind(format!( + r#"{{"operator": {{"capabilities": {{"flows": "{}"}}}}}}"#, + if flows { "compose" } else { "none" } + )) .bind(WS) .execute(db) .await?; // The right is read through a process-global 60s cache keyed by workspace id. - invalidate_operator_rights_cache(WS); + windmill_common::roles::invalidate_all_roles_cache(); Ok(()) } @@ -115,6 +117,16 @@ async fn test_operator_builder_flows_boundary(db: Pool) -> anyhow::Res .send() .await?; assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let notified: Vec = + sqlx::query_scalar("SELECT payload FROM notify_event WHERE channel = $1") + .bind(windmill_common::roles::ROLE_OVERRIDES_CHANGE_CHANNEL) + .fetch_all(&db) + .await?; + assert_eq!( + notified, + vec![WS.to_string()], + "other replicas drop their cached roles only through this event" + ); let resp = c .post(format!("{api}/flows/create")) @@ -313,5 +325,155 @@ async fn test_operator_builder_flows_boundary(db: Pool) -> anyhow::Res resp.text().await? ); + check_builder_agents(&db, &api, &c).await +} + +/// An agent is a resource an operator may otherwise write, and its stored tools run as they are, +/// so only the flow right opens it, and every write of one, drafts included, is checked like a +/// composed flow. Part of the boundary test: the right is read through a process-global cache +/// keyed by workspace id, which a second test in this binary would race. +async fn check_builder_agents( + db: &Pool, + api: &str, + c: &reqwest::Client, +) -> anyhow::Result<()> { + let tool = |mut value: serde_json::Value| { + value["tool_type"] = json!("flowmodule"); + value["input_transforms"] = json!({}); + json!({"tools": [{"id": "t", "summary": "t", "value": value}]}) + }; + let composed = tool(json!({"type": "script", "path": "u/operator/some_script"})); + let inline = tool(json!({"type": "rawscript", "content": "echo x", "language": "bash"})); + let agent = |path: &str, value: &serde_json::Value| json!({"path": path, "resource_type": "ai_agent", "value": value}); + + set_builder(db, false).await?; + let resp = c + .post(format!("{api}/resources/create")) + .json(&agent("u/operator/a1", &composed)) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "an operator without the builder right must not write an agent" + ); + + set_builder(db, true).await?; + let resp = c + .post(format!("{api}/resources/create")) + .json(&agent("u/operator/a1", &inline)) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not save an agent with an inline tool" + ); + let resp = c + .post(format!("{api}/resources/create")) + .json(&agent("u/operator/a1", &composed)) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + let resp = c + .post(format!("{api}/resources/update_value/u/operator/a1")) + .json(&json!({"value": inline})) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not swap an agent's tools for inline code" + ); + // A draft of a deployed agent may leave its type to the deployed row. + let resp = c + .post(format!("{api}/drafts/update/resource/u/operator/a1")) + .json(&json!({"value": {"args": inline, "description": ""}, "force": true})) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not draft an agent with an inline tool" + ); + // Deploying a draft over an agent keeps the row's type, whatever type the draft names. + let resp = c + .post(format!("{api}/drafts/update/resource/u/operator/a1")) + .json(&json!({"value": {"args": inline, "description": "", "resource_type": "object"}, + "force": true})) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not draft inline tools over an agent under another type" + ); + + let linking = |path: &str, agent: &str| { + json!({"path": path, "summary": "", "description": "", "schema": {}, + "value": {"modules": [{"id": "a", "value": {"type": "aiagent", + "input_transforms": {}, "tools": [], "agent": format!("$res:{agent}")}}]}}) + }; + let resp = c + .post(format!("{api}/flows/create")) + .json(&linking("u/operator/agent_f1", "u/operator/a1")) + .send() + .await?; + assert!( + resp.status().is_success(), + "a builder must be able to link a readable agent: {}", + resp.text().await? + ); + let resp = c + .post(format!("{api}/flows/create")) + .json(&linking("u/operator/agent_f2", "u/alice/agent")) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not link an agent it cannot read" + ); + + // A developer's agent may run inline code, and linking it runs it as authored. A step may bind + // the inputs the agent leaves to the model, never one its author set. + let mut dev_agent = inline.clone(); + dev_agent["tools"][0]["value"]["input_transforms"] = json!({ + "set": {"type": "static", "value": "fixed"}, "open": {"type": "ai"}}); + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, created_by) + VALUES ($1, 'u/operator/dev_agent', $2, 'ai_agent', 'alice')", + ) + .bind(WS) + .bind(&dev_agent) + .execute(db) + .await?; + let binding = |path: &str, input: &str| { + let mut flow = linking(path, "u/operator/dev_agent"); + flow["value"]["modules"][0]["value"]["tool_inputs"] = + json!({"t": {input: {"type": "static", "value": "bound"}}}); + flow + }; + let resp = c + .post(format!("{api}/flows/create")) + .json(&binding("u/operator/agent_f4", "open")) + .send() + .await?; + assert!( + resp.status().is_success(), + "a builder must be able to bind an input the agent leaves open: {}", + resp.text().await? + ); + let resp = c + .post(format!("{api}/flows/create")) + .json(&binding("u/operator/agent_f3", "set")) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not override an input the agent's author set" + ); + Ok(()) } diff --git a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs index 22901d1c87..dbc5f36e01 100644 --- a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs +++ b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs @@ -1,7 +1,6 @@ use serde_json::json; use serial_test::serial; use sqlx::{Pool, Postgres}; -use windmill_common::workspaces::invalidate_operator_rights_cache; use windmill_test_utils::*; /// Every test here must be `#[serial]`, and start by dropping the cache entry. The rights cache is @@ -44,7 +43,7 @@ async fn set_settings(api: &str, body: serde_json::Value) -> anyhow::Result .send() .await?; let status = resp.status().as_u16(); - invalidate_operator_rights_cache(WS); + windmill_common::roles::invalidate_all_roles_cache(); Ok(status) } @@ -53,7 +52,7 @@ async fn set_settings(api: &str, body: serde_json::Value) -> anyhow::Result #[serial] async fn test_operator_manage_rights(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; - invalidate_operator_rights_cache(WS); + windmill_common::roles::invalidate_all_roles_cache(); let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); let api = format!("http://localhost:{port}/api/w/{WS}"); @@ -146,7 +145,7 @@ async fn test_manage_triggers_covers_a_route_outside_the_shared_handler( db: Pool, ) -> anyhow::Result<()> { initialize_tracing().await; - invalidate_operator_rights_cache(WS); + windmill_common::roles::invalidate_all_roles_cache(); let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); let api = format!("http://localhost:{port}/api/w/{WS}"); @@ -223,7 +222,7 @@ async fn test_manage_triggers_covers_a_route_outside_the_shared_handler( #[serial] async fn test_manage_rights_admit_matching_drafts(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; - invalidate_operator_rights_cache(WS); + windmill_common::roles::invalidate_all_roles_cache(); let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); let api = format!("http://localhost:{port}/api/w/{WS}"); @@ -253,7 +252,9 @@ async fn test_manage_rights_admit_matching_drafts(db: Pool) -> anyhow: }; let resp = c - .post(format!("{api}/drafts/update/trigger_schedule/u/operator/sched_draft")) + .post(format!( + "{api}/drafts/update/trigger_schedule/u/operator/sched_draft" + )) .json(&json!({ "value": { "path": "u/operator/sched_draft", "schedule": "0 0 12 * * *", @@ -315,7 +316,7 @@ async fn test_manage_rights_admit_matching_drafts(db: Pool) -> anyhow: #[serial] async fn test_operators_draft_resources_and_variables(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; - invalidate_operator_rights_cache(WS); + windmill_common::roles::invalidate_all_roles_cache(); let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); let api = format!("http://localhost:{port}/api/w/{WS}"); @@ -405,3 +406,62 @@ async fn test_operators_draft_resources_and_variables(db: Pool) -> any Ok(()) } + +/// The two endpoints that make the API server run `pg_dump`/`psql` against a database a request +/// names are closed to a role that cannot run code. +/// +/// Both polarities on each route: a 403 alone would equally be a route that does not exist or one +/// refusing the source for some other reason, and the admin's 400 shows the gate is about the role +/// rather than the request. The source is deliberately unresolvable, so the gate is the only thing +/// that can answer 403 and no database is ever reached. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_dumping_a_database_needs_the_code_right(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + windmill_common::roles::invalidate_all_roles_cache(); + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + + let cases = [ + ( + "workspaces/export_pg_schema", + json!({"source": "u/operator/not-a-source"}), + "export a database schema", + ), + ( + "workspaces/import_pg_database", + json!({"source": "u/operator/not-a-source", "target": "u/operator/not-a-source", + "fork_behavior": "schema_only"}), + "import a database", + ), + ]; + + for (route, body, action) in cases { + let resp = operator_client() + .post(format!("{api}/{route}")) + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert_eq!(status, 403, "{route}: {text}"); + assert!( + text.contains(&format!("Your role cannot {action} in this workspace")), + "{route} refused for another reason: {text}" + ); + + let resp = reqwest::Client::new() + .post(format!("{api}/{route}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert_eq!(status, 400, "{route}: {text}"); + assert!(text.contains("Invalid source format"), "{route}: {text}"); + } + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/users.rs b/backend/windmill-api-integration-tests/tests/users.rs index 56656e54dd..3a52e94e4a 100644 --- a/backend/windmill-api-integration-tests/tests/users.rs +++ b/backend/windmill-api-integration-tests/tests/users.rs @@ -1046,3 +1046,117 @@ async fn test_impersonation_session_is_never_refreshed(db: Pool) -> an Ok(()) } + +#[cfg(all(feature = "enterprise", feature = "private"))] +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_set_password_revokes_mcp_oauth_grants(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + + sqlx::raw_sql( + "INSERT INTO mcp_oauth_server_client (client_id, client_name, redirect_uris) + VALUES ('mcp-client', 'MCP client', ARRAY['http://localhost/cb']); + INSERT INTO token (token_hash, token_prefix, email, label, expiration) + VALUES (encode(sha256('MCP_ACCESS_TOKEN'::bytea), 'hex'), 'MCP_ACCESS', 'test2@windmill.dev', + 'mcp-oauth-mcp-client', now() + interval '7 days'), + (encode(sha256('OTHER_MCP_TOKEN'::bytea), 'hex'), 'OTHER_MCP_', 'test3@windmill.dev', + 'mcp-oauth-mcp-client', now() + interval '7 days'); + INSERT INTO mcp_oauth_refresh_token + (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at) + VALUES ('test2-refresh', encode(sha256('MCP_ACCESS_TOKEN'::bytea), 'hex'), 'mcp-client', + 'test2@windmill.dev', 'test-workspace', ARRAY['mcp:all'], gen_random_uuid(), now() + interval '30 days'), + ('test3-refresh', encode(sha256('OTHER_MCP_TOKEN'::bytea), 'hex'), 'mcp-client', + 'test3@windmill.dev', 'test-workspace', ARRAY['mcp:all'], gen_random_uuid(), now() + interval '30 days'); + INSERT INTO mcp_oauth_server_code (code, client_id, user_email, workspace_id, scopes, redirect_uri) + VALUES ('test2-code', 'mcp-client', 'test2@windmill.dev', 'test-workspace', ARRAY['mcp:all'], + 'http://localhost/cb');", + ) + .execute(&db) + .await?; + + // A refresh in flight: it holds the grant lock and writes its rotated tokens while the + // password change is waiting on that lock. + let mut grant = db.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtext('mcp_oauth_grant:' || $1))") + .bind("test2@windmill.dev") + .execute(&mut *grant) + .await?; + let request = tokio::spawn( + authed(client().post(format!( + "http://localhost:{}/api/users/set_password_of/test2@windmill.dev", + server.addr.port() + ))) + .json(&json!({"password": "new-test-password-123"})) + .send(), + ); + let mut waiting = false; + for _ in 0..100 { + waiting = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND NOT granted + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()))", + ) + .fetch_one(&db) + .await?; + if waiting { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + assert!( + waiting, + "the password change never waited on the grant lock" + ); + sqlx::raw_sql( + "INSERT INTO token (token_hash, token_prefix, email, label, expiration) + VALUES (encode(sha256('MCP_ROTATED_TOKEN'::bytea), 'hex'), 'MCP_ROTATE', 'test2@windmill.dev', + 'mcp-oauth-mcp-client', now() + interval '7 days'); + INSERT INTO mcp_oauth_refresh_token + (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at) + VALUES ('test2-rotated', encode(sha256('MCP_ROTATED_TOKEN'::bytea), 'hex'), 'mcp-client', + 'test2@windmill.dev', 'test-workspace', ARRAY['mcp:all'], gen_random_uuid(), now() + interval '30 days');", + ) + .execute(&mut *grant) + .await?; + grant.commit().await?; + + let resp = request.await??; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let labels: Vec<(String, String)> = sqlx::query_as( + "SELECT email, label FROM token WHERE email IN ('test2@windmill.dev', 'test3@windmill.dev') ORDER BY email, label", + ) + .fetch_all(&db) + .await?; + assert_eq!( + labels, + vec![ + ("test2@windmill.dev".to_string(), "test token 2".to_string()), + ( + "test3@windmill.dev".to_string(), + "mcp-oauth-mcp-client".to_string() + ), + ("test3@windmill.dev".to_string(), "test token 3".to_string()), + ] + ); + let refresh: Vec = sqlx::query_scalar( + "SELECT refresh_token FROM mcp_oauth_refresh_token ORDER BY refresh_token", + ) + .fetch_all(&db) + .await?; + assert_eq!(refresh, vec!["test3-refresh".to_string()]); + let invalidated: Vec = sqlx::query_scalar( + "SELECT payload FROM notify_event WHERE channel = 'notify_token_invalidation' ORDER BY payload", + ) + .fetch_all(&db) + .await?; + assert_eq!( + invalidated, + vec!["MCP_ACCESS".to_string(), "MCP_ROTATE".to_string()] + ); + let codes: i64 = sqlx::query_scalar("SELECT count(*) FROM mcp_oauth_server_code") + .fetch_one(&db) + .await?; + assert_eq!(codes, 0); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/variables.rs b/backend/windmill-api-integration-tests/tests/variables.rs index e5018f4f97..adb9f29c36 100644 --- a/backend/windmill-api-integration-tests/tests/variables.rs +++ b/backend/windmill-api-integration-tests/tests/variables.rs @@ -338,3 +338,133 @@ async fn test_variables_are_cached(db: Pool) -> anyhow::Result<()> { Ok(()) } + +/// A draft-only row is built field by field, so a forgotten field is dropped silently. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_draft_only_row_carries_value_valid_until(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/drafts/update/variable/u/test-user/draft_var" + ))) + .json(&json!({ + "value": { + "path": "u/test-user/draft_var", + "variable": { "value": "x", "is_secret": true, "description": "" }, + "wsSpecific": false, + "value_valid_until": "2027-03-15T08:00:00Z" + } + })) + .send() + .await?; + + let resp = authed(client().get(format!( + "http://localhost:{port}/api/w/test-workspace/variables/list?include_draft_only=true" + ))) + .send() + .await?; + assert_eq!(resp.status(), 200); + let rows = resp.json::>().await?; + + let row = rows + .iter() + .find(|v| v["path"] == "u/test-user/draft_var") + .expect("draft-only row is listed"); + assert_eq!(row["draft_only"], true); + assert_eq!(row["value_valid_until"], "2027-03-15T08:00:00Z"); + + Ok(()) +} + +/// An expiry on an OAuth-linked variable is refused with a readable error, not a raw +/// constraint violation. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_oauth_variable_refuses_value_expiry(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::query( + "WITH a AS (INSERT INTO account (workspace_id, expires_at, refresh_token, client) + VALUES ('test-workspace', now() + interval '1 hour', 'r', 'github') RETURNING id) + INSERT INTO variable (workspace_id, path, value, is_secret, description, account, is_oauth) + SELECT 'test-workspace', 'u/test-user/oauth_var', 't', false, '', id, true FROM a", + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/variables/update/u/test-user/oauth_var" + ))) + .json(&json!({ "value_valid_until": "2027-03-15T08:00:00Z" })) + .send() + .await?; + assert_eq!(resp.status(), 400); + assert!(resp.text().await?.contains("OAuth")); + + Ok(()) +} + +/// Reading a variable linked to an OAuth account refreshes through it and returns the fresh token, +/// so the variable endpoints must not let a caller choose the link. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_variable_endpoints_ignore_account_link(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}/api/w/test-workspace/variables"); + + let account: i32 = sqlx::query_scalar( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token) + VALUES ('test-workspace', 'github', now(), 'r') RETURNING id", + ) + .fetch_one(&db) + .await?; + let link = |path: &'static str| { + let db = db.clone(); + async move { + sqlx::query_scalar::<_, Option>( + "SELECT account FROM variable WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(path) + .fetch_one(&db) + .await + .unwrap() + } + }; + + let path = "u/test-user/oauth_probe"; + let resp = authed(client().post(format!("{base}/create"))) + .json( + &json!({ "path": path, "value": "t", "is_secret": true, "description": "", + "is_oauth": true, "account": account }), + ) + .send() + .await?; + assert_eq!(resp.status(), 201); + assert_eq!(link(path).await, None); + + let other: i32 = sqlx::query_scalar( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token) + VALUES ('test-workspace', 'github', now(), 'r') RETURNING id", + ) + .fetch_one(&db) + .await?; + sqlx::query( + "UPDATE variable SET account = $1 WHERE workspace_id = 'test-workspace' AND path = $2", + ) + .bind(account) + .bind(path) + .execute(&db) + .await?; + let resp = authed(client().post(variable_url(port, "update", path))) + .json(&json!({ "description": "d", "account": other })) + .send() + .await?; + assert_eq!(resp.status(), 200); + assert_eq!(link(path).await, Some(account)); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs index 1aa2bc8df2..830a29e8c2 100644 --- a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs +++ b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs @@ -2549,6 +2549,26 @@ async fn test_rename_records_the_vacated_path(db: Pool) -> anyhow::Res "script deploy failed: {status} — {hash}" ); parent_hash = Some(hash.trim().trim_matches('"').to_string()); + // Each deploy tallies from its own spawned task: let the create's `write` land + // before the rename, or it can overwrite the `rename_from` asserted below. + if path == "u/admin/inline" { + let mut written = false; + for _ in 0..40 { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + written = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM workspace_diff + WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script' + AND path = 'u/admin/inline' AND fork_last_event_kind = 'write')" + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if written { + break; + } + } + assert!(written, "the inline create should be tallied"); + } } let mut vacated = None; for _ in 0..40 { @@ -2556,7 +2576,7 @@ async fn test_rename_records_the_vacated_path(db: Pool) -> anyhow::Res vacated = sqlx::query!( "SELECT fork_last_event_kind, fork_last_event_origin FROM workspace_diff WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script' - AND path = 'u/admin/inline' AND fork_last_event_kind IS NOT NULL" + AND path = 'u/admin/inline' AND fork_last_event_kind <> 'write'" ) .fetch_optional(&db) .await?; @@ -2570,3 +2590,263 @@ async fn test_rename_records_the_vacated_path(db: Pool) -> anyhow::Res Ok(()) } + +/// Regression: a resource or resource type can be stored with a NULL description while deploy +/// writes "", so the comparison must read the two as equal or the item never settles. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_compare_null_description_equals_empty(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base_url = format!("http://localhost:{port}/api"); + let client = windmill_api_client::create_client( + &format!("http://localhost:{port}"), + "SECRET_TOKEN".to_string(), + ); + + for q in [ + "INSERT INTO workspace (id, name, owner, parent_workspace_id) + VALUES ('wm-fork-test-workspace', 'Fork', 'test-user', 'test-workspace')", + "INSERT INTO workspace_settings (workspace_id) VALUES ('wm-fork-test-workspace')", + "INSERT INTO workspace_key(workspace_id, kind, key) + VALUES ('wm-fork-test-workspace', 'cloud', 'test-key')", + "INSERT INTO resource (workspace_id, path, value, resource_type, description, created_by) VALUES + ('test-workspace', 'u/test-user/null_desc', '{}', 'generic', NULL, 'test-user'), + ('wm-fork-test-workspace', 'u/test-user/null_desc', '{}', 'generic', '', 'test-user'), + ('test-workspace', 'u/test-user/other_desc', '{}', 'generic', NULL, 'test-user'), + ('wm-fork-test-workspace', 'u/test-user/other_desc', '{}', 'generic', 'x', 'test-user')", + "INSERT INTO resource_type (workspace_id, name, schema, description, created_by) VALUES + ('test-workspace', 'null_desc_rt', '{}', NULL, 'test-user'), + ('wm-fork-test-workspace', 'null_desc_rt', '{}', '', 'test-user'), + ('test-workspace', 'other_desc_rt', '{}', NULL, 'test-user'), + ('wm-fork-test-workspace', 'other_desc_rt', '{}', 'x', 'test-user')", + "INSERT INTO workspace_diff + (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes) VALUES + ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/null_desc', 'resource', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/other_desc', 'resource', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'null_desc_rt', 'resource_type', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'other_desc_rt', 'resource_type', 1, 1, NULL)", + ] { + sqlx::query(q).execute(&db).await?; + } + + let comparison: serde_json::Value = client + .client() + .get(&format!( + "{base_url}/w/test-workspace/workspaces/compare/wm-fork-test-workspace" + )) + .send() + .await? + .json() + .await?; + let mut paths: Vec<&str> = comparison["diffs"] + .as_array() + .unwrap_or_else(|| panic!("no diffs: {comparison}")) + .iter() + .map(|d| d["path"].as_str().unwrap()) + .collect(); + paths.sort(); + assert_eq!( + paths, + ["other_desc_rt", "u/test-user/other_desc"], + "{comparison}" + ); + + Ok(()) +} + +/// Runs its closure when dropped, so process-wide state is put back even when an assertion +/// fails. +struct OnDrop(F); +impl Drop for OnDrop { + fn drop(&mut self) { + (self.0)() + } +} + +/// Secrets are encrypted with a fresh nonce on every write, so a secret holding the same value on +/// both sides must compare by plaintext, not ciphertext. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_compare_secret_variables_by_value(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let client = windmill_api_client::create_client( + &format!("http://localhost:{port}"), + "SECRET_TOKEN".to_string(), + ); + let base_url = format!("http://localhost:{port}/api"); + + let resp = client + .client() + .post(&format!( + "{base_url}/w/test-workspace/workspaces/create_fork" + )) + .json(&json!({ "id": "wm-fork-secrets", "name": "Secrets Fork" })) + .send() + .await?; + assert!( + resp.status().is_success(), + "fork creation failed: {}", + resp.status() + ); + + // Secrets are written in CBC, which is deterministic, until every worker reads AES-GCM. + use windmill_common::min_version::{MIN_VERSION, MIN_VERSION_SUPPORTS_AEAD_SECRETS}; + 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_AEAD_SECRETS.version().clone(), + )); + + for (ws, path, value) in [ + ("test-workspace", "u/test-user/same", "s3cret"), + ("wm-fork-secrets", "u/test-user/same", "s3cret"), + ("test-workspace", "u/test-user/different", "one"), + ("wm-fork-secrets", "u/test-user/different", "two"), + ] { + let resp = client + .client() + .post(&format!("{base_url}/w/{ws}/variables/create")) + .json(&json!({ "path": path, "value": value, "is_secret": true, "description": "" })) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + } + let stored = sqlx::query_scalar!( + "SELECT COUNT(DISTINCT value) FROM variable WHERE path = 'u/test-user/same'" + ) + .fetch_one(&db) + .await?; + assert_eq!( + stored, + Some(2), + "the same secret must be stored as two different ciphertexts" + ); + + // The creates above tally these rows from a spawned task that can land after the + // DELETE, so the plant must upsert. + sqlx::query!("DELETE FROM workspace_diff WHERE fork_workspace_id = 'wm-fork-secrets'") + .execute(&db) + .await?; + sqlx::query!( + "INSERT INTO workspace_diff + (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes) + VALUES + ('test-workspace', 'wm-fork-secrets', 'u/test-user/same', 'variable', 1, 1, NULL), + ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL) + ON CONFLICT (source_workspace_id, fork_workspace_id, path, kind) + DO UPDATE SET ahead = 1, behind = 1, has_changes = NULL" + ) + .execute(&db) + .await?; + + let comparison: serde_json::Value = client + .client() + .get(&format!( + "{base_url}/w/test-workspace/workspaces/compare/wm-fork-secrets" + )) + .send() + .await? + .json() + .await?; + let diffs = comparison["diffs"].as_array().unwrap(); + let listed = |path: &str| { + diffs + .iter() + .any(|d| d["path"] == path && d["kind"] == "variable") + }; + + assert!( + !listed("u/test-user/same"), + "equal secrets must compare as unchanged: {comparison}" + ); + assert!( + listed("u/test-user/different"), + "different secrets must compare as changed: {comparison}" + ); + + Ok(()) +} + +/// `compare_two_variables` hand-lists its columns, so a forgotten one hides that difference +/// from the fork diff, and it can never be promoted. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_compare_variables_detects_value_valid_until(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base_url = format!("http://localhost:{port}/api"); + let admin = windmill_api_client::create_client( + &format!("http://localhost:{port}"), + "SECRET_TOKEN".to_string(), + ); + + sqlx::query!( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until) + VALUES ('test-workspace', 'u/admin/expiring', 'v', false, 'same', '2027-01-01T00:00:00Z')" + ) + .execute(&db) + .await?; + + let resp = admin + .client() + .post(&format!( + "{base_url}/w/test-workspace/workspaces/create_fork" + )) + .json(&json!({ "id": "wm-fork-expiry", "name": "Expiry Fork" })) + .send() + .await?; + assert!( + resp.status().is_success(), + "fork creation failed: {}", + resp.status() + ); + + // Before the UPDATE below overwrites it: the fork must inherit the date from the source. + let inherited: Option = sqlx::query_scalar( + "SELECT to_char(value_valid_until, 'YYYY-MM-DD') FROM variable + WHERE workspace_id = 'wm-fork-expiry' AND path = 'u/admin/expiring'", + ) + .fetch_one(&db) + .await?; + assert_eq!(inherited.as_deref(), Some("2027-01-01")); + + // Only the expiry differs. + sqlx::query!( + "UPDATE variable SET value_valid_until = '2029-12-31T00:00:00Z' + WHERE workspace_id = 'wm-fork-expiry' AND path = 'u/admin/expiring'" + ) + .execute(&db) + .await?; + + // Forces the endpoint to re-evaluate the pair rather than trust a cached verdict. + sqlx::query!( + "INSERT INTO workspace_diff + (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes) + VALUES ('test-workspace', 'wm-fork-expiry', 'u/admin/expiring', 'variable', 0, 1, NULL)" + ) + .execute(&db) + .await?; + + let comparison = admin + .client() + .get(&format!( + "{base_url}/w/test-workspace/workspaces/compare/wm-fork-expiry" + )) + .send() + .await? + .json::() + .await?; + + assert_eq!( + comparison["summary"]["variables_changed"].as_u64(), + Some(1), + "an expiry-only change must show as deployable: {comparison}" + ); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/workspaces.rs b/backend/windmill-api-integration-tests/tests/workspaces.rs index a159bf6090..de5ed4baa0 100644 --- a/backend/windmill-api-integration-tests/tests/workspaces.rs +++ b/backend/windmill-api-integration-tests/tests/workspaces.rs @@ -1262,5 +1262,35 @@ async fn test_admin_and_operator_are_exclusive(db: Pool) -> anyhow::Re .await?; assert_eq!(resp.status(), 400, "{}", resp.text().await?); + // Rows written before the rule can still carry both flags: the admin wins, and `whoami` + // says so, since the frontend hides every gated page from an operator. + sqlx::query( + "UPDATE usr SET is_admin = true, operator = true + WHERE workspace_id = 'test-workspace' AND username = 'operator'", + ) + .execute(&db) + .await?; + let resp = client() + .get(format!("{api}/users/whoami")) + .header("Authorization", "Bearer OPERATOR_TOKEN_1") + .send() + .await?; + assert_eq!(resp.status(), 200); + let me: serde_json::Value = resp.json().await?; + assert_eq!( + (me["is_admin"].as_bool(), me["operator"].as_bool()), + (Some(true), Some(false)) + ); + let resp = client() + .post(format!("{api}/scripts/create")) + .header("Authorization", "Bearer OPERATOR_TOKEN_1") + .json(&json!({ + "path": "u/operator/legacy_admin", "summary": "", "description": "", + "content": "export function main() {}", "language": "deno", "schema": {} + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + Ok(()) } diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index da77acbf7c..53c318b70d 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -916,6 +916,35 @@ pub async fn handle_chat_conversation_messages( is_test: bool, // The run's args, for the files the message carried. args: &HashMap>, +) -> error::Result<()> { + file_chat_turn( + tx, + &authed.username, + authed.is_admin, + w_id, + flow_path, + run_query, + user_message_raw, + job_id, + is_test, + args, + ) + .await +} + +/// [`handle_chat_conversation_messages`] for a conversation owned by `owner`, which need not be a +/// user: an anonymous app visitor's is owned by `ANONYMOUS_CONVERSATION_OWNER`. +pub async fn file_chat_turn( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + owner: &str, + is_admin: bool, + w_id: &str, + flow_path: &str, + run_query: &RunJobQuery, + user_message_raw: Option<&Box>, + job_id: Uuid, + is_test: bool, + args: &HashMap>, ) -> error::Result<()> { // Names the query parameter rather than the field: it is not a flow argument, and // supplying it as one is the first thing tried on reading `memory_id is required`. @@ -945,8 +974,8 @@ pub async fn handle_chat_conversation_messages( tx, w_id, flow_path, - &authed.username, - authed.is_admin, + owner, + is_admin, &user_message, memory_id, is_test, diff --git a/backend/windmill-api-jobs/src/query.rs b/backend/windmill-api-jobs/src/query.rs index 96d8ca3698..ebfc0c3725 100644 --- a/backend/windmill-api-jobs/src/query.rs +++ b/backend/windmill-api-jobs/src/query.rs @@ -268,9 +268,10 @@ pub fn filter_list_queue_query( if let Some(bf) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(bf)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(runnable_path ILIKE ? OR v2_job.tag ILIKE ? OR trigger ILIKE ? OR trigger_kind::text ILIKE ?)" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } @@ -490,7 +491,7 @@ pub fn filter_list_completed_query( } if let Some(dt) = &lq.created_or_started_after { let ts = dt.to_rfc3339(); - sqlb.and_where("(created_at >= ? OR started_at >= ?)".bind(&ts).bind(&ts)); + sqlb.and_where("(created_at >= ? OR started_at >= ?)".binds(&[&ts])); } if let Some(dt) = &lq.created_before { @@ -591,10 +592,11 @@ pub fn filter_list_completed_query( if let Some(bf) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(bf)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(runnable_path ILIKE ? OR v2_job.tag ILIKE ? OR trigger ILIKE ? OR trigger_kind::text ILIKE ? \ OR EXISTS (SELECT 1 FROM unnest(v2_job.labels) lbl WHERE lbl ILIKE ?))" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } @@ -945,6 +947,20 @@ mod tests { assert!(sql.contains("'schedule'")); } + #[test] + fn test_queue_broad_filter_with_question_mark() { + let lq = ListQueueQuery { broad_filter: Some("a?b".to_string()), ..empty_queue_query() }; + let sqlb = filter_list_queue_query( + SqlBuilder::select_from("v2_job_queue").clone(), + &lq, + "ws", + false, + ); + let sql = build_sql(sqlb); + assert_eq!(sql.matches("ILIKE '%a?b%'").count(), 4); + assert!(!sql.contains("ILIKE ?")); + } + // --- Completed query tests --- #[test] @@ -1124,4 +1140,19 @@ mod tests { let sql = build_sql(sqlb); assert!(sql.contains("result @>")); } + + #[test] + fn test_completed_broad_filter_with_question_mark() { + let lq = + ListCompletedQuery { broad_filter: Some("a?b".to_string()), ..empty_completed_query() }; + let sqlb = filter_list_completed_query( + SqlBuilder::select_from("v2_job_completed").clone(), + &lq, + "ws", + false, + ); + let sql = build_sql(sqlb); + assert_eq!(sql.matches("ILIKE '%a?b%'").count(), 5); + assert!(!sql.contains("ILIKE ?")); + } } diff --git a/backend/windmill-api-schedule/src/lib.rs b/backend/windmill-api-schedule/src/lib.rs index fb935e0b5c..e2fa7da8fe 100644 --- a/backend/windmill-api-schedule/src/lib.rs +++ b/backend/windmill-api-schedule/src/lib.rs @@ -894,17 +894,18 @@ async fn list_schedule( } if let Some(broad_filter) = &lsq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(broad_filter)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(path ILIKE ? OR script_path ILIKE ? OR description ILIKE ? OR summary ILIKE ? OR schedule ILIKE ?)" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } if let Some(label) = &lsq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(labels @> ARRAY[?] OR folder_labels(workspace_id, path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } @@ -926,13 +927,13 @@ async fn list_schedule( && lsq.summary.is_none() && lsq.broad_filter.is_none() && lsq.label.is_none() - && (!authed.is_operator - || windmill_common::workspaces::operator_can_draft( - &db, - &w_id, - UserDraftItemKind::TriggerSchedule, - ) - .await?) + && windmill_common::workspaces::operator_can_draft( + &db, + &w_id, + &authed, + UserDraftItemKind::TriggerSchedule, + ) + .await? { let draft_only_rows = fetch_draft_only_list_rows( &db, diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index 4bbe372254..4e8516b8ed 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -185,6 +185,10 @@ async fn list_scripts( Query(pagination): Query, Query(lq): Query, ) -> JsonResult> { + // A role that cannot write code lists only what it can run: no libraries, no drafts. + let cannot_code = !windmill_common::roles::caller_capabilities(&db, &w_id, &authed) + .await? + .code; let (per_page, offset) = paginate_without_limits(pagination); let mut sqlb = SqlBuilder::select_from("script as o") .fields(&[ @@ -255,7 +259,7 @@ async fn list_scripts( .as_ref() .map(|x| !x.contains(&"preprocessor".to_string())) .unwrap_or(true)) - || authed.is_operator + || cannot_code { // only include scripts that have a runnable entrypoint. Use a // deny-list: anything that isn't a 'lib' (library script without @@ -305,14 +309,14 @@ async fn list_scripts( } if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(o.labels @> ARRAY[?] OR folder_labels(o.workspace_id, o.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } - if authed.is_operator { + if cannot_code { sqlb.and_where_eq("kind", quote("script")); } else if let Some(lowercased_kinds) = lowercased_kinds { let safe_kinds = lowercased_kinds @@ -360,7 +364,7 @@ async fn list_scripts( // `include_draft_only` so picker callers stay deployed-only (home page opts in); // skipped past page 0 or under any narrowing filter to keep pagination clean. if lq.include_draft_only.unwrap_or(false) - && !authed.is_operator + && !cannot_code && offset == 0 && lq.path_start.is_none() && lq.path_exact.is_none() @@ -1248,7 +1252,7 @@ async fn validate_dbt_relation( /// The schema the editor would have derived from `content`, for a deploy that sends /// none (MCP, a bare API call). `None` for a language whose parser this build lacks, /// or code that does not parse. -fn infer_main_schema( +pub fn infer_main_schema( language: &ScriptLang, kind: Option<&ScriptKind>, content: &str, @@ -1352,11 +1356,7 @@ async fn create_script_internal<'c>( Option, Vec, )> { - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot create scripts for security reasons".to_string(), - )); - } + windmill_common::workspaces::check_role_can_code(&db, &w_id, &authed, "create scripts").await?; check_scopes(&authed, || format!("scripts:write:{}", ns.path))?; // Normalize positive-only settings so a `<= 0` value (e.g. a CLI-pushed `0`) persists as @@ -4086,11 +4086,8 @@ async fn archive_script_by_path( Extension(db): Extension, Path((w_id, path)): Path<(String, StripPath)>, ) -> Result<()> { - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot archive scripts for security reasons".to_string(), - )); - } + windmill_common::workspaces::check_role_can_code(&db, &w_id, &authed, "archive scripts") + .await?; let path = path.to_path(); check_scopes(&authed, || format!("scripts:write:{}", path))?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( @@ -4182,11 +4179,8 @@ async fn archive_script_by_hash( Extension(webhook): Extension, Path((w_id, hash)): Path<(String, ScriptHash)>, ) -> JsonResult> { - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot archive scripts for security reasons".to_string(), - )); - } + windmill_common::workspaces::check_role_can_code(&db, &w_id, &authed, "archive scripts") + .await?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, AuditAuthorable::username(&authed), diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index 96c1be32c9..2dbb7d427c 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -74,7 +74,7 @@ use windmill_common::{ RETENTION_PERIOD_SECS_OVERRIDES_SETTING, RUFF_CONFIG_SETTING, UNIQUE_ID_SETTING, WORKSPACE_FAIRNESS_DURATION_SECS_SETTING, WORKSPACE_FAIRNESS_ENABLED_SETTING, WORKSPACE_FAIRNESS_MAX_PERCENT_SETTING, WORKSPACE_FAIRNESS_MIN_TOTAL_SETTING, - WS_BASE_URL_SETTING, + WORKSPACE_ROLES_SETTING, WS_BASE_URL_SETTING, }, instance_config::{self, ApplyMode, InstanceConfig}, server::Smtp, @@ -969,6 +969,8 @@ pub async fn set_global_setting_internal( bump_instance_ai_config_revision(); } + run_setting_post_write_hook(db, &key).await?; + // Tag reads are served from an in-memory cache that this process otherwise only // refreshes on the next global-settings poll, so without this a refetch right after // the write still returns the pre-write list. The setting is already persisted at @@ -983,6 +985,14 @@ pub async fn set_global_setting_internal( Ok(()) } +/// Side effects a setting needs once it is stored, for both the per-key and the bulk endpoint. +async fn run_setting_post_write_hook(db: &DB, key: &str) -> error::Result<()> { + if key == WORKSPACE_ROLES_SETTING { + windmill_common::roles::after_instance_roles_write(db).await?; + } + Ok(()) +} + /// Run side-effect hooks for specific settings before writing to DB. /// Extracted from `set_global_setting_internal` for reuse by the bulk endpoint. async fn run_setting_pre_write_hook( @@ -999,6 +1009,9 @@ async fn run_setting_pre_write_hook( error::Error::BadRequest(format!("The dev workspace tag suffix {e}")) })?, }, + WORKSPACE_ROLES_SETTING => { + windmill_common::roles::validate_instance_roles_write(db, Some(value)).await?; + } // The instance AI config is written as an untyped blob through this generic // endpoint, so it never passes the typed check the workspace handler applies. // Rates that reach a cost total unbounded would make it negative or infinite. @@ -1369,6 +1382,14 @@ async fn set_instance_config( run_setting_pre_write_hook(&db, key, value).await?; } } + if settings_diff + .deletes + .iter() + .any(|k| k == WORKSPACE_ROLES_SETTING) + { + run_setting_pre_write_hook(&db, WORKSPACE_ROLES_SETTING, &serde_json::Value::Null) + .await?; + } let auditor = InstanceConfigAuditor { db: &db, author: &authed, source: None }; // The external-instance write removes its own key from the diff. windmill_common::external_instance_pg::write_external_instance_pg_from_diff( @@ -1384,6 +1405,14 @@ async fn set_instance_config( if ai_config_changed { bump_instance_ai_config_revision(); } + for key in settings_diff + .upserts + .iter() + .map(|(k, _)| k) + .chain(settings_diff.deletes.iter()) + { + run_setting_post_write_hook(&db, key).await?; + } } if !desired.worker_configs.is_empty() { diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 9c853d8ef8..dbc883305e 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -262,6 +262,7 @@ pub struct WorkspaceInvite { pub email: String, pub is_admin: bool, pub operator: bool, + pub role: String, pub parent_workspace_id: Option, } @@ -301,7 +302,10 @@ pub struct EditUser { #[derive(Deserialize)] pub struct EditWorkspaceUser { pub is_admin: Option, + /// Legacy role selector: `true` is the `operator` role, `false` `developer`. `role` wins. pub operator: Option, + /// The member's role, one of the workspace's roles. + pub role: Option, pub disabled: Option, } @@ -414,7 +418,9 @@ async fn list_users( let rows = sqlx::query_as!( User, " - SELECT workspace_id, username, email, is_admin, created_at, operator, disabled, role, added_via, is_service_account + SELECT workspace_id, username, email, is_admin, created_at, operator, disabled, + COALESCE(workspace_role, CASE WHEN operator THEN 'operator' ELSE 'developer' END) AS role, + added_via, is_service_account FROM usr WHERE workspace_id = $1 ORDER BY email @@ -636,6 +642,7 @@ async fn list_invites( workspace_invite.email, workspace_invite.is_admin, workspace_invite.operator, + COALESCE(workspace_invite.workspace_role, CASE WHEN workspace_invite.operator THEN 'operator' ELSE 'developer' END) AS \"role!\", workspace.parent_workspace_id FROM workspace_invite JOIN workspace ON workspace_invite.workspace_id = workspace.id WHERE email = $1", authed.email @@ -765,7 +772,7 @@ async fn whoami( authed: ApiAuthed, ) -> JsonResult { let is_guest = windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()); - let ApiAuthed { username, email, is_admin, groups, folders, .. } = authed; + let ApiAuthed { username, email, is_admin, is_operator, groups, folders, .. } = authed; // A guest would otherwise fall through to the non-member branch below and be // handed a `superadmin` role. Answer it here, as the operator-shaped identity it is. if is_guest { @@ -794,7 +801,13 @@ async fn whoami( // never happen, but guard against it so a non-member superadmin is never // shown another member's identity/role. if let Some(user) = user.filter(|u| u.email == email) { - Ok(Json(user)) + // The frontend gates pages on `operator`, so it reports what `caller_capabilities` + // decides rather than the raw column: an admin (or superadmin) whose row still carries + // `operator` holds everything. + Ok(Json(UserInfo { + operator: is_operator && !is_admin, + ..user + })) } else { Ok(Json(UserInfo { workspace_id: w_id, @@ -937,12 +950,13 @@ pub struct User2 { #[serde(skip_serializing_if = "Option::is_none")] pub added_via: Option, pub is_service_account: bool, + pub workspace_role: Option, } async fn get_user(w_id: &str, username: &str, db: &DB) -> Result> { let user = sqlx::query_as!( User2, - "SELECT usr.*, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2 + "SELECT usr.workspace_id, usr.email, usr.username, usr.is_admin, usr.created_at, usr.operator, usr.disabled, usr.role, usr.added_via, usr.is_service_account, usr.workspace_role, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2 ", username, w_id @@ -972,7 +986,10 @@ async fn get_user(w_id: &str, username: &str, db: &DB) -> Result, Json(eu): Json, ) -> Result { - let mut tx = db.begin().await?; - require_admin(authed.is_admin, &authed.username)?; + #[cfg(feature = "enterprise")] + let seat_baseline = windmill_common::ee_oss::seat_cap_baseline(&db).await?; + let mut tx = db.begin().await?; + update_workspace_user_internal( &w_id, &username_to_update, eu.is_admin, eu.operator, + eu.role, eu.disabled, &mut tx, Some(&authed), ) .await?; + #[cfg(feature = "enterprise")] + if let Some(msg) = + windmill_common::ee_oss::check_seat_cap_for_role_change(&seat_baseline, &mut tx).await? + { + return Err(Error::BadRequest(msg)); + } + let user_email = sqlx::query_scalar!( "SELECT email FROM usr WHERE username = $1 AND workspace_id = $2", &username_to_update, @@ -1417,65 +1457,44 @@ async fn convert_user_to_group( )); } - // Determine the group with highest precedence (same logic as reconcile_workspace_instance_groups) - let roles: std::collections::HashMap = - if let Some(roles_json) = &eligible_groups[0].instance_groups_roles { - serde_json::from_value(roles_json.clone()).unwrap_or_default() - } else { - std::collections::HashMap::new() - }; + let roles: std::collections::HashMap = eligible_groups[0] + .instance_groups_roles + .clone() + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default(); + let group_names: Vec = eligible_groups + .iter() + .map(|g| g.group_name.clone()) + .collect(); + let role_order: Vec = windmill_common::roles::workspace_roles_on(&mut *tx, &w_id) + .await? + .iter() + .map(|r| r.name.clone()) + .collect(); + let (primary_group_name, is_admin, role) = + windmill_common::users::compute_highest_workspace_role( + &group_names, + &group_names, + &roles, + &role_order, + ); - let mut best_group = &eligible_groups[0].group_name; - let mut best_precedence = 0u8; - - for group in &eligible_groups { - let default_role = "developer".to_string(); - let role = roles.get(&group.group_name).unwrap_or(&default_role); - - let precedence = match role.as_str() { - "admin" => 3, - "developer" => 2, - "operator" => 1, - _ => 2, - }; - - if precedence > best_precedence { - best_precedence = precedence; - best_group = &group.group_name; - } - } - - let primary_group_name = best_group; - - // Determine role from group configuration using the selected primary group - let default_role = "developer".to_string(); - let role = roles - .get(primary_group_name) - .unwrap_or(&default_role) - .as_str(); - - let (is_admin, is_operator) = match role { - "admin" => (true, false), - "operator" => (false, true), - _ => (false, false), - }; - - // Update user with instance group information let instance_group_source = serde_json::json!({ "source": "instance_group", "group": primary_group_name }); sqlx::query!( - "UPDATE usr SET added_via = $1, is_admin = $2, operator = $3 WHERE username = $4 AND workspace_id = $5", + "UPDATE usr SET added_via = $1, is_admin = $2 WHERE username = $3 AND workspace_id = $4", instance_group_source, is_admin, - is_operator, username_to_convert, &w_id ) .execute(&mut *tx) .await?; + set_workspace_role(&mut tx, &w_id, &username_to_convert, &role).await?; + let role = if is_admin { "admin" } else { role.as_str() }; audit_log( &mut *tx, @@ -2414,26 +2433,28 @@ lazy_static::lazy_static! { } /// Internal helper for updating workspace user permissions - used by both API and system operations +/// +/// `role` names one of the workspace's roles; without it, the legacy `operator` flag selects the +/// `operator` or `developer` role. Admin is a flag on top of the role, so it is set independently. pub async fn update_workspace_user_internal( w_id: &str, username_to_update: &str, is_admin: Option, operator: Option, + role: Option, disabled: Option, tx: &mut Transaction<'_, Postgres>, authed: Option<&ApiAuthed>, // None for system operations ) -> Result<()> { - // The role is one choice stored as two flags. Granting one clears the other, or a request - // setting only `is_admin` leaves a user shown as admin but refused as an operator. - let (is_admin, operator) = match (is_admin, operator) { - (Some(true), Some(true)) => { - return Err(Error::BadRequest( - "A user cannot be both admin and operator".to_string(), - )) - } - (Some(true), _) => (Some(true), Some(false)), - (_, Some(true)) => (Some(false), Some(true)), - flags => flags, + if role.is_none() && is_admin == Some(true) && operator == Some(true) { + return Err(Error::BadRequest( + "A user cannot be both admin and operator".to_string(), + )); + } + // The legacy selector made admin and operator one choice: granting operator demoted. + let is_admin = match (&role, is_admin, operator) { + (None, None, Some(true)) => Some(false), + _ => is_admin, }; if let Some(a) = is_admin { sqlx::query_scalar!( @@ -2445,15 +2466,20 @@ pub async fn update_workspace_user_internal( .execute(&mut **tx) .await?; } - if let Some(a) = operator { - sqlx::query_scalar!( - "UPDATE usr SET operator = $1 WHERE username = $2 AND workspace_id = $3", - a, - username_to_update, - w_id - ) - .execute(&mut **tx) - .await?; + // A legacy payload granting admin also cleared `operator`; keep that, as the default role. + let role = match (role, is_admin, operator) { + (Some(role), _, _) => Some(role), + (None, _, Some(true)) => Some(windmill_common::roles::OPERATOR_ROLE.to_string()), + (None, Some(true), _) | (None, _, Some(false)) => { + let roles = windmill_common::roles::workspace_roles_on(&mut **tx, w_id).await?; + Some(windmill_common::roles::default_role_name( + roles.iter().map(|r| r.name.as_str()), + )) + } + _ => None, + }; + if let Some(role) = role { + set_workspace_role(tx, w_id, username_to_update, &role).await?; } if let Some(a) = disabled { sqlx::query_scalar!( @@ -2483,6 +2509,39 @@ pub async fn update_workspace_user_internal( Ok(()) } +/// Gives a member role `role`, which must be one of the workspace's roles. `usr.operator` is +/// kept as "this role cannot write code", the reading clients that predate roles give it. +/// +/// AUTHORIZATION: changes what the member may do and checks nothing. Callers MUST have verified +/// that the caller is an admin of `w_id`, or run as trusted server-side code (instance group sync, +/// invite acceptance). +pub async fn set_workspace_role( + tx: &mut Transaction<'_, Postgres>, + w_id: &str, + username: &str, + role: &str, +) -> Result<()> { + let caps = windmill_common::roles::workspace_roles_on(&mut **tx, w_id) + .await? + .iter() + .find(|r| r.name == role) + .map(|r| r.capabilities) + .ok_or_else(|| { + Error::BadRequest(format!("role `{role}` is not defined in workspace {w_id}")) + })?; + sqlx::query!( + "UPDATE usr SET workspace_role = $1, operator = $2 WHERE username = $3 AND workspace_id = $4", + role, + !caps.code, + username, + w_id + ) + .execute(&mut **tx) + .await?; + windmill_common::roles::invalidate_member_role_cache(w_id, username); + Ok(()) +} + /// Internal helper for deleting workspace users - used by both API and system operations pub async fn delete_workspace_user_internal( w_id: &str, diff --git a/backend/windmill-api-workspaces/src/datatable_clone.rs b/backend/windmill-api-workspaces/src/datatable_clone.rs index 1e6c6b55c2..067a248aa7 100644 --- a/backend/windmill-api-workspaces/src/datatable_clone.rs +++ b/backend/windmill-api-workspaces/src/datatable_clone.rs @@ -104,7 +104,7 @@ pub(crate) async fn connection_snapshot( continue; } let row: Option<(String, bool)> = sqlx::query_as( - "SELECT value, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", + "SELECT value::text, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", ) .bind(w_id) .bind(var) diff --git a/backend/windmill-api-workspaces/src/datatable_migrations.rs b/backend/windmill-api-workspaces/src/datatable_migrations.rs index 839b449f37..35ea6210dd 100644 --- a/backend/windmill-api-workspaces/src/datatable_migrations.rs +++ b/backend/windmill-api-workspaces/src/datatable_migrations.rs @@ -157,15 +157,17 @@ async fn ensure_may_edit_migration( Ok(()) } -/// Operators run deployed code only, and a migration is SQL written or run by hand. Checked before -/// anything else, including the role checks: on a data table not under roles those pass everyone. -fn ensure_not_operator(authed: &ApiAuthed) -> Result<()> { - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot manage or run data table migrations".to_string(), - )); - } - Ok(()) +/// A migration is SQL written or run by hand, so it needs a role that may run code of its own. +/// Checked before anything else, including the data table role checks: on a data table not under +/// roles those pass everyone. +async fn ensure_not_operator(db: &DB, w_id: &str, authed: &ApiAuthed) -> Result<()> { + windmill_common::workspaces::check_role_can_code( + db, + w_id, + authed, + "manage or run data table migrations", + ) + .await } /// Whether new migrations declare a scope, which the editors push for but do not require. @@ -691,7 +693,7 @@ async fn run_datatable_migrations( Path((w_id, datatable_name)): Path<(String, String)>, Query(query): Query, ) -> JsonResult { - ensure_not_operator(&authed)?; + ensure_not_operator(&db, &w_id, &authed).await?; // Before the admin connection is opened at all: the bookkeeping below is created and read // through it, so a caller no role covers must be refused here rather than after the fact. crate::datatable_permissions::ensure_reaches_datatable(&db, &w_id, &datatable_name, &authed) @@ -827,7 +829,7 @@ async fn rollback_datatable_migrations( Path((w_id, datatable_name)): Path<(String, String)>, Query(query): Query, ) -> JsonResult { - ensure_not_operator(&authed)?; + ensure_not_operator(&db, &w_id, &authed).await?; // Before the admin connection is opened at all: the bookkeeping below is created and read // through it, so a caller no role covers must be refused here rather than after the fact. crate::datatable_permissions::ensure_reaches_datatable(&db, &w_id, &datatable_name, &authed) @@ -1488,7 +1490,7 @@ async fn create_datatable_migration( Path((w_id, datatable_name)): Path<(String, String)>, Json(payload): Json, ) -> JsonResult { - ensure_not_operator(&authed)?; + ensure_not_operator(&db, &w_id, &authed).await?; validate_datatable_path_segment(&datatable_name)?; validate_migration_name(&payload.name)?; let scope = parse_migration_schemas(&payload.code_up)?; @@ -1555,7 +1557,7 @@ async fn delete_datatable_migration( Extension(db): Extension, Path((w_id, datatable_name, timestamp)): Path<(String, String, i64)>, ) -> Result { - ensure_not_operator(&authed)?; + ensure_not_operator(&db, &w_id, &authed).await?; let deleted_message = format!("Deleted migration {} from {}", timestamp, datatable_name); // A definition already gone is not an error: `wmill sync push` deletes whatever the repo @@ -1692,7 +1694,7 @@ async fn upsert_datatable_migration( Path((w_id, datatable_name)): Path<(String, String)>, Json(payload): Json, ) -> Result { - ensure_not_operator(&authed)?; + ensure_not_operator(&db, &w_id, &authed).await?; validate_datatable_path_segment(&datatable_name)?; validate_migration_name(&payload.name)?; ensure_datatable_migrations_enabled(&db, &w_id, &datatable_name).await?; @@ -1896,7 +1898,7 @@ async fn generate_initial_datatable_migration( Extension(db): Extension, Path((w_id, datatable_name)): Path<(String, String)>, ) -> JsonResult { - ensure_not_operator(&authed)?; + ensure_not_operator(&db, &w_id, &authed).await?; // Returns a `pg_dump` of the whole schema and writes into the data table's own bookkeeping, so // it answers to the workspace that governs it rather than to whoever is asking. ensure_datatable_admin_access( diff --git a/backend/windmill-api-workspaces/src/lib.rs b/backend/windmill-api-workspaces/src/lib.rs index 8d37fdf194..cc5a7b9ab0 100644 --- a/backend/windmill-api-workspaces/src/lib.rs +++ b/backend/windmill-api-workspaces/src/lib.rs @@ -11,6 +11,7 @@ pub mod datatable_permissions_oss; pub mod datatable_replay_oss; pub mod deployment_requests; pub mod remote_deploy; +pub mod workspace_roles; pub mod workspaces; pub mod workspaces_extra; pub mod workspaces_oss; diff --git a/backend/windmill-api-workspaces/src/workspace_roles.rs b/backend/windmill-api-workspaces/src/workspace_roles.rs new file mode 100644 index 0000000000..58bf4e1904 --- /dev/null +++ b/backend/windmill-api-workspaces/src/workspace_roles.rs @@ -0,0 +1,290 @@ +//! The workspace's roles and its overrides of them. See `windmill_common::roles`. + +use axum::{ + extract::{Extension, Path}, + routing::{get, post}, + Json, Router, +}; +use serde::{Deserialize, Serialize}; +use windmill_api_auth::ApiAuthed; +use windmill_audit::{audit_oss::audit_log, ActionKind}; +use windmill_common::{ + error::{Error, JsonResult, Result}, + roles::{ + self, instance_roles, load_role_overrides, EffectiveRole, RoleCapabilities, RoleOverrides, + RoleSource, OPERATOR_ROLE, + }, + utils::require_admin, + DB, +}; +use windmill_git_sync::handle_deployment_metadata; + +pub fn workspaced_service() -> Router { + Router::new() + .route("/roles", get(list_roles)) + .route("/role_overrides", post(update_role_overrides)) +} + +#[derive(Serialize)] +struct WorkspaceRoles { + roles: Vec, + overrides: RoleOverrides, + /// Whether this workspace may add roles of its own. + custom_roles_enabled: bool, + /// The caller's role, `None` for a caller with no membership (a superadmin, a guest). + my_role: Option, + my_capabilities: RoleCapabilities, +} + +async fn list_roles( + authed: ApiAuthed, + Path(w_id): Path, + Extension(db): Extension, +) -> JsonResult { + let roles = roles::workspace_roles(&db, &w_id).await?; + let overrides = load_role_overrides(&db, &w_id).await?; + let my_role = sqlx::query!( + "SELECT workspace_role, operator FROM usr WHERE workspace_id = $1 AND username = $2", + &w_id, + &authed.username + ) + .fetch_optional(&db) + .await? + .map(|r| roles::resolve_role_name(r.workspace_role, r.operator)); + // Not `caller_capabilities`: its fast path answers FULL for an unrestricted member, which + // drops the visibility a role may still withhold. + let my_capabilities = match &my_role { + _ if authed.is_admin => roles::RoleCapabilities::FULL, + Some(role) => roles::role_capabilities_by_name(&db, &w_id, role).await?, + None => roles::RoleCapabilities::NONE, + }; + Ok(Json(WorkspaceRoles { + roles: roles.as_ref().clone(), + overrides, + custom_roles_enabled: roles::custom_roles_enabled(), + my_role, + my_capabilities, + })) +} + +async fn update_role_overrides( + authed: ApiAuthed, + Path(w_id): Path, + Extension(db): Extension, + Json(overrides): Json, +) -> Result { + require_admin(authed.is_admin, &authed.username)?; + write_role_overrides(&db, &authed, &w_id, overrides, None).await?; + Ok("Role overrides updated".to_string()) +} + +/// Replaces the workspace's role overrides with `overrides`. Refuses removing a workspace-only role +/// anything still names, and a change that pushes an offline license over its seat cap. +/// `operator_settings` is the legacy `/operator_settings` payload, mirrored into its column for +/// git sync and for servers that predate roles. +pub(crate) async fn write_role_overrides( + db: &DB, + authed: &ApiAuthed, + w_id: &str, + overrides: RoleOverrides, + operator_settings: Option, +) -> Result<()> { + let instance = instance_roles(db).await?; + roles::validate_overrides(&instance, &overrides)?; + roles::check_frozen_overrides( + &instance, + &roles::load_role_overrides(db, w_id).await?, + &overrides, + )?; + + let previous = roles::workspace_roles(db, w_id).await?; + let removed: Vec = previous + .iter() + .filter(|r| r.source == RoleSource::Workspace && !overrides.contains_key(&r.name)) + .map(|r| r.name.clone()) + .collect(); + for name in &removed { + roles::ensure_role_unused(db, Some(w_id), name).await?; + } + + let overrides_json = serde_json::to_value(&overrides) + .map_err(|e| Error::internal_err(format!("serializing role overrides: {e:#}")))?; + #[cfg(feature = "enterprise")] + let seat_baseline = windmill_common::ee_oss::seat_cap_baseline(db).await?; + let mut tx = db.begin().await?; + sqlx::query!( + "UPDATE workspace_settings SET role_overrides = $1 WHERE workspace_id = $2", + if overrides.is_empty() { + None + } else { + Some(&overrides_json) + }, + w_id + ) + .execute(&mut *tx) + .await?; + roles::notify_role_overrides_change(&mut tx, w_id).await?; + if let Some(settings) = &operator_settings { + sqlx::query!( + "UPDATE workspace_settings + SET operator_settings = COALESCE(operator_settings, '{}'::jsonb) || $1 + WHERE workspace_id = $2", + settings, + w_id + ) + .execute(&mut *tx) + .await?; + } + roles::invalidate_workspace_roles_cache(w_id); + roles::sync_role_seats(&mut tx, Some(w_id)).await?; + + #[cfg(feature = "enterprise")] + if let Some(msg) = + windmill_common::ee_oss::check_seat_cap_for_role_change(&seat_baseline, &mut tx).await? + { + return Err(Error::BadRequest(msg)); + } + + audit_log( + &mut *tx, + authed, + if operator_settings.is_some() { + "workspaces.update_operator_settings" + } else { + "workspaces.update_role_overrides" + }, + ActionKind::Update, + w_id, + None, + Some([("role_overrides", overrides_json.to_string().as_str())].into()), + ) + .await?; + tx.commit().await?; + roles::invalidate_workspace_roles_cache(w_id); + + handle_deployment_metadata( + &authed.email, + &authed.username, + db, + w_id, + windmill_git_sync::DeployedObject::Settings { + setting_type: if operator_settings.is_some() { + "operator_settings".to_string() + } else { + "role_overrides".to_string() + }, + }, + Some("Workspace roles updated".to_string()), + false, + None, + ) + .await?; + Ok(()) +} + +/// The legacy `/operator_settings` payload. Visibility flags always serialize; the rights are +/// `Option` because git-sync posts whole files that may predate them, and an absent key must +/// leave the stored value alone. +#[derive(Deserialize, Serialize)] +pub(crate) struct ChangeOperatorSettings { + #[serde(default)] + runs: bool, + #[serde(default)] + schedules: bool, + #[serde(default)] + resources: bool, + #[serde(default)] + variables: bool, + #[serde(default)] + assets: bool, + #[serde(default)] + triggers: bool, + #[serde(default)] + audit_logs: bool, + #[serde(default)] + groups: bool, + #[serde(default)] + folders: bool, + #[serde(default)] + workers: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + builder_flows: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + builder_apps: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + manage_schedules: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + manage_triggers: Option, +} + +/// Applies a legacy operator settings payload as an override of the `operator` role. A key equal +/// to what the instance gives the role is dropped rather than pinned, so it keeps following the +/// instance definition. +pub(crate) async fn update_operator_settings( + authed: ApiAuthed, + Path(w_id): Path, + Extension(db): Extension, + Json(settings): Json, +) -> Result { + require_admin(authed.is_admin, &authed.username)?; + + let instance = instance_roles(&db).await?; + let Some(base) = roles::effective_roles(&instance, &RoleOverrides::new())? + .into_iter() + .find(|r| r.name == OPERATOR_ROLE) + else { + return Err(Error::BadRequest( + "this instance defines no `operator` role: edit the workspace roles instead" + .to_string(), + )); + }; + let base = base.capabilities; + + let mut overrides = load_role_overrides(&db, &w_id).await?; + let current = roles::workspace_roles(&db, &w_id) + .await? + .iter() + .find(|r| r.name == OPERATOR_ROLE) + .map(|r| r.capabilities) + .unwrap_or(base); + + let mut target = current; + let v = &mut target.visibility; + (v.runs, v.schedules, v.resources, v.variables, v.assets) = ( + settings.runs, + settings.schedules, + settings.resources, + settings.variables, + settings.assets, + ); + (v.triggers, v.audit_logs, v.groups, v.folders, v.workers) = ( + settings.triggers, + settings.audit_logs, + settings.groups, + settings.folders, + settings.workers, + ); + let compose_or_keep = |cur: roles::AuthorLevel, grant: Option| match grant { + Some(true) if cur == roles::AuthorLevel::None => roles::AuthorLevel::Compose, + Some(false) => roles::AuthorLevel::None, + _ => cur, + }; + target.flows = compose_or_keep(current.flows, settings.builder_flows); + target.apps = compose_or_keep(current.apps, settings.builder_apps); + if let Some(b) = settings.manage_schedules { + target.manage_schedules = b; + } + if let Some(b) = settings.manage_triggers { + target.manage_triggers = b; + } + + let entry = overrides.entry(OPERATOR_ROLE.to_string()).or_default(); + entry.capabilities = roles::diff_capabilities(&base, &target); + if entry.label.is_none() && entry.capabilities == Default::default() { + overrides.remove(OPERATOR_ROLE); + } + + let settings_json = serde_json::json!(settings); + write_role_overrides(&db, &authed, &w_id, overrides, Some(settings_json)).await?; + Ok("Operator settings updated successfully".to_string()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 0c70946c58..9a6efec148 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -39,7 +39,7 @@ use windmill_common::global_settings::HTTP_ROUTE_WORKSPACED_ROUTE; use windmill_common::query_builders::{render_db_quoted_identifier, DbType}; use windmill_common::users::username_to_permissioned_as; use windmill_common::variables::{ - crypt_from_key_with_suffix, decrypt, encrypt, WORKSPACE_CRYPT_CACHE, + crypt_from_key_with_suffix, decrypt, decrypt_secret_value, encrypt, WORKSPACE_CRYPT_CACHE, }; use windmill_common::worker::{to_raw_value, CLOUD_HOSTED}; use windmill_common::workspaces::GitRepositorySettings; @@ -76,7 +76,9 @@ use hyper::StatusCode; use serde::{Deserialize, Serialize}; use sqlx::{FromRow, Postgres, Row, Transaction}; use windmill_common::oauth2::InstanceEvent; -use windmill_common::secret_backend::{get_secret_backend, is_vault_backend_configured}; +use windmill_common::secret_backend::{ + get_secret_backend, is_external_stored_value, is_vault_backend_configured, +}; use windmill_common::utils::not_found_if_none; lazy_static::lazy_static! { @@ -113,6 +115,7 @@ pub fn workspaced_service() -> Router { .route("/slack_oauth_config", get(get_slack_oauth_config)) .route("/slack_oauth_config", post(set_slack_oauth_config)) .route("/slack_oauth_config", delete(delete_slack_oauth_config)) + .route("/slack_signing_secret", post(set_slack_signing_secret)) .route("/edit_webhook", post(edit_webhook)) .route("/edit_auto_invite", post(edit_auto_invite)) .route("/edit_instance_groups", post(edit_instance_groups)) @@ -124,6 +127,10 @@ pub fn workspaced_service() -> Router { .route("/billable_seats", get(get_billable_seats)) .route("/edit_error_handler", post(edit_error_handler)) .route("/edit_success_handler", post(edit_success_handler)) + .route( + "/edit_variable_expiration_handler", + post(edit_variable_expiration_handler), + ) .route( "/edit_large_file_storage_config", post(edit_large_file_storage_config), @@ -192,7 +199,11 @@ pub fn workspaced_service() -> Router { .route("/usage", get(get_usage)) .route("/used_triggers", get(get_used_triggers)) .route("/public_app_rate_limit", post(edit_public_app_rate_limit)) - .route("/operator_settings", post(update_operator_settings)) + .route( + "/operator_settings", + post(crate::workspace_roles::update_operator_settings), + ) + .merge(crate::workspace_roles::workspaced_service()) .route( "/create_workspace_fork_branch", post(create_workspace_fork_branch), @@ -335,6 +346,8 @@ pub struct WorkspaceSettings { #[serde(skip_serializing_if = "Option::is_none")] pub success_handler: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub variable_expiration_handler: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub public_app_execution_limit_per_minute: Option, pub error_handler_fallback_to_instance_alerts: bool, /// Whether this workspace admits guest sessions (`ExecutionMode::Guest`). An app's @@ -442,6 +455,8 @@ struct RunSlackMessageTestJobResponse { #[derive(Deserialize)] pub struct EditAutoInvite { pub operator: Option, + /// The role auto-invited members get; wins over `operator`. + pub role: Option, pub invite_all: Option, pub auto_add: Option, } @@ -579,6 +594,9 @@ struct UserWorkspace { pub created_by: Option, pub disabled: bool, pub is_service_account: bool, + /// The member's role in this workspace. + pub role: String, + pub capabilities: windmill_common::roles::RoleCapabilities, } #[derive(Deserialize)] @@ -596,7 +614,11 @@ struct ValidateUsername { pub struct NewWorkspaceInvite { pub email: String, pub is_admin: bool, + /// Legacy role selector, `true` for the `operator` role; `role` wins. + #[serde(default)] pub operator: bool, + #[serde(default)] + pub role: Option, } #[derive(Deserialize)] @@ -604,7 +626,34 @@ pub struct NewWorkspaceUser { pub email: String, pub username: Option, pub is_admin: bool, + #[serde(default)] pub operator: bool, + #[serde(default)] + pub role: Option, +} + +/// The role a new member or invite gets, `role` if given, else the one the legacy `operator` flag +/// names, and the `usr.operator` value that goes with it: "cannot write code". +async fn resolve_new_member_role( + db: &DB, + w_id: &str, + operator: bool, + role: Option<&str>, +) -> Result<(String, bool)> { + let roles = windmill_common::roles::workspace_roles(db, w_id).await?; + let name = match role { + Some(role) => role.to_string(), + None if operator => windmill_common::roles::OPERATOR_ROLE.to_string(), + None => windmill_common::roles::default_role_name(roles.iter().map(|r| r.name.as_str())), + }; + let caps = roles + .iter() + .find(|r| r.name == name) + .ok_or_else(|| { + Error::BadRequest(format!("role `{name}` is not defined in workspace {w_id}")) + })? + .capabilities; + Ok((name, !caps.code)) } /// The role is one choice stored as two flags; both set would show as admin in the UI while the @@ -718,6 +767,7 @@ async fn list_pending_invites( workspace_invite.email, workspace_invite.is_admin, workspace_invite.operator, + COALESCE(workspace_invite.workspace_role, CASE WHEN workspace_invite.operator THEN 'operator' ELSE 'developer' END) AS \"role!\", workspace.parent_workspace_id FROM workspace_invite JOIN workspace ON workspace_invite.workspace_id = workspace.id WHERE workspace_id = $1 @@ -1159,6 +1209,7 @@ async fn get_settings( auto_invite, error_handler, success_handler, + variable_expiration_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, @@ -1729,6 +1780,7 @@ struct SetSlackOAuthConfigRequest { struct GetSlackOAuthConfigResponse { slack_oauth_client_id: Option, slack_oauth_client_secret: Option, + slack_signing_secret: Option, } async fn get_slack_oauth_config( @@ -1739,7 +1791,8 @@ async fn get_slack_oauth_config( require_admin(authed.is_admin, &authed.username)?; let settings = sqlx::query!( - "SELECT slack_oauth_client_id, slack_oauth_client_secret FROM workspace_settings WHERE workspace_id = $1", + "SELECT slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret + FROM workspace_settings WHERE workspace_id = $1", &w_id ) .fetch_one(&db) @@ -1753,6 +1806,7 @@ async fn get_slack_oauth_config( Ok(Json(GetSlackOAuthConfigResponse { slack_oauth_client_id: settings.slack_oauth_client_id, slack_oauth_client_secret: masked_secret, + slack_signing_secret: settings.slack_signing_secret.map(|_| "***".to_string()), })) } @@ -1810,8 +1864,11 @@ async fn set_slack_oauth_config( let mut tx = db.begin().await?; sqlx::query!( + // Another app's signing secret would reject every request the new app sends. "UPDATE workspace_settings - SET slack_oauth_client_id = $1, slack_oauth_client_secret = $2 + SET slack_oauth_client_id = $1, slack_oauth_client_secret = $2, + slack_signing_secret = CASE WHEN slack_oauth_client_id = $1::varchar + THEN slack_signing_secret END WHERE workspace_id = $3", &req.slack_oauth_client_id, &req.slack_oauth_client_secret, @@ -1848,6 +1905,51 @@ async fn set_slack_oauth_config( Ok(format!("Slack OAuth config set for workspace {}", &w_id)) } +#[derive(Deserialize)] +struct SetSlackSigningSecretRequest { + slack_signing_secret: Option, +} + +/// The signing secret of the workspace's own Slack app, which authenticates what Slack sends for it. +async fn set_slack_signing_secret( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Json(req): Json, +) -> Result { + require_admin(authed.is_admin, &authed.username)?; + let secret = req + .slack_signing_secret + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + + let mut tx = db.begin().await?; + sqlx::query!( + "UPDATE workspace_settings SET slack_signing_secret = $1 WHERE workspace_id = $2", + secret, + &w_id + ) + .execute(&mut *tx) + .await?; + audit_log( + &mut *tx, + &authed, + "workspaces.set_slack_signing_secret", + if secret.is_some() { + ActionKind::Update + } else { + ActionKind::Delete + }, + &w_id, + Some(&authed.email), + None, + ) + .await?; + tx.commit().await?; + + Ok(format!("Slack signing secret updated for workspace {w_id}")) +} + async fn delete_slack_oauth_config( authed: ApiAuthed, Extension(db): Extension, @@ -1859,7 +1961,8 @@ async fn delete_slack_oauth_config( sqlx::query!( "UPDATE workspace_settings - SET slack_oauth_client_id = NULL, slack_oauth_client_secret = NULL + SET slack_oauth_client_id = NULL, slack_oauth_client_secret = NULL, + slack_signing_secret = NULL WHERE workspace_id = $1", &w_id ) @@ -3263,6 +3366,10 @@ pub(crate) async fn resolve_pg_source_checked_with_kind( let pg: PgDatabase = serde_json::from_value(db_resource) .map_err(|e| Error::internal_err(format!("Failed to parse database credentials: {}", e)))?; + // Checked here rather than at each caller: every source and target of a dump, restore or copy + // comes through this function, and `validate_dbname` only ever reaches a target. The check is + // deliberately the narrow one — see `validate_dbname_not_option_like`. + windmill_common::validate_dbname_not_option_like(&pg.dbname)?; Ok((pg, managed_kind)) } @@ -3352,21 +3459,20 @@ pub(crate) struct PgDumpOptions<'a> { pub(crate) no_acl: bool, } -/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. -/// Returns a DumpFile handle; the file is deleted when the handle is dropped. -pub(crate) async fn pg_dump_database( +/// A pg_dump invocation against `pg_db` writing to `dump_path`, carrying the connection settings +/// the CLI reads from the environment. The returned file, when there is one, holds the root +/// certificate the command points at and must outlive it. +fn pg_dump_command( pg_db: &PgDatabase, opts: PgDumpOptions<'_>, -) -> Result { - let dump_file = DumpFile::new()?; - + dump_path: &std::path::Path, +) -> Result<(tokio::process::Command, Option)> { let host = &pg_db.host; let port = pg_db.port.unwrap_or(5432).to_string(); let user = pg_db.login_name(); - let dbname = &pg_db.dbname; let mut cmd = tokio::process::Command::new("pg_dump"); - cmd.arg("--format=plain").arg("--file").arg(&dump_file.path); + cmd.arg("--format=plain").arg("--file").arg(dump_path); if opts.schema_only { cmd.arg("--schema-only"); } @@ -3384,13 +3490,31 @@ pub(crate) async fn pg_dump_database( .arg("--port") .arg(&port) .arg("--username") - .arg(user) - .arg(dbname); + .arg(user); + + // The name comes from a resource, so it never goes on the command line: as the positional + // argument a name starting with `-` is read as an option of pg_dump (`--file`, + // `--restrict-key`), and as `--dbname` a name holding `=` is expanded as a libpq connection + // string overriding the host, port and user set above. libpq takes the environment variable + // as a plain database name, neither parsed as an option nor expanded. + cmd.env("PGDATABASE", &pg_db.dbname); if let Some(ref password) = pg_db.password { cmd.env("PGPASSWORD", password); } - let _root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; + let root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; + Ok((cmd, root_cert)) +} + +/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. +/// Returns a DumpFile handle; the file is deleted when the handle is dropped. +pub(crate) async fn pg_dump_database( + pg_db: &PgDatabase, + opts: PgDumpOptions<'_>, +) -> Result { + let dump_file = DumpFile::new()?; + + let (mut cmd, _root_cert) = pg_dump_command(pg_db, opts, &dump_file.path)?; let output = cmd .output() @@ -3516,12 +3640,14 @@ fn psql_command(pg_db: &PgDatabase) -> Result<(tokio::process::Command, Option PgDatabase { + PgDatabase { + host: "127.0.0.1".to_string(), + user: None, + password: None, + port: Some(1), + sslmode: None, + dbname: dbname.to_string(), + root_certificate_pem: None, + accept_invalid_certs: None, + use_iam_auth: None, + region: None, + options: None, + } + } + + fn pgdatabase_of(cmd: &std::process::Command) -> Option { + cmd.get_envs() + .find(|(k, _)| *k == "PGDATABASE") + .and_then(|(_, v)| v.map(|v| v.to_os_string())) + } + + #[test] + fn pg_dump_takes_the_dbname_from_the_environment() { + let dump_file = DumpFile::new().unwrap(); + let name = "--file=/tmp/written_by_the_caller"; + let (cmd, _root_cert) = + pg_dump_command(&pg_db(name), PgDumpOptions::default(), &dump_file.path).unwrap(); + let cmd = cmd.as_std(); + assert!( + cmd.get_args().all(|arg| arg != name), + "the dbname is still in pg_dump's argument vector" + ); + assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); + // The only `--file` pg_dump is given is still Windmill's own. + assert_eq!( + cmd.get_args() + .filter(|arg| arg.to_string_lossy().starts_with("--file")) + .count(), + 1 + ); + } + + #[test] + fn psql_takes_the_dbname_from_the_environment() { + let name = "host=elsewhere"; + let (cmd, _root_cert) = psql_command(&pg_db(name)).unwrap(); + let cmd = cmd.as_std(); + assert!( + cmd.get_args().all(|arg| arg != name), + "the dbname is still in psql's argument vector" + ); + assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); + } + + /// The same, observed on the real binary: an option-shaped name must reach the connection + /// attempt rather than pg_dump's option parser. Skipped where pg_dump is not installed — + /// which is why the assertion also requires that pg_dump ran at all (our `pg_dump failed:` + /// prefix) instead of only that the option message is absent. + #[tokio::test] + async fn pg_dump_does_not_read_an_option_shaped_dbname_as_an_option() { + if std::process::Command::new("pg_dump") + .arg("--version") + .output() + .is_err() + { + eprintln!("skipped: pg_dump is not installed"); + return; + } + let Err(err) = pg_dump_database(&pg_db("--no-such-option"), PgDumpOptions::default()).await + else { + panic!("pg_dump reached a server on 127.0.0.1:1"); + }; + let err = err.to_string(); + assert!( + err.contains("pg_dump failed:"), + "pg_dump did not run: {err}" + ); + assert!(!err.contains("unrecognized option"), "{err}"); + } +} + /// GUC names the server backing `pg_db` knows about. /// /// Asked through psql rather than a tokio-postgres connection so the lookup reaches @@ -3958,6 +4175,25 @@ fn ensure_copied_without_roles(governing: &GoverningDatatable) -> Result<()> { Ok(()) } +/// Gate for the endpoints that make the API server run `pg_dump`/`psql` against a database a +/// request names. +/// +/// Those two processes are children of the API server, outside any job sandbox and holding its +/// environment, and the dump they exchange is a `psql` script assembled from strings the source +/// server returns — so reaching them is close enough to running code on the server that the role +/// which may not run code at all must not reach them either. `code` is the capability the data +/// table migration endpoints next door already ask for (`datatable_migrations::ensure_not_operator`), +/// and not admin: the database manager offers an export and an import of a user's own Postgres +/// resource to every author, who can run the same `pg_dump` in a job anyway. +async fn ensure_can_dump_databases( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + action: &str, +) -> Result<()> { + windmill_common::workspaces::check_role_can_code(db, w_id, authed, action).await +} + /// Import (pg_dump/pg_import) from source to target async fn import_pg_database( authed: ApiAuthed, @@ -3966,6 +4202,8 @@ async fn import_pg_database( Path(w_id): Path, Json(req): Json, ) -> Result { + ensure_can_dump_databases(&db, &w_id, &authed, "import a database").await?; + if req.fork_behavior == DataTableForkBehavior::KeepOriginal { return Ok("No action needed for KeepOriginal behavior".to_string()); } @@ -4082,6 +4320,8 @@ async fn export_pg_schema( Path(w_id): Path, Json(req): Json, ) -> Result { + ensure_can_dump_databases(&db, &w_id, &authed, "export a database schema").await?; + let pg = resolve_pg_source_checked(&db, &user_db, &authed, &w_id, &req.source).await?; let dump_file = pg_dump_database( &pg, @@ -6157,6 +6397,157 @@ async fn edit_error_handler( Ok(format!("Edit error_handler for workspace {}", &w_id)) } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EditVariableExpirationHandler { + pub path: Option, + pub extra_args: Option, + #[serde(default)] + pub muted_on_user_path: bool, + pub notify_before_secs: Option, + pub remind_every_secs: Option, +} + +async fn edit_variable_expiration_handler( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Json(es): Json, +) -> Result { + require_admin(authed.is_admin, &authed.username)?; + + let mut tx = db.begin().await?; + + // Created with no access: an admin grants it write access to each variable it rotates. + sqlx::query_as!( + Group, + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING", + w_id, + "variable_expiration_handler", + "The group the variable expiration handler acts on behalf of", + serde_json::json!({username_to_permissioned_as(&authed.username): true}) + ) + .execute(&mut *tx) + .await?; + + if let Some(path) = &es.path { + if es + .extra_args + .as_ref() + .is_some_and(|extra_args| !extra_args.is_object()) + { + return Err(Error::BadRequest( + "Field `extra_args` expected to be JSON object".to_string(), + )); + } + + // Any hub script is left unchecked, so saving never needs the hub. + let exists = if let Some(p) = path.strip_prefix("script/") { + p.starts_with("hub/") + || sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND archived = false AND deleted = false)", + w_id, + p + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false) + } else if let Some(p) = path.strip_prefix("flow/") { + sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2 AND archived = false)", + w_id, + p + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false) + } else { + return Err(Error::BadRequest(format!( + "Field `path` must start with script/ or flow/ (got {path})" + ))); + }; + if !exists { + return Err(Error::BadRequest(format!( + "Variable expiration handler '{path}' not found. The handler must be an existing, non-archived script or flow." + ))); + } + + // Persisted even when false, like `error_handler`'s. + let mut variable_expiration_handler = serde_json::json!({ + "path": path, + "muted_on_user_path": es.muted_on_user_path, + }); + if let Some(extra_args) = &es.extra_args { + variable_expiration_handler["extra_args"] = extra_args.clone(); + } + if let Some(notify_before_secs) = es.notify_before_secs { + variable_expiration_handler["notify_before_secs"] = notify_before_secs.into(); + } + if let Some(remind_every_secs) = es.remind_every_secs { + variable_expiration_handler["remind_every_secs"] = remind_every_secs.into(); + } + + // A recorded failure is the sweep's: it ends at the handler's next start. + sqlx::query!( + "UPDATE workspace_settings SET variable_expiration_handler = $1 WHERE workspace_id = $2", + variable_expiration_handler, + &w_id + ) + .execute(&mut *tx) + .await?; + } else { + sqlx::query!( + "UPDATE workspace_settings SET variable_expiration_handler = NULL WHERE workspace_id = $1", + &w_id + ) + .execute(&mut *tx) + .await?; + } + + audit_log( + &mut *tx, + &authed, + "workspaces.edit_variable_expiration_handler", + ActionKind::Update, + &w_id, + Some(&authed.email), + Some([("variable_expiration_handler", &format!("{:?}", es.path)[..])].into()), + ) + .await?; + tx.commit().await?; + + handle_deployment_metadata( + &authed.email, + &authed.username, + &db, + &w_id, + windmill_git_sync::DeployedObject::Settings { + setting_type: "variable_expiration_handler".to_string(), + }, + Some("Variable expiration handler configuration updated".to_string()), + false, + None, + ) + .await?; + + windmill_common::feature_usage::log_feature_usage( + "variable_expiration", + "handler_configured", + // By slug, not hub id, so a bumped hub version still counts as the built-in. + match es.path.as_deref() { + None => "cleared", + Some(p) if p.ends_with("/variable-expiration-handler-slack") => "slack", + Some(p) if p.ends_with("/variable-expiration-handler-teams") => "teams", + Some(_) => "custom", + }, + ); + + Ok(format!( + "Edit variable_expiration_handler for workspace {}", + &w_id + )) +} + async fn edit_success_handler( authed: ApiAuthed, Extension(db): Extension, @@ -6428,7 +6819,7 @@ async fn set_encryption_key( ); let all_variables = sqlx::query!( - "SELECT path, value, is_secret FROM variable WHERE workspace_id = $1", + "SELECT path, value::text AS \"value!\", is_secret FROM variable WHERE workspace_id = $1", w_id ) .fetch_all(&mut *tx) @@ -6689,13 +7080,11 @@ async fn user_workspaces( Extension(db): Extension, ApiAuthed { email, .. }: ApiAuthed, ) -> JsonResult { - let mut tx = db.begin().await?; - let workspaces = sqlx::query_as!( - UserWorkspace, + let rows = sqlx::query!( "SELECT workspace.id, workspace.name, usr.username, workspace_settings.color, workspace.parent_workspace_id, workspace.is_dev_workspace, workspace.dev_workspace_label, workspace.owner AS \"created_by?\", - CASE WHEN usr.operator THEN workspace_settings.operator_settings ELSE NULL END as operator_settings, + usr.is_admin, usr.operator, usr.workspace_role, usr.disabled, usr.is_service_account FROM workspace JOIN usr ON usr.workspace_id = workspace.id @@ -6703,9 +7092,46 @@ async fn user_workspaces( WHERE usr.email = $1 AND workspace.deleted = false", email ) - .fetch_all(&mut *tx) + .fetch_all(&db) .await?; - tx.commit().await?; + let mut workspaces = Vec::with_capacity(rows.len()); + for r in rows { + let role = windmill_common::roles::resolve_role_name(r.workspace_role, r.operator); + let capabilities = if r.is_admin { + windmill_common::roles::RoleCapabilities::FULL + } else { + windmill_common::roles::role_capabilities_by_name(&db, &r.id, &role).await? + }; + // The pre-roles shape the frontend gates on: present exactly for a restricted member. + let operator_settings = (capabilities.is_restricted()).then(|| { + let v = &capabilities.visibility; + Some(serde_json::json!({ + "runs": v.runs, "schedules": v.schedules, "resources": v.resources, + "variables": v.variables, "assets": v.assets, "triggers": v.triggers, + "audit_logs": v.audit_logs, "groups": v.groups, "folders": v.folders, + "workers": v.workers, + "builder_flows": capabilities.flows != windmill_common::roles::AuthorLevel::None, + "builder_apps": capabilities.apps != windmill_common::roles::AuthorLevel::None, + "manage_schedules": capabilities.manage_schedules, + "manage_triggers": capabilities.manage_triggers, + })) + }); + workspaces.push(UserWorkspace { + id: r.id, + name: r.name, + username: r.username, + color: r.color, + operator_settings, + parent_workspace_id: r.parent_workspace_id, + is_dev_workspace: r.is_dev_workspace, + dev_workspace_label: r.dev_workspace_label, + created_by: r.created_by, + disabled: r.disabled, + is_service_account: r.is_service_account, + role, + capabilities, + }); + } Ok(Json(WorkspaceList { email, workspaces })) } @@ -7672,9 +8098,9 @@ async fn copy_workspace_members( // instance-group config, so a copied `instance_group` provenance would let the fork's // reconciliation delete them and their data. sqlx::query!( - "INSERT INTO usr (workspace_id, username, email, is_admin, created_at, operator, disabled, role, is_service_account, added_via) + "INSERT INTO usr (workspace_id, username, email, is_admin, created_at, operator, disabled, role, is_service_account, added_via, workspace_role) SELECT $1, username, email, is_admin, created_at, operator, disabled, role, is_service_account, - CASE WHEN $3 THEN NULL ELSE added_via END + CASE WHEN $3 THEN NULL ELSE added_via END, workspace_role FROM usr WHERE workspace_id = $2 AND (NOT $3 OR (NOT operator AND NOT disabled AND NOT is_service_account)) ON CONFLICT DO NOTHING", @@ -7684,6 +8110,27 @@ async fn copy_workspace_members( ) .execute(&mut **tx) .await?; + // The members keep their roles, so the fork needs the source's workspace-only roles and + // overrides to give them the same meaning. + sqlx::query!( + "UPDATE workspace_settings SET role_overrides = + (SELECT role_overrides FROM workspace_settings WHERE workspace_id = $2) + WHERE workspace_id = $1", + target_workspace_id, + source_workspace_id, + ) + .execute(&mut **tx) + .await?; + sqlx::query!( + "INSERT INTO role_seat (workspace_id, role, author) + SELECT $1, role, author FROM role_seat WHERE workspace_id = $2 + ON CONFLICT DO NOTHING", + target_workspace_id, + source_workspace_id, + ) + .execute(&mut **tx) + .await?; + windmill_common::roles::invalidate_workspace_roles_cache(target_workspace_id); Ok(()) } @@ -7773,9 +8220,10 @@ async fn clone_variables( source_workspace_id: &str, target_workspace_id: &str, ) -> Result<()> { + // Dispatch markers are not copied, so the fork re-arms its own handler. sqlx::query!( - "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at) - SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at + "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until) + SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until FROM variable WHERE workspace_id = $1", source_workspace_id, @@ -11389,7 +11837,11 @@ async fn invite_user( Json(mut nu): Json, ) -> Result<(StatusCode, String)> { require_admin(is_admin, &username)?; - reject_admin_and_operator(nu.is_admin, nu.operator)?; + if nu.role.is_none() { + reject_admin_and_operator(nu.is_admin, nu.operator)?; + } + let (role, role_operator) = + resolve_new_member_role(&db, &w_id, nu.operator, nu.role.as_deref()).await?; #[cfg(not(feature = "enterprise"))] if w_id == "admins" { @@ -11404,7 +11856,7 @@ async fn invite_user( if let Some(msg) = windmill_common::ee_oss::check_seat_cap_for_new_user( &db, &nu.email, - windmill_common::workspaces::consumes_operator_seat(&db, &w_id, nu.operator).await?, + windmill_common::workspaces::consumes_operator_seat(&db, &w_id, nu.is_admin, &role).await?, ) .await? { @@ -11431,13 +11883,15 @@ async fn invite_user( sqlx::query!( "INSERT INTO workspace_invite - (workspace_id, email, is_admin, operator) - VALUES ($1, $2, $3, $4) ON CONFLICT (workspace_id, email) - DO UPDATE SET is_admin = EXCLUDED.is_admin, operator = EXCLUDED.operator", + (workspace_id, email, is_admin, operator, workspace_role) + VALUES ($1, $2, $3, $4, $5) ON CONFLICT (workspace_id, email) + DO UPDATE SET is_admin = EXCLUDED.is_admin, operator = EXCLUDED.operator, + workspace_role = EXCLUDED.workspace_role", &w_id, nu.email, nu.is_admin, - nu.operator + role_operator, + &role ) .execute(&mut *tx) .await?; @@ -11490,7 +11944,13 @@ async fn authorize_fork_owner_add_user( .await? .ok_or_else(|| Error::RequireAdmin(authed.username.clone()))?; - if nu.is_admin || nu.operator { + if nu.is_admin + || nu.operator + || nu + .role + .as_deref() + .is_some_and(|r| r != windmill_common::roles::DEVELOPER_ROLE) + { return Err(Error::PermissionDenied(format!( "as the creator of fork {w_id} you can only add members as developers; ask an admin of \ {w_id} for any other role" @@ -11541,7 +12001,11 @@ async fn add_user( Path(w_id): Path, Json(mut nu): Json, ) -> Result<(StatusCode, String)> { - reject_admin_and_operator(nu.is_admin, nu.operator)?; + if nu.role.is_none() { + reject_admin_and_operator(nu.is_admin, nu.operator)?; + } + let (role, role_operator) = + resolve_new_member_role(&db, &w_id, nu.operator, nu.role.as_deref()).await?; #[cfg(not(feature = "enterprise"))] if w_id == "admins" { @@ -11562,7 +12026,7 @@ async fn add_user( if let Some(msg) = windmill_common::ee_oss::check_seat_cap_for_new_user( &db, &nu.email, - windmill_common::workspaces::consumes_operator_seat(&db, &w_id, nu.operator).await?, + windmill_common::workspaces::consumes_operator_seat(&db, &w_id, nu.is_admin, &role).await?, ) .await? { @@ -11622,13 +12086,14 @@ async fn add_user( sqlx::query!( "INSERT INTO usr - (workspace_id, email, username, is_admin, operator) - VALUES ($1, $2, $3, $4, $5)", + (workspace_id, email, username, is_admin, operator, workspace_role) + VALUES ($1, $2, $3, $4, $5, $6)", &w_id, nu.email, username, nu.is_admin, - nu.operator + role_operator, + &role ) .execute(&mut *tx) .await?; @@ -11737,11 +12202,14 @@ async fn delete_invite( sqlx::query!( "DELETE FROM workspace_invite WHERE - workspace_id = $1 AND email = $2 AND is_admin = $3 AND operator = $4", + workspace_id = $1 AND email = $2 AND is_admin = $3 + AND ($5::text IS NOT NULL OR operator = $4) + AND ($5::text IS NULL OR $5 = COALESCE(workspace_role, CASE WHEN operator THEN 'operator' ELSE 'developer' END))", &w_id, nu.email, nu.is_admin, - nu.operator + nu.operator, + nu.role ) .execute(&mut *tx) .await?; @@ -12105,114 +12573,6 @@ pub async fn get_public_app_rate_limit(db: &DB, w_id: &str) -> Result, - #[serde(default, skip_serializing_if = "Option::is_none")] - builder_apps: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - manage_schedules: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - manage_triggers: Option, -} - -async fn update_operator_settings( - authed: ApiAuthed, - Path(w_id): Path, - Extension(db): Extension, - Json(settings): Json, -) -> Result { - require_admin(authed.is_admin, &authed.username)?; - - // Every operator of the workspace turns into a full seat, which an offline license may not - // cover. Either right costs the same seat, so this prices "any", and it is a no-op delta when - // one of them is already on. - #[cfg(feature = "enterprise")] - if settings.builder_flows == Some(true) || settings.builder_apps == Some(true) { - if let Some(msg) = - windmill_common::ee_oss::check_seat_cap_for_operator_builder(&db, &w_id).await? - { - return Err(Error::BadRequest(msg)); - } - } - - let mut tx = db.begin().await?; - - let settings_json = serde_json::json!(settings); - - // Merged for the `Option` fields above; the visibility flags always serialize, so for them - // this is a plain overwrite. - sqlx::query!( - "UPDATE workspace_settings - SET operator_settings = COALESCE(operator_settings, '{}'::jsonb) || $1 - WHERE workspace_id = $2", - settings_json, - &w_id - ) - .execute(&mut *tx) - .await?; - - audit_log( - &mut *tx, - &authed, - "workspaces.update_operator_settings", - ActionKind::Update, - &w_id, - None, - Some([("operator_settings", settings_json.to_string().as_str())].into()), - ) - .await?; - tx.commit().await?; - - windmill_common::workspaces::invalidate_operator_rights_cache(&w_id); - - // Trigger git sync for operator settings changes - handle_deployment_metadata( - &authed.email, - &authed.username, - &db, - &w_id, - windmill_git_sync::DeployedObject::Settings { - setting_type: "operator_settings".to_string(), - }, - Some("Operator settings updated".to_string()), - false, - None, - ) - .await?; - - Ok("Operator settings updated successfully".to_string()) -} - // Protection Rules API endpoints #[derive(Deserialize)] @@ -13812,7 +14172,7 @@ async fn load_workspace_authed( let is_super_admin = windmill_api_auth::is_super_admin_authed(db, base_authed).await?; let user_row = sqlx::query!( - "SELECT username, is_admin, operator FROM usr + "SELECT username, is_admin, operator, workspace_role FROM usr WHERE workspace_id = $1 AND email = $2 AND disabled = false", workspace_id, &base_authed.email @@ -13858,7 +14218,14 @@ async fn load_workspace_authed( email: base_authed.email.clone(), username: user_row.username, is_admin: is_super_admin || user_row.is_admin, - is_operator: user_row.operator, + is_operator: !user_row.is_admin + && windmill_common::roles::member_is_restricted( + &mut conn, + workspace_id, + user_row.workspace_role.clone(), + user_row.operator, + ) + .await?, groups, folders, scopes: base_authed.scopes.clone(), @@ -14303,6 +14670,12 @@ async fn compare_two_apps( }); } +// Resources and resource types can be stored with a NULL description, but deploy writes "", +// so the two must compare equal or the item never settles after a deploy. +fn description_differs(a: &Option, b: &Option) -> bool { + a.as_deref().unwrap_or("") != b.as_deref().unwrap_or("") +} + async fn compare_two_resources( db: &DB, source_workspace_id: &str, @@ -14371,7 +14744,7 @@ async fn compare_two_resources( source.value != target.value }; if values_differ - || source.description != target.description + || description_differs(&source.description, &target.description) || source.resource_type != target.resource_type { has_changes = true; @@ -14426,7 +14799,7 @@ async fn compare_two_variables( // Get variable from each workspace let source_variable = sqlx::query!( - "SELECT value, is_secret, description + "SELECT value::text AS \"value!\", is_secret, description, value_valid_until FROM variable WHERE workspace_id = $1 AND path = $2", source_workspace_id, @@ -14436,7 +14809,7 @@ async fn compare_two_variables( .await?; let target_variable = sqlx::query!( - "SELECT value, is_secret, description + "SELECT value::text AS \"value!\", is_secret, description, value_valid_until FROM variable WHERE workspace_id = $1 AND path = $2", fork_workspace_id, @@ -14450,10 +14823,24 @@ async fn compare_two_variables( // Check metadata differences if let (Some(source), Some(target)) = (&source_variable, &target_variable) { if source.is_secret != target.is_secret - || source.value != target.value || source.description != target.description + || source.value_valid_until != target.value_valid_until { has_changes = true; + } else if source.value != target.value + || (source.is_secret && is_external_stored_value(&source.value)) + { + // A secret's ciphertext is randomized on every write, so equal secrets are compared + // by plaintext, each decrypted with its own workspace's key. An external backend + // reference is the same text on both sides but names a per-workspace entry. + has_changes = !source.is_secret + || !matches!( + tokio::try_join!( + decrypt_secret_value(db, source_workspace_id, path, source.value.clone()), + decrypt_secret_value(db, fork_workspace_id, path, target.value.clone()), + ), + Ok((a, b)) if a == b + ); } } else if source_variable.is_some() || target_variable.is_some() { // The variable exists in one of source or target, but not the other, this is considered as a change @@ -14499,7 +14886,7 @@ async fn compare_two_resource_types( // Check metadata differences if let (Some(source), Some(target)) = (&source_resource_type, &target_resource_type) { if source.schema != target.schema - || source.description != target.description + || description_differs(&source.description, &target.description) || source.format_extension != target.format_extension || source.is_fileset != target.is_fileset { @@ -15267,6 +15654,7 @@ pub enum SettingsEdit { InstanceGroups, ErrorHandler, SuccessHandler, + VariableExpirationHandler, LargeFileStorage, GitSync, DefaultScripts, @@ -15319,6 +15707,9 @@ pub async fn apply_settings_edit( InstanceGroups => edit_instance_groups(a, d, p, settings_edit_body(edit, body)?).await?, ErrorHandler => edit_error_handler(a, d, p, settings_edit_body(edit, body)?).await?, SuccessHandler => edit_success_handler(a, d, p, settings_edit_body(edit, body)?).await?, + VariableExpirationHandler => { + edit_variable_expiration_handler(a, d, p, settings_edit_body(edit, body)?).await? + } LargeFileStorage => { edit_large_file_storage_config(a, d, p, settings_edit_body(edit, body)?).await? } @@ -15327,7 +15718,13 @@ pub async fn apply_settings_edit( DefaultApp => edit_default_app(a, d, p, settings_edit_body(edit, body)?).await?, Color => change_workspace_color(a, p, d, settings_edit_body(edit, body)?).await?, OperatorSettings => { - update_operator_settings(a, p, d, settings_edit_body(edit, body)?).await? + crate::workspace_roles::update_operator_settings( + a, + p, + d, + settings_edit_body(edit, body)?, + ) + .await? } Datatable => { let Json(result) = diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index e02d7c8c3e..aea887624d 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -135,7 +135,7 @@ pub(crate) async fn change_workspace_id( // Duplicate workspace settings (keep copy in old workspace for reference) info!("Duplicating workspace_settings table"); sqlx::query!( - "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at FROM workspace_settings WHERE workspace_id = $2", + "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", &rw.new_id, &old_id ) @@ -225,6 +225,14 @@ pub(crate) async fn change_workspace_id( .execute(&mut *tx) .await?; + sqlx::query!( + "UPDATE role_seat SET workspace_id = $1 WHERE workspace_id = $2", + &rw.new_id, + &old_id + ) + .execute(&mut *tx) + .await?; + info!("Updating account table"); sqlx::query!( "UPDATE account SET workspace_id = $1 WHERE workspace_id = $2", @@ -856,7 +864,7 @@ pub(crate) async fn change_workspace_id( info!("Duplicating usr table"); sqlx::query!( - "INSERT INTO usr SELECT $1, username, email, is_admin, created_at, operator, disabled, role FROM usr WHERE workspace_id = $2", + "INSERT INTO usr (workspace_id, username, email, is_admin, created_at, operator, disabled, role, workspace_role) SELECT $1, username, email, is_admin, created_at, operator, disabled, role, workspace_role FROM usr WHERE workspace_id = $2", &rw.new_id, &old_id ) @@ -1258,6 +1266,10 @@ pub(crate) async fn delete_workspace( .execute(&mut *tx) .await?; + sqlx::query!("DELETE FROM role_seat WHERE workspace_id = $1", &w_id) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM resource_type WHERE workspace_id = $1", &w_id) .execute(&mut *tx) .await?; diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index dc32e6e50b..f889890c92 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.841.0 + version: 1.849.0 title: Windmill API contact: @@ -3696,13 +3696,16 @@ paths: type: boolean operator: type: boolean + description: Legacy role selector, true for the `operator` role. + role: + type: string + description: The workspace role to give, one of the workspace's roles. Wins over `operator`. parent_workspace_id: type: string nullable: true required: - email - is_admin - - operator responses: "200": description: status @@ -3735,10 +3738,13 @@ paths: type: string operator: type: boolean + description: Legacy role selector, true for the `operator` role. + role: + type: string + description: The workspace role to give, one of the workspace's roles. Wins over `operator`. required: - email - is_admin - - operator responses: "200": description: status @@ -4078,6 +4084,46 @@ paths: schema: type: string + /w/{workspace}/workspaces/roles: + get: + operationId: listWorkspaceRoles + summary: List the workspace's roles + description: The roles members of this workspace can hold, as they apply here (instance definition with the workspace's override applied, then workspace-only roles), the stored overrides, and the caller's own role and capabilities. + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: workspace roles + content: + application/json: + schema: + $ref: "#/components/schemas/WorkspaceRoles" + + /w/{workspace}/workspaces/role_overrides: + post: + operationId: updateWorkspaceRoleOverrides + summary: Replace the workspace's role overrides + description: Replaces the workspace's overrides of instance roles, and its workspace-only roles (EE). Refuses removing a workspace-only role still held or referenced, and a change exceeding an offline license's seat cap. Requires workspace admin privileges. + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/RoleOverrides" + responses: + "200": + description: role overrides updated + content: + text/plain: + schema: + type: string + /w/{workspace}/workspaces/compare/{target_workspace_id}: get: operationId: compareWorkspaces @@ -4320,6 +4366,8 @@ paths: $ref: "#/components/schemas/ErrorHandlerConfig" success_handler: $ref: "#/components/schemas/SuccessHandlerConfig" + variable_expiration_handler: + $ref: "#/components/schemas/VariableExpirationHandlerConfig" large_file_storage: $ref: "#/components/schemas/LargeFileStorage" ducklake: @@ -4778,6 +4826,10 @@ paths: type: string nullable: true description: Masked with *** if set + slack_signing_secret: + type: string + nullable: true + description: Masked with *** if set post: summary: set workspace slack oauth config operationId: setWorkspaceSlackOauthConfig @@ -4822,6 +4874,33 @@ paths: schema: type: string + /w/{workspace}/workspaces/slack_signing_secret: + post: + summary: set the signing secret of the workspace's own slack app + operationId: setWorkspaceSlackSigningSecret + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + description: The Slack app's signing secret, null or empty to remove it + required: true + content: + application/json: + schema: + type: object + properties: + slack_signing_secret: + type: string + nullable: true + responses: + "200": + description: status + content: + text/plain: + schema: + type: string + /w/{workspace}/workspaces/edit_teams_command: post: summary: edit teams command @@ -5075,6 +5154,9 @@ paths: properties: operator: type: boolean + role: + type: string + description: The workspace role to give, one of the workspace's roles. Wins over `operator`. invite_all: type: boolean auto_add: @@ -5352,6 +5434,29 @@ paths: schema: type: string + /w/{workspace}/workspaces/edit_variable_expiration_handler: + post: + summary: edit variable expiration handler + operationId: editVariableExpirationHandler + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + description: WorkspaceVariableExpirationHandler + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/EditVariableExpirationHandler" + responses: + "200": + description: status + content: + text/plain: + schema: + type: string + /w/{workspace}/workspaces/edit_success_handler: post: summary: edit success handler @@ -8757,6 +8862,11 @@ paths: type: string state: type: string + params: + type: object + description: The callback URL's other query params, which the provider's `connect_fields` may read (QuickBooks' `realmId`) + additionalProperties: + type: string required: - code - state @@ -8814,6 +8924,9 @@ paths: items: type: string description: "OAuth scopes to use for token refresh. Overrides instance-level scopes." + variable: + $ref: "#/components/schemas/CreateVariable" + description: "The variable holding this account's access token. It is created with the account, in one transaction and with the same checks as createVariable, and linked to it so it refreshes through it." required: - refresh_token - expires_in @@ -15658,6 +15771,10 @@ paths: value: {} policy: $ref: "#/components/schemas/Policy" + execution_mode: + type: string + enum: [viewer, publisher, guest, anonymous] + description: "Changes who may open the app and leaves the rest of the deployed policy, its run-as user included, as it is. Applied under the same lock as a deploy, so neither overwrites the other. Cannot be sent with `policy`, which states its own mode. When the app runs as another user, refused to a caller who is neither an admin nor in 'wm_deployers', and to an operator with builder rights even in 'wm_deployers'; they change the mode by deploying." deployment_message: type: string custom_path: @@ -17024,6 +17141,12 @@ paths: user_attachments: type: array items: {} + previous_messages: + description: | + The history to answer from, as chat messages, when the agent's memory is off. + An agent with managed memory reads its conversation instead and ignores this. + type: array + items: {} responses: "201": description: job created @@ -21019,12 +21142,22 @@ paths: schema: $ref: "#/components/schemas/NativeServiceName" requestBody: - description: redirect_uri + description: >- + redirect_uri, and where to save the connection (defaults to + u/{caller}/native_{resource_type}). Uses the workspace OAuth client, or the instance + one when the instance shares it. required: true content: application/json: schema: - $ref: "#/components/schemas/RedirectUri" + type: object + properties: + redirect_uri: + type: string + resource_path: + type: string + required: + - redirect_uri responses: "200": description: native trigger service connect url @@ -21054,10 +21187,59 @@ paths: schema: type: boolean - /w/{workspace}/native_triggers/integrations/{service_name}/generate_instance_connect_url: + /w/{workspace}/native_triggers/integrations/{service_name}/connections: + get: + summary: list the native trigger connections of a service the caller can use + operationId: listNativeTriggerConnections + tags: + - workspace_integration + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: service_name + in: path + required: true + schema: + $ref: "#/components/schemas/NativeServiceName" + responses: + "200": + description: connections + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/NativeTriggerConnection" + + /w/{workspace}/native_triggers/integrations/{service_name}/connections/delete: + delete: + summary: disconnect a native trigger connection and delete the triggers using it + operationId: deleteNativeTriggerConnection + tags: + - workspace_integration + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: service_name + in: path + required: true + schema: + $ref: "#/components/schemas/NativeServiceName" + - name: path + in: query + required: true + schema: + type: string + responses: + "200": + description: connection deleted + content: + application/json: + schema: + type: string + + /w/{workspace}/native_triggers/integrations/{service_name}/workspace_connection: post: - summary: generate connect url using instance-level credentials - operationId: generateInstanceConnectUrl + summary: share a connection of this service with every member of the workspace (admin only), or stop sharing + operationId: setNativeTriggerWorkspaceConnection tags: - workspace_integration parameters: @@ -21068,15 +21250,19 @@ paths: schema: $ref: "#/components/schemas/NativeServiceName" requestBody: - description: redirect_uri required: true content: application/json: schema: - $ref: "#/components/schemas/RedirectUri" + type: object + properties: + path: + type: string + nullable: true + description: The connection to share, or null to stop sharing responses: "200": - description: authorization URL using instance credentials + description: workspace connection updated content: application/json: schema: @@ -21130,17 +21316,15 @@ paths: type: string redirect_uri: type: string - resource_path: - type: string required: - code - state - redirect_uri responses: "200": - description: native trigger service oauth completed + description: path of the saved connection content: - text/plain: + application/json: schema: type: string @@ -21415,6 +21599,12 @@ paths: required: true schema: type: string + - name: connection_path + in: query + description: Connection to browse through; defaults to the caller's only usable one + required: false + schema: + type: string responses: "200": description: list of available NextCloud events @@ -21437,6 +21627,12 @@ paths: required: true schema: type: string + - name: connection_path + in: query + description: Connection to browse through; defaults to the caller's only usable one + required: false + schema: + type: string responses: "200": description: list of Google Calendars @@ -21459,6 +21655,12 @@ paths: required: true schema: type: string + - name: connection_path + in: query + description: Connection to browse through; defaults to the caller's only usable one + required: false + schema: + type: string - name: q in: query description: search query to filter files by name @@ -21500,6 +21702,12 @@ paths: required: true schema: type: string + - name: connection_path + in: query + description: Connection to browse through; defaults to the caller's only usable one + required: false + schema: + type: string responses: "200": description: list of shared drives @@ -21522,6 +21730,12 @@ paths: required: true schema: type: string + - name: connection_path + in: query + description: Connection to browse through; defaults to the caller's only usable one + required: false + schema: + type: string responses: "200": description: list of GitHub repositories @@ -24469,6 +24683,56 @@ paths: items: $ref: "#/components/schemas/AutoscalingEvent" + /configs/test_autoscaling/{worker_group}: + post: + summary: Run an autoscaling integration once for a worker group, without recording an autoscaling event + operationId: testAutoscaling + tags: + - config + parameters: + - name: worker_group + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + desired_workers: + type: integer + minimum: 0 + integration: + description: The integration to run, as in the worker group's autoscaling config + type: object + properties: + type: + type: string + enum: [script, kubernetes, dryrun] + path: + type: string + tag: + type: string + required: + - type + required: + - desired_workers + - integration + responses: + "200": + description: The job queued for a script integration + content: + application/json: + schema: + type: object + properties: + job_id: + type: string + nullable: true + /configs/native_kubernetes_autoscaling_healthcheck: get: summary: Check Kubernetes autoscaling health for a worker group @@ -29609,6 +29873,45 @@ components: type: boolean default: false + EditVariableExpirationHandler: + type: object + description: > + Request body for editing the workspace variable expiration handler. Omit + `path` (or send null) to unset the handler. + properties: + path: + type: string + nullable: true + description: Path to the variable expiration handler script or flow + extra_args: + $ref: "#/components/schemas/ScriptArgs" + muted_on_user_path: + type: boolean + description: Do not run the handler for variables on a personal (u/) path + notify_before_secs: + type: integer + minimum: 0 + description: How long before a variable's value expires the handler runs. 1 day when omitted. + remind_every_secs: + type: integer + minimum: 0 + description: Run the handler again at this interval until the value expires. No reminders when omitted or 0. + + VariableExpirationHandlerConfig: + type: object + description: Workspace variable expiration handler configuration + properties: + path: + type: string + extra_args: + $ref: "#/components/schemas/ScriptArgs" + muted_on_user_path: + type: boolean + notify_before_secs: + type: integer + remind_every_secs: + type: integer + EditSuccessHandler: description: Request body for editing the workspace success handler. Accepts both new grouped format and legacy flat format for backward compatibility. oneOf: @@ -32079,6 +32382,10 @@ components: type: boolean operator: type: boolean + description: Legacy role selector, true for the `operator` role and false for `developer`. + role: + type: string + description: The member's workspace role, one of the workspace's roles. Wins over `operator`. disabled: type: boolean @@ -32476,6 +32783,10 @@ components: expires_at: type: string format: date-time + value_valid_until: + type: string + nullable: true + format: date-time labels: type: array items: @@ -32545,13 +32856,25 @@ components: description: The description of the variable account: type: integer - description: The account identifier + deprecated: true + description: Ignored. A variable is linked to an OAuth account only when `createAccount` creates both. is_oauth: type: boolean description: Whether the variable is an OAuth variable expires_at: type: string - description: The expiration date of the variable + description: > + When to garbage-collect the variable. Used for ephemeral secrets; + the variable is deleted once this is reached. Not the value's expiry + — see value_valid_until. + format: date-time + value_valid_until: + type: string + description: > + When the value stored in this variable stops working. Triggers the + workspace's variable expiration handler ahead of it, by the handler's + `notify_before_secs` (1 day by default); never causes the variable + to be deleted. format: date-time labels: type: array @@ -32580,6 +32903,14 @@ components: description: type: string description: The new description of the variable + value_valid_until: + type: string + nullable: true + description: > + When the value stored in this variable stops working. Omit to leave + it unchanged; send null to clear it. Changing it re-arms the + workspace's variable expiration handler. + format: date-time labels: type: array items: @@ -32687,6 +33018,7 @@ components: - "workspaces.edit_webhook" - "workspaces.edit_copilot_config" - "workspaces.edit_error_handler" + - "workspaces.edit_variable_expiration_handler" - "workspaces.create" - "workspaces.update" - "workspaces.archive" @@ -36921,6 +37253,11 @@ components: is_service_account: type: boolean description: Whether this membership is a service account. + role: + type: string + description: The member's workspace role. + capabilities: + $ref: "#/components/schemas/RoleCapabilities" required: - id - name @@ -36928,6 +37265,8 @@ components: - color - is_dev_workspace - disabled + - role + - capabilities required: - email - workspaces @@ -37106,6 +37445,9 @@ components: type: boolean operator: type: boolean + role: + type: string + description: The workspace role the invite grants. parent_workspace_id: type: string nullable: true @@ -37114,6 +37456,7 @@ components: - email - is_admin - operator + - role GlobalUserInfo: type: object @@ -37785,6 +38128,13 @@ components: type: string grant_type: type: string + resource_fields: + type: object + additionalProperties: {} + description: > + Resource fields the provider's `connect_fields` picked on connect + (Salesforce's instance_url, Docusign's account_id and base_uri, + QuickBooks' realmId), for the connect dialog to prefill. required: - access_token @@ -38870,6 +39220,122 @@ components: type: boolean description: Whether operators can create, edit and delete triggers. Granted unless withdrawn; omitting the field leaves the stored value unchanged. + AuthorLevel: + type: string + enum: [none, compose, full] + description: How much of a kind of runnable a role may author. `compose` assembles already-deployed runnables with no code of one's own. + + RoleVisibility: + type: object + description: Pages a role sees. Not enforced. + properties: + runs: { type: boolean } + schedules: { type: boolean } + resources: { type: boolean } + variables: { type: boolean } + assets: { type: boolean } + triggers: { type: boolean } + audit_logs: { type: boolean } + groups: { type: boolean } + folders: { type: boolean } + workers: { type: boolean } + required: [runs, schedules, resources, variables, assets, triggers, audit_logs, groups, folders, workers] + + RoleCapabilities: + type: object + properties: + code: + type: boolean + description: Author scripts and run code of one's own (previews, dependency jobs, dynamic selects, resolving jobs, data table migrations). Required by `full` flows or apps. + flows: + $ref: "#/components/schemas/AuthorLevel" + apps: + $ref: "#/components/schemas/AuthorLevel" + manage_schedules: + type: boolean + manage_triggers: + type: boolean + visibility: + $ref: "#/components/schemas/RoleVisibility" + required: [code, flows, apps, manage_schedules, manage_triggers, visibility] + + RoleCapabilitiesPatch: + type: object + description: A partial RoleCapabilities; an unset key falls through to the layer below. + properties: + code: { type: boolean } + flows: + $ref: "#/components/schemas/AuthorLevel" + apps: + $ref: "#/components/schemas/AuthorLevel" + manage_schedules: { type: boolean } + manage_triggers: { type: boolean } + visibility: + type: object + additionalProperties: + type: boolean + + RoleDefinition: + type: object + description: One entry of the `workspace_roles` instance setting. + properties: + name: + type: string + label: + type: string + capabilities: + $ref: "#/components/schemas/RoleCapabilitiesPatch" + required: [name] + + RoleOverride: + type: object + properties: + label: + type: string + capabilities: + $ref: "#/components/schemas/RoleCapabilitiesPatch" + + RoleOverrides: + type: object + description: A workspace's overrides keyed by role name; a name the instance does not define adds a workspace-only role (EE). + additionalProperties: + $ref: "#/components/schemas/RoleOverride" + + EffectiveRole: + type: object + properties: + name: + type: string + label: + type: string + capabilities: + $ref: "#/components/schemas/RoleCapabilities" + source: + type: string + enum: [instance, workspace] + overridden: + type: boolean + required: [name, label, capabilities, source, overridden] + + WorkspaceRoles: + type: object + properties: + roles: + type: array + items: + $ref: "#/components/schemas/EffectiveRole" + overrides: + $ref: "#/components/schemas/RoleOverrides" + custom_roles_enabled: + type: boolean + description: Whether this workspace may add roles of its own. + my_role: + type: string + nullable: true + my_capabilities: + $ref: "#/components/schemas/RoleCapabilities" + required: [roles, overrides, custom_roles_enabled, my_capabilities] + WorkspaceComparison: type: object required: @@ -39648,6 +40114,10 @@ components: enabled: type: boolean description: Whether the trigger starts a job when it fires + connection_path: + type: string + nullable: true + description: Path of the connection the trigger acts through on the external service required: - external_id - workspace_id @@ -39690,6 +40160,10 @@ components: enabled: type: boolean description: Whether the trigger starts a job when it fires + connection_path: + type: string + nullable: true + description: Path of the connection the trigger acts through on the external service external_data: type: object nullable: true @@ -39721,10 +40195,6 @@ components: oauth_data: nullable: true $ref: "#/components/schemas/WorkspaceOAuthConfig" - resource_path: - type: string - nullable: true - description: Path to the resource storing the OAuth token required: - service_name @@ -39770,14 +40240,6 @@ components: - async - sync - RedirectUri: - type: object - properties: - redirect_uri: - type: string - required: - - redirect_uri - NativeTriggerData: type: object description: Data for creating or updating a native trigger @@ -39802,11 +40264,36 @@ components: Whether the trigger starts a job when it fires. Honoured on create only, so a trigger can be registered already paused; an update ignores it and setenabled is the only way to change an existing trigger's state. Defaults to true. + connection_path: + type: string + nullable: true + description: >- + Path of the connection the trigger acts through. Honoured on create only; an update + keeps the trigger's connection. When omitted on create, the caller's only usable + connection for the service is used. required: - script_path - is_flow - service_config + NativeTriggerConnection: + type: object + description: An account connected for native triggers, stored as an OAuth resource + properties: + path: + type: string + description: Path of the resource and variable holding the connection + owner: + type: string + nullable: true + description: Username of whoever connected the account, when the caller can read its resource + workspace: + type: boolean + description: Whether this is the workspace connection, which every member may use + required: + - path + - workspace + CreateTriggerResponse: type: object description: Response returned when a native trigger is created diff --git a/backend/windmill-api/src/agent_runs.rs b/backend/windmill-api/src/agent_runs.rs index bec7180f19..3bf65c9808 100644 --- a/backend/windmill-api/src/agent_runs.rs +++ b/backend/windmill-api/src/agent_runs.rs @@ -21,7 +21,7 @@ use windmill_common::{ jobs::JobPayload, users::username_to_permissioned_as, utils::{not_found_if_none, StripPath}, - variables::arg_needs_interpolation, + variables::untrusted_arg_interpolates, }; use windmill_queue::{push, PushArgs, PushIsolationLevel}; @@ -68,51 +68,9 @@ pub(crate) async fn run_agent_as( crate::jobs::check_license_key_valid().await?; // Read through the caller's own permissions: reading the agent is what allows running it. - let mut tx = user_db.clone().begin(authed).await?; - let value = sqlx::query_scalar!( - "SELECT value AS \"value: sqlx::types::Json\" - FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", - w_id, - path - ) - .fetch_optional(&mut *tx) - .await?; - tx.commit().await?; - let Some(sqlx::types::Json(mut value)) = not_found_if_none(value, "Agent", path)? else { - return Err(Error::BadRequest(format!( - "Agent {path} has no configuration" - ))); - }; - // Who the agent runs as and who can ask it in Slack, not inputs: its identity when it opts - // in, as a deployed flow does. - let obj = value.as_object_mut(); - let (agent_obo, run_obo) = obj - .map(|o| { - o.remove("slack_anyone"); - (o.remove("on_behalf_of"), o.remove("run_on_behalf_of")) - }) - .unwrap_or_default(); - let agent_obo = agent_obo - .filter(|_| run_obo.and_then(|v| v.as_bool()).unwrap_or(false)) - .and_then(|v| v.as_str().map(str::to_string)); - let config = config_to_draft(value)?; - - // A chat turn is filed where the agent's chat lists its conversations, which a flow cannot - // name (flow paths carry no `.`), so the two never share a conversation list. let chat = run_query.memory_id.is_some(); - let run_path = if chat { - format!("{path}.chat") - } else { - path.to_string() - }; - // A step memory id would replace the conversation's, and the agent would forget the turns - // before; history comes from the conversation alone. - let flow_value = agent_step_flow( - &config, - AGENT_NODE_ID, - chat, - &["memory_id", "previous_messages"], - )?; + let AgentTurn { flow_value, run_path, agent_obo } = + agent_turn(authed, user_db, w_id, path, chat).await?; let on_behalf_of = windmill_common::on_behalf_of_from_permissioned_as(agent_obo.as_deref(), w_id, db).await?; @@ -136,11 +94,8 @@ pub(crate) async fn run_agent_as( }; if let Some(obo) = on_behalf_of.as_ref() { // The worker would interpolate such an input with the job's token, which is the - // identity's. Checked on the decoded value: the raw JSON can spell `$` as `\u0024`. - if args.values().any(|v| { - serde_json::from_str::(v.get()) - .is_ok_and(|v| arg_needs_interpolation(&v.to_string())) - }) { + // identity's. + if args.values().any(|v| untrusted_arg_interpolates(v.get())) { return Err(Error::BadRequest(format!( "Agent {path} runs on behalf of {}, so its inputs cannot reference variables or resources", obo.permissioned_as @@ -213,11 +168,73 @@ pub(crate) async fn run_agent_as( Ok(uuid) } +/// A turn of a saved agent, as the flow that runs it. +pub(crate) struct AgentTurn { + pub flow_value: windmill_common::flows::FlowValue, + /// Where the turn is filed: a chat turn under `.chat`, which a flow cannot name (flow + /// paths carry no `.`), so the agent's conversations never share a list with a flow's. + pub run_path: String, + /// The identity the agent runs as when it opts in (`run_on_behalf_of`). A caller that runs it + /// as some other identity, such as an app's, ignores it. + pub agent_obo: Option, +} + +/// Reads the agent through `authed`'s own permissions and builds the flow of one of its turns. +/// Who it may see and which inputs or slack settings it carries are not inputs of the run. +pub(crate) async fn agent_turn( + authed: &ApiAuthed, + user_db: &UserDB, + w_id: &str, + path: &str, + chat: bool, +) -> Result { + let mut tx = user_db.clone().begin(authed).await?; + let value = sqlx::query_scalar!( + "SELECT value AS \"value: sqlx::types::Json\" + FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + w_id, + path + ) + .fetch_optional(&mut *tx) + .await?; + tx.commit().await?; + let Some(sqlx::types::Json(mut value)) = not_found_if_none(value, "Agent", path)? else { + return Err(Error::BadRequest(format!( + "Agent {path} has no configuration" + ))); + }; + let obj = value.as_object_mut(); + let (agent_obo, run_obo) = obj + .map(|o| { + o.remove("slack_anyone"); + (o.remove("on_behalf_of"), o.remove("run_on_behalf_of")) + }) + .unwrap_or_default(); + let agent_obo = agent_obo + .filter(|_| run_obo.and_then(|v| v.as_bool()).unwrap_or(false)) + .and_then(|v| v.as_str().map(str::to_string)); + let config = config_to_draft(value)?; + let run_path = if chat { + format!("{path}.chat") + } else { + path.to_string() + }; + // A step memory id would replace the conversation's, and the agent would forget the turns + // before; history comes from the conversation alone. + let flow_value = agent_step_flow( + &config, + AGENT_NODE_ID, + chat, + &["memory_id", "previous_messages"], + )?; + Ok(AgentTurn { flow_value, run_path, agent_obo }) +} + /// The step fetches the message's files with its job's token, so a run as the agent's identity /// would read any file that identity can: a caller attaches only what they could download /// themselves, checked as `sign_s3_objects` checks a key before signing it. #[cfg(all(feature = "parquet", feature = "private"))] -async fn check_attachments_readable( +pub(crate) async fn check_attachments_readable( db: &DB, authed: &ApiAuthed, w_id: &str, @@ -227,14 +244,9 @@ async fn check_attachments_readable( get_large_file_storage, get_workspace_s3_resource_and_check_paths, }; use windmill_common::db::DbWithOptAuthed; - use windmill_types::s3::{S3Object, S3Permission}; + use windmill_types::s3::S3Permission; - let Some(raw) = args.get("user_attachments") else { - return Ok(()); - }; - let attachments: Option> = serde_json::from_str(raw.get()) - .map_err(|e| Error::BadRequest(format!("invalid user_attachments: {e}")))?; - for attachment in attachments.iter().flatten().filter(|a| !a.s3.is_empty()) { + for attachment in run_attachments(args)? { // The path check is skipped, not failed, when the storage does not resolve. if get_large_file_storage(db, w_id, attachment.storage.clone()) .await? @@ -257,10 +269,39 @@ async fn check_attachments_readable( Ok(()) } +/// Every file the step fetches with its job's token: the message's attachments, and the +/// `s3_object` parts of the history a caller supplies, which the worker downloads alike. +pub(crate) fn run_attachments( + args: &HashMap>, +) -> Result> { + use windmill_ai::ai_types::{ContentPart, OpenAIContent, OpenAIMessage}; + + let mut files: Vec = match args.get("user_attachments") { + Some(raw) => serde_json::from_str::>>(raw.get()) + .map_err(|e| Error::BadRequest(format!("invalid user_attachments: {e}")))? + .unwrap_or_default(), + None => vec![], + }; + if let Some(raw) = args.get("previous_messages") { + let messages = serde_json::from_str::>>(raw.get()) + .map_err(|e| Error::BadRequest(format!("invalid previous_messages: {e}")))?; + for message in messages.into_iter().flatten() { + if let Some(OpenAIContent::Parts(parts)) = message.content { + files.extend(parts.into_iter().filter_map(|part| match part { + ContentPart::S3Object { s3_object } => Some(s3_object), + _ => None, + })); + } + } + } + files.retain(|f| !f.s3.is_empty()); + Ok(files) +} + /// The agent as a one-step flow, validated by deserializing through `FlowValue` rather than /// trusted as raw JSON. Its own transforms are the step's, minus `without`, and the run's inputs -/// supply the message and the attachments over the top. Always inlined, never a link to the -/// resource: a linked step would resolve the agent when it runs, not as it was read here. +/// supply the message, the attachments and any history over the top. Always inlined, never a link +/// to the resource: a linked step would resolve the agent when it runs, not as it was read here. pub(crate) fn agent_step_flow( config: &AgentDraft, id: &str, @@ -274,7 +315,7 @@ pub(crate) fn agent_step_flow( for key in without { input_transforms.remove(*key); } - for key in ["user_message", "user_attachments"] { + for key in ["user_message", "user_attachments", "previous_messages"] { input_transforms.insert( key.to_string(), serde_json::json!({ "type": "javascript", "expr": format!("flow_input.{}", key) }), @@ -295,3 +336,25 @@ pub(crate) fn agent_step_flow( } Ok(serde_json::from_value(flow)?) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn run_attachments_include_the_files_a_supplied_history_quotes() { + let args: HashMap> = serde_json::from_value(serde_json::json!({ + "user_attachments": [{ "s3": "u/a/attached.png" }], + "previous_messages": [ + { "role": "user", "content": [ + { "type": "text", "text": "look" }, + { "type": "s3_object", "s3_object": { "s3": "u/b/quoted.png" } } + ]}, + { "role": "assistant", "content": "ok" } + ] + })) + .unwrap(); + let keys: Vec<_> = run_attachments(&args).unwrap().into_iter().map(|f| f.s3).collect(); + assert_eq!(keys, ["u/a/attached.png", "u/b/quoted.png"]); + } +} diff --git a/backend/windmill-api/src/ai.rs b/backend/windmill-api/src/ai.rs index 8de5e16c11..213a41b4eb 100644 --- a/backend/windmill-api/src/ai.rs +++ b/backend/windmill-api/src/ai.rs @@ -24,7 +24,10 @@ use windmill_ai::ai_providers::{ empty_string_as_none, AIPlatform, AIProvider, ProviderConfig, ProviderModel, }; use windmill_ai::ai_types::{validate_token_limit, CONTEXT_WINDOWS, MAX_MODEL_RATE, OUTPUT_LIMITS}; -use windmill_ai::credentials::ProviderCredentials; +use windmill_ai::credentials::{AnthropicFederation, ProviderCredentials}; +use windmill_ai::providers::anthropic::{ + exchange_federated_token, FederatedAccessToken, ANTHROPIC_API_BASE_URL, +}; #[cfg(feature = "bedrock")] use windmill_ai::providers::bedrock::{ handle_bedrock_proxy, BedrockProxyResponse, BedrockProxyResponseBody, @@ -119,6 +122,10 @@ lazy_static::lazy_static! { pub static ref AI_REQUEST_CACHE: Cache<(String, AIProvider), ExpiringProviderCredentials> = Cache::new(500); + /// Anthropic access tokens from a federated exchange, keyed by (workspace, + /// 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); } #[cfg(feature = "bedrock")] @@ -132,6 +139,8 @@ lazy_static::lazy_static! { 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); // 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. @@ -247,10 +256,33 @@ struct OAuthTokens { access_token: String, } +/// An `anthropic_federated` resource: the Claude Console federation rule, +/// organization, service account and (for a rule enabled in several workspaces) +/// workspace to exchange the requesting user's OIDC token against. +/// +/// It has no base URL on purpose. The exchanged token is the identity of whoever +/// uses the resource, not of whoever wrote it, so a configurable host would let +/// the resource's author collect other users' tokens. +/// +/// Only `federation_rule_id` decides that a value is one: the other fields are +/// optional here and checked afterwards, so a resource missing one is reported +/// rather than read as a standard resource with no key. +#[derive(Deserialize, Debug)] +struct AIAnthropicFederatedResource { + federation_rule_id: String, + #[serde(default)] + organization_id: String, + #[serde(default)] + service_account_id: String, + #[serde(default, deserialize_with = "empty_string_as_none")] + workspace_id: Option, +} + #[derive(Deserialize, Debug)] #[serde(untagged)] enum AIResource { OAuth(AIOAuthResource), + AnthropicFederated(AIAnthropicFederatedResource), Standard(AIStandardResource), } @@ -345,10 +377,50 @@ async fn resolve_provider_credentials( aws_secret_access_key, aws_session_token, oidc_role_arn, + anthropic_federation: None, platform: resource.platform, custom_headers: resource.headers, }) } + AIResource::AnthropicFederated(resource) => { + if *provider != AIProvider::Anthropic { + return Err(Error::BadRequest(format!( + "An anthropic_federated resource can only be used for the Anthropic provider, not {provider:?}" + ))); + } + let required = [ + ("federation_rule_id", &resource.federation_rule_id), + ("organization_id", &resource.organization_id), + ("service_account_id", &resource.service_account_id), + ]; + if let Some((field, _)) = required.iter().find(|(_, value)| value.is_empty()) { + return Err(Error::BadRequest(format!( + "The anthropic_federated resource needs {field} to be set" + ))); + } + + Ok(ProviderCredentials { + provider: provider.clone(), + base_url: ANTHROPIC_API_BASE_URL.to_string(), + api_key: None, + access_token: None, + organization_id: None, + user: None, + region: None, + aws_access_key_id: None, + aws_secret_access_key: None, + aws_session_token: None, + oidc_role_arn: None, + anthropic_federation: Some(AnthropicFederation { + federation_rule_id: resource.federation_rule_id, + organization_id: resource.organization_id, + service_account_id: resource.service_account_id, + workspace_id: resource.workspace_id, + }), + platform: AIPlatform::Standard, + custom_headers: HashMap::new(), + }) + } AIResource::OAuth(resource) => { let user = if let Some(user) = resource.user.clone() { Some(resolve_var(user, db, w_id, user_db.as_ref(), authed).await?) @@ -370,6 +442,7 @@ async fn resolve_provider_credentials( aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), }) @@ -522,6 +595,73 @@ async fn assume_bedrock_role( } } +/// Exchange an OIDC token minted for the requesting user for an Anthropic access +/// token, in place, when the resource is set up for Workload Identity Federation. +/// +/// Runs after the workspace credential cache for the same reason the Bedrock +/// exchange does: the token's `sub` names the user, and is what a federation rule +/// matches and the Claude Console's authentication history records. +async fn resolve_anthropic_federated_credentials( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + credentials: &mut ProviderCredentials, +) -> Result<()> { + let Some(federation) = credentials.anthropic_federation.as_ref() else { + return Ok(()); + }; + + let cache_key = (w_id.to_string(), federation.clone(), authed.email.clone()); + let token = match ANTHROPIC_FEDERATED_TOKEN_CACHE + .get(&cache_key) + .filter(FederatedAccessToken::is_fresh) + { + Some(cached) => cached, + None => { + let assertion = mint_anthropic_oidc_token(db, w_id, authed).await?; + let client = pinned_ai_client_for(&credentials.base_url).await?; + let token = + exchange_federated_token(&client, &credentials.base_url, federation, &assertion) + .await?; + ANTHROPIC_FEDERATED_TOKEN_CACHE.insert(cache_key, token.clone()); + token + } + }; + + credentials.access_token = Some(token.access_token); + Ok(()) +} + +async fn mint_anthropic_oidc_token(db: &DB, w_id: &str, authed: &ApiAuthed) -> Result { + #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] + { + use windmill_ai::providers::anthropic::{ + ANTHROPIC_OIDC_AUDIENCE, ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS, + }; + use windmill_common::oidc_oss::{generate_id_token, OidcCaller, WorkspaceClaim}; + + let id_token = generate_id_token( + OidcCaller::Anthropic, + Some(db), + WorkspaceClaim { workspace: w_id.to_string() }, + ANTHROPIC_OIDC_AUDIENCE, + format!("{}::{}", authed.email, w_id), + Some(authed.email.clone()), + Some(ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS), + ) + .await?; + Ok(id_token.to_string()) + } + #[cfg(not(all(feature = "enterprise", feature = "openidconnect", feature = "private")))] + { + let _ = (db, w_id, authed); + Err(Error::BadRequest( + "Anthropic Workload Identity Federation through Windmill's OIDC provider requires an enterprise license" + .to_string(), + )) + } +} + #[derive(Clone, Debug)] pub struct ExpiringProviderCredentials { credentials: ProviderCredentials, @@ -1129,6 +1269,7 @@ async fn global_proxy( aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), }; @@ -1435,6 +1576,7 @@ 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?; // Free tier: pin the model and clamp max_tokens server-side before forwarding, // since the request body is otherwise client-controlled. @@ -1643,11 +1785,41 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), } } + #[test] + fn only_a_federation_rule_makes_a_resource_anthropic_federated() { + let federated = serde_json::json!({ + "federation_rule_id": "fdrl_x", + "organization_id": "00000000-0000-0000-0000-000000000000", + "service_account_id": "svac_x", + "workspace_id": "" + }); + assert!(matches!( + serde_json::from_value::(federated), + Ok(AIResource::AnthropicFederated( + AIAnthropicFederatedResource { workspace_id: None, .. } + )) + )); + + let incomplete = serde_json::json!({"federation_rule_id": "fdrl_x"}); + assert!(matches!( + serde_json::from_value::(incomplete), + Ok(AIResource::AnthropicFederated(_)) + )); + + // `organization_id` is also the OpenAI organization of a standard resource. + let standard = serde_json::json!({"api_key": "k", "organization_id": "org-x"}); + assert!(matches!( + serde_json::from_value::(standard), + Ok(AIResource::Standard(_)) + )); + } + #[test] fn ai_standard_resource_ignores_legacy_enable_1m_context_keys() { // Resources created before the field was removed still carry the legacy key diff --git a/backend/windmill-api/src/ai_evals/datasets.rs b/backend/windmill-api/src/ai_evals/datasets.rs index 8e1acb3d2a..107a316676 100644 --- a/backend/windmill-api/src/ai_evals/datasets.rs +++ b/backend/windmill-api/src/ai_evals/datasets.rs @@ -123,17 +123,15 @@ pub async fn list_datasets( pub async fn create_dataset( authed: ApiAuthed, + Extension(db): Extension, Extension(user_db): Extension, Path(w_id): Path, Json(payload): Json, ) -> Result { check_proper_path(&payload.path)?; check_summary(payload.summary.as_deref())?; - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot create eval datasets".to_string(), - )); - } + windmill_common::workspaces::check_role_can_code(&db, &w_id, &authed, "create eval datasets") + .await?; check_case_set( payload .cases @@ -207,15 +205,13 @@ pub async fn get_dataset( /// or not at all. pub async fn update_dataset( authed: ApiAuthed, + Extension(db): Extension, Extension(user_db): Extension, Path((w_id, path)): Path<(String, String)>, Json(payload): Json, ) -> Result { - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot modify eval datasets".to_string(), - )); - } + windmill_common::workspaces::check_role_can_code(&db, &w_id, &authed, "modify eval datasets") + .await?; check_summary(payload.summary.as_deref())?; let new_path = match payload.path.filter(|p| *p != path) { Some(new_path) => { @@ -301,15 +297,13 @@ pub async fn update_dataset( /// own retention. pub async fn delete_dataset( authed: ApiAuthed, + Extension(db): Extension, Extension(user_db): Extension, Path((w_id, path)): Path<(String, String)>, ) -> Result { check_proper_path(&path)?; - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot delete eval datasets".to_string(), - )); - } + windmill_common::workspaces::check_role_can_code(&db, &w_id, &authed, "delete eval datasets") + .await?; let mut tx = user_db.clone().begin(&authed).await?; let deleted = sqlx::query_scalar!( "DELETE FROM eval_dataset WHERE workspace_id = $1 AND path = $2 RETURNING path", diff --git a/backend/windmill-api/src/ai_evals/mod.rs b/backend/windmill-api/src/ai_evals/mod.rs index b4d6009857..867f638aa7 100644 --- a/backend/windmill-api/src/ai_evals/mod.rs +++ b/backend/windmill-api/src/ai_evals/mod.rs @@ -267,16 +267,14 @@ pub(crate) async fn read_dataset_and_cases( /// being mirrored here. async fn require_dataset_writable( authed: &ApiAuthed, + db: &DB, user_db: &UserDB, w_id: &str, path: &str, ) -> Result<()> { check_proper_path(path)?; - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot modify eval datasets".to_string(), - )); - } + windmill_common::workspaces::check_role_can_code(db, w_id, authed, "modify eval datasets") + .await?; let mut tx = user_db.clone().begin(authed).await?; let writable = sqlx::query_scalar!( "SELECT path FROM eval_dataset WHERE workspace_id = $1 AND path = $2 FOR UPDATE", diff --git a/backend/windmill-api/src/ai_evals/run.rs b/backend/windmill-api/src/ai_evals/run.rs index 57e75b3f9f..6b219e5597 100644 --- a/backend/windmill-api/src/ai_evals/run.rs +++ b/backend/windmill-api/src/ai_evals/run.rs @@ -255,6 +255,8 @@ fn agent_module(config: &AgentDraft) -> Result { .entry("input_transforms") .or_insert_with(|| serde_json::json!({})); if let Some(transforms) = transforms.as_object_mut() { + // A case carries no history: each one is asked fresh. + transforms.remove("previous_messages"); for key in ["user_message", "user_attachments"] { transforms.insert( key.to_string(), @@ -561,7 +563,7 @@ pub async fn run_experiment( ) -> Result { check_scopes(&authed, || "jobs:run".to_string())?; // A write, not a read: it persists an experiment into the dataset. - require_dataset_writable(&authed, &user_db, &w_id, &payload.dataset).await?; + require_dataset_writable(&authed, &db, &user_db, &w_id, &payload.dataset).await?; let mut subject = payload.subject; let draft = validate_subject(&subject)?; diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 944535dd84..cdc66496c0 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -55,18 +55,19 @@ use sqlx::{types::Uuid, FromRow}; use std::str; use windmill_audit::audit_oss::{audit_log, AuditAuthorable}; use windmill_audit::ActionKind; +use windmill_common::roles::{caller_capabilities, AuthorLevel}; use windmill_common::{ apps::{ - app_value_has_inline_script, app_value_runnable_paths, AppScriptId, ListAppQuery, - APP_WORKSPACED_ROUTE, + app_value_has_inline_script, app_value_runnable_paths, AppRunnableKind, AppScriptId, + ListAppQuery, APP_WORKSPACED_ROUTE, }, auth::{APP_EMBED_TOKEN_LABEL_PREFIX, RAW_APP_SDK_TOKEN_LABEL_PREFIX, TOKEN_PREFIX_LEN}, cache, db::{DbWithOptAuthed, UserDB}, error::{to_anyhow, Error, JsonResult, Result}, jobs::{ - get_payload_tag_from_prefixed_path, resolve_delete_after_secs, schedule_job_deletion, - JobPayload, JobTriggerKind, RawCode, + get_payload_tag_from_prefixed_path, normalize_nul_in_args, resolve_delete_after_secs, + sanitize_untrusted_args, schedule_job_deletion, JobPayload, JobTriggerKind, RawCode, }, scripts::ScriptLang, triggers::TriggerMetadata, @@ -76,7 +77,7 @@ use windmill_common::{ check_proper_path, http_get_from_hub, not_found_if_none, paginate, paginate_optional, query_elems_from_hub, require_admin, strip_json_nul, Pagination, RunnableKind, StripPath, }, - variables::{build_crypt, build_crypt_with_key_suffix, encrypt}, + variables::{build_crypt, build_crypt_with_key_suffix, encrypt, omit_untrusted_interpolation}, worker::{to_raw_value, CLOUD_HOSTED}, workspaces::{ check_deploy_rules, check_operator_can_build, check_user_against_rule, @@ -601,6 +602,11 @@ pub struct EditApp { pub summary: Option, pub value: Option>>, pub policy: Option, + /// Changes only who may open the app: applied to the deployed policy under the row lock a + /// deploy takes, so it neither reverts a concurrent deploy's policy nor is reverted by it. + /// Exclusive with `policy`, which states its own mode. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub execution_mode: Option, pub deployment_message: Option, pub custom_path: Option, pub preserve_on_behalf_of: Option, @@ -734,10 +740,10 @@ async fn list_apps( if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(app.labels @> ARRAY[?] OR folder_labels(app.workspace_id, app.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } @@ -760,7 +766,7 @@ async fn list_apps( // Append the authed user's `app`/`raw_app` drafts at paths with no deployed app; // see scripts.rs. if lq.include_draft_only.unwrap_or(false) - && (!authed.is_operator || operator_builder_rights(&db, &w_id).await?.apps) + && operator_builder_rights(&db, &w_id, &authed).await?.apps && offset == 0 && lq.path_start.is_none() && lq.path_exact.is_none() @@ -1755,6 +1761,17 @@ pub struct PreviewSdkTokenRequest { /// conveys nothing `users/tokens/create` wouldn't. Scopes come from the request /// so the preview matches an app whose scopes aren't deployed yet, as /// `execute_component` already does for editor previews. +/// Gate for an app write only full app authoring allows: low-code apps, whose inline scripts are +/// code, and anything built on a worker. +async fn require_full_apps(db: &DB, w_id: &str, authed: &ApiAuthed, action: &str) -> Result<()> { + if caller_capabilities(db, w_id, authed).await?.apps != AuthorLevel::Full { + return Err(Error::PermissionDenied(format!( + "Your role cannot {action} in this workspace" + ))); + } + Ok(()) +} + async fn mint_preview_sdk_token( authed: ApiAuthed, OptJobAuthed { job_id, .. }: OptJobAuthed, @@ -1762,14 +1779,7 @@ async fn mint_preview_sdk_token( Path(w_id): Path, Json(req): Json, ) -> Result { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Apps, - "preview raw apps", - ) - .await?; + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Apps, "preview raw apps").await?; check_scopes(&authed, || format!("apps:write:{}", req.path))?; let (token, _expiration) = mint_raw_app_sdk_token(&db, &w_id, &req.path, &authed, &req.scopes, job_id).await?; @@ -2302,14 +2312,14 @@ pub(crate) enum BuilderAppWrite { } /// The half of the builder-app check that needs no DB (see `docs/operator-builder-rights.md`). -/// Returns every runnable the app can invoke, as `(is_flow, path)`, from both the policy's +/// Returns every runnable the app can invoke, as `(kind, path)`, from both the policy's /// triggerables and the value's path runnables: they are not the same list. fn check_operator_composed_app( write: BuilderAppWrite, raw_app: bool, value: Option<&RawValue>, policy: Option<&mut Policy>, -) -> Result> { +) -> Result> { let verb = if write == BuilderAppWrite::Deploy { "deploy" } else { @@ -2320,7 +2330,7 @@ fn check_operator_composed_app( "Operators with builder rights can only author full-code apps".to_string(), )); } - let mut referenced: Vec<(bool, String)> = Vec::new(); + let mut referenced: Vec<(AppRunnableKind, String)> = Vec::new(); if let Some(value) = value { // The text stored, NULs stripped: a stripped NUL can rename a key into one this reads. let value: serde_json::Value = @@ -2361,18 +2371,12 @@ fn check_operator_composed_app( // Viewer mode would make the triggerables collected above non-exhaustive (see the docs), and // the deploy panel shows it as members-only, so an admin deploying a draft would not see it. - // Pin an omitted mode on deploy: `update_app_internal` resolves it to the deployed app's, so a - // redeploy over an admin's viewer-mode app would otherwise inherit `Viewer`. - match policy.stated_execution_mode() { - Some(ExecutionMode::Viewer) => { - return Err(Error::PermissionDenied(format!( - "Operators with builder rights cannot {verb} an app that runs as its viewer" - ))) - } - None if write == BuilderAppWrite::Deploy => { - policy.set_execution_mode(ExecutionMode::Publisher) - } - _ => {} + // An omitted mode is resolved by the deploy: create's default, or on update the deployed mode, + // which `update_app_internal` turns into `Publisher` for a builder when it is `Viewer`. + if policy.stated_execution_mode() == Some(ExecutionMode::Viewer) { + return Err(Error::PermissionDenied(format!( + "Operators with builder rights cannot {verb} an app that runs as its viewer" + ))); } referenced.sort(); @@ -2381,9 +2385,9 @@ fn check_operator_composed_app( Ok(referenced) } -/// The runnables a builder app's policy authorizes, as `(is_flow, path)`; refuses a policy that +/// The runnables a builder app's policy authorizes, as `(kind, path)`; refuses a policy that /// pins inline code. -fn checked_policy_runnable_paths(policy: &Policy) -> Result> { +fn checked_policy_runnable_paths(policy: &Policy) -> Result> { // A `rawscript/` triggerable is the deployed app's authorization to run caller-supplied // `raw_code` hashing to it: pinning one hands a builder arbitrary code execution through an // app whose value passed the inline-script check. A composition-only app has none. @@ -2420,21 +2424,24 @@ fn checked_policy_runnable_paths(policy: &Policy) -> Result> std::iter::once(key.as_str()) .chain(key.match_indices(':').map(|(i, _)| &key[i + 1..])) .filter_map(|candidate| { - candidate - .strip_prefix("script/") - .map(|p| (false, p.to_string())) - .or_else(|| { - candidate - .strip_prefix("flow/") - .map(|p| (true, p.to_string())) - }) + [ + ("script/", AppRunnableKind::Script), + ("flow/", AppRunnableKind::Flow), + ("agent/", AppRunnableKind::Agent), + ] + .into_iter() + .find_map(|(prefix, kind)| { + candidate + .strip_prefix(prefix) + .map(|p| (kind, p.to_string())) + }) }) .collect::>() }) .collect()) } -fn refuse_hub_runnables(referenced: &[(bool, String)]) -> Result<()> { +fn refuse_hub_runnables(referenced: &[(AppRunnableKind, String)]) -> Result<()> { for (_, path) in referenced { if path.starts_with("hub/") { return Err(Error::PermissionDenied(format!( @@ -2465,15 +2472,7 @@ pub(crate) async fn validate_operator_composed_app( // docs/operator-builder-rights.md); a draft keeps whatever it names, which an admin's // one-click draft deploy preserves without showing it. if let (BuilderAppWrite::Draft, Some(policy)) = (write, policy.as_deref()) { - let names_another = policy - .on_behalf_of - .as_deref() - .is_some_and(|p| p != username_to_permissioned_as(&authed.username)) - || policy - .on_behalf_of_email - .as_deref() - .is_some_and(|e| e != authed.email); - if names_another { + if policy_runs_as_another(policy, authed) { return Err(Error::PermissionDenied( "Operators with builder rights cannot save an app that runs as someone else" .to_string(), @@ -2484,12 +2483,23 @@ pub(crate) async fn validate_operator_composed_app( require_runnables_readable(authed, db, user_db, w_id, referenced).await } +fn policy_runs_as_another(policy: &Policy, authed: &ApiAuthed) -> bool { + policy + .on_behalf_of + .as_deref() + .is_some_and(|p| p != username_to_permissioned_as(&authed.username)) + || policy + .on_behalf_of_email + .as_deref() + .is_some_and(|e| e != authed.email) +} + async fn require_runnables_readable( authed: &ApiAuthed, db: &DB, user_db: &UserDB, w_id: &str, - referenced: Vec<(bool, String)>, + referenced: Vec<(AppRunnableKind, String)>, ) -> Result<()> { if referenced.is_empty() { return Ok(()); @@ -2499,26 +2509,33 @@ async fn require_runnables_readable( // whichever version the caller happens to see. Resolved before the transaction opens so no // request holds two pool connections at once. let mut hashes = Vec::with_capacity(referenced.len()); - for (is_flow, path) in &referenced { - hashes.push(if *is_flow { - None - } else { + for (kind, path) in &referenced { + hashes.push(if *kind == AppRunnableKind::Script { windmill_common::get_latest_script_hash(db, path, w_id).await? + } else { + None }); } let mut tx = user_db.clone().begin(authed).await?; - for ((is_flow, path), hash) in referenced.into_iter().zip(hashes) { - let readable = if is_flow { - sqlx::query_scalar!( + for ((kind, path), hash) in referenced.into_iter().zip(hashes) { + let readable = match kind { + AppRunnableKind::Flow => sqlx::query_scalar!( "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2)", w_id, path, ) .fetch_one(&mut *tx) .await? - .unwrap_or(false) - } else { - match hash { + .unwrap_or(false), + AppRunnableKind::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(&mut *tx) + .await? + .unwrap_or(false), + AppRunnableKind::Script => match hash { Some(hash) => sqlx::query_scalar!( "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND hash = $2)", w_id, @@ -2528,17 +2545,21 @@ async fn require_runnables_readable( .await? .unwrap_or(false), None => false, - } + }, }; // One message for every cause: telling "no runnable version" apart from "not readable" // would reveal that a path the caller cannot read exists. if !readable { - return Err(Error::PermissionDenied(if is_flow { - format!("Flow {path} does not exist or is not readable by you") - } else { - format!( + return Err(Error::PermissionDenied(match kind { + AppRunnableKind::Flow => { + format!("Flow {path} does not exist or is not readable by you") + } + AppRunnableKind::Agent => { + format!("Agent {path} does not exist or is not readable by you") + } + AppRunnableKind::Script => format!( "Script {path} does not exist, is not readable by you, or has not finished deploying" - ) + ), })); } } @@ -2622,14 +2643,7 @@ async fn create_app_raw<'a>( Path(w_id): Path, multipart: Multipart, ) -> Result<(StatusCode, String)> { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Apps, - "create apps", - ) - .await?; + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Apps, "create apps").await?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, @@ -2693,11 +2707,7 @@ async fn create_app( Path(w_id): Path, Json(app): Json, ) -> Result<(StatusCode, String)> { - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot create apps for security reasons".to_string(), - )); - } + require_full_apps(&db, &w_id, &authed, "create low-code apps").await?; let path = app.path.clone(); if let RuleCheckResult::Blocked(msg) = check_deploy_rules( @@ -2806,7 +2816,7 @@ async fn create_app_internal<'a>( if raw_app { validate_raw_app_path_keys(&app.value.0)?; } - if authed.is_operator { + if caller_capabilities(&db, w_id, &authed).await?.apps == AuthorLevel::Compose { validate_operator_composed_app( &authed, &db, @@ -3125,21 +3135,16 @@ async fn delete_app( Extension(webhook): Extension, Path((w_id, path)): Path<(String, StripPath)>, ) -> Result { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Apps, - "delete apps", - ) - .await?; + let apps_level = + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Apps, "delete apps").await?; let path = path.to_path(); check_scopes(&authed, || format!("apps:write:{}", path))?; // One endpoint deletes both kinds, and builder rights only cover full-code apps. - if authed.is_operator && deployed_app_kind(&user_db, &authed, &w_id, path).await? != Some(true) + if apps_level == AuthorLevel::Compose + && deployed_app_kind(&user_db, &authed, &w_id, path).await? != Some(true) { return Err(Error::PermissionDenied( - "Operators with builder rights can only delete full-code apps".to_string(), + "Your role can only delete full-code apps".to_string(), )); } @@ -3332,14 +3337,14 @@ async fn update_app( let path = path.to_path(); // The deploy panel saves a deployed full-code app's access and frontend scopes here. A // builder may change those settings; the app itself only through `update_app_raw`. - if authed.is_operator { - check_operator_can_build(&db, &w_id, true, BuilderKind::Apps, "update apps").await?; + let apps_level = + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Apps, "update apps").await?; + if apps_level == AuthorLevel::Compose { if ns.value.is_some() || deployed_app_kind(&user_db, &authed, &w_id, path).await? != Some(true) { return Err(Error::PermissionDenied( - "Operators with builder rights can only change the settings of full-code apps" - .to_string(), + "Your role can only change the settings of full-code apps".to_string(), )); } } @@ -3360,7 +3365,7 @@ async fn update_app( let opath = path.to_string(); let db2 = db.clone(); // Settings-only for an operator, of an app checked above to be full-code. - let raw_app = authed.is_operator; + let raw_app = apps_level == AuthorLevel::Compose; let (new_tx, npath, v_id) = update_app_internal(authed, db, user_db, &w_id, path, raw_app, ns, None).await?; new_tx.commit().await?; @@ -3395,11 +3400,7 @@ async fn update_app_raw_source( // next to it: this path compiles caller-supplied sources with a bundler job on a worker, which // is arbitrary code execution. Builders lose nothing: the browser and the CLI both bundle // locally and deploy through the multipart endpoints. - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot update apps for security reasons".to_string(), - )); - } + require_full_apps(&db, &w_id, &authed, "build apps on a worker").await?; let path = path.to_path(); check_scopes(&authed, || format!("apps:write:{}", path))?; @@ -3556,11 +3557,7 @@ async fn create_app_raw_source( Json(mut app): Json, ) -> Result<(StatusCode, String)> { // Closed to builders too, for the reason on `update_app_raw_source`. - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot create apps for security reasons".to_string(), - )); - } + require_full_apps(&db, &w_id, &authed, "build apps on a worker").await?; let path = app.path.clone(); check_scopes(&authed, || format!("apps:write:{}", path))?; @@ -3721,14 +3718,8 @@ async fn update_app_raw<'a>( Path((w_id, path)): Path<(String, StripPath)>, multipart: Multipart, ) -> JsonResult { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Apps, - "update apps", - ) - .await?; + let apps_level = + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Apps, "update apps").await?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, @@ -3746,10 +3737,11 @@ async fn update_app_raw<'a>( check_scopes(&authed, || format!("apps:write:{}", path))?; // `update_app_internal` only compares kinds when a new value is deployed, so a // policy-only update would otherwise let a builder rewrite a low-code app's policy. - if authed.is_operator && deployed_app_kind(&user_db, &authed, &w_id, path).await? != Some(true) + if apps_level == AuthorLevel::Compose + && deployed_app_kind(&user_db, &authed, &w_id, path).await? != Some(true) { return Err(Error::PermissionDenied( - "Operators with builder rights can only update full-code apps".to_string(), + "Your role can only update full-code apps".to_string(), )); } let opath = path.to_string(); @@ -3819,10 +3811,22 @@ async fn update_app_internal<'a>( } } - if authed.is_operator { + if ns.policy.is_some() && ns.execution_mode.is_some() { + return Err(Error::BadRequest( + "Send execution_mode either inside the policy or alone, not both".to_string(), + )); + } + // The policy a mode-only change writes is only known under the row lock, so a builder's + // check on it runs there. + let mode_only = ns.policy.is_none() && ns.value.is_none() && ns.execution_mode.is_some(); + + let composes_only = caller_capabilities(&db, w_id, &authed).await?.apps == AuthorLevel::Compose; + if composes_only { // Restoring a full-code version always sends allow_kind_change. A builder converts // nothing, so drop it and let the locked kind check below refuse an actual conversion. ns.allow_kind_change = None; + } + if composes_only && !mode_only { validate_operator_composed_app( &authed, &db, @@ -3900,6 +3904,7 @@ async fn update_app_internal<'a>( || ns.summary.is_some() || ns.custom_path.is_some() || ns.labels.is_some() + || ns.execution_mode.is_some() // A source deploy may send nothing but the value, and its runnables are // what the derived grants describe: skipping the UPDATE here would keep // the grants keyed to the sources this deploy just replaced. @@ -3917,7 +3922,12 @@ async fn update_app_internal<'a>( // that carries no policy keeps the deployed mode, read under the row // lock so a policy update landing alongside cannot slip a guest app // onto a path it cannot be scoped to. - let mode = match ns.policy.as_ref().and_then(|p| p.stated_execution_mode()) { + let stated = ns + .policy + .as_ref() + .and_then(|p| p.stated_execution_mode()) + .or(ns.execution_mode); + let mode = match stated { Some(mode) => mode, None => sqlx::query_scalar::<_, Option>( "SELECT policy->>'execution_mode' FROM app @@ -3997,12 +4007,13 @@ async fn update_app_internal<'a>( // no policy at all, in which case the rest of the deployed one carries // over. Either way a policy is about to be written wholesale. let caller_sent_policy = ns.policy.is_some(); - if caller_sent_policy || derived_triggerables.is_some() { + if caller_sent_policy || derived_triggerables.is_some() || ns.execution_mode.is_some() { // One locked read serving everything below: the mode an omitted one // inherits, the already-anonymous check, and the policy a source - // deploy carries over. FOR UPDATE holds the row until this - // transaction's UPDATE commits, so a policy edit landing between the - // read and the write cannot be clobbered by this stale snapshot. + // deploy or a mode-only change carries over. FOR UPDATE holds the row + // until this transaction's UPDATE commits, so a policy edit landing + // between the read and the write cannot be clobbered by this stale + // snapshot. let deployed = sqlx::query_scalar!( "SELECT policy FROM app WHERE path = $1 AND workspace_id = $2 FOR UPDATE", path, @@ -4016,30 +4027,81 @@ async fn update_app_internal<'a>( let mut npolicy = match ns.policy.take() { Some(npolicy) => npolicy, + None if deployed.is_none() => { + return Err(Error::NotFound(format!("App {path} not found"))) + } // Carrying the deployed policy forward is only safe if all of it // survived the round trip; a partial one would silently drop // `on_behalf_of`, sandboxing or S3 rules. None => deployed_policy.clone().ok_or_else(|| { - Error::internal_err(format!( - "app {path} has no readable policy to deploy its new sources under" - )) + Error::internal_err(format!("app {path} has no readable policy to update")) })?, }; if let Some(triggerables) = derived_triggerables { npolicy.triggerables = None; npolicy.triggerables_v2 = Some(triggerables); } + if let Some(mode) = ns.execution_mode { + // A policy write from someone who cannot keep the run-as user rebinds it + // to them, so the mode alone must not let them open an app running as + // someone else to a new audience. A builder who may keep it is refused too: + // its deploy checks the triggerables against its own RLS, which needs a + // second pool connection and so cannot run under this lock. + if policy_runs_as_another(&npolicy, &authed) + && (composes_only || !windmill_common::can_preserve_on_behalf_of(&authed)) + { + let runs_as = npolicy + .on_behalf_of_email + .as_deref() + .or(npolicy.on_behalf_of.as_deref()) + .unwrap_or("another user"); + return Err(Error::PermissionDenied(if composes_only { + format!( + "app {path} runs as {runs_as}: change who can open it by deploying it" + ) + } else { + format!( + "app {path} runs as {runs_as}: only admins and members of \ + wm_deployers can change who can open it without deploying it, and a \ + deploy from you makes it run as you" + ) + })); + } + npolicy.set_execution_mode(mode); + if composes_only { + // The check below sandboxes an app whose policy leaves `sandbox` unset; a + // mode-only change keeps every other field, so that is left to a deploy. + if npolicy.sandbox != Some(true) { + return Err(Error::PermissionDenied(format!( + "app {path} is not sandboxed: change who can open it by deploying it" + ))); + } + check_operator_composed_app( + BuilderAppWrite::Deploy, + raw_app, + None, + Some(&mut npolicy), + )?; + } + } validate_frontend_sdk_scopes(&npolicy)?; // The policy is written wholesale, so one that states no mode would // otherwise re-permission the app to the create-time default: a // `viewer` app would start running on the publisher's identity. Keep - // the deployed mode instead, and make the stored policy state it. + // the deployed mode instead, and make the stored policy state it. A + // builder may not deploy `Viewer` (see `check_operator_composed_app`), + // so a builder's redeploy over a viewer-mode app makes it `Publisher`. if npolicy.stated_execution_mode().is_none() { + let deployed_mode = deployed_policy + .as_ref() + .map(|d| d.execution_mode()) + .unwrap_or_default(); npolicy.set_execution_mode( - deployed_policy - .as_ref() - .map(|d| d.execution_mode()) - .unwrap_or_default(), + if composes_only && deployed_mode == ExecutionMode::Viewer { + ExecutionMode::Publisher + } else { + deployed_mode + }, ); } refuse_unscopable_guest_app( @@ -4165,7 +4227,8 @@ async fn update_app_internal<'a>( // 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. - if !ns.skip_draft_deletion.unwrap_or(false) { + // A mode-only change publishes nothing from the draft, so it keeps it. + if !ns.skip_draft_deletion.unwrap_or(false) && !mode_only { sqlx::query!( "DELETE FROM draft WHERE path = $1 AND workspace_id = $2 AND typ IN ('app', 'raw_app') \ AND (email = $3 OR email IS NULL)", @@ -4553,23 +4616,24 @@ async fn execute_component( let previews_hub = payload.path.as_deref().is_some_and(|p| { p.strip_prefix("script/") .or_else(|| p.strip_prefix("flow/")) + .or_else(|| p.strip_prefix("agent/")) .unwrap_or(p) .starts_with("hub/") }); - if authed.is_operator { - let msg = "Operators cannot run preview jobs for security reasons".to_string(); - if !operator_builder_rights(&db, &w_id).await?.apps { - return Err(Error::NotAuthorized(msg)); - } - if payload.raw_code.is_some() || previews_hub { - return Err(Error::PermissionDenied(msg)); - } + let caps = caller_capabilities(&db, &w_id, authed).await?; + if !caps.code + && (caps.apps == AuthorLevel::None || payload.raw_code.is_some() || previews_hub) + { + return Err(Error::PermissionDenied( + "Your role cannot run preview jobs in this workspace".to_string(), + )); } check_scopes(authed, || format!("jobs:run"))?; if let Some(p) = payload.path.as_deref() { let runnable_path = p .strip_prefix("script/") .or_else(|| p.strip_prefix("flow/")) + .or_else(|| p.strip_prefix("agent/")) .unwrap_or(p); require_path_read_access_for_preview(authed, &Some(runnable_path.to_string()))?; } @@ -4899,11 +4963,45 @@ async fn execute_component( let resolved_delete_secs = resolve_delete_after_secs(None, policy_triggerables.delete_after_secs); - // `_TEMP_SCRIPT_REFS` is a server-injected control key (into `extra`) that the - // worker reads back for a `Preview` job, which an inline run is. A caller - // supplying it in `args` would redirect relative-import resolution, unpinned, as - // the app identity. Drop it; the legitimate value rides in `extra`. - payload.args.remove("_TEMP_SCRIPT_REFS"); + // The caller here is a viewer of the app, down to an anonymous visitor of a public one, + // and the job runs as the app's identity on code the policy pins. So the viewer fills in + // the runnable's inputs and nothing else: not the function called instead of `main` + // (which would reach helpers the app never exposes, as the publisher), not the module + // files written into the job directory, and not `_TEMP_SCRIPT_REFS`, which would + // redirect relative-import resolution, unpinned, as the app identity. The legitimate + // `_TEMP_SCRIPT_REFS` is server-injected into `extra` further below, which this leaves + // alone — as it does the policy's own `static_inputs`, which the publisher writes. + sanitize_untrusted_args(&mut payload.args); + + // An agent runnable takes the message and its files, plus optionally the conversation they + // belong to, which names the agent's memory rather than an input of its run. Without it the + // run is a single one, as on the direct agent endpoint. + let agent_path = payload + .path + .as_deref() + .and_then(|p| p.strip_prefix("agent/")) + .map(str::to_string); + let agent_memory_id = if agent_path.is_some() { + let memory_id = payload + .args + .remove("memory_id") + .map(|v| { + serde_json::from_str::>(v.get()) + .map_err(|_| Error::BadRequest("memory_id must be a string".to_string())) + }) + .transpose()? + .flatten() + .filter(|m| !m.trim().is_empty()); + payload.args.retain(|k, _| { + matches!( + k.as_str(), + "user_message" | "user_attachments" | "previous_messages" + ) + }); + memory_id + } else { + None + }; let (mut args, job_id) = build_args( policy, @@ -4943,9 +5041,64 @@ async fn execute_component( } .filter(|t| !t.is_empty()) }; + if agent_path.is_some() { + #[cfg(feature = "enterprise")] + crate::jobs::check_license_key_valid().await?; + let has_attachments = !crate::agent_runs::run_attachments(&args.args)?.is_empty(); + match opt_authed.as_ref() { + // The agent reads the files with the app's token: a viewer attaches only what they + // could download themselves. + Some(_viewer) if has_attachments => { + #[cfg(all(feature = "parquet", feature = "private"))] + crate::agent_runs::check_attachments_readable(&db, _viewer, &w_id, &args.args) + .await?; + } + None if has_attachments => { + return Err(Error::BadRequest( + "an anonymous viewer cannot send files to an agent".to_string(), + )); + } + _ => {} + } + } + // Filed under the viewer, who must therefore be kept past the push below. + let agent_viewer = agent_path.as_ref().and(opt_authed.clone()); + let mut agent_run_path = None; + let component = payload.component.clone(); let (job_payload, tag, _runnable_on_behalf_of) = match (payload.path, payload.raw_code, payload.id) { + (Some(_), None, None) if agent_path.is_some() => { + let agent = agent_path.as_deref().unwrap_or_default(); + // Read as the identity the app runs as: reading the agent is what allows running + // it. The app's identity is also the run's, never the agent's own on-behalf-of. + let run_as = windmill_api_auth::fetch_api_authed_from_permissioned_as( + permissioned_as.clone(), + email.clone(), + &w_id, + &db, + None, + ) + .await?; + let turn = crate::agent_runs::agent_turn( + &run_as, + &user_db, + &w_id, + agent, + agent_memory_id.is_some(), + ) + .await?; + agent_run_path = Some(turn.run_path.clone()); + ( + JobPayload::RawFlow { + value: turn.flow_value, + path: Some(turn.run_path), + restarted_from: None, + }, + None, + None, + ) + } // flow or script: (Some(path), None, None) => { get_payload_tag_from_prefixed_path(&path, &db, &w_id).await? @@ -5086,6 +5239,44 @@ async fn execute_component( .await?; } + if let (Some(run_path), Some(memory_id)) = (agent_run_path.as_deref(), agent_memory_id) { + // A signed-in viewer's turn is filed under them: nobody else may continue their + // conversation. An anonymous visitor's id is derived per app so that it can name no + // signed-in user's conversation (a bare UUID is used as is). Either way the + // conversation's row lock refuses a turn while one runs, and retention collects its + // memory with its messages. + let (owner, is_admin, memory_id) = match agent_viewer.as_ref() { + Some(viewer) => (viewer.username.clone(), viewer.is_admin, memory_id), + None => ( + windmill_common::flow_conversations::ANONYMOUS_CONVERSATION_OWNER.to_string(), + false, + windmill_common::flow_conversations::memory_key( + &w_id, + run_path, + &format!("anonymous:{path}:{memory_id}"), + ) + .to_string(), + ), + }; + 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, + is_admin, + &w_id, + run_path, + &run_query, + args.args.get("user_message"), + uuid, + is_preview, + &args.args, + ) + .await?; + } + // Apply runnable query parameters if provided if let Some(ref run_query) = payload.run_query_params { if let Some(flow_path) = flow_path.as_deref() { @@ -5266,11 +5457,7 @@ async fn upload_s3_file_from_app( let authed = opt_authed.as_ref().ok_or_else(|| { Error::NotAuthorized("App S3 preview upload requires authentication".to_string()) })?; - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot run app S3 previews for security reasons".to_string(), - )); - } + require_full_apps(&db, &w_id, authed, "run app S3 previews").await?; check_scopes(authed, || format!("apps:write:{}", path.to_path()))?; Some(Policy { stated_execution_mode: Some(ExecutionMode::Viewer), @@ -5965,11 +6152,7 @@ async fn download_s3_file_from_app( let authed = opt_authed.as_ref().ok_or_else(|| { Error::NotAuthorized("App S3 preview download requires authentication".to_string()) })?; - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot run app S3 previews for security reasons".to_string(), - )); - } + require_full_apps(&db, &w_id, authed, "run app S3 previews").await?; check_scopes(authed, || format!("apps:write:{}", path))?; Some(serde_json::from_str::>(&force_viewer_allowed_s3_keys).unwrap_or_default()) } else { @@ -6461,6 +6644,16 @@ async fn build_args( let mut job_id: Option = None; let mut safe_args = HashMap::>::new(); + // Every check below matches an argument by name against the policy the publisher wrote, + // and `push` stores the args with their `\u0000` escapes removed, names included. So + // compare the names that will actually be stored: otherwise a viewer's `tenant\0` is + // never recognized as the `tenant` the policy pins in `static_inputs` (and is stored as + // `tenant`, winning over the pinned value), and `greeting\0` is never recognized as the + // `greeting` restricted by `one_of_inputs`, so neither list is enforced. Values are + // normalized along with the names, so the checks that look at a value see what the job + // will receive. + normalize_nul_in_args(&mut args); + // Before anything reads `args`: a context input the runnable declares is never taken // from the request, or a viewer could name someone else as themselves. for (k, prop) in ctx_inputs.into_iter().flatten() { @@ -6553,6 +6746,7 @@ async fn build_args( } } + let mut untrusted = HashMap::new(); for (k, v) in args { if safe_args.contains_key(&k) { continue; @@ -6566,31 +6760,16 @@ async fn build_args( k.to_string(), ctx_value(prop, policy, authed, w_id, db).await?, ); - } else if !arg_str.contains("\"$var:") && !arg_str.contains("\"$res:") { - safe_args.insert(k.to_string(), v); } else { - safe_args.insert( - k.to_string(), - RawValue::from_string( - arg_str - .replace( - "$var:", - "The following variable has been omitted for security reasons: ", - ) - .replace( - "$res:", - "The following resource has been omitted for security reasons, to allow it, toggle: 'Allow resources from users' on that field input: ", - ), - ) - .map_err(|e| { - Error::internal_err(format!( - "failed to remove sensitive variable(s)/resource(s) with error: {}", - e - )) - })?, - ); + untrusted.insert(k, v); } } + safe_args.extend( + omit_untrusted_interpolation( + untrusted, + "The following resource has been omitted for security reasons, to allow it, toggle: 'Allow resources from users' on that field input: ", + ), + ); for k in sensitive_inputs { let Some(v) = safe_args.get(k) else { continue }; let raw = v.get(); @@ -6970,7 +7149,7 @@ mod embed_token_tests { #[cfg(test)] mod operator_app_tests { - use super::{check_operator_composed_app, BuilderAppWrite, Policy}; + use super::{check_operator_composed_app, AppRunnableKind, BuilderAppWrite, Policy}; use windmill_common::error::Result; use windmill_common::worker::to_raw_value; @@ -6988,7 +7167,10 @@ mod operator_app_tests { }}) } - fn composed_app(value: serde_json::Value, policy: &mut Policy) -> Result> { + fn composed_app( + value: serde_json::Value, + policy: &mut Policy, + ) -> Result> { let value = to_raw_value(&value); check_operator_composed_app(BuilderAppWrite::Deploy, true, Some(&value), Some(policy)) } @@ -7006,7 +7188,10 @@ mod operator_app_tests { let referenced = composed_app(clean.clone(), &mut policy).unwrap(); assert_eq!(policy.sandbox, Some(true)); // The runnables the policy authorizes are handed back for the caller to authorize. - assert_eq!(referenced, vec![(false, "f/x/s".to_string())]); + assert_eq!( + referenced, + vec![(AppRunnableKind::Script, "f/x/s".to_string())] + ); // A hub reference is unreviewed code, refused like it is in a flow. let mut policy = builder_policy( @@ -7043,12 +7228,20 @@ mod operator_app_tests { let mut policy = builder_policy(serde_json::json!({})); assert_eq!( composed_app(path_runnable("f/x/s", "script"), &mut policy).unwrap(), - vec![(false, "f/x/s".to_string())] + vec![(AppRunnableKind::Script, "f/x/s".to_string())] ); let mut policy = builder_policy(serde_json::json!({})); assert_eq!( composed_app(path_runnable("f/x/f", "flow"), &mut policy).unwrap(), - vec![(true, "f/x/f".to_string())] + vec![(AppRunnableKind::Flow, "f/x/f".to_string())] + ); + // An agent is reported from both surfaces, for the caller to check it can read it. + let mut policy = builder_policy( + serde_json::json!({"a:agent/f/x/bot": {"static_inputs": {}, "one_of_inputs": {}}}), + ); + assert_eq!( + composed_app(path_runnable("f/x/bot", "agent"), &mut policy).unwrap(), + 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()); @@ -7065,7 +7258,7 @@ mod operator_app_tests { ); assert_eq!( composed_app(clean.clone(), &mut policy).unwrap(), - vec![(false, "f/x/s".to_string())] + vec![(AppRunnableKind::Script, "f/x/s".to_string())] ); // `Viewer` mode makes `execute_component` accept any script/flow path, triggerables or diff --git a/backend/windmill-api/src/apps_raw_bundler.ts b/backend/windmill-api/src/apps_raw_bundler.ts index 965a9289b5..47460be3a6 100644 --- a/backend/windmill-api/src/apps_raw_bundler.ts +++ b/backend/windmill-api/src/apps_raw_bundler.ts @@ -135,7 +135,7 @@ export async function main( const nonEmpty = (v: unknown) => typeof v === 'string' && v.length > 0 // The prefixes `execute_component` resolves a run against; anything else is a // grant no run can match. - const RUN_TYPES = ['script', 'flow', 'hubscript'] + const RUN_TYPES = ['script', 'flow', 'hubscript', 'agent'] const malformed = Object.entries(runnables ?? {}) .filter(([, r]) => r != null) .filter(([, r]) => { diff --git a/backend/windmill-api/src/drafts.rs b/backend/windmill-api/src/drafts.rs index b582e84e36..31a7bea2c5 100644 --- a/backend/windmill-api/src/drafts.rs +++ b/backend/windmill-api/src/drafts.rs @@ -16,6 +16,7 @@ use axum::{ use serde::{Deserialize, Serialize}; use windmill_api_flows::flows::validate_operator_flow; use windmill_audit::{audit_oss::audit_log, ActionKind}; +use windmill_common::roles::AuthorLevel; use windmill_common::{ db::UserDB, error::{Error, Result}, @@ -469,7 +470,10 @@ async fn update_draft( } } - if authed.is_operator && kind == UserDraftItemKind::Flow { + // 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 { @@ -495,8 +499,45 @@ async fn update_draft( } } + // 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, + } + 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 authed.is_operator && kind == UserDraftItemKind::RawApp { + 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}")))?; @@ -1269,9 +1310,9 @@ pub(crate) async fn require_can_write_path( // about. Read access is deliberately asymmetric: `require_can_read_path` has no operator block, // so an operator can still READ a draft they can read via `/drafts/get`, mirroring their read // access to deployed content. Intended. - if authed.is_operator && !operator_can_draft(db, w_id, kind).await? { + if !operator_can_draft(db, w_id, authed, kind).await? { return Err(Error::PermissionDenied(format!( - "operators cannot save {} drafts in this workspace", + "your role cannot save {} drafts in this workspace", kind.as_str() ))); } diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index a7e2915571..bf3d7ea24c 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -36,12 +36,13 @@ use windmill_common::error::JsonResult; use windmill_common::flow_status::{JobResult, RestartedFrom}; use windmill_common::jobs::{ format_completed_job_result, format_result, is_safe_log_file_path, is_valid_entrypoint_name, - DynamicInput, ENTRYPOINT_OVERRIDE, + sanitize_untrusted_args, DynamicInput, ENTRYPOINT_OVERRIDE, }; #[cfg(feature = "run_inline")] use windmill_common::jobs::{ InlineScriptTarget, RunInlinePreviewScriptFnParams, RunInlineScriptFnParams, }; +use windmill_common::roles::AuthorLevel; use windmill_common::runnable_settings::{ ConcurrencySettings, ConcurrencySettingsWithCustom, DebouncingSettings, }; @@ -7058,7 +7059,7 @@ async fn batch_rerun_handle_job( ) .await; if let Ok((uuid, _, _, _)) = result { - resolve_batch_rerun_source(authed, user_db, w_id, job.id, uuid).await; + resolve_batch_rerun_source(authed, db, user_db, w_id, job.id, uuid).await; return Ok(uuid.to_string()); } } @@ -7092,7 +7093,7 @@ async fn batch_rerun_handle_job( .map(|r| r.0) }; if let Ok(uuid) = result { - resolve_batch_rerun_source(authed, user_db, w_id, job.id, uuid).await; + resolve_batch_rerun_source(authed, db, user_db, w_id, job.id, uuid).await; return Ok(uuid.to_string()); } } @@ -7109,12 +7110,13 @@ async fn batch_rerun_handle_job( /// re-run, which is already queued: a source that cannot be resolved is logged and left as is. async fn resolve_batch_rerun_source( authed: &ApiAuthed, + db: &DB, user_db: &UserDB, w_id: &str, source: Uuid, rerun: Uuid, ) { - if authed.is_operator { + if !role_can_code(db, w_id, authed).await.unwrap_or(false) { return; } let result: error::Result<()> = async { @@ -8989,14 +8991,24 @@ async fn operator_may_run_datatable_query( .unwrap_or(false)) } -/// The refusal an operator 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. +/// 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 { + Ok( + windmill_common::roles::caller_capabilities(db, w_id, authed) + .await? + .code, + ) +} + +/// 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) -> error::Error { let reason = if job_id.is_some() { - "Operators cannot run preview jobs for security reasons: from inside a job, an \ - operator may only run a wmill.datatable() query while that job is running" + "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" } else { - "Operators cannot run preview jobs for security reasons" + "Your role cannot run preview jobs in this workspace" }; // 403, not 401: the frontend reads a 401 as a dead session and logs the user out, and the // flow editor builders open reaches this route. @@ -9023,7 +9035,9 @@ pub(crate) async fn preview_on_behalf_of( if requested == own || requested == authed.email { return Ok(None); } - if authed.is_operator || !windmill_common::can_preserve_on_behalf_of(authed) { + if !role_can_code(db, w_id, authed).await? + || !windmill_common::can_preserve_on_behalf_of(authed) + { return Err(Error::PermissionDenied( "Only admins and members of wm_deployers can run a preview on behalf of another user" .to_string(), @@ -9119,7 +9133,7 @@ async fn run_preview_script( ) -> error::Result<(StatusCode, String)> { #[cfg(feature = "enterprise")] check_license_key_valid().await?; - if authed.is_operator { + if !role_can_code(&db, &w_id, &authed).await? { // A deferred run would outlive the running job the exemption keys off. if run_query.get_scheduled_for(&db).await?.is_some() || !operator_may_run_datatable_query( @@ -9250,7 +9264,7 @@ async fn run_inline_preview_script( // Same arbitrary-code class as run_preview_script, and every worker and standalone // server exposes this route, so an operator is refused on the same terms. A // narrowly-scoped token must not escape its scope through inline preview either. - if authed.is_operator + if !role_can_code(&db, &w_id, &authed).await? && !operator_may_run_datatable_query( &db, &w_id, @@ -9556,10 +9570,8 @@ async fn run_bundle_preview_script( Query(run_query): Query, mut multipart: axum::extract::Multipart, ) -> error::Result<(StatusCode, String)> { - if authed.is_operator { - return Err(error::Error::NotAuthorized( - "Operators cannot run preview jobs for security reasons".to_string(), - )); + if !role_can_code(&db, &w_id, &authed).await? { + return Err(operator_preview_refusal(None)); } // Bundle preview runs arbitrary, request-supplied code; require the broad jobs:run // scope so a narrowly-scoped token cannot escape its scope. See run_preview_script. @@ -9766,9 +9778,9 @@ async fn push_dependencies_job( req: RunDependenciesRequest, ) -> error::Result { check_dependencies_scope(authed, &req.entrypoint)?; - if authed.is_operator { - return Err(error::Error::NotAuthorized( - "Operators cannot run dependencies jobs for security reasons".to_string(), + if !role_can_code(db, w_id, authed).await? { + return Err(error::Error::PermissionDenied( + "Your role cannot run dependencies jobs in this workspace".to_string(), )); } @@ -9889,10 +9901,10 @@ async fn push_flow_dependencies_job( req: RunFlowDependenciesRequest, ) -> error::Result { check_dependencies_scope(authed, &req.path)?; - check_operator_can_build( + let flows_level = check_operator_can_build( db, w_id, - authed.is_operator, + authed, BuilderKind::Flows, "run dependencies jobs", ) @@ -9900,7 +9912,7 @@ async fn push_flow_dependencies_job( // The dependency job locks whatever inline code this request carries, on a worker. A // composition-only flow has none, so validating here costs a builder nothing and keeps the // lock step from becoming the way to run code the write path refuses. - if authed.is_operator { + 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. @@ -10316,14 +10328,9 @@ async fn run_preview_flow_job( Query(run_query): Query, Json(raw_flow): Json, ) -> error::Result<(StatusCode, String)> { - check_operator_can_build( - &db, - &w_id, - authed.is_operator, - BuilderKind::Flows, - "run preview jobs", - ) - .await?; + let flows_level = + check_operator_can_build(&db, &w_id, &authed, BuilderKind::Flows, "run preview jobs") + .await?; // Flow preview runs an arbitrary, request-supplied flow definition; require the broad // jobs:run scope so a narrowly-scoped token cannot escape its scope. See run_preview_script. check_scopes(&authed, || format!("jobs:run"))?; @@ -10337,7 +10344,7 @@ async fn run_preview_flow_job( } // A builder must be able to test what it composes, but the submitted value is not the stored // one: without this the preview is a way to run inline code the write path refuses. - if authed.is_operator { + if flows_level == AuthorLevel::Compose { validate_operator_composed_flow( &raw_flow.value, &raw_flow.tag, @@ -10481,7 +10488,7 @@ async fn run_dynamic_select( Extension(user_db): Extension, Path(w_id): Path, Query(run_query): Query, - Json(request): Json, + Json(mut request): Json, ) -> error::Result { #[cfg(feature = "enterprise")] check_license_key_valid().await?; @@ -10489,7 +10496,7 @@ async fn run_dynamic_select( if matches!( request.runnable_ref, DynamicSelectRunnableRef::Inline { .. } - ) && authed.is_operator + ) && !role_can_code(&db, &w_id, &authed).await? { return Err(operator_preview_refusal(None)); } @@ -10503,6 +10510,20 @@ async fn run_dynamic_select( ))); } + // The dyn-select code is the runnable's, not necessarily the caller's: a deployed flow + // has no deployed runnable for it, so it runs as a `JobKind::Preview` job, and the + // executors honor `_TEMP_SCRIPT_REFS` on every preview — it resolves the code's + // workspace imports from the temporary script store, which any workspace member can + // write. A caller of this route (an operator, for a deployed flow) only fills in that + // code's inputs; the function to call is taken from `entrypoint_function`, validated + // above and inserted server-side below, never from the args. So the reserved control + // keys are dropped here, in the spellings `push` would store them under. Nothing + // server-side puts them in `args`: the request has no `temp_script_refs` field, and the + // run form does not send them. + if let Some(args) = request.args.as_mut() { + sanitize_untrusted_args(args); + } + // Deployed scripts keep their normal deployed-run path (a `script` job, resolved below by // push_script_job_by_path_into_queue). Deployed flows and inline snippets have no deployed // runnable, so they run their dyn-select code as a `preview`; the flow carries its path and @@ -12572,14 +12593,16 @@ fn resolution_attribution<'a>( (None, None) } -fn check_resolution_request( +async fn check_resolution_request( authed: &ApiAuthed, + db: &DB, + w_id: &str, job_ids: &[Uuid], note: Option<&str>, ) -> error::Result<()> { - if authed.is_operator { - return Err(error::Error::NotAuthorized( - "Operators cannot resolve jobs".to_string(), + if !role_can_code(db, w_id, authed).await? { + return Err(error::Error::PermissionDenied( + "Your role cannot resolve jobs in this workspace".to_string(), )); } if job_ids.len() > MAX_RESOLUTION_BATCH { @@ -12604,11 +12627,12 @@ fn check_resolution_request( /// absent rather than an error, so a bulk selection never fails as a whole. async fn resolve_completed_jobs( authed: ApiAuthed, + Extension(db): Extension, Extension(user_db): Extension, Path(w_id): Path, Json(req): Json, ) -> error::JsonResult> { - check_resolution_request(&authed, &req.job_ids, req.note.as_deref())?; + check_resolution_request(&authed, &db, &w_id, &req.job_ids, req.note.as_deref()).await?; let mut tx = user_db.begin(&authed).await?; let tags = get_scope_tags(&authed); let (resolved_by, typed_note) = resolution_attribution(&authed, req.note.as_deref()); @@ -12690,11 +12714,12 @@ async fn resolve_completed_jobs( async fn unresolve_completed_jobs( authed: ApiAuthed, + Extension(db): Extension, Extension(user_db): Extension, Path(w_id): Path, Json(req): Json, ) -> error::JsonResult> { - check_resolution_request(&authed, &req.job_ids, None)?; + check_resolution_request(&authed, &db, &w_id, &req.job_ids, None).await?; let mut tx = user_db.begin(&authed).await?; let tags = get_scope_tags(&authed); let unresolved = sqlx::query_scalar!( diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 3bf21463eb..446a585d35 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -9,8 +9,6 @@ use crate::db::ApiAuthed; #[cfg(feature = "embedding")] use crate::embeddings::load_embeddings_db; -#[cfg(feature = "oauth2")] -use crate::oauth2_oss::SlackVerifier; #[cfg(feature = "smtp")] use crate::smtp_server_oss::SmtpServer; use axum::middleware::from_fn_with_state; @@ -250,10 +248,6 @@ pub use windmill_oauth::OAUTH_CLIENTS; #[cfg(feature = "oauth2")] lazy_static::lazy_static! { - pub static ref SLACK_SIGNING_SECRET: Option = std::env::var("SLACK_SIGNING_SECRET") - .ok() - .map(|x| SlackVerifier::new(x).unwrap()); - // Comma-separated Slack v2 OAuth bot scopes requested when connecting a workspace. // Must be a subset of the bot scopes declared in the Slack app manifest. Default matches // Windmill's recommended manifest at docs.windmill.dev/docs/misc/setup_oauth. @@ -576,14 +570,14 @@ pub async fn run_server( // Setup MCP server #[allow(unused_variables)] - let (mcp_router, gateway_mcp_router, mcp_cancellation_token) = { + let (mcp_router, gateway_mcp_router, gateway_session_router, mcp_cancellation_token) = { #[cfg(feature = "mcp")] if server_mode || mcp_mode { use mcp::{ add_www_authenticate_header, add_www_authenticate_header_gateway, extract_workspace_from_token, reject_token_query_param, }; - let (mcp_router, mcp_cancellation_token) = setup_mcp_server( + let (mcp_router, session_router, mcp_cancellation_token) = setup_mcp_server( db.clone(), user_db, _base_internal_url.clone(), @@ -605,17 +599,32 @@ pub async fn run_server( .layer(axum::middleware::from_fn( add_www_authenticate_header_gateway, )); + // The workspace server. Its tools name their workspace; the token bounds which. + let gateway_session_router = session_router + .route_layer(from_extractor::()) + .layer(axum::middleware::from_fn(extract_workspace_from_token)) + .layer(axum::middleware::from_fn(reject_token_query_param)) + .layer(axum::middleware::from_fn( + add_www_authenticate_header_gateway, + )) + .layer(Extension(mcp::McpEndpoint("/api/mcp"))); ( workspaced_mcp_router, gateway_mcp_router, + gateway_session_router, Some(mcp_cancellation_token), ) } else { - (Router::new(), Router::new(), None) + (Router::new(), Router::new(), Router::new(), None) } #[cfg(not(feature = "mcp"))] - (Router::new(), Router::new(), Option::<()>::None) + ( + Router::new(), + Router::new(), + Router::new(), + Option::<()>::None, + ) }; // Workers block on this before pulling their first job, so it is released ahead of @@ -628,15 +637,15 @@ pub async fn run_server( } tokio::task::yield_now().await; - let mcp_list_tools_service = { + let (mcp_list_tools_service, mcp_toolset_service) = { #[cfg(feature = "mcp")] { - mcp::list_tools_service() + (mcp::list_tools_service(), mcp::toolset_service()) } #[cfg(not(feature = "mcp"))] { - Router::new() + (Router::new(), Router::new()) } }; @@ -854,6 +863,7 @@ pub async fn run_server( .nest("/docs", docs::global_service()) .nest("/indexer", indexer_oss::management_service()) .nest("/mcp/w/{workspace_id}/list_tools", mcp_list_tools_service) + .nest("/mcp/toolset", mcp_toolset_service) .nest("/db_health", db_health::global_service()) .nest("/health/detailed", health::detailed_service()) .nest( @@ -949,6 +959,7 @@ pub async fn run_server( mcp_router.clone().layer(mcp_cors.clone()), ) .nest("/mcp/gateway", gateway_mcp_router.layer(mcp_cors.clone())) + .merge(gateway_session_router.layer(mcp_cors.clone())) .nest("/agent_workers", { #[cfg(feature = "agent_worker_server")] { @@ -1186,6 +1197,16 @@ pub async fn run_server( get(|| async { axum::http::StatusCode::NOT_FOUND }) } }) + .route("/.well-known/oauth-protected-resource/api/mcp", { + #[cfg(feature = "mcp")] + { + get(mcp::oauth_server::gateway_session_protected_resource_metadata) + } + #[cfg(not(feature = "mcp"))] + { + get(|| async { axum::http::StatusCode::NOT_FOUND }) + } + }) // JWKS endpoint for HashiCorp Vault JWT authentication (must be outside /api prefix) .route("/.well-known/jwks.json", { #[cfg(all(feature = "private", feature = "enterprise", feature = "openidconnect"))] @@ -1259,6 +1280,9 @@ pub async fn run_server( if let Some(name) = name.as_ref() { tracing::info!("server starting for name={name}"); } + #[cfg(feature = "mcp")] + mcp::register_router(&_base_internal_url, Some(app.clone())); + let listener = listener.tap_io(move |tcp_stream| { let _ = tcp_stream.set_nodelay(!server_mode); }); @@ -1296,7 +1320,10 @@ pub async fn run_server( } }); - server.await?; + let served = server.await; + #[cfg(feature = "mcp")] + mcp::register_router(&_base_internal_url, None); + served?; let forks = &windmill_api_workspaces::workspaces::BACKGROUND_FORKS; forks.close(); if !forks.is_empty() { diff --git a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs index 8ff3e9f5c2..9add0792ee 100644 --- a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs +++ b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs @@ -184,7 +184,12 @@ pub fn all_tools() -> Vec { }, "expires_at": { "type": "string", - "description": "The expiration date of the variable", + "description": "When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry — see value_valid_until.\n", + "format": "date-time" + }, + "value_valid_until": { + "type": "string", + "description": "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it, by the handler's `notify_before_secs` (1 day by default); never causes the variable to be deleted.\n", "format": "date-time" }, "labels": { @@ -272,6 +277,12 @@ pub fn all_tools() -> Vec { "type": "string", "description": "The new description of the variable" }, + "value_valid_until": { + "type": "string", + "nullable": true, + "description": "When the value stored in this variable stops working. Omit to leave it unchanged; send null to clear it. Changing it re-arms the workspace's variable expiration handler.\n", + "format": "date-time" + }, "labels": { "type": "array", "items": { diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index a8eb420ac4..52a6a32014 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -13,7 +13,8 @@ use windmill_mcp::common::types::{ FlowInfo, HubScriptInfo, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo, }; use windmill_mcp::server::{ - BackendResult, EndpointTool, ErrorData, McpBackend, McpRequest, PathFilter, + BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend, McpRequest, PathFilter, + SessionAccess, Tool, }; use crate::auth::AuthCache; @@ -23,6 +24,7 @@ use crate::jobs::{ }; use super::auto_generated_endpoints::all_tools; +use super::session; use super::utils::{ build_query_string, build_request_body, create_http_request, get_hub_script_schema, get_item_paths, get_item_schema, get_items, get_resources, get_resources_types, @@ -33,9 +35,10 @@ use std::sync::Arc; use std::time::Duration; use tokio_util::sync::CancellationToken; +use windmill_mcp::common::SESSION_SCOPE; use windmill_mcp::server::{ - LocalSessionManager, McpToken, MultiWorkspaceMcp, Runner, StreamableHttpServerConfig, - StreamableHttpService, + LocalSessionManager, McpToken, MultiWorkspaceMcp, NoEndpointTools, Runner, SessionRunner, + StreamableHttpServerConfig, StreamableHttpService, }; use windmill_mcp::WorkspaceId; @@ -64,6 +67,32 @@ pub struct WindmillBackend { } impl WindmillBackend { + /// The instructions only read, so they are built at the token's own read-only flag. + fn session_ctx<'a>(&'a self, auth: &'a ApiAuthed, w_id: &'a str) -> session::Ctx<'a> { + let access = if auth.read_only { + SessionAccess::ReadOnly + } else { + SessionAccess::Full + }; + self.session_ctx_with(auth, w_id, access) + } + + fn session_ctx_with<'a>( + &'a self, + auth: &'a ApiAuthed, + w_id: &'a str, + access: SessionAccess, + ) -> session::Ctx<'a> { + session::Ctx { + auth, + w_id, + base_internal_url: &self.base_internal_url, + access, + origin: None, + jwt: Default::default(), + } + } + pub fn new( db: DB, user_db: UserDB, @@ -242,6 +271,7 @@ impl McpBackend for WindmillBackend { args: Value, request: &McpRequest<'_>, ) -> BackendResult { + windmill_common::feature_usage::log_feature_usage("mcp", "runnable_tool_call", "script"); let push_args = prepare_push_args(&self.db, workspace_id, path, false, args, request) .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; @@ -269,6 +299,7 @@ impl McpBackend for WindmillBackend { args: Value, request: &McpRequest<'_>, ) -> BackendResult { + windmill_common::feature_usage::log_feature_usage("mcp", "runnable_tool_call", "flow"); let push_args = prepare_push_args(&self.db, workspace_id, path, true, args, request) .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; @@ -295,6 +326,12 @@ impl McpBackend for WindmillBackend { endpoint_tool: &EndpointTool, args: Value, ) -> BackendResult { + // Whether the generated endpoint tools are used at all, and which ones. + windmill_common::feature_usage::log_feature_usage( + "mcp", + "endpoint_tool_call", + &endpoint_tool.name, + ); let args_map = match &args { Value::Object(map) => map, _ => { @@ -421,8 +458,68 @@ impl McpBackend for WindmillBackend { fn all_endpoint_tools(&self) -> Vec { all_tools() } + + async fn session_instructions( + &self, + auth: &ApiAuthed, + workspace_id: &str, + ) -> BackendResult { + Ok(session::session_instructions(&self.session_ctx(auth, workspace_id)).await) + } + + fn generic_session_instructions(&self) -> String { + session::generic_session_instructions() + } + + async fn workspace_context(&self, auth: &ApiAuthed, workspace_id: &str) -> String { + session::workspace_context(&self.session_ctx(auth, workspace_id)).await + } + + fn session_tools(&self, access: SessionAccess) -> Vec { + session::session_tools(access) + } + + async fn call_session_tool( + &self, + auth: &ApiAuthed, + workspace_id: &str, + name: &str, + args: Value, + access: SessionAccess, + origin: Option<&str>, + ) -> BackendResult { + let ctx = session::Ctx { origin, ..self.session_ctx_with(auth, workspace_id, access) }; + session::call_session_tool(&ctx, name, args).await + } } +/// Set on a request whose token is scoped to a selection of scripts, flows and endpoints +/// rather than `mcp:all`: on `/api/mcp`, the tools server answers it. +#[derive(Clone, Copy)] +pub struct McpSelection; + +/// MCP scopes without `mcp:all`: favorites, chosen scripts, flows, endpoints or hub apps. +fn scoped_to_selection(scopes: &[String]) -> bool { + let mut mcp = scopes.iter().filter(|scope| scope.starts_with("mcp:")); + mcp.clone().next().is_some() && !mcp.any(|scope| scope == "mcp:all") +} + +/// Whether the tools server's URLs (`/api/mcp/gateway`, `/api/mcp/w/{workspace}/mcp`) serve +/// a token the session's toolset: an `mcp:all` grant marked `mcp:session`, or narrowed by +/// `mcp:read_only` / `mcp:read_run`, which the consent page describes as session access. +/// Every other token there keeps the tools server it was issued for. +fn serves_session_toolset(scopes: &[String]) -> bool { + scopes.iter().any(|scope| scope == "mcp:all") + && scopes + .iter() + .any(|scope| [SESSION_SCOPE, "mcp:read_only", "mcp:read_run"].contains(&scope.as_str())) +} + +/// The path of a workspace-less MCP URL, when it is not the tools server's +/// `/api/mcp/gateway`: each URL is its own OAuth protected resource. +#[derive(Clone, Copy)] +pub struct McpEndpoint(pub &'static str); + /// Extract workspace ID from path and store it in request extensions pub async fn extract_and_store_workspace_id( Path(params): Path, @@ -434,6 +531,16 @@ pub async fn extract_and_store_workspace_id( next.run(request).await } +/// RFC 9728 challenge pointing at the endpoint's protected resource metadata. `scope` is what +/// a client requests: without it, Claude requests every scope the metadata lists, read-only +/// included, and the consent page would then default to read-only access. +fn www_authenticate_value(base_url: &str, endpoint: &str) -> String { + format!( + "Bearer resource_metadata=\"{base_url}/.well-known/oauth-protected-resource{endpoint}\", \ + scope=\"mcp:all\"" + ) +} + /// Middleware that adds WWW-Authenticate header to 401 responses /// This helps MCP clients discover the OAuth authorization server (RFC 9728) pub async fn add_www_authenticate_header( @@ -454,18 +561,14 @@ pub async fn add_www_authenticate_header( .body(axum::body::Body::from("Missing workspace_id in request")) .unwrap(); }; - let response = next.run(request).await; // Only add header to 401 Unauthorized responses if response.status() == StatusCode::UNAUTHORIZED { let base_url = BASE_URL.load(); - // RFC 9728: The resource parameter contains the protected resource URL. - // Clients derive the metadata URL by inserting /.well-known/oauth-protected-resource - // after the host, e.g., http://host/.well-known/oauth-protected-resource/api/mcp/w/test/mcp - let resource_url = format!("{}/api/mcp/w/{}/mcp", base_url, workspace_id); - let www_authenticate = format!("Bearer resource=\"{}\"", resource_url); + let www_authenticate = + www_authenticate_value(&base_url, &format!("/api/mcp/w/{}/mcp", workspace_id)); // Reconstruct response with the new header let (mut parts, body) = response.into_parts(); @@ -541,27 +644,32 @@ pub async fn extract_workspace_from_token( .fetch_optional(&db) .await { - Ok(Some(row)) => match row.workspace_id { - Some(workspace_id) => { - request - .extensions_mut() - .insert(GatewayWorkspaceId(workspace_id.clone())); - request.extensions_mut().insert(WorkspaceId(workspace_id)); + Ok(Some(row)) => { + if scoped_to_selection(row.scopes.as_deref().unwrap_or_default()) { + request.extensions_mut().insert(McpSelection); } - None => { - // Only enter multi-workspace mode for genuine MCP tokens; a - // full-privilege global token without mcp scope is rejected - // by the runner's mcp-scope check anyway. - let is_mcp = row - .scopes - .as_deref() - .is_some_and(|s| s.iter().any(|scope| scope.starts_with("mcp:"))); - if is_mcp { - request.extensions_mut().insert(MultiWorkspaceMcp); - request.extensions_mut().insert(McpToken(token)); + match row.workspace_id { + Some(workspace_id) => { + request + .extensions_mut() + .insert(GatewayWorkspaceId(workspace_id.clone())); + request.extensions_mut().insert(WorkspaceId(workspace_id)); + } + None => { + // Only enter multi-workspace mode for genuine MCP tokens; a + // full-privilege global token without mcp scope is rejected + // by the runner's mcp-scope check anyway. + let is_mcp = row + .scopes + .as_deref() + .is_some_and(|s| s.iter().any(|scope| scope.starts_with("mcp:"))); + if is_mcp { + request.extensions_mut().insert(MultiWorkspaceMcp); + request.extensions_mut().insert(McpToken(token)); + } } } - }, + } Ok(None) => {} Err(e) => { tracing::error!("Gateway token workspace lookup failed: {}", e); @@ -580,12 +688,16 @@ pub async fn add_www_authenticate_header_gateway( use axum::http::StatusCode; use windmill_common::BASE_URL; + let endpoint = request + .extensions() + .get::() + .map_or("/api/mcp/gateway", |e| e.0); + let response = next.run(request).await; if response.status() == StatusCode::UNAUTHORIZED { let base_url = BASE_URL.load(); - let resource_url = format!("{}/api/mcp/gateway", base_url); - let www_authenticate = format!("Bearer resource=\"{}\"", resource_url); + let www_authenticate = www_authenticate_value(&base_url, endpoint); let (mut parts, body) = response.into_parts(); parts.headers.insert( @@ -606,11 +718,12 @@ pub async fn setup_mcp_server( user_db: UserDB, base_internal_url: String, auth_cache: Arc, -) -> anyhow::Result<(Router, CancellationToken)> { +) -> anyhow::Result<(Router, Router, CancellationToken)> { let cancellation_token = CancellationToken::new(); let session_manager = Arc::new(LocalSessionManager::default()); let backend = WindmillBackend::new(db, user_db, base_internal_url, auth_cache); + let session_runner = SessionRunner::new(backend.clone()); let runner = Runner::new(backend); let service_config = StreamableHttpServerConfig::default() @@ -632,11 +745,61 @@ pub async fn setup_mcp_server( // much smaller default, which would 413 them with no way to raise it. .with_max_request_body_bytes(*crate::REQUEST_SIZE_LIMIT.read().await); + let session_service = StreamableHttpService::new( + move || Ok(session_runner.clone()), + session_manager.clone(), + service_config.clone(), + ); let service = StreamableHttpService::new(move || Ok(runner.clone()), session_manager, service_config); - let router = Router::new().route_service("/", service); - Ok((router, cancellation_token)) + let router = Router::new().route( + "/", + axum::routing::any({ + let (service, session_service) = (service.clone(), session_service.clone()); + move |request: Request| { + let (service, session_service) = (service.clone(), session_service.clone()); + async move { + use tower::ServiceExt; + let session = request.extensions().get::().is_some_and(|a| { + serves_session_toolset(a.scopes.as_deref().unwrap_or_default()) + }); + let response = if session { + session_service.oneshot(request).await + } else { + service.oneshot(request).await + }; + match response { + Ok(response) => response.into_response(), + Err(never) => match never {}, + } + } + } + }), + ); + // `/api/mcp` serves both servers: a token scoped to a selection of scripts, flows and + // endpoints gets the tools server, any other the session's toolset. At `/mcp` itself, + // beside the `/mcp/...` routes, so it is merged rather than nested. + let session_router = Router::new().route( + "/mcp", + axum::routing::any(move |mut request: Request| { + let (service, session_service) = (service.clone(), session_service.clone()); + async move { + use tower::ServiceExt; + let response = if request.extensions().get::().is_some() { + request.extensions_mut().insert(NoEndpointTools); + service.oneshot(request).await + } else { + session_service.oneshot(request).await + }; + match response { + Ok(response) => response.into_response(), + Err(never) => match never {}, + } + } + }), + ); + Ok((router, session_router, cancellation_token)) } /// HTTP handler to list MCP tools as JSON @@ -649,3 +812,75 @@ async fn list_mcp_tools_handler() -> JsonResult> { pub fn list_tools_service() -> Router { Router::new().route("/", get(list_mcp_tools_handler)) } + +#[derive(serde::Deserialize)] +struct ToolsetQuery { + access: Option, +} + +#[derive(serde::Serialize)] +struct ToolsetEntry { + name: String, + description: String, +} + +/// The tools `/api/mcp` offers an `mcp:all` token at each access level, for the token +/// form to show: the server's own filter, so the list cannot drift from it. +async fn list_toolset_handler( + axum::extract::Query(query): axum::extract::Query, +) -> JsonResult> { + let access = match query.access.as_deref() { + Some("read") => SessionAccess::ReadOnly, + Some("read_run") => SessionAccess::ReadAndRun, + _ => SessionAccess::Full, + }; + Ok(Json( + session::session_tools(access) + .into_iter() + .map(|tool| ToolsetEntry { + name: tool.name.to_string(), + description: tool.description.map(|d| d.to_string()).unwrap_or_default(), + }) + .collect(), + )) +} + +pub fn toolset_service() -> Router { + Router::new().route("/", get(list_toolset_handler)) +} + +#[cfg(test)] +mod tests { + use super::{scoped_to_selection, serves_session_toolset}; + + #[test] + fn only_a_token_without_mcp_all_is_a_selection() { + let selection = |scopes: &[&str]| { + scoped_to_selection(&scopes.iter().map(|s| s.to_string()).collect::>()) + }; + assert!(selection(&["mcp:favorites"])); + assert!(selection(&["mcp:scripts:f/x/*", "mcp:endpoints:listJobs"])); + assert!(selection(&["mcp:all:f/x/*"])); + assert!(!selection(&["mcp:all"])); + assert!(!selection(&[ + "mcp:all", + "mcp:read_run", + "mcp:workspaces:a,b" + ])); + assert!(!selection(&[])); + assert!(!selection(&["variables:read"])); + } + + #[test] + fn tools_server_urls_keep_unmarked_tokens() { + let session = |scopes: &[&str]| { + serves_session_toolset(&scopes.iter().map(|s| s.to_string()).collect::>()) + }; + assert!(session(&["mcp:all", "mcp:session"])); + assert!(session(&["mcp:all", "mcp:read_only"])); + assert!(session(&["mcp:all", "mcp:read_run", "mcp:workspaces:a,b"])); + assert!(!session(&["mcp:all"])); + assert!(!session(&["mcp:favorites", "mcp:session"])); + assert!(!session(&["mcp:all:f/x/*", "mcp:read_only"])); + } +} diff --git a/backend/windmill-api/src/mcp/mod.rs b/backend/windmill-api/src/mcp/mod.rs index 5545d59a9f..20c5532b29 100644 --- a/backend/windmill-api/src/mcp/mod.rs +++ b/backend/windmill-api/src/mcp/mod.rs @@ -5,6 +5,7 @@ mod auto_generated_endpoints; mod core; +mod session; mod utils; // Re-export only what's needed externally @@ -12,5 +13,6 @@ pub mod oauth_server; pub use core::{ add_www_authenticate_header, add_www_authenticate_header_gateway, extract_and_store_workspace_id, extract_workspace_from_token, list_tools_service, - reject_token_query_param, setup_mcp_server, + reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint, }; +pub(crate) use session::register_router; diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index d7c8c35586..677875da96 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -19,7 +19,7 @@ use windmill_common::{ use crate::db::ApiAuthed; use windmill_api_auth::forbid_elevated_job_token; -use windmill_mcp::parse_mcp_scopes; +use windmill_mcp::{common::SESSION_SCOPE, parse_mcp_scopes}; /// Token expiration for MCP OAuth tokens (1 week in seconds) const MCP_OAUTH_TOKEN_EXPIRATION_SECS: u64 = 7 * 24 * 60 * 60; @@ -201,7 +201,7 @@ struct AuthorizationCode { code: String, client_id: String, user_email: String, - workspace_id: String, + workspace_id: Option, scopes: Vec, redirect_uri: String, code_challenge: Option, @@ -216,7 +216,7 @@ struct RefreshTokenRow { access_token_hash: String, client_id: String, user_email: String, - workspace_id: String, + workspace_id: Option, scopes: Vec, token_family: sqlx::types::Uuid, created_at: chrono::DateTime, @@ -225,14 +225,25 @@ struct RefreshTokenRow { revoked: bool, } -fn supported_scopes() -> Vec { - vec![ - "mcp:all".to_string(), - "mcp:favorites".to_string(), - "mcp:scripts:*".to_string(), - "mcp:flows:*".to_string(), - "mcp:endpoints:*".to_string(), +/// The scopes that grant access. A protected resource advertises only these: MCP clients +/// that request every listed scope must not pick up a narrowing, which would make the +/// consent page start from a narrower access than they meant to ask for. +fn granting_scopes() -> Vec { + [ + "mcp:all", + "mcp:favorites", + "mcp:scripts:*", + "mcp:flows:*", + "mcp:endpoints:*", ] + .map(String::from) + .to_vec() +} + +fn supported_scopes() -> Vec { + let mut scopes = granting_scopes(); + scopes.extend(["mcp:read_only", "mcp:read_run", "mcp:runnables_as_tools"].map(String::from)); + scopes } /// GET /.well-known/oauth-authorization-server/api/w/:workspace_id/mcp/oauth/server @@ -260,7 +271,7 @@ fn build_protected_resource_metadata( ProtectedResourceMetadata { resource: format!("{}{}", base_url, resource_path), authorization_servers: vec![format!("{}{}", base_url, oauth_prefix)], - scopes_supported: Some(supported_scopes()), + scopes_supported: Some(granting_scopes()), bearer_methods_supported: Some(vec!["header".to_string()]), } } @@ -365,18 +376,59 @@ pub async fn oauth_token( Extension(db): Extension, Form(req): Form, ) -> std::result::Result, OAuthTokenError> { - match req.grant_type.as_str() { - "authorization_code" => handle_authorization_code_grant(&db, &req).await, - "refresh_token" => handle_refresh_token_grant(&db, &req).await, - _ => Err(OAuthTokenError::unsupported_grant_type( - "Supported grant types: authorization_code, refresh_token", - )), + let db_error = |e: sqlx::Error| { + tracing::error!("Database error issuing MCP OAuth token: {}", e); + OAuthTokenError::server_error("Database error") + }; + let owner = match req.grant_type.as_str() { + "authorization_code" => sqlx::query_scalar!( + "SELECT user_email FROM mcp_oauth_server_code WHERE code = $1", + req.code + ) + .fetch_optional(&db) + .await + .map_err(db_error)?, + "refresh_token" => sqlx::query_scalar!( + "SELECT user_email FROM mcp_oauth_refresh_token WHERE refresh_token = $1", + req.refresh_token.as_deref().unwrap_or_default() + ) + .fetch_optional(&db) + .await + .map_err(db_error)?, + _ => { + return Err(OAuthTokenError::unsupported_grant_type( + "Supported grant types: authorization_code, refresh_token", + )) + } + }; + let mut tx = db.begin().await.map_err(db_error)?; + if let Some(email) = &owner { + crate::users::lock_mcp_oauth_grants(&mut tx, email, false) + .await + .map_err(db_error)?; + } + let res = if req.grant_type == "authorization_code" { + handle_authorization_code_grant(&mut tx, &req).await + } else { + handle_refresh_token_grant(&mut tx, &req).await + }; + // Committed on error too, so a rejected exchange still consumes its code or refresh token. + let committed = tx.commit().await; + match (res, committed) { + (Ok(res), Ok(())) => Ok(res), + (Err(e), committed) => { + if let Err(ce) = committed { + tracing::error!("Failed to commit rejected MCP OAuth exchange: {}", ce); + } + Err(e) + } + (Ok(_), Err(e)) => Err(db_error(e)), } } /// Handle authorization_code grant type async fn handle_authorization_code_grant( - db: &DB, + tx: &mut sqlx::PgConnection, req: &TokenRequest, ) -> std::result::Result, OAuthTokenError> { let auth_code = match sqlx::query_as!( @@ -387,7 +439,7 @@ async fn handle_authorization_code_grant( code_challenge, code_challenge_method", req.code ) - .fetch_optional(db) + .fetch_optional(&mut *tx) .await { Ok(Some(code)) => code, @@ -458,7 +510,7 @@ async fn handle_authorization_code_grant( &scopes, auth_code.workspace_id, ) - .execute(db) + .execute(&mut *tx) .await .map_err(|e| { tracing::error!("Failed to create access token: {}", e); @@ -471,7 +523,7 @@ async fn handle_authorization_code_grant( } // Create refresh token — store the hash of the access token so we can delete it later - let refresh_token_result = sqlx::query!( + sqlx::query!( "INSERT INTO mcp_oauth_refresh_token (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval)", @@ -484,29 +536,25 @@ async fn handle_authorization_code_grant( token_family, MCP_OAUTH_REFRESH_TOKEN_EXPIRATION_SECS.to_string(), ) - .execute(db) - .await; - - let refresh_token_value = match refresh_token_result { - Ok(_) => Some(refresh_token), - Err(e) => { - tracing::error!("Failed to create refresh token: {}", e); - None // Don't include invalid refresh token - } - }; + .execute(&mut *tx) + .await + .map_err(|e| { + tracing::error!("Failed to create refresh token: {}", e); + OAuthTokenError::server_error("Failed to create refresh token") + })?; Ok(Json(TokenResponse { access_token, token_type: "Bearer".to_string(), expires_in: MCP_OAUTH_TOKEN_EXPIRATION_SECS, scope: Some(scopes.join(" ")), - refresh_token: refresh_token_value, + refresh_token: Some(refresh_token), })) } /// Handle refresh_token grant type with token rotation and theft detection async fn handle_refresh_token_grant( - db: &DB, + tx: &mut sqlx::PgConnection, req: &TokenRequest, ) -> std::result::Result, OAuthTokenError> { let refresh_token_value = req @@ -533,7 +581,7 @@ async fn handle_refresh_token_grant( refresh_token_value, req.client_id ) - .fetch_optional(db) + .fetch_optional(&mut *tx) .await { Ok(Some(row)) => row, @@ -544,7 +592,7 @@ async fn handle_refresh_token_grant( WHERE refresh_token = $1 AND used_at IS NOT NULL", refresh_token_value ) - .fetch_optional(db) + .fetch_optional(&mut *tx) .await { tracing::warn!("Refresh token reuse detected, revoking family {:?}", family); @@ -552,7 +600,7 @@ async fn handle_refresh_token_grant( "UPDATE mcp_oauth_refresh_token SET revoked = TRUE WHERE token_family = $1", family ) - .execute(db) + .execute(&mut *tx) .await; } return Err(OAuthTokenError::invalid_grant("Invalid refresh token")); @@ -564,16 +612,16 @@ async fn handle_refresh_token_grant( }; // Delete old access token using the stored hash - if let Err(e) = sqlx::query!( + sqlx::query!( "DELETE FROM token WHERE token_hash = $1", token_row.access_token_hash ) - .execute(db) + .execute(&mut *tx) .await - { + .map_err(|e| { tracing::error!("Failed to delete old access token: {}", e); - // Non-fatal, continue with token creation - } + OAuthTokenError::server_error("Database error") + })?; // Generate new tokens let new_access_token = rd_string(32); @@ -605,7 +653,7 @@ async fn handle_refresh_token_grant( &scopes, token_row.workspace_id, ) - .execute(db) + .execute(&mut *tx) .await .map_err(|e| { tracing::error!("Failed to create new access token: {}", e); @@ -618,7 +666,7 @@ async fn handle_refresh_token_grant( } // Create new refresh token (same token family for tracking) — store hash of access token - if let Err(e) = sqlx::query!( + sqlx::query!( "INSERT INTO mcp_oauth_refresh_token (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval)", @@ -631,12 +679,12 @@ async fn handle_refresh_token_grant( token_row.token_family, MCP_OAUTH_REFRESH_TOKEN_EXPIRATION_SECS.to_string(), ) - .execute(db) + .execute(&mut *tx) .await - { + .map_err(|e| { tracing::error!("Failed to create new refresh token: {}", e); - // Access token was created, return success without refresh token - } + OAuthTokenError::server_error("Failed to create refresh token") + })?; Ok(Json(TokenResponse { access_token: new_access_token, @@ -758,10 +806,31 @@ async fn oauth_authorize_inner( } /// Shared approve logic — validates form, checks membership, stores auth code. +async fn ensure_member(db: &DB, workspace_id: &str, email: &str) -> Result<()> { + let is_member = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled)", + workspace_id, + email + ) + .fetch_one(db) + .await + .map_err(|e| Error::InternalErr(format!("Database error: {}", e)))? + .unwrap_or(false); + + if !is_member { + return Err(Error::NotAuthorized(format!( + "User is not a member of workspace '{workspace_id}'" + ))); + } + Ok(()) +} + +/// `workspace_id` is the workspace the minted token is bound to; without one, the token +/// reaches what its scopes allow (`mcp:workspaces:`), or every workspace of its owner. async fn oauth_approve_inner( db: &DB, authed: &ApiAuthed, - workspace_id: &str, + workspace_id: Option<&str>, form: ApprovalForm, ) -> Result> { // The code approved here is exchanged for a database token carrying only this @@ -771,21 +840,8 @@ async fn oauth_approve_inner( // the gateway approve route reach the exchange through here. forbid_elevated_job_token(db, &authed.email, authed.job_id).await?; - // Verify user is a member of the workspace - let is_member = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled)", - workspace_id, - authed.email - ) - .fetch_one(db) - .await - .map_err(|e| Error::InternalErr(format!("Database error: {}", e)))? - .unwrap_or(false); - - if !is_member { - return Err(Error::NotAuthorized( - "User is not a member of this workspace".to_string(), - )); + if let Some(workspace_id) = workspace_id { + ensure_member(db, workspace_id, &authed.email).await?; } // Verify client exists and redirect_uri is registered @@ -825,11 +881,14 @@ async fn oauth_approve_inner( let code = format!("mcp-code-{}", rd_string(32)); - let scopes: Vec = form + let mut scopes: Vec = form .scope .split_whitespace() .map(|s| s.to_string()) .collect(); + if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) { + scopes.push(SESSION_SCOPE.to_string()); + } // The approver's own token bounds what it may grant: a scope-restricted MCP // token must not approve a broader one (e.g. mcp:scripts:f/x -> mcp:all). An @@ -908,7 +967,7 @@ pub async fn workspaced_oauth_approve( authed: ApiAuthed, Json(form): Json, ) -> Result> { - oauth_approve_inner(&db, &authed, &workspace_id, form).await + oauth_approve_inner(&db, &authed, Some(&workspace_id), form).await } /// PKCE validation (S256 only) @@ -990,6 +1049,16 @@ pub async fn gateway_protected_resource_metadata() -> Json Json { + let base_url = BASE_URL.load(); + Json(build_protected_resource_metadata( + "/api/mcp", + "/api/mcp/gateway/oauth/server", + &base_url, + )) +} + /// GET /api/mcp/gateway/oauth/server/authorize — gateway mode (no workspace in path) pub async fn gateway_oauth_authorize( Extension(db): Extension, @@ -998,23 +1067,44 @@ pub async fn gateway_oauth_authorize( oauth_authorize_inner(&db, params, None).await } -/// POST /api/mcp/gateway/oauth/server/approve — workspace_id comes from JSON body +/// POST /api/mcp/gateway/oauth/server/approve — the workspaces come from the JSON body pub async fn gateway_oauth_approve( Extension(db): Extension, authed: ApiAuthed, Json(form): Json, ) -> Result> { - if form.workspace_id.is_empty() { - return Err(Error::BadRequest("workspace_id is required".to_string())); + let mut scope = form.scope; + let mut workspace_ids = form.workspace_ids; + if workspace_ids.is_empty() { + workspace_ids.extend(form.workspace_id); } + let workspace_id = if form.all_workspaces { + None + } else { + match workspace_ids.as_slice() { + [] => { + return Err(Error::BadRequest( + "Pick at least one workspace, or all of them".to_string(), + )) + } + [only] => Some(only.as_str()), + several => { + for workspace_id in several { + ensure_member(&db, workspace_id, &authed.email).await?; + } + scope.push_str(&format!(" mcp:workspaces:{}", several.join(","))); + None + } + } + }; oauth_approve_inner( &db, &authed, - &form.workspace_id, + workspace_id, ApprovalForm { client_id: form.client_id, redirect_uri: form.redirect_uri, - scope: form.scope, + scope, state: form.state, code_challenge: form.code_challenge, code_challenge_method: form.code_challenge_method, @@ -1023,7 +1113,8 @@ pub async fn gateway_oauth_approve( .await } -/// Gateway approval form — same as ApprovalForm but includes workspace_id +/// Gateway approval form — same as ApprovalForm, plus the workspaces the token reaches: +/// one binds the token to it, several are listed in its scopes. #[derive(Debug, Deserialize)] pub struct GatewayApprovalForm { pub client_id: String, @@ -1032,7 +1123,14 @@ pub struct GatewayApprovalForm { pub state: String, pub code_challenge: String, pub code_challenge_method: String, - pub workspace_id: String, + #[serde(default)] + pub workspace_ids: Vec, + /// The single workspace a consent page loaded before `workspace_ids` existed sends. + #[serde(default)] + pub workspace_id: Option, + /// Every workspace the user is a member of, including ones they join later. + #[serde(default)] + pub all_workspaces: bool, } // ── Router constructors ── diff --git a/backend/windmill-api/src/mcp/session/apps.rs b/backend/windmill-api/src/mcp/session/apps.rs new file mode 100644 index 0000000000..66ad43de47 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/apps.rs @@ -0,0 +1,1282 @@ +//! Raw app drafts: files, backend runnables and their test runs. + +use std::cmp::Ordering; +use std::collections::HashSet; +use std::sync::LazyLock; + +use serde_json::{json, Map, Value}; +use sha2::{Digest, Sha256}; + +use super::runs::finish_run; +use super::workspace::{ + api_message, app_source_to_draft_value, deployed_item_exists, find_and_replace, get_deployed, + get_draft, item_exists, normalize_app_draft, path_enc, persist_draft, Persist, +}; +use super::{ + bool_arg, js_head, js_len, matches_glob, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult, +}; + +// `init_app` is dispatched below but stays out of this list until `gen/app_templates.json` +// is emitted by the generator. +pub(super) const TOOLS: &[&str] = &[ + "init_app", + "read_app_file", + "search_app", + "write_app_file", + "delete_app_file", + "patch_app_file", + "write_app_runnable", + "delete_app_runnable", + "test_run_app_runnable", +]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "init_app" => init_app(ctx, args).await, + "read_app_file" => read_app_file(ctx, args).await, + "search_app" => search_app(ctx, args).await, + "write_app_file" => write_app_file(ctx, args).await, + "delete_app_file" => delete_app_file(ctx, args).await, + "patch_app_file" => patch_app_file(ctx, args).await, + "write_app_runnable" => write_app_runnable(ctx, args).await, + "delete_app_runnable" => delete_app_runnable(ctx, args).await, + "test_run_app_runnable" => test_run_app_runnable(ctx, args).await, + _ => unreachable!("{name} is not a apps tool"), + } +} + +const GENERATED_FILE: &str = "/wmill.d.ts"; + +const READ_DEFAULT_LINE_LIMIT: i64 = 1500; +const READ_CHAR_BUDGET: usize = 50_000; + +const SEARCH_DEFAULT_MAX_MATCHES: i64 = 100; +const SEARCH_MAX_MATCHES_CEILING: i64 = 200; +const SEARCH_MAX_LINE_CHARS: usize = 200; +const SEARCH_TOTAL_CHAR_BUDGET: usize = 12_000; +const SEARCH_CONTEXT_LINES: usize = 2; + +const MAX_TOOL_ERROR_LENGTH: usize = 2000; + +/// `{templates: {: {: content}}, starter_runnables: {: runnable}}`, +/// the frontend's `FRAMEWORK_TEMPLATES` and `STARTER_RUNNABLES`. +static APP_TEMPLATES: LazyLock = LazyLock::new(|| { + serde_json::from_str(include_str!("gen/app_templates.json")) + .expect("gen/app_templates.json is valid") +}); + +// --------------------------------------------------------------------------- +// JS-shaped helpers +// --------------------------------------------------------------------------- + +fn entries(value: &Value, key: &str) -> Map { + value + .get(key) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default() +} + +/// The object under `key`, created (or replacing a non-object) when missing. +fn object_mut<'a>(value: &'a mut Value, key: &str) -> &'a mut Map { + let slot = &mut value[key]; + if !slot.is_object() { + *slot = json!({}); + } + slot.as_object_mut().expect("just made an object") +} + +fn text_of<'a>(value: &'a Value, key: &str) -> Option<&'a str> { + value.get(key).and_then(Value::as_str) +} + +fn is_inline(runnable: &Value) -> bool { + matches!(text_of(runnable, "type"), Some("inline" | "runnableByName")) +} + +fn is_by_path(runnable: &Value) -> bool { + matches!(text_of(runnable, "type"), Some("path" | "runnableByPath")) +} + +// --------------------------------------------------------------------------- +// File targets +// --------------------------------------------------------------------------- + +enum Target { + Frontend(String), + Backend { file_path: String, key: String, extension: &'static str }, +} + +impl Target { + fn file_path(&self) -> &str { + match self { + Target::Frontend(file_path) | Target::Backend { file_path, .. } => file_path, + } + } +} + +fn resolve_target(raw: &str) -> Target { + let trimmed = raw.trim(); + let backend = trimmed.strip_prefix("backend/").and_then(|rest| { + let (key, extension) = rest + .strip_suffix("/main.ts") + .map(|key| (key, "ts")) + .or_else(|| rest.strip_suffix("/main.py").map(|key| (key, "py")))?; + (!key.is_empty() && !key.contains('/')).then_some((key, extension)) + }); + match backend { + Some((key, extension)) => { + Target::Backend { file_path: trimmed.to_string(), key: key.to_string(), extension } + } + None if trimmed.starts_with('/') => Target::Frontend(trimmed.to_string()), + None => Target::Frontend(format!("/{trimmed}")), + } +} + +fn assert_not_generated(file_path: &str) -> Result<(), String> { + if file_path == GENERATED_FILE { + return Err(format!( + "\"{file_path}\" is generated automatically from backend runnables and cannot be modified directly." + )); + } + Ok(()) +} + +fn inline_extension(runnable: &Value) -> &'static str { + let language = runnable.get("inlineScript").and_then(|s| s.get("language")); + if language.and_then(Value::as_str) == Some("python3") { + "py" + } else { + "ts" + } +} + +/// The inline script behind a `backend//main.` target, and its runnable. +fn inline_runnable_content<'a>( + value: &'a Value, + key: &str, + extension: &str, + app_path: &str, +) -> Result<(&'a str, &'a Value), String> { + let runnable = value + .get("runnables") + .and_then(|r| r.get(key)) + .filter(|r| truthy(Some(r))) + .ok_or_else(|| format!("Backend runnable \"{key}\" not found in app \"{app_path}\"."))?; + if !is_inline(runnable) { + return Err(format!( + "Runnable \"{key}\" is not inline. Use read_workspace_item on the referenced {} instead.", + text_of(runnable, "runType").unwrap_or("item") + )); + } + let expected = inline_extension(runnable); + if extension != expected { + return Err(format!( + "Runnable \"{key}\" language is {expected}. Use backend/{key}/main.{expected}." + )); + } + let content = runnable + .get("inlineScript") + .and_then(|s| text_of(s, "content")) + .unwrap_or_default(); + Ok((content, runnable)) +} + +// --------------------------------------------------------------------------- +// Loading and saving the draft +// --------------------------------------------------------------------------- + +struct Loaded { + value: Value, + last_sync: Option, +} + +/// The caller's draft of the app, else the deployed app shaped as one. +async fn load_app(ctx: &Ctx<'_>, path: &str) -> Result { + let draft = get_draft(ctx, "raw_app", path).await?; + let mut last_sync = None; + if let Some(draft) = draft { + if draft.value.get("files").is_some() { + return Ok(Loaded { value: draft.value, last_sync: draft.created_at }); + } + last_sync = draft.created_at; + } + let app = get_deployed(ctx, "app", None, path) + .await + .map_err(|e| api_message(&e).to_string())?; + // Only an explicit false: an app known by its draft alone carries no version, so no + // `raw_app`, and must not read as low-code. + if app.get("raw_app") == Some(&Value::Bool(false)) { + return Err(format!( + "\"{path}\" is a low-code app. This chat only edits code-based apps — open it in the app editor instead." + )); + } + Ok(Loaded { value: app_source_to_draft_value(&app, Some(&app)), last_sync }) +} + +/// What the backend requires of a draft from an operator with builder rights: sandboxed, +/// never in viewer mode, and running as nobody but its builder. +async fn conform_builder_policy(ctx: &Ctx<'_>, value: &mut Value) { + if !ctx.auth.is_operator { + return; + } + let Ok(memberships) = ctx.get("/workspaces/users").await else { + return; + }; + let builder = memberships + .get("workspaces") + .and_then(Value::as_array) + .and_then(|list| list.iter().find(|w| text_of(w, "id") == Some(ctx.w_id))) + .and_then(|w| w.get("operator_settings")) + .and_then(|s| s.get("builder_apps")) + == Some(&Value::Bool(true)); + if !builder { + return; + } + let policy = object_mut(value, "policy"); + policy.insert("sandbox".into(), json!(true)); + if policy.get("execution_mode").and_then(Value::as_str) == Some("viewer") { + policy.insert("execution_mode".into(), json!("publisher")); + } + let username = &ctx.auth.username; + let this_user = if username.contains('@') { + username.clone() + } else { + format!("u/{username}") + }; + let differs = |key: &str, own: &str| { + policy + .get(key) + .is_some_and(|v| !v.is_null() && v.as_str() != Some(own)) + }; + if differs("on_behalf_of", &this_user) || differs("on_behalf_of_email", &ctx.auth.email) { + policy.shift_remove("on_behalf_of"); + policy.shift_remove("on_behalf_of_email"); + } +} + +/// Save the draft and report: the success JSON, or the conflict / failed-save JSON. +async fn save_app( + ctx: &Ctx<'_>, + path: &str, + mut value: Value, + last_sync: Option<&str>, + message: String, + warning: Option, +) -> ToolResult { + conform_builder_policy(ctx, &mut value).await; + let value = normalize_app_draft(&value); + match persist_draft(ctx, "app", path, None, &value, last_sync, false).await? { + Persist::Failed(text) => Ok(text), + Persist::Saved(_) => { + let mut out = Map::new(); + out.insert("success".into(), json!(true)); + out.insert("message".into(), json!(message)); + out.insert( + "preview_url".into(), + json!(ctx.page_url(&format!( + "/apps_raw/edit/{path}?view=preview&nomenubar=true" + ))), + ); + if let Some(warning) = warning { + out.insert("warning".into(), json!(warning)); + } + Ok(pretty(&Value::Object(out))) + } + } +} + +fn sha256_hex(text: &str) -> String { + hex::encode(Sha256::digest(text.as_bytes())) +} + +/// Rebuild `policy.triggerables_v2` from the runnables: the key names what a runnable +/// may execute (an inline script by the hash of its code), the entry which of its inputs +/// the caller cannot set. +fn recompute_policy(value: &mut Value) { + let mut triggerables = Map::new(); + for (id, runnable) in entries(value, "runnables") { + let target = if is_inline(&runnable) { + let content = runnable + .get("inlineScript") + .and_then(|s| text_of(s, "content")) + .unwrap_or_default(); + format!("rawscript/{}", sha256_hex(content)) + } else if is_by_path(&runnable) { + let run_type = match text_of(&runnable, "runType") { + Some("hubscript") => "script", + Some(other) => other, + None => "undefined", + }; + format!( + "{run_type}/{}", + text_of(&runnable, "path").unwrap_or("undefined") + ) + } else { + continue; + }; + let fields = entries(&runnable, "fields"); + let flagged = |flag: &str| -> Vec<&String> { + fields + .iter() + .filter(|(_, field)| truthy(field.get(flag))) + .map(|(name, _)| name) + .collect() + }; + let static_inputs: Map = fields + .iter() + .filter(|(_, field)| text_of(field, "type") == Some("static")) + .filter_map(|(name, field)| Some((name.clone(), field.get("value")?.clone()))) + .collect(); + let mut entry = Map::new(); + entry.insert("static_inputs".into(), Value::Object(static_inputs)); + entry.insert("one_of_inputs".into(), json!({})); + entry.insert( + "allow_user_resources".into(), + json!(flagged("allowUserResources")), + ); + if let Some(secs) = runnable + .get("delete_after_secs") + .filter(|s| s.as_f64().is_some_and(|s| s >= 0.0)) + { + entry.insert("delete_after_secs".into(), secs.clone()); + } + let sensitive = flagged("sensitive"); + if !sensitive.is_empty() { + entry.insert("sensitive_inputs".into(), json!(sensitive)); + } + if let Some(tag) = runnable + .get("inlineScript") + .and_then(|s| s.get("tag")) + .filter(|tag| truthy(Some(tag))) + { + entry.insert("tag".into(), tag.clone()); + } + // The server honors it on inline runnables only, whose code is deployed with the app. + if is_inline(&runnable) && runnable.get("viewer_data_access") == Some(&Value::Bool(true)) { + entry.insert("viewer_data_access".into(), json!(true)); + } + triggerables.insert(format!("{id}:{target}"), Value::Object(entry)); + } + let policy = object_mut(value, "policy"); + policy.insert("triggerables_v2".into(), Value::Object(triggerables)); + if !truthy(policy.get("execution_mode")) { + policy.insert("execution_mode".into(), json!("publisher")); + } +} + +// --------------------------------------------------------------------------- +// init_app +// --------------------------------------------------------------------------- + +/// A table reference canonicalized to `/` or `/:
`. +/// A bare name is a table of the app's own schema. +fn app_table_ref(datatable: &str, schema: Option<&str>, reference: &str) -> String { + if reference.contains('/') { + return reference.to_string(); + } + let separator = if reference.contains(':') { ':' } else { '.' }; + let (schema, table) = match reference.split_once(separator) { + Some((schema, table)) => (Some(schema), table), + None => (schema, reference), + }; + match schema { + _ if table.is_empty() => datatable.to_string(), + None | Some("" | "public") => format!("{datatable}/{table}"), + Some(schema) => format!("{datatable}/{schema}:{table}"), + } +} + +async fn init_app(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let framework = str_arg(args, "framework")?; + let template = APP_TEMPLATES["templates"] + .get(framework) + .ok_or_else(|| format!("Invalid framework \"{framework}\""))?; + + if get_draft(ctx, "raw_app", path).await?.is_some() { + return Err(format!( + "A draft for app \"{path}\" already exists. Use write_app_file / write_app_runnable to modify it, or delete the existing draft first." + )); + } + if item_exists(ctx, "app", None, path).await? { + return Err(format!( + "An app already exists at \"{path}\". Use read_workspace_item + write_app_file / write_app_runnable to modify it." + )); + } + + let starters = &APP_TEMPLATES["starter_runnables"]; + let mut value = Map::new(); + if let Some(summary) = opt_str_arg(args, "summary") { + value.insert("summary".into(), json!(summary)); + } + value.insert("files".into(), template.clone()); + value.insert("runnables".into(), starters.clone()); + value.insert("policy".into(), json!({ "sandbox": true })); + let data = args.get("data").filter(|d| truthy(Some(d))); + let schema = data.and_then(|d| text_of(d, "schema")); + let datatable = data + .and_then(|d| text_of(d, "datatable")) + .unwrap_or_default(); + if let Some(data) = data { + let tables: Vec = data + .get("tables") + .and_then(Value::as_array) + .map(|tables| { + tables + .iter() + .filter_map(Value::as_str) + .map(|reference| app_table_ref(datatable, schema, reference)) + .collect() + }) + .unwrap_or_default(); + let mut out = Map::new(); + out.insert("tables".into(), json!(tables)); + out.insert("datatable".into(), json!(datatable)); + if let Some(schema) = schema { + out.insert("schema".into(), json!(schema)); + } + value.insert("data".into(), Value::Object(out)); + } + let mut value = Value::Object(value); + recompute_policy(&mut value); + + let starter_keys: Vec<&str> = starters + .as_object() + .map(|s| s.keys().map(String::as_str).collect()) + .unwrap_or_default(); + let data_note = match schema.filter(|s| !s.is_empty()) { + Some(schema) => format!(" Its data config names schema \"{schema}\" of data table \"{datatable}\" without creating it: if it does not exist yet, create it before the tables that go in it."), + None => String::new(), + }; + let message = format!( + "Initialized a per-user draft app \"{path}\" from the {framework} template (saved server-side, not a deployed workspace item). The template is a demo tour with starter runnables {}: replace its UI and delete the runnables the app does not need (delete_app_runnable). Use write_app_file / write_app_runnable to evolve it.{data_note} Open preview_url in a browser the user can see from this conversation if you have one, and otherwise give them the link: its live preview follows every later edit.", + starter_keys.join(", ") + ); + save_app(ctx, path, value, None, message, None).await +} + +// --------------------------------------------------------------------------- +// read_app_file +// --------------------------------------------------------------------------- + +fn format_file_read(content: &str, offset: Option, limit: Option) -> String { + let lines: Vec<&str> = content.split('\n').collect(); + let total = lines.len(); + let requested_start = offset.unwrap_or(1); + let start = (requested_start.saturating_sub(1).max(0) as usize).min(total); + let line_limit = limit.unwrap_or(READ_DEFAULT_LINE_LIMIT).max(0) as usize; + let end = start.saturating_add(line_limit).min(total); + let window = lines[start..end].join("\n"); + let window_chars = js_len(&window); + let char_truncated = window_chars > READ_CHAR_BUDGET; + let body = js_head(&window, READ_CHAR_BUDGET); + + if requested_start > total as i64 { + return format!("offset {requested_start} is past the end of the file ({total} lines)."); + } + if start == 0 && end == total && !char_truncated { + return body.to_string(); + } + let mut label = format!("lines {}-{end} of {total}", start + 1); + let mut more = String::new(); + if char_truncated { + label.push_str(&format!( + ", truncated to the first {READ_CHAR_BUDGET} of {window_chars} chars" + )); + more = format!(" Reached the {READ_CHAR_BUDGET}-char limit; re-read with a smaller limit (fewer lines). If a single line exceeds the limit the file is likely minified and not readable this way."); + } else if end < total { + more = format!( + " Call read_app_file again with offset={} to continue.", + end + 1 + ); + } + format!("{label}.{more}\n\n{body}") +} + +async fn read_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let target = resolve_target(str_arg(args, "file_path")?); + let value = load_app(ctx, path).await?.value; + let content = match &target { + Target::Frontend(file_path) => value + .get("files") + .and_then(|files| text_of(files, file_path)) + .ok_or_else(|| format!("Frontend file \"{file_path}\" not found in app \"{path}\"."))?, + Target::Backend { key, extension, .. } => { + inline_runnable_content(&value, key, extension, path)?.0 + } + }; + let int = |name: &str| args.get(name).and_then(Value::as_i64); + Ok(format_file_read(content, int("offset"), int("limit"))) +} + +// --------------------------------------------------------------------------- +// search_app +// --------------------------------------------------------------------------- + +/// Frontend files (the generated one aside) and inline runnables, each under the path +/// `read_app_file` takes. +fn searchable_files(value: &Value) -> Vec<(String, String)> { + let mut files: Vec<(String, String)> = entries(value, "files") + .into_iter() + .filter(|(file_path, _)| file_path != GENERATED_FILE) + .filter_map(|(file_path, content)| Some((file_path, content.as_str()?.to_string()))) + .collect(); + for (key, runnable) in entries(value, "runnables") { + let Some(content) = runnable + .get("inlineScript") + .and_then(|s| text_of(s, "content")) + else { + continue; + }; + files.push(( + format!("backend/{key}/main.{}", inline_extension(&runnable)), + content.to_string(), + )); + } + files +} + +// ponytail: approximates `localeCompare` (punctuation, then digits, then letters, case +// ignored until a tie) rather than full ICU collation; only the order files are listed in +// depends on it. +fn locale_compare(a: &str, b: &str) -> Ordering { + let key = |text: &str| -> Vec<(u8, char)> { + text.chars() + .flat_map(char::to_lowercase) + .map(|c| { + let class = if c.is_alphabetic() { + 2 + } else if c.is_numeric() { + 1 + } else { + 0 + }; + (class, c) + }) + .collect() + }; + key(a).cmp(&key(b)).then_with(|| b.cmp(a)) +} + +fn search_files( + mut files: Vec<(String, String)>, + query: &str, + file_glob: Option<&str>, + max_matches: i64, +) -> String { + let needle = query.to_lowercase(); + files.sort_by(|a, b| locale_compare(&a.0, &b.0)); + if let Some(glob) = file_glob { + files.retain(|(file_path, _)| matches_glob(file_path, glob)); + } + + // (file, 1-based line, text) rows: every matching line with its context window. + let mut rows: Vec<(&str, usize, &str)> = Vec::new(); + let (mut total, mut rendered, mut file_count, mut truncated) = (0usize, 0i64, 0usize, false); + for (file_path, content) in &files { + let lines: Vec<&str> = content.split('\n').collect(); + let mut file_had_match = false; + for (i, line) in lines.iter().enumerate() { + if !line.to_lowercase().contains(&needle) { + continue; + } + total += 1; + file_had_match = true; + if rendered >= max_matches { + truncated = true; + continue; + } + rendered += 1; + let lo = i.saturating_sub(SEARCH_CONTEXT_LINES); + let hi = (i + SEARCH_CONTEXT_LINES).min(lines.len() - 1); + for j in lo..=hi { + rows.push((file_path, j + 1, lines[j])); + } + } + if file_had_match { + file_count += 1; + } + } + + if total == 0 { + return format!( + "No matches. Try a broader or differently-spelled term{}.", + if file_glob.is_some() { + ", or drop the file_glob" + } else { + "" + } + ); + } + + let plural = |n: usize, one: &str, many: &str| { + if n == 1 { + one.to_string() + } else { + many.to_string() + } + }; + let header = format!( + "{total} {} in {file_count} {}{}", + plural(total, "match", "matches"), + plural(file_count, "file", "files"), + if truncated { + format!(" (showing the first {max_matches}; narrow with file_glob or a more specific query)") + } else { + String::new() + } + ); + + let mut spent = js_len(&header); + let mut out = vec![header]; + let mut current_file = ""; + let mut budget_hit = false; + let mut seen = HashSet::new(); + for (file_path, line, text) in rows { + if !seen.insert((file_path, line)) { + continue; + } + let text = if js_len(text) > SEARCH_MAX_LINE_CHARS { + format!("{}… [line truncated]", js_head(text, SEARCH_MAX_LINE_CHARS)) + } else { + text.to_string() + }; + let new_file = file_path != current_file; + let row = if new_file { + format!("{file_path}\n {line}: {text}") + } else { + format!(" {line}: {text}") + }; + if spent + js_len(&row) + 1 > SEARCH_TOTAL_CHAR_BUDGET { + budget_hit = true; + break; + } + if new_file { + current_file = file_path; + } + spent += js_len(&row) + 1; + out.push(row); + } + if budget_hit { + out.push( + "… output truncated at the context budget — narrow with file_glob or a more specific query." + .to_string(), + ); + } + out.join("\n") +} + +async fn search_app(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let query = str_arg(args, "query")?; + if query.is_empty() { + return Err("search_app requires a non-empty query.".to_string()); + } + let value = load_app(ctx, path).await?.value; + let max_matches = args + .get("max_matches") + .and_then(Value::as_i64) + .unwrap_or(SEARCH_DEFAULT_MAX_MATCHES) + .min(SEARCH_MAX_MATCHES_CEILING); + let file_glob = opt_str_arg(args, "file_glob").filter(|glob| !glob.is_empty()); + Ok(search_files( + searchable_files(&value), + query, + file_glob, + max_matches, + )) +} + +// --------------------------------------------------------------------------- +// File writes +// --------------------------------------------------------------------------- + +async fn write_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let content = str_arg(args, "content")?; + let Target::Frontend(file_path) = resolve_target(str_arg(args, "file_path")?) else { + return Err("write_app_file only writes frontend files. Use write_app_runnable to set inline backend script content.".to_string()); + }; + assert_not_generated(&file_path)?; + + let Loaded { mut value, last_sync } = load_app(ctx, path).await?; + object_mut(&mut value, "files").insert(file_path.clone(), json!(content)); + let message = format!("Updated draft app \"{path}\" with frontend file \"{file_path}\"."); + save_app(ctx, path, value, last_sync.as_deref(), message, None).await +} + +async fn delete_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let Target::Frontend(file_path) = resolve_target(str_arg(args, "file_path")?) else { + return Err("delete_app_file only deletes frontend files. Use delete_app_runnable for backend runnables.".to_string()); + }; + assert_not_generated(&file_path)?; + + let Loaded { mut value, last_sync } = load_app(ctx, path).await?; + if object_mut(&mut value, "files") + .shift_remove(&file_path) + .is_none() + { + return Err(format!( + "Frontend file \"{file_path}\" not found in app \"{path}\"." + )); + } + let message = format!("Removed \"{file_path}\" from draft app \"{path}\"."); + save_app(ctx, path, value, last_sync.as_deref(), message, None).await +} + +async fn patch_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let old = str_arg(args, "old_string")?; + let new = str_arg(args, "new_string")?; + let replace_all = bool_arg(args, "replace_all"); + let target = resolve_target(str_arg(args, "file_path")?); + if let Target::Frontend(file_path) = &target { + assert_not_generated(file_path)?; + } + + let Loaded { mut value, last_sync } = load_app(ctx, path).await?; + let label = format!("{} content", target.file_path()); + match &target { + Target::Frontend(file_path) => { + let current = value + .get("files") + .and_then(|files| text_of(files, file_path)) + .ok_or_else(|| { + format!("Frontend file \"{file_path}\" not found in app \"{path}\".") + })?; + let updated = find_and_replace(current, old, new, replace_all, &label)?; + object_mut(&mut value, "files").insert(file_path.clone(), json!(updated)); + } + Target::Backend { key, extension, .. } => { + let (current, runnable) = inline_runnable_content(&value, key, extension, path)?; + let updated = find_and_replace(current, old, new, replace_all, &label)?; + let language = runnable + .get("inlineScript") + .and_then(|s| s.get("language")) + .filter(|l| !l.is_null()) + .cloned() + .unwrap_or_else(|| json!(if *extension == "py" { "python3" } else { "bun" })); + let mut runnable = runnable.clone(); + runnable["inlineScript"] = json!({ "language": language, "content": updated }); + object_mut(&mut value, "runnables").insert(key.clone(), runnable); + } + } + let message = format!( + "Patched \"{}\" in draft app \"{path}\".", + target.file_path() + ); + save_app(ctx, path, value, last_sync.as_deref(), message, None).await +} + +// --------------------------------------------------------------------------- +// Runnable writes +// --------------------------------------------------------------------------- + +/// The stored runnable for a `write_app_runnable` input. Converting between kinds drops +/// the other kind's fields, and a path runnable's `schema` survives only while its target +/// is unchanged: it describes the item pointed at. `viewer_data_access` is inline-only. +fn build_persisted_runnable(input: &Value, existing: Option<&Value>) -> Result { + let name = str_arg(input, "name")?; + let kind = str_arg(input, "type")?; + let existing = existing.and_then(Value::as_object); + let fields = match input.get("staticInputs").and_then(Value::as_object) { + Some(static_inputs) => Value::Object( + static_inputs + .iter() + .map(|(k, v)| { + ( + k.clone(), + json!({ "type": "static", "value": v, "fieldType": "object" }), + ) + }) + .collect(), + ), + None => existing + .and_then(|e| e.get("fields")) + .filter(|f| !f.is_null()) + .cloned() + .unwrap_or_else(|| json!({})), + }; + let mut out = existing.cloned().unwrap_or_default(); + let carried_as_viewer = out.shift_remove("viewer_data_access") == Some(Value::Bool(true)); + for key in ["runType", "path", "inlineScript"] { + out.shift_remove(key); + } + out.insert("name".into(), json!(name)); + + if kind == "inline" { + let inline = input + .get("inlineScript") + .filter(|s| truthy(Some(s))) + .ok_or("inlineScript is required when runnable type is \"inline\".")?; + out.insert("type".into(), json!("inline")); + out.insert( + "inlineScript".into(), + json!({ "content": inline.get("content"), "language": inline.get("language") }), + ); + let viewer_data_access = input + .get("viewerDataAccess") + .and_then(Value::as_bool) + .unwrap_or(carried_as_viewer); + if viewer_data_access { + out.insert("viewer_data_access".into(), json!(true)); + } + out.insert("fields".into(), fields); + return Ok(Value::Object(out)); + } + + let path = text_of(input, "path") + .filter(|p| !p.is_empty()) + .ok_or("path is required when runnable type is \"script\", \"flow\", or \"hubscript\".")?; + let same_target = existing.is_some_and(|e| { + matches!( + e.get("type").and_then(Value::as_str), + Some("path" | "runnableByPath") + ) && e.get("runType").and_then(Value::as_str) == Some(kind) + && e.get("path").and_then(Value::as_str) == Some(path) + }); + let schema = existing + .filter(|_| same_target) + .and_then(|e| e.get("schema")) + .filter(|s| !s.is_null()) + .cloned() + .unwrap_or_else(|| json!({})); + out.insert("type".into(), json!("path")); + out.insert("runType".into(), json!(kind)); + out.insert("path".into(), json!(path)); + out.insert("fields".into(), fields); + out.insert("schema".into(), schema); + Ok(Value::Object(out)) +} + +/// Whether the script or flow a path runnable names is deployed. None when it names +/// neither, or the probe failed: the answer only annotates a write. +async fn path_target_deployed(ctx: &Ctx<'_>, runnable: &Value) -> Option { + let kind = text_of(runnable, "runType").filter(|k| matches!(*k, "script" | "flow"))?; + let path = text_of(runnable, "path").filter(|p| !p.is_empty())?; + deployed_item_exists(ctx, kind, None, path).await.ok() +} + +async fn write_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let key = str_arg(args, "key")?; + let input = args + .get("runnable") + .filter(|r| r.is_object()) + .ok_or("Missing required object argument `runnable`")?; + + let Loaded { mut value, last_sync } = load_app(ctx, path).await?; + let existing = value.get("runnables").and_then(|r| r.get(key)); + let persisted = build_persisted_runnable(input, existing)?; + let warning = match path_target_deployed(ctx, &persisted).await { + Some(false) => Some(format!( + "This runnable points at an item that is NOT deployed (\"{key}\" → {} \"{}\"), so it fails at runtime — a path runnable runs the deployed item, never a draft. Offer to deploy just that item with deploy_workspace_item; the app itself does not need deploying, since the preview runs its draft.", + text_of(&persisted, "runType").unwrap_or_default(), + text_of(&persisted, "path").unwrap_or_default(), + )), + _ => None, + }; + object_mut(&mut value, "runnables").insert(key.to_string(), persisted); + recompute_policy(&mut value); + let message = format!("Updated draft app \"{path}\" with runnable \"{key}\"."); + save_app(ctx, path, value, last_sync.as_deref(), message, warning).await +} + +async fn delete_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let key = str_arg(args, "key")?; + let Loaded { mut value, last_sync } = load_app(ctx, path).await?; + if object_mut(&mut value, "runnables") + .shift_remove(key) + .is_none() + { + return Err(format!( + "Backend runnable \"{key}\" not found in app \"{path}\"." + )); + } + recompute_policy(&mut value); + let message = format!("Removed runnable \"{key}\" from draft app \"{path}\"."); + save_app(ctx, path, value, last_sync.as_deref(), message, None).await +} + +// --------------------------------------------------------------------------- +// test_run_app_runnable +// --------------------------------------------------------------------------- + +/// The `execute_component` body that runs a runnable the way the editor preview does. +fn execute_component_body(app_path: &str, key: &str, runnable: &Value, args: &Value) -> Value { + let fields = entries(runnable, "fields"); + let mut test_args = args.as_object().cloned().unwrap_or_default(); + let mut static_fields = Map::new(); + let mut sensitive = Vec::new(); + for (name, field) in &fields { + match text_of(field, "type") { + Some("static") => { + if let Some(value) = field.get("value") { + static_fields.insert(name.clone(), value.clone()); + } + } + // Filled by the server from `$ctx:`; left out, the argument is missing. + Some("ctx") => { + if let Some(prop) = text_of(field, "ctx").filter(|p| !p.is_empty()) { + test_args.insert(name.clone(), json!(format!("$ctx:{prop}"))); + } + } + Some("user") if truthy(field.get("sensitive")) => sensitive.push(name.clone()), + _ => {} + } + } + + let mut body = Map::new(); + body.insert("component".into(), json!(key)); + body.insert("args".into(), Value::Object(test_args)); + // Sent even when empty: its presence is what puts the server in preview mode, which + // is what lets inline draft code run at all. + body.insert( + "force_viewer_static_fields".into(), + Value::Object(static_fields), + ); + // The server encrypts a queued argument only when it is named here. + if !sensitive.is_empty() { + body.insert("force_viewer_sensitive_inputs".into(), json!(sensitive)); + } + if is_inline(runnable) { + if let Some(inline) = runnable.get("inlineScript").filter(|s| truthy(Some(s))) { + let id = inline.get("id").filter(|id| !id.is_null()); + let mut raw_code = Map::new(); + raw_code.insert( + "content".into(), + if id.is_some() { + json!("") + } else { + inline.get("content").cloned().unwrap_or_default() + }, + ); + raw_code.insert( + "language".into(), + inline + .get("language") + .filter(|l| !l.is_null()) + .cloned() + .unwrap_or_else(|| json!("")), + ); + raw_code.insert("path".into(), json!(format!("{app_path}/{key}"))); + match id { + Some(id) => { + body.insert("id".into(), id.clone()); + } + None => { + if let Some(lock) = inline.get("lock") { + raw_code.insert("lock".into(), lock.clone()); + } + } + } + if let Some(cache_ttl) = inline.get("cache_ttl") { + raw_code.insert("cache_ttl".into(), cache_ttl.clone()); + } + if let Some(tag) = inline.get("tag").filter(|tag| truthy(Some(tag))) { + raw_code.insert("tag".into(), tag.clone()); + } + body.insert("raw_code".into(), Value::Object(raw_code)); + } + } else if is_by_path(runnable) { + let run_type = match text_of(runnable, "runType") { + Some("hubscript") | None => "script", + Some(other) => other, + }; + body.insert( + "path".into(), + json!(format!( + "{run_type}/{}", + text_of(runnable, "path").unwrap_or_default() + )), + ); + } + Value::Object(body) +} + +async fn test_run_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let key = str_arg(args, "key")?; + let value = load_app(ctx, path).await?.value; + let runnables = entries(&value, "runnables"); + let Some(runnable) = runnables.get(key).filter(|r| truthy(Some(r))) else { + let known: Vec<&str> = runnables.keys().map(String::as_str).collect(); + return Err(format!( + "App \"{path}\" has no backend runnable \"{key}\".{}", + if known.is_empty() { + String::new() + } else { + format!(" Available runnables: {}.", known.join(", ")) + } + )); + }; + + let body = execute_component_body( + path, + key, + runnable, + args.get("args").unwrap_or(&Value::Null), + ); + let id = ctx + .request( + "POST", + &ctx.ws(&format!("apps_u/execute_component/{}", path_enc(path))), + Some(body), + ) + .await + .map_err(|e| { + let message = api_message(&e); + let message = if js_len(message) > MAX_TOOL_ERROR_LENGTH { + format!("{}... (truncated)", js_head(message, MAX_TOOL_ERROR_LENGTH)) + } else { + message.to_string() + }; + format!("Failed to execute test run: {message}") + })?; + let id = id.trim().trim_matches('"').to_string(); + + // A path runnable aimed at a flow queues a flow job, whose steps are worth a look. + let is_flow = text_of(runnable, "runType") == Some("flow"); + let label = format!("{path} / {key}"); + finish_run(ctx, Ok(id), &label, is_flow, "test", args).await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn targets_resolve_to_frontend_files_or_inline_runnables() { + assert!(matches!(resolve_target(" App.tsx "), Target::Frontend(p) if p == "/App.tsx")); + assert!(matches!( + resolve_target("backend/a/main.py"), + Target::Backend { key, extension: "py", .. } if key == "a" + )); + // Not the virtual file of a runnable: a frontend path like any other. + assert!(matches!( + resolve_target("backend/a/b/main.ts"), + Target::Frontend(p) if p == "/backend/a/b/main.ts" + )); + } + + #[test] + fn file_reads_are_whole_or_annotated_windows() { + assert_eq!(format_file_read("a\nb", None, None), "a\nb"); + assert_eq!( + format_file_read("a\nb\nc", Some(2), Some(1)), + "lines 2-2 of 3. Call read_app_file again with offset=3 to continue.\n\nb" + ); + assert_eq!( + format_file_read("a\nb\nc", Some(2), None), + "lines 2-3 of 3.\n\nb\nc" + ); + assert_eq!( + format_file_read("a", Some(5), None), + "offset 5 is past the end of the file (1 lines)." + ); + let long = "x".repeat(READ_CHAR_BUDGET + 1); + assert!(format_file_read(&long, None, None).starts_with( + "lines 1-1 of 1, truncated to the first 50000 of 50001 chars. Reached the 50000-char limit;" + )); + } + + #[test] + fn search_caps_matching_lines_and_dedupes_context() { + let files = vec![ + ( + "/b.ts".to_string(), + "one\nFoo()\nfoo()\nfour\nfive\nsix".to_string(), + ), + ("/App.tsx".to_string(), "foo".to_string()), + ]; + assert_eq!( + search_files(files.clone(), "foo", None, 100), + "3 matches in 2 files\n/App.tsx\n 1: foo\n/b.ts\n 1: one\n 2: Foo()\n 3: foo()\n 4: four\n 5: five" + ); + assert_eq!( + search_files(files.clone(), "foo", Some("*.ts"), 1), + "2 matches in 1 file (showing the first 1; narrow with file_glob or a more specific query)\n/b.ts\n 1: one\n 2: Foo()\n 3: foo()\n 4: four" + ); + assert_eq!( + search_files(files, "nope", Some("*.ts"), 100), + "No matches. Try a broader or differently-spelled term, or drop the file_glob." + ); + } + + #[test] + fn globs_match_the_name_or_the_full_path() { + assert!(matches_glob("/components/Button.tsx", "*.tsx")); + assert!(!matches_glob("/components/Button.tsx", "/*.tsx")); + assert!(matches_glob("/components/Button.tsx", "/components/*")); + assert!(matches_glob("backend/a/main.ts", "backend/**")); + assert!(!matches_glob("/a.tsx", "?.ts")); + } + + #[test] + fn runnable_kind_changes_drop_the_other_kinds_fields() { + let existing = json!({ + "name": "old", "type": "path", "runType": "script", "path": "u/a/s", + "fields": { "x": { "type": "static", "value": 1 } }, "schema": { "k": 1 } + }); + let same = build_persisted_runnable( + &json!({ "name": "n", "type": "script", "path": "u/a/s" }), + Some(&existing), + ) + .unwrap(); + assert_eq!(same["schema"], json!({ "k": 1 })); + assert_eq!(same["fields"], existing["fields"]); + + let retargeted = build_persisted_runnable( + &json!({ "name": "n", "type": "flow", "path": "u/a/s" }), + Some(&existing), + ) + .unwrap(); + assert_eq!(retargeted["schema"], json!({})); + + let inline = build_persisted_runnable( + &json!({ + "name": "n", "type": "inline", "staticInputs": { "y": 2 }, + "inlineScript": { "language": "bun", "content": "c" } + }), + Some(&existing), + ) + .unwrap(); + assert!(inline.get("path").is_none() && inline.get("runType").is_none()); + assert_eq!( + inline["fields"], + json!({ "y": { "type": "static", "value": 2, "fieldType": "object" } }) + ); + assert_eq!( + build_persisted_runnable(&json!({ "name": "n", "type": "inline" }), None), + Err("inlineScript is required when runnable type is \"inline\".".to_string()) + ); + } + + #[test] + fn viewer_data_access_is_set_kept_or_cleared_on_inline_runnables_only() { + let inline = |viewer: Value| { + let mut input = json!({ + "name": "n", "type": "inline", + "inlineScript": { "language": "bun", "content": "c" } + }); + if !viewer.is_null() { + input["viewerDataAccess"] = viewer; + } + input + }; + let set = build_persisted_runnable(&inline(json!(true)), None).unwrap(); + assert_eq!(set["viewer_data_access"], json!(true)); + let kept = build_persisted_runnable(&inline(Value::Null), Some(&set)).unwrap(); + assert_eq!(kept["viewer_data_access"], json!(true)); + let cleared = build_persisted_runnable(&inline(json!(false)), Some(&set)).unwrap(); + assert!(cleared.get("viewer_data_access").is_none()); + let by_path = build_persisted_runnable( + &json!({ "name": "n", "type": "script", "path": "u/a/s", "viewerDataAccess": true }), + Some(&set), + ) + .unwrap(); + assert!(by_path.get("viewer_data_access").is_none()); + + let mut value = json!({ "runnables": { "a": set, "b": { + "type": "path", "runType": "script", "path": "u/a/s", "viewer_data_access": true + } } }); + recompute_policy(&mut value); + let triggerables = &value["policy"]["triggerables_v2"]; + let flagged: Vec<&String> = triggerables + .as_object() + .unwrap() + .iter() + .filter(|(_, e)| e["viewer_data_access"] == json!(true)) + .map(|(k, _)| k) + .collect(); + assert_eq!(flagged.len(), 1); + assert!(flagged[0].starts_with("a:rawscript/")); + } + + #[test] + fn policy_keys_inline_runnables_by_the_hash_of_their_code() { + let mut value = json!({ + "runnables": { + "a": { + "type": "inline", "inlineScript": { "content": "", "language": "bun" }, + "fields": { + "s": { "type": "static", "value": 1 }, + "u": { "type": "user", "sensitive": true } + } + }, + "b": { "type": "path", "runType": "hubscript", "path": "hub/1/x" } + }, + "policy": { "on_behalf_of": "u/x", "triggerables_v2": { "stale": {} } } + }); + recompute_policy(&mut value); + assert_eq!( + value["policy"], + json!({ + "on_behalf_of": "u/x", + "triggerables_v2": { + "a:rawscript/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855": { + "static_inputs": { "s": 1 }, "one_of_inputs": {}, + "allow_user_resources": [], "sensitive_inputs": ["u"] + }, + "b:script/hub/1/x": { + "static_inputs": {}, "one_of_inputs": {}, "allow_user_resources": [] + } + }, + "execution_mode": "publisher" + }) + ); + } + + #[test] + fn preview_body_fills_static_ctx_and_sensitive_inputs() { + let runnable = json!({ + "type": "inline", + "inlineScript": { "content": "code", "language": "bun" }, + "fields": { + "s": { "type": "static", "value": 1 }, + "who": { "type": "ctx", "ctx": "username" }, + "pw": { "type": "user", "sensitive": true } + } + }); + assert_eq!( + execute_component_body("u/a/app", "k", &runnable, &json!({ "x": 1 })), + json!({ + "component": "k", + "args": { "x": 1, "who": "$ctx:username" }, + "force_viewer_static_fields": { "s": 1 }, + "force_viewer_sensitive_inputs": ["pw"], + "raw_code": { "content": "code", "language": "bun", "path": "u/a/app/k" } + }) + ); + let by_path = json!({ "type": "path", "runType": "flow", "path": "u/a/f" }); + assert_eq!( + execute_component_body("u/a/app", "k", &by_path, &Value::Null), + json!({ + "component": "k", "args": {}, "force_viewer_static_fields": {}, + "path": "flow/u/a/f" + }) + ); + } + + #[test] + fn table_refs_are_canonicalized_against_the_apps_schema() { + assert_eq!( + app_table_ref("main", Some("shop"), "orders"), + "main/shop:orders" + ); + assert_eq!(app_table_ref("main", None, "orders"), "main/orders"); + assert_eq!( + app_table_ref("main", Some("shop"), "public.orders"), + "main/orders" + ); + assert_eq!( + app_table_ref("main", Some("shop"), "crm:leads"), + "main/crm:leads" + ); + assert_eq!(app_table_ref("main", Some("shop"), "other/x"), "other/x"); + } +} diff --git a/backend/windmill-api/src/mcp/session/data.rs b/backend/windmill-api/src/mcp/session/data.rs new file mode 100644 index 0000000000..665647c7ce --- /dev/null +++ b/backend/windmill-api/src/mcp/session/data.rs @@ -0,0 +1,969 @@ +//! Data tables, DuckLake and database resource schemas. + +use std::sync::LazyLock; + +use regex::Regex; +use serde_json::{json, Map, Value}; + +use super::runs::{backgrounded_summary, run_script_preview, wait_budget, wait_job}; +use super::workspace::{api_message, path_enc}; +use super::{array, enc, js_str, non_null, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult}; + +pub(super) const TOOLS: &[&str] = &[ + "list_datatables", + "get_datatable_table_schema", + "exec_datatable_sql", + "list_data_metrics", + "list_ducklakes", + "get_db_schema", + "list_datatable_migrations", + "create_datatable_migration", + "run_datatable_migrations", + "rollback_datatable_migration", +]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "list_datatables" => Ok(list_datatables(ctx, args) + .await + .unwrap_or_else(|e| format!("Error listing datatables: {e}"))), + "get_datatable_table_schema" => get_datatable_table_schema(ctx, args).await, + "exec_datatable_sql" => exec_datatable_sql(ctx, args).await, + "list_data_metrics" => list_data_metrics(ctx, args).await, + "list_ducklakes" => Ok(list_ducklakes(ctx) + .await + .unwrap_or_else(|e| format!("Error listing DuckLake catalogs: {e}"))), + "get_db_schema" => get_db_schema(ctx, args).await, + "list_datatable_migrations" => list_datatable_migrations(ctx, args).await, + "create_datatable_migration" => create_datatable_migration(ctx, args).await, + "run_datatable_migrations" => run_datatable_migrations(ctx, args).await, + "rollback_datatable_migration" => rollback_datatable_migration(ctx, args).await, + _ => unreachable!("{name} is not a data tool"), + } +} + +const NO_DATATABLES_CONFIGURED_MESSAGE: &str = "No datatables are configured in this workspace. Datatable operations (querying data, creating or altering tables) are blocked until a datatable exists. Datatables are not created by SQL — the user must set one up in the workspace settings (Workspace settings → Data Tables) first. Do not call exec_datatable_sql or assume a \"main\" datatable exists; instead tell the user this is a required prerequisite and ask them to configure a datatable in their workspace settings."; + +const NO_DUCKLAKES_CONFIGURED_MESSAGE: &str = "No DuckLake catalogs are configured in this workspace. A data pipeline that materializes DuckLake tables or reads/writes S3 assets cannot run until object storage and a DuckLake catalog are set up. You can still draft the pipeline scripts, but tell the user how to enable it by role: a workspace admin adds object storage under Workspace settings → Object Storage (S3/Azure/GCS), then a DuckLake catalog on top of it; a user without admin rights should ask a workspace admin. Do not assume a default 'main' DuckLake exists."; + +const NO_DATA_METRICS_NOTE: &str = "Nothing matched. That does not establish that nothing is declared: declarations whose producing script you cannot read are omitted from this list, not flagged. You may write your own aggregate, but tell the user you found no declared measure you can read rather than stating none is declared."; + +const DEFAULT_DATA_METRICS_LIMIT: u64 = 200; +/// Rows of a SELECT handed to the model. +const MAX_ROWS: usize = 100; +/// Seconds a query is awaited before it is left running for `get_run`. +const MAX_SCHEMA_LENGTH: usize = 350_000; + +/// The worker's error for a data table that is not configured in the workspace. +static DATATABLE_NOT_FOUND: LazyLock = + LazyLock::new(|| Regex::new(r"(?i)datatable\s+\S+\s+not found").expect("valid regex")); + +fn datatable_not_configured_message(name: &str) -> String { + format!( + "Datatable \"{name}\" is not configured in this workspace, so this operation cannot run. \ + Datatables are not created by SQL — they must be set up first by the user in the workspace settings \ + (Workspace settings → Data Tables) before any table can be queried or created. \ + This is a required, blocking prerequisite: do not retry on this or another name. \ + Tell the user they need to configure a datatable (e.g. named \"{name}\") in their workspace settings, then try again." + ) +} + +/// The optional `role` argument, held to the rule the server applies to a role name. +fn role_arg(args: &Value) -> Result, String> { + let role = opt_str_arg(args, "role"); + match role { + Some(r) + if r.is_empty() + || r.len() > 63 + || !r + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') => + { + Err(format!( + "Invalid `role` '{r}': only letters, digits, '_' and '-' are allowed (1 to 63 characters)" + )) + } + _ => Ok(role), + } +} + +/// `path?k=v&...` over the parameters that are set. +fn with_query(path: String, params: &[(&str, Option<&str>)]) -> String { + let query: Vec = params + .iter() + .filter_map(|(k, v)| v.map(|v| format!("{k}={}", enc(v)))) + .collect(); + if query.is_empty() { + path + } else { + format!("{path}?{}", query.join("&")) + } +} + +async fn list_datatables(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let role = role_arg(args)?; + let datatable_name = opt_str_arg(args, "datatable_name"); + if role.is_some() && datatable_name.is_none() { + return Err("`role` needs `datatable_name`, the datatable it is a role of".to_string()); + } + let path = with_query( + ctx.ws("workspaces/list_datatable_tables"), + &[ + ("datatable_name", datatable_name), + ("role_for", role.and(datatable_name)), + ("role", role), + ], + ); + let metadata = ctx.get(&path).await?; + let metadata = array(Some(&metadata)); + if metadata.is_empty() { + return Ok(NO_DATATABLES_CONFIGURED_MESSAGE.to_string()); + } + let listed: Vec = metadata + .iter() + .map(|d| { + let mut out = Map::new(); + out.insert("datatable_name".into(), d["datatable_name"].clone()); + out.insert("schemas".into(), d["schemas"].clone()); + if truthy(d.get("error")) { + out.insert("error".into(), d["error"].clone()); + } + if truthy(d.get("permissioned")) { + for key in ["usable_roles", "default_role"] { + if let Some(v) = d.get(key) { + out.insert(key.into(), v.clone()); + } + } + } + Value::Object(out) + }) + .collect(); + Ok(pretty(&Value::Array(listed))) +} + +async fn get_datatable_table_schema(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let datatable_name = str_arg(args, "datatable_name")?; + let schema_name = str_arg(args, "schema_name")?; + let table_name = str_arg(args, "table_name")?; + let role = role_arg(args)?; + let path = with_query( + ctx.ws("workspaces/get_datatable_table_schema"), + &[ + ("datatable_name", Some(datatable_name)), + ("schema_name", Some(schema_name)), + ("table_name", Some(table_name)), + ("role", role), + ], + ); + Ok(match ctx.get(&path).await { + Ok(schema) => pretty(&json!({ + "datatable_name": datatable_name, + "schema_name": schema_name, + "table_name": table_name, + "columns": schema["columns"], + })), + Err(e) if DATATABLE_NOT_FOUND.is_match(&e) => { + datatable_not_configured_message(datatable_name) + } + Err(e) => format!("Error getting table schema: {e}"), + }) +} + +async fn list_ducklakes(ctx: &Ctx<'_>) -> ToolResult { + let ducklakes = ctx.get(&ctx.ws("workspaces/list_ducklakes")).await?; + if ducklakes.as_array().is_none_or(Vec::is_empty) { + return Ok(NO_DUCKLAKES_CONFIGURED_MESSAGE.to_string()); + } + Ok(pretty(&json!({ "ducklakes": ducklakes }))) +} + +async fn list_data_metrics(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let limit = match args.get("limit") { + None | Some(Value::Null) => DEFAULT_DATA_METRICS_LIMIT, + Some(v) => v + .as_u64() + .filter(|n| (1..=1000).contains(n)) + .ok_or("`limit` must be an integer between 1 and 1000")?, + }; + let table = opt_str_arg(args, "table"); + let path = with_query( + ctx.ws("data_metrics/list"), + &[ + ("table", table), + ("path_prefix", opt_str_arg(args, "path_prefix")), + ("per_page", Some(&limit.to_string())), + ], + ); + let page = ctx.get(&path).await?; + let metrics = page.get("metrics").cloned().unwrap_or_else(|| json!([])); + let note = if truthy(page.get("next_cursor")) { + Some(format!("More declarations exist beyond the first {limit}. Re-call with table/path_prefix to target what you are looking for, or with a higher limit (max 1000) for the rest of the list, rather than concluding a measure is undeclared.")) + } else if metrics.as_array().is_some_and(Vec::is_empty) { + // The endpoint expands a table filter only once it contains a `/`, so a bare + // table name matches nothing whatever is declared. + let bare = table.map(|t| t.replacen("ducklake://", "", 1)); + Some(match (table, bare) { + (Some(table), Some(bare)) if !bare.is_empty() && !bare.contains('/') => format!("Nothing matched `{table}`: a table filter must name its lake, as `/{bare}`. Re-call with the lake before concluding anything about what is declared."), + _ => NO_DATA_METRICS_NOTE.to_string(), + }) + } else { + None + }; + let mut out = Map::new(); + out.insert("metrics".into(), metrics); + if let Some(note) = note { + out.insert("note".into(), note.into()); + } + Ok(pretty(&Value::Object(out))) +} + +async fn exec_datatable_sql(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let name = str_arg(args, "datatable_name")?; + let sql = str_arg(args, "sql")?; + let role = role_arg(args)?; + let failed = |e: String| format!("Failed to execute test run: {e}"); + + let database = match role { + None => format!("datatable://{name}"), + // A stored name holding a `?` is read whole by the server, so a role cannot follow it. + Some(role) if name.contains('?') => { + return Err(failed(format!("Data table '{name}' has a '?' in its name, so it can only be used here as its default role. Rename it to connect as role '{role}'."))); + } + Some(role) => format!("datatable://{name}?role={role}"), + }; + let id = run_script_preview( + ctx, + None, + "postgresql", + sql, + json!({ "database": database }), + ) + .await + .map_err(failed)?; + + match wait_job(ctx, &id, wait_budget(args), false).await { + Some(job) => Ok(format_datatable_sql_completion(&job, name)), + None => Ok(backgrounded_summary(&id, &format!("SQL · {name}"))), + } +} + +fn format_datatable_sql_completion(job: &Value, datatable_name: &str) -> String { + if job["success"] == true { + let rows = array(job.get("result")); + let row_count = rows.len(); + return pretty(&if row_count > MAX_ROWS { + json!({ + "success": true, + "rowCount": row_count, + "result": &rows[..MAX_ROWS], + "note": format!("Showing first {MAX_ROWS} of {row_count} rows"), + }) + } else { + json!({ "success": true, "rowCount": row_count, "result": rows }) + }); + } + let error = match job.get("result") { + None => json!("Unknown error"), + Some(result) => match result.pointer("/error/message") { + Some(message) if !message.is_null() => message.clone(), + _ => match result { + Value::String(_) => result.clone(), + other => Value::String(other.to_string()), + }, + }, + }; + let error = match error.as_str() { + Some(raw) if DATATABLE_NOT_FOUND.is_match(raw) => { + Value::String(datatable_not_configured_message(datatable_name)) + } + _ => error, + }; + json!({ "success": false, "error": error }).to_string() +} + +/// The optional `version` argument: a migration's timestamp. +fn version_arg(args: &Value) -> Result, String> { + match args.get("version") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_i64() + .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0).map(|f| f as i64)) + .map(Some) + .ok_or_else(|| "`version` must be an integer".to_string()), + } +} + +/// `workspaces//`, the shape of every migration route. +fn migrations_path(ctx: &Ctx<'_>, endpoint: &str, datatable_name: &str) -> String { + ctx.ws(&format!("workspaces/{endpoint}/{}", enc(datatable_name))) +} + +async fn migrations_status(ctx: &Ctx<'_>, datatable_name: &str) -> Result { + ctx.get(&migrations_path( + ctx, + "datatable_migrations_status", + datatable_name, + )) + .await + .map_err(|e| api_message(&e).to_string()) +} + +/// `POST` without a body: applying and rolling back take their target from the query. +async fn post_migrations(ctx: &Ctx<'_>, path: &str) -> Result { + let text = ctx + .request("POST", path, None) + .await + .map_err(|e| api_message(&e).to_string())?; + serde_json::from_str(&text).map_err(|e| format!("unexpected response: {e}")) +} + +fn migration_label(version: &Value, name: &Value) -> String { + format!("{} ({})", js_str(version), js_str(name)) +} + +fn labels(migrations: Option<&Value>) -> String { + array(migrations) + .iter() + .map(|m| migration_label(&m["version"], &m["name"])) + .collect::>() + .join(", ") +} + +fn migration_status(status: &Value) -> &'static str { + match status.as_str() { + Some("ran") => "applied", + Some("not_run") => "pending", + _ => "unknown", + } +} + +/// The rest of a leading comment line whose first word is `keyword`: an annotation attempt. +fn annotation_attempt<'a>(line: &'a str, keyword: &str) -> Option<&'a str> { + let body = line.strip_prefix("--")?.trim_start(); + let after = body + .get(..keyword.len()) + .filter(|w| w.eq_ignore_ascii_case(keyword)) + .map(|_| &body[keyword.len()..])?; + match after.chars().next() { + Some(c) if !(c.is_whitespace() || c == ':' || c == '=') => None, + _ => Some(after), + } +} + +/// The lines of `sql`'s leading comment block, where the server reads its annotations. +fn leading_block(sql: &str) -> impl Iterator { + sql.split('\n') + .map(str::trim) + .filter(|l| !l.is_empty()) + .take_while(|l| l.starts_with("--")) +} + +/// `sql` with every `keyword` attempt of its leading comment block removed, and `line`, if +/// any, on top. +fn with_annotation(sql: &str, keyword: &str, line: Option) -> String { + let lines: Vec<&str> = sql.split('\n').collect(); + let leading = lines + .iter() + .position(|l| !l.trim().is_empty() && !l.trim().starts_with("--")) + .unwrap_or(lines.len()); + let rest = lines[..leading] + .iter() + .filter(|l| annotation_attempt(l.trim(), keyword).is_none()) + .chain(&lines[leading..]) + .skip_while(|l| l.trim().is_empty()) + .map(|l| l.to_string()); + line.into_iter().chain(rest).collect::>().join("\n") +} + +/// `sql` declaring `role`: the server reads the role a migration runs as from a `-- role ` +/// annotation in its leading comment block, so any attempt there is replaced by one on top. +fn with_migration_role(sql: &str, role: Option<&str>) -> String { + match role { + Some(role) => with_annotation(sql, "role", Some(format!("-- role {role}"))), + None => sql.to_string(), + } +} + +fn is_annotatable_schema_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 63 + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '$' | '-')) +} + +/// The scope `sql`'s `-- schemas a, b` annotation declares, lowercased, as the server's +/// `parse_migration_schemas` reads it. None for the whole database, which is also what a +/// malformed annotation stands for here. +fn declared_schemas(sql: &str) -> Option> { + let after = leading_block(sql).find_map(|l| annotation_attempt(l, "schemas"))?; + let rest = after.trim_start(); + let rest = rest.strip_prefix([':', '=']).unwrap_or(rest).trim(); + let rest = rest.strip_suffix(';').unwrap_or(rest); + let mut schemas: Vec = Vec::new(); + for name in rest.split(',').map(str::trim) { + if !is_annotatable_schema_name(name) { + return None; + } + let name = name.to_ascii_lowercase(); + if !schemas.contains(&name) { + schemas.push(name); + } + } + Some(schemas) +} + +/// Whether a listed migration's `schemas` overlaps `own`; an absent scope is the whole database. +fn scopes_overlap(theirs: &Value, own: Option<&[String]>) -> bool { + match (theirs.as_array(), own) { + (Some(theirs), Some(own)) => theirs + .iter() + .any(|s| own.iter().any(|o| s.as_str() == Some(o))), + _ => true, + } +} + +/// The optional `schemas` argument, held to the rule the server applies to a scope name. +fn schemas_arg(args: &Value) -> Result>, String> { + let Some(value) = non_null(args.get("schemas")) else { + return Ok(None); + }; + let names = value + .as_array() + .ok_or("`schemas` must be an array of schema names")?; + names + .iter() + .map(|name| match name.as_str() { + Some(name) if is_annotatable_schema_name(name) => Ok(name.to_ascii_lowercase()), + _ => Err(format!( + "Invalid schema name '{}' in `schemas`: only letters, digits, '_', '$' and '-' are allowed (1 to 63 characters)", + js_str(name) + )), + }) + .collect::>() + .map(Some) +} + +async fn list_datatable_migrations(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let datatable_name = str_arg(args, "datatable_name")?; + let version = version_arg(args)?; + let status = match migrations_status(ctx, datatable_name).await { + Ok(status) => status, + Err(e) => return Ok(format!("Error listing migrations: {e}")), + }; + if !truthy(status.get("enabled")) { + return Ok(format!("Migrations are not enabled on datatable \"{datatable_name}\": its schema is changed with plain SQL and there is no history to list. Enabling them is a workspace admin's decision, made in Workspace settings → Data Tables.")); + } + let migrations = array(status.get("migrations")); + let Some(version) = version else { + let mut out = Map::new(); + out.insert( + "migrations".into(), + migrations + .iter() + .map(|m| { + json!({ + "version": m["timestamp"], + "name": m["name"], + "status": migration_status(&m["status"]), + "schemas": non_null(m.get("schemas")).cloned().unwrap_or_else(|| json!("whole database")), + }) + }) + .collect(), + ); + if truthy(status.get("error")) { + out.insert("error".into(), status["error"].clone()); + } + return Ok(pretty(&Value::Object(out))); + }; + let Some(migration) = migrations + .iter() + .find(|m| m["timestamp"].as_i64() == Some(version)) + else { + return Ok(format!( + "No migration {version} on datatable \"{datatable_name}\"" + )); + }; + let mut out = Map::new(); + out.insert("version".into(), version.into()); + out.insert("name".into(), migration["name"].clone()); + out.insert( + "status".into(), + migration_status(&migration["status"]).into(), + ); + out.insert("code_up".into(), migration["code_up"].clone()); + if let Some(code_down) = non_null(migration.get("code_down")) { + out.insert("code_down".into(), code_down.clone()); + } + Ok(pretty(&Value::Object(out))) +} + +/// Saves the definition and answers its version, or the message the tool returns instead. +async fn save_migration( + ctx: &Ctx<'_>, + datatable_name: &str, + version: Option, + mut definition: Map, +) -> Result, String> { + let Some(version) = version else { + let created = ctx + .post( + &migrations_path(ctx, "create_datatable_migration", datatable_name), + Value::Object(definition), + ) + .await?; + return created["timestamp"] + .as_i64() + .map(Ok) + .ok_or_else(|| "the created migration has no version".to_string()); + }; + // The server inserts at a version it does not know, which would wedge a new migration + // into the middle of the history, and stores a down left out as none. + let status = migrations_status(ctx, datatable_name).await?; + let existing = array(status.get("migrations")) + .iter() + .find(|m| m["timestamp"].as_i64() == Some(version)); + let Some(existing) = existing.filter(|m| m["status"] == "not_run") else { + return Ok(Err(format!("Migration {version} is not a pending migration of datatable \"{datatable_name}\", so it cannot be rewritten. Omit `version` to add a new migration."))); + }; + definition.insert("timestamp".into(), version.into()); + if let Some(code_down) = non_null(existing.get("code_down")) { + definition + .entry("code_down") + .or_insert_with(|| code_down.clone()); + } + ctx.post( + &migrations_path(ctx, "upsert_datatable_migration", datatable_name), + Value::Object(definition), + ) + .await?; + Ok(Ok(version)) +} + +/// The labels of the migrations before `version`, in a scope overlapping `scope`, that are +/// not applied yet. +async fn earlier_pending( + ctx: &Ctx<'_>, + datatable_name: &str, + version: i64, + scope: Option<&[String]>, +) -> Result, String> { + let status = migrations_status(ctx, datatable_name).await?; + let earlier: Vec<&Value> = array(status.get("migrations")) + .iter() + .filter(|m| m["timestamp"].as_i64().is_some_and(|t| t < version)) + .filter(|m| scopes_overlap(&m["schemas"], scope)) + .collect(); + // Unreadable is not pending: reporting it so would send the user to apply migrations + // that already ran. + if truthy(status.get("error")) { + return Err(js_str(&status["error"])); + } + if earlier.iter().any(|m| m["status"] == "unknown") { + return Err("the applied migrations could not be read".to_string()); + } + Ok(earlier + .into_iter() + .filter(|m| m["status"] == "not_run") + .map(|m| migration_label(&m["timestamp"], &m["name"])) + .collect()) +} + +async fn create_datatable_migration(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let datatable_name = str_arg(args, "datatable_name")?; + let name = str_arg(args, "name")?; + if name.is_empty() + || !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + { + return Err(format!( + "Invalid `name` '{name}': only letters, digits, '_' and '-' are allowed" + )); + } + let role = role_arg(args)?; + let version = version_arg(args)?; + let code_up = str_arg(args, "code_up")?; + // What the caller declares, else what `code_up` does; none is the whole database. + let scope = schemas_arg(args)? + .or_else(|| declared_schemas(code_up)) + .unwrap_or_default(); + let header = (!scope.is_empty()).then(|| format!("-- schemas {}", scope.join(", "))); + + let mut definition = Map::new(); + definition.insert("name".into(), name.into()); + definition.insert( + "code_up".into(), + with_annotation(&with_migration_role(code_up, role), "schemas", header).into(), + ); + if let Some(code_down) = opt_str_arg(args, "code_down") { + // A rollback has to run as the role that created what it drops. + definition.insert( + "code_down".into(), + with_migration_role(code_down, role).into(), + ); + } + let version = match save_migration(ctx, datatable_name, version, definition).await { + Ok(Ok(version)) => version, + Ok(Err(message)) => return Ok(message), + Err(e) => return Ok(format!("Error saving migration: {}", api_message(&e))), + }; + let label = format!("{version} ({name})"); + if args.get("apply") == Some(&Value::Bool(false)) { + return Ok(format!( + "Saved migration {label} as pending. It is not applied yet." + )); + } + + // Applying it alone would run it ahead of migrations it may depend on. + let own_scope = (!scope.is_empty()).then_some(scope.as_slice()); + let earlier = match earlier_pending(ctx, datatable_name, version, own_scope).await { + Ok(earlier) => earlier, + Err(e) => return Ok(format!("Saved migration {label} as pending, but could not check what else is pending, so it was not applied: {e}")), + }; + if !earlier.is_empty() { + return Ok(format!("Saved migration {label} as pending without applying it: earlier migrations are not applied yet ({}) and it may depend on them. Tell the user, then apply them all in order with run_datatable_migrations.", earlier.join(", "))); + } + + let run = format!( + "{}?only={version}", + migrations_path(ctx, "run_datatable_migrations", datatable_name) + ); + Ok(match post_migrations(ctx, &run).await { + Ok(_) => format!("Applied migration {label} on datatable \"{datatable_name}\"."), + Err(e) => format!("Migration {label} is saved but failed to apply: {e}. It stays pending and blocks later migrations. If nothing of it was applied, fix it by calling this tool again with version {version}; otherwise, or to drop it, tell the user, who can edit or delete it in Workspace settings → Data Tables."), + }) +} + +async fn run_datatable_migrations(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let datatable_name = str_arg(args, "datatable_name")?; + let path = migrations_path(ctx, "run_datatable_migrations", datatable_name); + Ok(match post_migrations(ctx, &path).await { + Ok(result) => { + let applied = array(result.get("applied")); + if applied.is_empty() { + format!("No pending migration to apply on datatable \"{datatable_name}\".") + } else { + format!( + "Applied {} migration(s) on datatable \"{datatable_name}\": {}.", + applied.len(), + labels(result.get("applied")) + ) + } + } + Err(e) => format!("Error applying migrations: {e}. Migrations before the failing one may have been applied: list them to see."), + }) +} + +async fn rollback_datatable_migration(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let datatable_name = str_arg(args, "datatable_name")?; + let version = version_arg(args)?.ok_or("Missing required number argument `version`")?; + let path = format!( + "{}?only={version}", + migrations_path(ctx, "rollback_datatable_migrations", datatable_name) + ); + Ok(match post_migrations(ctx, &path).await { + Ok(result) if array(result.get("rolled_back")).is_empty() => format!("Migration {version} is not applied on datatable \"{datatable_name}\", so there is nothing to roll back."), + Ok(result) => format!( + "Rolled back migration {} on datatable \"{datatable_name}\". It is pending again.", + labels(result.get("rolled_back")) + ), + Err(e) => format!("Error rolling back: {e}"), + }) +} + +const POSTGRESQL_SCHEMA_QUERY: &str = " +SELECT table_name, column_name, udt_name, column_default, is_nullable, nsp.nspname AS table_schema FROM information_schema.columns +RIGHT JOIN pg_namespace nsp ON table_schema = nsp.nspname WHERE nsp.nspname NOT IN ('information_schema', 'pg_toast', 'pg_catalog') +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'"; +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({ + credentials: args +}) +const [datasets] = await bq.getDatasets(); +if (!datasets) return {} +const schema = {} as any +let queries = datasets.map(dataset => ` + SELECT + table_name, + '${dataset.id}' as dataset, + ARRAY_AGG(STRUCT( + if(is_nullable = 'YES', true, false) AS required, + column_name AS name, + data_type AS type, + if(column_default = 'NULL', null, column_default) AS \`default\` + ) ORDER BY ordinal_position) + AS schema + FROM \`${dataset.id}\`.INFORMATION_SCHEMA.COLUMNS + GROUP BY table_name` +) +let query = queries.join('\nUNION ALL \n') +const [rows] = await bq.query(query) +for (const row of rows) { + schema[row.dataset] ??= {} + schema[row.dataset][row.table_name] = {} + for (const col of row.schema) { + const colName = col.name + delete col.name + if (col.default === null) { + delete col.default + } + schema[row.dataset][row.table_name][colName] = col + } +} +return schema +}"#; + +/// How long a schema introspection is awaited. +const DB_SCHEMA_WAIT_SECS: u64 = 120; + +async fn get_db_schema(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = opt_str_arg(args, "resourcePath") + .filter(|p| !p.is_empty()) + .ok_or("Database path not provided")?; + let resource = ctx + .get(&ctx.ws(&format!("resources/get/{}", path_enc(path)))) + .await?; + let resource_type = resource["resource_type"].as_str().unwrap_or_default(); + let not_found = || "Database not found".to_string(); + let (language, content, arg_name) = match resource_type { + "postgresql" => ("postgresql", POSTGRESQL_SCHEMA_QUERY, "database"), + "mysql" => ("mysql", MYSQL_SCHEMA_QUERY, "database"), + "ms_sql_server" | "mssql" => ("mssql", MSSQL_SCHEMA_QUERY, "database"), + "snowflake" | "snowflake_oauth" => ("snowflake", SNOWFLAKE_SCHEMA_QUERY, "database"), + "bigquery" => ("bun", BIGQUERY_SCHEMA_SCRIPT, "args"), + _ => return Err(not_found()), + }; + let id = run_script_preview( + ctx, + None, + language, + content, + json!({ arg_name: format!("$res:{path}") }), + ) + .await + .map_err(|_| not_found())?; + let job = wait_job(ctx, &id, DB_SCHEMA_WAIT_SECS, false) + .await + .ok_or_else(|| { + format!( + "The schema query did not finish within {DB_SCHEMA_WAIT_SECS} seconds (job {id})" + ) + })?; + if job["success"] != true { + return Err(not_found()); + } + let mut stringified = + stringify_db_schema(resource_type, &job["result"]).ok_or_else(not_found)?; + if stringified.chars().count() > MAX_SCHEMA_LENGTH { + stringified = stringified + .chars() + .take(MAX_SCHEMA_LENGTH) + .collect::() + + "..."; + } + Ok(format!( + "DATABASE SCHEMA (each column is in the format [name, type, required, default?]):\n{stringified}" + )) +} + +/// The object under `key`, created empty where a JavaScript object would first get it. +fn slot(map: &mut Map, key: String) -> &mut Map { + map.entry(key) + .or_insert_with(|| json!({})) + .as_object_mut() + .expect("only objects are inserted") +} + +/// The introspection result as `{schema: {table: [[name, type, required, default?]]}}`, +/// narrowed to the default schema's tables when the database has one. +fn stringify_db_schema(resource_type: &str, result: &Value) -> Option { + let mut schemas: Map = Map::new(); + let column = |name: String, ty: &Value, required: Value, default: Option<&Value>| { + let mut col = vec![Value::String(name), ty.clone(), required]; + if truthy(default) { + col.extend(default.cloned()); + } + Value::Array(col) + }; + if resource_type == "bigquery" { + for (dataset, tables) in result.as_object()? { + let dataset = slot(&mut schemas, dataset.clone()); + for (table, columns) in tables.as_object()? { + let table = slot(dataset, table.clone()); + for (name, col) in columns.as_object()? { + let entry = column( + name.clone(), + &col["type"], + col["required"].clone(), + col.get("default"), + ); + table.insert(name.clone(), entry); + } + } + } + } else { + for row in result.as_array()? { + let (schema, table, name, ty, required, default) = match resource_type { + "postgresql" => ( + "table_schema", + "table_name", + "column_name", + "udt_name", + row["is_nullable"] == "NO", + row.get("column_default"), + ), + // `required` reads IS_NULLABLE the way the session does: "YES" is true. + "snowflake" | "snowflake_oauth" => ( + "TABLE_SCHEMA", + "TABLE_NAME", + "COLUMN_NAME", + "DATA_TYPE", + row["IS_NULLABLE"] == "YES", + row.get("COLUMN_DEFAULT"), + ), + // These queries select neither nullability nor a default the session reads. + _ => ( + "TABLE_SCHEMA", + "TABLE_NAME", + "COLUMN_NAME", + "DATA_TYPE", + false, + None, + ), + }; + let schema = slot(&mut schemas, js_str(&row[schema])); + // A schema with no table comes back as one row of nulls. + if resource_type == "postgresql" && !truthy(row.get(table)) && !truthy(row.get(name)) { + continue; + } + let name = js_str(&row[name]); + let entry = column(name.clone(), &row[ty], json!(required), default); + slot(schema, js_str(&row[table])).insert(name, entry); + } + } + + for table in schemas.values_mut().filter_map(Value::as_object_mut) { + for columns in table.values_mut() { + if let Some(by_name) = columns.as_object_mut() { + *columns = Value::Array( + std::mem::take(by_name) + .into_iter() + .map(|(_, c)| c) + .collect(), + ); + } + } + } + let default_schema = ["public", "PUBLIC", "dbo"] + .into_iter() + .find(|k| schemas.contains_key(*k)) + .or_else(|| { + (resource_type == "mysql" && schemas.len() == 1) + .then(|| schemas.keys().next().map(String::as_str)) + .flatten() + }) + .map(str::to_string); + Some(match default_schema { + Some(key) => schemas[&key].to_string(), + None => Value::Object(schemas).to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn postgres_schema_is_compact_and_narrowed_to_public() { + let rows = json!([ + { "table_schema": "empty", "table_name": null, "column_name": null }, + { "table_schema": "public", "table_name": "t", "column_name": "id", "udt_name": "int4", "is_nullable": "NO", "column_default": "nextval('s')" }, + { "table_schema": "public", "table_name": "t", "column_name": "name", "udt_name": "text", "is_nullable": "YES", "column_default": null }, + { "table_schema": "other", "table_name": "u", "column_name": "x", "udt_name": "bool", "is_nullable": "YES", "column_default": "" }, + ]); + assert_eq!( + stringify_db_schema("postgresql", &rows).unwrap(), + r#"{"t":[["id","int4",true,"nextval('s')"],["name","text",false]]}"# + ); + let rows = json!([rows[0], rows[3]]); + assert_eq!( + stringify_db_schema("postgresql", &rows).unwrap(), + r#"{"empty":{},"other":{"u":[["x","bool",false]]}}"# + ); + assert_eq!(stringify_db_schema("postgresql", &json!({})), None); + } + + #[test] + fn migration_role_replaces_a_leading_annotation_only() { + assert_eq!(with_migration_role("BEGIN;\nEND;", None), "BEGIN;\nEND;"); + assert_eq!( + with_migration_role( + "\n-- note\n--ROLE: old;\n-- roles kept\nBEGIN;\n-- role below\nEND;", + Some("app_rw") + ), + "-- role app_rw\n-- note\n-- roles kept\nBEGIN;\n-- role below\nEND;" + ); + } + + #[test] + fn migration_scope_is_read_from_the_leading_block_and_overlaps() { + let sql = "-- role r\n--SCHEMAS: Sales, billing, sales;\nBEGIN;\n-- schemas other\nEND;"; + let scope = declared_schemas(sql).unwrap(); + assert_eq!(scope, ["sales", "billing"]); + assert_eq!(declared_schemas("BEGIN;\n-- schemas a\nEND;"), None); + assert_eq!(declared_schemas("-- schemas a b\nBEGIN;"), None); + assert_eq!(declared_schemas("-- schemasx a\nBEGIN;"), None); + assert_eq!( + with_annotation( + &with_migration_role(sql, Some("w")), + "schemas", + Some("-- schemas sales".into()) + ), + "-- schemas sales\n-- role w\nBEGIN;\n-- schemas other\nEND;" + ); + assert_eq!( + with_annotation(sql, "schemas", None), + "-- role r\nBEGIN;\n-- schemas other\nEND;" + ); + + assert!(scopes_overlap(&json!(["billing", "x"]), Some(&scope))); + assert!(!scopes_overlap(&json!(["x"]), Some(&scope))); + assert!(scopes_overlap(&Value::Null, Some(&scope))); + assert!(scopes_overlap(&json!(["x"]), None)); + } + + #[test] + fn sql_completion_caps_rows_and_rewrites_the_missing_datatable_error() { + let rows: Vec = (0..101).map(|i| json!({ "i": i })).collect(); + let out: Value = serde_json::from_str(&format_datatable_sql_completion( + &json!({ "success": true, "result": rows }), + "main", + )) + .unwrap(); + assert_eq!(out["rowCount"], 101); + assert_eq!(out["result"].as_array().unwrap().len(), 100); + assert_eq!(out["note"], "Showing first 100 of 101 rows"); + + assert_eq!( + format_datatable_sql_completion(&json!({ "success": true, "result": [] }), "main"), + "{\n \"success\": true,\n \"rowCount\": 0,\n \"result\": []\n}" + ); + assert_eq!( + format_datatable_sql_completion( + &json!({ "success": false, "result": { "error": { "message": "boom" } } }), + "main" + ), + r#"{"success":false,"error":"boom"}"# + ); + let missing = format_datatable_sql_completion( + &json!({ "success": false, "result": { "error": { "message": "datatable main not found" } } }), + "main", + ); + assert!(missing.contains("Datatable \\\"main\\\" is not configured")); + } +} diff --git a/backend/windmill-api/src/mcp/session/deploy.rs b/backend/windmill-api/src/mcp/session/deploy.rs new file mode 100644 index 0000000000..ba65488c75 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/deploy.rs @@ -0,0 +1,2126 @@ +//! Deploying and deleting workspace items, and diffing drafts against what is deployed. + +use std::sync::LazyLock; + +use futures::{stream, StreamExt}; +use regex::Regex; +use serde_json::{json, Map, Value}; + +use super::flows::drop_stale_step_locks; +use super::workspace::{ + api_message, app_source_to_draft_value, delete_draft, deployed_item_exists, draft_kind, + get_deployed, get_draft_item, item_exists, item_type_arg, path_enc, service, unified_patch, + ITEM_TYPES, TRIGGER_KINDS, +}; +use super::{ + array, bool_arg, is_not_found, js_str, matches_glob, non_null, opt_str_arg, pretty, str_arg, + truthy, Ctx, ToolResult, +}; + +pub(super) const TOOLS: &[&str] = &["deploy_workspace_item", "delete_workspace_item", "diff"]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "deploy_workspace_item" => deploy_item(ctx, args).await, + "delete_workspace_item" => delete_item(ctx, args).await, + "diff" => diff(ctx, args).await, + _ => unreachable!("{name} is not a deploy tool"), + } +} + +/// An object without `keys`; `{}` for anything that is not an object. +fn without(value: &Value, keys: &[&str]) -> Value { + let mut out = value.as_object().cloned().unwrap_or_default(); + for key in keys { + out.shift_remove(*key); + } + Value::Object(out) +} + +fn uint_arg(args: &Value, name: &str) -> Option { + args.get(name) + .and_then(Value::as_u64) + .map(|n| usize::try_from(n).unwrap_or(usize::MAX)) +} + +// ============================================================================ +// deploy_workspace_item +// ============================================================================ + +fn assert_draft_based_on_latest( + item_type: &str, + path: &str, + base: Option<&Value>, + head: Option<&Value>, + force: bool, +) -> Result<(), String> { + let (Some(base), Some(head)) = (base.filter(|v| !v.is_null()), head.filter(|v| !v.is_null())) + else { + return Ok(()); + }; + if force || base == head { + return Ok(()); + } + Err(format!( + "This {item_type} draft \"{path}\" was started from an older deployed version (forked from {}, \ + latest is {}). Deploying now would overwrite the version deployed since. Call rebase_draft to \ + discard the stale draft and get your changes back as a diff, then re-apply them (the new draft \ + re-bases onto the latest version) and deploy. To deploy as-is and replace the newer version, call \ + deploy_workspace_item again with force: true.", + js_str(base), + js_str(head) + )) +} + +/// An editor draft of a script or flow can stage trigger edits, which the editors deploy +/// through per-kind forms. Deploying the item alone deletes the draft and those edits +/// with it, so it is refused instead. +fn refuse_staged_triggers(item_type: &str, path: &str, draft: &Value) -> Result<(), String> { + let staged = draft + .get("draft_triggers") + .and_then(Value::as_array) + .is_some_and(|triggers| triggers.iter().any(|t| truthy(t.get("draftConfig")))); + if staged { + return Err(format!( + "Draft {item_type} \"{path}\" also stages trigger changes made in the Windmill editor, which \ + cannot be deployed from here. Deploy it from the editor so they are not lost." + )); + } + Ok(()) +} + +async fn deploy_script(ctx: &Ctx<'_>, path: &str, message: Option<&str>) -> Result<(), String> { + let body_of = |e: String| api_message(&e).to_string(); + let row = ctx + .get(&ctx.ws(&format!("scripts/get/p/{}?get_draft=true", path_enc(path)))) + .await + .map_err(body_of)?; + let draft = non_null(row.get("draft")).unwrap_or(&row); + refuse_staged_triggers("script", path, draft)?; + let mut body = without( + draft, + &[ + "draft_triggers", + "draft_only", + "parent_hash", + "deployment_message", + "preserve_on_behalf_of", + // A draft seeded from the deployed script carries its lock, and the server skips + // the dependency job whenever one is set. + "lock", + "lock_error_logs", + ], + ); + body["path"] = non_null(draft.get("path")).cloned().unwrap_or(json!(path)); + if let Some(hash) = row.get("hash") { + body["parent_hash"] = hash.clone(); + } + if let Some(message) = message { + body["deployment_message"] = json!(message); + } + // Without the flag the server resets the identity to the deploying user. + if truthy(draft.get("on_behalf_of_email")) { + body["preserve_on_behalf_of"] = json!(true); + } + ctx.post(&ctx.ws("scripts/create"), body) + .await + .map_err(body_of)?; + Ok(()) +} + +async fn deploy_flow( + ctx: &Ctx<'_>, + path: &str, + draft_only: bool, + message: Option<&str>, +) -> Result<(), String> { + let body_of = |e: String| api_message(&e).to_string(); + let row = ctx + .get(&ctx.ws(&format!("flows/get/{}?get_draft=true", path_enc(path)))) + .await + .map_err(body_of)?; + let draft = non_null(row.get("draft")).unwrap_or(&row); + refuse_staged_triggers("flow", path, draft)?; + let or_empty = |key: &str| non_null(draft.get(key)).cloned().unwrap_or(json!("")); + let mut body = Map::new(); + body.insert( + "path".into(), + non_null(draft.get("draft_path")) + .or_else(|| non_null(draft.get("path"))) + .cloned() + .unwrap_or(json!(path)), + ); + body.insert("summary".into(), or_empty("summary")); + body.insert("description".into(), or_empty("description")); + for key in [ + "value", + "schema", + "tag", + "dedicated_worker", + "ws_error_handler_muted", + "visible_to_runner_only", + "on_behalf_of_email", + "on_behalf_of", + "labels", + "job_token_scopes", + ] { + if let Some(value) = draft.get(key) { + body.insert(key.into(), value.clone()); + } + } + if let Some(Value::Object(value)) = body.get_mut("value") { + // With nothing deployed the server fills `value` from the draft itself. + let deployed = row + .get("value") + .filter(|_| !draft_only && !truthy(row.get("no_deployed"))); + drop_stale_step_locks(value, deployed); + } + if truthy(draft.get("on_behalf_of_email")) { + body.insert("preserve_on_behalf_of".into(), json!(true)); + } + if let Some(message) = message { + body.insert("deployment_message".into(), json!(message)); + } + // A draft-only flow has no flow row to update. + let route = if draft_only { + "flows/create".to_string() + } else { + format!("flows/update/{}", path_enc(path)) + }; + ctx.post(&ctx.ws(&route), Value::Object(body)) + .await + .map_err(body_of)?; + Ok(()) +} + +async fn upsert( + ctx: &Ctx<'_>, + item_type: &str, + trigger_kind: Option<&str>, + path: &str, + body: Value, +) -> Result<(), String> { + let service = service(item_type, trigger_kind)?; + let route = if item_exists(ctx, item_type, trigger_kind, path).await? { + format!("{service}/update/{}", path_enc(path)) + } else { + format!("{service}/create") + }; + ctx.post(&ctx.ws(&route), body).await?; + Ok(()) +} + +/// An agent's draft never carries the identity it runs as, and without the flag the server +/// resets it to the deploying user, so an update restates the deployed one. +async fn deploy_resource(ctx: &Ctx<'_>, path: &str, draft: &Value) -> Result<(), String> { + if !item_exists(ctx, "resource", None, path).await? { + ctx.post(&ctx.ws("resources/create"), draft.clone()).await?; + return Ok(()); + } + let deployed = get_deployed(ctx, "resource", None, path).await?; + let mut body = draft.clone(); + let agent_obo = deployed + .get("value") + .and_then(|value| value.get("on_behalf_of")) + .filter(|obo| { + deployed.get("resource_type").and_then(Value::as_str) == Some("ai_agent") + && truthy(Some(obo)) + }); + if let (Some(obo), Some(body)) = (agent_obo, body.as_object_mut()) { + let mut value = body + .get("value") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + value.insert("on_behalf_of".into(), obo.clone()); + body.insert("value".into(), Value::Object(value)); + body.insert("preserve_on_behalf_of".into(), json!(true)); + } + ctx.post( + &ctx.ws(&format!("resources/update/{}", path_enc(path))), + body, + ) + .await?; + Ok(()) +} + +/// Deploys a variable draft; the note says when a secret's stored value was left alone. +async fn deploy_variable( + ctx: &Ctx<'_>, + path: &str, + draft: &Value, +) -> Result, String> { + let is_secret = truthy(draft.get("is_secret")); + let stages_no_value = draft.get("value").and_then(Value::as_str) == Some(""); + if !item_exists(ctx, "variable", None, path).await? { + if is_secret && stages_no_value { + return Err(format!( + "Draft variable \"{}\" is secret but stages no value, so it cannot be created. Run write_variable with its value first.", + draft.get("path").map(js_str).unwrap_or_default() + )); + } + ctx.post(&ctx.ws("variables/create"), draft.clone()).await?; + return Ok(None); + } + // A draft never carries a secret's or an OAuth-managed value, so `''` there means + // "none staged": sending it would blank the stored value or wipe a rotating token. + let protected = is_secret + || draft.get("is_oauth") == Some(&Value::Bool(true)) + || non_null(draft.get("account")).is_some(); + let keep_stored = protected && stages_no_value; + let mut body = if keep_stored { + without(draft, &["value"]) + } else { + draft.clone() + }; + // The draft holds the full variable, so an absent expiry was cleared, while the update + // endpoint reads an absent one as unchanged. + if let Some(body) = body.as_object_mut() { + body.entry("value_valid_until").or_insert(Value::Null); + } + ctx.post( + &ctx.ws(&format!("variables/update/{}", path_enc(path))), + body, + ) + .await?; + Ok((is_secret && keep_stored).then(|| { + "Its secret value was left unchanged, because the draft staged only metadata. If a new value was meant to be set, run write_variable again with it.".to_string() + })) +} + +/// A path runnable runs the DEPLOYED item at its path, so one pointing at a draft-only +/// script or flow fails at runtime. +async fn undeployed_runnable_targets(ctx: &Ctx<'_>, runnables: &Map) -> Vec { + let mut targets = Vec::new(); + for (key, runnable) in runnables { + let kind = runnable.get("type").and_then(Value::as_str); + let target_type = if matches!(kind, Some("path" | "runnableByPath")) { + runnable.get("runType").and_then(Value::as_str) + } else { + kind + }; + let (Some(target_type @ ("script" | "flow")), Some(path)) = ( + target_type, + runnable + .get("path") + .and_then(Value::as_str) + .filter(|p| !p.is_empty()), + ) else { + continue; + }; + // Advisory: a failed probe must not block the deploy it annotates. + if let Ok(false) = deployed_item_exists(ctx, target_type, None, path).await { + targets.push(format!("\"{key}\" → {target_type} \"{path}\"")); + } + } + targets +} + +async fn guest_access_is_live(ctx: &Ctx<'_>) -> bool { + let (Ok(usage), Ok(settings)) = ( + ctx.get(&ctx.ws("workspaces/guest_usage")).await, + ctx.get(&ctx.ws("workspaces/get_public_settings")).await, + ) else { + return false; + }; + truthy(usage.get("available")) + && truthy(usage.get("instance_enabled")) + && truthy(settings.get("guest_access_enabled")) +} + +/// Deploys a raw app draft from its sources: the server bundles them on a worker and +/// derives the policy's triggerables from the runnables. Returns the note for the result. +async fn deploy_app( + ctx: &Ctx<'_>, + path: &str, + item: &Value, + draft: &Value, + message: Option<&str>, + force: bool, +) -> Result, String> { + if let Some(base) = non_null(item.get("parentVersionId")) { + let head = if item_exists(ctx, "app", None, path).await? { + get_deployed(ctx, "app", None, path) + .await? + .get("versions") + .and_then(Value::as_array) + .and_then(|versions| versions.last()) + .cloned() + } else { + None + }; + assert_draft_based_on_latest("app", path, Some(base), head.as_ref(), force)?; + } + let object_or_empty = |key: &str| { + draft + .get(key) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default() + }; + let runnables = object_or_empty("runnables"); + let mut policy = object_or_empty("policy"); + if !truthy(policy.get("execution_mode")) { + policy.insert("execution_mode".into(), json!("publisher")); + } + + let mut notes = Vec::new(); + let undeployed = undeployed_runnable_targets(ctx, &runnables).await; + if !undeployed.is_empty() { + notes.push(format!( + "These backend runnables point at items that are NOT deployed, so they fail at runtime: \ + {}. Deploy those items too, and tell the user the app is not working until they are.", + undeployed.join(", ") + )); + } + // What a runnable runs as is the server's to decide, so the note names who can + // reach the app and never an identity. + match policy.get("execution_mode").and_then(Value::as_str) { + Some("anonymous") => notes.push( + "This app is deployed as anonymous: its backend runnables are now reachable by anyone \ + with the URL, without logging in. Tell the user plainly what is now reachable and by whom." + .to_string(), + ), + // `guest` is stored whether or not a guest is admitted: silent unless it is live. + Some("guest") if guest_access_is_live(ctx).await => notes.push( + "This app is deployed as guest: anyone the instance's identity provider authenticates \ + can now open it and run its backend runnables, member of this workspace or not. Tell \ + the user plainly what is now reachable and by whom." + .to_string(), + ), + _ => {} + } + + // An editor-created draft is parked at a synthetic storage key, its chosen path in + // the stored draft. Only a missing item justifies falling back to the storage path. + let target = match ctx + .get(&ctx.ws(&format!( + "apps/get/p/{}?get_draft=true&raw_app=true", + path_enc(path) + ))) + .await + { + Ok(row) => non_null(row.get("draft")) + .and_then(|d| non_null(d.get("draft_path")).or_else(|| non_null(d.get("path")))) + .or_else(|| non_null(row.get("draft_path"))) + .and_then(Value::as_str) + .unwrap_or(path) + .to_string(), + Err(e) if is_not_found(&e) => path.to_string(), + Err(e) => return Err(e), + }; + + let mut app = Map::new(); + app.insert("path".into(), json!(target)); + app.insert( + "value".into(), + json!({ + "files": object_or_empty("files"), + "runnables": runnables, + "data": non_null(draft.get("data")).cloned().unwrap_or_else(|| json!({ "tables": [] })), + }), + ); + app.insert( + "summary".into(), + non_null(draft.get("summary")) + .or_else(|| non_null(item.get("summary"))) + .cloned() + .unwrap_or(json!("")), + ); + if truthy(policy.get("on_behalf_of")) { + app.insert("preserve_on_behalf_of".into(), json!(true)); + } + app.insert("policy".into(), Value::Object(policy)); + if let Some(message) = message { + app.insert("deployment_message".into(), json!(message)); + } + if item_exists(ctx, "app", None, &target).await? { + // `custom_path` stays out of an update: the server keeps it when absent, and + // sending it takes admin rights. + ctx.post( + &ctx.ws(&format!("apps/update_raw_source/{}", path_enc(&target))), + Value::Object(app), + ) + .await?; + } else { + if let Some(custom_path) = draft.get("custom_path") { + app.insert("custom_path".into(), custom_path.clone()); + } + ctx.post(&ctx.ws("apps/create_raw_source"), Value::Object(app)) + .await?; + } + Ok((!notes.is_empty()).then(|| notes.join(" "))) +} + +fn mutation_result( + message: String, + item_type: &str, + path: &str, + trigger_kind: Option<&str>, + url: Option, +) -> String { + let mut out = Map::new(); + out.insert("success".into(), json!(true)); + out.insert("message".into(), json!(message)); + out.insert("type".into(), json!(item_type)); + out.insert("path".into(), json!(path)); + if let Some(trigger_kind) = trigger_kind { + out.insert("triggerKind".into(), json!(trigger_kind)); + } + if let Some(url) = url { + out.insert("url".into(), json!(url)); + } + pretty(&Value::Object(out)) +} + +/// Where a deployed item is seen in Windmill. +fn deployed_page(item_type: &str, path: &str, value: &Value) -> Option { + Some(match item_type { + "script" => format!("/scripts/get/{path}"), + "flow" => format!("/flows/get/{path}"), + "app" => format!("/apps_raw/get/{path}"), + "variable" => format!("/variables#{path}"), + "resource" if super::workspace::is_agent(value) => format!("/agents/get/{path}"), + "resource" => format!("/resources#/resource/{path}"), + "schedule" => format!("/schedules#{path}"), + _ => return None, + }) +} + +async fn deploy_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let item_type = item_type_arg(args)?; + let path = str_arg(args, "path")?; + let trigger_kind = opt_str_arg(args, "trigger_kind"); + let message = opt_str_arg(args, "deployment_message"); + let force = bool_arg(args, "force"); + if item_type == "trigger" && trigger_kind.is_none() { + return Err("trigger_kind is required when deploying a trigger.".to_string()); + } + let no_draft = || format!("No draft found for {item_type} \"{path}\"."); + let kind = draft_kind(item_type, trigger_kind).ok_or_else(no_draft)?; + let (item, draft) = get_draft_item(ctx, item_type, path, trigger_kind) + .await? + .ok_or_else(no_draft)?; + let value = item + .get("value") + .ok_or_else(|| format!("Draft {item_type} \"{path}\" has no value to deploy."))?; + + let mut note = None; + match item_type { + "script" => { + let head = if item_exists(ctx, "script", None, path).await? { + get_deployed(ctx, "script", None, path) + .await? + .get("hash") + .cloned() + } else { + None + }; + assert_draft_based_on_latest( + "script", + path, + item.get("parentHash"), + head.as_ref(), + force, + )?; + deploy_script(ctx, path, message).await?; + } + "flow" => { + let exists = item_exists(ctx, "flow", None, path).await?; + let head = if exists { + get_deployed(ctx, "flow", None, path) + .await? + .get("version_id") + .cloned() + } else { + None + }; + assert_draft_based_on_latest( + "flow", + path, + item.get("parentVersionId"), + head.as_ref(), + force, + )?; + deploy_flow(ctx, path, !exists, message).await?; + } + "variable" => note = deploy_variable(ctx, path, value).await?, + "resource" => deploy_resource(ctx, path, value).await?, + "app" => note = deploy_app(ctx, path, &item, value, message, force).await?, + _ => upsert(ctx, item_type, trigger_kind, path, value.clone()).await?, + } + + // The baseline keeps a draft saved since the read above from being deleted undeployed. + delete_draft(ctx, &kind, path, draft.created_at.as_deref()).await?; + + let note = note.map(|note| format!(" {note}")).unwrap_or_default(); + Ok(mutation_result( + format!("Deployed draft {item_type} \"{path}\" to the workspace. Draft removed.{note}"), + item_type, + path, + trigger_kind, + deployed_page(item_type, path, value).map(|page| ctx.page_url(&page)), + )) +} + +// ============================================================================ +// delete_workspace_item +// ============================================================================ + +async fn delete_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let item_type = item_type_arg(args)?; + let path = str_arg(args, "path")?; + let trigger_kind = opt_str_arg(args, "trigger_kind"); + if item_type == "trigger" && trigger_kind.is_none() { + return Err("trigger_kind is required when deleting a trigger.".to_string()); + } + // Undoing a draft is a discard, not a delete: say so before the delete route 404s. + if !deployed_item_exists(ctx, item_type, trigger_kind, path).await? { + let draft = get_draft_item(ctx, item_type, path, trigger_kind).await?; + return Err(if draft.is_some() { + format!( + "No deployed {item_type} at \"{path}\" — it only exists as a draft, so there is nothing to delete \ + from the workspace. Call discard_local_draft with the same arguments to remove the draft." + ) + } else { + format!("No {item_type} at \"{path}\": neither a deployed item nor a draft. Nothing to delete.") + }); + } + + let path_in_url = path_enc(path); + if item_type == "script" { + ctx.request( + "POST", + &ctx.ws(&format!("scripts/delete/p/{path_in_url}")), + None, + ) + .await?; + } else { + ctx.delete(&ctx.ws(&format!( + "{}/delete/{path_in_url}", + service(item_type, trigger_kind)? + ))) + .await?; + } + if let Some(kind) = draft_kind(item_type, trigger_kind) { + delete_draft(ctx, &kind, path, None).await?; + } + Ok(mutation_result( + format!( + "Deleted {item_type} \"{path}\" from the workspace. Any matching draft was also cleared." + ), + item_type, + path, + trigger_kind, + None, + )) +} + +// ============================================================================ +// Stable YAML: what the session's `yaml` library prints for +// `stringify(value, { sortMapEntries: true, aliasDuplicateObjects: false, lineWidth: 0 })`, +// so a diff reads the same here as in a session. +// ============================================================================ + +static YAML_CONTROL_CHARS: LazyLock = + LazyLock::new(|| Regex::new(r"[\x00-\x08\x0b-\x1f\x7f-\u{9f}]").expect("valid regex")); +static YAML_NOT_PLAIN: LazyLock = LazyLock::new(|| { + Regex::new( + r#"^[\n\t ,\[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$"#, + ) + .expect("valid regex") +}); +/// Plain scalars the core schema would read back as null, a boolean or a number. +static YAML_NOT_A_STRING: LazyLock = LazyLock::new(|| { + Regex::new(concat!( + r"^(?:~|[Nn]ull|NULL)?$", + r"|^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$", + r"|^0o[0-7]+$|^[-+]?[0-9]+$|^0x[0-9a-fA-F]+$", + r"|^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$", + r"|^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$", + r"|^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$", + )) + .expect("valid regex") +}); +static YAML_DOCUMENT_MARKER: LazyLock = + LazyLock::new(|| Regex::new(r"(?m)^(%|---|\.\.\.)").expect("valid regex")); + +/// Null object properties are dropped so `field: null` never diffs against an absent +/// field; array elements are kept so positions stay aligned. +fn prune_nulls(value: &Value) -> Value { + match value { + Value::Array(items) => Value::Array(items.iter().map(prune_nulls).collect()), + Value::Object(map) => Value::Object( + map.iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k.clone(), prune_nulls(v))) + .collect(), + ), + other => other.clone(), + } +} + +fn to_stable_yaml(value: Option<&Value>) -> String { + match value { + None | Some(Value::Null) => String::new(), + Some(value) => yaml_node(&prune_nulls(value), "") + "\n", + } +} + +fn yaml_node(value: &Value, indent: &str) -> String { + let nested = format!("{indent} "); + match value { + Value::Null => "null".to_string(), + Value::Bool(b) => b.to_string(), + Value::Number(n) => yaml_number(n), + Value::String(s) => yaml_string(s, indent, false), + Value::Array(items) if items.is_empty() => "[]".to_string(), + Value::Object(map) if map.is_empty() => "{}".to_string(), + Value::Array(items) => items + .iter() + .map(|item| format!("- {}", yaml_node(item, &nested))) + .collect::>() + .join(&format!("\n{indent}")), + Value::Object(map) => { + let mut entries: Vec<(&String, &Value)> = map.iter().collect(); + entries.sort_by(|a, b| a.0.cmp(b.0)); + entries + .into_iter() + .map(|(key, value)| { + let key = yaml_string(key, &nested, true); + let rendered = yaml_node(value, &nested); + let is_block = match value { + Value::Array(items) => !items.is_empty(), + Value::Object(map) => !map.is_empty(), + _ => false, + }; + if is_block { + format!("{key}:\n{nested}{rendered}") + } else { + format!("{key}: {rendered}") + } + }) + .collect::>() + .join(&format!("\n{indent}")) + } + } +} + +// ponytail: prints what Rust prints for a float. JS switches to exponent notation +// below 1e-6 and from 1e21, and rounds integers past 2^53; port Number#toString if a +// diff of such numbers ever has to match a session's byte for byte. +fn yaml_number(n: &serde_json::Number) -> String { + match n.as_f64() { + Some(f) if !n.is_i64() && !n.is_u64() && f.fract() == 0.0 && f.abs() < 1e21 => { + format!("{f:.0}") + } + _ => n.to_string(), + } +} + +fn yaml_string(value: &str, indent: &str, implicit_key: bool) -> String { + if YAML_CONTROL_CHARS.is_match(value) { + return yaml_double_quoted(value, indent, implicit_key); + } + let multiline = value.contains('\n'); + if implicit_key && multiline { + return yaml_quoted(value, indent, implicit_key); + } + if multiline { + return yaml_block(value, indent); + } + let top_level_key = implicit_key && indent.len() == 2; + if YAML_NOT_PLAIN.is_match(value) + || YAML_NOT_A_STRING.is_match(value) + || (top_level_key && YAML_DOCUMENT_MARKER.is_match(value)) + { + return yaml_quoted(value, indent, implicit_key); + } + value.to_string() +} + +fn yaml_quoted(value: &str, indent: &str, implicit_key: bool) -> String { + let single = value.contains('"') && !value.contains('\'') && !value.contains('\n'); + if single { + format!("'{}'", value.replace('\'', "''")) + } else { + yaml_double_quoted(value, indent, implicit_key) + } +} + +/// Lines of a double-quoted scalar shorter than this stay on one line, newlines escaped. +const YAML_MIN_MULTILINE_LENGTH: usize = 40; + +fn yaml_double_quoted(value: &str, indent: &str, implicit_key: bool) -> String { + let json: Vec = serde_json::to_string(value) + .unwrap_or_default() + .chars() + .collect(); + let at = |i: usize| json.get(i).copied(); + let mut out = String::new(); + let mut start = 0; + let mut i = 0; + while i < json.len() { + let mut ch = json[i]; + // A space before a line break would be folded away unless escaped. + if ch == ' ' && at(i + 1) == Some('\\') && at(i + 2) == Some('n') { + out.extend(&json[start..i]); + out.push_str("\\ "); + i += 1; + start = i; + ch = '\\'; + } + if ch == '\\' { + match at(i + 1) { + Some('u') => { + out.extend(&json[start..i]); + let code: String = json[i + 2..(i + 6).min(json.len())].iter().collect(); + match code.as_str() { + "0000" => out.push_str("\\0"), + "0007" => out.push_str("\\a"), + "000b" => out.push_str("\\v"), + "001b" => out.push_str("\\e"), + _ if code.starts_with("00") => out.push_str(&format!("\\x{}", &code[2..])), + _ => out.push_str(&format!("\\u{code}")), + } + i += 5; + start = i + 1; + } + Some('n') => { + if implicit_key + || at(i + 2) == Some('"') + || json.len() < YAML_MIN_MULTILINE_LENGTH + { + i += 1; + } else { + // A real line break; the reader folds the first one away. + out.extend(&json[start..i]); + out.push_str("\n\n"); + while at(i + 2) == Some('\\') + && at(i + 3) == Some('n') + && at(i + 4) != Some('"') + { + out.push('\n'); + i += 2; + } + out.push_str(indent); + if at(i + 2) == Some(' ') { + out.push('\\'); + } + i += 1; + start = i + 1; + } + } + _ => i += 1, + } + } + i += 1; + } + if start == 0 { + return json.into_iter().collect(); + } + out.extend(&json[start.min(json.len())..]); + out +} + +/// Appends `indent` after every run of line breaks; `inner_only` leaves a run that +/// ends the text alone. +fn indent_after_breaks(text: &str, indent: &str, inner_only: bool) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(ch) = chars.next() { + out.push(ch); + if ch == '\n' && chars.peek() != Some(&'\n') && !(inner_only && chars.peek().is_none()) { + out.push_str(indent); + } + } + out +} + +/// A literal block scalar, so multi-line text (code most of all) diffs line by line. +fn yaml_block(value: &str, indent: &str) -> String { + let is_space = |c: char| matches!(c, '\n' | '\t' | ' '); + let body_len = value.trim_end_matches(is_space).len(); + let (mut body, mut end) = value.split_at(body_len); + // A block cannot end in whitespace-only text after its last line break. + if end + .rfind('\n') + .is_some_and(|last_break| last_break + 1 < end.len()) + { + return yaml_quoted(value, indent, false); + } + let chomp = match end.find('\n') { + None => "-", + Some(first_break) if body.is_empty() || first_break != end.len() - 1 => "+", + Some(_) => "", + }; + end = end.strip_suffix('\n').unwrap_or(end); + let end = indent_after_breaks(end, indent, true); + + // Leading spaces need an explicit indentation indicator; leading line breaks are + // kept ahead of the body. + let lead_len = body.len() - body.trim_start_matches([' ', '\n']).len(); + let lead = &body[..lead_len]; + let starts_with_space = lead.contains(' '); + let start = lead.rfind('\n').map(|i| &lead[..=i]).unwrap_or(""); + body = &body[start.len()..]; + let indicator = match (starts_with_space, indent.is_empty()) { + (false, _) => "", + (true, true) => "1", + (true, false) => "2", + }; + format!( + "|{indicator}{chomp}\n{indent}{}{}{end}", + indent_after_breaks(start, indent, false), + indent_after_breaks(body, indent, false), + ) +} + +// ============================================================================ +// Patches +// ============================================================================ + +fn line_count(patch: &str) -> usize { + if patch.is_empty() { + 0 + } else { + patch.split('\n').count() + } +} + +/// Unified patch between two sides of an item, `""` when they render the same. +fn yaml_patch(before: Option<&Value>, after: Option<&Value>, labels: (&str, &str)) -> String { + let (before, after) = (to_stable_yaml(before), to_stable_yaml(after)); + if before == after { + return String::new(); + } + unified_patch(labels.0, labels.1, &before, &after, 3) +} + +/// Unified patch between two raw files; an absent side reads as empty. +fn text_patch(before: Option<&str>, after: Option<&str>, labels: (&str, &str)) -> String { + let (before, after) = (before.unwrap_or(""), after.unwrap_or("")); + if before == after { + return String::new(); + } + unified_patch(labels.0, labels.1, before, after, 3) +} + +/// Indices of the added and removed lines of a patch. The `---`/`+++` file labels only +/// occur ahead of the first hunk, while a changed source line may itself start with +/// `++` or `--`. +fn changed_line_indices(patch: &str) -> Vec { + let mut in_hunk = false; + let mut indices = Vec::new(); + for (i, line) in patch.split('\n').enumerate() { + if line.starts_with("@@") { + in_hunk = true; + } else if in_hunk && (line.starts_with('+') || line.starts_with('-')) { + indices.push(i); + } + } + indices +} + +const MAX_DIFF_PATCH_CHARS: usize = 50_000; +const DIFF_READ_DEFAULT_LINES: usize = 500; + +/// A window of a patch by lines, with a character backstop. When the backstop cuts +/// inside the window the continuation offset advances past the complete lines +/// delivered only, or the rest of the window would be skipped for good. +fn window_patch(patch: &str, offset: usize, limit: usize, max_chars: usize) -> String { + let lines: Vec<&str> = patch.split('\n').collect(); + let total = lines.len(); + if offset >= total { + return format!( + "(no lines at offset {offset} — the patch has {total} lines; call again with a smaller offset)" + ); + } + let requested_end = total.min(offset.saturating_add(limit)); + let mut body = lines[offset..requested_end].join("\n"); + let mut effective_end = requested_end; + let mut note = String::new(); + if body.chars().count() > max_chars { + body = body.chars().take(max_chars).collect(); + match body.rfind('\n') { + // One line over the whole budget: deliver its head and step past it. + None => { + effective_end = offset + 1; + note = format!("\n… [line truncated at {max_chars} chars]"); + } + Some(last_break) => { + body.truncate(last_break); + effective_end = offset + body.split('\n').count(); + note = format!("\n… window truncated at {max_chars} chars."); + } + } + } + if offset > 0 || effective_end < total { + let rest = if effective_end < total { + format!("; call diff again with offset={effective_end} for the rest") + } else { + String::new() + }; + note.push_str(&format!( + "\n(lines {}-{effective_end} of {total}{rest})", + offset + 1 + )); + } + body + note.as_str() +} + +struct FileDiff { + status: &'static str, + patch: String, + line_count: usize, +} + +#[derive(Default)] +struct DiffParts { + /// The whole-value patch, or the config-only patch of a multi-file app. + patch: String, + /// Changed files of a multi-file app, by name. + files: Option>, + line_count: usize, + has_changes: bool, +} + +/// A map of string contents marks a multi-file app value. +fn app_files(value: Option<&Value>) -> Option<&Map> { + value? + .get("files")? + .as_object() + .filter(|files| !files.is_empty() && files.values().all(Value::is_string)) +} + +/// Per-file text patches plus a config-only patch for a multi-file app, one whole-value +/// YAML patch for anything else. +fn diff_parts(before: Option<&Value>, after: Option<&Value>, labels: (&str, &str)) -> DiffParts { + let (before_files, after_files) = (app_files(before), app_files(after)); + if before_files.is_none() && after_files.is_none() { + let patch = yaml_patch(before, after, labels); + return DiffParts { + line_count: line_count(&patch), + has_changes: !patch.is_empty(), + patch, + files: None, + }; + } + let mut names: Vec<&String> = before_files + .into_iter() + .chain(after_files) + .flat_map(|files| files.keys()) + .collect(); + names.sort(); + names.dedup(); + fn content<'a>(files: Option<&'a Map>, name: &str) -> Option<&'a str> { + files?.get(name)?.as_str() + } + let mut files = Vec::new(); + let mut total = 0; + for name in names { + let (old, new) = (content(before_files, name), content(after_files, name)); + let patch = text_patch(old, new, labels); + // An empty file appearing or disappearing yields no patch, but its presence + // is a change in its own right. + if patch.is_empty() && old.is_some() == new.is_some() { + continue; + } + let line_count = line_count(&patch); + total += line_count; + let status = match (old, new) { + (None, _) => "added", + (_, None) => "deleted", + _ => "modified", + }; + files.push((name.clone(), FileDiff { status, patch, line_count })); + } + let config = |side: Option<&Value>| { + side.map(|v| { + if v.is_object() { + without(v, &["files"]) + } else { + v.clone() + } + }) + }; + let patch = yaml_patch(config(before).as_ref(), config(after).as_ref(), labels); + DiffParts { + line_count: total + line_count(&patch), + has_changes: !files.is_empty() || !patch.is_empty(), + patch, + files: Some(files), + } +} + +// ============================================================================ +// The two sides of a draft +// ============================================================================ + +/// The per-user markers a `get_draft=true` read adds beside the deployed item. +const OVERLAY_KEYS: &[&str] = &[ + "draft", + "is_draft", + "draft_saved_at", + "draft_base", + "no_deployed", + "other_drafts_users", +]; + +/// Server-managed script fields: identical noise, or recomputed at every deploy. +const SCRIPT_RUNTIME_KEYS: &[&str] = &[ + "workspace_id", + "hash", + "parent_hash", + "parent_hashes", + "created_at", + "created_by", + "archived", + "deleted", + "extra_perms", + "lock", + "lock_error_logs", + "starred", + "has_draft", + "draft_only", + "assets", + "marked", +]; + +/// Runtime fields of a schedule or trigger, which the workspace comparison ignores too. +const TRIGGER_RUNTIME_KEYS: &[&str] = &[ + "workspace_id", + "edited_by", + "edited_at", + "email", + "error", + "enabled", + "mode", + "server_id", + "last_server_ping", + "extra_perms", + "permissioned_as", + "subscription_id", + "push_auth_config", +]; + +struct DraftSides { + deployed: Value, + draft: Value, + /// False when the read carried no draft, and the item's own value stood in for it. + has_draft: bool, + /// True when the item was never deployed. + no_deployed: bool, +} + +/// A raw app on the flat draft shape, without the inline-script locks the server +/// recomputes at every deploy. +fn canonical_raw_app(source: &Value, path: Option<&Value>) -> Value { + let mut value = app_source_to_draft_value(source, None); + if let Some(runnables) = value.get_mut("runnables").and_then(Value::as_object_mut) { + for runnable in runnables.values_mut() { + if let Some(inline) = runnable + .get_mut("inlineScript") + .and_then(Value::as_object_mut) + { + inline.shift_remove("lock"); + } + } + } + // A staged rename changes where a deploy lands the app, so the path is compared too. + if let (Some(path), Some(value)) = (path, value.as_object_mut()) { + value.insert("path".into(), path.clone()); + } + value +} + +/// A low-code app draft split into its grid and the metadata the editor mirrors into +/// it: `(value, summary, draft_path)`. +fn classic_app_parts(json: Option<&Value>) -> (Value, Option, Option) { + let Some(Value::Object(obj)) = json else { + return (json.cloned().unwrap_or(Value::Null), None, None); + }; + // A legacy draft wraps the grid; a bare app always carries `grid` at the top. + let inner = obj.get("value").filter(|v| v.get("grid").is_some()); + if let (false, Some(inner)) = (obj.contains_key("grid"), inner) { + let (value, summary, draft_path) = classic_app_parts(Some(inner)); + let outer = |key: &str| obj.get(key).filter(|v| !v.is_null()).cloned(); + return ( + value, + outer("summary").or(summary), + outer("draft_path").or(draft_path), + ); + } + let mut value = obj.clone(); + value.shift_remove("parent_version"); + let draft_path = value.shift_remove("draft_path").filter(|v| !v.is_null()); + let summary = value.shift_remove("summary").filter(|v| !v.is_null()); + (Value::Object(value), summary, draft_path) +} + +/// A variable, resource, schedule or trigger on one field set, whether it comes as the +/// deployed row or as the editor state a draft stores. +fn canonical_drawer_value(kind: &str, raw: &Value, is_draft: bool) -> Value { + if !raw.is_object() { + return json!({}); + } + let or_empty = + |value: Option<&Value>| value.filter(|v| !v.is_null()).cloned().unwrap_or(json!("")); + let ws_specific = if is_draft { + "wsSpecific" + } else { + "ws_specific" + }; + let mut out = Map::new(); + match kind { + "variable" => { + let empty = json!({}); + let variable = if is_draft { + non_null(raw.get("variable")).unwrap_or(&empty) + } else { + raw + }; + let is_secret = truthy(variable.get("is_secret")); + out.insert( + "value".into(), + if is_secret { + json!("") + } else { + or_empty(variable.get("value")) + }, + ); + out.insert("is_secret".into(), json!(is_secret)); + out.insert("description".into(), or_empty(variable.get("description"))); + } + "resource" => { + let key = if is_draft { "args" } else { "value" }; + let mut value = non_null(raw.get(key)).cloned().unwrap_or(json!({})); + // An agent's identity is in its deployed value and never in a draft: not an edit. + if raw.get("resource_type").and_then(Value::as_str) == Some("ai_agent") { + if let Some(value) = value.as_object_mut() { + value.shift_remove("on_behalf_of"); + } + } + out.insert("value".into(), value); + out.insert("description".into(), or_empty(raw.get("description"))); + if let Some(resource_type) = non_null(raw.get("resource_type")) { + out.insert("resource_type".into(), resource_type.clone()); + } + } + _ => return without(raw, TRIGGER_RUNTIME_KEYS), + } + if let Some(labels) = non_null(raw.get("labels")) { + out.insert("labels".into(), labels.clone()); + } + if let Some(ws_specific) = non_null(raw.get(ws_specific)) { + out.insert("ws_specific".into(), ws_specific.clone()); + } + Value::Object(out) +} + +/// The deployed value and the draft value of an item, each normalised so that only a +/// real change differs. `kind` is a draft kind; an item that is neither deployed nor +/// drafted is the API's 404. +async fn draft_sides(ctx: &Ctx<'_>, kind: &str, path: &str) -> Result { + let path_in_url = path_enc(path); + let route = match kind { + "script" => format!("scripts/get/p/{path_in_url}?get_draft=true"), + "flow" => format!("flows/get/{path_in_url}?get_draft=true"), + // The server resolves a never-deployed app's draft kind from `raw_app`. + "app" | "raw_app" => format!( + "apps/get/p/{path_in_url}?get_draft=true&raw_app={}", + kind == "raw_app" + ), + "variable" => format!("variables/get/{path_in_url}?decrypt_secret=false&get_draft=true"), + "resource" => format!("resources/get/{path_in_url}?get_draft=true"), + "trigger_schedule" => format!("schedules/get/{path_in_url}?get_draft=true"), + _ => { + let trigger_kind = kind + .strip_prefix("trigger_") + .filter(|k| TRIGGER_KINDS.contains(k)) + .ok_or_else(|| format!("Draft diff not supported for kind {kind}"))?; + format!("{trigger_kind}_triggers/get/{path_in_url}?get_draft=true") + } + }; + Ok(sides_of_row(kind, &ctx.get(&ctx.ws(&route)).await?)) +} + +/// Splits a `get_draft=true` read into its two sides. +fn sides_of_row(kind: &str, row: &Value) -> DraftSides { + let draft = non_null(row.get("draft")); + let has_draft = draft.is_some(); + let no_deployed = row.get("no_deployed") == Some(&Value::Bool(true)); + let deployed = without(row, OVERLAY_KEYS); + let (deployed, draft) = match kind { + "script" => ( + without(&deployed, SCRIPT_RUNTIME_KEYS), + without(draft.unwrap_or(&deployed), SCRIPT_RUNTIME_KEYS), + ), + // The base a draft pinned differs from the head when it is stale: not a change. + "flow" => ( + without(&deployed, &["version_id"]), + without(draft.unwrap_or(&deployed), &["version_id"]), + ), + "app" | "raw_app" + if kind == "raw_app" || row.get("raw_app") == Some(&Value::Bool(true)) => + { + let row_path = row.get("path"); + let staged_path = draft + .and_then(|d| non_null(d.get("draft_path"))) + .or(row_path); + ( + canonical_raw_app(row, row_path), + canonical_raw_app(draft.unwrap_or(row), staged_path), + ) + } + "app" => { + let row_summary = non_null(row.get("summary")).cloned().unwrap_or(json!("")); + let deployed_parts = classic_app_parts(row.get("value")); + let value = deployed_parts.0.clone(); + let (draft_value, summary, draft_path) = match draft { + Some(draft) => classic_app_parts(Some(draft)), + None => deployed_parts, + }; + ( + json!({ "summary": row_summary, "value": value, "path": row.get("path") }), + json!({ + "summary": summary.unwrap_or(row_summary.clone()), + "value": draft_value, + "path": draft_path.or_else(|| row.get("path").cloned()), + }), + ) + } + _ => ( + canonical_drawer_value(kind, &deployed, false), + canonical_drawer_value(kind, draft.unwrap_or(&deployed), true), + ), + }; + DraftSides { deployed, draft, has_draft, no_deployed } +} + +const VARIABLE_VALUE_PLACEHOLDER: &str = ""; +const VARIABLE_VALUE_CHANGED_PLACEHOLDER: &str = ""; +const VARIABLE_MASKED_NOTE: &str = "Note: variable values are never shown in chat — the diff marks whether the value changed without revealing it.\n\n"; +const SECRET_UNCOMPARABLE_NOTE: &str = "Note: this is a SECRET variable — its value is never shown and cannot be compared, so it may ALSO have changed beyond what this diff shows.\n\n"; + +/// A variable's value never reaches a tool result, secret or not: both sides get a +/// placeholder that still shows WHETHER a readable value changed. The flag is set for a +/// secret, whose sides are never comparable — the deployed value is not decrypted and a +/// draft holds a marker — so equal sides prove nothing. +fn mask_variable_sides(before: &mut Option, after: &mut Option) -> bool { + let object = |side: &Option| side.as_ref().is_some_and(Value::is_object); + let both = object(before) && object(after); + let is_secret = |side: &Option| { + side.as_ref().and_then(|v| v.get("is_secret")) == Some(&Value::Bool(true)) + }; + let secret = is_secret(before) || is_secret(after); + let value = |side: &Option| side.as_ref().and_then(|v| v.get("value")).cloned(); + let changed = !secret && both && value(before) != value(after); + if let Some(Value::Object(before)) = before { + before.insert("value".into(), json!(VARIABLE_VALUE_PLACEHOLDER)); + } + if let Some(Value::Object(after)) = after { + let placeholder = if changed { + VARIABLE_VALUE_CHANGED_PLACEHOLDER + } else { + VARIABLE_VALUE_PLACEHOLDER + }; + after.insert("value".into(), json!(placeholder)); + } + secret && both +} + +// ============================================================================ +// diff +// ============================================================================ + +/// One of the caller's drafts, as the drafts listing reports it. +struct DraftRow { + kind: String, + /// The path the draft is stored under. + path: String, + /// The path the item is known by: a staged name when there is one. + display_path: String, + /// The item type and trigger kind a tool addresses the draft by, if any does. + addressing: Option<(&'static str, Option<&'static str>)>, +} + +fn addressing_of(kind: &str) -> Option<(&'static str, Option<&'static str>)> { + Some(match kind { + "script" => ("script", None), + "flow" => ("flow", None), + "resource" => ("resource", None), + "variable" => ("variable", None), + "app" | "raw_app" => ("app", None), + "trigger_schedule" => ("schedule", None), + _ => { + let trigger_kind = kind.strip_prefix("trigger_")?; + let trigger_kind = TRIGGER_KINDS.iter().find(|k| **k == trigger_kind)?; + ("trigger", Some(*trigger_kind)) + } + }) +} + +/// The caller's drafts, and how many drafts other users hold in the workspace. +async fn list_draft_rows(ctx: &Ctx<'_>) -> Result<(Vec, usize), String> { + let rows = ctx.get(&ctx.ws("drafts/list?all_users=true")).await?; + let rows = array(Some(&rows)); + let mine: Vec = rows + .iter() + .filter(|row| row.get("mine") != Some(&Value::Bool(false))) + .filter_map(|row| { + let kind = row.get("kind")?.as_str()?; + let path = row.get("path")?.as_str()?; + let display_path = row + .get("draft_path") + .and_then(Value::as_str) + .filter(|p| !p.is_empty()) + .unwrap_or(path); + Some(DraftRow { + kind: kind.to_string(), + path: path.to_string(), + display_path: display_path.to_string(), + addressing: addressing_of(kind), + }) + }) + .collect(); + let others = rows.len() - mine.len(); + Ok((mine, others)) +} + +/// A draft's computed diff against what is deployed. +#[derive(Default)] +struct Materialized { + parts: DiffParts, + /// Variable content was masked: the patch marks a value change without showing it. + value_masked: bool, + value_uncomparable: bool, + no_deployed: bool, + error: Option, +} + +async fn materialize(ctx: &Ctx<'_>, kind: &str, path: &str) -> Materialized { + match draft_sides(ctx, kind, path).await { + Ok(sides) => materialized_of(kind, sides), + Err(e) => { + let error = if is_not_found(&e) { + "item not found (the draft may reference a deleted item)".to_string() + } else { + e + }; + Materialized { error: Some(error), ..Default::default() } + } + } +} + +fn materialized_of(kind: &str, sides: DraftSides) -> Materialized { + let mut before = (!sides.no_deployed).then_some(sides.deployed); + let mut after = Some(sides.draft); + let value_masked = kind == "variable"; + let value_uncomparable = value_masked && mask_variable_sides(&mut before, &mut after); + Materialized { + parts: diff_parts(before.as_ref(), after.as_ref(), ("deployed", "draft")), + value_masked, + value_uncomparable, + no_deployed: sides.no_deployed, + error: None, + } +} + +/// What an item read prints for a multi-file app: one file's patch when `file` is +/// given, otherwise the per-file summary plus the config changes. +fn render_files( + files: &[(String, FileDiff)], + config_patch: &str, + file: Option<&str>, + offset: usize, + limit: usize, +) -> ToolResult { + let window = |patch: &str| window_patch(patch, offset, limit, MAX_DIFF_PATCH_CHARS); + if let Some(requested) = file { + // App files are keyed with a leading slash: the slash-less spelling and a + // unique base name are accepted too. + let suffix = format!("/{}", requested.strip_prefix('/').unwrap_or(requested)); + let by_suffix: Vec<_> = files.iter().filter(|(n, _)| n.ends_with(&suffix)).collect(); + let resolved = files + .iter() + .find(|(name, _)| name == requested) + .or_else(|| { + files + .iter() + .find(|(name, _)| *name == format!("/{requested}")) + }) + .or_else(|| (by_suffix.len() == 1).then(|| by_suffix[0])); + let Some((name, file_diff)) = resolved else { + let names: Vec<&str> = files.iter().map(|(name, _)| name.as_str()).collect(); + let changed = if names.is_empty() { + "(none)".to_string() + } else { + names.join(", ") + }; + return Err(format!( + "No changes in file \"{requested}\". Changed files: {changed}." + )); + }; + if file_diff.patch.is_empty() { + return Ok(format!( + "File \"{name}\" was {} with empty content.", + file_diff.status + )); + } + return Ok(window(&file_diff.patch)); + } + let mut sections = Vec::new(); + if files.is_empty() { + sections.push("No file contents changed.".to_string()); + } else { + let lines: Vec = files + .iter() + .map(|(name, file_diff)| { + let size = match (file_diff.status, file_diff.line_count) { + ("deleted", _) => String::new(), + (_, 0) => " (empty file)".to_string(), + (_, n) => format!(" ({n} diff lines)"), + }; + format!("- {name} — {}{size}", file_diff.status) + }) + .collect(); + sections.push(format!( + "{} file(s) changed:\n{}\nRead one with file=\"\".", + lines.len(), + lines.join("\n") + )); + } + if !config_patch.is_empty() { + sections.push(format!("Config changes:\n{}", window(config_patch))); + } + Ok(sections.join("\n\n")) +} + +async fn diff_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let non_empty = |name: &str| opt_str_arg(args, name).filter(|s| !s.is_empty()); + let (Some(item_type), Some(path)) = (non_empty("type"), non_empty("path")) else { + return Err("type is required when path is provided.".to_string()); + }; + if !ITEM_TYPES.contains(&item_type) { + return Err(format!("Invalid type \"{item_type}\"")); + } + let kind = draft_kind(item_type, opt_str_arg(args, "trigger_kind")) + .ok_or("trigger_kind is required when type is trigger.")?; + let file = opt_str_arg(args, "file"); + let offset = uint_arg(args, "offset").unwrap_or(0); + let limit = uint_arg(args, "limit").unwrap_or(DIFF_READ_DEFAULT_LINES); + + // The listing is what knows a draft parked under a synthetic key by the name staged + // for it, and which of the two app kinds a draft at this path is. + let kinds: &[&str] = if item_type == "app" { + &["raw_app", "app"] + } else { + &[kind.as_str()] + }; + let (rows, _) = list_draft_rows(ctx).await?; + let listed = kinds + .iter() + .find_map(|kind| rows.iter().find(|r| r.kind == *kind && r.path == path)) + .or_else(|| { + rows.iter().find(|r| { + kinds.contains(&r.kind.as_str()) && (r.display_path == path || r.path == path) + }) + }); + + let mut caveat = ""; + let (parts, no_deployed, value_uncomparable) = match listed { + Some(row) => { + let m = materialize(ctx, &row.kind, &row.path).await; + if let Some(error) = m.error { + return Err(format!("Could not diff {item_type} \"{path}\": {error}")); + } + if m.value_masked { + caveat = if m.value_uncomparable { + SECRET_UNCOMPARABLE_NOTE + } else { + VARIABLE_MASKED_NOTE + }; + } + (m.parts, m.no_deployed, m.value_uncomparable) + } + // Not listed: no draft at all, nothing at the path, or a draft the listing + // does not show. The item's own read settles which. + None => { + let sides = draft_sides(ctx, &kind, path).await.map_err(|e| { + if is_not_found(&e) { + format!( + "No {item_type} found at \"{path}\" — it has neither a deployed version nor a draft." + ) + } else { + e + } + })?; + if !sides.no_deployed && !sides.has_draft { + return Ok(format!( + "No draft exists for {item_type} \"{path}\" — the deployed version is current." + )); + } + let mut before = (!sides.no_deployed).then_some(sides.deployed); + let mut after = Some(sides.draft); + let mut value_uncomparable = false; + if kind == "variable" { + value_uncomparable = mask_variable_sides(&mut before, &mut after); + caveat = if value_uncomparable { + SECRET_UNCOMPARABLE_NOTE + } else { + VARIABLE_MASKED_NOTE + }; + } + let patch = yaml_patch(before.as_ref(), after.as_ref(), ("deployed", "draft")); + ( + DiffParts { patch, ..Default::default() }, + sides.no_deployed, + value_uncomparable, + ) + } + }; + + let changed_files = parts.files.as_ref().map_or(0, Vec::len); + if parts.patch.is_empty() && changed_files == 0 { + // A secret is masked on both ends: an empty patch cannot prove it unchanged. + let message = if value_uncomparable { + format!( + "No visible changes for {item_type} \"{path}\" — but a secret's value cannot be compared and may have been updated in the draft." + ) + } else { + format!("Draft matches the deployed version of {item_type} \"{path}\" — no changes.") + }; + return Ok(format!("{caveat}{message}")); + } + let header = if no_deployed { + format!("{item_type} \"{path}\" has no deployed version yet — the entire draft is new.\n\n") + } else { + format!("Draft changes vs deployed for {item_type} \"{path}\":\n\n") + }; + let body = match &parts.files { + Some(files) => render_files(files, &parts.patch, file, offset, limit)?, + None if file.is_some() => { + return Err(format!( + "file only applies to multi-file apps; {item_type} \"{path}\" diffs as a single document — call again without file." + )) + } + None => window_patch(&parts.patch, offset, limit, MAX_DIFF_PATCH_CHARS), + }; + Ok(format!("{caveat}{header}{body}")) +} + +/// Patches computed per index read, so a workspace with hundreds of drafts still +/// answers; the rest report as pending and compute on an item read. +const EAGER_MATERIALIZE_CAP: usize = 50; +const FETCH_CONCURRENCY: usize = 6; +const DIFF_INDEX_DEFAULT_ITEMS: usize = 50; +const DIFF_INDEX_MAX_ITEMS: usize = 100; +const DIFF_INDEX_MAX_FILE_CHILDREN: usize = 20; + +struct IndexEntry { + row: DraftRow, + materialized: Option, +} + +/// Every draft of the caller with its diff, computed for the first `cap` addressable ones. +async fn diff_index_entries(ctx: &Ctx<'_>, cap: usize) -> Result<(Vec, usize), String> { + let (rows, others) = list_draft_rows(ctx).await?; + let eager: Vec = (0..rows.len()) + .filter(|i| rows[*i].addressing.is_some()) + .take(cap) + .collect(); + // Built ahead of the stream: a closure borrowing `rows` inside it does not make a + // `Send` future. + let fetches: Vec<_> = eager + .iter() + .map(|i| materialize(ctx, &rows[*i].kind, &rows[*i].path)) + .collect(); + let computed: Vec = stream::iter(fetches) + .buffered(FETCH_CONCURRENCY) + .collect() + .await; + let mut entries: Vec = rows + .into_iter() + .map(|row| IndexEntry { row, materialized: None }) + .collect(); + for (i, materialized) in eager.into_iter().zip(computed) { + entries[i].materialized = Some(materialized); + } + Ok((entries, others)) +} + +fn index_line(entry: &IndexEntry) -> String { + let row = &entry.row; + let Some((item_type, trigger_kind)) = row.addressing else { + return format!( + "- {} draft \"{}\" — not addressable in this chat", + row.kind, row.display_path + ); + }; + let label = match trigger_kind { + Some(trigger_kind) => format!("{trigger_kind} trigger"), + None => item_type.to_string(), + }; + let name = format!("{label} \"{}\"", row.display_path); + let Some(m) = &entry.materialized else { + return format!("- {name} — draft present (diff not computed yet; read it with type+path)"); + }; + let lines = m.parts.line_count; + match ( + &m.error, + m.no_deployed, + m.parts.has_changes, + m.value_uncomparable, + ) { + (Some(error), ..) => format!("- {name} — diff failed: {error}"), + (None, true, ..) => format!("- {name} — new, never deployed ({lines} lines)"), + (None, false, true, true) => { + format!("- {name} — modified ({lines} diff lines; secret value may also differ)") + } + (None, false, true, false) => format!("- {name} — modified ({lines} diff lines)"), + (None, false, false, true) => { + format!("- {name} — no visible changes (secret value cannot be compared; may differ)") + } + (None, false, false, false) => format!("- {name} — draft matches deployed"), + } +} + +/// The indented per-file rows under a multi-file app's index line. +fn file_children_lines(entry: &IndexEntry) -> Vec { + let Some(parts) = entry.materialized.as_ref().map(|m| &m.parts) else { + return Vec::new(); + }; + let Some(files) = &parts.files else { + return Vec::new(); + }; + let mut lines: Vec = files + .iter() + .take(DIFF_INDEX_MAX_FILE_CHILDREN) + .map(|(name, file_diff)| { + let size = match (file_diff.status, file_diff.line_count) { + ("deleted", _) => String::new(), + (_, 0) => " (empty file)".to_string(), + (_, n) => format!(" ({n} lines)"), + }; + format!(" · {name} — {}{size}", file_diff.status) + }) + .collect(); + if files.len() > DIFF_INDEX_MAX_FILE_CHILDREN { + lines.push(format!( + " · … {} more files", + files.len() - DIFF_INDEX_MAX_FILE_CHILDREN + )); + } + if !parts.patch.is_empty() { + lines.push(format!( + " · (config) — modified ({} lines)", + line_count(&parts.patch) + )); + } + lines +} + +async fn diff_index(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let (entries, others) = diff_index_entries(ctx, EAGER_MATERIALIZE_CAP).await?; + let types: Vec<&str> = args + .get("types") + .and_then(Value::as_array) + .map(|types| types.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let prefix = opt_str_arg(args, "path_prefix").filter(|p| !p.is_empty()); + let matching: Vec<&IndexEntry> = entries + .iter() + .filter(|e| { + types.is_empty() + || e.row + .addressing + .is_some_and(|(item_type, _)| types.contains(&item_type)) + }) + .filter(|e| { + prefix.is_none_or(|prefix| { + e.row.display_path.starts_with(prefix) || e.row.path.starts_with(prefix) + }) + }) + .collect(); + let total = matching.len(); + let limit = uint_arg(args, "limit") + .unwrap_or(DIFF_INDEX_DEFAULT_ITEMS) + .min(DIFF_INDEX_MAX_ITEMS); + let shown = &matching[..total.min(limit)]; + + let filtered = !types.is_empty() || prefix.is_some(); + let mut lines = vec![if total > 0 { + format!("{total} draft(s) vs deployed:") + } else if filtered && !entries.is_empty() { + format!( + "No drafts match your filters ({} draft(s) exist in the workspace).", + entries.len() + ) + } else { + "No drafts in this workspace — nothing differs from the deployed state.".to_string() + }]; + for entry in shown { + lines.push(index_line(entry)); + lines.extend(file_children_lines(entry)); + } + if total > shown.len() { + lines.push(format!( + "Showing {} of {total} drafts — narrow with types/path_prefix or raise limit.", + shown.len() + )); + } + if others > 0 { + lines.push(format!( + "{others} draft(s) by other users exist in this workspace (not shown — drafts are per-user)." + )); + } + Ok(lines.join("\n")) +} + +const DIFF_SEARCH_DEFAULT_MAX_MATCHES: usize = 50; +const DIFF_SEARCH_MAX_MATCHES_CEILING: usize = 200; +const SEARCH_CONTEXT_LINES: usize = 2; +const SEARCH_MAX_LINE_CHARS: usize = 200; +const SEARCH_TOTAL_CHAR_BUDGET: usize = 12_000; + +/// Literal, case-insensitive search over the changed lines of every draft's diff. +async fn diff_search(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let query = opt_str_arg(args, "search").unwrap_or_default(); + if query.is_empty() { + return Err("search requires a non-empty string.".to_string()); + } + if opt_str_arg(args, "against") == Some("parent_workspace") { + return Err(parent_comparison_unavailable(ctx).await); + } + let (entries, _) = diff_index_entries(ctx, usize::MAX).await?; + let file_glob = opt_str_arg(args, "file_glob").filter(|g| !g.is_empty()); + let max_matches = uint_arg(args, "max_matches") + .unwrap_or(DIFF_SEARCH_DEFAULT_MAX_MATCHES) + .min(DIFF_SEARCH_MAX_MATCHES_CEILING); + Ok(search_entries(&entries, query, file_glob, max_matches)) +} + +fn search_entries( + entries: &[IndexEntry], + query: &str, + file_glob: Option<&str>, + max_matches: usize, +) -> String { + // `(subject, patch)`: an item path, or `/` for a file inside an app. + let mut units: Vec<(String, &str)> = Vec::new(); + let mut failed: Vec<&str> = Vec::new(); + for entry in entries { + let Some(m) = &entry.materialized else { + continue; + }; + let path = entry.row.display_path.as_str(); + // A diff that could not be computed has no patch: reporting "no matches" for + // it would present an incomplete search as a definitive one. + if m.error.is_some() { + failed.push(path); + continue; + } + for (name, file_diff) in m.parts.files.iter().flatten() { + units.push(( + format!("{path}/{}", name.trim_start_matches('/')), + &file_diff.patch, + )); + } + if !m.parts.patch.is_empty() { + units.push((path.to_string(), &m.parts.patch)); + } + } + let mut warning = String::new(); + if !failed.is_empty() { + let one = failed.len() == 1; + warning = format!( + "\nWarning: {} could not be computed and {} NOT searched (matches may be missing): {}. Retry, or read the item{} directly for the error.", + if one { "this diff" } else { "these diffs" }, + if one { "was" } else { "were" }, + failed.join(", "), + if one { "" } else { "s" } + ); + } + if let Some(glob) = file_glob { + units.retain(|(subject, _)| matches_glob(subject, glob)); + } + // ponytail: byte order, where the session sorts with the locale's collation; the + // two only differ in which diff's matches come first. + units.sort_by(|a, b| a.0.cmp(&b.0)); + + let needle = query.to_lowercase(); + // `(unit, line index)` of every line to print: the matches and their context. + let mut rows: Vec<(usize, usize)> = Vec::new(); + let mut unit_lines: Vec> = Vec::new(); + let (mut total, mut rendered, mut subjects) = (0, 0, 0); + for (unit, (_, patch)) in units.iter().enumerate() { + let lines: Vec<&str> = patch.split('\n').collect(); + let mut unit_matched = false; + for i in changed_line_indices(patch) { + if !lines[i].to_lowercase().contains(&needle) { + continue; + } + total += 1; + unit_matched = true; + if rendered >= max_matches { + continue; + } + rendered += 1; + let last = (i + SEARCH_CONTEXT_LINES).min(lines.len() - 1); + rows.extend((i.saturating_sub(SEARCH_CONTEXT_LINES)..=last).map(|j| (unit, j))); + } + subjects += usize::from(unit_matched); + unit_lines.push(lines); + } + if total == 0 { + return format!( + "No changed lines match. Try a broader or differently-spelled term{}.{warning}", + if file_glob.is_some() { + ", or drop the file_glob" + } else { + "" + } + ); + } + + let plural = |n: usize| if n == 1 { "" } else { "s" }; + let header = format!( + "{total} changed line{} match in {subjects} diff{}{}", + plural(total), + plural(subjects), + if total > rendered { + format!( + " (showing the first {max_matches}; narrow with file_glob or a more specific query)" + ) + } else { + String::new() + } + ); + let mut spent = header.chars().count(); + let mut out = vec![header]; + let mut current_unit = None; + let mut seen = std::collections::HashSet::new(); + for row @ (unit, line) in rows { + if !seen.insert(row) { + continue; + } + let text = unit_lines[unit][line]; + let text = if text.chars().count() > SEARCH_MAX_LINE_CHARS { + let head: String = text.chars().take(SEARCH_MAX_LINE_CHARS).collect(); + format!("{head}… [line truncated]") + } else { + text.to_string() + }; + let subject = if current_unit == Some(unit) { + String::new() + } else { + format!("{}\n", units[unit].0) + }; + let row = format!("{subject} {}: {text}", line + 1); + let cost = row.chars().count() + 1; + if spent + cost > SEARCH_TOTAL_CHAR_BUDGET { + out.push( + "… output truncated at the context budget — narrow with file_glob or a more specific query." + .to_string(), + ); + break; + } + current_unit = Some(unit); + spent += cost; + out.push(row); + } + out.join("\n") + warning.as_str() +} + +/// Why `against="parent_workspace"` fails. A tool reaches the API with a credential +/// that is only valid in its own workspace, and the comparison reads the parent's +/// items under the caller's rights there. +async fn parent_comparison_unavailable(ctx: &Ctx<'_>) -> String { + let unavailable = "Comparing a fork with its parent workspace is not available on this server. Use diff without 'against' to compare drafts vs deployed versions, or the fork's compare page in Windmill for the comparison with the parent."; + let Ok(user) = ctx.get("/workspaces/users").await else { + return unavailable.to_string(); + }; + let workspace = user + .get("workspaces") + .and_then(Value::as_array) + .and_then(|workspaces| { + workspaces + .iter() + .find(|w| w.get("id").and_then(Value::as_str) == Some(ctx.w_id)) + }); + match workspace { + Some(workspace) if non_null(workspace.get("parent_workspace_id")).is_none() => format!( + "Workspace \"{}\" is not a fork — it has no parent workspace to compare against. Use diff without 'against' to compare drafts vs deployed versions.", + ctx.w_id + ), + _ => unavailable.to_string(), + } +} + +async fn diff(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + if args.get("search").is_some_and(|s| !s.is_null()) { + return diff_search(ctx, args).await; + } + if opt_str_arg(args, "against") == Some("parent_workspace") { + return Err(parent_comparison_unavailable(ctx).await); + } + if args.get("path").is_some_and(|p| !p.is_null()) { + diff_item(ctx, args).await + } else { + diff_index(ctx, args).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn yaml_matches_the_session_emitter() { + // Expected texts are what the session's `yaml` library prints for these values. + let scalars = json!({ "s": [ + "true", "~", "12", "1e3", "yes", "-", "- a", "a: b", "a:b", "#x", "a #b", "x ", + "\"q\"", "it's", "say \"hi\"", "@at", "a,b", "[x]", "?q", "---", " lead", + "0 0 12 * * *", "$encrypted:abc==", "", null, 1.0, -2.5e-3, [], {}, [[1, 2], ["a"]] + ], "gone": null }); + assert_eq!( + to_stable_yaml(Some(&scalars)), + "s:\n - \"true\"\n - \"~\"\n - \"12\"\n - \"1e3\"\n - yes\n - \"-\"\n - \"- a\"\n - \"a: b\"\n - a:b\n - \"#x\"\n - \"a #b\"\n - \"x \"\n - '\"q\"'\n - it's\n - say \"hi\"\n - \"@at\"\n - a,b\n - \"[x]\"\n - ?q\n - ---\n - \" lead\"\n - 0 0 12 * * *\n - $encrypted:abc==\n - \"\"\n - null\n - 1\n - -0.0025\n - []\n - {}\n - - - 1\n - 2\n - - a\n" + ); + + let blocks = json!({ + "content": "export async function main() {\n return 1\n}\n", + "one": "a\nb", "keep": "a\n\n", "keeps": "a\n\n\nb\n\n\n", + "lead": " indented\nnext", "leadnl": "\n\nx\n", "blank": "a\n\n\nb", + "wsend": "a\n ", "onlynl": "\n", "nlnl": "\n\n", "crlf": "a\r\nb\r\n", "ctrl": "a\u{7}b", + "longcrlf": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\nbbbbbbbbbbbbbbbbbbbbbbbb\r\n\r\n cccc \r\nd", + "z": " \nfoo", "x": "a\n\n \nb\n", + "seq": [{ "a": "x\ny\n", "b": [{ "c": "p\nq" }] }, "m\nn"], + }); + assert_eq!( + to_stable_yaml(Some(&blocks)), + "blank: |-\n a\n\n\n b\ncontent: |\n export async function main() {\n return 1\n }\ncrlf: \"a\\r\\nb\\r\\n\"\nctrl: \"a\\ab\"\nkeep: |+\n a\n\nkeeps: |+\n a\n\n\n b\n\n\nlead: |2-\n indented\n next\nleadnl: |\n \n\n x\nlongcrlf: \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\r\n\n bbbbbbbbbbbbbbbbbbbbbbbb\\r\n\n \\r\n\n \\ cccc \\r\n\n d\"\nnlnl: |+\n \n\none: |-\n a\n b\nonlynl: |+\n \nseq:\n - a: |\n x\n y\n b:\n - c: |-\n p\n q\n - |-\n m\n n\nwsend: \"a\\n \"\nx: |\n a\n\n \n b\nz: |2-\n \n foo\n" + ); + + let keys = json!({ + "": 1, "12": 1, "true": 1, "a b": 1, "a:b": 1, "a: b": 1, "#k": 1, "-": 1, + "x\ny": 1, "say \"hi\"": 1, "$schema": 1, "/App.tsx": 1, "---": 1, "~": 1, + }); + assert_eq!( + to_stable_yaml(Some(&keys)), + "\"\": 1\n\"#k\": 1\n$schema: 1\n\"-\": 1\n\"---\": 1\n/App.tsx: 1\n\"12\": 1\na b: 1\n\"a: b\": 1\na:b: 1\nsay \"hi\": 1\n\"true\": 1\n\"x\\ny\": 1\n\"~\": 1\n" + ); + assert_eq!(to_stable_yaml(None), ""); + assert_eq!(to_stable_yaml(Some(&json!({}))), "{}\n"); + } + + #[test] + fn yaml_patch_ignores_key_order_and_null_fields() { + let labels = ("deployed", "draft"); + let patch = |a: Value, b: Value| yaml_patch(Some(&a), Some(&b), labels); + assert_eq!(patch(json!({"a": 1, "b": 2}), json!({"b": 2, "a": 1})), ""); + assert_eq!(patch(json!({"a": 1, "tag": null}), json!({"a": 1})), ""); + assert!(patch(json!({"a": 1, "tag": "prod"}), json!({"a": 1})).contains("-tag: prod")); + + let code = patch( + json!({"content": "line1\nline2\nline3\n", "language": "bun"}), + json!({"content": "line1\nchanged\nline3\n", "language": "bun"}), + ); + assert!(code.contains("- line2") && code.contains("+ changed")); + assert!(!code.contains("- line1")); + + let new = yaml_patch(None, Some(&json!({"summary": "new item"})), labels); + assert!(new.contains("+summary: new item")); + } + + #[test] + fn window_patch_resumes_at_the_first_undelivered_line() { + let patch = (0..20) + .map(|i| format!("line-{i:02}")) + .collect::>() + .join("\n"); + // The cap fits five complete lines. + assert_eq!( + window_patch(&patch, 0, 20, 40), + "line-00\nline-01\nline-02\nline-03\nline-04\n… window truncated at 40 chars.\n(lines 1-5 of 20; call diff again with offset=5 for the rest)" + ); + assert!(window_patch(&patch, 5, 20, 40).starts_with("line-05\n")); + assert!(window_patch("a\nb", 10, 5, 100).contains("no lines at offset 10")); + + let long = format!("{}\nafter", "x".repeat(100)); + assert!(window_patch(&long, 0, 10, 40).contains("offset=1")); + assert_eq!(window_patch(&long, 1, 10, 40), "after\n(lines 2-2 of 2)"); + } + + #[test] + fn changed_lines_exclude_the_file_labels_only() { + let patch = text_patch( + Some("a\n--counter\nb\n"), + Some("a\n++counter\nb\n"), + ("deployed", "draft"), + ); + let lines: Vec<&str> = patch.split('\n').collect(); + let changed: Vec<&str> = changed_line_indices(&patch) + .into_iter() + .map(|i| lines[i]) + .collect(); + assert_eq!(changed, ["---counter", "+++counter"]); + } + + #[test] + fn variable_values_are_masked_on_both_sides() { + let mut before = Some(json!({"value": "old-plaintext", "is_secret": false})); + let mut after = Some(json!({"value": "new-plaintext", "is_secret": false})); + assert!(!mask_variable_sides(&mut before, &mut after)); + let patch = yaml_patch(before.as_ref(), after.as_ref(), ("deployed", "draft")); + assert!(!patch.contains("plaintext") && patch.contains("(changed)")); + + // Equal masked sides prove nothing about a secret. + let mut before = Some(json!({"value": "", "is_secret": true})); + let mut after = before.clone(); + assert!(mask_variable_sides(&mut before, &mut after)); + assert_eq!(before, after); + } + + #[test] + fn multi_file_apps_split_into_file_patches_and_a_config_patch() { + let before = json!({ + "summary": "Dash", + "files": { "src/App.tsx": "a\nb\nc\n", "old.js": "legacy\n", "gone.css": "", "kept.ts": "same\n" }, + }); + let after = json!({ + "summary": "Dash v2", + "files": { "src/App.tsx": "a\nB\nc\n", "new.ts": "fresh\n", "added.ts": "", "kept.ts": "same\n" }, + }); + let parts = diff_parts(Some(&before), Some(&after), ("deployed", "draft")); + let files = parts.files.unwrap(); + let statuses: Vec<(&str, &str, usize)> = files + .iter() + .map(|(name, f)| (name.as_str(), f.status, f.line_count)) + .collect(); + assert_eq!( + statuses, + [ + ("added.ts", "added", 0), + ("gone.css", "deleted", 0), + ("new.ts", "added", 6), + ("old.js", "deleted", 6), + ("src/App.tsx", "modified", 9), + ] + ); + assert!(parts.patch.contains("+summary: Dash v2") && !parts.patch.contains("App.tsx")); + assert!(parts.has_changes); + + let same = diff_parts(Some(&before), Some(&before), ("deployed", "draft")); + assert!(!same.has_changes && same.files.unwrap().is_empty()); + } + + #[test] + fn globs_match_file_names_or_full_paths() { + assert!(matches_glob("f/dash/main/src/App.tsx", "*.tsx")); + assert!(matches_glob("f/dash/main/src/App.tsx", "f/dash/**")); + assert!(!matches_glob("f/dash/main/src/App.tsx", "f/dash/*.tsx")); + assert!(!matches_glob("f/dash/main", "*.tsx")); + } +} diff --git a/backend/windmill-api/src/mcp/session/flows.rs b/backend/windmill-api/src/mcp/session/flows.rs new file mode 100644 index 0000000000..6911552c41 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/flows.rs @@ -0,0 +1,1184 @@ +//! Flow drafts: the compact view, structural patches and inline module code. +//! +//! The model never sees a rawscript body inside flow JSON: the compact view shows +//! `inline_script.` in its place, and a write resolves each such placeholder +//! back to a body (an existing module's, or an empty one for the module's own id). + +use std::collections::{HashMap, HashSet}; + +use serde_json::{json, Map, Value}; +use windmill_types::flows::FlowModule; + +use super::workspace::{ + compact_flow, empty_schema, find_and_replace, finish_draft_write, load_flow, persist_draft, + write_base, Persist, FLOW_VALUE_SETTINGS_KEYS, +}; +use super::{js_len, non_null, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult}; + +pub(super) const TOOLS: &[&str] = &[ + "write_flow", + "patch_flow_json", + "read_flow_module_code", + "set_flow_module_code", +]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "write_flow" => write_flow(ctx, args).await, + "patch_flow_json" => patch_flow_json(ctx, args).await, + "read_flow_module_code" => read_flow_module_code(ctx, args).await, + "set_flow_module_code" => set_flow_module_code(ctx, args).await, + _ => unreachable!("{name} is not a flows tool"), + } +} + +const STRUCTURAL_KEYS: &[&str] = &[ + "modules", + "schema", + "preprocessor_module", + "failure_module", + "groups", + "notes", +]; +const SPECIAL_MODULES: [(&str, &str); 2] = [ + ("preprocessor_module", "preprocessor"), + ("failure_module", "failure"), +]; +const NOTE_COLORS: &[&str] = &[ + "yellow", "blue", "green", "purple", "pink", "orange", "red", "cyan", "lime", "gray", +]; +/// Names the flow editor reserves, which an agent tool cannot answer to. +const RESERVED_TOOL_NAMES: &[&str] = &[ + "do", + "bg", + "ctx", + "state", + "if", + "else", + "for", + "delete", + "while", + "new", + "in", + "failure", + "preprocessor", + "__wm_agent_root", + "as", + "Input", + "Result", + "Trigger", + "__wm_web_search", +]; +const PROVIDER_SHAPE: &str = r#"{ "type": "static", "value": { "kind": "", "resource": "$res:", "model": "" } }"#; + +fn module_id(module: &Value) -> &str { + module.get("id").and_then(Value::as_str).unwrap_or_default() +} + +fn value_type(value: &Map) -> &str { + value + .get("type") + .and_then(Value::as_str) + .unwrap_or_default() +} + +fn module_type(module: &Value) -> &str { + module + .get("value") + .and_then(Value::as_object) + .map(value_type) + .unwrap_or_default() +} + +/// The module id an `inline_script.` placeholder names. +fn placeholder_ref(content: &str) -> Option<&str> { + content + .strip_prefix("inline_script.") + .filter(|id| !id.is_empty() && !id.contains(['\n', '\r', '\u{2028}', '\u{2029}'])) +} + +fn content_of(value: &Map) -> Option<&str> { + value.get("content").and_then(Value::as_str) +} + +/// Every rawscript the compact view shows as a placeholder, with its owner's id: the +/// modules of loops and branches, and an AI agent's own rawscript tools (not what those +/// tools nest). +fn visit_scripts(modules: Option<&mut Value>, f: &mut dyn FnMut(&str, &mut Map)) { + let Some(Value::Array(modules)) = modules else { + return; + }; + for module in modules { + let id = module_id(module).to_string(); + let Some(value) = module.get_mut("value").and_then(Value::as_object_mut) else { + continue; + }; + let kind = value_type(value).to_string(); + match kind.as_str() { + "rawscript" => f(&id, value), + "forloopflow" | "whileloopflow" => visit_scripts(value.get_mut("modules"), f), + "branchone" | "branchall" => { + if let Some(Value::Array(branches)) = value.get_mut("branches") { + for branch in branches { + visit_scripts(branch.get_mut("modules"), f); + } + } + if kind == "branchone" { + visit_scripts(value.get_mut("default"), f); + } + } + "aiagent" => { + let Some(Value::Array(tools)) = value.get_mut("tools") else { + continue; + }; + for tool in tools { + let tool_id = module_id(tool).to_string(); + let Some(tool_value) = tool.get_mut("value").and_then(Value::as_object_mut) + else { + continue; + }; + let is_flow_module = + tool_value.get("tool_type").and_then(Value::as_str) == Some("flowmodule"); + if is_flow_module && value_type(tool_value) == "rawscript" { + f(&tool_id, tool_value); + } + } + } + _ => {} + } + } +} + +/// `visit_scripts` over a flow value: its modules, then its preprocessor and failure +/// modules when they are rawscripts. +fn visit_flow_scripts( + flow: &mut Map, + f: &mut dyn FnMut(&str, &mut Map), +) { + visit_scripts(flow.get_mut("modules"), f); + for (key, _) in SPECIAL_MODULES { + let Some(module) = flow.get_mut(key) else { + continue; + }; + let id = module_id(module).to_string(); + if let Some(value) = module.get_mut("value").and_then(Value::as_object_mut) { + if value_type(value) == "rawscript" { + f(&id, value); + } + } + } +} + +/// Every module of a tree, parents first, an AI agent's tools included as modules +/// (`in_tool` is set from there down). +fn walk(modules: Option<&mut Value>, in_tool: bool, f: &mut dyn FnMut(&mut Value, bool)) { + let Some(Value::Array(modules)) = modules else { + return; + }; + for module in modules { + f(module, in_tool); + let Some(value) = module.get_mut("value").and_then(Value::as_object_mut) else { + continue; + }; + let kind = value_type(value).to_string(); + match kind.as_str() { + "forloopflow" | "whileloopflow" => walk(value.get_mut("modules"), in_tool, f), + "branchone" | "branchall" => { + if kind == "branchone" { + walk(value.get_mut("default"), in_tool, f); + } + if let Some(Value::Array(branches)) = value.get_mut("branches") { + for branch in branches { + walk(branch.get_mut("modules"), in_tool, f); + } + } + } + "aiagent" => walk(value.get_mut("tools"), true, f), + _ => {} + } + } +} + +/// `walk` over a flow value: its modules, then its preprocessor and failure modules. +fn walk_flow(flow: &mut Map, f: &mut dyn FnMut(&mut Value, bool)) { + walk(flow.get_mut("modules"), false, f); + for (key, _) in SPECIAL_MODULES { + if let Some(module) = flow.get_mut(key).filter(|m| !m.is_null()) { + let mut single = Value::Array(vec![module.take()]); + walk(Some(&mut single), false, f); + *module = single[0].take(); + } + } +} + +/// Drops the lock of every step whose code differs from the same step in `base`: the worker +/// reuses any non-empty step lock, so a changed step keeping its lock runs against the old +/// dependencies. A step id `base` lacks (renamed or duplicated) keeps its lock only when some +/// `base` step has the same code. Without a base nothing is dropped: a copied flow's locks match. +pub(super) fn drop_stale_step_locks(value: &mut Map, base: Option<&Value>) { + let Some(mut base) = base.and_then(Value::as_object).cloned() else { + return; + }; + let code = |module: &Value| module.get("value").and_then(|v| v.get("content")).cloned(); + let mut base_code_by_id = HashMap::new(); + let mut base_codes = Vec::new(); + walk_flow(&mut base, &mut |module, _| { + base_code_by_id.insert(module_id(module).to_string(), code(module)); + base_codes.push(code(module)); + }); + walk_flow(value, &mut |module, _| { + let (id, content) = (module_id(module).to_string(), code(module)); + let Some(step) = module.get_mut("value").and_then(Value::as_object_mut) else { + return; + }; + if step.get("lock").is_none_or(Value::is_null) { + return; + } + let unchanged = match base_code_by_id.get(&id) { + Some(base_code) => *base_code == content, + None => base_codes.contains(&content), + }; + if !unchanged { + step.shift_remove("lock"); + } + }); +} + +/// Put the stored bodies back in place of the placeholders that name them. +fn restore_inline_scripts(flow: &mut Map, scripts: &HashMap) { + visit_flow_scripts(flow, &mut |_, value| { + let body = content_of(value) + .and_then(placeholder_ref) + .and_then(|id| scripts.get(id)); + if let Some(body) = body { + value.insert("content".into(), json!(body)); + } + }); +} + +fn unresolved_inline_scripts(flow: &mut Map) -> Vec { + let mut refs = Vec::new(); + visit_flow_scripts(flow, &mut |_, value| { + if let Some(id) = content_of(value).and_then(placeholder_ref) { + refs.push(id.to_string()); + } + }); + refs +} + +/// What is left of the placeholders once the stored bodies are back: one naming its own +/// module is a new body, saved empty; one naming anything else must not be saved as code. +fn finalize_inline_scripts(flow: &mut Map) -> Result<(), String> { + let mut blank = |module: &mut Value, _: bool| { + let id = module_id(module).to_string(); + let Some(value) = module.get_mut("value").and_then(Value::as_object_mut) else { + return; + }; + if value_type(value) == "rawscript" + && content_of(value).and_then(placeholder_ref) == Some(id.as_str()) + { + value.insert("content".into(), json!("")); + } + }; + walk_flow(flow, &mut blank); + let unresolved = unresolved_inline_scripts(flow); + if unresolved.is_empty() { + return Ok(()); + } + let refs = unresolved + .iter() + .map(|id| format!("\"inline_script.{id}\"")) + .collect::>() + .join(", "); + Err(format!("Unresolved inline script reference(s): {refs}. A rawscript \"content\" placeholder must be \"inline_script.\" (a new body, filled afterwards with the set-module-code tool) or reference an existing rawscript module to keep its current body. Nothing was saved.")) +} + +/// The inline scripts of a flow value that still have no body, in flow order. +fn empty_inline_script_ids(flow: &Map) -> Vec { + let mut scripts: Vec<(String, String)> = Vec::new(); + visit_flow_scripts(&mut flow.clone(), &mut |id, value| { + let Some(content) = content_of(value) else { + return; + }; + match scripts.iter_mut().find(|(known, _)| known == id) { + Some(script) => script.1 = content.to_string(), + None => scripts.push((id.to_string(), content.to_string())), + } + }); + scripts + .into_iter() + .filter(|(_, content)| content.trim().is_empty() || content.starts_with("inline_script.")) + .map(|(id, _)| id) + .collect() +} + +/// A patched compact view applied onto the flow value it was built from. The view is +/// the whole state of what it shows, so a key it no longer has is removed; fields of +/// the value it never showed are kept. +fn apply_editable( + original: Option<&Value>, + editable: &Map, + scripts: &HashMap, +) -> Map { + let mut value = original + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + value.insert( + "modules".into(), + editable + .get("modules") + .cloned() + .unwrap_or_else(|| json!([])), + ); + let optional = ["preprocessor_module", "failure_module", "groups", "notes"]; + for key in optional.iter().chain(FLOW_VALUE_SETTINGS_KEYS) { + match non_null(editable.get(*key)).cloned() { + Some(field) => value.insert((*key).into(), field), + None => value.shift_remove(*key), + }; + } + restore_inline_scripts(&mut value, scripts); + value +} + +fn json_type(value: &Value) -> &'static str { + match value { + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} + +fn validate_settings(flow: &Map) -> Result<(), String> { + let invalid = |path: &str, expected: &str, got: &Value| { + format!( + "Invalid flow setting {path}: Invalid input: expected {expected}, received {}", + json_type(got) + ) + }; + for key in FLOW_VALUE_SETTINGS_KEYS { + let Some(value) = flow.get(*key) else { + continue; + }; + let (expected, ok) = match *key { + "same_worker" + | "preserve_step_tags" + | "cache_ignore_s3_path" + | "chat_input_enabled" => ("boolean", value.is_boolean()), + "concurrency_key" | "debounce_key" | "skip_expr" | "early_return" => { + ("string", value.is_string()) + } + "debounce_args_to_accumulate" => ("array", value.is_array()), + "flow_env" => ("record", value.is_object()), + _ => ("number", value.is_number()), + }; + if !ok { + return Err(invalid(key, expected, value)); + } + for (index, entry) in value.as_array().into_iter().flatten().enumerate() { + if !entry.is_string() { + return Err(invalid(&format!("{key}.{index}"), "string", entry)); + } + } + } + Ok(()) +} + +/// What the server itself can read as a flow module: the shape it would refuse to run. +fn check_module_shape(module: &Value) -> Result<(), String> { + serde_json::from_str::(&module.to_string()) + .map_err(|e| e.to_string())? + .get_value() + .map(|_| ()) + .map_err(|e| e.to_string()) +} + +fn tool_name_error(name: &str, siblings: &[&str]) -> Option { + if name.is_empty() { + return Some("Tool name must not be empty".into()); + } + if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + return Some("Tool name must only contain letters, numbers and underscores".into()); + } + if RESERVED_TOOL_NAMES.contains(&name) { + return Some(format!("'{name}' is a reserved name")); + } + (siblings.iter().filter(|n| **n == name).count() > 1).then(|| "Duplicate tool name".into()) +} + +/// A provider config that cannot run whatever the workspace holds. +fn provider_shape_error(provider: Option<&Value>, step_type: &str) -> Option { + let provider = match provider { + Some(Value::String(reference)) => { + return Some(format!( + "provider must be an object {PROVIDER_SHAPE}, not the resource reference string {}", + json!(reference) + )) + } + Some(Value::Object(provider)) => provider, + _ => return Some(format!("provider must be an object {PROVIDER_SHAPE}")), + }; + let text = |key: &str| { + provider + .get(key) + .and_then(Value::as_str) + .unwrap_or_default() + }; + let kind = text("kind"); + if kind.is_empty() { + return Some(format!( + "provider.kind is missing. Expected {PROVIDER_SHAPE}" + )); + } + let decision_only = ["typesafe", "cloudflare"].contains(&kind); + if step_type == "aidecision" && !decision_only && kind != "openai" { + return Some(format!("an AI decision step runs on a decision model: provider.kind must be \"typesafe\", \"cloudflare\" or \"openai\", not \"{kind}\"")); + } + if step_type != "aidecision" && decision_only { + return Some(format!("\"{kind}\" serves decision models, which answer typed questions rather than messages: use an \"aidecision\" step rather than an AI agent")); + } + if !text("resource").starts_with("$res:") { + return Some(format!("provider.resource must be a \"$res:\" reference. Expected {PROVIDER_SHAPE}")); + } + text("model") + .is_empty() + .then(|| format!("provider.model is missing. Expected {PROVIDER_SHAPE}")) +} + +fn quoted_list(ids: &[String]) -> String { + ids.iter() + .map(|id| format!("\"{id}\"")) + .collect::>() + .join(", ") +} + +/// Checks the modules array and returns every id it holds, agent tools included. +fn validate_modules(modules: &mut Value) -> Result, String> { + if !modules.is_array() { + return Err("Flow modules must be an array".into()); + } + let mut shape_errors = Vec::new(); + let mut ids = Vec::new(); + let mut providerless = Vec::new(); + let mut tool_names = Vec::new(); + let mut providers = Vec::new(); + walk(Some(modules), false, &mut |module, in_tool| { + let id = module_id(module); + // A tool is not a flow module: the agent that owns it checks its shape. + if !in_tool && shape_errors.len() < 5 { + if let Err(e) = check_module_shape(module) { + shape_errors.push(format!("Module \"{id}\": {e}")); + } + } + if !id.is_empty() { + ids.push(id.to_string()); + } + let kind = module_type(module); + if kind != "aiagent" && kind != "aidecision" { + return; + } + let value = &module["value"]; + let linked = truthy(value.get("agent")); + let provider = value + .get("input_transforms") + .and_then(|transforms| transforms.get("provider")) + .filter(|provider| truthy(Some(provider))); + if kind == "aiagent" && !linked && provider.is_none() { + providerless.push(id.to_string()); + } + + // Only a flow module tool's summary is a name the agent calls. + let named: Vec<&Value> = value + .get("tools") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|tool| { + let tool_type = tool.get("value").and_then(|v| v.get("tool_type")); + !matches!(tool_type.and_then(Value::as_str), Some("mcp" | "websearch")) + }) + .collect(); + fn name_of(tool: &Value) -> &str { + tool.get("summary") + .and_then(Value::as_str) + .unwrap_or_default() + } + let siblings: Vec<&str> = named.iter().map(|tool| name_of(tool)).collect(); + for tool in &named { + if let Some(error) = tool_name_error(name_of(tool), &siblings) { + tool_names.push(format!( + "agent \"{id}\" tool \"{}\" is named {} - {error}", + module_id(tool), + json!(name_of(tool)) + )); + } + } + + let is_static = |p: &&Value| p.get("type").and_then(Value::as_str) == Some("static"); + if let Some(provider) = provider.filter(|_| !linked).filter(is_static) { + if let Some(error) = provider_shape_error(provider.get("value"), kind) { + providers.push(format!("Step \"{id}\": {error}")); + } + } + }); + + if !shape_errors.is_empty() { + return Err(format!( + "Invalid flow modules:\n{}", + shape_errors.join("\n") + )); + } + let unique: HashSet = ids.iter().cloned().collect(); + if unique.len() != ids.len() { + return Err("Duplicate module IDs found in flow".into()); + } + if SPECIAL_MODULES.iter().any(|(_, id)| unique.contains(*id)) { + return Err("Special modules must be provided via preprocessor_module and failure_module, not inside modules".into()); + } + if !providerless.is_empty() { + return Err(format!( + "AI agent modules {} need a provider input transform, or an \"agent\" path linking them to a saved agent", + quoted_list(&providerless) + )); + } + if !tool_names.is_empty() { + return Err(format!( + "Invalid AI agent tool name(s): {}. The tool's \"summary\" is the name the agent calls it by: use underscores instead of spaces (e.g. \"search_docs\").", + tool_names.join("; ") + )); + } + if !providers.is_empty() { + return Err(format!( + "Invalid AI agent provider configuration:\n{}", + providers.join("\n") + )); + } + Ok(unique) +} + +fn check_color(color: Option<&Value>) -> Result<(), String> { + match color { + None | Some(Value::Null) => Ok(()), + Some(Value::String(color)) if NOTE_COLORS.contains(&color.as_str()) => Ok(()), + Some(_) => Err(format!("color must be one of {}", NOTE_COLORS.join(", "))), + } +} + +fn validate_groups(raw: Option<&Value>, module_ids: &HashSet) -> Result { + let groups = match raw { + None | Some(Value::Null) => return Ok(Value::Null), + Some(Value::Array(groups)) => groups, + Some(_) => return Err("Flow groups must be an array".into()), + }; + for (index, group) in groups.iter().enumerate() { + let fail = |what: String| format!("Invalid group at index {index}: {what}"); + let Value::Object(group) = group else { + return Err(fail("must be an object".into())); + }; + for key in ["start_id", "end_id"] { + let id = group.get(key).and_then(Value::as_str).unwrap_or_default(); + if id.is_empty() { + return Err(fail(format!("{key} must be a non-empty string"))); + } + } + for key in ["start_id", "end_id"] { + let id = group[key].as_str().unwrap_or_default(); + if !module_ids.contains(id) { + return Err(fail(format!( + "{key} \"{id}\" does not match any flow module" + ))); + } + } + check_color(group.get("color")).map_err(fail)?; + } + Ok(Value::Array(groups.clone())) +} + +fn number(n: f64) -> Value { + if n.fract() == 0.0 && n.abs() < 9e15 { + json!(n as i64) + } else { + json!(n) + } +} + +const NOTE_WIDTH: f64 = 275.0; +const NOTE_MIN_HEIGHT: f64 = 60.0; +/// Where a free note without a position goes: a column left of the flow. +const NOTE_COLUMN_X: f64 = -(NOTE_WIDTH + 100.0); +const NOTE_GAP: f64 = 24.0; + +/// The editor shows a free note at a fixed size, so one written without a size needs a +/// box tall enough for its text (12px text, 1.4 line height, 16px padding). +fn free_note_height(text: &str) -> f64 { + let chars_per_line = ((NOTE_WIDTH - 32.0) / 6.2).floor().max(1.0); + let lines: f64 = text + .split('\n') + .map(|line| (js_len(line) as f64 / chars_per_line).ceil().max(1.0)) + .sum(); + (lines * 17.0 + 32.0).clamp(NOTE_MIN_HEIGHT, 600.0) +} + +/// Checks the notes and fills in what the editor needs of each: a type, a color and, +/// for a free note, the size and position without which it cannot be moved. +fn validate_notes(raw: Option<&Value>, module_ids: &HashSet) -> Result { + let notes = match raw { + None | Some(Value::Null) => return Ok(Value::Null), + Some(Value::Array(notes)) => notes, + Some(_) => return Err("Flow notes must be an array".into()), + }; + let mut seen = HashSet::new(); + let mut stack_y = 0.0_f64; + let mut out = Vec::new(); + for (index, note) in notes.iter().enumerate() { + let fail = |what: String| format!("Invalid note at index {index}: {what}"); + let Value::Object(note) = note else { + return Err(fail("must be an object".into())); + }; + let id = note.get("id").and_then(Value::as_str).unwrap_or_default(); + if id.is_empty() { + return Err(fail("id must be a non-empty string".into())); + } + if !seen.insert(id) { + return Err(fail(format!("duplicate note id \"{id}\""))); + } + let Some(text) = note.get("text").and_then(Value::as_str) else { + return Err(fail("text must be a string".into())); + }; + let kind = match note.get("type") { + None | Some(Value::Null) => "free", + Some(Value::String(kind)) if kind == "free" || kind == "group" => kind.as_str(), + Some(_) => return Err(fail("type must be \"free\" or \"group\"".into())), + }; + check_color(note.get("color")).map_err(fail)?; + let pair = |key: &str, a: &str, b: &str| -> Result, String> { + let Some(value) = note.get(key).filter(|v| !v.is_null()) else { + return Ok(None); + }; + let field = |name: &str| value.get(name).and_then(Value::as_f64); + match (value.is_object(), field(a), field(b)) { + (true, Some(a), Some(b)) => Ok(Some((a, b))), + _ => Err(fail(format!( + "{key} must be an object with numeric {a} and {b}" + ))), + } + }; + let position = pair("position", "x", "y")?; + let size = pair("size", "width", "height")?; + if kind == "group" { + if let Some(contained) = note.get("contained_node_ids") { + let ids: Option> = contained + .as_array() + .and_then(|ids| ids.iter().map(Value::as_str).collect()); + let Some(ids) = ids else { + return Err(fail( + "contained_node_ids must be an array of strings".into(), + )); + }; + if let Some(id) = ids.iter().find(|id| !module_ids.contains(**id)) { + return Err(fail(format!( + "contained_node_ids \"{id}\" does not match any flow module" + ))); + } + } + } + + let mut normalized = note.clone(); + normalized.insert("type".into(), json!(kind)); + if !note.get("color").is_some_and(Value::is_string) { + normalized.insert("color".into(), json!("green")); + } + if kind == "free" { + let (width, height) = size.unwrap_or_else(|| (NOTE_WIDTH, free_note_height(text))); + if size.is_none() { + normalized.insert( + "size".into(), + json!({ "width": number(width), "height": number(height) }), + ); + } + match position { + None => { + normalized.insert( + "position".into(), + json!({ "x": number(NOTE_COLUMN_X), "y": number(stack_y) }), + ); + stack_y += height + NOTE_GAP; + } + // A placed note standing in the column pushes the next unplaced one below it. + Some((x, y)) if x < NOTE_COLUMN_X + NOTE_WIDTH && x + width > NOTE_COLUMN_X => { + stack_y = stack_y.max(y + height + NOTE_GAP); + } + Some(_) => {} + } + } + out.push(Value::Object(normalized)); + } + Ok(Value::Array(out)) +} + +/// Checks a compact flow view (`modules, schema, preprocessor_module, failure_module, +/// groups, notes` and the top-level settings) and returns it with every structural key +/// present, `null` when unset. +fn validate_editable(raw: Value) -> Result, String> { + let Value::Object(mut flow) = raw else { + return Err("Flow JSON must be an object".into()); + }; + let allowed = || STRUCTURAL_KEYS.iter().chain(FLOW_VALUE_SETTINGS_KEYS); + // An unknown key is refused rather than dropped: the patch that added it would + // otherwise report success for an edit that never lands on the flow. + let unknown: Vec<&str> = flow + .keys() + .map(String::as_str) + .filter(|key| !allowed().any(|known| known == key)) + .collect(); + if !unknown.is_empty() { + return Err(format!( + "Unknown top-level flow key(s): {}. Allowed keys: {}", + unknown.join(", "), + allowed().copied().collect::>().join(", ") + )); + } + validate_settings(&flow)?; + + let mut modules = flow.remove("modules").unwrap_or(Value::Null); + let module_ids = validate_modules(&mut modules)?; + let schema = match flow.get("schema") { + None | Some(Value::Null) => Value::Null, + Some(schema @ Value::Object(_)) => schema.clone(), + Some(_) => return Err("Flow schema must be an object or null".into()), + }; + for (key, _) in SPECIAL_MODULES { + if let Some(module) = non_null(flow.get(key)) { + check_module_shape(&module).map_err(|e| format!("Invalid {key}: {e}"))?; + } + } + let groups = validate_groups(flow.get("groups"), &module_ids)?; + let notes = validate_notes(flow.get("notes"), &module_ids)?; + for (key, id) in SPECIAL_MODULES { + let Some(module) = non_null(flow.get(key)) else { + continue; + }; + if module_id(&module) != id { + return Err(format!("Invalid {key}: id must be \"{id}\"")); + } + if !["rawscript", "script"].contains(&module_type(&module)) { + return Err(format!( + "Invalid {key}: only \"rawscript\" and \"script\" modules are supported" + )); + } + } + + let mut editable = Map::new(); + editable.insert("modules".into(), modules); + editable.insert("schema".into(), schema); + for (key, _) in SPECIAL_MODULES { + editable.insert(key.into(), flow.remove(key).unwrap_or(Value::Null)); + } + editable.insert("groups".into(), groups); + editable.insert("notes".into(), notes); + for key in FLOW_VALUE_SETTINGS_KEYS { + if let Some(setting) = flow.remove(*key) { + editable.insert((*key).into(), setting); + } + } + Ok(editable) +} + +struct FlowWrite<'a> { + path: &'a str, + summary: Option<&'a str>, + description: Option<&'a str>, + value: Map, + schema: Option, + groups: Option, + /// Keep the fields of the current flow value that `value` cannot express. + preserve_base_settings: bool, + /// Name the inline scripts left without a body in the result. + warn_empty_scripts: bool, + force: bool, +} + +async fn write_flow_draft(ctx: &Ctx<'_>, write: FlowWrite<'_>) -> ToolResult { + let FlowWrite { path, mut value, .. } = write; + let base = write_base(ctx, "flow", path, None).await?; + let existed = base.base.is_some(); + if let Some(groups) = write.groups { + value.insert("groups".into(), groups); + } + let base_flow = match base.base { + Some(Value::Object(flow)) => Some(flow), + _ => None, + }; + if write.preserve_base_settings { + let base_value = base_flow.as_ref().and_then(|flow| flow.get("value")); + for (key, field) in base_value.and_then(Value::as_object).into_iter().flatten() { + if !STRUCTURAL_KEYS.contains(&key.as_str()) && !value.contains_key(key) { + value.insert(key.clone(), field.clone()); + } + } + } + // Also done at deploy; here too because a test run of the draft reads the locks. + drop_stale_step_locks( + &mut value, + base_flow.as_ref().and_then(|flow| flow.get("value")), + ); + let empty_scripts = if write.warn_empty_scripts { + empty_inline_script_ids(&value) + } else { + Vec::new() + }; + let draft = match base_flow { + Some(mut flow) => { + flow.insert("path".into(), json!(path)); + if let Some(summary) = write.summary { + flow.insert("summary".into(), json!(summary)); + } + if let Some(description) = write.description { + flow.insert("description".into(), json!(description)); + } + flow.insert("value".into(), Value::Object(value)); + if let Some(schema) = write.schema { + flow.insert("schema".into(), schema); + } + Value::Object(flow) + } + None => json!({ + "path": path, + "summary": write.summary.unwrap_or_default(), + "description": write.description.unwrap_or_default(), + "value": value, + "schema": write.schema.unwrap_or_else(empty_schema), + "edited_by": "", + "edited_at": "", + "archived": false, + "extra_perms": {}, + }), + }; + let persisted = persist_draft( + ctx, + "flow", + path, + None, + &draft, + base.last_sync.as_deref(), + write.force, + ) + .await?; + let item = match persisted { + Persist::Saved(item) => item, + Persist::Failed(text) => return Ok(text), + }; + let result = finish_draft_write(ctx, &item, existed); + if empty_scripts.is_empty() { + return Ok(result); + } + let Ok(Value::Object(mut parsed)) = serde_json::from_str::(&result) else { + return Ok(result); + }; + let message = parsed + .get("message") + .and_then(Value::as_str) + .unwrap_or_default(); + let message = format!("{message}\n\nWarning: inline scripts {} have no code yet. Fill each one with set_flow_module_code(path, module_id, code) — do not re-send the whole flow.", quoted_list(&empty_scripts)); + parsed.insert("message".into(), json!(message)); + Ok(pretty(&Value::Object(parsed))) +} + +/// A flow-structure argument: a JSON string, or the value itself from a client that +/// did not stringify it. +fn json_arg(args: &Value, field: &str) -> Result { + let Some(Value::String(text)) = args.get(field) else { + return Ok(args.get(field).cloned().unwrap_or(Value::Null)); + }; + serde_json::from_str(text).map_err(|e| { + let hint = if ["modules", "preprocessor_module", "failure_module"].contains(&field) { + " A rawscript \"content\" string with multi-line code or quotes is the usual cause. Instead of inlining large code, create the rawscript module with empty content (\"\") and fill its body with set_flow_module_code afterwards." + } else { + "" + }; + format!("Invalid JSON for {field}: {e}{hint}") + }) +} + +async fn write_flow(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let mut raw = Map::new(); + for key in STRUCTURAL_KEYS { + raw.insert((*key).into(), json_arg(args, key)?); + } + let mut editable = validate_editable(Value::Object(raw))?; + + // A placeholder keeps the body the current flow has for that module, so a rewrite + // does not have to send code it is not changing. + if !unresolved_inline_scripts(&mut editable).is_empty() { + let current = write_base(ctx, "flow", path, None).await?.base; + if let Some(value) = current.as_ref().and_then(|flow| flow.get("value")) { + restore_inline_scripts(&mut editable, &compact_flow(value, None).1); + } + finalize_inline_scripts(&mut editable)?; + } + + let schema = non_null(editable.get("schema")).cloned(); + let groups = non_null(editable.get("groups")).cloned(); + editable.remove("schema"); + editable.retain(|_, field| !field.is_null()); + write_flow_draft( + ctx, + FlowWrite { + path, + summary: opt_str_arg(args, "summary"), + description: opt_str_arg(args, "description"), + value: editable, + schema, + groups, + preserve_base_settings: true, + warn_empty_scripts: true, + force: args.get("override").and_then(Value::as_bool) == Some(true), + }, + ) + .await +} + +async fn patch_flow_json(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let base = load_flow(ctx, path).await?; + let (compact, scripts) = compact_flow( + base.flow.get("value").unwrap_or(&Value::Null), + base.flow.get("schema"), + ); + let updated = find_and_replace( + &compact.to_string(), + str_arg(args, "old_string")?, + str_arg(args, "new_string")?, + args.get("replace_all").and_then(Value::as_bool) == Some(true), + "compact flow JSON", + )?; + let parsed: Value = serde_json::from_str(&updated) + .map_err(|e| format!("Invalid JSON after replacement: {e}"))?; + let editable = validate_editable(parsed)?; + let mut value = apply_editable(base.flow.get("value"), &editable, &scripts); + finalize_inline_scripts(&mut value)?; + write_flow_draft( + ctx, + FlowWrite { + path, + summary: base.summary.as_deref(), + description: None, + value, + schema: non_null(editable.get("schema")).cloned(), + groups: non_null(editable.get("groups")).cloned(), + preserve_base_settings: false, + warn_empty_scripts: true, + force: false, + }, + ) + .await +} + +async fn read_flow_module_code(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let (path, module_id) = (str_arg(args, "path")?, str_arg(args, "module_id")?); + let base = load_flow(ctx, path).await?; + let (_, mut scripts) = compact_flow(base.flow.get("value").unwrap_or(&Value::Null), None); + scripts.remove(module_id).ok_or_else(|| format!("Module \"{module_id}\" is not an inline rawscript in flow \"{path}\". (Path runnables, branches, and loops have no inline script content; use patch_flow_json to inspect them.)")) +} + +async fn set_flow_module_code(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let (path, module_id) = (str_arg(args, "path")?, str_arg(args, "module_id")?); + let code = str_arg(args, "code")?; + let base = load_flow(ctx, path).await?; + let (compact, mut scripts) = compact_flow( + base.flow.get("value").unwrap_or(&Value::Null), + base.flow.get("schema"), + ); + if !scripts.contains_key(module_id) { + return Err(format!("Module \"{module_id}\" is not an inline rawscript in flow \"{path}\". Use patch_flow_json or write_flow for structural changes.")); + } + scripts.insert(module_id.to_string(), code.to_string()); + let editable = compact.as_object().cloned().unwrap_or_default(); + write_flow_draft( + ctx, + FlowWrite { + path, + summary: base.summary.as_deref(), + description: None, + value: apply_editable(base.flow.get("value"), &editable, &scripts), + schema: non_null(base.flow.get("schema")).cloned(), + groups: non_null(base.flow.get("groups")).cloned(), + preserve_base_settings: false, + warn_empty_scripts: false, + force: false, + }, + ) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn raw(id: &str, content: &str) -> Value { + json!({ "id": id, "value": { "type": "rawscript", "content": content, "language": "bun", "input_transforms": {} } }) + } + + fn content<'a>(flow: &'a Map, pointer: &str) -> &'a str { + Value::pointer(&flow["modules"], pointer) + .and_then(|module| module["value"]["content"].as_str()) + .unwrap() + } + + #[test] + fn placeholders_resolve_to_an_existing_body_or_an_empty_new_one() { + let scripts = HashMap::from([("a".to_string(), "A".to_string())]); + let mut flow = json!({ + "modules": [ + raw("a", "inline_script.a"), + raw("copy", "inline_script.a"), + { "id": "loop", "value": { "type": "forloopflow", "modules": [raw("new", "inline_script.new")] } }, + raw("multiline", "inline_script.a\nmore"), + ], + "failure_module": raw("failure", "inline_script.failure"), + }) + .as_object() + .cloned() + .unwrap(); + restore_inline_scripts(&mut flow, &scripts); + finalize_inline_scripts(&mut flow).unwrap(); + assert_eq!(content(&flow, "/0"), "A"); + assert_eq!(content(&flow, "/1"), "A"); + assert_eq!(content(&flow, "/2/value/modules/0"), ""); + assert_eq!(content(&flow, "/3"), "inline_script.a\nmore"); + assert_eq!(flow["failure_module"]["value"]["content"], ""); + assert_eq!( + empty_inline_script_ids(&flow), + ["new", "multiline", "failure"] + ); + + let mut dangling = json!({ "modules": [raw("b", "inline_script.gone")] }) + .as_object() + .cloned() + .unwrap(); + restore_inline_scripts(&mut dangling, &scripts); + let error = finalize_inline_scripts(&mut dangling).unwrap_err(); + assert!( + error.starts_with("Unresolved inline script reference(s): \"inline_script.gone\". ") + ); + } + + #[test] + fn only_steps_whose_code_changed_lose_their_lock() { + let locked = |id: &str, content: &str| { + let mut module = raw(id, content); + module["value"]["lock"] = json!("lock"); + module + }; + let base = json!({ "modules": [raw("edited", "A"), raw("kept", "B")] }); + let mut value = json!({ + "modules": [locked("edited", "B"), locked("kept", "B"), locked("renamed", "B"), locked("new", "C")], + "failure_module": locked("failure", "F"), + }) + .as_object() + .cloned() + .unwrap(); + let unlocked = value.clone(); + drop_stale_step_locks(&mut value, None); + assert_eq!(value, unlocked); + + drop_stale_step_locks(&mut value, Some(&base)); + let has_lock = |module: &Value| module["value"].get("lock").is_some(); + let kept: Vec = value["modules"] + .as_array() + .unwrap() + .iter() + .map(has_lock) + .collect(); + assert_eq!(kept, [false, true, true, false]); + assert!(!has_lock(&value["failure_module"])); + } + + #[test] + fn a_patch_of_the_compact_view_keeps_bodies_and_unsets_removed_settings() { + let value = json!({ + "modules": [raw("a", "A"), raw("b", "B")], + "same_worker": true, + "untouched": 1, + }); + let (compact, scripts) = compact_flow(&value, None); + let patched = compact + .to_string() + .replace(",\"same_worker\":true", "") + .replace("\"id\":\"b\"", "\"id\":\"c\""); + let editable = validate_editable(serde_json::from_str(&patched).unwrap()).unwrap(); + let mut applied = apply_editable(Some(&value), &editable, &scripts); + finalize_inline_scripts(&mut applied).unwrap(); + assert_eq!(content(&applied, "/0"), "A"); + // Renamed, so its placeholder still names the body it had. + assert_eq!(content(&applied, "/1"), "B"); + assert_eq!(applied.get("same_worker"), None); + assert_eq!(applied["untouched"], 1); + assert_eq!(applied.get("groups"), None); + } + + #[test] + fn validation_reports_what_the_editor_would_refuse() { + let check = |flow: Value| validate_editable(flow).unwrap_err(); + assert_eq!( + check(json!({ "modules": [raw("a", ""), raw("a", "")] })), + "Duplicate module IDs found in flow" + ); + assert!(check(json!({ "modules": [], "bogus": 1 })) + .starts_with("Unknown top-level flow key(s): bogus. Allowed keys: modules, schema,")); + assert_eq!( + check(json!({ "modules": [], "same_worker": "yes" })), + "Invalid flow setting same_worker: Invalid input: expected boolean, received string" + ); + assert!( + check(json!({ "modules": [{ "id": "a", "value": { "type": "rawscript" } }] })) + .starts_with("Invalid flow modules:\nModule \"a\": ") + ); + assert_eq!( + check(json!({ "modules": [], "failure_module": raw("oops", "") })), + "Invalid failure_module: id must be \"failure\"" + ); + let agent = |tools: Value| { + json!({ "modules": [{ "id": "agent", "value": { + "type": "aiagent", + "tools": tools, + "input_transforms": { "provider": { "type": "static", "value": { "kind": "openai", "resource": "$res:u/a/b", "model": "m" } } }, + } }] }) + }; + let tool = |summary: &str| { + let mut tool = raw("t", ""); + tool["summary"] = json!(summary); + tool["value"]["tool_type"] = json!("flowmodule"); + tool + }; + assert!(check(agent(json!([tool("search docs")]))).starts_with( + "Invalid AI agent tool name(s): agent \"agent\" tool \"t\" is named \"search docs\" - Tool name must only contain letters, numbers and underscores. " + )); + validate_editable(agent(json!([tool("search_docs")]))).unwrap(); + } + + #[test] + fn notes_get_the_geometry_the_editor_needs() { + let notes = validate_notes( + Some(&json!([ + { "id": "n1", "text": "hello\nworld" }, + { "id": "n2", "text": "", "color": "red", "position": { "x": 5, "y": 6 } }, + { "id": "n3", "text": "x" }, + ])), + &HashSet::new(), + ) + .unwrap(); + assert_eq!( + notes[0], + json!({ "id": "n1", "text": "hello\nworld", "type": "free", "color": "green", "size": { "width": 275, "height": 66 }, "position": { "x": -375, "y": 0 } }) + ); + assert_eq!(notes[1]["color"], "red"); + assert_eq!(notes[1]["position"], json!({ "x": 5, "y": 6 })); + assert_eq!(notes[2]["position"], json!({ "x": -375, "y": 90 })); + } +} diff --git a/backend/windmill-api/src/mcp/session/gen/app_templates.json b/backend/windmill-api/src/mcp/session/gen/app_templates.json new file mode 100644 index 0000000000..02c1fa35b5 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/gen/app_templates.json @@ -0,0 +1,123 @@ +{ + "templates": { + "react19": { + "/index.tsx": "\nimport React from 'react'\n\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\nconst root = createRoot(document.getElementById('root')!);\nroot.render();\n", + "/App.tsx": "import React, { useState } from 'react'\nimport { backend, backendAsync, getJob, streamJob } from './wmill'\nimport './index.css'\n\n// Windmill injects the viewer (absent for anonymous visitors) and the workspace.\nconst ctx = (window as any).ctx ?? {}\nconst viewer: { name?: string; username?: string } | undefined = ctx.ctx\nconst firstName = (viewer?.name || viewer?.username || '').split(' ')[0]\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nfunction errorMessage(e: any): string {\n return e?.message ?? (typeof e === 'string' ? e : JSON.stringify(e))\n}\n\nfunction Card(props: {\n step: string\n title: string\n description: string\n code: string\n children: React.ReactNode\n}) {\n return (\n
\n
\n {props.step}\n
\n

{props.title}

\n

{props.description}

\n
\n
\n
{props.children}
\n
\n        {props.code}\n      
\n
\n )\n}\n\nfunction GreetDemo() {\n const [name, setName] = useState(firstName || 'world')\n const [result, setResult] = useState<{ message: string; ran_at: string }>()\n const [error, setError] = useState()\n const [loading, setLoading] = useState(false)\n\n async function run() {\n setLoading(true)\n setError(undefined)\n try {\n setResult(await backend.greet({ name }))\n } catch (e) {\n setError(errorMessage(e))\n }\n setLoading(false)\n }\n\n return (\n \n {\n e.preventDefault()\n run()\n }}\n >\n setName(e.target.value)} placeholder=\"Your name\" />\n \n \n
\n {error ? (\n {error}\n ) : result ? (\n <>\n {result.message}\n Ran at {new Date(result.ran_at).toLocaleTimeString()}\n \n ) : (\n The result shows up here.\n )}\n
\n \n )\n}\n\ntype Stats = { words: number; characters: number; sentences: number; top_words: string[] }\n\nfunction StatsDemo() {\n const [text, setText] = useState(\"Windmill turns scripts into apps. Write the frontend in React or Svelte, and the backend in TypeScript, Python or any other supported language. Scripts run on workers, and the app calls them like functions.\")\n const [stats, setStats] = useState()\n const [error, setError] = useState()\n const [loading, setLoading] = useState(false)\n\n async function run() {\n setLoading(true)\n setError(undefined)\n try {\n setStats(await backend.word_stats({ text }))\n } catch (e) {\n setError(errorMessage(e))\n }\n setLoading(false)\n }\n\n return (\n \n \n
\n \n
\n {#if statsError}\n
{statsError}
\n {/if}\n {#if stats}\n
\n
{stats.words}words
\n
{stats.sentences}sentences
\n
{stats.characters}characters
\n
\n {#each stats.top_words as word (word)}\n {word}\n {/each}\n
\n
\n {/if}\n \n
const stats = await backend.word_stats({ text })
\n \n\n
\n {@render header('3', 'Run jobs in the background', 'Start long jobs without blocking the UI, then poll their status. Start several at once.')}\n
\n
\n \n
\n {#if jobsError}\n
{jobsError}
\n {/if}\n
    \n {#each jobs as job (job.id)}\n
  • \n {job.status}\n {job.id.slice(-8)}\n {job.seconds}s\n
    \n
    \n
    \n
  • \n {:else}\n
  • No jobs yet.
  • \n {/each}\n
\n
\n
const id = await backendAsync.slow_task({ seconds })\nconst job = await getJob(id)
\n
\n\n
\n {@render header('4', 'Stream results', 'A runnable can yield its output bit by bit. Render it as it arrives, like an LLM answer.')}\n
\n
\n \n
\n
\n {#if streamError}\n {streamError}\n {:else if streamed || streaming}\n {streamed}{#if streaming}{/if}\n {:else}\n Streamed text shows up here.\n {/if}\n
\n
\n
await streamJob(id, (u) => append(u.new_result_stream))
\n
\n \n\n", + "/index.css": "/* The app renders inside an iframe whose host page has its own theme the\n iframe cannot read, so paint an opaque surface here: without one the host's\n background shows through and dark text lands on it unreadable. */\n:root {\n color-scheme: light;\n --bg: #f4f5f8;\n --card: #ffffff;\n --sunken: #efeff4;\n --border: #e2e3eb;\n --fg: #3d4758;\n --fg-strong: #1d2430;\n --muted: #718096;\n --accent: #5074f6;\n --accent-hover: #2c5beb;\n --accent-soft: #e8ebfb;\n --success: #15803d;\n --success-soft: #dcfce7;\n --error: #b91c1c;\n --error-soft: #fef2f2;\n --warning: #a16207;\n --warning-soft: #fef9c3;\n}\n\n@media (prefers-color-scheme: dark) {\n :root {\n color-scheme: dark;\n --bg: #242832;\n --card: #2e3441;\n --sunken: #272c35;\n --border: #3b4252;\n --fg: #d4d7dd;\n --fg-strong: #eeeff2;\n --muted: #a9b0ba;\n --accent: #7085db;\n --accent-hover: #5670d5;\n --accent-soft: #343d5c;\n --success: #86efac;\n --success-soft: #1f3a2b;\n --error: #fca5a5;\n --error-soft: #431a1a;\n --warning: #fde68a;\n --warning-soft: #3d3419;\n }\n}\n\n* {\n box-sizing: border-box;\n}\n\nbody {\n margin: 0;\n min-height: 100vh;\n background: var(--bg);\n color: var(--fg);\n font-family: Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;\n font-size: 14px;\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n}\n\nh1,\nh2 {\n margin: 0;\n color: var(--fg-strong);\n}\n\ncode,\npre {\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n}\n\n.muted {\n color: var(--muted);\n}\n\n.error {\n color: var(--error);\n}\n\n.app {\n max-width: 1040px;\n margin: 0 auto;\n padding: 40px 20px 56px;\n}\n\n.hero {\n margin-bottom: 28px;\n}\n\n.hero h1 {\n font-size: 1.75rem;\n font-weight: 650;\n letter-spacing: -0.01em;\n margin: 8px 0 6px;\n}\n\n.hero p {\n max-width: 620px;\n margin: 0;\n}\n\n.eyebrow {\n display: inline-block;\n padding: 2px 10px;\n border-radius: 999px;\n background: var(--accent-soft);\n color: var(--accent);\n font-size: 12px;\n font-weight: 600;\n}\n\n.grid {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr));\n gap: 16px;\n}\n\n.card {\n display: flex;\n flex-direction: column;\n background: var(--card);\n border: 1px solid var(--border);\n border-radius: 10px;\n box-shadow: 0 1px 2px rgb(16 24 40 / 0.04);\n overflow: hidden;\n}\n\n.card-header {\n display: flex;\n gap: 12px;\n padding: 18px 18px 0;\n}\n\n.card-header h2 {\n font-size: 15px;\n font-weight: 600;\n}\n\n.card-header p {\n margin: 2px 0 0;\n font-size: 13px;\n}\n\n.card-step {\n flex: none;\n display: grid;\n place-items: center;\n width: 26px;\n height: 26px;\n border-radius: 7px;\n background: var(--accent-soft);\n color: var(--accent);\n font-size: 13px;\n font-weight: 700;\n}\n\n.card-body {\n flex: 1;\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 16px 18px 18px;\n}\n\n.snippet {\n margin: 0;\n padding: 10px 18px;\n border-top: 1px solid var(--border);\n background: var(--sunken);\n color: var(--muted);\n font-size: 12px;\n white-space: pre-wrap;\n}\n\n.row {\n display: flex;\n gap: 8px;\n}\n\ninput,\ntextarea {\n flex: 1;\n min-width: 0;\n padding: 7px 10px;\n border: 1px solid var(--border);\n border-radius: 6px;\n background: var(--card);\n color: var(--fg-strong);\n font: inherit;\n resize: vertical;\n}\n\ninput:focus,\ntextarea:focus {\n outline: 2px solid var(--accent);\n outline-offset: -1px;\n}\n\nbutton {\n padding: 7px 14px;\n border: none;\n border-radius: 6px;\n background: var(--accent);\n color: #fff;\n font: inherit;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s;\n}\n\nbutton:hover:not(:disabled) {\n background: var(--accent-hover);\n}\n\nbutton:disabled {\n opacity: 0.6;\n cursor: default;\n}\n\n.output {\n min-height: 44px;\n padding: 11px 12px;\n border-radius: 6px;\n background: var(--sunken);\n word-break: break-word;\n}\n\n.output.error {\n background: var(--error-soft);\n}\n\n.output.stream {\n min-height: 96px;\n white-space: pre-wrap;\n}\n\n.caret {\n display: inline-block;\n width: 7px;\n height: 1em;\n margin-left: 2px;\n vertical-align: text-bottom;\n background: var(--accent);\n animation: blink 1s steps(1) infinite;\n}\n\n@keyframes blink {\n 50% {\n opacity: 0;\n }\n}\n\n.stats {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 8px;\n}\n\n.stats > div {\n display: flex;\n flex-direction: column;\n padding: 10px 12px;\n border-radius: 6px;\n background: var(--sunken);\n}\n\n.stats strong {\n font-size: 20px;\n color: var(--fg-strong);\n}\n\n.stats span {\n font-size: 12px;\n}\n\n.stats .tags {\n grid-column: 1 / -1;\n flex-direction: row;\n flex-wrap: wrap;\n gap: 6px;\n padding: 0;\n background: none;\n}\n\n.tag {\n padding: 2px 8px;\n border-radius: 999px;\n background: var(--accent-soft);\n color: var(--accent);\n}\n\n.jobs {\n display: flex;\n flex-direction: column;\n gap: 6px;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.jobs li {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 8px 10px;\n border-radius: 6px;\n background: var(--sunken);\n font-size: 13px;\n}\n\n.pill {\n min-width: 64px;\n padding: 1px 8px;\n border-radius: 999px;\n font-size: 12px;\n font-weight: 600;\n text-align: center;\n}\n\n.pill.queued {\n background: var(--warning-soft);\n color: var(--warning);\n}\n\n.pill.running {\n background: var(--accent-soft);\n color: var(--accent);\n}\n\n.pill.success {\n background: var(--success-soft);\n color: var(--success);\n}\n\n.pill.failure {\n background: var(--error-soft);\n color: var(--error);\n}\n\n.bar {\n flex: 1;\n height: 4px;\n border-radius: 999px;\n background: var(--border);\n overflow: hidden;\n}\n\n.bar-fill {\n width: 0;\n height: 100%;\n border-radius: inherit;\n background: var(--accent);\n}\n\n.bar-fill.running {\n animation: fill linear forwards;\n}\n\n.bar-fill.success {\n width: 100%;\n background: var(--success);\n}\n\n.bar-fill.failure {\n width: 100%;\n background: var(--error);\n}\n\n@keyframes fill {\n to {\n width: 95%;\n }\n}\n", + "/package.json": "{\n \"dependencies\": {\n \"svelte\": \"^5.56.8\"\n }\n}" + } + }, + "starter_runnables": { + "greet": { + "name": "greet", + "fields": { + "username": { + "type": "ctx", + "ctx": "username" + } + }, + "type": "inline", + "inlineScript": { + "content": "// import * as wmill from \"windmill-client\"\n\n// `username` is a context field: the app fills it with the viewer's username.\n// Direct API callers can pass any value, so don't use it for access control.\nexport async function main(name: string, username: string) {\n return {\n message: `Hello ${name}! ${username ? `You are signed in as ${username}.` : 'You are not signed in.'}`,\n ran_at: new Date().toISOString()\n }\n}\n", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "name": { + "default": null, + "description": "", + "originalType": "string", + "type": "string" + }, + "username": { + "default": null, + "description": "", + "originalType": "string", + "type": "string" + } + }, + "required": [ + "name", + "username" + ], + "type": "object" + } + } + }, + "word_stats": { + "name": "word_stats", + "fields": {}, + "type": "inline", + "inlineScript": { + "content": "import re\nfrom collections import Counter\n\n\ndef main(text: str):\n words = re.findall(r\"[a-z']+\", text.lower())\n top = Counter(w for w in words if len(w) > 4).most_common(5)\n return {\n \"words\": len(words),\n \"characters\": len(text),\n \"sentences\": len(re.findall(r\"[.!?]+\", text)),\n \"top_words\": [word for word, _ in top],\n }\n", + "language": "python3", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "text": { + "default": null, + "description": "", + "originalType": "string", + "type": "string" + } + }, + "required": [ + "text" + ], + "type": "object" + } + } + }, + "slow_task": { + "name": "slow_task", + "fields": {}, + "type": "inline", + "inlineScript": { + "content": "export async function main(seconds: number) {\n await new Promise((resolve) => setTimeout(resolve, seconds * 1000))\n return `Done after ${seconds}s`\n}\n", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "seconds": { + "default": null, + "description": "", + "originalType": "number", + "type": "number" + } + }, + "required": [ + "seconds" + ], + "type": "object" + } + } + }, + "stream_text": { + "name": "stream_text", + "fields": {}, + "type": "inline", + "inlineScript": { + "content": "// Returning an async generator streams each yielded chunk to the caller.\nexport async function main() {\n const text =\n 'Every word of this text is yielded by a Bun script as soon as it is ready, ' +\n 'and the app renders it the moment it arrives. Use the same pattern to ' +\n 'stream an LLM answer, a long report or live logs.'\n return (async function* () {\n for (const word of text.split(' ')) {\n await new Promise((resolve) => setTimeout(resolve, 60))\n yield word + ' '\n }\n })()\n}\n", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": {}, + "required": [], + "type": "object" + } + } + } + } +} diff --git a/backend/windmill-api/src/mcp/session/gen/instructions.json b/backend/windmill-api/src/mcp/session/gen/instructions.json new file mode 100644 index 0000000000..9cdb920c99 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/gen/instructions.json @@ -0,0 +1,237 @@ +{ + "index": { + "script": { + "": "script", + "python3": "script.python3", + "deno": "script.deno", + "go": "script.go", + "bash": "script.bash", + "powershell": "script.powershell", + "postgresql": "script.postgresql", + "mysql": "script.mysql", + "bigquery": "script.bigquery", + "snowflake": "script.snowflake", + "mssql": "script.mssql", + "oracledb": "script.oracledb", + "graphql": "script.graphql", + "nativets": "script.nativets", + "bun": "script.bun", + "php": "script.php", + "rust": "script.rust", + "ansible": "script.ansible", + "csharp": "script.csharp", + "nu": "script.nu", + "java": "script.java", + "ruby": "script.ruby", + "rlang": "script.rlang", + "duckdb": "script.duckdb", + "bunnative": "script.bunnative", + "dbt": "script.dbt" + }, + "flow": { + "": "flow", + "python3": "flow", + "deno": "flow", + "go": "flow", + "bash": "flow", + "powershell": "flow", + "postgresql": "flow", + "mysql": "flow", + "bigquery": "flow", + "snowflake": "flow", + "mssql": "flow", + "oracledb": "flow", + "graphql": "flow", + "nativets": "flow", + "bun": "flow", + "php": "flow", + "rust": "flow", + "ansible": "flow", + "csharp": "flow", + "nu": "flow", + "java": "flow", + "ruby": "flow", + "rlang": "flow", + "duckdb": "flow", + "bunnative": "flow", + "dbt": "flow" + }, + "resource": { + "": "resource", + "python3": "resource", + "deno": "resource", + "go": "resource", + "bash": "resource", + "powershell": "resource", + "postgresql": "resource", + "mysql": "resource", + "bigquery": "resource", + "snowflake": "resource", + "mssql": "resource", + "oracledb": "resource", + "graphql": "resource", + "nativets": "resource", + "bun": "resource", + "php": "resource", + "rust": "resource", + "ansible": "resource", + "csharp": "resource", + "nu": "resource", + "java": "resource", + "ruby": "resource", + "rlang": "resource", + "duckdb": "resource", + "bunnative": "resource", + "dbt": "resource" + }, + "app": { + "": "app", + "python3": "app.python3", + "deno": "app", + "go": "app", + "bash": "app", + "powershell": "app", + "postgresql": "app", + "mysql": "app", + "bigquery": "app", + "snowflake": "app", + "mssql": "app", + "oracledb": "app", + "graphql": "app", + "nativets": "app", + "bun": "app", + "php": "app", + "rust": "app", + "ansible": "app", + "csharp": "app", + "nu": "app", + "java": "app", + "ruby": "app", + "rlang": "app", + "duckdb": "app", + "bunnative": "app", + "dbt": "app" + }, + "datatable": { + "": "datatable", + "python3": "datatable.python3", + "deno": "datatable", + "go": "datatable.go", + "bash": "datatable.go", + "powershell": "datatable.go", + "postgresql": "datatable.go", + "mysql": "datatable.go", + "bigquery": "datatable.go", + "snowflake": "datatable.go", + "mssql": "datatable.go", + "oracledb": "datatable.go", + "graphql": "datatable.go", + "nativets": "datatable", + "bun": "datatable", + "php": "datatable.go", + "rust": "datatable.go", + "ansible": "datatable.go", + "csharp": "datatable.go", + "nu": "datatable.go", + "java": "datatable.go", + "ruby": "datatable.go", + "rlang": "datatable.go", + "duckdb": "datatable.go", + "bunnative": "datatable", + "dbt": "datatable.go" + }, + "pipeline": { + "": "pipeline", + "python3": "pipeline", + "deno": "pipeline", + "go": "pipeline", + "bash": "pipeline", + "powershell": "pipeline", + "postgresql": "pipeline", + "mysql": "pipeline", + "bigquery": "pipeline", + "snowflake": "pipeline", + "mssql": "pipeline", + "oracledb": "pipeline", + "graphql": "pipeline", + "nativets": "pipeline", + "bun": "pipeline", + "php": "pipeline", + "rust": "pipeline", + "ansible": "pipeline", + "csharp": "pipeline", + "nu": "pipeline", + "java": "pipeline", + "ruby": "pipeline", + "rlang": "pipeline", + "duckdb": "pipeline", + "bunnative": "pipeline", + "dbt": "pipeline" + }, + "workspace_settings": { + "": "workspace_settings", + "python3": "workspace_settings", + "deno": "workspace_settings", + "go": "workspace_settings", + "bash": "workspace_settings", + "powershell": "workspace_settings", + "postgresql": "workspace_settings", + "mysql": "workspace_settings", + "bigquery": "workspace_settings", + "snowflake": "workspace_settings", + "mssql": "workspace_settings", + "oracledb": "workspace_settings", + "graphql": "workspace_settings", + "nativets": "workspace_settings", + "bun": "workspace_settings", + "php": "workspace_settings", + "rust": "workspace_settings", + "ansible": "workspace_settings", + "csharp": "workspace_settings", + "nu": "workspace_settings", + "java": "workspace_settings", + "ruby": "workspace_settings", + "rlang": "workspace_settings", + "duckdb": "workspace_settings", + "bunnative": "workspace_settings", + "dbt": "workspace_settings" + } + }, + "texts": { + "script": "# 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- No script language was provided. Default to `bun` only for new TypeScript scripts; if the user requested another language or you read an existing script, call get_instructions again with that language.\n\n# Windmill script authoring reference (bun)\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)\n\nBun runtime with full npm ecosystem and fastest execution. **Bun is the default and preferred TypeScript runtime** — choose it for any TypeScript script unless there is a major reason to use Deno for that specific use-case.\n\n## Structure\n\nExport a single **async** function called `main`:\n\n```typescript\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. Libraries are installed automatically.\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\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```typescript\nimport Stripe from \"stripe\";\nimport { someFunction } from \"some-package\";\n```\n\n## Prefer `//native` when the runtime allows it\n\nIf a script only needs `fetch` and the JavaScript standard library — including when it uses `windmill-client` — prefer making it a **native** script: add `//native` as the first line and write it with the `write-script-bunnative` skill. Native scripts run on a lightweight V8 isolate, start faster, and parallelize heavily. `windmill-client` works on the native worker (its calls go over `fetch`), so needing the Windmill client is **not** a reason to avoid `//native`. Use the regular `bun` language only when the code (or a dependency) needs Node/Bun runtime APIs — `node:*` modules, the filesystem, child processes, or native addons.\n\n## Windmill Client\n\nImport the windmill client for platform interactions:\n\n```typescript\nimport * as wmill from \"windmill-client\";\n```\n\n**Prefer `windmill-client` over raw `fetch` for anything that talks to Windmill** — reading resources/variables/states, running scripts and flows, S3 object operations, etc. It handles auth, the workspace, and the base URL for you, so you don't hand-roll URLs or tokens. Reserve `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 to use instead of guessing or falling back to `fetch`.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```typescript\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\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\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.python3": "# 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 (python3)\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# Python\n\n## Structure\n\nThe script must contain at least one function called `main`:\n\n```python\ndef main(param1: str, param2: int):\n # Your code here\n return {\"result\": param1, \"count\": param2}\n```\n\nDo not call the main function. Libraries are installed automatically.\n\n## Resource Types\n\nOn Windmill, credentials and configuration are stored in resources and passed as parameters to main.\n\nYou need to **redefine** the type of the resources that are needed before the main function as TypedDict:\n\n```python\nfrom typing import TypedDict\n\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 database connection details\n pass\n```\n\n**Important rules:**\n\n- The resource type name must be **IN LOWERCASE**\n- Only include resource types if they are actually needed\n- If an import conflicts with a resource type name, **rename the imported object, not the type name**\n- Make sure to import TypedDict from typing **if you're using it**\n\n## Imports\n\nLibraries are installed automatically. Do not show installation instructions.\n\n```python\nimport requests\nimport pandas as pd\nfrom datetime import datetime\n```\n\nIf an import name conflicts with a resource type:\n\n```python\n# Wrong - don't rename the type\nimport stripe as stripe_lib\nclass stripe_type(TypedDict): ...\n\n# Correct - rename the import\nimport stripe as stripe_sdk\nclass stripe(TypedDict):\n api_key: str\n```\n\n## Windmill Client\n\nImport the windmill client for platform interactions:\n\n```python\nimport wmill\n```\n\nSee the SDK documentation for available methods.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```python\nfrom typing import TypedDict, Literal, Any\n\nclass Event(TypedDict):\n kind: Literal[\"webhook\", \"http\", \"websocket\", \"kafka\", \"email\", \"nats\", \"postgres\", \"sqs\", \"mqtt\", \"amqp\", \"gcp\", \"azure\"]\n body: Any\n headers: dict[str, str]\n query: dict[str, str]\n\ndef preprocessor(event: Event):\n # Transform the event into flow input parameters\n return {\n \"param1\": event[\"body\"][\"field1\"],\n \"param2\": event[\"query\"][\"id\"]\n }\n```\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations.\n\n### Receiving an S3Object as a script parameter\n\nTo accept a file from S3 as input to a script, type the parameter with `S3Object` (imported from `wmill`):\n\n```python\nimport wmill\nfrom wmill import S3Object\n\ndef main(file: S3Object):\n content = wmill.load_s3_file(file)\n # ...\n```\n\n### S3 operations\n\n```python\nimport wmill\n\n# Load file content from S3\ncontent: bytes = wmill.load_s3_file(s3object)\n\n# Load file as stream reader\nreader: BufferedReader = wmill.load_s3_file_reader(s3object)\n\n# Write file to S3\nresult: S3Object = wmill.write_s3_file(\n s3object, # Target path (or None to auto-generate)\n file_content, # bytes or BufferedReader\n s3_resource_path, # Optional: specific S3 resource\n content_type, # Optional: MIME type\n content_disposition # Optional: Content-Disposition header\n)\n```\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:///`` 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:///`` 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:///` URI string (`s3:///`\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", + "script.deno": "# 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 (deno)\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 (Deno)\n\nDeno runtime with npm support via `npm:` prefix and native Deno libraries.\n\n**Prefer Bun (`write-script-bun`) for TypeScript.** Only use Deno when the script specifically requires the Deno runtime — Deno's standard library or `deno.land` URL imports that have no npm equivalent. For all other TypeScript, use Bun instead.\n\n## Structure\n\nExport a single **async** function called `main`:\n\n```typescript\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. Libraries are installed automatically.\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\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```typescript\n// npm packages use npm: prefix\nimport Stripe from \"npm:stripe\";\nimport { someFunction } from \"npm:some-package\";\n\n// Deno standard library\nimport { serve } from \"https://deno.land/std/http/server.ts\";\n```\n\n## Windmill Client\n\nImport the windmill client for platform interactions:\n\n```typescript\nimport * as wmill from \"windmill-client\";\n```\n\n**Prefer `windmill-client` over raw `fetch` for anything that talks to Windmill** — reading resources/variables/states, running scripts and flows, S3 object operations, etc. It handles auth, the workspace, and the base URL for you. Reserve `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 guessing or falling back to `fetch`.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```typescript\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\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\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.go": "# 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 (go)\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# Go\n\n## Structure\n\nThe file package must be `inner` and export a function called `main`:\n\n```go\npackage inner\n\nfunc main(param1 string, param2 int) (map[string]interface{}, error) {\n return map[string]interface{}{\n \"result\": param1,\n \"count\": param2,\n }, nil\n}\n```\n\n**Important:**\n- Package must be `inner`\n- Return type must be `({return_type}, error)`\n- Function name is `main` (lowercase)\n\n## Return Types\n\nThe return type can be any Go type that can be serialized to JSON:\n\n```go\npackage inner\n\ntype Result struct {\n Name string `json:\"name\"`\n Count int `json:\"count\"`\n}\n\nfunc main(name string, count int) (Result, error) {\n return Result{\n Name: name,\n Count: count,\n }, nil\n}\n```\n\n## Error Handling\n\nReturn errors as the second return value:\n\n```go\npackage inner\n\nimport \"errors\"\n\nfunc main(value int) (string, error) {\n if value < 0 {\n return \"\", errors.New(\"value must be positive\")\n }\n return \"success\", nil\n}\n```\n", + "script.bash": "# 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 (bash)\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# Bash\n\n## Structure\n\nDo not include `#!/bin/bash`. Arguments are obtained as positional parameters:\n\n```bash\n# Get arguments\nvar1=\"$1\"\nvar2=\"$2\"\n\necho \"Processing $var1 and $var2\"\n\n# Return JSON by echoing to stdout\necho \"{\\\"result\\\": \\\"$var1\\\", \\\"count\\\": $var2}\"\n```\n\n**Important:**\n- Do not include shebang (`#!/bin/bash`)\n- Arguments are always strings\n- Access with `$1`, `$2`, etc.\n\n## Output\n\nThe script output is captured as the result. For structured data, output valid JSON:\n\n```bash\nname=\"$1\"\ncount=\"$2\"\n\n# Output JSON result\ncat << EOF\n{\n \"name\": \"$name\",\n \"count\": $count,\n \"timestamp\": \"$(date -Iseconds)\"\n}\nEOF\n```\n\n## Environment Variables\n\nEnvironment variables set in Windmill are available:\n\n```bash\n# Access environment variable\necho \"Workspace: $WM_WORKSPACE\"\necho \"Job ID: $WM_JOB_ID\"\n```\n", + "script.powershell": "# 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 (powershell)\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# PowerShell\n\n## Structure\n\nArguments are obtained by calling the `param` function on the first line:\n\n```powershell\nparam($Name, $Count = 0, [int]$Age)\n\n# Your code here\nWrite-Output \"Processing $Name, count: $Count, age: $Age\"\n\n# Return object\n@{\n name = $Name\n count = $Count\n age = $Age\n}\n```\n\n## Parameter Types\n\nYou can specify types for parameters:\n\n```powershell\nparam(\n [string]$Name,\n [int]$Count = 0,\n [bool]$Enabled = $true,\n [array]$Items\n)\n\n@{\n name = $Name\n count = $Count\n enabled = $Enabled\n items = $Items\n}\n```\n\n## Return Values\n\nReturn values by outputting them at the end of the script:\n\n```powershell\nparam($Input)\n\n$result = @{\n processed = $true\n data = $Input\n timestamp = Get-Date -Format \"o\"\n}\n\n$result\n```\n", + "script.postgresql": "# 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 (postgresql)\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# PostgreSQL\n\nArguments are obtained directly in the statement with `$1::{type}`, `$2::{type}`, etc.\n\nName the parameters by adding comments at the beginning of the script (without specifying the type):\n\n```sql\n-- $1 name1\n-- $2 name2 = default_value\nSELECT * FROM users WHERE name = $1::TEXT AND age > $2::INT;\n```\n\n## Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for\nit, downloads the file, and binds it as a `jsonb` parameter — Parquet/CSV files\nare decoded server-side into a JSON array of records, JSON/JSONL pass through.\nConsume with `jsonb_to_recordset` (or any `jsonb` API):\n\n```sql\n-- $1 file (s3object)\nSELECT *\nFROM jsonb_to_recordset($1::jsonb) AS r(id INT, name TEXT);\n```\n\n## Streaming query results to S3\n\nAdd a `-- s3` directive at the top of the script to stream the result set to S3\ninstead of returning rows. Windmill writes the file and returns its `S3Object`\nas the script result.\n\n```sql\n-- s3 prefix=exports/users format=parquet\nSELECT id, name FROM users;\n```\n\nAll keys are optional: `prefix` (object key prefix), `storage` (named storage —\nomit to use the workspace default), `format` (`json` (default), `parquet`, or\n`csv`). Use this for large result sets — rows stream directly to S3 instead of\nbeing buffered as the script return value.\n", + "script.mysql": "# 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 (mysql)\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# MySQL\n\nArguments use `?` placeholders.\n\nName the parameters by adding comments before the statement:\n\n```sql\n-- ? name1 (text)\n-- ? name2 (int) = 0\nSELECT * FROM users WHERE name = ? AND age > ?;\n```\n\n## Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for\nit, downloads the file, and binds it as JSON text — Parquet/CSV files are\ndecoded server-side into a JSON array of records, JSON/JSONL pass through.\nConsume with `JSON_TABLE`:\n\n```sql\n-- ? file (s3object)\nSELECT id, name\nFROM JSON_TABLE(?, '$[*]'\n COLUMNS (id INT PATH '$.id', name VARCHAR(200) PATH '$.name')\n) AS r;\n```\n\n## Streaming query results to S3\n\nAdd a `-- s3` directive at the top of the script to stream the result set to S3\ninstead of returning rows. Windmill writes the file and returns its `S3Object`\nas the script result.\n\n```sql\n-- s3 prefix=exports/users format=parquet\nSELECT id, name FROM users;\n```\n\nAll keys are optional: `prefix` (object key prefix), `storage` (named storage —\nomit to use the workspace default), `format` (`json` (default), `parquet`, or\n`csv`). Use this for large result sets — rows stream directly to S3 instead of\nbeing buffered as the script return value.\n", + "script.bigquery": "# 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 (bigquery)\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# BigQuery\n\nArguments use `@name` syntax.\n\nName the parameters by adding comments before the statement:\n\n```sql\n-- @name1 (string)\n-- @name2 (int64) = 0\nSELECT * FROM users WHERE name = @name1 AND age > @name2;\n```\n\n## Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for\nit, downloads the file, and binds it as a `STRING` JSON parameter — Parquet/CSV\nfiles are decoded server-side into a JSON array of records, JSON/JSONL pass\nthrough. Consume with `JSON_EXTRACT_ARRAY` / `JSON_VALUE`:\n\n```sql\n-- @file (s3object)\nSELECT\n CAST(JSON_VALUE(row, '$.id') AS INT64) AS id,\n JSON_VALUE(row, '$.name') AS name\nFROM UNNEST(JSON_EXTRACT_ARRAY(@file)) AS row;\n```\n\n## Streaming query results to S3\n\nAdd a `-- s3` directive at the top of the script to stream the result set to S3\ninstead of returning rows. Windmill writes the file and returns its `S3Object`\nas the script result.\n\n```sql\n-- s3 prefix=exports/users format=parquet\nSELECT id, name FROM users;\n```\n\nAll keys are optional: `prefix` (object key prefix), `storage` (named storage —\nomit to use the workspace default), `format` (`json` (default), `parquet`, or\n`csv`). Use this for large result sets — rows stream directly to S3 instead of\nbeing buffered, bypassing the 10000-row return cap.\n", + "script.snowflake": "# 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 (snowflake)\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# Snowflake\n\nArguments use `?` placeholders.\n\nName the parameters by adding comments before the statement:\n\n```sql\n-- ? name1 (text)\n-- ? name2 (number) = 0\nSELECT * FROM users WHERE name = ? AND age > ?;\n```\n\n## Array parameters\n\nDeclare a list with a `[]` suffix on the element type (`(varchar[])`,\n`(int[])`), or `(array)` for an untyped one. Snowflake cannot bind an array\ndirectly, so Windmill binds the list as JSON text: wrap the placeholder with\n`PARSE_JSON(?)`, and cast to `ARRAY` where a function expects one.\n\n```sql\n-- ? groups (varchar[])\nSELECT o.* FROM orders o\nWHERE ARRAY_CONTAINS(o.owner_group::VARIANT, PARSE_JSON(?)::ARRAY);\n```\n\nOr join on the elements with `FLATTEN`:\n\n```sql\n-- ? groups (varchar[])\nSELECT o.* FROM orders o\nJOIN TABLE(FLATTEN(input => PARSE_JSON(?))) g ON g.value::STRING = o.owner_group;\n```\n\n## Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for\nit, downloads the file, and binds it as JSON text — Parquet/CSV files are\ndecoded server-side into a JSON array of records, JSON/JSONL pass through.\nWrap the bind with `PARSE_JSON(?)` and walk it with `LATERAL FLATTEN`:\n\n```sql\n-- ? file (s3object)\nSELECT\n v.value:id::NUMBER AS id,\n v.value:name::STRING AS name\nFROM LATERAL FLATTEN(input => PARSE_JSON(?)) v;\n```\n\n## Streaming query results to S3\n\nAdd a `-- s3` directive at the top of the script to stream the result set to S3\ninstead of returning rows. Windmill writes the file and returns its `S3Object`\nas the script result.\n\n```sql\n-- s3 prefix=exports/users format=parquet\nSELECT id, name FROM users;\n```\n\nAll keys are optional: `prefix` (object key prefix), `storage` (named storage —\nomit to use the workspace default), `format` (`json` (default), `parquet`, or\n`csv`). Use this for large result sets — rows stream directly to S3 instead of\nbeing buffered, bypassing the 10000-row return cap.\n", + "script.mssql": "# 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 (mssql)\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# Microsoft SQL Server (MSSQL)\n\nArguments use `@P1`, `@P2`, etc.\n\nName the parameters by adding comments before the statement:\n\n```sql\n-- @P1 name1 (varchar)\n-- @P2 name2 (int) = 0\nSELECT * FROM users WHERE name = @P1 AND age > @P2;\n```\n\n## Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for\nit, downloads the file, and binds it as `nvarchar(max)` JSON text — Parquet/CSV\nfiles are decoded server-side into a JSON array of records, JSON/JSONL pass\nthrough. Consume with `OPENJSON`:\n\n```sql\n-- @P1 file (s3object)\nSELECT id, name\nFROM OPENJSON(@P1)\nWITH (id INT, name NVARCHAR(200));\n```\n\n## Streaming query results to S3\n\nAdd a `-- s3` directive at the top of the script to stream the result set to S3\ninstead of returning rows. Windmill writes the file and returns its `S3Object`\nas the script result.\n\n```sql\n-- s3 prefix=exports/users format=parquet\nSELECT id, name FROM users;\n```\n\nAll keys are optional: `prefix` (object key prefix), `storage` (named storage —\nomit to use the workspace default), `format` (`json` (default), `parquet`, or\n`csv`). Use this for large result sets — rows stream directly to S3 instead of\nbeing buffered as the script return value.\n", + "script.oracledb": "# 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 (oracledb)\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", + "script.graphql": "# 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 (graphql)\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# GraphQL\n\n## Structure\n\nWrite GraphQL queries or mutations. Arguments can be added as query parameters:\n\n```graphql\nquery GetUser($id: ID!) {\n user(id: $id) {\n id\n name\n email\n }\n}\n```\n\n## Variables\n\nVariables are passed as script arguments and automatically bound to the query:\n\n```graphql\nquery SearchProducts($query: String!, $limit: Int = 10) {\n products(search: $query, first: $limit) {\n edges {\n node {\n id\n name\n price\n }\n }\n }\n}\n```\n\n## Mutations\n\n```graphql\nmutation CreateUser($input: CreateUserInput!) {\n createUser(input: $input) {\n id\n name\n createdAt\n }\n}\n```\n", + "script.nativets": "# 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 (nativets)\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 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.bun": "# 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 (bun)\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)\n\nBun runtime with full npm ecosystem and fastest execution. **Bun is the default and preferred TypeScript runtime** — choose it for any TypeScript script unless there is a major reason to use Deno for that specific use-case.\n\n## Structure\n\nExport a single **async** function called `main`:\n\n```typescript\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. Libraries are installed automatically.\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\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```typescript\nimport Stripe from \"stripe\";\nimport { someFunction } from \"some-package\";\n```\n\n## Prefer `//native` when the runtime allows it\n\nIf a script only needs `fetch` and the JavaScript standard library — including when it uses `windmill-client` — prefer making it a **native** script: add `//native` as the first line and write it with the `write-script-bunnative` skill. Native scripts run on a lightweight V8 isolate, start faster, and parallelize heavily. `windmill-client` works on the native worker (its calls go over `fetch`), so needing the Windmill client is **not** a reason to avoid `//native`. Use the regular `bun` language only when the code (or a dependency) needs Node/Bun runtime APIs — `node:*` modules, the filesystem, child processes, or native addons.\n\n## Windmill Client\n\nImport the windmill client for platform interactions:\n\n```typescript\nimport * as wmill from \"windmill-client\";\n```\n\n**Prefer `windmill-client` over raw `fetch` for anything that talks to Windmill** — reading resources/variables/states, running scripts and flows, S3 object operations, etc. It handles auth, the workspace, and the base URL for you, so you don't hand-roll URLs or tokens. Reserve `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 to use instead of guessing or falling back to `fetch`.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```typescript\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\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\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.php": "# 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 (php)\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# PHP\n\n## Structure\n\nThe script must start with ` $param1, \"count\" => $param2];\n}\n```\n\n## Resource Types\n\nOn Windmill, credentials and configuration are stored in resources and passed as parameters to main.\n\nYou need to **redefine** the type of the resources that are needed before the main function. Always check if the class already exists using `class_exists`:\n\n```php\n/` 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 (rust)\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# Rust\n\n## Structure\n\nThe script must contain a function called `main` with proper return type:\n\n```rust\nuse anyhow::anyhow;\nuse serde::Serialize;\n\n#[derive(Serialize, Debug)]\nstruct ReturnType {\n result: String,\n count: i32,\n}\n\nfn main(param1: String, param2: i32) -> anyhow::Result {\n Ok(ReturnType {\n result: param1,\n count: param2,\n })\n}\n```\n\n**Important:**\n- Arguments should be owned types\n- Return type must be serializable (`#[derive(Serialize)]`)\n- Return type is `anyhow::Result`\n\n## Dependencies\n\nPackages must be specified with a partial cargo.toml at the beginning of the script:\n\n```rust\n//! ```cargo\n//! [dependencies]\n//! anyhow = \"1.0.86\"\n//! reqwest = { version = \"0.11\", features = [\"json\"] }\n//! tokio = { version = \"1\", features = [\"full\"] }\n//! ```\n\nuse anyhow::anyhow;\n// ... rest of the code\n```\n\n**Note:** Serde is already included, no need to add it again.\n\n## Async Functions\n\nIf you need to handle async functions (e.g., using tokio), keep the main function sync and create the runtime inside:\n\n```rust\n//! ```cargo\n//! [dependencies]\n//! anyhow = \"1.0.86\"\n//! tokio = { version = \"1\", features = [\"full\"] }\n//! reqwest = { version = \"0.11\", features = [\"json\"] }\n//! ```\n\nuse anyhow::anyhow;\nuse serde::Serialize;\n\n#[derive(Serialize, Debug)]\nstruct Response {\n data: String,\n}\n\nfn main(url: String) -> anyhow::Result {\n let rt = tokio::runtime::Runtime::new()?;\n rt.block_on(async {\n let resp = reqwest::get(&url).await?.text().await?;\n Ok(Response { data: resp })\n })\n}\n```\n", + "script.ansible": "# 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 (ansible)\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# Ansible\n\nWindmill runs Ansible playbooks with `ansible-playbook`. A script is a single YAML\ndocument made of two parts separated by a `---` line: a Windmill **header** and one or\nmore standard Ansible **plays**.\n\n## Structure\n\n```yaml\n---\n# Windmill header: configures inventories, file resources, arguments and dependencies\nextra_vars:\n world_qualifier:\n type: string\ndependencies:\n galaxy:\n collections:\n - name: community.general\n python:\n - jmespath\n---\n# Standard Ansible plays\n- name: Echo\n hosts: 127.0.0.1\n connection: local\n tasks:\n - name: Print debug message\n debug:\n msg: \"Hello, {{ world_qualifier }} world!\"\n```\n\n## Header\n\nThe header is **not** standard Ansible — it is parsed by Windmill to build the script's\ninputs and runtime environment. Supported keys:\n\n- `extra_vars`: defines the script arguments. Each entry is passed to the playbook via\n `--extra-vars` and becomes a Jinja variable usable as `{{ name }}` in the plays. Give\n each argument a `type` (`string`, `number`, `boolean`, `object`, ...) so Windmill can\n generate the input form.\n- `inventory`: lists inventories. Use `resource_type: ansible_inventory` (optionally\n pinned with `resource: u/user/your_resource`) or `resource_type: dynamic_inventory`.\n- `files`: writes Windmill resources/variables to files before the run, e.g.\n `- resource: u/user/template` with `target: ./config.j2`, or\n `- variable: u/user/ssh_key` with `target: ./ssh_key` and `mode: '0600'`.\n- `dependencies`: `galaxy` collections/roles (installed with `ansible-galaxy`) and\n `python` pip packages available to the playbook.\n- `options`: extra `ansible-playbook` flags such as `- verbosity: vvv`.\n- `vault_password`: a Windmill variable path to use as the Ansible Vault password.\n\n## Arguments\n\nReference header `extra_vars` directly as Jinja variables in the plays:\n\n```yaml\nextra_vars:\n name:\n type: string\n count:\n type: number\n---\n- hosts: localhost\n tasks:\n - debug:\n msg: \"{{ name }} x {{ count }}\"\n```\n\n## Environment variables\n\nWindmill contextual variables are available as environment variables and read with the\n`env` lookup:\n\n```yaml\n- debug:\n msg: \"Running in workspace {{ lookup('env', 'WM_WORKSPACE') }}\"\n```\n\n## Output\n\nTo return a result, write JSON to a `result.json` file in the job directory:\n\n```yaml\n- hosts: localhost\n tasks:\n - name: Write result\n copy:\n content: \"{{ { 'ok': true, 'value': 42 } | to_json }}\"\n dest: result.json\n```\n", + "script.csharp": "# 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 (csharp)\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# C#\n\nThe script must contain a public static `Main` method inside a class:\n\n```csharp\npublic class Script\n{\n public static object Main(string name, int count)\n {\n return new { Name = name, Count = count };\n }\n}\n```\n\n**Important:**\n- Class name is irrelevant\n- Method must be `public static`\n- Return type can be `object` or specific type\n\n## NuGet Packages\n\nAdd packages using the `#r` directive at the top:\n\n```csharp\n#r \"nuget: Newtonsoft.Json, 13.0.3\"\n#r \"nuget: RestSharp, 110.2.0\"\n\nusing Newtonsoft.Json;\nusing RestSharp;\n\npublic class Script\n{\n public static object Main(string url)\n {\n var client = new RestClient(url);\n var request = new RestRequest();\n var response = client.Get(request);\n return JsonConvert.DeserializeObject(response.Content);\n }\n}\n```\n", + "script.nu": "# 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 (nu)\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", + "script.java": "# 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 (java)\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# Java\n\nThe script must contain a Main public class with a `public static main()` method:\n\n```java\npublic class Main {\n public static Object main(String name, int count) {\n java.util.Map result = new java.util.HashMap<>();\n result.put(\"name\", name);\n result.put(\"count\", count);\n return result;\n }\n}\n```\n\n**Important:**\n- Class must be named `Main`\n- Method must be `public static Object main(...)`\n- Return type is `Object` or `void`\n\n## Maven Dependencies\n\nAdd dependencies using comments at the top:\n\n```java\n//requirements:\n//com.google.code.gson:gson:2.10.1\n//org.apache.httpcomponents:httpclient:4.5.14\n\nimport com.google.gson.Gson;\n\npublic class Main {\n public static Object main(String input) {\n Gson gson = new Gson();\n return gson.fromJson(input, Object.class);\n }\n}\n```\n", + "script.ruby": "# 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 (ruby)\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", + "script.rlang": "# 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 (rlang)\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# R\n\n## Structure\n\nDefine a `main` function using `<-` or `=` assignment. Parameters become the script inputs:\n\n```r\nlibrary(dplyr)\nlibrary(jsonlite)\n\nmain <- function(x, name = \"default\", flag = TRUE) {\n df <- tibble(x = x, name = name)\n result <- df %>% mutate(greeting = paste(\"Hello\", name))\n return(toJSON(result, auto_unbox = TRUE))\n}\n```\n\n**Important:**\n- The `main` function is required\n- Use `library()` to load packages — they are resolved and installed automatically\n- `jsonlite` is always available (used internally for argument parsing)\n- Return values must be JSON-serializable\n\n## Parameters\n\nR types map to Windmill types:\n- `numeric` → float/int\n- `character` → string\n- `logical` → bool (use `TRUE`/`FALSE`)\n- `list` → object/dict\n- `NULL` → null\n\nDefault values are inferred from the function signature:\n\n```r\nmain <- function(\n name, # required string\n count = 10, # optional int, default 10\n verbose = FALSE # optional bool, default FALSE\n) {\n # ...\n}\n```\n\n## Resources and Variables\n\nUse the built-in Windmill helpers (no import needed):\n\n```r\nmain <- function() {\n # Get a variable\n api_key <- get_variable(\"f/my_folder/api_key\")\n\n # Get a resource (returns a list)\n db <- get_resource(\"f/my_folder/postgres_config\")\n host <- db$host\n port <- db$port\n\n return(list(host = host, port = port))\n}\n```\n\n## Output\n\nReturn any JSON-serializable value from `main`. The return value becomes the step result:\n\n```r\nmain <- function(x) {\n # Return a scalar\n return(x + 1)\n\n # Or a list (becomes JSON object)\n return(list(result = x + 1, status = \"ok\"))\n}\n```\n\n## Annotations\n\nControl execution behavior with comment annotations:\n\n```r\n#renv_verbose = true # Show verbose renv output during resolution\n#renv_install_verbose = true # Show verbose output during package installation\n#sandbox = true # Run in nsjail sandbox (requires nsjail)\n```\n", + "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, 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, 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/flow tool, `mcp` for an MCP server\ntool, `websearch` for web search.\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\": \"static\", \"value\": \"\" } }\n }\n }\n ]\n }\n}\n```\n\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` tool's\n`summary` is a plain label (`Web Search`), and an `mcp` tool exposes the MCP server's own tool\nnames, so neither 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\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- 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\"},\"debounce_delay_s\":{\"type\":\"integer\",\"description\":\"Delay in seconds to debounce flow executions\"},\"debounce_key\":{\"type\":\"string\",\"description\":\"Expression to group debounced executions\"},\"debounce_args_to_accumulate\":{\"type\":\"array\",\"description\":\"Arguments to accumulate across debounced executions\",\"items\":{\"type\":\"string\"}},\"max_total_debouncing_time\":{\"type\":\"integer\",\"description\":\"Maximum total time in seconds that a job can be debounced\"},\"max_total_debounces_amount\":{\"type\":\"integer\",\"description\":\"Maximum number of times a job can be debounced\"},\"skip_expr\":{\"type\":\"string\",\"description\":\"JavaScript expression to conditionally skip the entire flow\"},\"cache_ttl\":{\"type\":\"number\",\"description\":\"Cache duration in seconds for flow results\"},\"cache_ignore_s3_path\":{\"type\":\"boolean\"},\"delete_after_secs\":{\"type\":\"integer\",\"description\":\"If set, delete the flow job's args, result and logs after this many seconds following job completion\"},\"flow_env\":{\"type\":\"object\",\"description\":\"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).\",\"additionalProperties\":{}},\"priority\":{\"type\":\"number\",\"description\":\"Execution priority (higher numbers run first)\"},\"early_return\":{\"type\":\"string\",\"description\":\"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead.\"},\"chat_input_enabled\":{\"type\":\"boolean\",\"description\":\"Whether this flow accepts chat-style input\"},\"notes\":{\"type\":\"array\",\"description\":\"Sticky notes attached to the flow\",\"items\":{\"$ref\":\"#/components/schemas/FlowNote\"}},\"groups\":{\"type\":\"array\",\"description\":\"Semantic groups of modules for organizational purposes\",\"items\":{\"$ref\":\"#/components/schemas/FlowGroup\"}}},\"required\":[\"modules\"]},\"Retry\":{\"type\":\"object\",\"description\":\"Retry configuration for failed module executions\",\"properties\":{\"constant\":{\"type\":\"object\",\"description\":\"Retry with constant delay between attempts\",\"properties\":{\"attempts\":{\"type\":\"integer\",\"description\":\"Number of retry attempts\"},\"seconds\":{\"type\":\"integer\",\"description\":\"Seconds to wait between retries\"}}},\"exponential\":{\"type\":\"object\",\"description\":\"Retry with exponential backoff: the n-th retry waits multiplier \\u00d7 seconds^n\",\"properties\":{\"attempts\":{\"type\":\"integer\",\"description\":\"Number of retry attempts\"},\"multiplier\":{\"type\":\"integer\",\"description\":\"Multiplier for exponential backoff\"},\"seconds\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Base of the exponential (seconds); the n-th retry waits multiplier \\u00d7 seconds^n, where n counts constant retries too\"},\"random_factor\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"description\":\"Random jitter percentage (0-100) to avoid thundering herd\"}}},\"retry_if\":{\"$ref\":\"#/components/schemas/RetryIf\"}}},\"FlowNote\":{\"type\":\"object\",\"description\":\"A sticky note attached to a flow for documentation and annotation\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for the note\"},\"text\":{\"type\":\"string\",\"description\":\"Content of the note\"},\"position\":{\"type\":\"object\",\"description\":\"Position of the note in the flow editor\",\"properties\":{\"x\":{\"type\":\"number\",\"description\":\"X coordinate\"},\"y\":{\"type\":\"number\",\"description\":\"Y coordinate\"}},\"required\":[\"x\",\"y\"]},\"size\":{\"type\":\"object\",\"description\":\"Size of the note in the flow editor\",\"properties\":{\"width\":{\"type\":\"number\",\"description\":\"Width in pixels\"},\"height\":{\"type\":\"number\",\"description\":\"Height in pixels\"}},\"required\":[\"width\",\"height\"]},\"color\":{\"type\":\"string\",\"description\":\"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled.\"},\"type\":{\"type\":\"string\",\"enum\":[\"free\",\"group\"],\"description\":\"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead.\"},\"locked\":{\"type\":\"boolean\",\"default\":false,\"description\":\"Whether the note is locked and cannot be edited or moved\"},\"contained_node_ids\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"For group notes, the IDs of nodes contained within this group\"}},\"required\":[\"id\",\"text\",\"color\",\"type\"]},\"FlowGroup\":{\"type\":\"object\",\"description\":\"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Display name for this group\"},\"note\":{\"type\":\"string\",\"description\":\"Markdown note shown below the group header\"},\"autocollapse\":{\"type\":\"boolean\",\"default\":false,\"description\":\"If true, this group is collapsed by default in the flow editor. UI hint only.\"},\"start_id\":{\"type\":\"string\",\"description\":\"ID of the first flow module in this group (topological entry point)\"},\"end_id\":{\"type\":\"string\",\"description\":\"ID of the last flow module in this group (topological exit point)\"},\"color\":{\"type\":\"string\",\"description\":\"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one.\"}},\"required\":[\"start_id\",\"end_id\"]},\"RetryIf\":{\"type\":\"object\",\"description\":\"Conditional retry based on error or result\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\"}},\"required\":[\"expr\"]},\"StopAfterIf\":{\"type\":\"object\",\"description\":\"Early termination condition for a module\",\"properties\":{\"skip_if_stopped\":{\"type\":\"boolean\",\"description\":\"If true, following steps are skipped when this condition triggers\"},\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop\"},\"error_message\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.\"},\"error_include_result\":{\"type\":\"boolean\",\"description\":\"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.\"}},\"required\":[\"expr\"]},\"FlowModule\":{\"type\":\"object\",\"description\":\"A single step in a flow. Can be a script, subflow, loop, or branch\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)\"},\"value\":{\"$ref\":\"#/components/schemas/FlowModuleValue\"},\"stop_after_if\":{\"description\":\"Early termination condition evaluated after this step completes\",\"$ref\":\"#/components/schemas/StopAfterIf\"},\"stop_after_all_iters_if\":{\"description\":\"For loops only - early termination condition evaluated after all iterations complete\",\"$ref\":\"#/components/schemas/StopAfterIf\"},\"skip_if\":{\"type\":\"object\",\"description\":\"Conditionally skip this step based on previous results or flow inputs\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.'\"}},\"required\":[\"expr\"]},\"sleep\":{\"description\":\"Delay before executing this step (in seconds or as expression)\",\"$ref\":\"#/components/schemas/InputTransform\"},\"cache_ttl\":{\"type\":\"number\",\"description\":\"Cache duration in seconds for this step's results\"},\"cache_ignore_s3_path\":{\"type\":\"boolean\"},\"timeout\":{\"description\":\"Maximum execution time in seconds (static value or expression)\",\"$ref\":\"#/components/schemas/InputTransform\"},\"delete_after_secs\":{\"type\":\"integer\",\"description\":\"If set, delete the step's args, result and logs after this many seconds following job completion\"},\"summary\":{\"type\":\"string\",\"description\":\"Short description of what this step does\"},\"mock\":{\"type\":\"object\",\"description\":\"Mock configuration for testing without executing the actual step\",\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"If true, return mock value instead of executing\"},\"return_value\":{\"description\":\"Value to return when mocked\"}}},\"suspend\":{\"type\":\"object\",\"description\":\"Configuration for approval/resume steps that wait for user input\",\"properties\":{\"required_events\":{\"type\":\"integer\",\"description\":\"Number of approvals required before continuing\"},\"timeout\":{\"type\":\"integer\",\"description\":\"Timeout in seconds before auto-continuing or canceling\"},\"resume_form\":{\"type\":\"object\",\"description\":\"Form schema for collecting input when resuming\",\"properties\":{\"schema\":{\"type\":\"object\",\"description\":\"JSON Schema for the resume form\"}}},\"user_auth_required\":{\"type\":\"boolean\",\"description\":\"If true, only authenticated users can approve\"},\"user_groups_required\":{\"description\":\"Expression or list of groups that can approve\",\"$ref\":\"#/components/schemas/InputTransform\"},\"self_approval_disabled\":{\"type\":\"boolean\",\"description\":\"If true, the user who started the flow cannot approve\"},\"hide_cancel\":{\"type\":\"boolean\",\"description\":\"If true, hide the cancel button on the approval form\"},\"continue_on_disapprove_timeout\":{\"type\":\"boolean\",\"description\":\"If true, continue flow on timeout instead of canceling\"},\"skin\":{\"type\":\"string\",\"enum\":[\"detailed\",\"minimal\"],\"description\":\"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions\"}}},\"priority\":{\"type\":\"number\",\"description\":\"Execution priority for this step (higher numbers run first)\"},\"continue_on_error\":{\"type\":\"boolean\",\"description\":\"If true, flow continues even if this step fails\"},\"job_token_scopes\":{\"type\":\"array\",\"nullable\":true,\"items\":{\"type\":\"string\"},\"description\":\"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).\"},\"retry\":{\"description\":\"Retry configuration if this step fails\",\"$ref\":\"#/components/schemas/Retry\"},\"debouncing\":{\"description\":\"Debounce configuration for this step (EE only)\",\"type\":\"object\",\"properties\":{\"debounce_delay_s\":{\"type\":\"integer\",\"description\":\"Delay in seconds to debounce this step's executions across flow runs\"},\"debounce_key\":{\"type\":\"string\",\"description\":\"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/-\"},\"debounce_args_to_accumulate\":{\"type\":\"array\",\"description\":\"Array-type arguments to accumulate across debounced executions\",\"items\":{\"type\":\"string\"}},\"max_total_debouncing_time\":{\"type\":\"integer\",\"description\":\"Maximum total time in seconds before forced execution\"},\"max_total_debounces_amount\":{\"type\":\"integer\",\"description\":\"Maximum number of debounces before forced execution\"}}}},\"required\":[\"value\",\"id\"]},\"InputTransform\":{\"description\":\"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"StaticTransform\":{\"type\":\"object\",\"description\":\"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'\",\"properties\":{\"value\":{\"description\":\"The static value. For resources, use format '$res:path/to/resource'\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\"]},\"JavascriptTransform\":{\"type\":\"object\",\"description\":\"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)\"},\"type\":{\"type\":\"string\",\"enum\":[\"javascript\"]}},\"required\":[\"expr\",\"type\"]},\"AiTransform\":{\"type\":\"object\",\"description\":\"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"ai\"]}},\"required\":[\"type\"]},\"AIProviderKind\":{\"type\":\"string\",\"description\":\"Supported AI provider types\",\"enum\":[\"openai\",\"azure_openai\",\"azure_foundry\",\"anthropic\",\"mistral\",\"deepseek\",\"googleai\",\"groq\",\"openrouter\",\"togetherai\",\"customai\",\"aws_bedrock\",\"typesafe\",\"cloudflare\"]},\"ProviderConfig\":{\"type\":\"object\",\"description\":\"Complete AI provider configuration with resource reference and model selection\",\"properties\":{\"kind\":{\"$ref\":\"#/components/schemas/AIProviderKind\"},\"resource\":{\"type\":\"string\",\"description\":\"Resource reference in format '$res:{resource_path}' pointing to provider credentials\"},\"model\":{\"type\":\"string\",\"description\":\"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')\"},\"reasoning_effort\":{\"type\":\"string\",\"description\":\"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.\"}},\"required\":[\"kind\",\"resource\",\"model\"]},\"StaticProviderTransform\":{\"type\":\"object\",\"description\":\"Static provider configuration passed directly to the AI agent\",\"properties\":{\"value\":{\"$ref\":\"#/components/schemas/ProviderConfig\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\",\"value\"]},\"ProviderTransform\":{\"description\":\"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticProviderTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticProviderTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"MemoryOff\":{\"type\":\"object\",\"description\":\"No conversation memory/context\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"off\"]}},\"required\":[\"kind\"]},\"MemoryWindow\":{\"type\":\"object\",\"description\":\"Keeps the most recent messages of the memory named by the run's memory id (or the step's\\n`memory_id`). Without a memory id the agent runs without memory.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"window\"]},\"context_length\":{\"type\":\"integer\",\"description\":\"Number of most recent messages to load and store. 0 turns memory off.\"}},\"required\":[\"kind\",\"context_length\"]},\"MemoryAuto\":{\"type\":\"object\",\"deprecated\":true,\"description\":\"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"auto\"]},\"context_length\":{\"type\":\"integer\",\"description\":\"Maximum number of messages to retain in context\"},\"memory_id\":{\"type\":\"string\",\"description\":\"Identifier for persistent memory across agent invocations\"}},\"required\":[\"kind\"]},\"MemoryCompaction\":{\"type\":\"object\",\"description\":\"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\\nits older part with a summary as the conversation approaches the model's context window.\\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"compaction\"]},\"context_window\":{\"type\":\"integer\",\"description\":\"Overrides the context window looked up from the model, in tokens. Only a model\\nWindmill does not know needs one; those fall back to 128000.\\n\"}},\"required\":[\"kind\"]},\"MemoryMessage\":{\"type\":\"object\",\"description\":\"A single message in conversation history\",\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"user\",\"assistant\",\"system\"]},\"content\":{\"type\":\"string\"}},\"required\":[\"role\",\"content\"]},\"MemoryManual\":{\"type\":\"object\",\"deprecated\":true,\"description\":\"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"manual\"]},\"messages\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/MemoryMessage\"}}},\"required\":[\"kind\",\"messages\"]},\"MemoryConfig\":{\"description\":\"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.\",\"oneOf\":[{\"$ref\":\"#/components/schemas/MemoryOff\"},{\"$ref\":\"#/components/schemas/MemoryWindow\"},{\"$ref\":\"#/components/schemas/MemoryCompaction\"},{\"$ref\":\"#/components/schemas/MemoryAuto\"},{\"$ref\":\"#/components/schemas/MemoryManual\"}],\"discriminator\":{\"propertyName\":\"kind\",\"mapping\":{\"off\":\"#/components/schemas/MemoryOff\",\"window\":\"#/components/schemas/MemoryWindow\",\"compaction\":\"#/components/schemas/MemoryCompaction\",\"auto\":\"#/components/schemas/MemoryAuto\",\"manual\":\"#/components/schemas/MemoryManual\"}}},\"StaticMemoryTransform\":{\"type\":\"object\",\"description\":\"Static memory configuration passed directly to the AI agent\",\"properties\":{\"value\":{\"$ref\":\"#/components/schemas/MemoryConfig\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\",\"value\"]},\"MemoryTransform\":{\"description\":\"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticMemoryTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticMemoryTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"FlowModuleValue\":{\"description\":\"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type\",\"oneOf\":[{\"$ref\":\"#/components/schemas/RawScript\"},{\"$ref\":\"#/components/schemas/PathScript\"},{\"$ref\":\"#/components/schemas/PathFlow\"},{\"$ref\":\"#/components/schemas/ForloopFlow\"},{\"$ref\":\"#/components/schemas/WhileloopFlow\"},{\"$ref\":\"#/components/schemas/BranchOne\"},{\"$ref\":\"#/components/schemas/BranchAll\"},{\"$ref\":\"#/components/schemas/Identity\"},{\"$ref\":\"#/components/schemas/AiAgent\"},{\"$ref\":\"#/components/schemas/AiDecision\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"rawscript\":\"#/components/schemas/RawScript\",\"script\":\"#/components/schemas/PathScript\",\"flow\":\"#/components/schemas/PathFlow\",\"forloopflow\":\"#/components/schemas/ForloopFlow\",\"whileloopflow\":\"#/components/schemas/WhileloopFlow\",\"branchone\":\"#/components/schemas/BranchOne\",\"branchall\":\"#/components/schemas/BranchAll\",\"identity\":\"#/components/schemas/Identity\",\"aiagent\":\"#/components/schemas/AiAgent\",\"aidecision\":\"#/components/schemas/AiDecision\"}}},\"RawScript\":{\"type\":\"object\",\"description\":\"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"content\":{\"type\":\"string\",\"description\":\"The script source code. Should export a 'main' function\"},\"language\":{\"type\":\"string\",\"description\":\"Programming language for this script\",\"enum\":[\"deno\",\"bun\",\"bunnative\",\"python3\",\"go\",\"bash\",\"powershell\",\"postgresql\",\"mysql\",\"bigquery\",\"snowflake\",\"mssql\",\"oracledb\",\"graphql\",\"nativets\",\"php\",\"rust\",\"ansible\",\"csharp\",\"nu\",\"java\",\"ruby\",\"rlang\",\"duckdb\"]},\"path\":{\"type\":\"string\",\"description\":\"Optional path for saving this script\"},\"lock\":{\"type\":\"string\",\"description\":\"Lock file content for dependencies\"},\"type\":{\"type\":\"string\",\"enum\":[\"rawscript\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing\"},\"concurrent_limit\":{\"type\":\"number\",\"description\":\"Maximum concurrent executions of this script\"},\"concurrency_time_window_s\":{\"type\":\"number\",\"description\":\"Time window for concurrent_limit\"},\"custom_concurrency_key\":{\"type\":\"string\",\"description\":\"Custom key for grouping concurrent executions\"},\"is_trigger\":{\"type\":\"boolean\",\"description\":\"If true, this script is a trigger that can start the flow\"},\"assets\":{\"type\":\"array\",\"description\":\"External resources this script accesses (S3 objects, resources, etc.)\",\"items\":{\"type\":\"object\",\"required\":[\"path\",\"kind\"],\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Path to the asset\"},\"kind\":{\"type\":\"string\",\"description\":\"Type of asset\",\"enum\":[\"s3object\",\"resource\",\"ducklake\",\"datatable\",\"volume\",\"dbt\"]},\"access_type\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Access level for this asset\",\"enum\":[\"r\",\"w\",\"rw\"]},\"alt_access_type\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Alternative access level\",\"enum\":[\"r\",\"w\",\"rw\"]}}}}},\"required\":[\"type\",\"content\",\"language\",\"input_transforms\"]},\"PathScript\":{\"type\":\"object\",\"description\":\"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"path\":{\"type\":\"string\",\"description\":\"Path to the script in the workspace (e.g., 'f/scripts/send_email')\"},\"hash\":{\"type\":\"string\",\"description\":\"Optional specific version hash of the script to use\"},\"type\":{\"type\":\"string\",\"enum\":[\"script\"]},\"tag_override\":{\"type\":\"string\",\"description\":\"Override the script's default worker group tag\"},\"is_trigger\":{\"type\":\"boolean\",\"description\":\"If true, this script is a trigger that can start the flow\"}},\"required\":[\"type\",\"path\",\"input_transforms\"]},\"PathFlow\":{\"type\":\"object\",\"description\":\"Reference to an existing flow by path. Use this to call another flow as a subflow\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"path\":{\"type\":\"string\",\"description\":\"Path to the flow in the workspace (e.g., 'f/flows/process_user')\"},\"type\":{\"type\":\"string\",\"enum\":[\"flow\"]}},\"required\":[\"type\",\"path\",\"input_transforms\"]},\"ForloopFlow\":{\"type\":\"object\",\"description\":\"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"iterator\":{\"description\":\"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'\",\"$ref\":\"#/components/schemas/InputTransform\"},\"skip_failures\":{\"type\":\"boolean\",\"description\":\"If true, iteration failures don't stop the loop. Failed iterations return null\"},\"type\":{\"type\":\"string\",\"enum\":[\"forloopflow\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency\"},\"parallelism\":{\"description\":\"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression\",\"$ref\":\"#/components/schemas/InputTransform\"},\"squash\":{\"type\":\"boolean\"}},\"required\":[\"modules\",\"iterator\",\"skip_failures\",\"type\"]},\"WhileloopFlow\":{\"type\":\"object\",\"description\":\"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute in each iteration\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"skip_failures\":{\"type\":\"boolean\",\"description\":\"If true, iteration failures don't stop the loop. Failed iterations return null\"},\"type\":{\"type\":\"string\",\"enum\":[\"whileloopflow\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, iterations run concurrently (use with caution in while loops)\"},\"parallelism\":{\"description\":\"Maximum number of concurrent iterations when parallel=true\",\"$ref\":\"#/components/schemas/InputTransform\"},\"squash\":{\"type\":\"boolean\"}},\"required\":[\"modules\",\"skip_failures\",\"type\"]},\"BranchOne\":{\"type\":\"object\",\"description\":\"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes\",\"properties\":{\"branches\":{\"type\":\"array\",\"description\":\"Array of branches to evaluate in order. The first branch with expr evaluating to true executes\",\"items\":{\"type\":\"object\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of this branch condition\"},\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins\"},\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute if this branch's expr is true\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}}},\"required\":[\"modules\",\"expr\"]}},\"default\":{\"type\":\"array\",\"description\":\"Steps to execute if no branch expressions match\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"type\":{\"type\":\"string\",\"enum\":[\"branchone\"]}},\"required\":[\"branches\",\"default\",\"type\"]},\"BranchAll\":{\"type\":\"object\",\"description\":\"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently\",\"properties\":{\"branches\":{\"type\":\"array\",\"description\":\"Array of branches that all execute (either in parallel or sequentially)\",\"items\":{\"type\":\"object\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of this branch's purpose\"},\"skip_failure\":{\"type\":\"boolean\",\"description\":\"If true, failure in this branch doesn't fail the entire flow\"},\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute in this branch\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}}},\"required\":[\"modules\"]}},\"type\":{\"type\":\"string\",\"enum\":[\"branchall\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, all branches execute concurrently. If false, they execute sequentially\"}},\"required\":[\"branches\",\"type\"]},\"AgentTool\":{\"type\":\"object\",\"description\":\"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')\"},\"summary\":{\"type\":\"string\",\"description\":\"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'.\"},\"description\":{\"type\":\"string\",\"description\":\"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script.\"},\"job_token_scopes\":{\"type\":\"array\",\"nullable\":true,\"items\":{\"type\":\"string\"},\"description\":\"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it.\"},\"value\":{\"$ref\":\"#/components/schemas/ToolValue\"}},\"required\":[\"id\",\"value\"]},\"ToolValue\":{\"description\":\"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference\",\"oneOf\":[{\"$ref\":\"#/components/schemas/FlowModuleTool\"},{\"$ref\":\"#/components/schemas/McpToolValue\"},{\"$ref\":\"#/components/schemas/WebsearchToolValue\"}],\"discriminator\":{\"propertyName\":\"tool_type\",\"mapping\":{\"flowmodule\":\"#/components/schemas/FlowModuleTool\",\"mcp\":\"#/components/schemas/McpToolValue\",\"websearch\":\"#/components/schemas/WebsearchToolValue\"}}},\"FlowModuleTool\":{\"description\":\"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module\",\"allOf\":[{\"type\":\"object\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"flowmodule\"]}},\"required\":[\"tool_type\"]},{\"$ref\":\"#/components/schemas/FlowModuleValue\"}]},\"WebsearchToolValue\":{\"type\":\"object\",\"description\":\"A tool implemented as a websearch tool. The AI can call this like any other websearch tool\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"websearch\"]}},\"required\":[\"tool_type\"]},\"McpToolValue\":{\"type\":\"object\",\"description\":\"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"mcp\"]},\"resource_path\":{\"type\":\"string\",\"description\":\"Path to the MCP resource/server configuration\"},\"include_tools\":{\"type\":\"array\",\"description\":\"Whitelist of specific tools to include from this MCP server\",\"items\":{\"type\":\"string\"}},\"exclude_tools\":{\"type\":\"array\",\"description\":\"Blacklist of tools to exclude from this MCP server\",\"items\":{\"type\":\"string\"}}},\"required\":[\"tool_type\",\"resource_path\"]},\"AiAgent\":{\"type\":\"object\",\"description\":\"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Input parameters for the AI agent mapped to their values\",\"properties\":{\"provider\":{\"$ref\":\"#/components/schemas/ProviderTransform\"},\"output_type\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n\"},\"user_message\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"The user's prompt/message to the AI agent. Supports variable interpolation with\\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\\nthe prompt; image output always needs it.\\n\"},\"system_prompt\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"System instructions that guide the AI's behavior, persona, and response style. Optional.\"},\"streaming\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n\"},\"memory\":{\"$ref\":\"#/components/schemas/MemoryTransform\"},\"memory_id\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Names the memory this step reads and writes, overriding the memory id the run\\nwas started with (the chat conversation, an app chat session or the `memory_id` run\\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\\nkey. When it evaluates to an empty value the agent runs without memory. Read only\\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\\nolder `auto` or `manual` memory reads neither history input.\\n\"},\"previous_messages\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\\nand the user message. Read only while `memory` is off or absent: managed memory\\nignores it, and an older `auto` or `manual` memory reads neither history input.\\n\"},\"output_schema\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n\"},\"user_attachments\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n\"},\"enabled_tools\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of strings naming which of the tools configured in `tools` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n\"},\"max_completion_tokens\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n\"},\"temperature\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n\"},\"max_iterations\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n\"},\"model\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Only on a step linked to a saved agent (see `agent`): replaces the model\\nsaved on the agent for this step's runs, on the agent's own provider resource. An\\nempty value keeps the saved model. Set it to an expression such as\\n`flow_input.model` to choose the model per run.\\n\"},\"reasoning_effort\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning\\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\\ndefault. Leave the input out to keep the saved effort, which holds only while the\\nstep runs the saved model. A step that is not linked sets both inside `provider`.\\n\"}}},\"tools\":{\"type\":\"array\",\"description\":\"Array of tools the agent can use. The agent decides which tools to call based on the task\",\"items\":{\"$ref\":\"#/components/schemas/AgentTool\"}},\"type\":{\"type\":\"string\",\"enum\":[\"aiagent\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)\"},\"omit_output_from_conversation\":{\"type\":\"boolean\",\"default\":false,\"description\":\"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.\"},\"agent\":{\"type\":\"string\",\"description\":\"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\\nand, optionally, the `model` and `reasoning_effort` overrides of what the agent saved.\\n\"},\"tool_inputs\":{\"type\":\"object\",\"description\":\"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n\",\"additionalProperties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}}},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, the agent can execute multiple tool calls in parallel\"}},\"required\":[\"type\",\"input_transforms\"]},\"AiDecision\":{\"type\":\"object\",\"description\":\"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\\nstate with calibrated probabilities, instead of generating text.\\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\\ncheap and its answers are structured. Its result is { output: { : answer },\\nmodel, usage }, so a later step reads e.g. results..output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults..output..choice. Usable as an AI agent tool, where the calling agent\\nsupplies the state.\\n\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Input parameters for the decision mapped to their values\",\"properties\":{\"provider\":{\"$ref\":\"#/components/schemas/ProviderTransform\"},\"state\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"What the questions are asked about: a string, an object or an array of strings.\\nAn object with descriptive keys holding only what the questions need works best.\\nExample: { message: flow_input.message, plan: results.a.plan }\\n\"},\"questions\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Object mapping each question name to { type, instructions, criteria }, where type is:\\n- 'choice': criteria maps each option to its description (up to 255); the answer\\n has choice, probabilities and confidence\\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\\n has score, legend, probabilities and confidence\\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\\n noul, the probability of yes (0 to 1)\\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\\n\"}},\"required\":[\"provider\",\"state\",\"questions\"]},\"type\":{\"type\":\"string\",\"enum\":[\"aidecision\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)\"}},\"required\":[\"type\",\"input_transforms\"]},\"Identity\":{\"type\":\"object\",\"description\":\"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"identity\"]},\"flow\":{\"type\":\"boolean\",\"description\":\"If true, marks this as a flow identity (special handling)\"}},\"required\":[\"type\"]},\"FlowStatus\":{\"type\":\"object\",\"properties\":{\"step\":{\"type\":\"integer\"},\"modules\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/FlowStatusModule\"}},\"user_states\":{\"additionalProperties\":true},\"preprocessor_module\":{\"allOf\":[{\"$ref\":\"#/components/schemas/FlowStatusModule\"}]},\"failure_module\":{\"allOf\":[{\"$ref\":\"#/components/schemas/FlowStatusModule\"},{\"type\":\"object\",\"properties\":{\"parent_module\":{\"type\":\"string\"}}}]},\"retry\":{\"type\":\"object\",\"properties\":{\"fail_count\":{\"type\":\"integer\"},\"failed_jobs\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}}}}},\"required\":[\"step\",\"modules\",\"failure_module\"]},\"FlowStatusModule\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"WaitingForPriorSteps\",\"WaitingForEvents\",\"WaitingForExecutor\",\"InProgress\",\"Success\",\"Failure\"]},\"id\":{\"type\":\"string\"},\"job\":{\"type\":\"string\",\"format\":\"uuid\"},\"count\":{\"type\":\"integer\"},\"progress\":{\"type\":\"integer\"},\"iterator\":{\"type\":\"object\",\"properties\":{\"index\":{\"type\":\"integer\"},\"itered\":{\"type\":\"array\",\"items\":{}},\"itered_len\":{\"type\":\"integer\"},\"args\":{}}},\"flow_jobs\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"flow_jobs_success\":{\"type\":\"array\",\"items\":{\"type\":\"boolean\"}},\"flow_jobs_duration\":{\"type\":\"object\",\"properties\":{\"started_at\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"duration_ms\":{\"type\":\"array\",\"items\":{\"type\":\"integer\"}}}},\"branch_chosen\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"branch\",\"default\"]},\"branch\":{\"type\":\"integer\"}},\"required\":[\"type\"]},\"branchall\":{\"type\":\"object\",\"properties\":{\"branch\":{\"type\":\"integer\"},\"len\":{\"type\":\"integer\"}},\"required\":[\"branch\",\"len\"]},\"approvers\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"resume_id\":{\"type\":\"integer\"},\"approver\":{\"type\":\"string\"}},\"required\":[\"resume_id\",\"approver\"]}},\"failed_retries\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}},\"skipped\":{\"type\":\"boolean\"},\"agent_actions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"oneOf\":[{\"type\":\"object\",\"properties\":{\"job_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"function_name\":{\"type\":\"string\"},\"type\":{\"type\":\"string\",\"enum\":[\"tool_call\"]},\"module_id\":{\"type\":\"string\"}},\"required\":[\"job_id\",\"function_name\",\"type\",\"module_id\"]},{\"type\":\"object\",\"properties\":{\"call_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"function_name\":{\"type\":\"string\"},\"resource_path\":{\"type\":\"string\"},\"type\":{\"type\":\"string\",\"enum\":[\"mcp_tool_call\"]},\"arguments\":{\"type\":\"object\"}},\"required\":[\"call_id\",\"function_name\",\"resource_path\",\"type\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"web_search\"]}},\"required\":[\"type\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"message\"]}},\"required\":[\"content\",\"type\"]}]}},\"agent_actions_success\":{\"type\":\"array\",\"items\":{\"type\":\"boolean\"}}},\"required\":[\"type\"]}}", + "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 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**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` and `memory_id`, the conversation id, which the chat fills in: 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 })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, 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 `memory_id` when the agent keeps managed memory or `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**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` and `memory_id`, the conversation id, which the chat fills in: 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 })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, 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 `memory_id` when the agent keeps managed memory or `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", + "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.) Write 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. 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\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM ducklake.main.orders GROUP BY 1\n```\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: [...] } }`, 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| `operator_settings` | What operators see and do: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). A write right the value omits keeps its stored value. |\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_access_enabled`, `guest_jwt_public_key`, `guest_jwt_jwks_url` | Guest access to public apps and the key that signs guest JWTs. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n" + } +} diff --git a/backend/windmill-api/src/mcp/session/gen/prompt.json b/backend/windmill-api/src/mcp/session/gen/prompt.json new file mode 100644 index 0000000000..b3ffea17b7 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/gen/prompt.json @@ -0,0 +1,14 @@ +{ + "base": "You are working in a Windmill workspace through its MCP server.\n\nThe user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a script, flow or agent draft's url (its editor), an app draft's preview_url (the app editor with its live preview, which these instructions call \"the preview\"), a deployed item's url. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves, open the link in a browser they can see from this conversation if you have one, and otherwise give them the link to open.\n\nThe current user's workspace username is \"{{username}}\".\n\nUse tools to inspect workspace items and create per-user drafts (saved server-side, visible only to this user — not deployed) for scripts, flows, schedules, triggers, resources, variables, and raw apps.\n\nRules:\n- Draft tools create or update drafts only; they do not deploy or mutate deployed workspace items.\n- Use list_workspace_items to find items and read_workspace_item before changing an existing item. For triggers, pass trigger_kind.\n- Use deploy_workspace_item only after the user explicitly asks to deploy. It persists a draft to the workspace.\n- Use get_instructions before writing scripts, flows, resources, or apps. For scripts, pass the target language.\n- After creating or editing a script or flow draft, run test_run_script, test_run_flow, or test_run_step with representative args before reporting that it works. These tools prefer drafts, so testing does not require deployment.\n- Default to test_run_script, test_run_flow, or test_run_step for any run request, an existing script included; they prefer drafts and need no deployment. Use run_script or run_flow only when the user names the deployed version (\"the deployed X\", \"in production\", \"for real\") — a bare \"run X\" is not that. For those two, read the item with read_workspace_item version: \"deployed\" first so the arguments match the deployed schema. test_run_script, test_run_flow, test_run_step, run_script and run_flow run with exactly the arguments you send, so fill in every argument the schema asks for. test_run_step takes the step's own inputs, not the flow's.\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; create one with `create_folder` only when the user explicitly asks for a new folder.\n{{folder_guidance}}\nMore rules:\n- Listings and reads return only what this user can see: items in folders they cannot read are hidden from you both. When an item the user names is missing, say it is not among what they can see and may be in a folder they cannot read, where someone with access can run it — never state that it does not exist or is not deployed.\n- An agent, as the Agents page lists it, is a resource of type `ai_agent`: read it with read_workspace_item type \"resource\". You may draft a change to an agent, but never deploy or rename one here: the user reviews and deploys it from the agent's page, `/agents/edit/<path>`, so point them there.\n- To undo something you created or changed in this chat, use discard_local_draft: everything you write is a draft until it is explicitly deployed, so \"delete it\" / \"never mind\" / \"remove that\" about your own work means discarding the draft (it also clears the matching open editor draft). Use delete_workspace_item only to remove an item that is already deployed in the workspace; it mutates the workspace and fails if nothing is deployed at that path.\n- Use diff to review changes — before deploying, or when the user asks what changed. It is read-only: without arguments it lists every draft in the workspace with its change status; with type+path it returns that item's unified diff (for multi-file apps, pass file to read one file's diff). In a fork, pass against=\"parent_workspace\" to compare the deployed fork with its parent workspace instead. Pass search to grep changed lines across all diffs.\n- You can never read a variable's value, secret or not, so never invent one: when editing an existing variable, omit value (and is_secret) from write_variable and pass only the fields you are actually changing. The user can reveal a value in the variable editor; you cannot, so never tell them a value is unreadable in general. \"$var:path/to/variable\" is how a resource value references a variable — it is never a variable's own value.\n- Use search_resource_types before write_resource, and get_trigger_schema before write_trigger: the trigger config fields differ per kind and are not listed in the write_trigger definition.\n- When script or raw app code needs an external npm package you are not fully familiar with, use search_npm_packages to find it and get its documentation and type definitions. Link the package documentation in your answer when you rely on it.\n- Hub scripts are prebuilt, vetted integrations for third-party services, hosted outside the workspace under `hub/<version>/<app>/<name>` paths. Check search_hub_scripts before hand-writing code against a third-party API, even when the user never mentions the hub; read a result with read_workspace_item type \"script\" and its hub path to get its code, language, and input schema. Use what you find in whichever way fits: reference the hub path directly from a flow module or app runnable when a script already does the job, copy it into a workspace draft and adapt it when it is close (note the source hub path in a comment at the top of the code), or take it as a worked example and write your own. A script that does not do what the user asked is still worth reading when it is the only example of that integration: pass its `integration` back to search_hub_scripts to list that integration's other scripts with their descriptions, or use the `suggested_integrations` a search hands back when it finds nothing.\n- Before writing your own code against an integration the hub covers, call get_hub_integration with its slug: it returns the resource type to take, its auth fields and the integration's most-used scripts, which beats inferring them from script bodies. Call it for the integration you are about to write against, whichever it is. A search marks an integration `documented` when the hub additionally holds provider knowledge checked against the live API — pagination, enums, error codes and gotchas — so read that closely where it appears rather than trusting your own memory of the API.\n- If you have a web search tool and the hub does not cover a third-party API, search for the vendor's own API documentation rather than writing its endpoints and auth from memory, and link the page you relied on. Reserve it for external APIs: search_docs answers questions about Windmill itself.\n- create_resource_type creates a resource type the workspace lacks. Show the user the schema you propose and create it once they agree.\n- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n- A \"data pipeline\" is NOT a flow: it is a DAG of independent scripts in one folder, wired by storage assets (DuckLake/data tables/S3) and triggers via top-of-file `pipeline` / `on <ref>` annotation comments written in each script's comment syntax (`--` for SQL, `#` for Python/Bash, `//` for TS — a `//` line in a SQL node is a syntax error). When the user asks for a data pipeline (or to ingest/transform/materialize data across steps), call get_instructions with subject \"pipeline\" and build annotated script drafts — do not build a flow. list_pipelines lists the existing ones by folder.\n- Do the same for a raw app: run test_run_app_runnable on each backend runnable you wrote or changed before saying the app works. A bundle that compiles proves nothing about whether the runnables run. An inline runnable executes the app's draft code; a path runnable executes the DEPLOYED script/flow it names, so a path runnable aimed at something you have not deployed fails here — that failure is the point: report it and offer to deploy that one target. The app itself does not need deploying to be tested.\n- Use list_runs to find recent runs (optionally filtered by path, creator, label, or status), then get_run with a returned id to see what that run was called with, what it returned and what it logged — without starting a new test run.\n- get_run also covers what a flow run did per step — statuses and results across the whole execution tree, subflow steps and loop iterations included — and works while the flow is still running. Pass step to read one step's result in full (capped at 12k chars).\n- Keep context targeted.\n\nDocumentation:\n- Use search_docs to look up how a Windmill feature works in the official documentation (a flag, concept, function, or \"does Windmill support X\") instead of guessing about product behavior. It returns matching doc snippets with their Source URL; call read_docs_page with a Source URL to read the full page (or a section, if it returns headings). Cite the Source URL when you rely on it.\n- Complete your response with precisions about how it works based on the documentation. Also drop a link to the relevant documentation if possible.\n- If the user asks about something that you are unsure about, say that you are not sure about the answer and suggest to ask the question to the windmill team.\n- If the first search returns nothing useful, retry with different or broader keywords before giving up.\n- If the documentation does not cover the user's question, say so clearly rather than inventing an answer, and suggest asking the Windmill team.\n\nFlows:\n- read_workspace_item returns compact flow JSON. Inline script bodies appear as \"inline_script.<moduleId>\".\n- Use read_flow_module_code and set_flow_module_code for inline script bodies.\n- Use patch_flow_json for structural flow edits and write_flow for full flow rewrites.\n\nRaw apps:\n- The app tools below only work on raw (code) apps. `rawApp` says which: false is a drag-and-drop app: you can list it and read its metadata, but not read its contents, edit it or deploy it. Check it before offering to change an app.\n- read_workspace_item returns app metadata only. Use read_app_file for file and inline runnable contents.\n- A draft app is reachable by nobody; deploying is what exposes its backend runnables. deploy_workspace_item says so when the deploy widens who may open the app: anonymous means anyone with the URL, without logging in; guest means anyone the instance's identity provider authenticates, member of this workspace or not. Relay that in plain words and carry on. This is disclosure, not a gate: do not stop and ask for permission, and do not refuse the deploy. You cannot change who may open an app from chat; it is set on the app's deploy settings.\n- Use write_app_file, patch_app_file, and delete_app_file for frontend files.\n- Use write_app_runnable and delete_app_runnable for backend runnables.\n- Use init_app for a new app, with framework react19 unless the user named one or points at an app to follow: do not ask about the framework, and write the summary and pick the path (path conventions above) yourself. When the app has to store data and the user did not say where, settle the data setup with the user BEFORE init_app or any SQL (get_instructions subject \"app\" lists the questions), then pass the outcome as init_app's data.\n- Use deploy_workspace_item after explicit user deploy intent; raw app deploy bundles JS/CSS before saving.\n\nData Tables:\n- Datatables are workspace-scoped managed PostgreSQL databases, shared across the workspace (not owned by any single app). They must be configured by the user in their workspace settings (Workspace settings → Data Tables); they cannot be created via SQL.\n- Use list_datatables to discover the available datatables and their tables. Reuse an existing table rather than creating a duplicate. If list_datatables reports none, this is a blocking prerequisite — tell the user to set up a datatable in their workspace settings and stop; do not assume a \"main\" datatable exists or call exec_datatable_sql.\n- Use get_datatable_table_schema only when you need a table's column names/types; list_datatables is enough for table-list or availability summaries.\n- Use exec_datatable_sql to explore data, run queries, mutate rows, or change schema (CREATE/ALTER/DROP). Creating a table is a normal CREATE TABLE statement — it appears in list_datatables afterward, with no registration step.\n- A datatable that list_datatables reports with `migrations_enabled` keeps its schema as versioned migrations: change its schema with create_datatable_migration, never exec_datatable_sql. list_datatable_migrations reads them, run_datatable_migrations applies what is pending, rollback_datatable_migration undoes one. A migration is applied for real, not drafted, so call get_instructions with subject \"datatable\" before your first one.\n- A datatable can be under roles; list_datatables then reports its `usable_roles` and `default_role`. When working on a raw app that pins a role (`data.roles` in its raw_app.yaml), pass that role to the datatable tools, and to wmill.datatable in its runnables, so you see and change only what the app itself can. For anything else about roles, grants or a `permission denied`, call get_instructions with subject \"datatable\".\n- When writing runnable code (inline app runnables, scripts, flow modules) that reads or writes datatable data at runtime, it accesses a datatable via wmill.datatable(). Default to TypeScript (bun) unless the user asked for another language. Call get_instructions with subject \"datatable\" and language \"bun\" for the TypeScript SQL SDK reference (or language \"python3\" for Python) — it returns only that language so you get just what you need.", + "folder_guidance": { + "admin": "- As a workspace admin you can write to any existing folder. Folders here include {{writable_folders}} (you can also write to others not listed; list_workspace_items with type \"folder\" lists them all). If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.\n", + "admin_no_folders": "- As a workspace admin you can write to any existing folder. If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.\n", + "member": "- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path. Use `create_folder` only when the user explicitly asks for a new folder.\n", + "member_no_folders": "- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, create one with `create_folder` (you become an owner); otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.\n", + "member_readonly": "- Folders you can write to in this workspace: {{writable_folders}}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use rather than inventing a path. Use `create_folder` only when the user explicitly asks for a new folder.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there.\n", + "member_no_folders_readonly": "- You have no shared folders you can write to in this workspace, so use `u/{{username}}/<name>`. If the user explicitly asks for a shared folder, create one with `create_folder` (you become an owner); otherwise ask before placing shared work rather than inventing an `f/<folder>/...` path.\n- You can see but NOT write to: {{readonly_folders}} — never create or deploy items there.\n" + }, + "skills_header": "\n\nSkills:\n- Skills are reusable instruction sets available in this workspace, each covering a specific kind of task. The available skills are listed below by resource path and description.\n- When a user's request matches a skill's description, call read_skill with its exact path to load the full instructions BEFORE acting, then follow them.\n", + "skill_line": "- {{skill_path}}: {{skill_description}}", + "workspace_instructions": "\n\nWORKSPACE INSTRUCTIONS (configured by a workspace admin, shared by everyone in this workspace — you cannot modify these):\n{{workspace_instructions}}" +} diff --git a/backend/windmill-api/src/mcp/session/gen/schemas.json b/backend/windmill-api/src/mcp/session/gen/schemas.json new file mode 100644 index 0000000000..f15242d1aa --- /dev/null +++ b/backend/windmill-api/src/mcp/session/gen/schemas.json @@ -0,0 +1,16 @@ +{ + "trigger": { + "http": "{\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when triggered\",\n \"type\": \"string\"\n },\n \"route_path\": {\n \"description\": \"The URL route path that will trigger this endpoint (e.g., 'api/myendpoint'). Must NOT start with a /.\",\n \"type\": \"string\"\n },\n \"workspaced_route\": {\n \"description\": \"If true, the route includes the workspace ID in the path\",\n \"type\": \"boolean\"\n },\n \"summary\": {\n \"anyOf\": [\n {\n \"description\": \"Short summary describing the purpose of this trigger\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"description\": {\n \"anyOf\": [\n {\n \"description\": \"Detailed description of what this trigger does\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"static_asset_config\": {\n \"anyOf\": [\n {\n \"description\": \"Configuration for serving static assets (s3 bucket, storage path, filename)\",\n \"type\": \"object\",\n \"properties\": {\n \"s3\": {\n \"description\": \"S3 bucket path for static assets\",\n \"type\": \"string\"\n },\n \"storage\": {\n \"description\": \"Storage path for static assets\",\n \"type\": \"string\"\n },\n \"filename\": {\n \"description\": \"Filename for the static asset\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"s3\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"http_method\": {\n \"description\": \"HTTP method (get, post, put, delete, patch) that triggers this endpoint\",\n \"type\": \"string\",\n \"enum\": [\n \"get\",\n \"post\",\n \"put\",\n \"delete\",\n \"patch\"\n ]\n },\n \"authentication_resource_path\": {\n \"anyOf\": [\n {\n \"description\": \"Path to the resource containing authentication configuration (for api_key, basic_http, custom_script, signature methods)\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"is_async\": {\n \"description\": \"Deprecated, use request_type instead\",\n \"type\": \"boolean\"\n },\n \"request_type\": {\n \"description\": \"How the request is handled - 'sync' waits for result, 'async' returns job ID immediately, 'sync_sse' streams results via Server-Sent Events\",\n \"type\": \"string\",\n \"enum\": [\n \"sync\",\n \"async\",\n \"sync_sse\"\n ]\n },\n \"authentication_method\": {\n \"description\": \"How requests are authenticated - 'none' (public), 'windmill' (Windmill token), 'api_key', 'basic_http', 'custom_script', 'signature'\",\n \"type\": \"string\",\n \"enum\": [\n \"none\",\n \"windmill\",\n \"api_key\",\n \"basic_http\",\n \"custom_script\",\n \"signature\"\n ]\n },\n \"is_static_website\": {\n \"description\": \"If true, serves static files from S3/storage instead of running a script\",\n \"type\": \"boolean\"\n },\n \"wrap_body\": {\n \"description\": \"If true, wraps the request body in a 'body' parameter\",\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"raw_string\": {\n \"description\": \"If true, passes the request body as a raw string instead of parsing as JSON\",\n \"type\": \"boolean\"\n },\n \"allowed_origins\": {\n \"anyOf\": [\n {\n \"description\": \"Origins allowed to call this route cross-origin, matched against the request's Origin header (ignoring case) and echoed back on a match. When set, the list governs both the preflight and the response, overriding any Access-Control-Allow-Origin the runnable returns via wm_headers. Use ['*'] to opt out of any restriction, including the http_route_default_allowed_origins instance setting. An empty list is not a configuration and resolves exactly as null does. When null, the instance setting applies, or Access-Control-Allow-Origin: * if it is unset. Ignored on a static website, which has no authentication of its own and so hands out public files: restricting which browsers may read them protects nothing while breaking cross-origin webfonts and fetches. A single-file static asset is not exempt, since it can carry an authentication_method.\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"path\",\n \"script_path\",\n \"route_path\",\n \"is_flow\",\n \"http_method\",\n \"authentication_method\",\n \"is_static_website\"\n ],\n \"additionalProperties\": false\n}", + "websocket": "{\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when a message is received\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"url\": {\n \"description\": \"The WebSocket URL to connect to (can be a static URL or computed by a runnable)\",\n \"type\": \"string\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"filters\": {\n \"description\": \"Filters to match incoming messages (only matching messages trigger the script). Each entry is either a leaf `{key, value}` (top-level field) or `{path, value}` (dotted path into nested objects), or a group `{any_of: [...]}` / `{all_of: [...]}` / `{none_of: [...]}` nesting more entries. Entries at the top level are combined with `filter_logic`.\",\n \"type\": \"array\",\n \"items\": {\n \"description\": \"Either a leaf filter, matching a field of the message (parsed as JSON) against a value by equality (or superset, when the value is an object or array) — addressed by `key` for a top-level field or `path` for a dotted path into nested objects — or a group nesting sub-filters under a boolean operator (`none_of` matches when none of its sub-filters do).\\n\",\n \"anyOf\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"key\": {\n \"type\": \"string\"\n },\n \"value\": {}\n },\n \"required\": [\n \"key\",\n \"value\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"description\": \"Dotted path into nested objects, e.g. `a.b.c`. Does not traverse arrays.\",\n \"type\": \"string\"\n },\n \"value\": {}\n },\n \"required\": [\n \"path\",\n \"value\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"any_of\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n }\n }\n },\n \"required\": [\n \"any_of\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"all_of\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n }\n }\n },\n \"required\": [\n \"all_of\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"none_of\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n }\n }\n },\n \"required\": [\n \"none_of\"\n ],\n \"additionalProperties\": false\n }\n ]\n }\n },\n \"filter_logic\": {\n \"default\": \"and\",\n \"description\": \"Logic to apply when evaluating the top-level filters. 'and' requires all of them to match, 'or' requires any of them to match. Nested `any_of`/`all_of`/`none_of` groups carry their own logic.\",\n \"type\": \"string\",\n \"enum\": [\n \"and\",\n \"or\"\n ]\n },\n \"initial_messages\": {\n \"anyOf\": [\n {\n \"description\": \"Messages to send immediately after connecting (can be raw strings or computed by runnables)\",\n \"type\": \"array\",\n \"items\": {\n \"anyOf\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"raw_message\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"raw_message\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"runnable_result\": {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\"\n },\n \"args\": {\n \"description\": \"The arguments to pass to the script or flow\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"is_flow\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"path\",\n \"args\",\n \"is_flow\"\n ],\n \"additionalProperties\": false\n }\n },\n \"required\": [\n \"runnable_result\"\n ],\n \"additionalProperties\": false\n }\n ]\n }\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"url_runnable_args\": {\n \"anyOf\": [\n {\n \"description\": \"Arguments to pass to the script/flow that computes the WebSocket URL\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"can_return_message\": {\n \"description\": \"If true, the script can return a message to send back through the WebSocket\",\n \"type\": \"boolean\"\n },\n \"can_return_error_result\": {\n \"description\": \"If true, error results are sent back through the WebSocket\",\n \"type\": \"boolean\"\n },\n \"heartbeat\": {\n \"anyOf\": [\n {\n \"description\": \"Optional periodic heartbeat message configuration\",\n \"type\": \"object\",\n \"properties\": {\n \"interval_secs\": {\n \"description\": \"Interval in seconds between heartbeat messages\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"message\": {\n \"description\": \"Message to send as heartbeat. Use {{state}} as a placeholder for a value extracted from incoming messages (see state_field).\",\n \"type\": \"string\"\n },\n \"state_field\": {\n \"description\": \"Optional. Top-level JSON field to extract from incoming messages. The extracted value replaces {{state}} in the heartbeat message.\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"interval_secs\",\n \"message\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"path\",\n \"script_path\",\n \"is_flow\",\n \"url\",\n \"filters\",\n \"can_return_message\",\n \"can_return_error_result\"\n ],\n \"additionalProperties\": false\n}", + "kafka": "{\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when a message is received\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"kafka_resource_path\": {\n \"description\": \"Path to the Kafka resource containing connection configuration\",\n \"type\": \"string\"\n },\n \"group_id\": {\n \"description\": \"Kafka consumer group ID for this trigger\",\n \"type\": \"string\"\n },\n \"topics\": {\n \"description\": \"Array of Kafka topic names to subscribe to\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"filters\": {\n \"description\": \"Filters to match incoming messages (only matching messages trigger the script). Each entry is either a leaf `{key, value}` (top-level field) or `{path, value}` (dotted path into nested objects), or a group `{any_of: [...]}` / `{all_of: [...]}` / `{none_of: [...]}` nesting more entries. Entries at the top level are combined with `filter_logic`.\",\n \"type\": \"array\",\n \"items\": {\n \"description\": \"Either a leaf filter, matching a field of the message (parsed as JSON) against a value by equality (or superset, when the value is an object or array) — addressed by `key` for a top-level field or `path` for a dotted path into nested objects — or a group nesting sub-filters under a boolean operator (`none_of` matches when none of its sub-filters do).\\n\",\n \"anyOf\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"key\": {\n \"type\": \"string\"\n },\n \"value\": {}\n },\n \"required\": [\n \"key\",\n \"value\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"description\": \"Dotted path into nested objects, e.g. `a.b.c`. Does not traverse arrays.\",\n \"type\": \"string\"\n },\n \"value\": {}\n },\n \"required\": [\n \"path\",\n \"value\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"any_of\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n }\n }\n },\n \"required\": [\n \"any_of\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"all_of\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n }\n }\n },\n \"required\": [\n \"all_of\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"none_of\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n }\n }\n },\n \"required\": [\n \"none_of\"\n ],\n \"additionalProperties\": false\n }\n ]\n }\n },\n \"filter_logic\": {\n \"default\": \"and\",\n \"description\": \"Logic to apply when evaluating the top-level filters. 'and' requires all of them to match, 'or' requires any of them to match. Nested `any_of`/`all_of`/`none_of` groups carry their own logic.\",\n \"type\": \"string\",\n \"enum\": [\n \"and\",\n \"or\"\n ]\n },\n \"auto_offset_reset\": {\n \"default\": \"latest\",\n \"description\": \"Initial offset behavior when consumer group has no committed offset.\",\n \"type\": \"string\",\n \"enum\": [\n \"latest\",\n \"earliest\"\n ]\n },\n \"auto_commit\": {\n \"default\": true,\n \"description\": \"When true (default), offsets are committed automatically after receiving each message. When false, you must manually commit offsets using the commit_offsets endpoint.\",\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"path\",\n \"script_path\",\n \"is_flow\",\n \"kafka_resource_path\",\n \"group_id\",\n \"topics\",\n \"filters\"\n ],\n \"additionalProperties\": false\n}", + "nats": "{\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when a message is received\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"nats_resource_path\": {\n \"description\": \"Path to the NATS resource containing connection configuration\",\n \"type\": \"string\"\n },\n \"use_jetstream\": {\n \"description\": \"If true, uses NATS JetStream for durable message delivery\",\n \"type\": \"boolean\"\n },\n \"stream_name\": {\n \"anyOf\": [\n {\n \"description\": \"JetStream stream name (required when use_jetstream is true)\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"consumer_name\": {\n \"anyOf\": [\n {\n \"description\": \"JetStream consumer name (required when use_jetstream is true)\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"subjects\": {\n \"description\": \"Array of NATS subjects to subscribe to\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"path\",\n \"script_path\",\n \"is_flow\",\n \"nats_resource_path\",\n \"use_jetstream\",\n \"subjects\"\n ],\n \"additionalProperties\": false\n}", + "postgres": "{\n \"type\": \"object\",\n \"properties\": {\n \"replication_slot_name\": {\n \"description\": \"Name of the PostgreSQL logical replication slot to use\",\n \"type\": \"string\"\n },\n \"publication_name\": {\n \"description\": \"Name of the PostgreSQL publication to subscribe to for change data capture\",\n \"type\": \"string\"\n },\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when database changes are detected\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"postgres_resource_path\": {\n \"description\": \"Path to the PostgreSQL resource containing connection configuration\",\n \"type\": \"string\"\n },\n \"publication\": {\n \"description\": \"Configuration for creating/managing the publication (tables, operations)\",\n \"type\": \"object\",\n \"properties\": {\n \"table_to_track\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"schema_name\": {\n \"type\": \"string\"\n },\n \"table_to_track\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"table_name\": {\n \"type\": \"string\"\n },\n \"columns_name\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"where_clause\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"table_name\"\n ],\n \"additionalProperties\": false\n }\n }\n },\n \"required\": [\n \"schema_name\",\n \"table_to_track\"\n ],\n \"additionalProperties\": false\n }\n },\n \"transaction_to_track\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"transaction_to_track\"\n ],\n \"additionalProperties\": false\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"path\",\n \"script_path\",\n \"is_flow\",\n \"postgres_resource_path\"\n ],\n \"additionalProperties\": false\n}", + "mqtt": "{\n \"type\": \"object\",\n \"properties\": {\n \"mqtt_resource_path\": {\n \"description\": \"Path to the MQTT resource containing broker connection configuration\",\n \"type\": \"string\"\n },\n \"subscribe_topics\": {\n \"description\": \"Array of MQTT topics to subscribe to, each with topic name and QoS level\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"qos\": {\n \"type\": \"string\",\n \"enum\": [\n \"qos0\",\n \"qos1\",\n \"qos2\"\n ]\n },\n \"topic\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"qos\",\n \"topic\"\n ],\n \"additionalProperties\": false\n }\n },\n \"client_id\": {\n \"anyOf\": [\n {\n \"description\": \"MQTT client ID for this connection\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"v3_config\": {\n \"anyOf\": [\n {\n \"description\": \"MQTT v3 specific configuration (clean_session)\",\n \"type\": \"object\",\n \"properties\": {\n \"clean_session\": {\n \"type\": \"boolean\"\n }\n },\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"v5_config\": {\n \"anyOf\": [\n {\n \"description\": \"MQTT v5 specific configuration (clean_start, topic_alias_maximum, session_expiry_interval)\",\n \"type\": \"object\",\n \"properties\": {\n \"clean_start\": {\n \"type\": \"boolean\"\n },\n \"topic_alias_maximum\": {\n \"type\": \"number\"\n },\n \"session_expiry_interval\": {\n \"type\": \"number\"\n }\n },\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"client_version\": {\n \"anyOf\": [\n {\n \"description\": \"MQTT protocol version ('v3' or 'v5')\",\n \"type\": \"string\",\n \"enum\": [\n \"v3\",\n \"v5\"\n ]\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when a message is received\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"mqtt_resource_path\",\n \"subscribe_topics\",\n \"path\",\n \"script_path\",\n \"is_flow\"\n ],\n \"additionalProperties\": false\n}", + "amqp": "{\n \"type\": \"object\",\n \"properties\": {\n \"amqp_resource_path\": {\n \"description\": \"Path to the AMQP resource containing broker connection configuration\",\n \"type\": \"string\"\n },\n \"queue_name\": {\n \"description\": \"Name of the queue to consume messages from\",\n \"type\": \"string\"\n },\n \"exchange\": {\n \"anyOf\": [\n {\n \"description\": \"Optional exchange binding for the consumed queue\",\n \"type\": \"object\",\n \"properties\": {\n \"exchange_name\": {\n \"description\": \"Name of the exchange to bind the consumed queue to\",\n \"type\": \"string\"\n },\n \"routing_keys\": {\n \"description\": \"Routing keys used to bind the queue to the exchange\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"exchange_name\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"options\": {\n \"anyOf\": [\n {\n \"description\": \"Optional consumer options (queue declaration, prefetch)\",\n \"type\": \"object\",\n \"properties\": {\n \"declare_queue\": {\n \"description\": \"Declare the queue (durable) before consuming; when false the queue is declared passively and must already exist\",\n \"type\": \"boolean\"\n },\n \"prefetch_count\": {\n \"description\": \"Maximum number of unacknowledged messages the broker delivers at once (1-65535)\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 65535\n }\n },\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when a message is received\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"amqp_resource_path\",\n \"queue_name\",\n \"path\",\n \"script_path\",\n \"is_flow\"\n ],\n \"additionalProperties\": false\n}", + "sqs": "{\n \"type\": \"object\",\n \"properties\": {\n \"queue_url\": {\n \"description\": \"The full URL of the AWS SQS queue to poll for messages\",\n \"type\": \"string\"\n },\n \"aws_auth_resource_type\": {\n \"description\": \"Authentication type - 'credentials' for access key/secret, 'oidc' for OpenID Connect\",\n \"type\": \"string\",\n \"enum\": [\n \"oidc\",\n \"credentials\"\n ]\n },\n \"aws_resource_path\": {\n \"description\": \"Path to the AWS resource containing credentials or OIDC configuration\",\n \"type\": \"string\"\n },\n \"message_attributes\": {\n \"anyOf\": [\n {\n \"description\": \"Array of SQS message attribute names to include with each message\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when a message is received\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script\",\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script to run when the triggered job fails. A bare path, without the script/ or flow/ prefix a schedule error handler takes; it cannot be a flow.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"queue_url\",\n \"aws_auth_resource_type\",\n \"aws_resource_path\",\n \"path\",\n \"script_path\",\n \"is_flow\"\n ],\n \"additionalProperties\": false\n}", + "gcp": "{\n \"description\": \"Data for creating or updating a Google Cloud Pub/Sub trigger.\",\n \"type\": \"object\",\n \"properties\": {\n \"gcp_resource_path\": {\n \"description\": \"Path to the GCP resource containing service account credentials for authentication. Omit to authenticate with the instance's application default credentials, which only workspace admins may select.\",\n \"type\": \"string\"\n },\n \"project_id\": {\n \"description\": \"GCP project the client operates in. Defaults to the project of the credentials. Topics and subscriptions given as fully qualified names are reached whatever it is.\",\n \"type\": \"string\"\n },\n \"subscription_mode\": {\n \"description\": \"The mode of subscription. 'existing' means using an existing GCP subscription, while 'create_update' involves creating or updating a new subscription.\",\n \"type\": \"string\",\n \"enum\": [\n \"existing\",\n \"create_update\"\n ]\n },\n \"topic_id\": {\n \"description\": \"Google Cloud Pub/Sub topic ID to subscribe to. Accepts a bare ID or a fully qualified name (projects/<project>/topics/<id>).\",\n \"type\": \"string\"\n },\n \"subscription_id\": {\n \"description\": \"Google Cloud Pub/Sub subscription ID. Accepts a bare ID or a fully qualified name (projects/<project>/subscriptions/<id>).\",\n \"type\": \"string\"\n },\n \"base_endpoint\": {\n \"description\": \"Base URL for push delivery endpoint.\",\n \"type\": \"string\"\n },\n \"delivery_type\": {\n \"description\": \"Delivery mode for messages. 'push' for HTTP push delivery where messages are sent to a webhook endpoint, 'pull' for polling where the trigger actively fetches messages.\",\n \"type\": \"string\",\n \"enum\": [\n \"push\",\n \"pull\"\n ]\n },\n \"delivery_config\": {\n \"anyOf\": [\n {\n \"description\": \"Configuration for push delivery mode.\",\n \"type\": \"object\",\n \"properties\": {\n \"audience\": {\n \"description\": \"The audience claim for OIDC tokens used in push authentication.\",\n \"type\": \"string\"\n },\n \"authenticate\": {\n \"description\": \"If true, push messages will include OIDC authentication tokens.\",\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"authenticate\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"description\": \"Path to the script or flow to execute when a message is received.\",\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"description\": \"True if script_path points to a flow, false if it points to a script.\",\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"auto_acknowledge_msg\": {\n \"description\": \"If true, automatically acknowledge messages after processing.\",\n \"type\": \"boolean\"\n },\n \"ack_deadline\": {\n \"description\": \"Time in seconds within which the message must be acknowledged. If not provided, defaults to the subscription's acknowledgment deadline (600 seconds).\",\n \"type\": \"integer\",\n \"minimum\": 10,\n \"maximum\": 600\n },\n \"error_handler_path\": {\n \"description\": \"Path to a script or flow to run when the triggered job fails.\",\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"Arguments to pass to the error handler.\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed executions.\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"subscription_mode\",\n \"topic_id\",\n \"path\",\n \"script_path\",\n \"is_flow\"\n ],\n \"additionalProperties\": false\n}", + "azure": "{\n \"description\": \"Data for creating or updating an Azure Event Grid trigger.\",\n \"type\": \"object\",\n \"properties\": {\n \"azure_resource_path\": {\n \"type\": \"string\"\n },\n \"azure_mode\": {\n \"description\": \"Azure Event Grid trigger mode.\",\n \"type\": \"string\",\n \"enum\": [\n \"basic_push\",\n \"namespace_push\",\n \"namespace_pull\"\n ]\n },\n \"scope_resource_id\": {\n \"type\": \"string\"\n },\n \"topic_name\": {\n \"anyOf\": [\n {\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"subscription_name\": {\n \"type\": \"string\"\n },\n \"base_endpoint\": {\n \"description\": \"Base URL for push delivery endpoints (push modes only).\",\n \"type\": \"string\"\n },\n \"event_type_filters\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"path\": {\n \"description\": \"The unique Windmill path for this trigger. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`. This is the trigger object path, not the HTTP route path.\",\n \"type\": \"string\"\n },\n \"script_path\": {\n \"type\": \"string\"\n },\n \"is_flow\": {\n \"type\": \"boolean\"\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"error_handler_path\": {\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"The arguments to pass to the script or flow\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed module executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"permissioned_as\": {\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"azure_resource_path\",\n \"azure_mode\",\n \"scope_resource_id\",\n \"subscription_name\",\n \"path\",\n \"script_path\",\n \"is_flow\"\n ],\n \"additionalProperties\": false\n}", + "email": "{\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\"\n },\n \"script_path\": {\n \"type\": \"string\"\n },\n \"local_part\": {\n \"type\": \"string\"\n },\n \"workspaced_local_part\": {\n \"type\": \"boolean\"\n },\n \"is_flow\": {\n \"type\": \"boolean\"\n },\n \"error_handler_path\": {\n \"type\": \"string\"\n },\n \"error_handler_args\": {\n \"description\": \"The arguments to pass to the script or flow\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n \"retry\": {\n \"description\": \"Retry configuration for failed module executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n \"mode\": {\n \"description\": \"job trigger mode\",\n \"type\": \"string\",\n \"enum\": [\n \"enabled\",\n \"disabled\",\n \"suspended\"\n ]\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this trigger runs as. Used during deployment to preserve the original trigger owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n },\n \"required\": [\n \"path\",\n \"script_path\",\n \"local_part\",\n \"is_flow\"\n ],\n \"additionalProperties\": false\n}" + }, + "schedule": "{\n \"type\": \"object\",\n \"properties\": {\n \"on_failure_times\": {\n \"anyOf\": [\n {\n \"description\": \"Number of consecutive failures before the on_failure handler is triggered (default 1)\",\n \"type\": \"number\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"on_failure_exact\": {\n \"anyOf\": [\n {\n \"description\": \"If true, trigger on_failure handler only on exactly N failures, not on every failure after N\",\n \"type\": \"boolean\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"on_failure_extra_args\": {\n \"anyOf\": [\n {\n \"description\": \"The arguments to pass to the script or flow\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"on_recovery_times\": {\n \"anyOf\": [\n {\n \"description\": \"Number of consecutive successes before the on_recovery handler is triggered (default 1)\",\n \"type\": \"number\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"on_recovery_extra_args\": {\n \"anyOf\": [\n {\n \"description\": \"The arguments to pass to the script or flow\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"on_success_extra_args\": {\n \"anyOf\": [\n {\n \"description\": \"The arguments to pass to the script or flow\",\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\"\n },\n \"additionalProperties\": {}\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"ws_error_handler_muted\": {\n \"description\": \"If true, the workspace-level error handler will not be triggered for this schedule's failures\",\n \"type\": \"boolean\"\n },\n \"retry\": {\n \"anyOf\": [\n {\n \"description\": \"Retry configuration for failed module executions\",\n \"type\": \"object\",\n \"properties\": {\n \"constant\": {\n \"description\": \"Retry with constant delay between attempts\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Seconds to wait between retries\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n }\n },\n \"additionalProperties\": false\n },\n \"exponential\": {\n \"description\": \"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n\",\n \"type\": \"object\",\n \"properties\": {\n \"attempts\": {\n \"description\": \"Number of retry attempts\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"multiplier\": {\n \"description\": \"Multiplier for exponential backoff\",\n \"type\": \"integer\",\n \"minimum\": -9007199254740991,\n \"maximum\": 9007199254740991\n },\n \"seconds\": {\n \"description\": \"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 9007199254740991\n },\n \"random_factor\": {\n \"description\": \"Random jitter percentage (0-100) to avoid thundering herd\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100\n }\n },\n \"additionalProperties\": false\n },\n \"retry_if\": {\n \"description\": \"Conditional retry based on error or result\",\n \"type\": \"object\",\n \"properties\": {\n \"expr\": {\n \"description\": \"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"expr\"\n ],\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"no_flow_overlap\": {\n \"description\": \"If true, skip this schedule's execution if the previous run is still in progress (prevents concurrent runs)\",\n \"type\": \"boolean\"\n },\n \"tag\": {\n \"anyOf\": [\n {\n \"description\": \"Worker tag to route jobs to specific worker groups\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"paused_until\": {\n \"anyOf\": [\n {\n \"description\": \"ISO 8601 datetime until which the schedule is paused. Schedule resumes automatically after this time\",\n \"type\": \"string\",\n \"format\": \"date-time\",\n \"pattern\": \"^(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))T(?:(?:[01]\\\\d|2[0-3]):[0-5]\\\\d(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?(?:Z|([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)))$\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"cron_version\": {\n \"anyOf\": [\n {\n \"description\": \"Cron parser version. Use 'v2' for extended syntax with additional features\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"dynamic_skip\": {\n \"anyOf\": [\n {\n \"description\": \"Path to a script that validates scheduled datetimes. Receives scheduled_for datetime and returns boolean to skip (true) or run (false)\",\n \"type\": \"string\"\n },\n {\n \"type\": \"null\"\n }\n ]\n },\n \"permissioned_as\": {\n \"description\": \"The user or group this schedule runs as. Used during deployment to preserve the original schedule owner.\",\n \"type\": \"string\"\n },\n \"preserve_permissioned_as\": {\n \"description\": \"When true and the caller is a member of the 'wm_deployers' group, preserves the original permissioned_as value instead of overwriting it.\",\n \"type\": \"boolean\"\n },\n \"labels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n }\n}" +} diff --git a/backend/windmill-api/src/mcp/session/gen/tools.json b/backend/windmill-api/src/mcp/session/gen/tools.json new file mode 100644 index 0000000000..da1d9cb32a --- /dev/null +++ b/backend/windmill-api/src/mcp/session/gen/tools.json @@ -0,0 +1,2557 @@ +[ + { + "name": "read_skill", + "description": "Load the full instructions for an AI skill by resource path. Skills are listed in the system prompt under \"Skills\"; call this before acting on a task a skill covers, then follow its instructions.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "The exact skill resource path as listed in the Skills section of the system prompt.", + "type": "string" + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "open_page", + "description": "Open a Windmill page with filters applied — Runs, Schedules, Variables, Resources, Assets, Audit logs, Folders, Groups, Triggers (by kind), Workspace settings (on a specific tab), or the Compare & Deploy page. Inside an AI session it opens as a tab in the side-panel preview next to the chat; elsewhere it offers a clickable link. Use after surfacing something the user likely wants to inspect (e.g. \"show me the failed runs of X\", \"open the schedule for Y\", \"open the git sync settings\", \"open the kafka triggers\"), and ALWAYS when asking the user to perform a manual step themselves (fill in a resource's credentials, set a variable's value — pass open with the item path so its editor opens directly). Never offer page \"compare\" for draft review. Use it only when the user explicitly asks to deploy a forked workspace into its parent; it always opens the fork-vs-parent comparison. This is the only way to show one of these pages in the session preview — open_preview only handles editable items (scripts, flows, raw apps, pipelines). Only pages listed for this user are available; do not offer others.", + "parameters": { + "type": "object", + "properties": { + "page": { + "description": "Which page to open", + "type": "string", + "enum": [ + "runs", + "schedules", + "variables", + "resources", + "assets", + "audit_logs", + "folders", + "groups", + "triggers", + "compare" + ] + }, + "path": { + "description": "Runs/Schedules/Variables/Resources/Assets: the script, flow or item path to filter by. On Runs, comma-separate to match several values, or prefix each with ! to exclude them instead (never mix included and excluded values in one filter).", + "type": "string" + }, + "status": { + "description": "Runs: filter by job execution status", + "type": "string", + "enum": [ + "running", + "success", + "failure", + "canceled", + "waiting", + "suspended" + ] + }, + "schedule_path": { + "description": "Runs: only runs triggered by this schedule path. Schedules: filter by this exact schedule path.", + "type": "string" + }, + "job_kinds": { + "description": "Runs: filter by job category (defaults to top-level runs)", + "type": "string", + "enum": [ + "all", + "runs", + "dependencies", + "previews", + "deploymentcallbacks" + ] + }, + "user": { + "description": "Runs: filter by the user who created the job. comma-separate to match several values, or prefix each with ! to exclude them instead (never mix included and excluded values in one filter). (e.g. 'admin' or '!admin')", + "type": "string" + }, + "folder": { + "description": "Runs: filter by the folder containing the script or flow — one folder name, without the 'f/' prefix and without ! or commas (use path for anything finer)", + "type": "string" + }, + "job_trigger_kind": { + "description": "Runs: filter by how the job was triggered — one of webhook, default_email, http, websocket, kafka, email, nats, mqtt, amqp, sqs, postgres, schedule, gcp, azure, google, github, asset, freshness, app. comma-separate to match several values, or prefix each with ! to exclude them instead (never mix included and excluded values in one filter). (e.g. '!schedule' to hide scheduled runs)", + "type": "string" + }, + "label": { + "description": "Runs: filter by a custom label attached to the job. Comma-separate to match several values; * matches any substring.", + "type": "string" + }, + "tag": { + "description": "Runs: filter by worker tag. Comma-separate to match several values; * matches any substring.", + "type": "string" + }, + "worker": { + "description": "Runs: filter by the worker instance that ran the job. Comma-separate to match several values; * matches any substring.", + "type": "string" + }, + "concurrency_key": { + "description": "Runs: filter by concurrency limit key, e.g. custom-key or a full script path. Cannot be combined with worker, search, or a waiting/suspended status — that view has no way to apply them.", + "type": "string" + }, + "arg": { + "description": "Runs: only runs whose arguments contain these key/value pairs, as a JSON object string, e.g. {\"customer_id\":\"42\"}", + "type": "string" + }, + "result": { + "description": "Runs: only runs whose result contains these key/value pairs, as a JSON object string, e.g. {\"status\":\"ko\"}", + "type": "string" + }, + "search": { + "description": "Runs: free-text search matched case-insensitively across several run fields at once. Prefer a specific filter when you know which one applies.", + "type": "string" + }, + "timeframe": { + "description": "Runs: relative time window to look at, ending now. Ignored when min_ts or max_ts is set.", + "type": "string", + "enum": [ + "Latest runs", + "Within 30 seconds", + "Within last minute", + "Within last 5 minutes", + "Within last 30 minutes", + "Within last 24 hours", + "Within last 7 days", + "Within last month" + ] + }, + "min_ts": { + "description": "Runs: only runs after this instant, as an ISO 8601 timestamp (e.g. 2026-08-01T09:00:00Z); a bare 2026-08-01 means local midnight. Use it with max_ts for an absolute window; prefer timeframe for a relative one.", + "type": "string" + }, + "max_ts": { + "description": "Runs: only runs before this instant, as an ISO 8601 timestamp. A bare 2026-08-01 means local midnight, so it excludes that day — pass the next day, or an explicit time, to include it.", + "type": "string" + }, + "resolved": { + "description": "Runs: filter failures by whether they have been marked as handled — 'unresolved' hides the ones already resolved", + "type": "string", + "enum": [ + "all", + "unresolved", + "resolved" + ] + }, + "show_skipped": { + "description": "Runs: include skipped flow steps (excluded by default)", + "type": "boolean" + }, + "show_future_jobs": { + "description": "Runs: include jobs scheduled for later (included by default — pass false to hide)", + "type": "boolean" + }, + "open": { + "description": "Schedules/Triggers/Variables/Resources: exact item path to open in its editor, e.g. f/foo/my_schedule — in a session, a preview tab of its own instead of the list page. Use it whenever the user should act on one specific item (e.g. fill in credentials) so they land directly in its editor.", + "type": "string" + }, + "summary": { + "description": "Schedules: search text matched against schedule summaries", + "type": "string" + }, + "trigger_kind": { + "description": "Triggers: which trigger kind page to open", + "type": "string", + "enum": [ + "http", + "websocket", + "postgres", + "mqtt", + "amqp", + "email" + ] + }, + "resource_type": { + "description": "Resources: filter by resource type, e.g. postgres", + "type": "string" + }, + "owner": { + "description": "Variables/Resources: filter by owner, e.g. u/alice or f/team", + "type": "string" + }, + "username": { + "description": "Audit logs: filter by the acting username", + "type": "string" + }, + "operation": { + "description": "Audit logs: filter by operation, e.g. jobs.run", + "type": "string" + }, + "resource": { + "description": "Audit logs: filter by the affected resource path", + "type": "string" + }, + "items": { + "description": "Compare: preselect exactly these fork changes, each as '<kind>:<path>' where kind is script, flow, raw_app, app, resource, variable, or a trigger kind like trigger_schedule / trigger_http (e.g. 'script:f/foo/bar'). Omit to use the page's default selection; pass items only when the user asked to deploy specific ones.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "new_tab": { + "description": "Open in a NEW preview tab instead of updating the tab already showing this page. Only set true when the user explicitly asks for a new or separate tab; by default changing filters reuses the existing tab.", + "type": "boolean" + } + }, + "required": [ + "page" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "get_instructions", + "description": "Get authoring guidance for scripts, flows, data pipelines, resources, apps, or data tables: their migrations and permissions, and the SQL SDK (wmill.datatable()) used inside runnables.", + "parameters": { + "type": "object", + "properties": { + "subject": { + "description": "What to get authoring instructions for: a workspace item type (script, flow, resource, app), \"pipeline\" for building a data pipeline (a DAG of annotated scripts wired by storage assets — NOT a flow), or \"datatable\" for how data tables work (schema changes and migrations, roles and permissions) plus the wmill.datatable() SQL SDK used inside runnables, or \"workspace_settings\" for the keys and rules of the workspace settings (admins only). Schedules, triggers, and variables don't need instructions — their tool schemas describe everything.", + "type": "string", + "enum": [ + "script", + "flow", + "resource", + "app", + "datatable", + "pipeline", + "workspace_settings" + ] + }, + "language": { + "description": "The target language. Required when subject is script. For subjects \"datatable\" and \"app\" it selects which SDK reference to return (e.g. \"bun\" for TypeScript, \"python3\" for Python) and defaults to TypeScript if omitted. Use the existing language when modifying, or the requested target language when creating. Other subjects ignore it.", + "type": "string", + "enum": [ + "python3", + "deno", + "go", + "bash", + "powershell", + "postgresql", + "mysql", + "bigquery", + "snowflake", + "mssql", + "oracledb", + "graphql", + "nativets", + "bun", + "php", + "rust", + "ansible", + "csharp", + "nu", + "java", + "ruby", + "rlang", + "duckdb", + "bunnative", + "dbt" + ] + } + }, + "required": [ + "subject" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "search_hub_scripts", + "description": "Search the Windmill Hub for prebuilt integration scripts, or list one integration's scripts with `integration`.", + "parameters": { + "type": "object", + "properties": { + "query": { + "description": "What you want the script to do, e.g. \"send email\", \"list stripe invoices\". Semantic search, so describe the intent. Omit when browsing with `integration` alone.", + "type": "string" + }, + "integration": { + "description": "Integration slug (e.g. \"stripe\") from a previous result's `integration` or `suggested_integrations`, or the vendor the user named. Alone, lists that integration's scripts with descriptions, including ones that do not match your task but show how the integration is used. With `query`, narrows the search to it; pass it whenever the user names the vendor, since ranking alone can surface another integration's scripts that merely mention it.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "get_hub_integration", + "description": "Read how one integration works before writing code against it: the resource type it takes, its auth fields, and its most-used scripts as examples. For an integration a search marked `documented` it also returns provider knowledge checked against the live API: pagination, enums, error codes and gotchas.", + "parameters": { + "type": "object", + "properties": { + "integration": { + "description": "Integration slug, e.g. \"stripe\". Take it from a search_hub_scripts result's `integration`, or guess the vendor name: a wrong guess comes back with the closest real slugs.", + "type": "string" + } + }, + "required": [ + "integration" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "search_npm_packages", + "description": "Search for npm packages and their documentation", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The query to search for" + } + }, + "required": [ + "query" + ] + }, + "read_only": true + }, + { + "name": "search_docs", + "description": "Full-text search across the entire Windmill documentation. Provide one or more keywords; returns the most relevant docs pages, each with its Source URL and short matching snippets. Use this FIRST to find relevant pages by their content (a flag, function, error message, config key or concept). If the snippets answer the question, answer directly; otherwise call read_docs_page with a returned Source URL to read the full page or a section.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Keywords to search for in the documentation body, e.g. \"chromium worker tag\" or \"retry exponential backoff\". Fewer, more distinctive words match better." + } + }, + "required": [ + "query" + ] + }, + "read_only": true + }, + { + "name": "read_docs_page", + "description": "Fetch the raw markdown of a single Windmill documentation page. Provide the `url` of a page found via search_docs (its Source URL). If the page is large, this returns its list of section headings instead of the full content; call again with the `section` argument set to one of those headings to read that section.", + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The docs page to read, as a Source URL returned by search_docs (e.g. https://www.windmill.dev/docs/core_concepts/jobs). A bare path (e.g. /docs/core_concepts/jobs) is also accepted." + }, + "section": { + "type": "string", + "description": "Optional. A heading title from the page outline to read just that section instead of the full page." + } + }, + "required": [ + "url" + ] + }, + "read_only": true + }, + { + "name": "askUserQuestion", + "description": "Ask the user a question with proposed answers and wait for their selected or custom answer before continuing.", + "parameters": { + "type": "object", + "properties": { + "question": { + "description": "The concise question to show to the user before continuing.", + "type": "string", + "minLength": 1 + }, + "choices": { + "description": "Two to ten proposed answer strings.", + "minItems": 2, + "maxItems": 10, + "type": "array", + "items": { + "description": "Proposed answer text shown to the user and returned as-is.", + "type": "string", + "minLength": 1 + } + }, + "multiSelect": { + "description": "When true, the user may select several answers; use only when the choices can genuinely co-apply (not mutually exclusive). Defaults to single-select.", + "type": "boolean" + } + }, + "required": [ + "question", + "choices" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "update_user_instructions", + "description": "Modify your own persistent personal instructions for the Global assistant. Use when the user asks you to remember a preference, always/never do something, or change/stop a behavior. Edits only the user-level instructions (the USER INSTRUCTIONS block, not workspace-level); changes persist in this browser and take effect on your next message.", + "parameters": { + "type": "object", + "properties": { + "operation": { + "description": "What to do with your personal Global instructions. 'append' adds a new instruction to the end (use for \"remember this\" / \"always do X\"). 'replace' performs an exact find-and-replace to edit or remove existing text (use for \"change X\" / \"stop doing Y\"); set new_string to \"\" to remove.", + "type": "string", + "enum": [ + "append", + "replace" + ] + }, + "text": { + "description": "Required when operation is 'append': the instruction to add. Ignored for 'replace'.", + "type": "string", + "minLength": 1 + }, + "old_string": { + "description": "Required when operation is 'replace': exact text to find in your current personal instructions. Ignored for 'append'.", + "type": "string", + "minLength": 1 + }, + "new_string": { + "description": "Required when operation is 'replace': replacement text. Use an empty string to delete the matched text. Ignored for 'append'.", + "type": "string" + }, + "replace_all": { + "description": "For operation 'replace': when true, replace every exact match; when false, old_string must match exactly once.", + "default": false, + "type": "boolean" + } + }, + "required": [ + "operation", + "replace_all" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "list_workspace_items", + "description": "List workspace items and drafts. Returns metadata only, up to limit items per item type per page (default 50); pass page to continue past a full page.", + "parameters": { + "type": "object", + "properties": { + "types": { + "description": "Optional item types to list. Defaults to scripts and flows. Pass schedule or trigger explicitly when needed (listing triggers spans 9 kinds and is heavier). \"folder\" lists folders with their owners and extraPerms; \"group\" lists groups with their extraPerms (read one for its members). path_prefix does not apply to these two.", + "type": "array", + "items": { + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app", + "folder", + "group" + ] + } + }, + "query": { + "description": "Optional case-insensitive path or summary search string.", + "type": "string" + }, + "path_prefix": { + "description": "Optional path prefix filter, such as f/ or u/user/.", + "type": "string" + }, + "limit": { + "description": "Maximum items per item type per page (for triggers, per trigger kind). Defaults to 50 and is capped at 100.", + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "page": { + "description": "Page number, starting at 1. Each item type pages independently: request the next page while any type still returns a full page. Drafts appear on page 1 only, capped at limit per type.", + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + }, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "list_pipelines", + "description": "List the data pipelines of the workspace: each folder holding at least one pipeline script, with its number of scripts. A pipeline is named by its folder, not by an item path.", + "parameters": { + "type": "object", + "properties": {}, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "read_workspace_item", + "description": "Read one workspace item or draft. Prefers your draft when one exists; pass version: \"deployed\" to read the deployed state instead. A deployed item carries extraPerms (a draft does not; pass version: \"deployed\" for it): who it is shared with beyond its owner, as u/<user> or g/<group> → true (write) or false (read-only). A folder returns its owners and extraPerms; a group returns its members and extraPerms (who may manage it). For a folder or group, path is its name. A g/<group> entry grants every member of that group (g/all is everyone), and workspace admins can read and write every folder and item whatever these lists say.", + "parameters": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app", + "folder", + "group" + ] + }, + "path": { + "description": "Workspace path of the item to read, or a hub/<version>/<app>/<name> path from search_hub_scripts to read a hub script. For a folder or group, its name.", + "type": "string" + }, + "trigger_kind": { + "description": "Required when type is trigger. Identifies which trigger service to call.", + "type": "string", + "enum": [ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email" + ] + }, + "version": { + "description": "Pass \"deployed\" to read the deployed workspace state even when a draft exists (e.g. to learn the deployed input schema before running the deployed version). Default reads your draft when one exists.", + "type": "string", + "enum": [ + "deployed" + ] + } + }, + "required": [ + "type", + "path" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "create_folder", + "description": "Create a new shared folder (addressable as f/<name>/) in the workspace. The current user is added as an owner.", + "parameters": { + "type": "object", + "properties": { + "name": { + "description": "Folder name — letters, digits, underscores or hyphens only. The folder becomes addressable as `f/<name>/<item>`.", + "type": "string" + }, + "summary": { + "description": "Optional human-readable description of the folder.", + "type": "string" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "write_script", + "description": "Create or overwrite a draft script.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the script, e.g. f/folder/name or u/user/name.", + "type": "string" + }, + "summary": { + "description": "Short human-readable summary.", + "type": "string" + }, + "language": { + "description": "Script language.", + "type": "string", + "enum": [ + "python3", + "deno", + "go", + "bash", + "powershell", + "postgresql", + "mysql", + "bigquery", + "snowflake", + "mssql", + "oracledb", + "graphql", + "nativets", + "bun", + "php", + "rust", + "ansible", + "csharp", + "nu", + "java", + "ruby", + "rlang", + "duckdb", + "bunnative", + "dbt" + ] + }, + "content": { + "description": "Full script source code.", + "type": "string" + }, + "override": { + "description": "Overwrite the server draft even if it changed externally since you last read it (resolve a save conflict, your version wins).", + "type": "boolean" + } + }, + "required": [ + "path", + "language", + "content" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "write_flow", + "description": "Create or overwrite a draft flow.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the flow, e.g. f/folder/name or u/user/name.", + "type": "string" + }, + "summary": { + "description": "Short human-readable summary.", + "type": "string" + }, + "description": { + "description": "Longer human-readable description of what the flow does. Top-level flow metadata, separate from the modules — not part of the compact value patched by patch_flow_json.", + "type": "string" + }, + "modules": { + "description": "JSON string containing the complete flow modules array.", + "type": "string" + }, + "schema": { + "description": "JSON string containing the flow input schema.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "preprocessor_module": { + "description": "JSON string containing the optional preprocessor module.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "failure_module": { + "description": "JSON string containing the optional failure module.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "groups": { + "description": "JSON string, array of semantic flow groups (call get_instructions subject:\"flow\" for the full field reference). color MUST be one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray — never hex codes. Pass null to clear groups.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "notes": { + "description": "JSON string, array of free-floating sticky notes (type must be \"free\"; call get_instructions subject:\"flow\" for the full field reference). color MUST be one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray — never hex codes. Pass null to clear notes.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "override": { + "description": "Overwrite the server draft even if it changed externally since you last read it (resolve a save conflict, your version wins).", + "type": "boolean" + } + }, + "required": [ + "path", + "modules" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "write_schedule", + "description": "Create or overwrite a draft schedule.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "The unique Windmill path for this schedule. Must be of the form `u/<user>/<path>` or `f/<folder>/<path>`.", + "type": "string" + }, + "schedule": { + "description": "Cron expression with 6 fields (seconds, minutes, hours, day of month, month, day of week). Example '0 0 12 * * *' for daily at noon", + "type": "string" + }, + "timezone": { + "description": "IANA timezone for the schedule (e.g., 'UTC', 'Europe/Paris', 'America/New_York')", + "type": "string" + }, + "script_path": { + "description": "Path to the script or flow to execute when triggered", + "type": "string" + }, + "is_flow": { + "description": "True if script_path points to a flow, false if it points to a script", + "type": "boolean" + }, + "args": { + "anyOf": [ + { + "description": "The arguments to pass to the script or flow", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + { + "type": "null" + } + ] + }, + "enabled": { + "description": "Whether the schedule is currently active and will trigger jobs", + "type": "boolean" + }, + "summary": { + "anyOf": [ + { + "description": "Short summary describing the purpose of this schedule", + "type": "string" + }, + { + "type": "null" + } + ] + }, + "description": { + "anyOf": [ + { + "description": "Detailed description of what this schedule does", + "type": "string" + }, + { + "type": "null" + } + ] + }, + "on_failure": { + "anyOf": [ + { + "description": "Path to a script or flow to run when the scheduled job fails", + "type": "string" + }, + { + "type": "null" + } + ] + }, + "on_recovery": { + "anyOf": [ + { + "description": "Path to a script or flow to run when the schedule recovers after failures", + "type": "string" + }, + { + "type": "null" + } + ] + }, + "on_success": { + "anyOf": [ + { + "description": "Path to a script or flow to run after each successful execution", + "type": "string" + }, + { + "type": "null" + } + ] + }, + "advanced": { + "description": "Less common schedule options (on_failure_times, on_failure_exact, on_failure_extra_args, on_recovery_times, on_recovery_extra_args, on_success_extra_args, ws_error_handler_muted, retry, no_flow_overlap, tag, paused_until, cron_version, dynamic_skip, permissioned_as, preserve_permissioned_as, labels). Call get_schedule_schema for their exact shape.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + "override": { + "description": "Overwrite the server draft even if it changed externally since you last read it (resolve a save conflict, your version wins).", + "type": "boolean" + } + }, + "required": [ + "path", + "schedule", + "timezone", + "script_path", + "is_flow", + "args" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "write_trigger", + "description": "Create or overwrite a draft trigger.", + "parameters": { + "type": "object", + "properties": { + "kind": { + "description": "Trigger kind. Determines which fields are valid in config.", + "type": "string", + "enum": [ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email" + ] + }, + "config": { + "description": "Full trigger configuration: path, script_path, is_flow plus the kind-specific fields. Call get_trigger_schema with the same kind first to get its exact fields.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + "override": { + "description": "Overwrite the server draft even if it changed externally since you last read it (resolve a save conflict, your version wins).", + "type": "boolean" + } + }, + "required": [ + "kind", + "config" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "get_trigger_schema", + "description": "Get the configuration schema for one trigger kind — its config fields differ per kind.", + "parameters": { + "type": "object", + "properties": { + "kind": { + "description": "Trigger kind whose configuration schema to return.", + "type": "string", + "enum": [ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email" + ] + } + }, + "required": [ + "kind" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "get_schedule_schema", + "description": "Get the shape of a schedule's `advanced` object: retry, pausing, tags, and error-handler tuning.", + "parameters": { + "type": "object", + "properties": {}, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "edit_script", + "description": "Find/replace exact text in a script and save a draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the script to edit.", + "type": "string" + }, + "old_string": { + "description": "Exact text to find in the script source.", + "type": "string", + "minLength": 1 + }, + "new_string": { + "description": "Replacement text.", + "type": "string" + }, + "replace_all": { + "description": "When true, replace every exact match. When false, old_string must match exactly once.", + "default": false, + "type": "boolean" + } + }, + "required": [ + "path", + "old_string", + "new_string", + "replace_all" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "patch_flow_json", + "description": "Find/replace exact text in compact flow JSON and save a draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the flow to edit.", + "type": "string" + }, + "old_string": { + "description": "Exact text to find in the flow value, serialized as compact JSON (no indent).", + "type": "string", + "minLength": 1 + }, + "new_string": { + "description": "Replacement JSON text.", + "type": "string" + }, + "replace_all": { + "description": "When true, replace every exact match. When false, old_string must match exactly once.", + "default": false, + "type": "boolean" + } + }, + "required": [ + "path", + "old_string", + "new_string", + "replace_all" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "test_run_script", + "description": "Execute a preview-style test run of a script by path, preferring draft content when it exists. It runs with exactly the `args` you send. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal is minted into a short-lived secret before the run, but stays in this call.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the script to test.", + "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) — you will be notified when it finishes. 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 detaches into the background jobs tray. 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": [ + "path" + ], + "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 is minted into a short-lived secret before the run, but stays in this call. A required file is the user's to attach, so call this even when you cannot supply one rather than asking in chat. Use only when the user names the deployed version (\"the deployed X\", \"in production\", \"for real\").", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the deployed script to run.", + "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) — you will be notified when it finishes. 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 detaches into the background jobs tray. 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": [ + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "test_run_flow", + "description": "Execute a preview-style test run of a flow by path, preferring draft content when it exists. It runs with exactly the `args` you send. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal is minted into a short-lived secret before the run, but stays in this call.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the flow to test.", + "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" + } + ] + }, + "memory_id": { + "description": "Chat-mode flows only. A UUID naming the conversation this turn belongs to, whose memory the agent steps read: reuse the same one across calls to test memory and follow-ups, and omit it for a one-off turn in a conversation of its own. Generate the UUID yourself so you can pass it again.", + "type": "string" + }, + "background": { + "description": "Run in the background without waiting. Set true for jobs you expect to be long (deploys, backfills, big queries) — you will be notified when it finishes. 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 detaches into the background jobs tray. 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": [ + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "run_flow", + "description": "Run a DEPLOYED flow 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 is minted into a short-lived secret before the run, but stays in this call. A required file is the user's to attach, so call this even when you cannot supply one rather than asking in chat. Use only when the user names the deployed version (\"the deployed X\", \"in production\", \"for real\").", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the deployed flow to run.", + "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) — you will be notified when it finishes. 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 detaches into the background jobs tray. 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": [ + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "test_run_step", + "description": "Execute a test run of one step in a flow by path, preferring draft flow/script content when it exists. `args` are the step's OWN inputs, not the flow's: a step is normally fed by its input transforms, so send what that step's code takes, not what the flow takes. An AI agent step takes the inputs a run supplies rather than code arguments, `user_message` above all; its form opens on the step's own configuration, so send only what this run should change. An AI decision step takes `state`, what its questions are asked about; its provider and questions are the step's own. It runs with exactly the `args` you send. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal is minted into a short-lived secret before the run, but stays in this call.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the flow containing the step to test.", + "type": "string" + }, + "stepId": { + "description": "The id of the step/module to test.", + "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) — you will be notified when it finishes. 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 detaches into the background jobs tray. 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": [ + "path", + "stepId" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "list_runs", + "description": "List recent runs (jobs), most recent first. Optionally filter by path, creator, label, or status. Returns compact metadata only — use get_run with a returned id to see what a run was called with, returned and logged.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Filter to runs of this exact script or flow path.", + "type": "string" + }, + "created_by": { + "description": "Filter by the username that started the run.", + "type": "string" + }, + "label": { + "description": "Filter by job label.", + "type": "string" + }, + "success": { + "description": "Only completed runs with this outcome (true = succeeded, false = failed).", + "type": "boolean" + }, + "running": { + "description": "Only currently running runs.", + "type": "boolean" + }, + "limit": { + "description": "Max number of runs to return, most recent first. Defaults to 30.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "list_workers", + "description": "List the workers connected to this Windmill instance (those that pinged in the last 5 minutes), with their worker group, custom tags, seconds since their last ping, and jobs executed. Pair with list_runs to diagnose a stuck queue: runs queued on a tag no listed worker picks up will never start. Three blind spots to report rather than reason past: an empty result states whether no worker is connected or whether workers may be hidden from you, so relay the one it gives instead of picking; a missing custom_tags can mean tags are hidden from you, not unset; and only the 100 most recently pinging workers are listed, so on a bigger instance a tag none of them carries may still be served.", + "parameters": { + "type": "object", + "properties": {}, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "get_run", + "description": "Inspect one run: its status, arguments, result and logs, plus — for a flow — the per-step execution tree with each step's status and truncated result (subflow steps, loop iterations, branches and retries included). Works on running jobs too. Pass step to fetch one step's result in full (up to 12k chars).", + "parameters": { + "type": "object", + "properties": { + "id": { + "description": "The UUID of the run (job) to inspect.", + "type": "string" + }, + "step": { + "description": "Step to drill into for its result (returned in full up to 12k chars), addressed by the step ids shown in the tree: \"b\" for a top-level step, \"b/c\" for a step inside a subflow, \"b[12]\" for iteration 12 of a loop or attempt 12 of a retried step (1-based), composable as \"b[12]/c\". Omit to get the run itself.", + "type": "string" + } + }, + "required": [ + "id" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "cancel_job", + "description": "Cancel a running or queued job by its id (e.g. a background test run you started that is no longer needed).", + "parameters": { + "type": "object", + "properties": { + "id": { + "description": "The UUID of the job to cancel.", + "type": "string" + } + }, + "required": [ + "id" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "deploy_workspace_item", + "description": "Deploy a draft to the workspace. Mutates the workspace.", + "parameters": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app" + ] + }, + "path": { + "description": "Workspace path of the draft to deploy.", + "type": "string" + }, + "trigger_kind": { + "description": "Required when type is trigger. Must match the draft trigger kind.", + "type": "string", + "enum": [ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email" + ] + }, + "deployment_message": { + "description": "Optional deployment message recorded with the change.", + "type": "string" + }, + "force": { + "description": "Deploy even if the draft was started from an older deployed version, overwriting the version deployed since. Defaults to false.", + "type": "boolean" + } + }, + "required": [ + "type", + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "rebase_draft", + "description": "Discard a stale script, flow, or app draft and return your changes as a diff to re-apply on the latest deployed version. Use when a deploy reports the draft was started from an older deployed version.", + "parameters": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app" + ] + }, + "path": { + "description": "Workspace path of the draft to rebase onto the latest deployed version.", + "type": "string" + } + }, + "required": [ + "type", + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "diff", + "description": "Diff workspace changes. Read-only. Default: drafts vs deployed versions (index without type/path, one item's unified diff with them; file=<name> for one file inside an app). against='parent_workspace': deployed fork vs its parent workspace. search=<text> greps changed lines across all diffs.", + "parameters": { + "type": "object", + "properties": { + "against": { + "description": "What to compare against. 'deployed' (default): the current draft vs the deployed version. 'parent_workspace': the deployed fork vs its parent workspace (only in a fork; local drafts are flagged but not part of that comparison).", + "type": "string", + "enum": [ + "deployed", + "parent_workspace" + ] + }, + "type": { + "description": "With path: the item to diff. Omit both type and path for the workspace index.", + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app" + ] + }, + "path": { + "description": "Workspace path of the item to diff (draft vs deployed). Omit for the index of every draft in the workspace.", + "type": "string" + }, + "trigger_kind": { + "description": "Required when type is trigger. Must match the draft trigger kind.", + "type": "string", + "enum": [ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email" + ] + }, + "file": { + "description": "Item mode, multi-file apps only: read one file's diff inside the app (e.g. \"src/App.tsx\"). Omit for the per-file summary plus config changes.", + "type": "string" + }, + "search": { + "description": "Search mode: literal substring (case-insensitive, not a regex) matched against added/removed diff lines across every diff in the comparison. Ignores type/path.", + "type": "string" + }, + "file_glob": { + "description": "Search mode: optional glob filter on item paths and app file paths (e.g. \"*.ts\" matches file names, \"f/dash/**\" matches full paths).", + "type": "string" + }, + "max_matches": { + "description": "Search mode: maximum matching diff lines returned (default 50, hard cap 200).", + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "types": { + "description": "Index mode: only list drafts of these item types.", + "type": "array", + "items": { + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app" + ] + } + }, + "path_prefix": { + "description": "Index mode: only list drafts under this path prefix, such as f/billing/.", + "type": "string" + }, + "offset": { + "description": "Item mode: skip this many patch lines (paginate a large diff).", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "limit": { + "description": "Index mode: max items to list (default 50, capped at 100). Item mode: max patch lines to return (default 500).", + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + }, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "delete_workspace_item", + "description": "Delete an item that is already deployed in the workspace. Mutates the workspace. FAILS if the path has no deployed item, so never call it to undo something you created in this chat — that is a draft; use discard_local_draft instead.", + "parameters": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app" + ] + }, + "path": { + "description": "Workspace path of the item to delete.", + "type": "string" + }, + "trigger_kind": { + "description": "Required when type is trigger. Identifies which trigger service to call.", + "type": "string", + "enum": [ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email" + ] + } + }, + "required": [ + "type", + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "discard_local_draft", + "description": "Discard a draft only — the tool to undo an item you created or edited in this chat and have not deployed. Does not mutate deployed workspace items, but clears the matching open editor draft if one is mounted.", + "parameters": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "script", + "flow", + "schedule", + "trigger", + "resource", + "variable", + "app" + ] + }, + "path": { + "description": "Workspace path of the draft to discard.", + "type": "string" + }, + "trigger_kind": { + "description": "Required when type is trigger. Must match the draft trigger kind.", + "type": "string", + "enum": [ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email" + ] + } + }, + "required": [ + "type", + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "write_resource", + "description": "Create or overwrite a draft resource.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "The path to the resource", + "type": "string" + }, + "value": {}, + "description": { + "description": "The description of the resource", + "type": "string" + }, + "resource_type": { + "description": "The resource_type associated with the resource", + "type": "string" + }, + "labels": { + "type": "array", + "items": { + "type": "string" + } + }, + "ws_specific": { + "type": "boolean" + }, + "preserve_on_behalf_of": { + "description": "ai_agent only. Keep the identity `value.on_behalf_of` names (`u/<username>`, `g/<group>`) rather than the caller's own. Honoured for admins and members of wm_deployers; otherwise every write of an agent sets it to the caller.", + "type": "boolean" + }, + "override": { + "description": "Overwrite the server draft even if it changed externally since you last read it (resolve a save conflict, your version wins).", + "type": "boolean" + } + }, + "required": [ + "path", + "value", + "resource_type" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "write_variable", + "description": "Create or edit a draft variable. Editing is a partial update: pass only the fields you are changing. You can never read the value of a variable, so to edit a secret variable you MUST omit value — any value you pass replaces the stored secret. FAILS if you pass a \"$var:\" self-reference as the value, or un-secret a variable without giving its new value.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "The path to the variable", + "type": "string" + }, + "value": { + "description": "The value of the variable. Omit it to leave the value alone — required only when creating a new variable, or when changing a secret variable into a non-secret one. Never invent or guess the value of an existing variable: you cannot read it, and a \"$var:...\" reference is NOT a valid value (a variable cannot reference itself). Omitting it keeps whatever the draft already holds, so a value you set earlier in this conversation stays set; discard_local_draft abandons it.", + "type": "string" + }, + "is_secret": { + "description": "Whether the variable is a secret. Omit it to keep the current secrecy — required only when creating a new variable. Never pass false for an existing secret variable unless the user explicitly asked to reveal it and you also pass its new value.", + "type": "boolean" + }, + "description": { + "description": "The description of the variable. Omit it to keep the current description.", + "type": "string" + }, + "account": { + "description": "Ignored. A variable is linked to an OAuth account only when `createAccount` creates both.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "is_oauth": { + "description": "Whether the variable is an OAuth variable", + "type": "boolean" + }, + "expires_at": { + "description": "When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry — see value_valid_until.\n", + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "value_valid_until": { + "description": "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it (1 day by default, set on the handler); never causes the variable to be deleted. Omit it to keep the current expiry, or pass null to clear one — for instance once the value has been rotated.", + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + { + "type": "null" + } + ] + }, + "labels": { + "type": "array", + "items": { + "type": "string" + } + }, + "ws_specific": { + "type": "boolean" + }, + "override": { + "description": "Overwrite the server draft even if it changed externally since you last read it (resolve a save conflict, your version wins).", + "type": "boolean" + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "search_resource_types", + "description": "Search workspace resource types and schemas.", + "parameters": { + "type": "object", + "properties": { + "query": { + "description": "Natural-language description of the integration or capability you need, e.g. \"stripe\", \"postgres database\", or \"send emails\". Matched semantically against resource type names and descriptions, so describe the intent rather than guessing the exact name.", + "type": "string" + }, + "limit": { + "description": "Max number of resource types to return. Defaults to 5.", + "type": "integer", + "minimum": 1, + "maximum": 20 + } + }, + "required": [ + "query" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "create_resource_type", + "description": "Create a resource type in the workspace. Mutates the workspace.", + "parameters": { + "type": "object", + "properties": { + "name": { + "description": "Type name with the c_ prefix of custom types, e.g. c_acme_billing (added when missing): 1 to 50 letters, digits, \"_\" or \"-\". Resources and resource-typed parameters refer to it by this name.", + "type": "string" + }, + "description": { + "description": "What a resource of this type connects to.", + "type": "string" + }, + "schema": { + "description": "JSON Schema of a resource value of this type: { \"type\": \"object\", \"properties\": {...}, \"required\": [...] }, with every connection field, secrets included (a resource fills those with \"$var:\" references).", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + } + }, + "required": [ + "name", + "description", + "schema" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "get_db_schema", + "description": "Fetch the schema (tables and columns) of a database resource by its path. Supports postgresql, mysql, ms_sql_server, snowflake and bigquery resources.", + "parameters": { + "type": "object", + "properties": { + "resourcePath": { + "type": "string", + "description": "The path of the database resource" + } + }, + "required": [ + "resourcePath" + ] + }, + "read_only": true + }, + { + "name": "read_flow_module_code", + "description": "Read inline script code from one flow module.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the flow.", + "type": "string" + }, + "module_id": { + "description": "Module id whose inline rawscript content to read. Must reference a module whose value.type is \"rawscript\".", + "type": "string" + } + }, + "required": [ + "path", + "module_id" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "set_flow_module_code", + "description": "Overwrite inline script code in one flow module and save a draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the flow.", + "type": "string" + }, + "module_id": { + "description": "Module id whose inline rawscript content to overwrite. Must reference a module whose value.type is \"rawscript\". Use patch_flow_json for structural changes.", + "type": "string" + }, + "code": { + "description": "New script source. Replaces the module's value.content entirely.", + "type": "string" + } + }, + "required": [ + "path", + "module_id", + "code" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "init_app", + "description": "Initialize a draft raw app from a framework template.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path for the new app, e.g. f/folder/my_app or u/username/my_app. Errors if an app already exists at this path or a draft is already in flight.", + "type": "string" + }, + "summary": { + "description": "Short human-readable summary of the app.", + "type": "string" + }, + "framework": { + "description": "Frontend framework template: the one the user named or an app they point at uses, otherwise react19. Do not ask.", + "type": "string", + "enum": [ + "react19", + "react18", + "svelte5" + ] + }, + "data": { + "description": "Data setup of an app that stores data, as the user gave or chose it. Omit for an app that stores nothing.", + "type": "object", + "properties": { + "datatable": { + "description": "Data table the app stores its data in.", + "type": "string" + }, + "schema": { + "description": "Schema the app's new tables go in. Omit for public.", + "type": "string" + }, + "tables": { + "description": "Tables the app queries, reused or about to be created, each as `<datatable>/<table>` (public) or `<datatable>/<schema>:<table>`.", + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "datatable" + ], + "additionalProperties": false + } + }, + "required": [ + "path", + "framework" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "read_app_file", + "description": "Read one raw app frontend file or inline backend runnable. Large files are truncated to a head slice; pass offset/limit to page through the rest.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app, e.g. f/folder/name.", + "type": "string" + }, + "file_path": { + "description": "Frontend file path like /index.tsx, or backend inline runnable path like backend/<key>/main.ts (or main.py).", + "type": "string" + }, + "offset": { + "description": "1-based line number to start reading from. Use to page through a large file.", + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "limit": { + "description": "Maximum number of lines to return. Large files are truncated by default; pass offset/limit to read a specific line range.", + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + }, + "required": [ + "path", + "file_path" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "search_app", + "description": "Grep across all of a raw app's frontend files and inline backend runnables in one call. Returns matching file:line rows (capped), not file bodies — use it to locate a symbol or string before read_app_file instead of reading whole files one by one.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app, e.g. f/folder/name.", + "type": "string" + }, + "query": { + "description": "Literal substring to find across all app files (case-insensitive) — not a regex, so spaces and operators match verbatim. Returns matching file:line rows, not file bodies. To find call sites and skip similarly-named helpers, include the call paren (e.g. \"formatCurrency(\" matches calls but not \"formatCurrencyPrecise\"). Then read_app_file to inspect the ranges.", + "type": "string" + }, + "file_glob": { + "description": "Optional path filter. A pattern without \"/\" matches the file name anywhere (e.g. \"*.tsx\"); a pattern with \"/\" matches the full path (e.g. \"/components/*\", \"backend/**\"). Supports * (any chars except /), ** (any chars), and ?.", + "type": "string" + }, + "max_matches": { + "description": "Maximum number of matching lines to return (default 100, hard cap 200); each is shown with a few lines of surrounding context, so the output has more rows than this.", + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + }, + "required": [ + "path", + "query" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "write_app_file", + "description": "Create or overwrite a frontend file in a local app draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app.", + "type": "string" + }, + "file_path": { + "description": "Frontend file path (must start with /). Use write_app_runnable to set inline backend script content.", + "type": "string" + }, + "content": { + "description": "Full file content.", + "type": "string" + } + }, + "required": [ + "path", + "file_path", + "content" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "delete_app_file", + "description": "Remove a frontend file from a local app draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app.", + "type": "string" + }, + "file_path": { + "description": "Frontend file path to remove from the draft. Use delete_app_runnable for backend runnables.", + "type": "string" + } + }, + "required": [ + "path", + "file_path" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "patch_app_file", + "description": "Find/replace exact text in a raw app file and save a draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app.", + "type": "string" + }, + "file_path": { + "description": "Frontend file path like /index.tsx, or backend inline runnable path like backend/<key>/main.ts.", + "type": "string" + }, + "old_string": { + "description": "Exact text to find.", + "type": "string", + "minLength": 1 + }, + "new_string": { + "description": "Replacement text.", + "type": "string" + }, + "replace_all": { + "description": "When true, replace every exact match. When false, old_string must match exactly once.", + "default": false, + "type": "boolean" + } + }, + "required": [ + "path", + "file_path", + "old_string", + "new_string", + "replace_all" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "write_app_runnable", + "description": "Create or overwrite a backend runnable in a local app draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app.", + "type": "string" + }, + "key": { + "description": "Unique key for the backend runnable (called from frontend as backend.<key>()). Becomes the file id at backend/<key>/main.{ts|py}.", + "type": "string" + }, + "runnable": { + "description": "Backend runnable shape: same as in app mode. Inline runnables carry their script content; path runnables reference an existing workspace/hub item.", + "type": "object", + "properties": { + "name": { + "description": "Short summary/description of what the runnable does.", + "type": "string" + }, + "type": { + "description": "Runnable kind: \"inline\" for custom code stored on the app; \"script\"/\"flow\" for a workspace runnable; \"hubscript\" for a hub script; \"agent\" for a saved AI agent, run as one chat turn.", + "type": "string", + "enum": [ + "inline", + "script", + "flow", + "hubscript", + "agent" + ] + }, + "staticInputs": { + "description": "Static inputs that are not overridable by the frontend caller. Useful for workspace/hub scripts to pre-fill arguments.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + "inlineScript": { + "description": "Required when type is \"inline\".", + "type": "object", + "properties": { + "language": { + "description": "Inline script language.", + "type": "string", + "enum": [ + "bun", + "python3" + ] + }, + "content": { + "description": "Inline script source. Must export a main function.", + "type": "string" + } + }, + "required": [ + "language", + "content" + ], + "additionalProperties": false + }, + "path": { + "description": "Required when type is \"script\", \"flow\", \"hubscript\" or \"agent\". Workspace path of the runnable.", + "type": "string" + }, + "viewerDataAccess": { + "description": "Inline only. When true, the runnable reads data as the person viewing the app instead of as the app's identity: data table connections that name no role hold the viewer's roles, and object storage permission rules are checked against the viewer, so row-level security and per-user storage paths answer per viewer. Resources and variables stay the app's. Anonymous viewers are refused. Omit to keep the current setting.", + "type": "boolean" + } + }, + "required": [ + "name", + "type" + ], + "additionalProperties": false + } + }, + "required": [ + "path", + "key", + "runnable" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "delete_app_runnable", + "description": "Remove a backend runnable from a local app draft.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app.", + "type": "string" + }, + "key": { + "description": "Key of the backend runnable to remove.", + "type": "string" + } + }, + "required": [ + "path", + "key" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "test_run_app_runnable", + "description": "Run one of an app's backend runnables with test arguments, the way the editor preview runs it. An inline runnable executes the draft code; a path runnable executes the deployed script/flow it points at. A deployed app runs under its stored policy instead, so this does not prove the runnable is reachable once deployed.", + "parameters": { + "type": "object", + "properties": { + "path": { + "description": "Workspace path of the app.", + "type": "string" + }, + "key": { + "description": "Key of the backend runnable to run.", + "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) — you will be notified when it finishes. 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 detaches into the background jobs tray. 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": [ + "path", + "key" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "list_datatables", + "description": "List datatables configured in the workspace with schema and table names only. Does not include column definitions. Use this directly for table-list or available-tables summaries. Only call get_datatable_table_schema when column names/types are required.", + "parameters": { + "type": "object", + "properties": { + "datatable_name": { + "description": "List only this datatable. Required with `role`.", + "type": "string" + }, + "role": { + "description": "The datatable role to connect as, when the code you are working on uses one (an app's `data.roles` entry, or the `role` it passes to wmill.datatable). Omit for the datatable's default role.", + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,63}$" + } + }, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "get_datatable_table_schema", + "description": "Get column definitions for one datatable table. Do not call this for row counts or table-list summaries; list_datatables is enough for those.", + "parameters": { + "type": "object", + "properties": { + "datatable_name": { + "description": "The datatable name to inspect, e.g. \"main\".", + "type": "string" + }, + "schema_name": { + "description": "The schema name, e.g. \"public\".", + "type": "string" + }, + "table_name": { + "description": "The table name to inspect.", + "type": "string" + }, + "role": { + "description": "The datatable role to connect as, when the code you are working on uses one (an app's `data.roles` entry, or the `role` it passes to wmill.datatable). Omit for the datatable's default role.", + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,63}$" + } + }, + "required": [ + "datatable_name", + "schema_name", + "table_name" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "exec_datatable_sql", + "description": "Execute a SQL query on a workspace datatable. Use this to explore data, test queries, create/alter tables, or make changes. Creating a table is a normal CREATE TABLE statement — no registration step is needed.", + "parameters": { + "type": "object", + "properties": { + "datatable_name": { + "description": "The name of the datatable to query (e.g., \"main\"). Must be one of the datatables configured in the workspace.", + "type": "string" + }, + "sql": { + "description": "The SQL query to execute. Supports SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, ALTER TABLE, DROP TABLE, etc. For SELECT queries, results are returned as an array of objects. A newly created table will appear in list_datatables automatically.", + "type": "string" + }, + "role": { + "description": "The datatable role to connect as, when the code you are working on uses one (an app's `data.roles` entry, or the `role` it passes to wmill.datatable). Omit for the datatable's default role.", + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,63}$" + }, + "background": { + "description": "Run in the background without waiting. Set true for queries you expect to be slow (large scans, heavy migrations) — you will be notified when it finishes. Leave unset for normal queries, which wait briefly and only background automatically if slow.", + "type": "boolean" + }, + "wait_seconds": { + "description": "How many seconds to wait for the query in-turn before it detaches into the background jobs tray. Defaults to 15. Raise it (capped at 120) for a query you expect to finish in ~30–60s and want the result in this same turn. Ignored when background is true.", + "type": "number" + } + }, + "required": [ + "datatable_name", + "sql" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "list_datatable_migrations", + "description": "List a datatable's migrations in order, each with its version, name and whether it is applied or pending. Pass `version` to read one migration's SQL.", + "parameters": { + "type": "object", + "properties": { + "datatable_name": { + "description": "The datatable the migrations belong to, e.g. \"main\".", + "type": "string" + }, + "version": { + "description": "Return the SQL of this one migration instead of the list.", + "type": "number" + } + }, + "required": [ + "datatable_name" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "create_datatable_migration", + "description": "Change the schema of a datatable that has migrations enabled: saves the change as a new migration and applies it. One that fails to apply stays saved as pending: call this again with its `version` to fix it.", + "parameters": { + "type": "object", + "properties": { + "datatable_name": { + "description": "The datatable the migrations belong to, e.g. \"main\".", + "type": "string" + }, + "name": { + "description": "Short name of the change, e.g. \"add_refunds_table\". Letters, digits, \"_\" and \"-\" only.", + "type": "string", + "pattern": "^[A-Za-z0-9_-]+$" + }, + "code_up": { + "description": "The SQL that makes the change. Wrap the statements in `BEGIN; ... END;` so they apply atomically, unless one of them cannot run in a transaction.", + "type": "string" + }, + "code_down": { + "description": "The SQL that undoes `code_up`. Without it the migration cannot be rolled back, so provide it whenever the change is reversible.", + "type": "string" + }, + "role": { + "description": "The datatable role the migration runs as, on a datatable that has roles. Omit to run as admin, which only the datatable admins may do.", + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,63}$" + }, + "schemas": { + "description": "Every schema the migration changes or depends on (including schemas of referenced tables, types and functions), with every name in `code_up` schema-qualified. A migration then waits only on earlier migrations touching those schemas. Omit only for a change that spans the whole database (an extension, a grant across schemas): every later migration then waits for it.", + "type": "array", + "items": { + "type": "string", + "pattern": "^[A-Za-z0-9_$-]{1,63}$" + } + }, + "version": { + "description": "Rewrite this migration instead of adding one: only for a pending migration, typically the one that just failed to apply.", + "type": "number" + }, + "apply": { + "description": "Set false to save the migration as pending without running it. Defaults to true.", + "type": "boolean" + } + }, + "required": [ + "datatable_name", + "name", + "code_up" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "run_datatable_migrations", + "description": "Apply a datatable's pending migrations, oldest first. It stops at the first one that fails.", + "parameters": { + "type": "object", + "properties": { + "datatable_name": { + "description": "The datatable the migrations belong to, e.g. \"main\".", + "type": "string" + } + }, + "required": [ + "datatable_name" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "rollback_datatable_migration", + "description": "Undo one applied migration of a datatable by running its down SQL. The migration stays in the list as pending.", + "parameters": { + "type": "object", + "properties": { + "datatable_name": { + "description": "The datatable the migrations belong to, e.g. \"main\".", + "type": "string" + }, + "version": { + "description": "The applied migration to undo, normally the most recent one, as listed.", + "type": "number" + } + }, + "required": [ + "datatable_name", + "version" + ], + "additionalProperties": false + }, + "read_only": false + }, + { + "name": "list_data_metrics", + "description": "List the measures and dimensions declared on DuckLake tables (from `// measure` / `// dimension` annotations in deployed scripts). Call this before writing any aggregate query over a DuckLake table: a declared measure is the canonical definition of that number, and reproducing it yourself silently disagrees with it (a `revenue` measure typically excludes refunds or test rows). Use each returned `expr` verbatim, and when a measure has a `filter` write it as `expr FILTER (WHERE filter)` so measures with different predicates share one GROUP BY. Only declarations whose producing script you can read are returned, so what comes back is never proof of what exists: if the number you need is not here you may still write your own aggregate, but say that you found no declared measure for it rather than implying none exists.", + "parameters": { + "type": "object", + "properties": { + "table": { + "description": "Only declarations on this DuckLake table, as `<lake>/<table>` or `<lake>/<schema>.<table>`, with or without the `ducklake://` scheme. A name with no lake matches nothing and comes back empty.", + "type": "string" + }, + "path_prefix": { + "description": "Only declarations made by scripts under this path, e.g. `f/analytics`.", + "type": "string" + }, + "limit": { + "description": "Max number of declarations to return. Defaults to 200.", + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + }, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "list_ducklakes", + "description": "List the DuckLake catalogs configured in this workspace, by name. Call this before building or deploying a data pipeline that materializes DuckLake tables or reads/writes S3 assets: if it returns none, the workspace has no object storage + DuckLake configured and the pipeline cannot run until a workspace admin sets it up. Returns names only.", + "parameters": { + "type": "object", + "properties": {}, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "search_files", + "description": "Search the user-attached files with a regular expression and return matching lines with their line numbers. Use this to locate content before reading a specific window with read_file.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "description": "JavaScript regular expression to search for.", + "type": "string" + }, + "file": { + "description": "Optional file to restrict the search to: its file id when one is listed, otherwise its exact filename. Omit to search across all attached files.", + "type": "string" + }, + "ignore_case": { + "description": "Case-insensitive matching. Defaults to false.", + "type": "boolean" + } + }, + "required": [ + "pattern" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "read_file", + "description": "Read a bounded window of lines from a user-attached file. Returns each line prefixed with its 1-based number (`<n>→<content>`) plus a pagination note. Files are not in context, so use this to inspect their contents.", + "parameters": { + "type": "object", + "properties": { + "file": { + "description": "File to read: its file id when one is listed, otherwise its exact filename.", + "type": "string" + }, + "start_line": { + "description": "1-based first line to read. Defaults to 1.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "end_line": { + "description": "1-based last line to read. The window is capped at 200 lines.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "file" + ], + "additionalProperties": false + }, + "read_only": true + }, + { + "name": "get_workspace_settings", + "description": "Read the workspace settings as YAML, in the layout of the settings.yaml file the CLI syncs. Secrets read as `__SENSITIVE_AND_UNCHANGED__`.", + "parameters": { + "type": "object", + "properties": { + "keys": { + "description": "Only these top-level keys. Omit for the whole document.", + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false, + "required": [] + }, + "read_only": true + }, + { + "name": "set_workspace_settings", + "description": "Change workspace settings. Keys the yaml omits are left as they are. Read get_instructions subject \"workspace_settings\" before your first change.", + "parameters": { + "type": "object", + "properties": { + "yaml": { + "description": "A YAML mapping of only the top-level keys to change, each given whole (a nested object replaces the stored one). A key set to null clears it.", + "type": "string" + } + }, + "required": [ + "yaml" + ], + "additionalProperties": false + }, + "read_only": false + } +] diff --git a/backend/windmill-api/src/mcp/session/guidance.rs b/backend/windmill-api/src/mcp/session/guidance.rs new file mode 100644 index 0000000000..385aaa5c2a --- /dev/null +++ b/backend/windmill-api/src/mcp/session/guidance.rs @@ -0,0 +1,142 @@ +//! `get_instructions` and `read_skill`: guidance the model pulls on demand. + +use std::collections::HashMap; +use std::sync::LazyLock; + +use serde::Deserialize; +use serde_json::Value; + +use super::{opt_str_arg, str_arg, Ctx, ToolResult}; + +pub(super) const TOOLS: &[&str] = &["get_instructions", "read_skill"]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "get_instructions" => get_instructions(ctx, args), + "read_skill" => read_skill(ctx, args).await, + _ => unreachable!("{name} is not a guidance tool"), + } +} + +/// Each subject's text per language, as the session renders it; `""` is the text for +/// a call that names no language. +#[derive(Deserialize)] +struct Instructions { + index: HashMap<String, HashMap<String, String>>, + texts: HashMap<String, String>, +} + +static INSTRUCTIONS: LazyLock<Instructions> = LazyLock::new(|| { + serde_json::from_str(include_str!("gen/instructions.json")) + .expect("gen/instructions.json is valid") +}); + +fn get_instructions(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let subject = str_arg(args, "subject")?; + if subject == "workspace_settings" && !ctx.auth.is_admin { + return Ok("Only a workspace admin can read or change the workspace settings. Tell the user plainly that you cannot, and suggest asking a workspace admin.".to_string()); + } + let by_language = INSTRUCTIONS + .index + .get(subject) + .ok_or_else(|| format!("Unknown subject `{subject}`"))?; + let language = opt_str_arg(args, "language").unwrap_or(""); + let id = by_language + .get(language) + .ok_or_else(|| format!("Unknown language `{language}`"))?; + Ok(INSTRUCTIONS.texts[id].clone()) +} + +const SKILL_RESOURCE_TYPE: &str = "ai_skill"; +const SKILLS_PAGE_SIZE: usize = 100; +/// Guard against a paging bug looping forever, not a product cap. +const MAX_SKILLS_PAGES: usize = 100; +const MAX_SKILL_DESCRIPTION_CHARS: usize = 1024; +const MAX_SKILL_INSTRUCTIONS_BYTES: usize = 64 * 1024; +const TRUNCATED: &str = "… [truncated]"; + +pub(super) struct Skill { + pub path: String, + pub description: String, +} + +/// Every skill the caller can read. The session lists only the ones its user left +/// switched on, a preference kept in the browser; here they are all in play. +pub(super) async fn list_skills(ctx: &Ctx<'_>) -> Result<Vec<Skill>, String> { + let mut skills = Vec::new(); + for page in 1..=MAX_SKILLS_PAGES { + let rows = ctx + .get(&ctx.ws(&format!( + "resources/list?resource_type={SKILL_RESOURCE_TYPE}&page={page}&per_page={SKILLS_PAGE_SIZE}" + ))) + .await?; + let rows = rows.as_array().map(Vec::as_slice).unwrap_or_default(); + for row in rows { + let Some(path) = row.get("path").and_then(Value::as_str) else { + continue; + }; + let description = row + .get("description") + .and_then(Value::as_str) + .unwrap_or_default(); + let description = if description.chars().count() > MAX_SKILL_DESCRIPTION_CHARS { + let cut: String = description + .chars() + .take(MAX_SKILL_DESCRIPTION_CHARS) + .collect(); + format!("{cut}{TRUNCATED}") + } else { + description.to_string() + }; + skills.push(Skill { path: path.to_string(), description }); + } + if rows.len() < SKILLS_PAGE_SIZE { + break; + } + } + Ok(skills) +} + +async fn read_skill(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + // Checked against the listing: the path is the model's, and without this the tool + // reads any resource holding a string `content`. + let listed = match list_skills(ctx).await { + Ok(skills) => skills.iter().any(|skill| skill.path == path), + Err(e) => return Ok(read_failed(path, &e)), + }; + if !listed { + return Ok(format!( + "\"{path}\" is not one of the skills available here. Only the paths listed under \"Skills\" in the instructions can be read." + )); + } + let value = match ctx + .get(&ctx.ws(&format!("resources/get_value/{path}"))) + .await + { + Ok(value) => value, + Err(e) => return Ok(read_failed(path, &e)), + }; + let Some(body) = value.get("content").and_then(Value::as_str) else { + return Ok(read_failed( + path, + &format!("resource {path} has no string \"content\" — is it an {SKILL_RESOURCE_TYPE}?"), + )); + }; + let body = if body.len() > MAX_SKILL_INSTRUCTIONS_BYTES { + let mut end = MAX_SKILL_INSTRUCTIONS_BYTES; + while !body.is_char_boundary(end) { + end -= 1; + } + format!("{}{TRUNCATED}", &body[..end]) + } else { + body.to_string() + }; + Ok(format!("Skill: {path}\n\nInstructions:\n{body}")) +} + +fn read_failed(path: &str, message: &str) -> String { + format!( + "Failed to read skill \"{path}\": {message}. Check the path against the Skills list in the instructions." + ) +} diff --git a/backend/windmill-api/src/mcp/session/instructions.rs b/backend/windmill-api/src/mcp/session/instructions.rs new file mode 100644 index 0000000000..f5c15c6e17 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/instructions.rs @@ -0,0 +1,152 @@ +//! The instructions a client receives on connecting: the session's system prompt as +//! rendered for an external client (`gen/prompt.json`), filled in for the caller. What +//! differs per workspace is cut out of it, so a connection spanning several workspaces +//! gets the rest up front and each workspace's part from `get_workspace_context`. + +use std::sync::LazyLock; + +use serde::Deserialize; +use windmill_mcp::server::McpAuth; + +use super::{guidance::list_skills, Ctx}; + +/// The prompt with a `{{folder_guidance}}` slot, the guidance once per folder situation, +/// and the sections appended when the workspace has something to put there. +#[derive(Deserialize)] +struct PromptParts { + base: String, + folder_guidance: FolderGuidance, + skills_header: String, + skill_line: String, + workspace_instructions: String, +} + +#[derive(Deserialize)] +struct FolderGuidance { + admin: String, + admin_no_folders: String, + member: String, + member_no_folders: String, + member_readonly: String, + member_no_folders_readonly: String, +} + +static PARTS: LazyLock<PromptParts> = LazyLock::new(|| { + serde_json::from_str(include_str!("gen/prompt.json")).expect("gen/prompt.json is valid") +}); + +/// Folders named in the prompt before the rest are counted rather than listed, as the +/// session does, so a folder-heavy workspace cannot dominate the instructions. +const MAX_LISTED_FOLDERS: usize = 40; + +fn folder_list(names: &[&str]) -> String { + let shown = names + .iter() + .take(MAX_LISTED_FOLDERS) + .map(|n| format!("`f/{n}`")) + .collect::<Vec<_>>() + .join(", "); + if names.len() > MAX_LISTED_FOLDERS { + format!("{shown} (+{} more)", names.len() - MAX_LISTED_FOLDERS) + } else { + shown + } +} + +fn folder_guidance(auth: &crate::db::ApiAuthed) -> String { + let writable: Vec<&str> = auth + .folders() + .iter() + .filter(|(_, write, _)| *write) + .map(|(name, _, _)| name.as_str()) + .collect(); + let readonly: Vec<&str> = auth + .folders() + .iter() + .filter(|(_, write, _)| !*write) + .map(|(name, _, _)| name.as_str()) + .collect(); + + let guidance = &PARTS.folder_guidance; + let template = match (auth.is_admin(), writable.is_empty(), readonly.is_empty()) { + (true, false, _) => &guidance.admin, + (true, true, _) => &guidance.admin_no_folders, + (false, false, true) => &guidance.member, + (false, false, false) => &guidance.member_readonly, + (false, true, true) => &guidance.member_no_folders, + (false, true, false) => &guidance.member_no_folders_readonly, + }; + template + .replace("{{username}}", auth.username()) + .replace("{{writable_folders}}", &folder_list(&writable)) + .replace("{{readonly_folders}}", &folder_list(&readonly)) +} + +/// The workspace's skills and its admin-written instructions. +async fn appendix(ctx: &Ctx<'_>) -> String { + let mut text = String::new(); + // Either lookup failing leaves its section out: a client that cannot connect at all + // is worse than one that connects without the skills list. + if let Ok(skills) = list_skills(ctx).await { + if !skills.is_empty() { + text.push_str(&PARTS.skills_header); + let lines = skills + .iter() + .map(|skill| { + PARTS + .skill_line + .replace("{{skill_path}}", &skill.path) + .replace("{{skill_description}}", &skill.description) + }) + .collect::<Vec<_>>() + .join("\n"); + text.push_str(&lines); + } + } + if let Ok(info) = ctx.get(&ctx.ws("workspaces/get_copilot_info")).await { + let workspace = info + .pointer("/custom_prompts/global") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()); + if let Some(workspace) = workspace { + text.push_str( + &PARTS + .workspace_instructions + .replace("{{workspace_instructions}}", workspace), + ); + } + } + text +} + +/// The whole prompt, for a connection that reaches one workspace. +pub(in crate::mcp) async fn session_instructions(ctx: &Ctx<'_>) -> String { + let mut prompt = PARTS + .base + .replace("{{folder_guidance}}", &folder_guidance(ctx.auth)) + .replace("{{username}}", ctx.auth.username()); + prompt.push_str(&appendix(ctx).await); + prompt +} + +/// The prompt without anything specific to a workspace, for a connection that reaches +/// several: usernames are per workspace, so paths read `u/<username>/...`. +pub(in crate::mcp) fn generic_session_instructions() -> String { + PARTS + .base + .replace("{{folder_guidance}}", "") + .replace("{{username}}", "<username>") +} + +/// What `generic_session_instructions` leaves out, for one workspace. +pub(in crate::mcp) async fn workspace_context(ctx: &Ctx<'_>) -> String { + let username = ctx.auth.username(); + format!( + "Workspace `{}`. Your username here is \"{username}\", so your personal paths are \ + `u/{username}/<name>`.\n{}{}", + ctx.w_id, + folder_guidance(ctx.auth).trim_end(), + appendix(ctx).await + ) +} diff --git a/backend/windmill-api/src/mcp/session/items.rs b/backend/windmill-api/src/mcp/session/items.rs new file mode 100644 index 0000000000..c075586a40 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/items.rs @@ -0,0 +1,739 @@ +//! Draft writes for the item kinds that are plain records: schedules, triggers, resources, variables. + +use std::sync::LazyLock; + +use serde_json::{json, Map, Value}; + +use super::workspace::{finish_draft_write, persist_draft, write_base, Persist}; +use super::{non_null, put, tool_parameters, Ctx, ToolResult, SCHEMAS}; + +pub(super) const TOOLS: &[&str] = &[ + "write_schedule", + "write_trigger", + "write_resource", + "write_variable", +]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "write_schedule" => write_schedule(ctx, args).await, + "write_trigger" => write_trigger(ctx, args).await, + "write_resource" => write_resource(ctx, args).await, + "write_variable" => write_variable(ctx, args).await, + _ => unreachable!("{name} is not an items tool"), + } +} + +// ============================================================================ +// Argument parsing. The session parses arguments with zod schemas; the same schemas +// reach this server as JSON Schema (`gen/tools.json`, `gen/schemas.json`), and `parse` +// applies them with zod's semantics rather than JSON Schema's: an undeclared key is +// dropped instead of refused, a `default` fills a missing key, a union yields the +// first branch that accepts the value. +// ============================================================================ + +fn tool_schema(name: &str) -> Value { + tool_parameters(name) + .map(|parameters| Value::Object(parameters.clone())) + .unwrap_or_default() +} + +/// A schedule's whole schema: the fields `write_schedule` lists plus the ones it takes +/// through `advanced`, which the session spreads to the top level before parsing. +static SCHEDULE_SCHEMA: LazyLock<Value> = LazyLock::new(|| { + let mut schema = tool_schema("write_schedule"); + let advanced: Value = serde_json::from_str(&SCHEMAS.schedule).unwrap_or_default(); + if let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) { + properties.remove("advanced"); + if let Some(advanced) = advanced.get("properties").and_then(Value::as_object) { + properties.extend(advanced.clone()); + } + } + schema +}); + +fn received(value: Option<&Value>) -> &'static str { + match value { + None => "undefined", + Some(Value::Null) => "null", + Some(Value::Bool(_)) => "boolean", + Some(Value::Number(_)) => "number", + Some(Value::String(_)) => "string", + Some(Value::Array(_)) => "array", + Some(Value::Object(_)) => "object", + } +} + +fn join(path: &str, key: &str) -> String { + if path.is_empty() { + key.to_string() + } else { + format!("{path}.{key}") + } +} + +/// `value` as `schema` accepts it, `None` standing for a missing one. Each violation is +/// pushed to `issues` as `<dotted path>: <message>`. +fn parse( + schema: &Value, + value: Option<&Value>, + path: &str, + issues: &mut Vec<String>, +) -> Option<Value> { + let mut issue = |message: String| { + let at = if path.is_empty() { "<root>" } else { path }; + issues.push(format!("{at}: {message}")); + None + }; + if value.is_none() { + if let Some(default) = schema.get("default") { + return Some(default.clone()); + } + } + if let Some(branches) = schema.get("anyOf").and_then(Value::as_array) { + let is_null = |branch: &&Value| branch.get("type").and_then(Value::as_str) == Some("null"); + if value.is_some_and(Value::is_null) && branches.iter().any(|b| is_null(&b)) { + return Some(Value::Null); + } + let branches: Vec<&Value> = branches.iter().filter(|b| !is_null(b)).collect(); + // A nullable field reports what its one real type refuses. + if let [only] = branches[..] { + return parse(only, value, path, issues); + } + for branch in branches { + let mut refused = Vec::new(); + let parsed = parse(branch, value, path, &mut refused); + if refused.is_empty() { + return parsed; + } + } + return issue("Invalid input".to_string()); + } + if let Some(options) = schema.get("enum").and_then(Value::as_array) { + if value.is_some_and(|v| options.contains(v)) { + return value.cloned(); + } + let options: Vec<String> = options.iter().map(Value::to_string).collect(); + return issue(format!( + "Invalid option: expected one of {}", + options.join("|") + )); + } + let Some(kind) = schema.get("type").and_then(Value::as_str) else { + return value.cloned(); + }; + match (kind, value) { + ("boolean", Some(Value::Bool(_))) | ("null", Some(Value::Null)) => value.cloned(), + ("string", Some(Value::String(text))) => { + let matches = schema + .get("pattern") + .and_then(Value::as_str) + .and_then(|pattern| regex::Regex::new(pattern).ok()) + .is_none_or(|pattern| pattern.is_match(text)); + if matches { + value.cloned() + } else if schema.get("format").and_then(Value::as_str) == Some("date-time") { + issue("Invalid ISO datetime".to_string()) + } else { + issue("Invalid string".to_string()) + } + } + ("number" | "integer", Some(Value::Number(number))) => { + let n = number.as_f64().unwrap_or_default(); + let bound = |key: &str| schema.get(key).and_then(Value::as_f64); + if kind == "integer" && n.fract() != 0.0 { + issue("Invalid input: expected int, received number".to_string()) + } else if let Some(min) = bound("minimum").filter(|min| n < *min) { + issue(format!("Too small: expected number to be >={min}")) + } else if let Some(max) = bound("maximum").filter(|max| n > *max) { + issue(format!("Too big: expected number to be <={max}")) + } else { + value.cloned() + } + } + ("array", Some(Value::Array(items))) => { + let any = json!({}); + let item_schema = schema.get("items").unwrap_or(&any); + Some(Value::Array( + items + .iter() + .enumerate() + .filter_map(|(i, item)| { + parse(item_schema, Some(item), &join(path, &i.to_string()), issues) + }) + .collect(), + )) + } + ("object", Some(Value::Object(fields))) => { + let Some(properties) = schema.get("properties").and_then(Value::as_object) else { + return value.cloned(); + }; + let required = schema.get("required").and_then(Value::as_array); + let mut out = Map::new(); + for (key, property) in properties { + let field = fields.get(key); + let optional = !required.is_some_and(|r| r.iter().any(|k| k == key)); + if field.is_none() && optional && property.get("default").is_none() { + continue; + } + if let Some(parsed) = parse(property, field, &join(path, key), issues) { + out.insert(key.clone(), parsed); + } + } + if schema.get("additionalProperties") != Some(&Value::Bool(false)) { + for (key, field) in fields { + if !properties.contains_key(key) { + out.insert(key.clone(), field.clone()); + } + } + } + Some(Value::Object(out)) + } + _ => { + let expected = match kind { + "integer" => "number", + "object" if schema.get("properties").is_none() => "record", + other => other, + }; + issue(format!( + "Invalid input: expected {expected}, received {}", + received(value) + )) + } + } +} + +fn parse_args(tool: &str, args: &Value) -> Result<Value, String> { + parse_with(&tool_schema(tool), args) +} + +fn parse_with(schema: &Value, args: &Value) -> Result<Value, String> { + let mut issues = Vec::new(); + let parsed = parse(schema, Some(args), "", &mut issues); + match parsed { + Some(parsed) if issues.is_empty() => Ok(parsed), + _ => Err(format!("Invalid arguments. Issues: {}", issues.join("; "))), + } +} + +/// Key paths `supplied` carries that parsing dropped. Every sub-field of a schedule's +/// `retry` is optional, so a guessed shape parses clean, loses its misspelled keys and +/// would save a policy that does nothing. +fn dropped_keys(supplied: &Value, parsed: Option<&Value>, prefix: &str, out: &mut Vec<String>) { + let Value::Object(supplied) = supplied else { + if parsed.is_none() && !prefix.is_empty() { + out.push(prefix.to_string()); + } + return; + }; + match parsed { + Some(parsed @ (Value::Object(_) | Value::Array(_))) => { + for (key, value) in supplied { + dropped_keys(value, parsed.get(key), &join(prefix, key), out); + } + } + _ => { + if !supplied.is_empty() && !prefix.is_empty() { + out.push(prefix.to_string()); + } + } + } +} + +fn describe_dropped_schedule_options(dropped: &[String]) -> String { + let is_field = |path: &&String| { + let field = path.split('.').next().unwrap_or_default(); + field != "override" && SCHEDULE_SCHEMA["properties"].get(field).is_some() + }; + let (misshaped, unknown): (Vec<&String>, Vec<&String>) = dropped.iter().partition(is_field); + let list = |paths: &[&String]| { + paths + .iter() + .map(|p| p.as_str()) + .collect::<Vec<_>>() + .join(", ") + }; + let mut parts = Vec::new(); + if !misshaped.is_empty() { + parts.push(format!("These schedule options do not match their schema and would have been dropped: {}. Call get_schedule_schema for their exact shape.", list(&misshaped))); + } + if !unknown.is_empty() { + parts.push(format!( + "These are not schedule fields: {}.", + list(&unknown) + )); + } + parts.join(" ") +} + +// ============================================================================ +// Draft values +// ============================================================================ + +fn into_object(value: Option<Value>) -> Map<String, Value> { + match value { + Some(Value::Object(map)) => map, + _ => Map::new(), + } +} + +/// A schedule's or trigger's draft: the base without what the server stamps on a +/// deployed row, then the fields of this write. +fn merge_config(base: Option<Value>, config: Value, path: &str) -> Map<String, Value> { + let mut draft = into_object(base); + for key in ["workspace_id", "edited_by", "edited_at", "email", "error"] { + draft.remove(key); + } + draft.extend(into_object(Some(config))); + draft.insert("path".into(), json!(path)); + draft +} + +fn resource_to_draft_state(resource: &Value) -> Value { + let mut state = Map::new(); + state.insert("path".into(), resource["path"].clone()); + state.insert( + "description".into(), + non_null(resource.get("description")) + .cloned() + .unwrap_or_else(|| json!("")), + ); + state.insert( + "args".into(), + non_null(resource.get("value")) + .cloned() + .unwrap_or_else(|| json!({})), + ); + put( + &mut state, + "labels", + non_null(resource.get("labels")).cloned(), + ); + state.insert( + "wsSpecific".into(), + non_null(resource.get("ws_specific")) + .cloned() + .unwrap_or(json!(false)), + ); + state.insert("resource_type".into(), resource["resource_type"].clone()); + Value::Object(state) +} + +fn resource_draft(args: &Value, base: Option<Value>) -> Value { + let mut draft = into_object(base); + let merged = |arg: &str, key: &str| { + non_null(args.get(arg)) + .or(non_null(draft.get(key))) + .cloned() + }; + let description = merged("description", "description").unwrap_or_else(|| json!("")); + let value = merged("value", "args").unwrap_or_else(|| json!({})); + let labels = merged("labels", "labels"); + let ws_specific = merged("ws_specific", "wsSpecific").unwrap_or(json!(false)); + let resource_type = merged("resource_type", "resource_type"); + draft.insert("path".into(), args["path"].clone()); + draft.insert("description".into(), description); + draft.insert("args".into(), value); + put(&mut draft, "labels", labels); + draft.insert("wsSpecific".into(), ws_specific); + put(&mut draft, "resource_type", resource_type); + Value::Object(draft) +} + +fn variable_to_draft_state(variable: &Value) -> Value { + let field = |key: &str| non_null(variable.get(key)).cloned(); + // An OAuth variable's value belongs to the refresh flow, and the API hands back a + // freshly refreshed live token for an expired one even undecrypted: carried into a + // draft, it would pin a rotating value to a static one at the next deploy. + let oauth_managed = variable.get("is_oauth").and_then(Value::as_bool) == Some(true) + || field("account").is_some(); + let value = if oauth_managed { None } else { field("value") }; + let mut state = Map::new(); + state.insert("path".into(), variable["path"].clone()); + state.insert( + "variable".into(), + json!({ + "value": value.unwrap_or_else(|| json!("")), + "is_secret": variable["is_secret"], + "description": field("description").unwrap_or_else(|| json!("")), + }), + ); + put(&mut state, "labels", field("labels")); + state.insert( + "wsSpecific".into(), + field("ws_specific").unwrap_or(json!(false)), + ); + for key in ["account", "is_oauth", "expires_at", "value_valid_until"] { + put(&mut state, key, field(key)); + } + Value::Object(state) +} + +/// The draft a `write_variable` call leaves. A variable's value is never read back, so +/// an omitted `value` keeps whatever the base holds: `""` for "nothing staged", or the +/// `$encrypted:` marker the draft store turned a staged secret into. +fn variable_draft(args: &Value, base: Option<Value>) -> Result<Value, String> { + let path = args["path"].as_str().unwrap_or_default(); + let arg = |key: &str| non_null(args.get(key)).cloned(); + let stored = |key: &str| { + base.as_ref() + .and_then(|b| b.get("variable")) + .and_then(|v| non_null(v.get(key)).cloned()) + }; + let value = arg("value"); + if base.is_none() && (value.is_none() || arg("is_secret").is_none()) { + return Err(format!("Variable \"{path}\" does not exist yet, so creating it requires both value and is_secret.")); + } + let was_secret = stored("is_secret").and_then(|s| s.as_bool()); + let is_secret = arg("is_secret") + .and_then(|s| s.as_bool()) + .or(was_secret) + .unwrap_or(false); + let empty = json!(""); + // "" is how a secret draft says "nothing staged", so it cannot also mean "set the + // secret to empty". + if is_secret && value.as_ref() == Some(&empty) { + return Err(format!("An empty string is not a valid value for secret variable \"{path}\". Omit value to keep the stored secret, or pass the real new one.")); + } + let next_value = value.clone().or_else(|| stored("value")); + if is_secret && was_secret == Some(false) && next_value.as_ref() == Some(&empty) { + return Err(format!("Cannot make variable \"{path}\" secret without a value: it currently holds an empty one, so there would be nothing to encrypt. Pass the value it should hold.")); + } + // The stored value of a secret cannot be read, and an `$encrypted:` marker is only + // decrypted at deploy while the target stays secret. + if !is_secret && was_secret == Some(true) && value.is_none() { + return Err(format!("Cannot turn secret variable \"{path}\" into a non-secret one without a value: its stored value cannot be read, so it would be replaced by an empty one. Pass the new plaintext value, or leave is_secret unset to keep it secret.")); + } + let description = arg("description").or_else(|| stored("description")); + + let mut draft = into_object(base); + let merged = |arg_key: &str, key: &str| { + non_null(args.get(arg_key)) + .or(non_null(draft.get(key))) + .cloned() + }; + let labels = merged("labels", "labels"); + let ws_specific = merged("ws_specific", "wsSpecific").unwrap_or(json!(false)); + let extras = ["account", "is_oauth", "expires_at"].map(|key| (key, merged(key, key))); + draft.insert("path".into(), json!(path)); + draft.insert( + "variable".into(), + json!({ + "value": next_value.unwrap_or(empty), + "is_secret": is_secret, + "description": description.unwrap_or_else(|| json!("")), + }), + ); + put(&mut draft, "labels", labels); + draft.insert("wsSpecific".into(), ws_specific); + for (key, value) in extras { + put(&mut draft, key, value); + } + // Deploying a draft reads an absent expiry as cleared. The draft starts from the base, so a + // `null` has to remove its date rather than skip it. + if args.get("value_valid_until").is_some_and(Value::is_null) { + draft.remove("value_valid_until"); + } else { + put(&mut draft, "value_valid_until", arg("value_valid_until")); + } + Ok(Value::Object(draft)) +} + +// ============================================================================ +// Tools +// ============================================================================ + +/// The shared write: build on the caller's draft, else on the deployed item (shaped +/// into a draft value by `from_deployed`), else from nothing. +async fn write_draft( + ctx: &Ctx<'_>, + item_type: &str, + trigger_kind: Option<&str>, + path: &str, + force: bool, + from_deployed: impl FnOnce(Value) -> Value, + build: impl FnOnce(Option<Value>) -> Result<Value, String>, +) -> ToolResult { + let base = write_base(ctx, item_type, path, trigger_kind).await?; + let existed = base.base.is_some(); + let from_draft = base.from_draft; + let draft = build( + base.base + .map(|b| if from_draft { b } else { from_deployed(b) }), + )?; + let persisted = persist_draft( + ctx, + item_type, + path, + trigger_kind, + &draft, + base.last_sync.as_deref(), + force, + ) + .await?; + Ok(match persisted { + Persist::Saved(item) => finish_draft_write(ctx, &item, existed), + Persist::Failed(text) => text, + }) +} + +fn take_override(parsed: &mut Value) -> bool { + parsed + .as_object_mut() + .and_then(|o| o.remove("override")) + .and_then(|v| v.as_bool()) + .unwrap_or(false) +} + +async fn write_schedule(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + // A named argument outranks the same key inside `advanced`. + let mut merged = into_object(args.get("advanced").cloned()); + for (key, value) in args.as_object().into_iter().flatten() { + if key != "advanced" { + merged.insert(key.clone(), value.clone()); + } + } + let merged = Value::Object(merged); + let mut parsed = parse_with(&SCHEDULE_SCHEMA, &merged)?; + let mut dropped = Vec::new(); + dropped_keys(&merged, Some(&parsed), "", &mut dropped); + if !dropped.is_empty() { + return Err(describe_dropped_schedule_options(&dropped)); + } + let force = take_override(&mut parsed); + let path = parsed["path"].as_str().unwrap_or_default().to_string(); + write_draft( + ctx, + "schedule", + None, + &path, + force, + |deployed| deployed, + |base| Ok(Value::Object(merge_config(base, parsed, &path))), + ) + .await +} + +async fn write_trigger(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let mut parsed = parse_args("write_trigger", args)?; + let force = take_override(&mut parsed); + let kind = parsed["kind"].as_str().unwrap_or_default(); + let schema: Value = SCHEMAS + .trigger + .get(kind) + .and_then(|schema| serde_json::from_str(schema).ok()) + .ok_or_else(|| format!("Unknown trigger kind `{kind}`"))?; + // The draft is filed under `kind`, so a config of another kind is refused here + // rather than stored as a draft no editor or deploy can read. + let mut issues = Vec::new(); + let config = parse(&schema, parsed.get("config"), "", &mut issues); + let config = match config { + Some(config) if issues.is_empty() => config, + _ => { + return Err(format!( + "Invalid config for a \"{kind}\" trigger. Call get_trigger_schema with kind \"{kind}\" for its exact fields. Issues: {}", + issues.join("; ") + )) + } + }; + let path = config["path"].as_str().unwrap_or_default().to_string(); + write_draft( + ctx, + "trigger", + Some(kind), + &path, + force, + |deployed| deployed, + |base| { + let mut draft = merge_config(base, config, &path); + // Optional in the schema, but a NOT NULL column. Defaulted on the merged + // draft so an omitted field keeps the existing trigger's value. + if kind == "email" && non_null(draft.get("workspaced_local_part")).is_none() { + draft.insert("workspaced_local_part".into(), json!(false)); + } + Ok(Value::Object(draft)) + }, + ) + .await +} + +async fn write_resource(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let mut parsed = parse_args("write_resource", args)?; + let force = take_override(&mut parsed); + let path = parsed["path"].as_str().unwrap_or_default().to_string(); + write_draft( + ctx, + "resource", + None, + &path, + force, + |deployed| resource_to_draft_state(&deployed), + |base| Ok(resource_draft(&parsed, base)), + ) + .await +} + +async fn write_variable(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let mut parsed = parse_args("write_variable", args)?; + let force = take_override(&mut parsed); + let path = parsed["path"].as_str().unwrap_or_default().to_string(); + // A variable's value is never interpolated, so its own `$var:` reference is the + // reference syntax echoed back, not a value. + if let Some(value) = parsed.get("value").and_then(Value::as_str) { + if value == format!("$var:{path}") { + return Err(format!("\"{value}\" is not a valid value for variable \"{path}\" — it is a self-reference. Omit value to keep the current one.")); + } + } + write_draft( + ctx, + "variable", + None, + &path, + force, + |deployed| variable_to_draft_state(&deployed), + |base| variable_draft(&parsed, base), + ) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn issues_of(schema: &Value, value: Value) -> (Option<Value>, Vec<String>) { + let mut issues = Vec::new(); + let parsed = parse(schema, Some(&value), "", &mut issues); + (parsed, issues) + } + + #[test] + fn trigger_config_parses_like_the_session() { + let kafka: Value = serde_json::from_str(&SCHEMAS.trigger["kafka"]).unwrap(); + let (parsed, issues) = issues_of( + &kafka, + json!({ + "path": "p", "script_path": "s", "is_flow": false, "kafka_resource_path": "r", + "group_id": "g", "topics": ["a"], "unknown_field": 1, + "filters": [{"key": "k", "value": 1, "zzz": 2}, {"any_of": [{"a": 1}]}], + }), + ); + assert_eq!(issues, Vec::<String>::new()); + let parsed = parsed.unwrap(); + assert_eq!(parsed.get("unknown_field"), None); + assert_eq!( + parsed["filters"], + json!([{"key": "k", "value": 1}, {"any_of": [{"a": 1}]}]) + ); + assert_eq!(parsed["filter_logic"], "and"); + assert_eq!(parsed["auto_commit"], true); + + let (_, issues) = issues_of( + &kafka, + json!({ + "path": 5, "is_flow": "x", "topics": "a", "filters": [3], "group_id": null, + "auto_offset_reset": "x", "kafka_resource_path": "r", + "retry": {"exponential": {"seconds": 0, "random_factor": 1.5}, "retry_if": {}}, + }), + ); + assert_eq!( + issues, + [ + "path: Invalid input: expected string, received number", + "script_path: Invalid input: expected string, received undefined", + "is_flow: Invalid input: expected boolean, received string", + "group_id: Invalid input: expected string, received null", + "topics: Invalid input: expected array, received string", + "filters.0: Invalid input", + "auto_offset_reset: Invalid option: expected one of \"latest\"|\"earliest\"", + "retry.exponential.seconds: Too small: expected number to be >=1", + "retry.exponential.random_factor: Invalid input: expected int, received number", + "retry.retry_if.expr: Invalid input: expected string, received undefined", + ] + ); + } + + #[test] + fn schedule_reports_what_parsing_would_drop() { + let merged = json!({ + "path": "p", "schedule": "s", "timezone": "UTC", "script_path": "x", + "is_flow": false, "args": null, "bogus": 1, "override": true, + "retry": {"constant": {"attempts": 2, "secs": 3}}, + }); + let parsed = parse_with(&SCHEDULE_SCHEMA, &merged).unwrap(); + let mut dropped = Vec::new(); + dropped_keys(&merged, Some(&parsed), "", &mut dropped); + assert_eq!( + describe_dropped_schedule_options(&dropped), + "These schedule options do not match their schema and would have been dropped: retry.constant.secs. Call get_schedule_schema for their exact shape. These are not schedule fields: bogus." + ); + assert!(parse_with( + &SCHEDULE_SCHEMA, + &json!({"path": "p", "paused_until": "tomorrow"}) + ) + .unwrap_err() + .contains("paused_until: Invalid ISO datetime")); + } + + #[test] + fn variable_value_rules() { + let secret = json!({ + "path": "p", + "variable": {"value": "$encrypted:abc", "is_secret": true, "description": "d"}, + "wsSpecific": false, + }); + let plain_empty = + json!({"path": "p", "variable": {"value": "", "is_secret": false, "description": ""}}); + + assert!(variable_draft(&json!({"path": "p", "value": "v"}), None).is_err()); + let kept = variable_draft( + &json!({"path": "p", "description": "new"}), + Some(secret.clone()), + ) + .unwrap(); + assert_eq!( + kept["variable"], + json!({"value": "$encrypted:abc", "is_secret": true, "description": "new"}) + ); + assert!(variable_draft(&json!({"path": "p", "value": ""}), Some(secret.clone())).is_err()); + assert!(variable_draft( + &json!({"path": "p", "is_secret": false}), + Some(secret.clone()) + ) + .is_err()); + let revealed = variable_draft( + &json!({"path": "p", "is_secret": false, "value": "v"}), + Some(secret), + ) + .unwrap(); + assert_eq!(revealed["variable"]["value"], "v"); + assert!( + variable_draft(&json!({"path": "p", "is_secret": true}), Some(plain_empty)).is_err() + ); + + let dated = variable_to_draft_state(&json!({ + "path": "p", "value": "v", "is_secret": false, "value_valid_until": "2027-01-15T00:00:00Z", + })); + let edit = |args: Value| variable_draft(&args, Some(dated.clone())).unwrap(); + assert_eq!( + edit(json!({"path": "p", "description": "new"}))["value_valid_until"], + "2027-01-15T00:00:00Z" + ); + assert!(edit(json!({"path": "p", "value_valid_until": null})) + .get("value_valid_until") + .is_none()); + + let oauth = variable_to_draft_state(&json!({ + "path": "p", "value": "live-token", "is_secret": true, "account": 3, + "description": null, "expires_at": null, + })); + assert_eq!( + oauth, + json!({ + "path": "p", + "variable": {"value": "", "is_secret": true, "description": ""}, + "wsSpecific": false, + "account": 3, + }) + ); + } +} diff --git a/backend/windmill-api/src/mcp/session/misc.rs b/backend/windmill-api/src/mcp/session/misc.rs new file mode 100644 index 0000000000..d613b89f92 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/misc.rs @@ -0,0 +1,728 @@ +//! Lookups that touch no draft: hub, docs, npm, resource types, workers, folders. + +use std::collections::HashSet; + +use futures::future::join_all; +use serde_json::{json, Map, Value}; +use windmill_common::utils::HTTP_CLIENT; + +use super::{ + array, enc, is_not_found, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult, SCHEMAS, +}; + +pub(super) const TOOLS: &[&str] = &[ + "search_hub_scripts", + "get_hub_integration", + "search_npm_packages", + "search_docs", + "read_docs_page", + "search_resource_types", + "create_resource_type", + "list_workers", + "create_folder", + "get_trigger_schema", + "get_schedule_schema", +]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "search_hub_scripts" => search_hub_scripts(ctx, args).await, + "get_hub_integration" => get_hub_integration(ctx, args).await, + "search_npm_packages" => search_npm_packages(args).await, + "search_docs" => search_docs(ctx, args).await, + "read_docs_page" => read_docs_page(ctx, args).await, + "search_resource_types" => search_resource_types(ctx, args).await, + "create_resource_type" => create_resource_type(ctx, args).await, + "list_workers" => list_workers(ctx).await, + "create_folder" => create_folder(ctx, args).await, + "get_trigger_schema" => get_trigger_schema(args), + "get_schedule_schema" => Ok(SCHEMAS.schedule.clone()), + _ => unreachable!("{name} is not a misc tool"), + } +} + +fn get_trigger_schema(args: &Value) -> ToolResult { + let kind = str_arg(args, "kind")?; + SCHEMAS + .trigger + .get(kind) + .cloned() + .ok_or_else(|| format!("Unknown trigger kind `{kind}`")) +} + +/// Copies `keys` from `from` into `to`, each only when truthy. +fn copy_truthy(to: &mut Map<String, Value>, from: &Value, keys: &[&str]) { + for key in keys { + if truthy(from.get(key)) { + to.insert(key.to_string(), from[key].clone()); + } + } +} + +/// Copies `keys` from `from` into `to`, each only when present (`null` included). +fn copy_present(to: &mut Map<String, Value>, from: &Value, keys: &[&str]) { + for key in keys { + if let Some(value) = from.get(key) { + to.insert(key.to_string(), value.clone()); + } + } +} + +fn words(text: &str) -> impl Iterator<Item = String> + '_ { + text.split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_ascii_lowercase) +} + +// --------------------------------------------------------------------------- +// Hub +// --------------------------------------------------------------------------- + +const MAX_BROWSED_HUB_SCRIPTS: usize = 20; +const MAX_SUGGESTED_INTEGRATIONS: usize = 5; +const MAX_INTEGRATION_EXAMPLES: usize = 5; + +/// An unreachable hub degrades to "no suggestions" rather than a tool error. +async fn hub_integrations(ctx: &Ctx<'_>) -> Vec<Value> { + match ctx.get("/integrations/hub/list?kind=script").await { + Ok(Value::Array(integrations)) => integrations, + _ => Vec::new(), + } +} + +/// A token matches a whole word of the slug or display name, or extends one from four +/// characters on: a bare substring test makes `for` hit sales*for*ce. +fn token_matches_integration(token: &str, integration: &Value) -> bool { + let name = integration.get("name").and_then(Value::as_str); + let display_name = integration.get("display_name").and_then(Value::as_str); + let words: Vec<String> = [name, display_name] + .into_iter() + .flatten() + .flat_map(words) + .collect(); + if words.iter().any(|w| w == token) { + return true; + } + token.len() >= 4 + && words + .iter() + .any(|w| w.len() >= 4 && (w.starts_with(token) || token.starts_with(w.as_str()))) +} + +/// Ranked by how many query words each integration accounts for, so "google drive" +/// puts `gdrive` ahead of every other `g*` integration matching on "google" alone. +fn suggest_hub_integrations(integrations: &[Value], query: &str) -> Vec<String> { + let tokens: Vec<String> = words(query).filter(|t| t.len() >= 2).collect(); + let mut ranked: Vec<(usize, &str)> = integrations + .iter() + .filter_map(|integration| { + let matched = tokens + .iter() + .filter(|t| token_matches_integration(t, integration)) + .count(); + let name = integration.get("name")?.as_str()?; + (matched > 0).then_some((matched, name)) + }) + .collect(); + ranked.sort_by(|a, b| b.0.cmp(&a.0)); + ranked + .into_iter() + .take(MAX_SUGGESTED_INTEGRATIONS) + .map(|(_, name)| name.to_string()) + .collect() +} + +/// The hub resolves a script by its version id alone; the other segments are descriptive. +fn hub_script_path(script: &Value) -> String { + let summary = script + .get("summary") + .and_then(Value::as_str) + .unwrap_or_default() + .to_lowercase(); + format!( + "hub/{}/{}/{}", + script.get("version_id").unwrap_or(&Value::Null), + script + .get("app") + .and_then(Value::as_str) + .unwrap_or_default(), + summary.split_whitespace().collect::<Vec<_>>().join("_") + ) +} + +async fn search_hub_scripts(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let query = opt_str_arg(args, "query").filter(|s| !s.is_empty()); + let app = opt_str_arg(args, "integration").filter(|s| !s.is_empty()); + if query.is_none() && app.is_none() { + return Ok( + "Pass query (what the script should do), integration (a slug to list), or both." + .to_string(), + ); + } + let app_param = app + .map(|app| format!("&app={}", enc(app))) + .unwrap_or_default(); + // Listing an integration goes through the top-scripts endpoint: it applies no + // similarity floor, so near-misses worth reading as examples survive. + let scripts = match query { + Some(query) => { + ctx.get(&format!( + "/embeddings/query_hub_scripts?text={}&kind=script{app_param}", + enc(query) + )) + .await? + } + None => ctx + .get(&format!( + "/scripts/hub/top?limit={MAX_BROWSED_HUB_SCRIPTS}&kind=script{app_param}" + )) + .await? + .get("asks") + .cloned() + .unwrap_or_default(), + }; + let scripts = array(Some(&scripts)); + let integrations = hub_integrations(ctx).await; + + if scripts.is_empty() { + let subject = [app, query] + .into_iter() + .flatten() + .collect::<Vec<_>>() + .join(" "); + return Ok(json!({ + "results": [], + "suggested_integrations": suggest_hub_integrations(&integrations, &subject) + }) + .to_string()); + } + + // Lowercased because a hub slug is case-sensitive and both casings can exist. + let documented: HashSet<String> = integrations + .iter() + .filter(|i| i.get("documented") == Some(&Value::Bool(true))) + .filter_map(|i| Some(i.get("name")?.as_str()?.to_lowercase())) + .collect(); + let results: Vec<Value> = scripts + .iter() + .map(|script| { + let mut result = Map::new(); + result.insert("path".to_string(), hub_script_path(script).into()); + copy_present(&mut result, script, &["summary"]); + let app = script.get("app").cloned().unwrap_or_default(); + let is_documented = + documented.contains(&app.as_str().unwrap_or_default().to_lowercase()); + result.insert("integration".to_string(), app); + if is_documented { + result.insert("documented".to_string(), true.into()); + } + copy_truthy(&mut result, script, &["description"]); + Value::Object(result) + }) + .collect(); + Ok(json!({ "results": results }).to_string()) +} + +/// How the authored notes were checked is provenance for a human reviewing the hub; +/// the verdict and the fields it flags as shaky are what a caller can act on. +fn without_provenance(meta: &Value) -> Value { + let Value::Object(meta) = meta else { + return meta.clone(); + }; + let mut rest = meta.clone(); + let validation = rest.shift_remove("validation"); + let kept: Map<String, Value> = validation + .as_ref() + .and_then(Value::as_object) + .into_iter() + .flatten() + .filter(|(key, _)| *key == "status" || *key == "low_confidence_fields") + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + if !kept.is_empty() { + rest.insert("validation".to_string(), Value::Object(kept)); + } + Value::Object(rest) +} + +async fn get_hub_integration(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let integration = str_arg(args, "integration")?; + let doc = match ctx + .get(&format!("/integrations/hub/{}/meta", enc(integration))) + .await + { + Ok(doc) => doc, + Err(e) => { + // Only a 404 means the integration is absent. Reporting a timeout the same + // way would teach the model that a real integration does not exist. + let error = if is_not_found(&e) { + format!("No hub metadata for \"{integration}\".") + } else { + format!("Could not reach the hub for \"{integration}\"; it may still exist. Read its scripts instead, or try again.") + }; + let integrations = hub_integrations(ctx).await; + return Ok(json!({ + "error": error, + "suggested_integrations": suggest_hub_integrations(&integrations, integration) + }) + .to_string()); + } + }; + + // The hub owns this response's shape and can be older than this server, so every + // section is optional: a hub that sends less returns less. + let mut out = Map::new(); + if let Some(app) = doc.get("app") { + out.insert("integration".to_string(), app.clone()); + } + copy_present(&mut out, &doc, &["display_name"]); + copy_truthy(&mut out, &doc, &["description", "docs_url"]); + if truthy(doc.get("meta")) { + out.insert( + "verified_provider_notes".to_string(), + without_provenance(&doc["meta"]), + ); + } + let derived = doc.get("derived").filter(|d| truthy(Some(d))); + if let Some(derived) = derived { + let mut observed = Map::new(); + let hosts: Vec<Value> = array(derived.get("api_hosts")) + .iter() + .filter_map(|h| h.get("host").cloned()) + .collect(); + observed.insert("api_hosts".to_string(), hosts.into()); + copy_present(&mut observed, derived, &["style"]); + let languages: Vec<&String> = derived + .get("languages") + .and_then(Value::as_object) + .map(|l| l.keys().collect()) + .unwrap_or_default(); + observed.insert("languages".to_string(), json!(languages)); + copy_present(&mut observed, derived, &["script_counts"]); + out.insert("observed_from_scripts".to_string(), observed.into()); + } + if doc.get("curated") == Some(&Value::Bool(true)) { + out.insert( + "scripts_note".to_string(), + "These scripts were pruned to idiomatic actions rather than generated one per API endpoint, so they are worth following as style examples.".into(), + ); + } + let resource_types: Vec<Value> = array(doc.get("resource_types")) + .iter() + .map(|rt| { + let mut entry = Map::new(); + copy_present(&mut entry, rt, &["name"]); + copy_truthy(&mut entry, rt, &["description"]); + // The hub keeps a schema in a text column and hands it back as a JSON string. + match rt.get("schema") { + Some(Value::String(schema)) => { + let parsed = serde_json::from_str(schema) + .unwrap_or_else(|_| Value::String(schema.clone())); + entry.insert("schema".to_string(), parsed); + } + Some(schema) => { + entry.insert("schema".to_string(), schema.clone()); + } + None => {} + } + Value::Object(entry) + }) + .collect(); + out.insert("resource_types".to_string(), resource_types.into()); + let examples: Vec<Value> = array(derived.and_then(|d| d.get("top_scripts"))) + .iter() + .take(MAX_INTEGRATION_EXAMPLES) + .map(|script| { + let mut entry = Map::new(); + copy_present(&mut entry, script, &["path", "summary"]); + copy_truthy(&mut entry, script, &["description", "language"]); + Value::Object(entry) + }) + .collect(); + out.insert("example_scripts".to_string(), examples.into()); + Ok(Value::Object(out).to_string()) +} + +// --------------------------------------------------------------------------- +// npm +// --------------------------------------------------------------------------- + +const NPM_SCORE_THRESHOLD: f64 = 1000.0; +/// The session caps a package's readme and types at 1% of its model's context window +/// each. The caller's model is unknown here, so this is 1% of the window the session +/// assumes for an unknown model (128000). +const NPM_TEXT_LIMIT: usize = 1280; + +fn take_chars(text: &str, limit: usize) -> String { + text.chars().take(limit).collect() +} + +async fn fetch(url: &str) -> Result<reqwest::Response, reqwest::Error> { + HTTP_CLIENT.get(url).send().await +} + +/// The package's declared entry declaration file. The session walks every `.d.ts` of the +/// package in the browser and keeps the same number of characters of the result. +async fn npm_package_types(name: &str, version: &str) -> Option<String> { + let base = format!("https://unpkg.com/{name}@{version}"); + let manifest: Value = fetch(&format!("{base}/package.json")) + .await + .ok()? + .error_for_status() + .ok()? + .json() + .await + .ok()?; + let entry = ["types", "typings"] + .iter() + .find_map(|key| manifest.get(key)?.as_str()) + .unwrap_or("index.d.ts") + .trim_start_matches("./"); + let types = fetch(&format!("{base}/{entry}")) + .await + .ok()? + .error_for_status() + .ok()? + .text() + .await + .ok()?; + Some(format!("// /node_modules/{name}/{entry}\n{types}")) +} + +async fn npm_search(query: &str) -> Result<Vec<Value>, String> { + let data: Value = fetch(&format!( + "https://registry.npmjs.org/-/v1/search?text={}&size=2", + enc(query) + )) + .await + .map_err(|e| e.to_string())? + .json() + .await + .map_err(|e| e.to_string())?; + let packages = data + .get("objects") + .and_then(Value::as_array) + .ok_or("no `objects` in the registry answer")? + .iter() + .filter(|o| { + o.get("searchScore").and_then(Value::as_f64).unwrap_or(0.0) >= NPM_SCORE_THRESHOLD + }) + .filter_map(|o| { + let package = o.get("package")?; + Some(( + package.get("name")?.as_str()?, + package.get("version").and_then(Value::as_str), + )) + }); + Ok(join_all(packages.map(|(name, version)| async move { + let documentation = match fetch(&format!("https://unpkg.com/{name}/readme.md")).await { + Ok(response) => response.text().await.unwrap_or_default(), + Err(_) => String::new(), + }; + let types = npm_package_types(name, version.unwrap_or("latest")) + .await + .unwrap_or_default(); + json!({ + "package": name, + "documentation": take_chars(&documentation, NPM_TEXT_LIMIT), + "types": take_chars(&types, NPM_TEXT_LIMIT), + }) + })) + .await) +} + +async fn search_npm_packages(args: &Value) -> ToolResult { + let query = str_arg(args, "query")?; + Ok(match npm_search(query).await { + Ok(results) => Value::Array(results).to_string(), + Err(e) => { + tracing::warn!("npm package search failed: {e}"); + "Error searching external integration resources".to_string() + } + }) +} + +// --------------------------------------------------------------------------- +// Docs +// --------------------------------------------------------------------------- + +/// `text` of a `/docs/*` answer, or the session's wording for a failed lookup. +fn docs_text(result: Result<Value, String>, action: &str) -> String { + match result { + Ok(response) => response + .get("text") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + Err(e) => format!("Failed to {action}: {e}, pursuing with the user request..."), + } +} + +async fn search_docs(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let query = opt_str_arg(args, "query").unwrap_or_default().trim(); + if query.is_empty() { + return Ok( + "No search query was provided. Provide a `query` of one or more keywords.".to_string(), + ); + } + let result = ctx.get(&format!("/docs/search?query={}", enc(query))).await; + Ok(docs_text(result, "search documentation")) +} + +async fn read_docs_page(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let url = opt_str_arg(args, "url").unwrap_or_default(); + if url.trim().is_empty() { + return Ok("No documentation page URL was provided. Provide a `url` — e.g. a `Source` URL returned by search_docs.".to_string()); + } + let section = opt_str_arg(args, "section") + .filter(|s| !s.trim().is_empty()) + .map(|s| format!("§ion={}", enc(s))) + .unwrap_or_default(); + let result = ctx + .get(&format!("/docs/page?url={}{section}", enc(url))) + .await; + Ok(docs_text(result, "read documentation page")) +} + +// --------------------------------------------------------------------------- +// Resource types +// --------------------------------------------------------------------------- + +/// The hub publishes hundreds of resource types and an instance seeds only a few of its +/// own, so fewer than this means the instance never synced with the hub. +const UNSYNCED_RESOURCE_TYPE_COUNT: usize = 20; + +const HUB_SYNC_INSTRUCTIONS: &str = "Tell the user: no resource of a missing type can be created until a superadmin syncs resource types from the hub, with \"Sync resource types with Hub\" in the Add resource dialog of the Resources page."; + +async fn search_resource_types(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let query = str_arg(args, "query")?; + let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(5); + let search_route = ctx.ws(&format!( + "embeddings/query_resource_types?text={}&limit={limit}", + enc(query) + )); + let names_route = ctx.ws("resources/type/listnames"); + let (results, names) = + futures::future::join(ctx.get(&search_route), ctx.get(&names_route)).await; + let results = results?; + let results = array(Some(&results)); + let count = names + .map(|names| { + array(Some(&names)) + .iter() + .filter_map(Value::as_str) + .collect::<HashSet<_>>() + .len() + }) + .unwrap_or(0); + let listing: Vec<Value> = results + .iter() + .map(|rt| { + let mut entry = Map::new(); + copy_present(&mut entry, rt, &["name", "schema"]); + Value::Object(entry) + }) + .collect(); + let listing = pretty(&Value::Array(listing)); + // The similarity search still returns the nearest of the few types there are, so the + // note cannot wait for an empty result; it replaces the "no dedicated type" one, which + // would have the model create a duplicate of a type a sync brings. + if count > 0 && count < UNSYNCED_RESOURCE_TYPE_COUNT { + return Ok(format!("{listing}\n\nOnly {count} resource types exist on this instance, so it has most likely never synced with the Windmill Hub, which has types for most services. {HUB_SYNC_INSTRUCTIONS}")); + } + // The search is semantic and always returns its closest types, so a miss reads + // like a hit unless the absence is spelled out. + let words: Vec<String> = words(query).filter(|w| w.len() >= 3).collect(); + let named = results.iter().any(|rt| { + let name = rt + .get("name") + .and_then(Value::as_str) + .unwrap_or_default() + .to_lowercase(); + words.iter().any(|w| name.contains(w.as_str())) + }); + Ok(if named || words.is_empty() { + listing + } else { + format!("{listing}\n\nNo resource type name contains \"{query}\": these are only the nearest matches, so no dedicated type exists. Searching again with synonyms will not find one — use a fitting generic type above, or create a custom c_<name> type.") + }) +} + +/// The prefix the Add resource type form adds: a hub type of the same name, synced later, +/// would otherwise clash with this one. +fn custom_resource_type_name(name: &str) -> String { + if name.starts_with("c_") { + name.to_string() + } else { + format!("c_{name}") + } +} + +async fn create_resource_type(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let name = custom_resource_type_name(str_arg(args, "name")?); + let description = str_arg(args, "description")?; + let schema = args + .get("schema") + .filter(|s| s.is_object()) + .ok_or("Missing required object argument `schema`")?; + ctx.post( + &ctx.ws("resources/type/create"), + json!({ "name": name, "description": description, "schema": schema }), + ) + .await?; + Ok(json!({ + "success": true, + "message": format!("Created resource type {name}. Refer to it by this name.") + }) + .to_string()) +} + +// --------------------------------------------------------------------------- +// Workers +// --------------------------------------------------------------------------- + +const WORKER_PAGE_SIZE: usize = 100; +// `GET /workers/list` hides workers from a caller without the devops role by returning +// an empty list, not an error, when HIDE_WORKERS_FOR_NON_ADMINS is set. The flag is not +// visible here, so absence is only provable for a devops or superadmin caller. +const NO_WORKERS_VISIBLE_MESSAGE: &str = "No workers came back. This does NOT establish that no workers are running: an instance can hide workers from callers without the devops role, and it does so by returning an empty list rather than an error. Tell the user you cannot see any workers and that worker visibility may be restricted for your account, and suggest they check the Workers page themselves if they can open it, or ask a workspace admin otherwise. Never state that no workers are online or that the instance has none."; +const NO_WORKERS_CONNECTED_MESSAGE: &str = "No workers are connected to this instance (none pinged in the last 5 minutes). Queued runs will stay queued until a worker starts."; + +async fn list_workers(ctx: &Ctx<'_>) -> ToolResult { + let pings = ctx + .get(&format!("/workers/list?per_page={WORKER_PAGE_SIZE}")) + .await?; + let pings = array(Some(&pings)); + if pings.is_empty() { + let me = ctx.get("/users/whoami").await.unwrap_or_default(); + let sees_all = truthy(me.get("super_admin")) || truthy(me.get("devops")); + return Ok(if sees_all { + NO_WORKERS_CONNECTED_MESSAGE + } else { + NO_WORKERS_VISIBLE_MESSAGE + } + .to_string()); + } + let workers: Vec<Value> = pings + .iter() + .map(|ping| { + let mut worker = Map::new(); + copy_present( + &mut worker, + ping, + &[ + "worker", + "worker_group", + "custom_tags", + "last_ping", + "jobs_executed", + ], + ); + Value::Object(worker) + }) + .collect(); + let mut out = Map::new(); + let listed = workers.len(); + out.insert("workers".to_string(), workers.into()); + if listed == WORKER_PAGE_SIZE { + out.insert( + "note".to_string(), + format!("Only the first {WORKER_PAGE_SIZE} workers are listed; more may be connected.") + .into(), + ); + } + Ok(pretty(&Value::Object(out))) +} + +// --------------------------------------------------------------------------- +// Folders +// --------------------------------------------------------------------------- + +async fn create_folder(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let name = str_arg(args, "name")?; + // Same rule as the API's own check, so an invalid name gets this wording. + if name.is_empty() + || !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + { + return Ok(json!({ + "success": false, + "error": "Folder name can only contain alphanumeric characters, underscores, and hyphens." + }) + .to_string()); + } + let mut body = Map::new(); + body.insert("name".to_string(), name.into()); + copy_present(&mut body, args, &["summary"]); + Ok( + match ctx.post(&ctx.ws("folders/create"), body.into()).await { + Ok(_) => json!({ + "success": true, + "message": format!("Created folder `f/{name}`. You can now write items to `f/{name}/<name>`.") + }), + Err(error) => json!({ "success": false, "error": error }), + } + .to_string(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn suggestions_rank_by_matched_words() { + let integrations = vec![ + json!({ "name": "gcal", "display_name": "Google Calendar" }), + json!({ "name": "gdrive", "display_name": "Google Drive" }), + json!({ "name": "salesforce", "display_name": null }), + json!({ "name": "s3", "display_name": "S3" }), + ]; + assert_eq!( + suggest_hub_integrations(&integrations, "google drive"), + ["gdrive", "gcal"] + ); + // A short token must equal a word; a long one may extend it. + assert!(suggest_hub_integrations(&integrations, "for").is_empty()); + assert_eq!( + suggest_hub_integrations(&integrations, "sales"), + ["salesforce"] + ); + assert_eq!(suggest_hub_integrations(&integrations, "s3 bucket"), ["s3"]); + } + + #[test] + fn provenance_keeps_only_the_verdict() { + let meta = json!({ + "pagination": "cursor", + "validation": { "status": "verified", "method": "live", "low_confidence_fields": ["a"] } + }); + assert_eq!( + without_provenance(&meta), + json!({ + "pagination": "cursor", + "validation": { "status": "verified", "low_confidence_fields": ["a"] } + }) + ); + assert_eq!( + without_provenance(&json!({ "a": 1, "validation": { "method": "live" } })), + json!({ "a": 1 }) + ); + } + + #[test] + fn custom_resource_types_carry_the_c_prefix_once() { + assert_eq!(custom_resource_type_name("acme"), "c_acme"); + assert_eq!(custom_resource_type_name("c_acme"), "c_acme"); + } + + #[test] + fn hub_path_from_summary() { + let script = json!({ "version_id": 28479, "app": "stripe", "summary": "Cancel Or Reverse a Payout" }); + assert_eq!( + hub_script_path(&script), + "hub/28479/stripe/cancel_or_reverse_a_payout" + ); + } +} diff --git a/backend/windmill-api/src/mcp/session/mod.rs b/backend/windmill-api/src/mcp/session/mod.rs new file mode 100644 index 0000000000..607c6be5f8 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/mod.rs @@ -0,0 +1,609 @@ +//! The Windmill MCP server's toolset (`/api/mcp`, tokens with `mcp:all`): an AI session's toolset, for a client +//! outside the Windmill UI. +//! +//! Everything a model reads here — tool names, descriptions, input schemas, the +//! instructions, the `get_instructions` texts — is generated from the session's own +//! definitions into `gen/` (`npm run gen:mcp-session` in `frontend/`). What a tool +//! *does* is written here, mirroring its session counterpart in +//! `frontend/src/lib/components/copilot/chat/global/core.ts`: a change to one side's +//! behaviour belongs on the other. +//! +//! A tool acts through the API as the caller, the way the session's does, so every +//! permission check is the API's own. It calls the server's router in-process rather +//! than over a socket. + +use std::collections::HashMap; +use std::sync::LazyLock; + +use serde::Deserialize; +use serde_json::{Map, Value}; +use windmill_mcp::server::{ + BackendResult, CallToolResult, ContentBlock, ErrorData, MetaObject, SessionAccess, Tool, + ToolAnnotations, +}; + +use crate::db::ApiAuthed; + +use super::utils::{mint_caller_jwt, send_as_caller}; + +/// Each running server's fully layered router, by its `base_internal_url`. Keyed rather +/// than global because the backend tests run one server per test in a single process, +/// each on its own database: a tool must reach the server it was called on. +static IN_PROCESS_ROUTERS: LazyLock<std::sync::RwLock<HashMap<String, axum::Router>>> = + LazyLock::new(Default::default); + +/// Let session tools of the server at `base_internal_url` call its API in-process. +/// Without a registration they fall back to HTTP. +pub(crate) fn register_router(base_internal_url: &str, router: Option<axum::Router>) { + let mut routers = IN_PROCESS_ROUTERS.write().unwrap(); + match router { + Some(router) => routers.insert(base_internal_url.to_string(), router), + None => routers.remove(base_internal_url), + }; +} + +mod apps; +mod data; +mod deploy; +mod flows; +mod guidance; +mod instructions; +mod items; +mod misc; +mod runs; +mod settings; +mod workspace; + +pub(super) use instructions::{ + generic_session_instructions, session_instructions, workspace_context, +}; + +#[derive(Deserialize)] +struct ToolDef { + name: String, + description: String, + parameters: Map<String, Value>, + read_only: bool, +} + +static TOOL_DEFS: LazyLock<Vec<ToolDef>> = LazyLock::new(|| { + serde_json::from_str(include_str!("gen/tools.json")).expect("gen/tools.json is valid") +}); + +/// A tool's input schema, as generated from the session's zod schema. +pub(super) fn tool_parameters(name: &str) -> Option<&'static Map<String, Value>> { + TOOL_DEFS + .iter() + .find(|def| def.name == name) + .map(|def| &def.parameters) +} + +/// The JSON Schema text of each trigger kind's config, and of a schedule's `advanced` bag, +/// as the session renders them from its request schemas. +#[derive(Deserialize)] +pub(super) struct Schemas { + pub trigger: HashMap<String, String>, + pub schedule: String, +} + +pub(super) static SCHEMAS: LazyLock<Schemas> = LazyLock::new(|| { + serde_json::from_str(include_str!("gen/schemas.json")).expect("gen/schemas.json is valid") +}); + +/// Session tools that need the Windmill UI and have no meaning for an external client. +/// Every generated tool is either here or implemented by a group below. +#[cfg(test)] +const EDITOR_ONLY: &[&str] = &[ + // The side panel, the question card and the browser-held user instructions. + "open_page", + "askUserQuestion", + "update_user_instructions", + // Files attached to the chat. + "search_files", + "read_file", +]; + +/// Tools whose effect reaches the deployed workspace and cannot be undone by discarding +/// a draft. Stands in for the session's confirmation card. +const DESTRUCTIVE: &[&str] = &[ + "deploy_workspace_item", + "delete_workspace_item", + "create_resource_type", + "set_workspace_settings", +]; + +/// Tools the session counts as reads that still start a job. A read-only token runs +/// nothing on the tools server, so it runs nothing here either. +const RUNS_A_JOB: &[&str] = &["get_db_schema"]; + +/// Tools that run a deployed script or flow, the one write a read-and-run token keeps. +const RUNS_DEPLOYED: &[&str] = &["run_script", "run_flow"]; + +fn allowed(def: &ToolDef, access: SessionAccess) -> bool { + let read = def.read_only && !RUNS_A_JOB.contains(&def.name.as_str()); + match access { + SessionAccess::Full => true, + SessionAccess::ReadAndRun => read || RUNS_DEPLOYED.contains(&def.name.as_str()), + SessionAccess::ReadOnly => read, + } +} + +/// Each group's tools and its dispatcher, tried in order. +macro_rules! groups { + ($($group:ident),*) => { + fn implemented() -> impl Iterator<Item = &'static str> { + std::iter::empty()$(.chain($group::TOOLS.iter().copied()))* + } + + async fn dispatch(ctx: &Ctx<'_>, name: &str, args: &Value) -> Option<ToolResult> { + $(if $group::TOOLS.contains(&name) { + return Some($group::call(ctx, name, args).await); + })* + None + } + }; +} +groups!(guidance, workspace, items, misc, flows, apps, runs, deploy, data, settings); + +/// Claude clients keep an MCP result in context only up to a token budget well under the +/// authoring references `get_instructions` returns, unless the tool raises it. Above the +/// runner's own cap on a result, so that cap is the one that applies. +fn result_size_meta() -> MetaObject { + let mut meta = Map::new(); + meta.insert("anthropic/maxResultSizeChars".to_string(), 100_000.into()); + MetaObject(meta) +} + +pub(super) fn session_tools(access: SessionAccess) -> Vec<Tool> { + TOOL_DEFS + .iter() + .filter(|def| implemented().any(|name| name == def.name)) + .filter(|def| allowed(def, access)) + .map(|def| { + Tool::new( + def.name.clone(), + def.description.clone(), + def.parameters.clone(), + ) + .with_annotations( + ToolAnnotations::new() + .read_only(def.read_only) + .destructive(DESTRUCTIVE.contains(&def.name.as_str())), + ) + .with_meta(result_size_meta()) + }) + .collect() +} + +/// What a tool hands back: the text the model reads, or the message of a failed call. +pub(super) type ToolResult = Result<String, String>; + +/// The caller, and the API reached as them. +pub(super) struct Ctx<'a> { + pub auth: &'a ApiAuthed, + pub w_id: &'a str, + pub base_internal_url: &'a str, + pub access: SessionAccess, + /// The scheme and host the MCP client reached, when known. + pub origin: Option<&'a str>, + /// Minted once per tool call: every JWT the API sees is cached by the auth layer, and a + /// tool can make dozens of calls, which would evict other users' cached sessions. + pub jwt: tokio::sync::OnceCell<String>, +} + +impl Ctx<'_> { + /// Call the API as the caller. `path` follows `/api`; a non-2xx answer is the error. + pub async fn request(&self, method: &str, path: &str, body: Option<Value>) -> ToolResult { + let url = guarded_url(self.base_internal_url, self.w_id, method, path, self.access)?; + // No route scope: this server only admits `mcp:all`, several routes (hub, embeddings) + // map to none, and `guarded_url` is what keeps a call on its route. The tag fence + // is not a route scope and stays: it limits which jobs the caller runs and reads. + let tag_scopes: Vec<String> = self + .auth + .scopes + .iter() + .flatten() + .filter(|s| s.starts_with("if_jobs:filter_tags:")) + .cloned() + .collect(); + let scopes = (!tag_scopes.is_empty()).then_some(tag_scopes); + let router = IN_PROCESS_ROUTERS + .read() + .unwrap() + .get(self.base_internal_url) + .cloned(); + let (status, text) = match router { + Some(router) => self.call_router(router, method, &url, body, scopes).await?, + None => { + let response = send_as_caller(method, &url, self.w_id, self.auth, body, scopes) + .await + .map_err(|e| e.message.to_string())?; + let status = response.status(); + (status, response.text().await.map_err(|e| e.to_string())?) + } + }; + if status.is_success() { + Ok(text) + } else { + Err(format!("{}: {}", status.as_u16(), text)) + } + } + + /// `request` through the server's own router: the same layers and handlers as over + /// HTTP, without a socket. + async fn call_router( + &self, + router: axum::Router, + method: &str, + url: &str, + body: Option<Value>, + scopes: Option<Vec<String>>, + ) -> Result<(http::StatusCode, String), String> { + use tower::ServiceExt; + let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?; + // The router does not see the base URL's own path prefix. + let at = reqwest::Url::parse(self.base_internal_url) + .map_or(0, |base| base.path().trim_end_matches('/').len()); + let uri = match parsed.query() { + Some(q) => format!("{}?{q}", &parsed.path()[at..]), + None => parsed.path()[at..].to_string(), + }; + let token = self + .jwt + .get_or_try_init(|| mint_caller_jwt(self.w_id, self.auth, scopes)) + .await + .map_err(|e| e.message.to_string())?; + let mut request = http::Request::builder() + .method(method) + .uri(uri) + .header(http::header::AUTHORIZATION, format!("Bearer {token}")); + let body = match body { + Some(body) => { + request = request.header(http::header::CONTENT_TYPE, "application/json"); + axum::body::Body::from(serde_json::to_vec(&body).map_err(|e| e.to_string())?) + } + None => axum::body::Body::empty(), + }; + let request = request.body(body).map_err(|e| e.to_string())?; + // The total timeout of the HTTP client this replaces. + tokio::time::timeout(std::time::Duration::from_secs(30), async { + let response = router.oneshot(request).await.map_err(|e| e.to_string())?; + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .map_err(|e| e.to_string())?; + Ok((status, String::from_utf8_lossy(&bytes).into_owned())) + }) + .await + .map_err(|_| format!("Failed to execute request: {method} {url} timed out"))? + } + + pub async fn get(&self, path: &str) -> Result<Value, String> { + let text = self.request("GET", path, None).await?; + serde_json::from_str(&text).map_err(|e| format!("unexpected response from {path}: {e}")) + } + + /// `POST` a JSON body. Several endpoints answer with plain text (a path, a job id): + /// that comes back as a JSON string. + pub async fn post(&self, path: &str, body: Value) -> Result<Value, String> { + let text = self.request("POST", path, Some(body)).await?; + Ok(serde_json::from_str(&text).unwrap_or(Value::String(text))) + } + + pub async fn delete(&self, path: &str) -> Result<Value, String> { + let text = self.request("DELETE", path, None).await?; + Ok(serde_json::from_str(&text).unwrap_or(Value::String(text))) + } + + /// A workspace-scoped path: `ws("scripts/list")` is `/w/<workspace>/scripts/list`. + pub fn ws(&self, rest: &str) -> String { + format!("/w/{}/{}", self.w_id, rest) + } + + /// A Windmill page in this workspace, as a link the user can open: an external client + /// has no preview panel, so a link is how it shows what a tool made or ran. + pub fn page_url(&self, page: &str) -> String { + let (page, hash) = page + .split_once('#') + .map_or((page, None), |(p, h)| (p, Some(h))); + let sep = if page.contains('?') { '&' } else { '?' }; + let hash = hash.map(|h| format!("#{h}")).unwrap_or_default(); + // An instance that never set its base URL holds this placeholder, which no client + // can open; the host the client reached is the better guess then. + let base = windmill_common::BASE_URL.load(); + let base = match self.origin { + Some(origin) if base.as_str() == "http://localhost" => origin, + _ => base.as_str(), + }; + format!("{base}{page}{sep}workspace={}{hash}", enc(self.w_id)) + } +} + +/// Routes outside the workspace that a tool reads. +const INSTANCE_ROUTES: &[&str] = &[ + "/docs/", + "/embeddings/", + "/integrations/hub/", + "/scripts/hub/", + "/users/whoami", + "/workers/list", + "/workspaces/users", +]; + +/// The URL of an API call, refused unless it lands on the route its handler wrote. +/// +/// The JWT behind a call carries the caller's full rights, and paths embed arguments a +/// model chose: a `..` segment, or an id carrying `#`, would otherwise turn a read of +/// one job into a run of any script. A read-only or read-and-run token is held to its rule +/// here too, since that JWT carries neither. +fn guarded_url( + base: &str, + w_id: &str, + method: &str, + path: &str, + access: SessionAccess, +) -> Result<String, String> { + let refused = || format!("Refusing to call `{path}`: not a route of this tool"); + let route = path.split('?').next().unwrap_or_default(); + let in_workspace = route + .strip_prefix("/w/") + .and_then(|rest| rest.strip_prefix(w_id)) + .is_some_and(|rest| rest.starts_with('/')); + let workspace_is_plain = w_id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if path.contains('#') + || !workspace_is_plain + || !(in_workspace || INSTANCE_ROUTES.iter().any(|r| route.starts_with(r))) + { + return Err(refused()); + } + let url = format!("{base}/api{path}"); + let parsed = reqwest::Url::parse(&url).map_err(|_| refused())?; + // Parsing resolves dot segments, encoded or not: a path that changed went elsewhere. + if !parsed.path().ends_with(&format!("/api{route}")) { + return Err(refused()); + } + // Runs of deployed items by path only: the preview routes take code, so they are writes. + // A run also stores its secret arguments as expiring variables; the write tools that + // could create other variables are not offered to a read-and-run token. + let run_writes = method == "POST" + && ["jobs/run/p/", "jobs/run/f/"] + .iter() + .any(|run| route.starts_with(&format!("/w/{w_id}/{run}"))) + || method == "POST" && route == format!("/w/{w_id}/variables/create"); + let held_to_reads = match access { + SessionAccess::Full => false, + SessionAccess::ReadAndRun => !run_writes, + SessionAccess::ReadOnly => true, + }; + if held_to_reads { + windmill_api_auth::scopes::check_read_only_for_route(parsed.path(), method) + .map_err(|e| e.to_string())?; + } + Ok(url) +} + +/// A string argument, or the error the model gets for leaving it out. +pub(super) fn str_arg<'a>(args: &'a Value, name: &str) -> Result<&'a str, String> { + args.get(name) + .and_then(Value::as_str) + .ok_or_else(|| format!("Missing required string argument `{name}`")) +} + +pub(super) fn opt_str_arg<'a>(args: &'a Value, name: &str) -> Option<&'a str> { + args.get(name).and_then(Value::as_str) +} + +/// `JSON.stringify(value, null, 2)`, the form the session's tools return objects in. +pub(super) fn pretty(value: &Value) -> String { + serde_json::to_string_pretty(value).unwrap_or_default() +} + +/// Percent-encode one query-string value. +pub(super) fn enc(value: &str) -> String { + urlencoding::encode(value).into_owned() +} + +pub(super) fn bool_arg(args: &Value, name: &str) -> bool { + args.get(name).and_then(Value::as_bool).unwrap_or(false) +} + +/// Whether a `Ctx` error is the API answering 404. +pub(super) fn is_not_found(error: &str) -> bool { + error.starts_with("404: ") +} + +/// JavaScript truthiness, for the fields the session keeps only `if (value)`. +pub(super) fn truthy(value: Option<&Value>) -> bool { + match value { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(Value::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0), + Some(Value::String(s)) => !s.is_empty(), + Some(_) => true, + } +} + +/// `value ?? undefined`: the value unless it is missing or null. +pub(super) fn non_null(value: Option<&Value>) -> Option<&Value> { + value.filter(|v| !v.is_null()) +} + +/// Set `key` unless the value is JS `undefined`, which `JSON.stringify` drops. +pub(super) fn put(map: &mut Map<String, Value>, key: &str, value: Option<Value>) { + if let Some(value) = value { + map.insert(key.to_string(), value); + } +} + +/// The elements of an array; none for anything else. +pub(super) fn array(value: Option<&Value>) -> &[Value] { + value + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or_default() +} + +/// A value as a JS template literal prints it. +pub(super) fn js_str(value: &Value) -> String { + match value { + Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +/// `String.length`: UTF-16 code units. +pub(super) fn js_len(text: &str) -> usize { + text.encode_utf16().count() +} + +/// `text.slice(0, max)` in UTF-16 units, never splitting a character. +pub(super) fn js_head(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut units = 0; + for (i, c) in text.char_indices() { + units += c.len_utf16(); + if units > max { + return &text[..i]; + } + } + text +} + +/// `text.slice(-max)` in UTF-16 units, never splitting a character. +pub(super) fn js_tail(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut units = 0; + for (i, c) in text.char_indices().rev() { + units += c.len_utf16(); + if units > max { + return &text[i + c.len_utf8()..]; + } + } + text +} + +/// `*` any characters but `/`, `**` any characters, `?` one character but `/`. A pattern +/// without `/` is matched against the file name alone, so `*.tsx` finds nested files. +pub(super) fn matches_glob(subject: &str, glob: &str) -> bool { + let subject = if glob.contains('/') { + subject + } else { + subject.rsplit('/').next().unwrap_or(subject) + }; + let mut pattern = String::from("^"); + let mut chars = glob.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '*' if chars.peek() == Some(&'*') => { + chars.next(); + pattern.push_str(".*"); + } + '*' => pattern.push_str("[^/]*"), + '?' => pattern.push_str("[^/]"), + c => pattern.push_str(®ex::escape(c.encode_utf8(&mut [0; 4]))), + } + } + pattern.push('$'); + regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(subject)) +} + +pub(super) async fn call_session_tool( + ctx: &Ctx<'_>, + name: &str, + args: Value, +) -> BackendResult<CallToolResult> { + let Some(def) = TOOL_DEFS.iter().find(|def| def.name == name) else { + return Err(ErrorData::invalid_params( + format!("Unknown tool '{name}'"), + None, + )); + }; + if !allowed(def, ctx.access) { + let token = match ctx.access { + SessionAccess::ReadAndRun => "can only read and run deployed scripts and flows", + _ => "is read-only", + }; + return Err(ErrorData::invalid_request( + format!("Tool '{name}' changes or runs something, and this token {token}"), + None, + )); + } + let Some(result) = dispatch(ctx, name, &args).await else { + return Err(ErrorData::invalid_params( + format!("Tool '{name}' is not available on this server"), + None, + )); + }; + windmill_common::feature_usage::log_feature_usage("mcp_workspace", "tool_call", name); + Ok(match result { + Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]), + // Without the status code `Ctx` prefixes an API failure with, as the session reads it. + Err(message) => { + let body = workspace::api_message(&message); + let text = if body.is_empty() { &message } else { body }; + CallToolResult::error(vec![ContentBlock::text(text.to_string())]) + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_call_stays_on_the_route_its_handler_wrote() { + use SessionAccess::*; + let url = |method, path, access| guarded_url("http://h", "ws", method, path, access); + assert!(url("GET", "/w/ws/jobs_u/get/0191?no_logs=true", Full).is_ok()); + assert!(url("GET", "/docs/search?query=a%2Fb", ReadOnly).is_ok()); + for path in [ + "/w/ws/jobs_u/get/../../jobs/run_wait_result/p/u/a/b", + "/w/ws/jobs_u/get/%2e%2e/%2E%2E/variables/get_value/u/a/b", + "/w/ws/jobs_u/get/x#", + "/w/other/scripts/list", + "/w/ws", + "/settings/global/x", + "/docs/../users/tokens/list", + ] { + assert!(url("GET", path, Full).is_err(), "{path} should be refused"); + } + assert!(guarded_url("http://h", "a/../b", "GET", "/w/a/../b/scripts/list", Full).is_err()); + // A read-only token neither writes nor runs, whatever the tool. + assert!(url("POST", "/w/ws/drafts/update", ReadOnly).is_err()); + assert!(url("GET", "/w/ws/jobs/run_wait_result/p/u/a/b", ReadOnly).is_err()); + assert!(url("POST", "/w/ws/jobs/run/p/u/a/b", ReadOnly).is_err()); + // A read-and-run token runs deployed items by path, and writes nothing else: a + // preview takes code. + assert!(url("POST", "/w/ws/jobs/run/p/u/a/b", ReadAndRun).is_ok()); + assert!(url("POST", "/w/ws/jobs/run/f/u/a/b", ReadAndRun).is_ok()); + assert!(url("POST", "/w/ws/jobs/run/preview", ReadAndRun).is_err()); + assert!(url("POST", "/w/ws/drafts/update", ReadAndRun).is_err()); + assert!(url("POST", "/w/ws/variables/create", ReadAndRun).is_ok()); + assert!(url("POST", "/w/ws/variables/update/u/a/b", ReadAndRun).is_err()); + assert!(url("POST", "/w/ws/variables/create", ReadOnly).is_err()); + } + + #[test] + fn every_session_tool_is_implemented_or_editor_only() { + let implemented: Vec<&str> = implemented().collect(); + for def in TOOL_DEFS.iter() { + let name = def.name.as_str(); + assert!( + implemented.contains(&name) != EDITOR_ONLY.contains(&name), + "session tool `{name}` must be implemented here or listed in EDITOR_ONLY, not both" + ); + } + for name in implemented.iter().chain(EDITOR_ONLY) { + assert!( + TOOL_DEFS.iter().any(|def| def.name == *name), + "`{name}` is not a session tool any more" + ); + } + } +} diff --git a/backend/windmill-api/src/mcp/session/runs.rs b/backend/windmill-api/src/mcp/session/runs.rs new file mode 100644 index 0000000000..10f1c7e224 --- /dev/null +++ b/backend/windmill-api/src/mcp/session/runs.rs @@ -0,0 +1,2009 @@ +//! Running scripts and flows, test runs on drafts, and reading runs back. + +use std::collections::HashMap; +use std::time::Duration; + +use serde::Serialize; +use serde_json::{json, Map, Value}; + +use super::workspace::{ + api_message, get_draft, infer_script_schema, load_flow, load_script, path_enc, +}; +use super::{enc, js_head, js_len, js_tail, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult}; + +pub(super) const TOOLS: &[&str] = &[ + "test_run_script", + "run_script", + "test_run_flow", + "run_flow", + "test_run_step", + "list_runs", + "get_run", + "cancel_job", +]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "test_run_script" => test_run_script(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, + "test_run_step" => test_run_step(ctx, args).await, + "list_runs" => list_runs(ctx, args).await, + "get_run" => get_run(ctx, args).await, + "cancel_job" => cancel_job(ctx, args).await, + _ => unreachable!("{name} is not a runs tool"), + } +} + +const MAX_RESULT_LENGTH: usize = 12000; +const MAX_LOG_LENGTH: usize = 4000; +const DEFAULT_WAIT_MS: f64 = 15000.0; +const MAX_WAIT_MS: f64 = 120000.0; +const MAX_SUBMITTED_ARGS_LENGTH: usize = 4000; + +/// `JSON.stringify(value, null, 1)`, the indent `get_run` renders with. +fn pretty1(value: &Value) -> String { + let mut out = Vec::new(); + let formatter = serde_json::ser::PrettyFormatter::with_indent(b" "); + let mut serializer = serde_json::Serializer::with_formatter(&mut out, formatter); + value + .serialize(&mut serializer) + .expect("a JSON value serializes"); + String::from_utf8(out).unwrap_or_default() +} + +// ============================================================================ +// Job helpers shared with the other groups. +// ============================================================================ + +fn job_id(response: Value) -> String { + match response { + Value::String(id) => id.trim().to_string(), + other => other.to_string(), + } +} + +/// Queue a script preview and return its job id. `path` files the run under an item. +pub(super) async fn run_script_preview( + ctx: &Ctx<'_>, + path: Option<&str>, + language: &str, + content: &str, + args: Value, +) -> Result<String, String> { + let mut body = Map::new(); + if let Some(path) = path { + body.insert("path".into(), path.into()); + } + body.insert("content".into(), content.into()); + body.insert("language".into(), language.into()); + body.insert("args".into(), args); + ctx.post(&ctx.ws("jobs/run/preview"), Value::Object(body)) + .await + .map(job_id) +} + +/// Queue a flow preview of `value` and return its job id. `memory_id` names the +/// conversation a chat-enabled flow's run belongs to. +pub(super) async fn run_flow_preview( + ctx: &Ctx<'_>, + path: Option<&str>, + value: &Value, + args: Value, + memory_id: Option<&str>, +) -> Result<String, String> { + let mut body = Map::new(); + if let Some(path) = path { + body.insert("path".into(), path.into()); + } + body.insert("value".into(), value.clone()); + body.insert("args".into(), args); + let query = memory_id + .map(|id| format!("?memory_id={}", enc(id))) + .unwrap_or_default(); + ctx.post( + &ctx.ws(&format!("jobs/run/preview_flow{query}")), + Value::Object(body), + ) + .await + .map(job_id) +} + +/// How many seconds a run tool waits before leaving the job in the background, from +/// its `background` and `wait_seconds` arguments: 15 by default, 120 at most. +pub(super) fn wait_budget(tool_args: &Value) -> u64 { + if tool_args.get("background").and_then(Value::as_bool) == Some(true) { + return 0; + } + let ms = tool_args + .get("wait_seconds") + .and_then(Value::as_f64) + .map_or(DEFAULT_WAIT_MS, |seconds| seconds.max(0.0) * 1000.0) + .min(MAX_WAIT_MS); + (ms / 1000.0).ceil() as u64 +} + +/// Poll a job once a second for up to `seconds`. The completed job, fetched once more +/// with its logs when `logs` is set, or `None` when it is still running by then. A +/// failed poll is retried on the next tick. +pub(super) async fn wait_job(ctx: &Ctx<'_>, id: &str, seconds: u64, logs: bool) -> Option<Value> { + let path = |no_logs: bool| { + ctx.ws(&format!( + "jobs_u/get/{}?no_logs={no_logs}&no_code=true", + enc(id) + )) + }; + for _ in 0..seconds { + tokio::time::sleep(Duration::from_secs(1)).await; + if let Ok(job) = ctx.get(&path(true)).await { + if job["type"] == "CompletedJob" { + return Some(match logs { + true => ctx.get(&path(false)).await.unwrap_or(job), + false => job, + }); + } + } + } + None +} + +/// What the model reads for a job that outlived its wait. +pub(super) fn backgrounded_summary(id: &str, label: &str) -> String { + format!( + "Job {id} for \"{label}\" is taking a while and is now running in the background. \ + To inspect it, call get_run with id=\"{id}\" (or list_runs); \ + to stop it, call cancel_job with id=\"{id}\"." + ) +} + +/// A job result as text: a string as it is, anything else as indented JSON. +pub(super) fn format_result(result: Option<&Value>) -> String { + match result { + Some(Value::String(text)) => text.clone(), + other => pretty(other.unwrap_or(&Value::Null)), + } +} + +/// The last 4000 chars of a job's logs, or `None` when it logged nothing. +pub(super) fn format_logs(logs: Option<&str>) -> Option<&str> { + logs.filter(|logs| !logs.trim().is_empty()) + .map(|logs| js_tail(logs, MAX_LOG_LENGTH)) +} + +/// A completed job as the run tools report it: outcome, result head (12k chars) and +/// logs tail. +pub(super) fn format_result_summary(job: &Value) -> String { + let success = truthy(job.get("success")); + let result = format_result(job.get("result")); + format!( + "Result ({})\n\n{}\n\nLogs:\n\n{}", + if success { "SUCCESS" } else { "FAILED" }, + js_head(&result, MAX_RESULT_LENGTH), + format_logs(job.get("logs").and_then(Value::as_str)).unwrap_or("No logs available"), + ) +} + +/// Settle a just-queued job (`started` is the queueing call's answer) into a run +/// tool's result: wait within the tool's budget, then the result summary or the +/// background notice. `action` is `test` or `run`, `label` names the job in the notice. +pub(super) async fn finish_run( + ctx: &Ctx<'_>, + started: Result<String, String>, + label: &str, + is_flow: bool, + action: &str, + tool_args: &Value, +) -> ToolResult { + let id = started.map_err(|e| format!("Failed to execute {action}: {}", api_message(&e)))?; + let run_page = format!("\n\nRun page: {}", ctx.page_url(&format!("/run/{id}"))); + let Some(job) = wait_job(ctx, &id, wait_budget(tool_args), true).await else { + return Ok(format!("{}{run_page}", backgrounded_summary(&id, label))); + }; + let mut summary = format_result_summary(&job); + if is_flow && !truthy(job.get("success")) { + summary.push_str(&format!( + "\n\nFor per-step statuses and results (subflow steps included), call get_run with id=\"{id}\"." + )); + } + summary.push_str(&run_page); + Ok(summary) +} + +// ============================================================================ +// Arguments: conformed to the schema of what is about to run, secrets minted. +// ============================================================================ + +const REFERENCE_PREFIXES: [&str; 3] = ["$var:", "$res:", "$jsonvar:"]; + +fn is_reference(value: &Value) -> bool { + value.as_str().is_some_and(|s| { + REFERENCE_PREFIXES + .iter() + .any(|prefix| s.starts_with(prefix)) + }) +} + +fn is_secret_prop(prop: &Value) -> bool { + truthy(prop.get("password")) +} + +fn is_file_prop(prop: &Value) -> bool { + prop["contentEncoding"] == "base64" || prop["items"]["contentEncoding"] == "base64" +} + +/// Apply `visit` to every value whose declaration matches `is_leaf`, at any depth; +/// `None` removes it. Descends on the value's shape, through every `oneOf` branch. +fn map_leaves( + value: &Value, + prop: Option<&Value>, + is_leaf: fn(&Value) -> bool, + visit: &mut dyn FnMut(&Value, &Value, &[Value]) -> Option<Value>, + path: &mut Vec<Value>, +) -> Value { + let items = prop.and_then(|p| p.get("items")).filter(|v| !v.is_null()); + match value { + Value::Array(list) => Value::Array( + list.iter() + .enumerate() + .map(|(i, item)| { + path.push(json!(i)); + let mapped = map_leaves(item, items.or(prop), is_leaf, visit, path); + path.pop(); + mapped + }) + .collect(), + ), + Value::Object(map) => { + let mut bags: Vec<&Map<String, Value>> = Vec::new(); + if let Some(properties) = prop.and_then(|p| p["properties"].as_object()) { + bags.push(properties); + } + for branch in prop + .and_then(|p| p["oneOf"].as_array()) + .into_iter() + .flatten() + { + if let Some(properties) = branch["properties"].as_object() { + bags.push(properties); + } + } + if bags.is_empty() { + return match items { + Some(items) => map_leaves(value, Some(items), is_leaf, visit, path), + None => value.clone(), + }; + } + let mut result = Map::new(); + for (key, current) in map { + let declared: Vec<&Value> = bags.iter().filter_map(|bag| bag.get(key)).collect(); + path.push(json!(key)); + if let Some(leaf) = declared.iter().find(|d| is_leaf(d)) { + if let Some(mapped) = visit(current, leaf, path) { + result.insert(key.clone(), mapped); + } + } else { + let mut mapped = current.clone(); + for declaration in declared { + mapped = map_leaves(&mapped, Some(declaration), is_leaf, visit, path); + } + result.insert(key.clone(), mapped); + } + path.pop(); + } + Value::Object(result) + } + other => other.clone(), + } +} + +fn map_arg_leaves( + args: &Map<String, Value>, + schema: &Value, + is_leaf: fn(&Value) -> bool, + visit: &mut dyn FnMut(&Value, &Value, &[Value]) -> Option<Value>, +) -> Map<String, Value> { + let root = json!({ "properties": schema.get("properties").filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})) }); + match map_leaves( + &Value::Object(args.clone()), + Some(&root), + is_leaf, + visit, + &mut Vec::new(), + ) { + Value::Object(map) => map, + _ => Map::new(), + } +} + +/// `$var:` hands the job the variable's text and `$jsonvar:` the parsed value, which a +/// field that cannot hold a string needs. +fn reference_prefix(prop: &Value, value: &Value) -> &'static str { + if value.is_string() && prop["type"] != "object" && prop["type"] != "array" { + "$var:" + } else { + "$jsonvar:" + } +} + +/// Turn every sensitive argument into a reference: a literal is minted into a secret +/// variable that expires on its own, so the job's stored arguments name a secret +/// instead of holding one. +async fn process_secret_args( + ctx: &Ctx<'_>, + args: Map<String, Value>, + schema: &Value, +) -> Result<Map<String, Value>, String> { + if !schema.get("properties").is_some_and(Value::is_object) { + return Ok(args); + } + let username = ctx.auth.username.split('@').next().unwrap_or_default(); + if username.is_empty() { + return Ok(args); + } + + let mut pending: Vec<(String, &'static str, Value)> = Vec::new(); + map_arg_leaves(&args, schema, is_secret_prop, &mut |value, prop, path| { + let holds_secret = !value.is_null() && value != "" && !is_reference(value); + if holds_secret { + pending.push(( + Value::from(path).to_string(), + reference_prefix(prop, value), + value.clone(), + )); + } + Some(value.clone()) + }); + + let mut minted: HashMap<String, String> = HashMap::new(); + for (key, prefix, value) in pending { + let variable = format!( + "u/{username}/secret_arg/{}", + windmill_common::utils::rd_string(12) + ); + let secret = match &value { + Value::String(text) if prefix == "$var:" => text.clone(), + other => other.to_string(), + }; + let expires_at = (chrono::Utc::now() + chrono::Duration::days(7)) + .to_rfc3339_opts(chrono::SecondsFormat::Millis, true); + ctx.post( + &ctx.ws("variables/create"), + json!({ + "value": secret, + "is_secret": true, + "path": variable, + "description": "Ephemeral secret variable", + "expires_at": expires_at, + }), + ) + .await?; + minted.insert(key, format!("{prefix}{variable}")); + } + + Ok(map_arg_leaves( + &args, + schema, + is_secret_prop, + &mut |value, prop, path| { + if let Some(reference) = minted.get(&Value::from(path).to_string()) { + return Some(reference.as_str().into()); + } + // A plain variable named for a field that cannot hold a string: its contents + // are meant, read the way the field needs them. + match value.as_str().and_then(|s| s.strip_prefix("$var:")) { + Some(variable) if reference_prefix(prop, value) == "$jsonvar:" => { + Some(format!("$jsonvar:{variable}").into()) + } + _ => Some(value.clone()), + } + }, + )) +} + +fn file_marker(base64: &str) -> String { + let bytes = js_len(base64) * 3 / 4; + if bytes < 1024 * 1024 { + format!( + "<file: {} KB>", + ((bytes as f64 / 1024.0).round() as usize).max(1) + ) + } else { + format!("<file: {:.1} MB>", bytes as f64 / 1024.0 / 1024.0) + } +} + +/// The arguments as the model may read them back: secrets hidden, file bytes replaced +/// by their size. +fn redact_args(args: &Map<String, Value>, schema: &Value) -> Map<String, Value> { + let secrets = map_arg_leaves( + args, + schema, + is_secret_prop, + &mut |value, _, _| match value { + Value::Null => None, + value if value == "" || is_reference(value) => Some(value.clone()), + _ => Some("<hidden>".into()), + }, + ); + let mark = |value: &Value| match value { + Value::String(base64) => file_marker(base64).into(), + other => other.clone(), + }; + map_arg_leaves( + &secrets, + schema, + is_file_prop, + &mut |value, _, _| match value { + Value::Array(files) => Some(files.iter().map(mark).collect()), + other => Some(mark(other)), + }, + ) +} + +/// Keep the arguments the schema declares, naming the rest. A schema without +/// `properties` declares nothing. +fn drop_undeclared_args( + args: Map<String, Value>, + schema: &Value, +) -> (Map<String, Value>, Vec<String>) { + let properties = schema.get("properties").and_then(Value::as_object); + let mut undeclared = Vec::new(); + let kept = args + .into_iter() + .filter(|(key, _)| { + let declared = properties.is_some_and(|p| p.contains_key(key)); + if !declared { + undeclared.push(key.clone()); + } + declared + }) + .collect(); + (kept, undeclared) +} + +/// A field the schema disables is not the caller's to set: the run sends its default. +/// Returns the keys whose proposed value was overwritten. +fn enforce_disabled_defaults(args: &mut Map<String, Value>, schema: &Value) -> Vec<String> { + let mut reset = Vec::new(); + for (key, prop) in schema + .get("properties") + .and_then(Value::as_object) + .into_iter() + .flatten() + { + let (true, Some(default)) = (truthy(prop.get("disabled")), prop.get("default")) else { + continue; + }; + if args.get(key).is_some_and(|proposed| proposed != default) { + reset.push(key.clone()); + } + args.insert(key.clone(), default.clone()); + } + reset +} + +struct Prepared { + args: Map<String, Value>, + /// Lines telling the model how what ran differs from what it proposed. + notes: Vec<String>, +} + +fn plural<'a>(keys: &[String], one: &'a str, many: &'a str) -> &'a str { + if keys.len() > 1 { + many + } else { + one + } +} + +/// The arguments a run carries, from the ones proposed. `schema` is the input schema +/// of the version about to run; `None` when it is unknown, which conforms nothing. +/// `Err` is the message the tool returns when a secret could not be stored. +async fn prepare_args( + ctx: &Ctx<'_>, + path: &str, + proposed: Map<String, Value>, + schema: Option<&Value>, + schema_noun: &str, +) -> Result<Prepared, String> { + let Some(schema) = schema else { + return Ok(Prepared { args: proposed, notes: Vec::new() }); + }; + let (mut args, undeclared) = drop_undeclared_args(proposed.clone(), schema); + let reset = enforce_disabled_defaults(&mut args, schema); + let args = process_secret_args(ctx, args, schema).await.map_err(|e| { + format!( + "Failed to store the sensitive arguments of \"{path}\": {}", + api_message(&e) + ) + })?; + + let mut notes = Vec::new(); + let redacted = redact_args(&args, schema); + if redacted != proposed { + let json = Value::Object(redacted).to_string(); + notes.push(if js_len(&json) > MAX_SUBMITTED_ARGS_LENGTH { + format!( + "Ran with arguments: {}... (truncated)", + js_head(&json, MAX_SUBMITTED_ARGS_LENGTH) + ) + } else { + format!("Ran with arguments: {json}") + }); + } + if !reset.is_empty() { + notes.push(format!( + "The {schema_noun} schema disables {}, so the run used {} rather than the proposed {}. Do not propose {} again.", + reset.join(", "), + plural(&reset, "its default", "their defaults"), + plural(&reset, "value", "values"), + plural(&reset, "it", "them"), + )); + } + if !undeclared.is_empty() { + notes.push(format!( + "The {schema_noun} schema does not declare {}, so {} not sent. Re-read the input schema and use the arguments it declares.", + undeclared.join(", "), + plural(&undeclared, "it was", "they were"), + )); + } + Ok(Prepared { args, notes }) +} + +fn proposed_args(tool_args: &Value) -> Map<String, Value> { + tool_args + .get("args") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default() +} + +fn has_properties(schema: Option<&Value>) -> bool { + schema + .and_then(|s| s.get("properties")) + .and_then(Value::as_object) + .is_some_and(|p| !p.is_empty()) +} + +/// The input schema a test run conforms its arguments to: the stored one where it +/// declares fields and speaks for the entrypoint about to run, else inferred from the +/// code. `None` when this build has no parser for the language. +fn schema_for_test_run( + language: &str, + content: &str, + stored: Option<Value>, + entrypoint: Option<&str>, +) -> Option<Value> { + if entrypoint.is_none() && has_properties(stored.as_ref()) { + return stored; + } + infer_script_schema(language, content, None, entrypoint) +} + +async fn conclude( + ctx: &Ctx<'_>, + tool_args: &Value, + mut notes: Vec<String>, + started: Result<String, String>, + label: &str, + is_flow: bool, + action: &str, +) -> ToolResult { + notes.push(finish_run(ctx, started, label, is_flow, action, tool_args).await?); + Ok(notes.join("\n")) +} + +// ============================================================================ +// Scripts and flows +// ============================================================================ + +async fn test_run_script(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let script = load_script(ctx, path).await?; + let schema = schema_for_test_run(&script.language, &script.content, script.schema, None); + let prepared = + match prepare_args(ctx, path, proposed_args(args), schema.as_ref(), "script").await { + Ok(prepared) => prepared, + Err(message) => return Ok(message), + }; + let started = run_script_preview( + ctx, + Some(path), + &script.language, + &script.content, + Value::Object(prepared.args), + ) + .await; + conclude(ctx, args, prepared.notes, started, path, false, "test").await +} + +/// `run_script` and `run_flow`: the deployed item, whatever draft sits on top of it. +async fn run_deployed(ctx: &Ctx<'_>, args: &Value, is_flow: bool) -> ToolResult { + let path = str_arg(args, "path")?; + let (get, run) = if is_flow { + ("flows/get", "jobs/run/f") + } else { + ("scripts/get/p", "jobs/run/p") + }; + let item = ctx + .get(&ctx.ws(&format!("{get}/{}", path_enc(path)))) + .await?; + let schema = item + .get("schema") + .filter(|s| !s.is_null()) + .cloned() + .unwrap_or_else(|| json!({})); + let prepared = + match prepare_args(ctx, path, proposed_args(args), Some(&schema), "deployed").await { + Ok(prepared) => prepared, + Err(message) => return Ok(message), + }; + // A chat-enabled flow is refused without a conversation, and this run is one of its own. + let memory_id = if is_flow && truthy(item["value"].get("chat_input_enabled")) { + format!("&memory_id={}", uuid::Uuid::new_v4()) + } else { + String::new() + }; + // The arguments fill the main input schema; a preprocessor would take them for a + // trigger event. + let started = ctx + .post( + &ctx.ws(&format!( + "{run}/{}?skip_preprocessor=true{memory_id}", + path_enc(path) + )), + Value::Object(prepared.args), + ) + .await + .map(job_id); + conclude(ctx, args, prepared.notes, started, path, is_flow, "run").await +} + +/// The flow value a preview runs, from a loaded `{value, schema, groups}`. +fn flow_preview_value(flow: &Value) -> Value { + let mut value = flow.get("value").cloned().unwrap_or_else(|| json!({})); + if let (Some(groups), Some(map)) = (flow.get("groups"), value.as_object_mut()) { + if groups.is_null() { + map.remove("groups"); + } else { + map.insert("groups".into(), groups.clone()); + } + } + value +} + +async fn test_run_flow(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let memory_id = opt_str_arg(args, "memory_id"); + if memory_id.is_some_and(|id| id.len() != 36 || uuid::Uuid::parse_str(id).is_err()) { + return Err("memory_id must be a UUID".to_string()); + } + let flow = load_flow(ctx, path).await?; + let schema = flow + .flow + .get("schema") + .filter(|s| !s.is_null()) + .cloned() + .unwrap_or_else(|| json!({})); + let prepared = match prepare_args(ctx, path, proposed_args(args), Some(&schema), "flow").await { + Ok(prepared) => prepared, + Err(message) => return Ok(message), + }; + let value = flow_preview_value(&flow.flow); + // The server refuses a chat-enabled flow's run without a conversation; a test run + // is one of its own unless the caller names another. + let memory_id = memory_id.map(String::from).or_else(|| { + truthy(value.get("chat_input_enabled")).then(|| uuid::Uuid::new_v4().to_string()) + }); + let started = run_flow_preview( + ctx, + Some(path), + &value, + Value::Object(prepared.args), + memory_id.as_deref(), + ) + .await; + conclude(ctx, args, prepared.notes, started, path, true, "test").await +} + +// ============================================================================ +// One step of a flow +// ============================================================================ + +fn modules_of<'a>(value: &'a Value, key: &str) -> impl Iterator<Item = &'a Value> { + value[key].as_array().into_iter().flatten() +} + +/// The modules nested directly under one: loop bodies, branches, and an agent's +/// flow-module tools. +fn child_modules(module: &Value, with_tools: bool) -> Vec<&Value> { + let value = &module["value"]; + let branches = || modules_of(value, "branches").flat_map(|b| modules_of(b, "modules")); + match value["type"].as_str() { + Some("forloopflow" | "whileloopflow") => modules_of(value, "modules").collect(), + Some("branchall") => branches().collect(), + Some("branchone") => branches().chain(modules_of(value, "default")).collect(), + Some("aiagent") if with_tools => modules_of(value, "tools") + .filter(|tool| { + matches!(tool["value"].get("tool_type"), None | Some(Value::Null)) + || tool["value"]["tool_type"] == "flowmodule" + }) + .collect(), + _ => Vec::new(), + } +} + +fn find_in_modules<'a>(modules: Vec<&'a Value>, id: &str) -> Option<&'a Value> { + modules.into_iter().find_map(|module| { + if module["id"] == id { + Some(module) + } else { + find_in_modules(child_modules(module, true), id) + } + }) +} + +fn find_module<'a>(flow: &'a Value, id: &str) -> Option<&'a Value> { + ["failure_module", "preprocessor_module"] + .iter() + .map(|key| &flow[*key]) + .find(|module| module["id"] == id) + .or_else(|| find_in_modules(modules_of(flow, "modules").collect(), id)) +} + +fn available_step_ids(flow: &Value) -> String { + fn collect<'a>(modules: Vec<&'a Value>, ids: &mut Vec<&'a str>) { + for module in modules { + ids.extend(module["id"].as_str()); + collect(child_modules(module, false), ids); + } + } + let mut ids = Vec::new(); + collect(modules_of(flow, "modules").collect(), &mut ids); + ids.extend(flow["preprocessor_module"]["id"].as_str()); + ids.extend(flow["failure_module"]["id"].as_str()); + let mut seen = Vec::new(); + for id in ids { + if !seen.contains(&id) { + seen.push(id); + } + } + seen.join(", ") +} + +/// The agent form's rows in its own order: key, whether an agent always has it, and +/// the value a run cannot tell apart from an absent key. +fn agent_fields() -> [(&'static str, bool, Option<Value>); 16] { + [ + ("provider", true, None), + ("temperature", false, None), + ("max_completion_tokens", false, None), + ("user_message", true, None), + ("system_prompt", true, None), + ("memory", false, Some(json!({ "kind": "off" }))), + ("memory_id", false, Some(json!(""))), + ("previous_messages", false, Some(json!([]))), + ("user_attachments", false, Some(json!([]))), + ("enabled_tools", false, None), + ("max_iterations", false, Some(json!(10))), + ("output_type", false, Some(json!("text"))), + ("output_schema", false, None), + ("streaming", false, Some(json!(true))), + ("model", false, Some(json!(""))), + ("reasoning_effort", false, Some(json!(""))), + ] +} + +/// The inputs a step linked to a saved agent supplies itself; the rest is the agent's. +const AGENT_FLOW_LOCAL_KEYS: [&str; 5] = [ + "user_message", + "user_attachments", + "enabled_tools", + "memory_id", + "previous_messages", +]; +const AGENT_HISTORY_KEYS: [&str; 2] = ["memory_id", "previous_messages"]; +/// A linked step's overrides of what its agent saved; an unlinked step has no such inputs. +const AGENT_OVERRIDE_KEYS: [&str; 2] = ["model", "reasoning_effort"]; + +/// Older spellings of two agent inputs, read as the current ones. +fn migrate_agent_transforms(transforms: &mut Map<String, Value>) { + if !transforms.contains_key("user_attachments") { + if let Some(images) = transforms.remove("user_images") { + transforms.insert("user_attachments".into(), images); + } + } + if transforms.contains_key("memory") { + return; + } + let Some(legacy) = transforms.get("messages_context_length").cloned() else { + return; + }; + if legacy.is_null() { + return; + } + match legacy["type"].as_str() { + Some("static") => { + let length = legacy.get("value").filter(|v| !v.is_null()).cloned(); + transforms.insert( + "memory".into(), + json!({ "type": "static", "value": { "kind": "auto", "context_length": length.unwrap_or(json!(0)) } }), + ); + } + Some("javascript") => { + let expr = legacy["expr"].as_str().unwrap_or("undefined"); + transforms.insert( + "memory".into(), + json!({ "type": "javascript", "expr": format!("{{ kind: 'auto', context_length: {expr} }}") }), + ); + } + _ => {} + } + transforms.remove("messages_context_length"); +} + +/// The inputs a test run of an agent step takes, in the agent form's order, and the +/// values the step itself configures for them. A row is one the step sets, an agent +/// always has, or the caller proposed. +fn agent_step_form( + module_value: &Value, + proposed: &Map<String, Value>, +) -> (Vec<String>, Map<String, Value>) { + let transforms = module_value.get("input_transforms"); + let linked = truthy(module_value.get("agent")); + let mut keys = Vec::new(); + let mut args = Map::new(); + for (key, core, implicit) in agent_fields() { + let override_key = AGENT_OVERRIDE_KEYS.contains(&key); + let applies = if linked { + override_key || AGENT_FLOW_LOCAL_KEYS.contains(&key) + } else { + !override_key + }; + if !applies { + continue; + } + let transform = transforms.and_then(|t| t.get(key)); + let is_set = core + || match transform.and_then(|t| t["type"].as_str()) { + Some("javascript") => truthy(transform.and_then(|t| t.get("expr"))), + Some("ai") => true, + _ => transform + .filter(|t| t.is_object()) + .and_then(|t| t.get("value")) + .is_some_and(|value| !value.is_null() && Some(value) != implicit.as_ref()), + }; + if !is_set && !proposed.contains_key(key) { + continue; + } + keys.push(key.to_string()); + // ponytail: only a static input opens on its value. An expression is evaluated by + // the session with no flow input or earlier results, so all but a literal one + // reads as unset there too; evaluate it here if literal expressions matter. + if let Some(value) = transform + .filter(|t| t["type"] == "static") + .and_then(|t| t.get("value")) + { + args.insert(key.to_string(), value.clone()); + } + } + for (key, value) in proposed { + args.insert(key.clone(), value.clone()); + } + // An absent `enabled_tools` runs every tool and `[]` none, and the row is fed from + // the run's arguments either way. + if keys.iter().any(|key| key == "enabled_tools") + && args.get("enabled_tools").is_none_or(Value::is_null) + { + args.insert("enabled_tools".into(), json!([])); + } + (keys, args) +} + +/// The input transforms a one-off test of an agent step runs with: each form key fed +/// from `flow_input`, over the step's own. A blank history input is unset. +fn agent_test_transforms( + step: Option<&Value>, + args: &Map<String, Value>, + form_keys: &[String], +) -> Map<String, Value> { + let kept = |key: &str| { + let blank = match args.get(key) { + None | Some(Value::Null) => true, + Some(Value::String(s)) => s.is_empty(), + Some(Value::Array(a)) => a.is_empty(), + Some(_) => false, + }; + !AGENT_HISTORY_KEYS.contains(&key) || !blank + }; + let mut out: Map<String, Value> = step + .and_then(Value::as_object) + .into_iter() + .flatten() + .filter(|(key, _)| kept(key)) + .map(|(key, transform)| (key.clone(), transform.clone())) + .collect(); + for key in form_keys.iter().filter(|key| kept(key)) { + out.insert( + key.clone(), + json!({ "type": "javascript", "expr": format!("flow_input.{key}") }), + ); + } + out +} + +fn normalize_agent_ref(agent: &str) -> &str { + let agent = agent.strip_prefix("$res:").unwrap_or(agent); + agent.strip_prefix("res://").unwrap_or(agent) +} + +fn linked_agent_paths(module: &Value, paths: &mut Vec<String>) { + let value = &module["value"]; + if value["type"] != "aiagent" { + return; + } + if let Some(agent) = value["agent"].as_str().filter(|a| !a.is_empty()) { + let path = normalize_agent_ref(agent).to_string(); + if !paths.contains(&path) { + paths.push(path); + } + } + for tool in modules_of(value, "tools") { + linked_agent_paths(tool, paths); + } +} + +fn inline_agent_draft(module: &mut Value, drafts: &HashMap<String, Value>) { + let value = &mut module["value"]; + if value["type"] != "aiagent" { + return; + } + let draft = value["agent"] + .as_str() + .and_then(|agent| drafts.get(normalize_agent_ref(agent))); + if let (Some(draft), Some(map)) = (draft, value.as_object_mut()) { + map.remove("agent"); + let mut transforms = Map::new(); + for (key, arg) in draft.as_object().into_iter().flatten() { + if key != "tools" && !AGENT_HISTORY_KEYS.contains(&key.as_str()) { + transforms.insert(key.clone(), json!({ "type": "static", "value": arg })); + } + } + for key in AGENT_FLOW_LOCAL_KEYS.into_iter().chain(AGENT_OVERRIDE_KEYS) { + if let Some(own) = map + .get("input_transforms") + .and_then(|t| t.get(key)) + .filter(|t| truthy(Some(t))) + { + transforms.insert(key.to_string(), own.clone()); + } + } + map.insert( + "tools".into(), + draft + .get("tools") + .filter(|t| !t.is_null()) + .cloned() + .unwrap_or_else(|| json!([])), + ); + map.insert("input_transforms".into(), Value::Object(transforms)); + } + if let Some(tools) = value.get_mut("tools").and_then(Value::as_array_mut) { + for tool in tools { + inline_agent_draft(tool, drafts); + } + } +} + +/// Replace every linked agent that has an unsaved draft with the draft's own +/// configuration, so the test runs what the agent editor shows. +async fn with_agent_drafts(ctx: &Ctx<'_>, module: &mut Value) -> Result<(), String> { + let mut paths = Vec::new(); + linked_agent_paths(module, &mut paths); + let mut drafts = HashMap::new(); + for path in paths { + let route = ctx.ws(&format!("resources/get/{}?get_draft=true", path_enc(&path))); + match ctx.get(&route).await { + Ok(resource) => { + if let Some(draft) = resource.get("draft").filter(|d| !d.is_null()) { + drafts.insert( + path, + draft.get("args").cloned().unwrap_or_else(|| json!({})), + ); + } + } + // A deleted or unreadable agent is an ordinary state of a link: the step + // then runs against whatever is deployed. + Err(e) if ["401", "403", "404"].iter().any(|s| e.starts_with(s)) => {} + Err(e) => return Err(format!("Could not load the agent {path}: {e}")), + } + } + inline_agent_draft(module, &drafts); + Ok(()) +} + +async fn test_run_step(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let step_id = str_arg(args, "stepId")?; + let flow_value = flow_preview_value(&load_flow(ctx, path).await?.flow); + let Some(module) = find_module(&flow_value, step_id) else { + return Err(format!( + "Step with id \"{step_id}\" not found in flow. Available steps: {}", + available_step_ids(&flow_value) + )); + }; + let value = &module["value"]; + let module_type = value["type"].as_str().unwrap_or_default(); + let text = |key: &str| value[key].as_str().unwrap_or_default().to_string(); + // A preprocessor takes the arguments of its own entrypoint, which no schema declares. + let entrypoint = (module["id"] == "preprocessor").then_some("preprocessor"); + let label = format!("step {step_id}"); + let proposed = proposed_args(args); + + let (schema, proposed) = match module_type { + "rawscript" => ( + schema_for_test_run(&text("language"), &text("content"), None, entrypoint), + proposed, + ), + "script" | "flow" | "aidecision" => (None, proposed), + "aiagent" => { + let (keys, args) = agent_step_form(&migrated_agent_value(value), &proposed); + let properties: Map<String, Value> = + keys.into_iter().map(|key| (key, json!({}))).collect(); + (Some(json!({ "properties": properties })), args) + } + other => { + return Err(format!( + "Cannot test step of type \"{other}\". Supported types: rawscript, script, flow, aiagent, aidecision" + )); + } + }; + + // The targets read from the workspace, each with the schema of what will run. + let mut script = None; + let mut subflow_preview = None; + let schema = match module_type { + "script" => { + let target = text("path"); + let hash = value["hash"].as_str().filter(|h| !h.is_empty()); + // A draft of the script runs even where the step pins a hash. + let loaded = match hash { + Some(hash) if get_draft(ctx, "script", &target).await?.is_none() => { + let deployed = ctx + .get(&ctx.ws(&format!("scripts/get/h/{}", enc(hash)))) + .await?; + ( + deployed["content"].as_str().unwrap_or_default().to_string(), + deployed["language"] + .as_str() + .unwrap_or_default() + .to_string(), + deployed.get("schema").filter(|s| !s.is_null()).cloned(), + ) + } + _ => { + let loaded = load_script(ctx, &target).await?; + (loaded.content, loaded.language, loaded.schema) + } + }; + let schema = schema_for_test_run(&loaded.1, &loaded.0, loaded.2, entrypoint); + script = Some((target, loaded.0, loaded.1)); + schema + } + "flow" => { + // Only a draft is previewed; a deployed subflow runs by path, as its parent + // flow would run it. + let subflow = load_flow(ctx, &text("path")).await?; + if subflow.is_draft { + subflow_preview = Some(flow_preview_value(&subflow.flow)); + } + Some( + subflow + .flow + .get("schema") + .filter(|s| !s.is_null()) + .cloned() + .unwrap_or_else(|| json!({})), + ) + } + // What a run supplies is the state; the provider and questions are the step's own. + "aidecision" => Some(json!({ "properties": { "state": {} } })), + _ => schema, + }; + + let prepared = match prepare_args(ctx, path, proposed, schema.as_ref(), "step").await { + Ok(prepared) => prepared, + Err(message) => return Ok(message), + }; + let mut run_args = prepared.args; + let with_entrypoint = |args: Map<String, Value>| { + let mut out = Map::new(); + if entrypoint.is_some() { + out.insert("_ENTRYPOINT_OVERRIDE".into(), "preprocessor".into()); + } + out.extend(args); + Value::Object(out) + }; + // Run alone, stripped of the settings around it: a mock would answer for the step + // and a suspend would hold the run for an approval. + let single_step = + |step_value: Value| json!({ "modules": [{ "id": module["id"], "value": step_value }] }); + + let (started, is_flow) = match module_type { + "rawscript" => ( + run_script_preview( + ctx, + None, + &text("language"), + &text("content"), + with_entrypoint(run_args), + ) + .await, + false, + ), + "script" => { + let (target, content, language) = script.unwrap_or_default(); + ( + run_script_preview( + ctx, + Some(&target), + &language, + &content, + with_entrypoint(run_args), + ) + .await, + false, + ) + } + "flow" => { + let target = text("path"); + let started = match subflow_preview { + Some(preview) => { + run_flow_preview(ctx, Some(&target), &preview, Value::Object(run_args), None) + .await + } + None => ctx + .post( + &ctx.ws(&format!( + "jobs/run/f/{}?skip_preprocessor=true", + path_enc(&target) + )), + Value::Object(run_args), + ) + .await + .map(job_id), + }; + (started, true) + } + "aiagent" => { + let mut step_value = migrated_agent_value(value); + let form_keys: Vec<String> = schema + .as_ref() + .and_then(|s| s["properties"].as_object()) + .map(|p| p.keys().cloned().collect()) + .unwrap_or_default(); + step_value["input_transforms"] = Value::Object(agent_test_transforms( + step_value.get("input_transforms"), + &run_args, + &form_keys, + )); + let mut step = json!({ "id": module["id"], "value": step_value }); + with_agent_drafts(ctx, &mut step).await?; + let preview = json!({ "modules": [step] }); + ( + run_flow_preview(ctx, Some(path), &preview, Value::Object(run_args), None).await, + true, + ) + } + _ => { + let mut step_value = value.clone(); + let mut transforms = value["input_transforms"] + .as_object() + .cloned() + .unwrap_or_default(); + for key in run_args.keys() { + transforms.insert( + key.clone(), + json!({ "type": "javascript", "expr": format!("flow_input.{key}") }), + ); + } + step_value["input_transforms"] = Value::Object(transforms); + let preview = single_step(step_value); + ( + run_flow_preview( + ctx, + Some(path), + &preview, + Value::Object(std::mem::take(&mut run_args)), + None, + ) + .await, + true, + ) + } + }; + conclude(ctx, args, prepared.notes, started, &label, is_flow, "test").await +} + +fn migrated_agent_value(value: &Value) -> Value { + let mut value = value.clone(); + if let Some(transforms) = value + .get_mut("input_transforms") + .and_then(Value::as_object_mut) + { + migrate_agent_transforms(transforms); + } + value +} + +// ============================================================================ +// Reading runs back +// ============================================================================ + +/// Compact metadata for one run: what identifies it and how it ended. +fn summarize_run(job: &Value) -> Map<String, Value> { + let mut out = Map::new(); + for (key, source) in [ + ("id", "id"), + ("job_kind", "job_kind"), + ("path", "script_path"), + ("created_by", "created_by"), + ("created_at", "created_at"), + ("started_at", "started_at"), + ("schedule_path", "schedule_path"), + ("is_flow_step", "is_flow_step"), + ("tag", "tag"), + ("worker", "worker"), + ] { + if let Some(value) = job.get(source) { + out.insert(key.into(), value.clone()); + } + } + let flag = |key: &str| truthy(job.get(key)); + let status = if job.get("success").is_some() { + // `success` is true for a skipped job too, so it is read last. + if flag("canceled") { + "canceled" + } else if flag("is_skipped") { + "skipped" + } else if flag("success") { + "success" + } else { + "failure" + } + } else if !flag("running") { + "queued" + } else if flag("suspend") { + // Parked on an approval or a parallelism slot, not working. + "suspended" + } else { + "running" + }; + out.insert("status".into(), status.into()); + if job.get("success").is_some() { + if let Some(duration) = job.get("duration_ms") { + out.insert("duration_ms".into(), duration.clone()); + } + } + out +} + +async fn list_runs(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let limit = args + .get("limit") + .and_then(Value::as_u64) + .unwrap_or(30) + .clamp(1, 100); + let mut query = format!("per_page={limit}"); + for (param, arg) in [ + ("script_path_exact", "path"), + ("created_by", "created_by"), + ("label", "label"), + ] { + if let Some(value) = opt_str_arg(args, arg) { + query.push_str(&format!("&{param}={}", enc(value))); + } + } + for flag in ["success", "running"] { + if let Some(value) = args.get(flag).and_then(Value::as_bool) { + query.push_str(&format!("&{flag}={value}")); + } + } + let jobs = ctx.get(&ctx.ws(&format!("jobs/list?{query}"))).await?; + let runs: Vec<Value> = jobs + .as_array() + .into_iter() + .flatten() + .map(|job| Value::Object(summarize_run(job))) + .collect(); + Ok(pretty(&Value::Array(runs))) +} + +async fn cancel_job(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let id = str_arg(args, "id")?; + Ok( + match ctx + .post( + &ctx.ws(&format!("jobs_u/queue/cancel/{}", enc(id))), + json!({}), + ) + .await + { + Ok(_) => format!("Job {id} was canceled."), + Err(e) => format!( + "Failed to cancel job {id}: {}. It may have already finished.", + api_message(&e) + ), + }, + ) +} + +/// Per-entry result budget asked of the server for the tree view. +const TREE_RESULT_HEAD_CHARS: usize = 700; +/// Cap on a full payload handed to the model: a drilled step result, and the run's own +/// args, result and logs. +const STEP_RESULT_MAX_CHARS: usize = 12000; +/// Cap on the whole rendered tree; heads shrink progressively to fit. +const TREE_TOTAL_BUDGET_CHARS: usize = 20000; +const MAX_FAILED_ITERATIONS_SHOWN: usize = 3; +/// `(head, success_head)` tried in order until the tree fits: succeeded steps lose +/// their results first so failure detail survives longest. +const SHRINK_LADDER: [(usize, usize); 4] = [ + (TREE_RESULT_HEAD_CHARS, TREE_RESULT_HEAD_CHARS), + (250, 250), + (250, 0), + (100, 0), +]; +/// Module types whose sibling jobs are iterations or branches; sibling jobs of any +/// other step are retry attempts of it. +const FAN_OUT_MODULE_TYPES: [&str; 5] = [ + "forloopflow", + "whileloopflow", + "branchall", + "branchone", + "aiagent", +]; +const LOGS_UNREADABLE: &str = "Logs could not be read for this run."; + +/// A run's jobs as the server lists them, depth-first, with each one's children. +struct RunTree<'a> { + entries: &'a [Value], + children: Vec<Vec<usize>>, +} + +impl<'a> RunTree<'a> { + fn new(entries: &'a [Value]) -> Self { + let depth = |i: usize| entries[i]["depth"].as_i64().unwrap_or(0); + let mut children = vec![Vec::new(); entries.len()]; + let mut stack: Vec<usize> = Vec::new(); + for i in 0..entries.len() { + while stack.last().is_some_and(|&top| depth(top) >= depth(i)) { + stack.pop(); + } + if let Some(&parent) = stack.last() { + children[parent].push(i); + } + stack.push(i); + } + RunTree { entries, children } + } + + fn status(&self, i: usize) -> &str { + self.entries[i]["status"].as_str().unwrap_or_default() + } + + fn shape_step( + &self, + i: usize, + heads: (usize, usize), + iteration: Option<&Value>, + ) -> Map<String, Value> { + let entry = &self.entries[i]; + let mut out = Map::new(); + if let Some(step) = entry["step_path"].as_str().filter(|s| !s.is_empty()) { + out.insert("step".into(), step.into()); + } + if let Some(iteration) = iteration { + out.insert("iteration".into(), iteration.clone()); + } + for key in ["label", "job_id", "status"] { + if let Some(value) = entry.get(key) { + out.insert(key.into(), value.clone()); + } + } + if let Some(duration) = entry.get("duration_ms").filter(|d| !d.is_null()) { + out.insert("duration_ms".into(), duration.clone()); + } + if let Some(prefix) = entry["result_prefix"].as_str() { + let budget = if truthy(entry.get("success")) { + heads.1 + } else { + heads.0 + }; + let length = entry["result_length"].as_u64(); + if budget == 0 { + if let Some(length) = length { + out.insert("result_total_chars".into(), length.into()); + } + } else { + // The server counts code points, so sizes are compared in them. + let head = js_head(prefix, budget); + let total = length.unwrap_or(prefix.chars().count() as u64); + out.insert("result".into(), head.into()); + if total > head.chars().count() as u64 { + out.insert("result_total_chars".into(), total.into()); + } + } + } + let steps = self.shape_children(i, heads); + if !steps.is_empty() { + out.insert("steps".into(), steps.into()); + } + out + } + + /// Sibling jobs grouped by flow step, so the iterations, branches or attempts of + /// one step read as one entry. + fn shape_children(&self, i: usize, heads: (usize, usize)) -> Vec<Value> { + let mut groups: Vec<(String, Vec<usize>)> = Vec::new(); + for &child in &self.children[i] { + let entry = &self.entries[child]; + let step_id = match entry["flow_step_id"].as_str() { + Some(id) => id.to_string(), + None => format!("job:{}", entry["job_id"].as_str().unwrap_or_default()), + }; + match groups.iter_mut().find(|(id, _)| *id == step_id) { + Some((_, nodes)) => nodes.push(child), + None => groups.push((step_id, vec![child])), + } + } + groups + .iter() + .map(|(step_id, nodes)| Value::Object(self.shape_group(step_id, nodes, heads))) + .collect() + } + + fn shape_group( + &self, + step_id: &str, + nodes: &[usize], + heads: (usize, usize), + ) -> Map<String, Value> { + let first = &self.entries[nodes[0]]; + if nodes.len() == 1 && first["sibling_count"].as_i64().is_some_and(|n| n <= 1) { + return self.shape_step(nodes[0], heads, None); + } + let step = first["step_path"].as_str().unwrap_or(step_id); + let parent_type = first["parent_module_type"].as_str().unwrap_or_default(); + let mut out = Map::new(); + out.insert("step".into(), step.into()); + if parent_type == "branchall" { + out.insert("type".into(), "branchall".into()); + let branches: Vec<Value> = nodes + .iter() + .map(|&n| Value::Object(self.shape_step(n, heads, None))) + .collect(); + out.insert("branches".into(), branches.into()); + return out; + } + + let index = |n: usize| &self.entries[n]["sibling_index"]; + let mut by_index = nodes.to_vec(); + by_index.sort_by_key(|&n| index(n).as_i64().unwrap_or(0)); + let last = by_index[by_index.len() - 1]; + + if !parent_type.is_empty() && !FAN_OUT_MODULE_TYPES.contains(&parent_type) { + // A retried step: the last attempt is its outcome, earlier ones are + // status-only references. + let mut shaped = self.shape_step(last, heads, None); + shaped.insert("attempts".into(), by_index.len().into()); + let previous: Vec<Value> = by_index[..by_index.len() - 1] + .iter() + .map(|&n| { + json!({ + "attempt": index(n), + "status": self.status(n), + "job_id": self.entries[n]["job_id"], + }) + }) + .collect(); + shaped.insert("previous_attempts".into(), previous.into()); + return shaped; + } + + let count = |status: &str| { + by_index + .iter() + .filter(|&&n| self.status(n) == status) + .count() + }; + let ok = count("success"); + let failed: Vec<usize> = by_index + .iter() + .copied() + .filter(|&n| matches!(self.status(n), "failure" | "canceled")) + .collect(); + let skipped = count("skipped"); + // Skipped is terminal: only running, queued and suspended are unfinished. + let unfinished = by_index.len() - ok - failed.len() - skipped; + let mut shown: Vec<usize> = failed + .iter() + .copied() + .take(MAX_FAILED_ITERATIONS_SHOWN) + .collect(); + if !shown.contains(&last) { + shown.push(last); + } + + out.insert( + "type".into(), + if parent_type.is_empty() { + "loop" + } else { + parent_type + } + .into(), + ); + out.insert("iterations".into(), by_index.len().into()); + out.insert("ok".into(), ok.into()); + if !failed.is_empty() { + let indices: Vec<Value> = failed.iter().map(|&n| index(n).clone()).collect(); + out.insert("failed_iterations".into(), indices.into()); + } + if skipped > 0 { + out.insert("skipped".into(), skipped.into()); + } + if unfinished > 0 { + out.insert("unfinished".into(), unfinished.into()); + } + let iterations: Vec<Value> = shown + .iter() + .map(|&n| Value::Object(self.shape_step(n, heads, Some(index(n))))) + .collect(); + out.insert("iterations_shown".into(), iterations.into()); + if by_index.len() > shown.len() { + out.insert( + "iterations_elided".into(), + (by_index.len() - shown.len()).into(), + ); + } + out + } + + fn render( + &self, + note: Option<&str>, + heads: (usize, usize), + run_overrides: &Map<String, Value>, + ) -> Value { + let mut run = self.shape_step(0, heads, None); + let steps = run.remove("steps"); + let kind = self.entries[0]["kind"].as_str().unwrap_or_default(); + // The server labels every depth-0 job "Flow", a plain script run included. + if steps.is_none() && kind != "flow" && kind != "flowpreview" { + run.insert("label".into(), format!("Job ({kind})").into()); + } + // A replacement result supersedes the tree entry's head. Without one the head + // stays: it is a real prefix of a payload too big to be read whole. + if run_overrides.contains_key("result") { + run.remove("result"); + run.remove("result_total_chars"); + } + for (key, value) in run_overrides { + run.insert(key.clone(), value.clone()); + } + let mut out = Map::new(); + if let Some(note) = note { + out.insert("note".into(), note.into()); + } + out.insert("run".into(), Value::Object(run)); + if let Some(steps) = steps { + out.insert("steps".into(), steps); + out.insert( + "hint".into(), + format!("Step results are truncated. Call get_run again with step=\"<step>\" (e.g. \"b/c\", or \"b[12]\" for one loop iteration) for a step's result in full (up to {STEP_RESULT_MAX_CHARS} chars), or with id set to a step's job_id for that step's own args, result and logs.").into(), + ); + } + Value::Object(out) + } +} + +/// Render a run's execution tree around the run's own summary and payloads +/// (`run_overrides`), shrinking result heads until the tree fits its budget. +fn shape_flow_run_tree(response: &Value, run_overrides: &Map<String, Value>) -> String { + let entries = response["entries"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default(); + if entries.is_empty() { + return pretty1(&json!({ "run": run_overrides })); + } + let mut notes = Vec::new(); + if let Some(enclosing) = response["enclosing_job"].as_str().filter(|j| !j.is_empty()) { + notes.push(format!("This job is a step of a larger flow run — its enclosing run is {enclosing}; pass that id to see more of the tree.")); + } + if truthy(response.get("truncated")) { + notes.push(format!("The run has more jobs than the server returns — this tree only covers the first {} (depth-first), so tallies may undercount.", entries.len())); + } + if truthy(response.get("scope_filtered")) { + notes.push( + "Your token is tag-scoped: steps running on other tags are omitted from this tree." + .to_string(), + ); + } + let note = (!notes.is_empty()).then(|| notes.join(" ")); + + // The budget caps the tree, not the run's own args, result and logs: those are + // capped on their own. + let override_chars = js_len(&pretty1(&Value::Object(run_overrides.clone()))); + let tree = RunTree::new(entries); + let mut rendered = String::new(); + for heads in SHRINK_LADDER { + rendered = pretty1(&tree.render(note.as_deref(), heads, run_overrides)); + if js_len(&rendered).saturating_sub(override_chars) <= TREE_TOTAL_BUDGET_CHARS { + return rendered; + } + } + format!( + "{}\n… (tree truncated at {TREE_TOTAL_BUDGET_CHARS} chars — drill into specific steps with the step parameter)", + js_head(&rendered, TREE_TOTAL_BUDGET_CHARS + override_chars) + ) +} + +/// Cap a payload to `STEP_RESULT_MAX_CHARS`. `tail` keeps the end, for logs, where the +/// failure is at the bottom. +fn cap(text: &str, tail: bool) -> String { + if js_len(text) <= STEP_RESULT_MAX_CHARS { + return text.to_string(); + } + let total = text.chars().count(); + if total <= STEP_RESULT_MAX_CHARS { + return text.to_string(); + } + let note = format!("… (truncated: {total} chars total)"); + if tail { + format!("{note}\n{}", js_tail(text, STEP_RESULT_MAX_CHARS)) + } else { + format!("{}\n{note}", js_head(text, STEP_RESULT_MAX_CHARS)) + } +} + +fn stringify(value: &Value) -> String { + match value { + Value::String(text) => text.clone(), + other => pretty1(other), + } +} + +async fn get_run(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let id = str_arg(args, "id")?; + let results_route = |max: usize| { + ctx.ws(&format!( + "jobs_u/get_flow_all_results/{}?max_result_len={max}", + enc(id) + )) + }; + if let Some(step) = opt_str_arg(args, "step").filter(|s| !s.is_empty()) { + let route = format!( + "{}&step={}", + results_route(STEP_RESULT_MAX_CHARS), + enc(step) + ); + return Ok(step_result(&ctx.get(&route).await?, step)); + } + + // Only the job read is load-bearing: logs and the step tree each answer part of + // the question, so neither failing costs the rest. + let job_route = ctx.ws(&format!("jobs_u/get/{}?no_logs=true&no_code=true", enc(id))); + let logs_route = ctx.ws(&format!( + "jobs_u/get_logs/{}?remove_ansi_warnings=true", + enc(id) + )); + let tree_route = results_route(TREE_RESULT_HEAD_CHARS); + let (job, logs, results) = tokio::join!( + ctx.get(&job_route), + ctx.request("GET", &logs_route, None), + ctx.get(&tree_route), + ); + let results = results.unwrap_or_else(|_| json!({ "entries": [] })); + Ok(format!( + "{}\n\nRun page: {}", + shape_run(id, &job?, logs, &results), + ctx.page_url(&format!("/run/{}", enc(id))) + )) +} + +/// A run as `get_run` reports it: its summary, args, result and logs around the step +/// tree. `logs` is the log read's own outcome, so a failed read is told apart from an +/// empty log. +fn shape_run(id: &str, job: &Value, logs: Result<String, String>, results: &Value) -> String { + let mut run = summarize_run(job); + run.remove("id"); + // Why a run ended badly. + for (key, source) in [ + ("canceled_by", "canceled_by"), + ("canceled_reason", "canceled_reason"), + ("mem_peak_kb", "mem_peak"), + ] { + if let Some(value) = job.get(source).filter(|v| truthy(Some(v))) { + run.insert(key.into(), value.clone()); + } + } + // A successful read always carries the job itself as the root entry, so no entries + // means the read failed, and nothing else would name the run. + if results["entries"].as_array().is_none_or(Vec::is_empty) { + run.insert("job_id".into(), id.into()); + run.insert("steps_unavailable".into(), true.into()); + } + // The server swaps a payload too big to send for a marker, each field in its own + // form. That is reported, never fetched around: the result keeps the head the step + // tree carries. + if let Some(job_args) = job.get("args").filter(|a| truthy(Some(a))) { + let too_big = job_args + .as_object() + .is_some_and(|o| o.len() == 1 && o.get("reason") == Some(&json!("WINDMILL_TOO_BIG"))); + if too_big { + run.insert("args_truncated".into(), true.into()); + } else { + run.insert("args".into(), cap(&stringify(job_args), false).into()); + } + } + if let Some(result) = job.get("result") { + if result == "WINDMILL_TOO_BIG" { + run.insert("result_truncated".into(), true.into()); + } else { + run.insert("result".into(), cap(&stringify(result), false).into()); + } + } + let logs = match logs { + Err(_) => LOGS_UNREADABLE.to_string(), + Ok(logs) if logs.trim().is_empty() => "No logs for this run.".to_string(), + Ok(logs) => cap(&logs, true), + }; + run.insert("logs".into(), logs.into()); + shape_flow_run_tree(results, &run) +} + +/// One step's result in full, from the single entry the server resolved its address to. +fn step_result(response: &Value, step: &str) -> String { + if let Some(error) = response["step_error"].as_str().filter(|e| !e.is_empty()) { + let hidden = if truthy(response.get("scope_filtered")) { + " (Steps running on tags outside your token’s scope are hidden.)" + } else { + "" + }; + return format!("{error}{hidden}"); + } + let Some(entry) = response["entries"].get(0) else { + return "No jobs found for this run.".to_string(); + }; + let job_id = entry["job_id"].as_str().unwrap_or_default(); + let status = entry["status"].as_str().unwrap_or_default(); + if matches!(status, "running" | "queued" | "suspended") { + return format!("Step \"{step}\" (job {job_id}) has not completed yet — status: {status}."); + } + let Some(prefix) = entry["result_prefix"].as_str() else { + return format!("Step \"{step}\" (job {job_id}, {status}) has no recorded result."); + }; + let received = prefix.chars().count() as u64; + let total = entry["result_length"].as_u64().unwrap_or(received); + let truncated = if total > received { + format!("\n… (result truncated: {total} chars total)") + } else { + String::new() + }; + format!("Step \"{step}\" (job {job_id}, {status}) result:\n{prefix}{truncated}") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(overrides: Value) -> Value { + let mut entry = json!({ + "job_id": "j", + "label": "Flow", + "kind": "script", + "depth": 1, + "sibling_index": 1, + "sibling_count": 1, + "status": "success", + "success": true, + "result_prefix": "\"ok\"", + "result_length": 4, + }); + for (key, value) in overrides.as_object().unwrap() { + entry[key] = value.clone(); + } + entry + } + + fn root() -> Value { + entry(json!({ "kind": "flow", "depth": 0, "step_path": "" })) + } + + fn shape(entries: Vec<Value>) -> Value { + serde_json::from_str(&shape_flow_run_tree( + &json!({ "entries": entries }), + &Map::new(), + )) + .unwrap() + } + + fn loop_entries(n: i64, failed: &[i64]) -> Vec<Value> { + let mut entries = vec![root()]; + for i in 1..=n { + entries.push(entry(json!({ + "step_path": "l", "flow_step_id": "l", "kind": "flow", + "parent_module_type": "forloopflow", "sibling_index": i, "sibling_count": n, + "status": if failed.contains(&i) { "failure" } else { "success" }, + "success": !failed.contains(&i), + }))); + } + entries + } + + #[test] + fn subflow_steps_nest_under_their_parent_step() { + let rendered = shape(vec![ + root(), + entry(json!({ "step_path": "a", "flow_step_id": "a" })), + entry(json!({ "step_path": "b", "flow_step_id": "b", "kind": "flow" })), + entry(json!({ + "step_path": "b/c", "flow_step_id": "c", "depth": 2, "status": "failure", + "success": false, "result_prefix": "{\"error\":\"boom\"}", "result_length": 16, + })), + ]); + assert_eq!(rendered["run"]["status"], "success"); + assert!(rendered["run"].get("step").is_none()); + let step_b = &rendered["steps"][1]; + assert_eq!(step_b["step"], "b"); + assert_eq!(step_b["steps"][0]["step"], "b/c"); + assert_eq!(step_b["steps"][0]["result"], "{\"error\":\"boom\"}"); + assert!(rendered["hint"].is_string()); + } + + #[test] + fn loop_iterations_collapse_to_a_tally() { + let looped = &shape(loop_entries(50, &[3, 7, 21, 30]))["steps"][0]; + assert_eq!(looped["type"], "forloopflow"); + assert_eq!(looped["iterations"], 50); + assert_eq!(looped["ok"], 46); + assert_eq!(looped["failed_iterations"], json!([3, 7, 21, 30])); + let shown: Vec<&Value> = looped["iterations_shown"] + .as_array() + .unwrap() + .iter() + .map(|i| &i["iteration"]) + .collect(); + assert_eq!(shown, [&json!(3), &json!(7), &json!(21), &json!(50)]); + assert_eq!(looped["iterations_elided"], 46); + + let mut entries = loop_entries(4, &[]); + entries[2] = entry(json!({ + "step_path": "l", "flow_step_id": "l", "parent_module_type": "forloopflow", + "sibling_index": 2, "sibling_count": 4, "status": "running", + "success": null, "result_prefix": null, "result_length": null, + })); + entries[3]["status"] = json!("skipped"); + let looped = &shape(entries)["steps"][0]; + assert_eq!(looped["ok"], 2); + assert_eq!(looped["unfinished"], 1); + assert_eq!(looped["skipped"], 1); + assert!(looped.get("failed_iterations").is_none()); + } + + #[test] + fn retried_steps_are_attempts_of_one_step() { + let mut entries = vec![root()]; + for i in 1..=3 { + entries.push(entry(json!({ + "step_path": "a", "flow_step_id": "a", "label": format!("Step a (attempt {i}/3)"), + "parent_module_type": "rawscript", "sibling_index": i, "sibling_count": 3, + "status": if i < 3 { "failure" } else { "success" }, "success": i == 3, + }))); + } + let step = &shape(entries)["steps"][0]; + assert!(step.get("iterations").is_none()); + assert_eq!(step["attempts"], 3); + assert_eq!(step["label"], "Step a (attempt 3/3)"); + assert_eq!(step["previous_attempts"][1]["status"], "failure"); + } + + #[test] + fn result_heads_shrink_to_fit_and_run_payloads_do_not_count() { + let mut entries = vec![root()]; + for i in 0..60 { + entries.push(entry(json!({ + "step_path": format!("s{i}"), "flow_step_id": format!("s{i}"), + "result_prefix": "x".repeat(700), "result_length": 5000, + }))); + } + let mut overrides = Map::new(); + overrides.insert("logs".into(), "y".repeat(12000).into()); + let rendered = shape_flow_run_tree(&json!({ "entries": entries }), &overrides); + assert!(rendered.len() - 12000 <= TREE_TOTAL_BUDGET_CHARS + 100); + let parsed: Value = serde_json::from_str(&rendered).unwrap(); + assert_eq!(parsed["run"]["logs"].as_str().unwrap().len(), 12000); + let step = &parsed["steps"][0]; + assert!(step["result"].as_str().is_none_or(|r| r.len() <= 250)); + assert_eq!(step["result_total_chars"], 5000); + } + + #[test] + fn truncation_counts_utf16_units_without_splitting_a_character() { + let text = format!("{}😀b", "a".repeat(3)); + assert_eq!(js_head(&text, 4), "aaa"); + assert_eq!(js_head(&text, 5), "aaa😀"); + assert_eq!(js_tail(&text, 2), "b"); + let long = "é".repeat(STEP_RESULT_MAX_CHARS + 5); + assert!(cap(&long, true).starts_with("… (truncated: 12005 chars total)\né")); + assert_eq!(cap("short", false), "short"); + } + + #[test] + fn args_conform_to_the_schema_and_read_back_redacted() { + let schema = json!({ "properties": { + "name": { "type": "string" }, + "locked": { "type": "number", "disabled": true, "default": 1 }, + "creds": { "type": "object", "properties": { "token": { "type": "string", "password": true } } }, + "file": { "type": "string", "contentEncoding": "base64" }, + }}); + let proposed = json!({ + "name": "x", "locked": 2, "extra": true, + "creds": { "token": "s3cret", "user": "u" }, "file": "A".repeat(4096), + }); + let (mut args, undeclared) = + drop_undeclared_args(proposed.as_object().unwrap().clone(), &schema); + assert_eq!(undeclared, ["extra"]); + assert_eq!(enforce_disabled_defaults(&mut args, &schema), ["locked"]); + assert_eq!(args["locked"], 1); + let redacted = redact_args(&args, &schema); + assert_eq!( + redacted["creds"], + json!({ "token": "<hidden>", "user": "u" }) + ); + assert_eq!(redacted["file"], "<file: 3 KB>"); + args["creds"]["token"] = json!("$var:u/admin/secret_arg/abc"); + assert_eq!( + redact_args(&args, &schema)["creds"]["token"], + "$var:u/admin/secret_arg/abc" + ); + } + + #[test] + fn agent_step_form_opens_on_what_the_step_sets() { + let value = json!({ "type": "aiagent", "input_transforms": { + "provider": { "type": "static", "value": { "kind": "openai" } }, + "user_message": { "type": "javascript", "expr": "flow_input.q" }, + "max_iterations": { "type": "static", "value": 10 }, + "temperature": { "type": "static", "value": 0.2 }, + "memory_id": { "type": "static", "value": "stale" }, + }}); + let proposed = json!({ "user_message": "hi", "enabled_tools": null }); + let (keys, args) = agent_step_form(&value, proposed.as_object().unwrap()); + assert_eq!( + keys, + [ + "provider", + "temperature", + "user_message", + "system_prompt", + "memory_id", + "enabled_tools" + ] + ); + assert_eq!(args["user_message"], "hi"); + assert_eq!(args["enabled_tools"], json!([])); + let mut run_args = args.clone(); + run_args.insert("memory_id".into(), json!("")); + let transforms = agent_test_transforms(value.get("input_transforms"), &run_args, &keys); + assert_eq!( + transforms["user_message"]["expr"], + "flow_input.user_message" + ); + assert_eq!(transforms["max_iterations"]["value"], 10); + assert!(!transforms.contains_key("memory_id")); + } +} diff --git a/backend/windmill-api/src/mcp/session/settings.rs b/backend/windmill-api/src/mcp/session/settings.rs new file mode 100644 index 0000000000..3548dada4b --- /dev/null +++ b/backend/windmill-api/src/mcp/session/settings.rs @@ -0,0 +1,140 @@ +//! The workspace settings document, in the layout of the `settings.yaml` the CLI syncs. + +use serde_json::{json, Map, Value}; + +use super::workspace::api_message; +use super::{array, js_head, js_len, js_str, str_arg, Ctx, ToolResult}; + +pub(super) const TOOLS: &[&str] = &["get_workspace_settings", "set_workspace_settings"]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "get_workspace_settings" => get_workspace_settings(ctx, args).await, + "set_workspace_settings" => set_workspace_settings(ctx, args).await, + _ => unreachable!("{name} is not a settings tool"), + } +} + +const MAX_READ_CHARS: usize = 20_000; + +async fn get_workspace_settings(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let doc = ctx + .get(&ctx.ws("workspaces/settings_document?secrets=redacted")) + .await?; + let keys: Vec<&str> = array(args.get("keys")) + .iter() + .filter_map(Value::as_str) + .collect(); + let mut picked = doc.clone(); + let mut note = String::new(); + if !keys.is_empty() { + picked = Value::Object( + keys.iter() + .filter_map(|k| Some((k.to_string(), doc.get(k)?.clone()))) + .collect::<Map<_, _>>(), + ); + let unset: Vec<&str> = keys + .iter() + .copied() + .filter(|k| doc.get(k).is_none()) + .collect(); + if !unset.is_empty() { + note = format!( + "\n# Not in the document (unset, or not a setting): {}", + unset.join(", ") + ); + } + } + let mut text = serde_yml::to_string(&picked).map_err(|e| e.to_string())?; + text.push_str(¬e); + Ok(if js_len(&text) > MAX_READ_CHARS { + format!( + "{}\n… truncated at {MAX_READ_CHARS} chars; read the keys you need with `keys`.", + js_head(&text, MAX_READ_CHARS) + ) + } else { + text + }) +} + +fn parse_settings_yaml(text: &str) -> Result<Value, String> { + match serde_yml::from_str::<Value>(text) { + Ok(doc @ Value::Object(_)) => Ok(doc), + Ok(_) => Err("The yaml must be a mapping of setting keys to values.".to_string()), + Err(e) => Err(e.to_string()), + } +} + +/// The dry run stands in for the session's confirmation card: it reports a no-op or an +/// invalid document before anything is written. +async fn set_workspace_settings(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let route = ctx.ws("workspaces/settings_document"); + let document = match parse_settings_yaml(str_arg(args, "yaml")?) { + Ok(document) => document, + Err(e) => return Ok(format!("Nothing was changed: {e}")), + }; + let dry_run = json!({ "document": document, "replace": false, "dry_run": true }); + let dry_run = match ctx.post(&route, dry_run).await { + Ok(result) => result, + Err(e) => return Ok(format!("Nothing was changed: {}", api_message(&e))), + }; + if array(dry_run.get("changes")).is_empty() { + let warnings: Vec<String> = array(dry_run.get("warnings")).iter().map(js_str).collect(); + let warnings = if warnings.is_empty() { + String::new() + } else { + format!(" Warnings: {}", warnings.join(" ")) + }; + return Ok(format!( + "The settings already hold these values: nothing to change.{warnings}" + )); + } + let applied = match ctx + .post(&route, json!({ "document": document, "replace": false })) + .await + { + Ok(result) => result, + Err(e) => return Ok(json!({ "success": false, "error": api_message(&e) }).to_string()), + }; + let keys: Vec<String> = array(applied.get("changes")) + .iter() + .map(|c| js_str(c.get("key").unwrap_or(&Value::Null))) + .collect(); + let mut out = Map::new(); + out.insert("success".into(), json!(true)); + out.insert( + "message".into(), + json!(format!( + "These settings are now applied: {}.", + keys.join(", ") + )), + ); + if let Some(warnings) = applied + .get("warnings") + .filter(|w| !array(Some(w)).is_empty()) + { + out.insert("warnings".into(), warnings.clone()); + } + Ok(Value::Object(out).to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings_yaml_must_be_a_mapping() { + assert_eq!( + parse_settings_yaml("webhook: null\ncolor: red").unwrap(), + json!({ "webhook": null, "color": "red" }) + ); + for text in ["- a\n- b", "just text", "42"] { + assert_eq!( + parse_settings_yaml(text).unwrap_err(), + "The yaml must be a mapping of setting keys to values.", + "{text}" + ); + } + assert!(parse_settings_yaml("a: [").is_err()); + } +} diff --git a/backend/windmill-api/src/mcp/session/workspace.rs b/backend/windmill-api/src/mcp/session/workspace.rs new file mode 100644 index 0000000000..43ab2c33ec --- /dev/null +++ b/backend/windmill-api/src/mcp/session/workspace.rs @@ -0,0 +1,1983 @@ +//! Listing and reading workspace items, and the draft store the write tools share. + +use std::collections::HashMap; + +use serde_json::{json, Map, Value}; + +use super::{ + array, bool_arg, enc, is_not_found, js_len, js_str, non_null, opt_str_arg, pretty, put, + str_arg, truthy, Ctx, ToolResult, +}; + +pub(super) const TOOLS: &[&str] = &[ + "list_workspace_items", + "read_workspace_item", + "write_script", + "edit_script", + "discard_local_draft", + "rebase_draft", + "list_pipelines", +]; + +pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + match name { + "list_workspace_items" => list_workspace_items(ctx, args).await, + "read_workspace_item" => read_workspace_item(ctx, args).await, + "write_script" => { + write_script_draft( + ctx, + str_arg(args, "path")?, + opt_str_arg(args, "summary"), + str_arg(args, "language")?, + str_arg(args, "content")?, + bool_arg(args, "override"), + ) + .await + } + "edit_script" => edit_script(ctx, args).await, + "discard_local_draft" => discard_local_draft(ctx, args).await, + "rebase_draft" => rebase_draft(ctx, args).await, + "list_pipelines" => { + let pipelines = ctx.get(&ctx.ws("assets/pipelines")).await?; + Ok(pipelines.to_string()) + } + _ => unreachable!("{name} is not a workspace tool"), + } +} + +// ============================================================================ +// Shared helpers: the per-user draft store and the item shapes built on it. +// +// Vocabulary. An item *type* is what a tool takes (`script`, `flow`, `schedule`, +// `trigger`, `resource`, `variable`, `app`); a draft *kind* is what the drafts API +// stores under (`script`, `flow`, `raw_app`, `trigger_schedule`, `trigger_<kind>`, +// `resource`, `variable`). An *item* is the JSON object the tools show the model +// (`{type, path, summary, value, isDraft, ...}`). A draft's *value* is stored exactly +// as the Windmill editors store it, so either side opens the other's drafts: +// script the `NewScript` body (`path, summary, description, content, schema, +// is_template, language, kind`, + `parent_hash` once forked from a deploy) +// flow the `Flow` object (`path, summary, description, value, schema`, + +// `version_id` when forked from a deploy) +// raw_app `{summary, files, runnables, data, policy?, custom_path?, +// parent_version?, draft_path?}` (`normalize_app_draft`) +// trigger_schedule the schedule request body; `trigger_<kind>` that trigger's body +// resource `{path, description, args, labels, wsSpecific, resource_type}` +// variable `{path, variable: {value, is_secret, description}, labels, +// wsSpecific, account?, is_oauth?, expires_at?}` +// ============================================================================ + +pub(super) const TRIGGER_KINDS: &[&str] = &[ + "http", + "websocket", + "kafka", + "nats", + "postgres", + "mqtt", + "amqp", + "sqs", + "gcp", + "azure", + "email", +]; + +/// The item types in the order a listing reports them. +pub(super) const ITEM_TYPES: &[&str] = &[ + "script", "flow", "schedule", "trigger", "resource", "variable", "app", +]; + +/// Folders and groups only carry permissions, so they are listed and read but kept out of +/// `ITEM_TYPES`, which the draft, deploy and delete tools share. +const ACCESS_TYPES: &[&str] = &["folder", "group"]; + +pub(super) const FLOW_VALUE_SETTINGS_KEYS: &[&str] = &[ + "same_worker", + "preserve_step_tags", + "concurrent_limit", + "concurrency_key", + "concurrency_time_window_s", + "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", + "flow_env", + "priority", + "early_return", + "chat_input_enabled", +]; + +const MAX_LIST_LIMIT: u64 = 100; + +pub(super) fn item_type_arg(args: &Value) -> Result<&str, String> { + let item_type = str_arg(args, "type")?; + if ITEM_TYPES.contains(&item_type) { + Ok(item_type) + } else { + Err(format!("Invalid type \"{item_type}\"")) + } +} + +fn object_or_empty(value: Option<&Value>) -> Value { + match value { + Some(Value::Object(o)) => Value::Object(o.clone()), + _ => json!({}), + } +} + +pub(super) fn api_message(error: &str) -> &str { + match error.split_once(": ") { + Some((status, rest)) if status.len() == 3 && status.bytes().all(|b| b.is_ascii_digit()) => { + rest + } + _ => error, + } +} + +pub(super) fn path_enc(path: &str) -> String { + path.split('/').map(enc).collect::<Vec<_>>().join("/") +} + +pub(super) fn draft_kind(item_type: &str, trigger_kind: Option<&str>) -> Option<String> { + match item_type { + "script" | "flow" | "resource" | "variable" => Some(item_type.to_string()), + "app" => Some("raw_app".to_string()), + "schedule" => Some("trigger_schedule".to_string()), + "trigger" => trigger_kind + .filter(|kind| TRIGGER_KINDS.contains(kind)) + .map(|kind| format!("trigger_{kind}")), + _ => None, + } +} + +/// The item type (and trigger kind) a draft kind surfaces as. None for the kinds no +/// tool addresses: low-code apps, webhook and poll triggers, pipelines. +fn item_type_of_kind(kind: &str) -> Option<(&'static str, Option<&str>)> { + Some(match kind { + "script" => ("script", None), + "flow" => ("flow", None), + "resource" => ("resource", None), + "variable" => ("variable", None), + "raw_app" => ("app", None), + "trigger_schedule" => ("schedule", None), + _ => { + let trigger_kind = kind.strip_prefix("trigger_")?; + if !TRIGGER_KINDS.contains(&trigger_kind) { + return None; + } + ("trigger", Some(trigger_kind)) + } + }) +} + +fn item_key(item_type: &str, path: &str, trigger_kind: Option<&str>) -> String { + if item_type == "trigger" { + format!("trigger:{}:{path}", trigger_kind.unwrap_or_default()) + } else { + format!("{item_type}:{path}") + } +} + +pub(super) fn service(item_type: &str, trigger_kind: Option<&str>) -> Result<String, String> { + Ok(match item_type { + "trigger" => { + let kind = trigger_kind + .filter(|kind| TRIGGER_KINDS.contains(kind)) + .ok_or("trigger_kind is required when type is trigger.")?; + format!("{kind}_triggers") + } + "script" | "flow" | "schedule" | "resource" | "variable" | "app" => { + format!("{item_type}s") + } + _ => return Err(format!("Invalid type \"{item_type}\"")), + }) +} + +pub(super) fn exists_route( + ctx: &Ctx<'_>, + item_type: &str, + trigger_kind: Option<&str>, + path: &str, +) -> Result<String, String> { + let by_path = if item_type == "script" { "p/" } else { "" }; + Ok(ctx.ws(&format!( + "{}/exists/{by_path}{}", + service(item_type, trigger_kind)?, + path_enc(path) + ))) +} + +pub(super) fn get_route( + ctx: &Ctx<'_>, + item_type: &str, + trigger_kind: Option<&str>, + path: &str, +) -> Result<String, String> { + let by_path = if matches!(item_type, "script" | "app") { + "p/" + } else { + "" + }; + // A variable's value never reaches a tool, so it is not decrypted to begin with. + let query = if item_type == "variable" { + "?decrypt_secret=false" + } else { + "" + }; + Ok(ctx.ws(&format!( + "{}/get/{by_path}{}{query}", + service(item_type, trigger_kind)?, + path_enc(path) + ))) +} + +pub(super) async fn item_exists( + ctx: &Ctx<'_>, + item_type: &str, + trigger_kind: Option<&str>, + path: &str, +) -> Result<bool, String> { + let exists = ctx + .get(&exists_route(ctx, item_type, trigger_kind, path)?) + .await?; + Ok(exists.as_bool().unwrap_or(false)) +} + +/// `exists` hides an archived script, which its path still resolves to and a delete by +/// path still removes, so an archived script counts as deployed. +pub(super) async fn deployed_item_exists( + ctx: &Ctx<'_>, + item_type: &str, + trigger_kind: Option<&str>, + path: &str, +) -> Result<bool, String> { + if item_exists(ctx, item_type, trigger_kind, path).await? { + return Ok(true); + } + if item_type != "script" { + return Ok(false); + } + match get_deployed(ctx, "script", None, path).await { + Ok(_) => Ok(true), + Err(e) if is_not_found(&e) => Ok(false), + Err(e) => Err(e), + } +} + +pub(super) async fn get_deployed( + ctx: &Ctx<'_>, + item_type: &str, + trigger_kind: Option<&str>, + path: &str, +) -> Result<Value, String> { + ctx.get(&get_route(ctx, item_type, trigger_kind, path)?) + .await +} + +pub(super) struct Draft { + pub value: Value, + pub created_at: Option<String>, +} + +pub(super) async fn get_draft( + ctx: &Ctx<'_>, + kind: &str, + path: &str, +) -> Result<Option<Draft>, String> { + let row = ctx + .get(&ctx.ws(&format!("drafts/get_own/{kind}/{}", path_enc(path)))) + .await?; + let Some(value) = non_null(row.get("value")).cloned() else { + return Ok(None); + }; + let created_at = row + .get("created_at") + .and_then(Value::as_str) + .map(String::from); + Ok(Some(Draft { value, created_at })) +} + +pub(super) async fn save_draft( + ctx: &Ctx<'_>, + kind: &str, + path: &str, + value: Option<&Value>, + last_sync: Option<&str>, + force: bool, +) -> Result<bool, String> { + let mut body = Map::new(); + body.insert("value".into(), value.cloned().unwrap_or(Value::Null)); + if !force { + put(&mut body, "last_sync", last_sync.map(Value::from)); + } + body.insert("force".into(), json!(force)); + let response = ctx + .post( + &ctx.ws(&format!("drafts/update/{kind}/{}", path_enc(path))), + Value::Object(body), + ) + .await?; + Ok(response.get("status").and_then(Value::as_str) != Some("conflict")) +} + +pub(super) async fn delete_draft( + ctx: &Ctx<'_>, + kind: &str, + path: &str, + last_sync: Option<&str>, +) -> Result<(), String> { + match save_draft(ctx, kind, path, None, last_sync, false).await { + Ok(true) => Ok(()), + Ok(false) => Err(format!( + "Draft \"{path}\" changed externally since you last read it; it was not removed. Re-read and retry." + )), + Err(e) => Err(api_message(&e).to_string()), + } +} + +pub(super) async fn list_drafts(ctx: &Ctx<'_>) -> Result<Vec<Value>, String> { + let rows = ctx.get(&ctx.ws("drafts/list")).await?; + let rows = array(Some(&rows)); + let mut drafts = Map::new(); + for row in rows { + let (Some(kind), Some(path)) = ( + row.get("kind").and_then(Value::as_str), + row.get("path").and_then(Value::as_str), + ) else { + continue; + }; + let Some((item_type, trigger_kind)) = item_type_of_kind(kind) else { + continue; + }; + let mut item = Map::new(); + item.insert("type".into(), json!(item_type)); + item.insert("path".into(), json!(path)); + put( + &mut item, + "draftPath", + row.get("draft_path") + .filter(|p| p.as_str() != Some(path)) + .cloned(), + ); + put(&mut item, "summary", row.get("summary").cloned()); + item.insert("isDraft".into(), json!(true)); + put(&mut item, "triggerKind", trigger_kind.map(Value::from)); + if kind == "raw_app" { + item.insert("rawApp".into(), json!(true)); + } + drafts.insert(item_key(item_type, path, trigger_kind), Value::Object(item)); + } + Ok(drafts.into_iter().map(|(_, item)| item).collect()) +} + +pub(super) fn normalize_app_draft(value: &Value) -> Value { + let mut out = Map::new(); + put(&mut out, "summary", value.get("summary").cloned()); + out.insert("files".into(), object_or_empty(value.get("files"))); + out.insert("runnables".into(), object_or_empty(value.get("runnables"))); + out.insert( + "data".into(), + non_null(value.get("data")) + .cloned() + .unwrap_or_else(|| json!({ "tables": [] })), + ); + for key in ["policy", "custom_path", "parent_version", "draft_path"] { + put(&mut out, key, value.get(key).cloned()); + } + Value::Object(out) +} + +pub(super) fn draft_item(kind: &str, path: &str, draft: &Value) -> Option<Value> { + let (item_type, trigger_kind) = item_type_of_kind(kind)?; + let field = |key: &str| draft.get(key).cloned(); + let mut item = Map::new(); + item.insert("type".into(), json!(item_type)); + put(&mut item, "triggerKind", trigger_kind.map(Value::from)); + item.insert("path".into(), json!(path)); + // A staged name that repeats the storage path tells the reader nothing. + let draft_path = |value: &Value| { + value + .get("draft_path") + .filter(|p| p.as_str() != Some(path)) + .cloned() + }; + match item_type { + "script" => { + put(&mut item, "draftPath", draft_path(draft)); + put(&mut item, "summary", field("summary")); + put(&mut item, "language", field("language")); + put(&mut item, "value", field("content")); + put(&mut item, "schema", field("schema")); + put(&mut item, "parentHash", field("parent_hash")); + } + "flow" => { + put(&mut item, "draftPath", draft_path(draft)); + put(&mut item, "summary", field("summary")); + put(&mut item, "parentVersionId", field("version_id")); + let or_null = |v: Option<&Value>| v.cloned().unwrap_or(Value::Null); + item.insert( + "value".into(), + json!({ + "value": or_null(draft.get("value")), + "schema": or_null(draft.get("schema")), + "groups": or_null(draft.get("value").and_then(|v| v.get("groups"))), + "description": or_null(draft.get("description")), + }), + ); + } + "app" => { + let value = normalize_app_draft(draft); + put(&mut item, "draftPath", draft_path(&value)); + put(&mut item, "summary", value.get("summary").cloned()); + put( + &mut item, + "parentVersionId", + value.get("parent_version").cloned(), + ); + item.insert("value".into(), value); + item.insert("rawApp".into(), json!(true)); + } + "schedule" => { + put( + &mut item, + "summary", + non_null(draft.get("summary")).cloned(), + ); + item.insert("value".into(), draft.clone()); + } + "trigger" => { + put( + &mut item, + "summary", + field("summary").filter(|s| truthy(Some(s))), + ); + item.insert("value".into(), draft.clone()); + } + "resource" => { + put( + &mut item, + "summary", + field("description").filter(|d| truthy(Some(d))), + ); + let mut value = Map::new(); + value.insert("path".into(), json!(path)); + put(&mut value, "value", field("args")); + put(&mut value, "description", field("description")); + value.insert( + "resource_type".into(), + non_null(draft.get("resource_type")) + .cloned() + .unwrap_or_else(|| json!("")), + ); + put(&mut value, "labels", field("labels")); + put(&mut value, "ws_specific", field("wsSpecific")); + item.insert("value".into(), Value::Object(value)); + } + "variable" => { + let variable = draft.get("variable").cloned().unwrap_or(Value::Null); + put( + &mut item, + "summary", + variable + .get("description") + .filter(|d| truthy(Some(d))) + .cloned(), + ); + put(&mut item, "isSecret", variable.get("is_secret").cloned()); + let mut value = Map::new(); + value.insert("path".into(), json!(path)); + put(&mut value, "value", variable.get("value").cloned()); + put(&mut value, "is_secret", variable.get("is_secret").cloned()); + put( + &mut value, + "description", + variable.get("description").cloned(), + ); + put(&mut value, "account", field("account")); + put(&mut value, "is_oauth", field("is_oauth")); + put(&mut value, "expires_at", field("expires_at")); + put(&mut value, "value_valid_until", field("value_valid_until")); + put(&mut value, "labels", field("labels")); + put(&mut value, "ws_specific", field("wsSpecific")); + item.insert("value".into(), Value::Object(value)); + } + _ => return None, + } + item.insert("isDraft".into(), json!(true)); + Some(Value::Object(item)) +} + +pub(super) async fn get_draft_item( + ctx: &Ctx<'_>, + item_type: &str, + path: &str, + trigger_kind: Option<&str>, +) -> Result<Option<(Value, Draft)>, String> { + let Some(kind) = draft_kind(item_type, trigger_kind) else { + return Ok(None); + }; + let Some(draft) = get_draft(ctx, &kind, path).await? else { + return Ok(None); + }; + Ok(draft_item(&kind, path, &draft.value).map(|item| (item, draft))) +} + +fn stash_inline_script( + value: &mut Map<String, Value>, + id: &str, + scripts: &mut HashMap<String, String>, +) { + if let Some(Value::String(content)) = value.get("content") { + scripts.insert(id.to_string(), content.clone()); + value.insert("content".into(), json!(format!("inline_script.{id}"))); + } +} + +fn compact_modules(modules: Option<&Value>, scripts: &mut HashMap<String, String>) -> Value { + let Some(modules) = modules.and_then(Value::as_array) else { + return json!([]); + }; + Value::Array( + modules + .iter() + .map(|module| compact_module(module, scripts)) + .collect(), + ) +} + +fn compact_branches(value: &mut Map<String, Value>, scripts: &mut HashMap<String, String>) { + let Some(Value::Array(branches)) = value.get_mut("branches") else { + return; + }; + for branch in branches { + if let Value::Object(branch) = branch { + let modules = compact_modules(branch.get("modules"), scripts); + branch.insert("modules".into(), modules); + } + } +} + +fn compact_module(module: &Value, scripts: &mut HashMap<String, String>) -> Value { + let mut module = module.clone(); + let id = module + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let Some(value) = module.get_mut("value").and_then(Value::as_object_mut) else { + return module; + }; + match value.get("type").and_then(Value::as_str) { + Some("rawscript") => stash_inline_script(value, &id, scripts), + Some("forloopflow" | "whileloopflow") if truthy(value.get("modules")) => { + let modules = compact_modules(value.get("modules"), scripts); + value.insert("modules".into(), modules); + } + Some("branchone") => { + compact_branches(value, scripts); + if truthy(value.get("default")) { + let default = compact_modules(value.get("default"), scripts); + value.insert("default".into(), default); + } + } + Some("branchall") => compact_branches(value, scripts), + Some("aiagent") => { + if let Some(Value::Array(tools)) = value.get_mut("tools") { + for tool in tools { + let tool_id = tool + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let Some(tool_value) = tool.get_mut("value").and_then(Value::as_object_mut) + else { + continue; + }; + let is = |key: &str, expected: &str| { + tool_value.get(key).and_then(Value::as_str) == Some(expected) + }; + if is("tool_type", "flowmodule") && is("type", "rawscript") { + stash_inline_script(tool_value, &tool_id, scripts); + } + } + } + } + _ => {} + } + module +} + +pub(super) fn compact_flow( + value: &Value, + schema: Option<&Value>, +) -> (Value, HashMap<String, String>) { + let mut scripts = HashMap::new(); + let mut out = Map::new(); + out.insert( + "modules".into(), + compact_modules(value.get("modules"), &mut scripts), + ); + out.insert("schema".into(), schema.cloned().unwrap_or(Value::Null)); + for key in ["preprocessor_module", "failure_module"] { + let mut module = value.get(key).cloned().unwrap_or(Value::Null); + let id = module + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + if let Some(module_value) = module.get_mut("value").and_then(Value::as_object_mut) { + if module_value.get("type").and_then(Value::as_str) == Some("rawscript") { + stash_inline_script(module_value, &id, &mut scripts); + } + } + out.insert(key.into(), module); + } + for key in ["groups", "notes"] { + out.insert(key.into(), value.get(key).cloned().unwrap_or(Value::Null)); + } + for key in FLOW_VALUE_SETTINGS_KEYS { + put(&mut out, key, value.get(*key).cloned()); + } + (Value::Object(out), scripts) +} + +pub(super) fn app_source_to_draft_value(app: &Value, fallback: Option<&Value>) -> Value { + // A deployed app nests its source under `value`; a draft carries it at the top. + let source = app.get("value").filter(|v| !v.is_null()).unwrap_or(app); + let data = source.get("data"); + let creation = data.and_then(|d| d.get("creation")); + let tables_only = |tables: &Value| json!({ "tables": tables }); + let data = if truthy(creation) { + let mut out = Map::new(); + out.insert( + "tables".into(), + data.and_then(|d| non_null(d.get("tables"))) + .cloned() + .unwrap_or_else(|| json!([])), + ); + put( + &mut out, + "datatable", + creation.and_then(|c| c.get("datatable")).cloned(), + ); + put( + &mut out, + "schema", + creation.and_then(|c| c.get("schema")).cloned(), + ); + Value::Object(out) + } else if truthy(data) { + data.cloned().unwrap_or_default() + } else if truthy(source.get("datatables")) { + tables_only(&source["datatables"]) + } else if truthy(source.get("dataTableRefs")) { + tables_only(&source["dataTableRefs"]) + } else { + tables_only(&json!([])) + }; + let or_fallback = |key: &str| { + non_null(app.get(key)) + .cloned() + .or_else(|| fallback?.get(key).cloned()) + }; + let mut out = Map::new(); + out.insert( + "summary".into(), + non_null(app.get("summary")) + .cloned() + .unwrap_or_else(|| json!("")), + ); + out.insert("files".into(), object_or_empty(source.get("files"))); + out.insert("runnables".into(), object_or_empty(source.get("runnables"))); + out.insert("data".into(), data); + put(&mut out, "policy", or_fallback("policy")); + put(&mut out, "custom_path", or_fallback("custom_path")); + // The fork base: the head of a deployed app's versions, or what a draft already pinned. + let head = app + .get("versions") + .and_then(Value::as_array) + .and_then(|versions| versions.last()) + .filter(|v| !v.is_null()) + .cloned(); + put( + &mut out, + "parent_version", + non_null(app.get("parent_version")) + .cloned() + .or(head) + .or_else(|| fallback?.get("parent_version").cloned()), + ); + Value::Object(out) +} + +pub(super) fn summarize_app_value(value: &Value) -> Value { + let entries = |key: &str| { + value + .get(key) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default() + }; + let frontend: Vec<Value> = entries("files") + .iter() + .map(|(path, content)| json!({ "path": path, "size": content.as_str().map(js_len).unwrap_or(0) })) + .collect(); + let backend: Vec<Value> = entries("runnables") + .iter() + .map(|(key, runnable)| { + let mut out = Map::new(); + out.insert("key".into(), json!(key)); + if !truthy(Some(runnable)) { + out.insert("name".into(), json!(key)); + out.insert("type".into(), json!("inline")); + return Value::Object(out); + } + out.insert( + "name".into(), + non_null(runnable.get("name")) + .cloned() + .unwrap_or_else(|| json!(key)), + ); + let kind = runnable.get("type").and_then(Value::as_str); + let by_path = matches!(kind, Some("path" | "runnableByPath")); + let run_type = match runnable.get("runType").and_then(Value::as_str) { + _ if !by_path => "inline", + Some("flow") => "flow", + Some("hubscript") => "hubscript", + _ => "script", + }; + out.insert("type".into(), json!(run_type)); + if by_path && truthy(runnable.get("path")) { + out.insert("path".into(), runnable["path"].clone()); + } + let inline = runnable.get("inlineScript").filter(|s| truthy(Some(s))); + if let Some(inline) = + inline.filter(|_| matches!(kind, Some("inline" | "runnableByName"))) + { + let language = match inline.get("language") { + Some(Value::String(l)) if l == "nativets" || l == "deno" => Some(json!("bun")), + other => other.cloned(), + }; + put(&mut out, "language", language); + let content = inline + .get("content") + .and_then(Value::as_str) + .unwrap_or_default(); + out.insert("contentSize".into(), json!(js_len(content))); + } + let static_keys: Vec<&String> = runnable + .get("fields") + .and_then(Value::as_object) + .map(|fields| { + fields + .iter() + .filter(|(_, v)| v.get("type").and_then(Value::as_str) == Some("static")) + .map(|(k, _)| k) + .collect() + }) + .unwrap_or_default(); + if !static_keys.is_empty() { + out.insert("staticInputKeys".into(), json!(static_keys)); + } + Value::Object(out) + }) + .collect(); + let mut out = Map::new(); + out.insert("frontend".into(), Value::Array(frontend)); + out.insert("backend".into(), Value::Array(backend)); + if truthy(value.get("data")) { + out.insert("data".into(), value["data"].clone()); + } + Value::Object(out) +} + +/// `guest` is stored on an app whether or not anyone is admitted by it, so the mode +/// alone would say strangers can open an app that admits members only. +pub(super) async fn describe_app_exposure(ctx: &Ctx<'_>, mode: Option<&Value>) -> Option<Value> { + if mode.and_then(Value::as_str) != Some("guest") { + return mode.cloned(); + } + let usage = ctx.get(&ctx.ws("workspaces/guest_usage")).await; + let settings = ctx.get(&ctx.ws("workspaces/get_public_settings")).await; + // A switch that could not be read proves nothing either way: report the mode bare. + let (Ok(usage), Ok(settings)) = (usage, settings) else { + return mode.cloned(); + }; + let live = truthy(usage.get("available")) + && truthy(usage.get("instance_enabled")) + && truthy(settings.get("guest_access_enabled")); + if live { + mode.cloned() + } else { + Some(json!( + "guest, but inert: the instance or workspace admits no guest, so this app admits members only" + )) + } +} + +pub(super) fn serialize_for_read(item: &Value, execution_mode: Option<Value>) -> Value { + let item_type = item.get("type").and_then(Value::as_str); + let mut out = Map::new(); + let copy = |out: &mut Map<String, Value>, keys: &[&str]| { + for key in keys { + put(out, key, item.get(*key).cloned()); + } + }; + match item_type { + Some("variable") => copy( + &mut out, + &[ + "type", + "path", + "summary", + "isSecret", + "extraPerms", + "isDraft", + ], + ), + Some("app") if item.get("value").is_some_and(|v| v.get("files").is_some()) => { + copy(&mut out, &["type", "path", "summary"]); + out.insert("value".into(), summarize_app_value(&item["value"])); + copy(&mut out, &["rawApp"]); + put( + &mut out, + "executionMode", + execution_mode.or_else(|| item.get("executionMode").cloned()), + ); + copy(&mut out, &["extraPerms", "isDraft"]); + } + Some("flow") if truthy(item.get("value")) => { + let flow = &item["value"]; + // A draft carries `groups` beside the flow value; a set one outranks the value's. + let mut value = flow.get("value").cloned().unwrap_or_else(|| json!({})); + if let (Some(groups), Some(value)) = (flow.get("groups"), value.as_object_mut()) { + if groups.is_null() { + value.remove("groups"); + } else { + value.insert("groups".into(), groups.clone()); + } + } + copy(&mut out, &["type", "path", "summary"]); + out.insert( + "value".into(), + compact_flow(&value, non_null(flow.get("schema"))).0, + ); + copy(&mut out, &["extraPerms", "isDraft"]); + } + _ => { + let mut item = item.clone(); + if let (Some(mode), Some(item)) = (execution_mode, item.as_object_mut()) { + item.insert("executionMode".into(), mode); + } + return item; + } + } + Value::Object(out) +} + +pub(super) struct LoadedScript { + pub content: String, + pub language: String, + pub summary: Option<String>, + pub schema: Option<Value>, +} + +pub(super) async fn load_script(ctx: &Ctx<'_>, path: &str) -> Result<LoadedScript, String> { + let text = |value: &Value, key: &str| value.get(key).and_then(Value::as_str).map(String::from); + if let Some((item, _)) = get_draft_item(ctx, "script", path, None).await? { + let (Some(content), Some(language)) = ( + text(&item, "value"), + text(&item, "language").filter(|l| !l.is_empty()), + ) else { + return Err(format!( + "Draft script \"{path}\" is missing content or language." + )); + }; + return Ok(LoadedScript { + content, + language, + summary: text(&item, "summary"), + schema: non_null(item.get("schema")).cloned(), + }); + } + let script = get_deployed(ctx, "script", None, path).await?; + Ok(LoadedScript { + content: text(&script, "content").unwrap_or_default(), + language: text(&script, "language").unwrap_or_default(), + summary: text(&script, "summary"), + schema: non_null(script.get("schema")).cloned(), + }) +} + +pub(super) struct LoadedFlow { + /// `{value, schema, groups}`, plus `description` when read from a draft. + pub flow: Value, + pub summary: Option<String>, + pub is_draft: bool, +} + +pub(super) async fn load_flow(ctx: &Ctx<'_>, path: &str) -> Result<LoadedFlow, String> { + let summary = |value: &Value| { + value + .get("summary") + .and_then(Value::as_str) + .map(String::from) + }; + if let Some((item, _)) = get_draft_item(ctx, "flow", path, None).await? { + let Some(flow) = item.get("value").filter(|v| v.is_object()) else { + return Err(format!("Draft flow \"{path}\" has no value.")); + }; + return Ok(LoadedFlow { flow: flow.clone(), summary: summary(&item), is_draft: true }); + } + let flow = get_deployed(ctx, "flow", None, path).await?; + Ok(LoadedFlow { flow: deployed_flow_value(&flow), summary: summary(&flow), is_draft: false }) +} + +fn deployed_flow_value(flow: &Value) -> Value { + let mut out = Map::new(); + put(&mut out, "value", flow.get("value").cloned()); + put(&mut out, "schema", flow.get("schema").cloned()); + out.insert( + "groups".into(), + flow.get("value") + .and_then(|v| non_null(v.get("groups"))) + .cloned() + .unwrap_or(Value::Null), + ); + Value::Object(out) +} + +pub(super) struct WriteBase { + pub base: Option<Value>, + pub from_draft: bool, + pub last_sync: Option<String>, +} + +pub(super) async fn write_base( + ctx: &Ctx<'_>, + item_type: &str, + path: &str, + trigger_kind: Option<&str>, +) -> Result<WriteBase, String> { + // A failed draft read must not fall through to the deployed item: the write would + // then be built on it and replace the draft's own changes. + let draft = match draft_kind(item_type, trigger_kind) { + Some(kind) => get_draft(ctx, &kind, path).await?, + None => None, + }; + if let Some(draft) = draft { + return Ok(WriteBase { + base: Some(draft.value), + from_draft: true, + last_sync: draft.created_at, + }); + } + let base = if item_exists(ctx, item_type, trigger_kind, path).await? { + Some(get_deployed(ctx, item_type, trigger_kind, path).await?) + } else { + None + }; + Ok(WriteBase { base, from_draft: false, last_sync: None }) +} + +pub(super) enum Persist { + Saved(Value), + Failed(String), +} + +pub(super) async fn persist_draft( + ctx: &Ctx<'_>, + item_type: &str, + path: &str, + trigger_kind: Option<&str>, + value: &Value, + last_sync: Option<&str>, + force: bool, +) -> Result<Persist, String> { + let kind = draft_kind(item_type, trigger_kind) + .ok_or_else(|| format!("Unsupported draft type \"{item_type}\"."))?; + let item = draft_item(&kind, path, value) + .ok_or_else(|| format!("Could not synthesize {item_type} draft \"{path}\"."))?; + let failure = match save_draft(ctx, &kind, path, Some(value), last_sync, force).await { + Ok(true) => return Ok(Persist::Saved(item)), + Ok(false) => json!({ + "success": false, + "conflict": true, + "message": format!("The {item_type} draft \"{path}\" changed externally since you last read it. Re-run this tool to merge onto the latest version, or pass override:true to overwrite. If an editor for it is open, a conflict dialog is also shown there."), + }), + Err(e) => json!({ + "success": false, + "error": true, + "message": format!("The {item_type} draft \"{path}\" could NOT be saved ({}). The change was not persisted — retry; do not assume it succeeded.", api_message(&e)), + }), + }; + Ok(Persist::Failed(pretty(&failure))) +} + +/// Whether a resource's draft or deployed value is an AI agent, which has its own page. +pub(super) fn is_agent(value: &Value) -> bool { + value.get("resource_type").and_then(Value::as_str) == Some("ai_agent") +} + +/// The editor that shows the user's draft: a detail page shows only the deployed version. +fn draft_page(item_type: &str, path: &str, value: &Value) -> Option<String> { + Some(match item_type { + "script" => format!("/scripts/edit/{path}?nomenubar=true"), + "flow" => format!("/flows/edit/{path}?nomenubar=true"), + "resource" if is_agent(value) => format!("/agents/edit/{path}?nomenubar=true"), + _ => return None, + }) +} + +pub(super) fn finish_draft_write(ctx: &Ctx<'_>, item: &Value, existed: bool) -> String { + let text = |key: &str| item.get(key).and_then(Value::as_str).unwrap_or_default(); + let (item_type, path) = (text("type"), text("path")); + let verb = if existed { "Updated" } else { "Created" }; + let mut out = Map::new(); + out.insert("success".into(), json!(true)); + out.insert( + "message".into(), + json!(format!("{verb} {item_type} \"{path}\" as a per-user draft (saved server-side, visible only to this user — not a deployed workspace item). It was not deployed.")), + ); + let value = item.get("value").unwrap_or(&Value::Null); + if let Some(page) = draft_page(item_type, path, value) { + out.insert("url".into(), json!(ctx.page_url(&page))); + } + // A flow is not echoed back: the model just sent it. A variable comes back redacted. + match item_type { + "flow" => {} + "variable" => { + out.insert("item".into(), serialize_for_read(item, None)); + } + _ => { + out.insert("item".into(), item.clone()); + } + } + pretty(&Value::Object(out)) +} + +pub(super) fn find_and_replace( + content: &str, + old: &str, + new: &str, + replace_all: bool, + label: &str, +) -> Result<String, String> { + let matches = if old.is_empty() { + 0 + } else { + content.matches(old).count() + }; + if matches == 0 { + return Err(format!("old_string was not found in the {label}.")); + } + if !replace_all && matches != 1 { + return Err(format!( + "old_string matched {matches} locations. Make it more specific or set replace_all to true." + )); + } + Ok(content.replace(old, new)) +} + +pub(super) fn empty_schema() -> Value { + json!({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": {}, + "required": [], + "type": "object", + }) +} + +pub(super) fn infer_script_schema( + language: &str, + content: &str, + previous: Option<&Value>, + entrypoint: Option<&str>, +) -> Option<Value> { + use windmill_common::scripts::{ScriptKind, ScriptLang}; + let language: ScriptLang = serde_json::from_value(Value::String(language.to_string())).ok()?; + let kind = (entrypoint == Some("preprocessor")).then_some(ScriptKind::Preprocessor); + let schema = windmill_api_scripts::scripts::infer_main_schema( + &language, + kind.as_ref(), + content, + previous, + )?; + serde_json::to_value(schema).ok() +} + +/// Lines with their terminator kept, so a missing final newline is a difference. +fn patch_lines(text: &str) -> Vec<&str> { + text.split_inclusive('\n').collect() +} + +/// `(tag, line)` for every line of both sides, `' '` for a shared one, deletions ahead +/// of insertions within a change. +fn diff_lines<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(char, &'a str)> { + let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count(); + let suffix = old[prefix..] + .iter() + .rev() + .zip(new[prefix..].iter().rev()) + .take_while(|(a, b)| a == b) + .count(); + let (a, b) = ( + &old[prefix..old.len() - suffix], + &new[prefix..new.len() - suffix], + ); + let mut ops: Vec<(char, &str)> = old[..prefix].iter().map(|l| (' ', *l)).collect(); + let (n, m) = (a.len(), b.len()); + // ponytail: quadratic LCS table. Past the cap the changed region is reported as + // replaced wholesale, still a valid patch; switch to Myers if that ever shows. + const MAX_CELLS: usize = 4_000_000; + if (n + 1).saturating_mul(m + 1) > MAX_CELLS { + ops.extend(a.iter().map(|l| ('-', *l))); + ops.extend(b.iter().map(|l| ('+', *l))); + } else { + let width = m + 1; + let mut lcs = vec![0u32; (n + 1) * width]; + for i in (0..n).rev() { + for j in (0..m).rev() { + lcs[i * width + j] = if a[i] == b[j] { + lcs[(i + 1) * width + j + 1] + 1 + } else { + lcs[(i + 1) * width + j].max(lcs[i * width + j + 1]) + }; + } + } + let (mut i, mut j) = (0, 0); + let mut inserted = Vec::new(); + while i < n || j < m { + if i < n && j < m && a[i] == b[j] { + ops.extend(inserted.drain(..)); + ops.push((' ', a[i])); + i += 1; + j += 1; + } else if j == m || (i < n && lcs[(i + 1) * width + j] >= lcs[i * width + j + 1]) { + ops.push(('-', a[i])); + i += 1; + } else { + inserted.push(('+', b[j])); + j += 1; + } + } + ops.extend(inserted); + } + ops.extend(old[old.len() - suffix..].iter().map(|l| (' ', *l))); + ops +} + +pub(super) fn unified_patch( + old_name: &str, + new_name: &str, + old: &str, + new: &str, + context: usize, +) -> String { + let ops = diff_lines(&patch_lines(old), &patch_lines(new)); + let mut out = String::new(); + if old_name == new_name { + out.push_str(&format!("Index: {old_name}\n")); + } + out.push_str(&format!( + "===================================================================\n--- {old_name}\t\n+++ {new_name}\t\n" + )); + let changes: Vec<usize> = (0..ops.len()).filter(|i| ops[*i].0 != ' ').collect(); + let mut next = 0; + while next < changes.len() { + let first = changes[next]; + let mut last = first; + // Two changes share a hunk when their contexts would touch. + while next + 1 < changes.len() && changes[next + 1] - last - 1 <= 2 * context { + next += 1; + last = changes[next]; + } + next += 1; + let start = first.saturating_sub(context); + let end = (last + context + 1).min(ops.len()); + let count = + |range: &[(char, &str)], skip: char| range.iter().filter(|op| op.0 != skip).count(); + let (old_before, new_before) = (count(&ops[..start], '+'), count(&ops[..start], '-')); + let (old_count, new_count) = (count(&ops[start..end], '+'), count(&ops[start..end], '-')); + // An empty side is addressed by the line before it. + let old_start = old_before + usize::from(old_count > 0); + let new_start = new_before + usize::from(new_count > 0); + out.push_str(&format!( + "@@ -{old_start},{old_count} +{new_start},{new_count} @@\n" + )); + for (tag, line) in &ops[start..end] { + out.push(*tag); + match line.strip_suffix('\n') { + Some(line) => { + out.push_str(line); + out.push('\n'); + } + None => { + out.push_str(line); + out.push_str("\n\\ No newline at end of file\n"); + } + } + } + } + out +} + +// ============================================================================ +// Tools +// ============================================================================ + +fn deployed_item(item_type: &str, trigger_kind: Option<&str>, row: &Value) -> Value { + let mut item = Map::new(); + item.insert("type".into(), json!(item_type)); + put(&mut item, "triggerKind", trigger_kind.map(Value::from)); + put(&mut item, "path", row.get("path").cloned()); + let mut is_draft = false; + match item_type { + "script" | "flow" => { + put(&mut item, "summary", row.get("summary").cloned()); + if item_type == "script" { + put(&mut item, "language", row.get("language").cloned()); + } + // A listing synthesizes rows for drafts with no deployed counterpart. + is_draft = truthy(row.get("draft_only")); + } + "schedule" | "trigger" => put(&mut item, "summary", non_null(row.get("summary")).cloned()), + "resource" => put(&mut item, "summary", row.get("description").cloned()), + "variable" => { + put(&mut item, "summary", row.get("description").cloned()); + put(&mut item, "isSecret", row.get("is_secret").cloned()); + } + _ => { + put(&mut item, "summary", row.get("summary").cloned()); + // The server omits the flag rather than sending false. + item.insert( + "rawApp".into(), + non_null(row.get("raw_app")) + .cloned() + .unwrap_or(json!(false)), + ); + } + } + item.insert("isDraft".into(), json!(is_draft)); + Value::Object(item) +} + +/// Put `value` (and a script's `schema`) where the session's item shape has them. +fn with_value(item: Value, value: Option<Value>, schema: Option<Value>) -> Value { + let Value::Object(item) = item else { + return item; + }; + let mut out = Map::new(); + for (key, field) in item { + if key == "isDraft" { + put(&mut out, "value", value.clone()); + put(&mut out, "schema", schema.clone()); + } + out.insert(key, field); + } + Value::Object(out) +} + +async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let requested: Vec<&str> = args + .get("types") + .and_then(Value::as_array) + .map(|types| types.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let (access_types, item_types): (Vec<&str>, Vec<&str>) = requested + .into_iter() + .partition(|t| ACCESS_TYPES.contains(t)); + // Asking only for folders or groups must not fall back to the default scripts and flows. + let types = if item_types.is_empty() && access_types.is_empty() { + vec!["script", "flow"] + } else { + item_types + }; + let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50); + let page = args.get("page").and_then(Value::as_u64); + let prefix = opt_str_arg(args, "path_prefix"); + + let mut query = format!("per_page={}", limit.min(MAX_LIST_LIMIT)); + if let Some(page) = page { + query.push_str(&format!("&page={page}")); + } + + // Group rows carry no members: the list endpoint does not return them. + let mut access_rows = Vec::new(); + for access_type in ACCESS_TYPES.iter().filter(|t| access_types.contains(t)) { + let rows = ctx + .get(&ctx.ws(&format!("{access_type}s/list?{query}"))) + .await?; + for row in array(Some(&rows)) { + let mut item = Map::new(); + item.insert("type".into(), json!(access_type)); + put(&mut item, "path", row.get("name").cloned()); + put(&mut item, "summary", row.get("summary").cloned()); + if *access_type == "folder" { + put(&mut item, "owners", row.get("owners").cloned()); + } + put(&mut item, "extraPerms", row.get("extra_perms").cloned()); + access_rows.push(Value::Object(item)); + } + } + + if let Some(prefix) = prefix { + query.push_str(&format!("&path_start={}", enc(prefix))); + } + + let mut by_key = Map::new(); + for item_type in ITEM_TYPES.iter().filter(|t| types.contains(t)) { + let kinds: Vec<Option<&str>> = if *item_type == "trigger" { + TRIGGER_KINDS.iter().map(|kind| Some(*kind)).collect() + } else { + vec![None] + }; + let extra = if matches!(*item_type, "script" | "flow") { + "&include_draft_only=true&without_description=true" + } else { + "" + }; + for trigger_kind in kinds { + let route = ctx.ws(&format!( + "{}/list?{query}{extra}", + service(item_type, trigger_kind)? + )); + let rows = match ctx.get(&route).await { + Ok(rows) => rows, + // A trigger kind this build does not serve answers 404: skip that kind + // alone. Any other failure is real. + Err(e) if trigger_kind.is_some() && is_not_found(&e) => continue, + Err(e) => return Err(e), + }; + for row in array(Some(&rows)) { + let path = row.get("path").and_then(Value::as_str).unwrap_or_default(); + by_key.insert( + item_key(item_type, path, trigger_kind), + deployed_item(item_type, trigger_kind, row), + ); + } + } + } + + // Drafts are not paginated: they overlay page 1 only, capped per type, so later + // pages never repeat a page-1 item as its draft twin. + if page.unwrap_or(1) == 1 { + let mut count_by_type: HashMap<String, u64> = HashMap::new(); + for draft in list_drafts(ctx).await? { + let text = |key: &str| draft.get(key).and_then(Value::as_str); + let (item_type, path) = ( + text("type").unwrap_or_default(), + text("path").unwrap_or_default(), + ); + if !types.contains(&item_type) { + continue; + } + // A draft's staged name is often not where it is stored, and this pass is + // the only source of draft-only rows under a prefix: either name may match. + if let Some(prefix) = prefix { + let staged = text("draftPath").is_some_and(|p| p.starts_with(prefix)); + if !path.starts_with(prefix) && !staged { + continue; + } + } + let count = count_by_type.entry(item_type.to_string()).or_default(); + if *count >= limit { + continue; + } + *count += 1; + by_key.insert( + item_key(item_type, path, text("triggerKind")), + draft.clone(), + ); + } + } + + 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 }; + ["path", "summary"].iter().any(|key| { + item.get(*key) + .and_then(Value::as_str) + .is_some_and(|text| text.to_lowercase().contains(query)) + }) + }) + .collect(); + Ok(pretty(&Value::Array(results))) +} + +async fn read_workspace_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + if let Some(access_type) = opt_str_arg(args, "type").filter(|t| ACCESS_TYPES.contains(t)) { + return read_access_entity(ctx, access_type, str_arg(args, "path")?).await; + } + let item_type = item_type_arg(args)?; + let path = str_arg(args, "path")?; + let trigger_kind = opt_str_arg(args, "trigger_kind"); + if item_type == "trigger" && trigger_kind.is_none() { + return Ok( + json!({ "success": false, "error": "trigger_kind is required when type is trigger." }) + .to_string(), + ); + } + let deployed_only = opt_str_arg(args, "version") == Some("deployed"); + // Hub scripts live outside the workspace: no draft, no workspace lookup. + let hub = path.starts_with("hub/"); + + if !deployed_only && !hub { + if let Some((item, _)) = get_draft_item(ctx, item_type, path, trigger_kind).await? { + // The mode reported is the draft's, which is what deploying it will write. + let mode = if item_type == "app" { + let mode = item + .get("value") + .and_then(|v| v.get("policy")) + .and_then(|p| p.get("execution_mode")); + describe_app_exposure(ctx, mode).await + } else { + None + }; + return Ok(pretty(&serialize_for_read(&item, mode))); + } + } + + let item = match item_type { + "script" if hub => { + let script = ctx + .get(&format!("/scripts/hub/get_full/{}", path_enc(path))) + .await?; + let mut row = script.clone(); + row["path"] = json!(path); + let mut item = with_value( + deployed_item("script", None, &row), + script.get("content").cloned(), + script.get("schema").cloned(), + ); + item["isDraft"] = json!(false); + item + } + "script" | "flow" => { + let route = get_route(ctx, item_type, None, path)?; + let deployed = ctx + .get(&format!("{route}?get_draft={}", !deployed_only)) + .await?; + let extra_perms = deployed.get("extra_perms").cloned(); + // The draft stored on the item itself outranks its deployed version. + let row = non_null(deployed.get("draft")) + .cloned() + .filter(|_| !deployed_only) + .unwrap_or(deployed); + if item_type == "script" { + with_extra_perms( + with_value( + deployed_item("script", None, &row), + row.get("content").cloned(), + row.get("schema").cloned(), + ), + extra_perms, + ) + } else { + let item = with_value( + deployed_item("flow", None, &row), + Some(deployed_flow_value(&row)), + None, + ); + serialize_for_read(&with_extra_perms(item, extra_perms), None) + } + } + "variable" => { + let row = get_deployed(ctx, "variable", None, path).await?; + let item = with_extra_perms( + deployed_item("variable", None, &row), + row.get("extra_perms").cloned(), + ); + serialize_for_read(&item, None) + } + "app" => { + // Metadata only: file and runnable contents come through `read_app_file`. + let app = get_deployed(ctx, "app", None, path).await?; + let mode = + describe_app_exposure(ctx, app.get("policy").and_then(|p| p.get("execution_mode"))) + .await; + let mut item = Map::new(); + item.insert("type".into(), json!("app")); + put(&mut item, "path", app.get("path").cloned()); + // A grid is not files and runnables: summarizing one would report an empty app. + if app.get("raw_app") == Some(&json!(false)) { + put(&mut item, "summary", app.get("summary").cloned()); + } else { + let value = app_source_to_draft_value(&app, None); + put(&mut item, "summary", value.get("summary").cloned()); + item.insert("value".into(), summarize_app_value(&value)); + } + put(&mut item, "rawApp", app.get("raw_app").cloned()); + put(&mut item, "executionMode", mode); + put(&mut item, "extraPerms", app.get("extra_perms").cloned()); + item.insert("isDraft".into(), json!(false)); + Value::Object(item) + } + _ => { + let row = get_deployed(ctx, item_type, trigger_kind, path).await?; + let item = with_value( + deployed_item(item_type, trigger_kind, &row), + Some(row.clone()), + None, + ); + with_extra_perms(item, row.get("extra_perms").cloned()) + } + }; + Ok(pretty(&item)) +} + +/// Who a deployed item is shared with. A draft has no permissions of its own, so a draft +/// read leaves it out rather than reporting the item unshared. +fn with_extra_perms(mut item: Value, extra_perms: Option<Value>) -> Value { + if let Some(item) = item.as_object_mut() { + put(item, "extraPerms", extra_perms); + } + item +} + +/// Accepts the `f/<name>` / `g/<name>` form the model sees in extra_perms keys and paths. +fn access_entity_name<'a>(access_type: &str, path: &'a str) -> &'a str { + let prefix = if access_type == "folder" { "f/" } else { "g/" }; + path.strip_prefix(prefix) + .unwrap_or(path) + .trim_end_matches('/') +} + +async fn read_access_entity(ctx: &Ctx<'_>, access_type: &str, path: &str) -> ToolResult { + let name = access_entity_name(access_type, path); + let row = ctx + .get(&ctx.ws(&format!("{access_type}s/get/{}", enc(name)))) + .await?; + let mut entity = Map::new(); + entity.insert("type".into(), json!(access_type)); + put(&mut entity, "name", row.get("name").cloned()); + put(&mut entity, "summary", row.get("summary").cloned()); + if access_type == "folder" { + put(&mut entity, "owners", row.get("owners").cloned()); + put(&mut entity, "extraPerms", row.get("extra_perms").cloned()); + put( + &mut entity, + "defaultPermissionedAs", + row.get("default_permissioned_as").cloned(), + ); + } else { + put(&mut entity, "members", row.get("members").cloned()); + put(&mut entity, "extraPerms", row.get("extra_perms").cloned()); + } + Ok(pretty(&Value::Object(entity))) +} + +async fn write_script_draft( + ctx: &Ctx<'_>, + path: &str, + summary: Option<&str>, + language: &str, + content: &str, + force: bool, +) -> ToolResult { + let base = write_base(ctx, "script", path, None).await?; + let existed = base.base.is_some(); + let mut draft = match base.base { + Some(Value::Object(mut script)) => { + if !base.from_draft { + let hash = script.get("hash").cloned().unwrap_or(Value::Null); + script.insert("parent_hash".into(), hash); + // The deployed lock describes the deployed content, not the draft's; the + // deploy recomputes it. + script.shift_remove("lock"); + script.shift_remove("lock_error_logs"); + } + script.insert("path".into(), json!(path)); + put(&mut script, "summary", summary.map(Value::from)); + script.insert("content".into(), json!(content)); + script.insert("language".into(), json!(language)); + script + } + _ => json!({ + "path": path, + "summary": summary.unwrap_or_default(), + "description": "", + "content": content, + "schema": empty_schema(), + "is_template": false, + "language": language, + "kind": "script", + }) + .as_object() + .cloned() + .unwrap_or_default(), + }; + // Inferred into the schema the base carries: its properties are the only copy of + // what no parser emits (`password`, enums, formats, titles). Code that does not + // parse keeps the schema as it was. + let previous = draft + .get("schema") + .filter(|schema| truthy(schema.get("properties"))) + .cloned() + .unwrap_or_else(empty_schema); + let code = if content.is_empty() { " " } else { content }; + // A language this build cannot parse, or code that does not parse yet, keeps the + // schema the draft had. + let schema = infer_script_schema(language, code, Some(&previous), None).unwrap_or(previous); + draft.insert("schema".into(), schema); + let persisted = persist_draft( + ctx, + "script", + path, + None, + &Value::Object(draft), + base.last_sync.as_deref(), + force, + ) + .await?; + Ok(match persisted { + Persist::Saved(item) => finish_draft_write(ctx, &item, existed), + Persist::Failed(text) => text, + }) +} + +async fn edit_script(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let script = load_script(ctx, path).await?; + let updated = find_and_replace( + &script.content, + str_arg(args, "old_string")?, + str_arg(args, "new_string")?, + bool_arg(args, "replace_all"), + "script source", + )?; + write_script_draft( + ctx, + path, + script.summary.as_deref(), + &script.language, + &updated, + false, + ) + .await +} + +async fn discard_local_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let item_type = item_type_arg(args)?; + let path = str_arg(args, "path")?; + let trigger_kind = opt_str_arg(args, "trigger_kind"); + if item_type == "trigger" && trigger_kind.is_none() { + return Err("trigger_kind is required when discarding a trigger draft.".to_string()); + } + let not_found = || format!("No draft found for {item_type} \"{path}\"."); + let kind = draft_kind(item_type, trigger_kind).ok_or_else(not_found)?; + let draft = get_draft(ctx, &kind, path).await?.ok_or_else(not_found)?; + delete_draft(ctx, &kind, path, draft.created_at.as_deref()).await?; + let mut out = Map::new(); + out.insert("success".into(), json!(true)); + out.insert( + "message".into(), + json!(format!( + "Discarded the draft for {item_type} \"{path}\". The deployed workspace item was not changed." + )), + ); + out.insert("type".into(), json!(item_type)); + out.insert("path".into(), json!(path)); + put(&mut out, "triggerKind", trigger_kind.map(Value::from)); + Ok(pretty(&Value::Object(out))) +} + +/// Discards a stale draft and hands back its own changes against the version it was +/// forked from. Discarding rather than resetting keeps the fork base honest: the next +/// write starts from the current head, and a premature deploy finds no draft instead +/// of shipping the latest version unchanged. +async fn rebase_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let item_type = item_type_arg(args)?; + let path = str_arg(args, "path")?; + let (label, noun) = match item_type { + "script" => ("script", "Script"), + "flow" => ("flow", "Flow"), + "app" => ("app", "App"), + _ => return Err("rebase_draft currently supports scripts, flows, and apps.".to_string()), + }; + let no_draft = || format!("No {label} draft found for \"{path}\"."); + let (item, draft) = get_draft_item(ctx, item_type, path, None) + .await? + .ok_or_else(no_draft)?; + let value = item.get("value").cloned().unwrap_or(Value::Null); + let usable = match item_type { + "script" => value.is_string() && truthy(item.get("language")), + _ => value.is_object(), + }; + if !usable { + return Err(no_draft()); + } + if !item_exists(ctx, item_type, None, path).await? { + return Err(format!( + "{noun} \"{path}\" is not deployed; there is no newer version to rebase onto." + )); + } + let latest = get_deployed(ctx, item_type, None, path).await?; + let (base, head, head_key) = match item_type { + "script" => ( + item.get("parentHash").filter(|h| truthy(Some(h))).cloned(), + latest.get("hash").cloned(), + "latest_hash", + ), + "flow" => ( + non_null(item.get("parentVersionId")).cloned(), + latest.get("version_id").cloned(), + "latest_version", + ), + _ => ( + non_null(item.get("parentVersionId")).cloned(), + latest + .get("versions") + .and_then(Value::as_array) + .and_then(|versions| versions.last()) + .cloned(), + "latest_version", + ), + }; + let head_text = head + .as_ref() + .map_or_else(|| "undefined".to_string(), js_str); + if base.is_some() && base == head { + let mut out = Map::new(); + out.insert("success".into(), json!(true)); + out.insert("alreadyLatest".into(), json!(true)); + put(&mut out, head_key, head); + out.insert( + "message".into(), + json!(format!( + "Draft \"{path}\" is already based on the latest deployed version ({head_text})." + )), + ); + return Ok(Value::Object(out).to_string()); + } + + // Captured before the discard: this diff is the only record of what to replay. A + // base version that can no longer be fetched diffs against nothing, so the whole + // draft surfaces. + let base_id = base.as_ref().map(js_str); + let (theirs, ours) = match item_type { + "script" => { + let base_content = match &base_id { + Some(hash) => ctx + .get(&ctx.ws(&format!("scripts/get/h/{}", enc(hash)))) + .await + .ok() + .and_then(|s| s.get("content").and_then(Value::as_str).map(String::from)), + None => None, + }; + ( + base_content.unwrap_or_default(), + value.as_str().unwrap_or_default().to_string(), + ) + } + "flow" => { + let base_value = match &base_id { + Some(version) => ctx + .get(&ctx.ws(&format!("flows/get/v/{}", enc(version)))) + .await + .ok() + .and_then(|flow| flow.get("value").cloned()), + None => None, + }; + ( + pretty(&base_value.unwrap_or_else(|| json!({}))), + pretty(value.get("value").unwrap_or(&Value::Null)), + ) + } + _ => { + let source = |app: &Value| { + let mut out = Map::new(); + for key in ["files", "runnables", "data"] { + put(&mut out, key, app.get(key).cloned()); + } + Value::Object(out) + }; + let base_app = match &base_id { + Some(version) => ctx + .get(&ctx.ws(&format!("apps/get/v/{}", enc(version)))) + .await + .ok() + .map(|app| app_source_to_draft_value(&app, Some(&app))), + None => None, + }; + ( + pretty(&source( + &base_app.unwrap_or_else(|| json!({ "files": {}, "runnables": {} })), + )), + pretty(&source(&value)), + ) + } + }; + let your_changes = unified_patch("fork-base", "your-draft", &theirs, &ours, 4); + + let (diff, tools, version) = match item_type { + "script" => ( + "a diff", + "edit_script / write_script", + format!("hash {head_text}"), + ), + "flow" => ( + "a JSON diff", + "the flow edit tools", + format!("version {head_text}"), + ), + _ => ( + "a JSON diff", + "the app edit tools", + format!("version {head_text}"), + ), + }; + let mut out = Map::new(); + out.insert("success".into(), json!(true)); + out.insert( + "message".into(), + json!(format!( + "Discarded the stale draft for \"{path}\". Your changes are in \"your_changes\" ({diff} against the version you forked from). Re-apply them with {tools} — the new draft will be based on the latest deployed version ({version}) — then deploy." + )), + ); + put(&mut out, head_key, head); + out.insert("your_changes".into(), json!(your_changes)); + let result = pretty(&Value::Object(out)); + // The diff is the only copy of the draft once it is discarded: a result the server + // would truncate must keep the draft instead. + if result.len() > windmill_mcp::server::MAX_TOOL_RESULT_BYTES { + let editor = match item_type { + "script" => "/scripts/edit", + "flow" => "/flows/edit", + _ => "/apps_raw/edit", + }; + return Err(format!( + "The draft of \"{path}\" differs from the version it was forked from by more than a tool result can hold, so it was kept as is. Ask the user to reconcile it with the latest deployed version ({version}) in the editor: {}", + ctx.page_url(&format!("{editor}/{path}")) + )); + } + let kind = draft_kind(item_type, None).ok_or_else(no_draft)?; + delete_draft(ctx, &kind, path, draft.created_at.as_deref()).await?; + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn access_entities_are_named_with_or_without_their_prefix() { + assert_eq!(access_entity_name("folder", "f/ops/"), "ops"); + assert_eq!(access_entity_name("folder", "ops"), "ops"); + assert_eq!(access_entity_name("group", "g/devs"), "devs"); + // Only the type's own prefix is stripped. + assert_eq!(access_entity_name("group", "f/devs"), "f/devs"); + } + + #[test] + fn find_and_replace_requires_one_match_unless_replace_all() { + let replace = |all| find_and_replace("a b a", "a", "x", all, "script source"); + assert_eq!(replace(true).unwrap(), "x b x"); + assert_eq!( + replace(false).unwrap_err(), + "old_string matched 2 locations. Make it more specific or set replace_all to true." + ); + assert_eq!( + find_and_replace("a", "z", "x", false, "script source").unwrap_err(), + "old_string was not found in the script source." + ); + } + + // Expected texts are jsdiff's `createTwoFilesPatch` output for the same inputs. + #[test] + fn unified_patch_matches_jsdiff() { + let header = + "===================================================================\n--- fork-base\t\n+++ your-draft\t\n"; + let patch = |old, new, context| unified_patch("fork-base", "your-draft", old, new, context); + assert_eq!( + patch( + "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\n", + "a\nb\nC\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\nO\np\nq", + 4 + ), + format!("{header}@@ -1,7 +1,7 @@\n a\n b\n-c\n+C\n d\n e\n f\n g\n@@ -11,6 +11,7 @@\n k\n l\n m\n n\n-o\n+O\n p\n+q\n\\ No newline at end of file\n") + ); + assert_eq!( + patch("", "x\ny\n", 4), + format!("{header}@@ -0,0 +1,2 @@\n+x\n+y\n") + ); + assert_eq!( + patch("x\ny", "", 4), + format!("{header}@@ -1,2 +0,0 @@\n-x\n-y\n\\ No newline at end of file\n") + ); + assert_eq!(patch("same\n", "same\n", 4), header); + assert_eq!( + patch("a\nb\nc\n", "a\nX\nY\nc\n", 1), + format!("{header}@@ -1,3 +1,4 @@\n a\n-b\n+X\n+Y\n c\n") + ); + assert_eq!( + patch("a\nb", "a\nb\n", 4), + format!("{header}@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n") + ); + } + + #[test] + fn compact_flow_replaces_nested_inline_scripts() { + let raw = |id: &str| json!({ "id": id, "value": { "type": "rawscript", "content": id.to_uppercase(), "language": "bun" } }); + let value = json!({ + "modules": [ + raw("a"), + { "id": "loop", "value": { "type": "forloopflow", "modules": [raw("b")] } }, + { "id": "br", "value": { "type": "branchone", "branches": [{ "modules": [raw("c")] }], "default": [raw("d")] } }, + ], + "failure_module": raw("failure"), + "same_worker": true, + }); + let (compact, scripts) = compact_flow(&value, None); + assert_eq!(scripts.len(), 5); + assert_eq!(scripts["c"], "C"); + assert_eq!( + compact["modules"][2]["value"]["default"][0]["value"]["content"], + "inline_script.d" + ); + assert_eq!( + compact["failure_module"]["value"]["content"], + "inline_script.failure" + ); + let keys: Vec<&String> = compact.as_object().unwrap().keys().collect(); + assert_eq!( + keys, + [ + "modules", + "schema", + "preprocessor_module", + "failure_module", + "groups", + "notes", + "same_worker" + ] + ); + } + + #[test] + fn draft_item_drops_a_staged_path_equal_to_the_storage_path() { + let draft = json!({ "path": "u/a/s", "draft_path": "u/a/s", "summary": "s", "language": "bun", "content": "x", "parent_hash": "h" }); + let item = draft_item("script", "u/a/s", &draft).unwrap(); + assert_eq!( + item, + json!({ "type": "script", "path": "u/a/s", "summary": "s", "language": "bun", "value": "x", "parentHash": "h", "isDraft": true }) + ); + assert!(draft_item("app", "u/a/s", &draft).is_none()); + } + + #[test] + fn draft_item_carries_the_variable_expiry() { + let draft = json!({ "path": "u/a/v", "variable": { "value": "", "is_secret": true, "description": "" }, "value_valid_until": "2027-01-15T00:00:00Z" }); + let item = draft_item("variable", "u/a/v", &draft).unwrap(); + assert_eq!(item["value"]["value_valid_until"], "2027-01-15T00:00:00Z"); + } +} diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index 6940c76043..6e125eefc6 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -183,8 +183,8 @@ fn items_query( let mut sqlb = SqlBuilder::select_from(&format!("{} as o", item_type)); if scope_type == "favorites" { sqlb.join("favorite") - .on("favorite.favorite_kind = ? AND favorite.workspace_id = o.workspace_id AND favorite.path = o.path AND favorite.usr = ?".bind(&item_type) - .bind(&authed.username)); + .on("favorite.favorite_kind = ? AND favorite.workspace_id = o.workspace_id AND favorite.path = o.path AND favorite.usr = ?" + .binds(&[&item_type, &authed.username])); } sqlb.and_where("o.workspace_id = ?".bind(&workspace_id)) .and_where("o.archived = false"); @@ -700,6 +700,47 @@ pub async fn create_http_request( workspace_id: &str, api_authed: &ApiAuthed, body_json: Option<Value>, +) -> BackendResult<reqwest::Response> { + // Scope the minted JWT to the proxied route so a scope-restricted MCP token + // can't be widened into a full-privilege blank check. See + // `jwt_scopes_for_proxied_route`. + let parsed = reqwest::Url::parse(url) + .map_err(|e| ErrorData::internal_error(format!("Invalid proxied URL: {}", e), None))?; + let scopes = jwt_scopes_for_proxied_route(api_authed.scopes.as_deref(), method, parsed.path())?; + send_as_caller(method, url, workspace_id, api_authed, body_json, scopes).await +} + +/// A JWT that acts as `api_authed`, carrying `scopes`; `None` is the caller's full rights. +pub(crate) async fn mint_caller_jwt( + workspace_id: &str, + api_authed: &ApiAuthed, + scopes: Option<Vec<String>>, +) -> BackendResult<String> { + // Carry the caller's job provenance into the JWT: a job's WM_TOKEN is capped at + // workspace admin (GHSA-hfh4-cx4h-3fcr), and dropping `job_id` here would re-mint an + // uncapped token that satisfies require_super_admin / require_devops_role. + create_jwt_token( + Authed::from(api_authed.clone()), + workspace_id, + 3600, + api_authed.job_id, + None, + None, + scopes, + ) + .await + .map_err(|e| ErrorData::internal_error(e.to_string(), None)) +} + +/// Call the API as `api_authed` with a JWT carrying `scopes`; `None` is the caller's +/// full rights, for a server whose own code picks every route it calls. +pub async fn send_as_caller( + method: &str, + url: &str, + workspace_id: &str, + api_authed: &ApiAuthed, + body_json: Option<Value>, + scopes: Option<Vec<String>>, ) -> BackendResult<reqwest::Response> { let client = &HTTP_CLIENT; let mut request_builder = match method { @@ -716,29 +757,7 @@ pub async fn create_http_request( } }; - // Scope the minted JWT to the proxied route so a scope-restricted MCP token - // can't be widened into a full-privilege blank check. See - // `jwt_scopes_for_proxied_route`. - let parsed = reqwest::Url::parse(url) - .map_err(|e| ErrorData::internal_error(format!("Invalid proxied URL: {}", e), None))?; - let scopes = jwt_scopes_for_proxied_route(api_authed.scopes.as_deref(), method, parsed.path())?; - - // Add authorization header. Carry the caller's job provenance into the proxy - // JWT: a job's WM_TOKEN is capped at workspace admin (GHSA-hfh4-cx4h-3fcr), and - // dropping `job_id` here would re-mint an uncapped token that satisfies - // require_super_admin / require_devops_role on the proxied route. - let authed = Authed::from(api_authed.clone()); - let token = create_jwt_token( - authed, - workspace_id, - 3600, - api_authed.job_id, - None, - None, - scopes, - ) - .await - .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; + let token = mint_caller_jwt(workspace_id, api_authed, scopes).await?; request_builder = request_builder.header("Authorization", format!("Bearer {}", token)); // Add body if present diff --git a/backend/windmill-api/src/mcp_tools.rs b/backend/windmill-api/src/mcp_tools.rs index ee7cd5e6b7..a7d32f6e9e 100644 --- a/backend/windmill-api/src/mcp_tools.rs +++ b/backend/windmill-api/src/mcp_tools.rs @@ -103,13 +103,12 @@ async fn connect_mcp_client( if let Some(info) = token_info { if let (Some(account_id), Some(true)) = (info.account_id, info.is_expired) { - let refresh_tx = user_db.clone().begin(authed).await?; if let Err(e) = crate::oauth2_oss::_refresh_token( - refresh_tx, token_var_path, w_id, account_id, db, + false, ) .await { diff --git a/backend/windmill-api/src/oauth2_oss.rs b/backend/windmill-api/src/oauth2_oss.rs index 6a9caee28f..0513cd5c68 100644 --- a/backend/windmill-api/src/oauth2_oss.rs +++ b/backend/windmill-api/src/oauth2_oss.rs @@ -22,8 +22,6 @@ use hmac::Mac; use itertools::Itertools; #[cfg(not(feature = "private"))] use serde::{Deserialize, Serialize}; -#[cfg(not(feature = "private"))] -use sqlx::{Postgres, Transaction}; #[cfg(all(feature = "oauth2", not(feature = "private")))] use windmill_common::more_serde::maybe_number_opt; #[cfg(all(feature = "oauth2", not(feature = "private")))] @@ -84,6 +82,7 @@ pub async fn build_oauth_clients( logins: HashMap::default(), connects: HashMap::default(), slack: None, + slack_signing_secret: None, }); } @@ -133,12 +132,12 @@ async fn list_connects() -> windmill_common::error::JsonResult<Vec<String>> { } #[cfg(not(feature = "private"))] -pub async fn _refresh_token<'c>( - _tx: Transaction<'c, Postgres>, +pub async fn _refresh_token( _path: &str, _w_id: &str, _id: i32, _db: &DB, + _force: bool, ) -> error::Result<String> { // Implementation is not open source Err(error::Error::BadRequest( diff --git a/backend/windmill-api/src/offboarding.rs b/backend/windmill-api/src/offboarding.rs index cc77f2bdbd..59305d96e3 100644 --- a/backend/windmill-api/src/offboarding.rs +++ b/backend/windmill-api/src/offboarding.rs @@ -1075,7 +1075,7 @@ async fn offboard_user_from_workspace<'c>( let new_var_prefix = format!("{}/", reassign_to); let vault_secrets: Vec<(String, String)> = sqlx::query!( - r#"SELECT path, value FROM variable + r#"SELECT path, value::text AS "value!" FROM variable WHERE path LIKE ('u/' || $1 || '/%') AND workspace_id = $2 AND is_secret = true @@ -1209,6 +1209,11 @@ async fn offboard_user_from_workspace<'c>( // They are NOT done here for reassign-only (delete_user=false) since the user stays. // ---- Related path tables ---- + sqlx::query!( + r#"UPDATE native_trigger SET connection_path = REGEXP_REPLACE(connection_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE connection_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, + &new_prefix, username, w_id + ).execute(&mut **tx).await?; + sqlx::query!( r#"UPDATE workspace_integrations SET resource_path = REGEXP_REPLACE(resource_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE resource_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, &new_prefix, username, w_id diff --git a/backend/windmill-api/src/raw_apps.rs b/backend/windmill-api/src/raw_apps.rs index 35e4f693a4..ad53872ca0 100644 --- a/backend/windmill-api/src/raw_apps.rs +++ b/backend/windmill-api/src/raw_apps.rs @@ -98,10 +98,10 @@ async fn list_apps( if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(app.labels @> ARRAY[?] OR folder_labels(app.workspace_id, app.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } diff --git a/backend/windmill-api/src/runnables.rs b/backend/windmill-api/src/runnables.rs index 754221dac0..0037a37042 100644 --- a/backend/windmill-api/src/runnables.rs +++ b/backend/windmill-api/src/runnables.rs @@ -36,7 +36,7 @@ use std::collections::HashMap; use windmill_common::{ db::UserDB, error::{Error, JsonResult}, - workspaces::{operator_builder_rights, OperatorBuilderRights}, + roles::{caller_capabilities, AuthorLevel, RoleCapabilities}, }; use windmill_types::scripts::ScriptHash; use windmill_types::user_drafts::DraftUserRef; @@ -471,6 +471,7 @@ async fn list_runnables( Path(w_id): Path<String>, Query(q): Query<ListRunnablesQuery>, ) -> JsonResult<ListRunnablesResponse> { + let caps = caller_capabilities(&db, &w_id, &authed).await?; let order_by_name = q.order_by.as_deref() == Some("name"); let desc = q.order_desc.unwrap_or(true); let per_page = q.per_page.unwrap_or(50).clamp(1, 1000); @@ -614,7 +615,7 @@ async fn list_runnables( "o.archived = false" }; let mut script_extras: Vec<String> = vec![]; - if !q.include_without_main.unwrap_or(false) || authed.is_operator { + if !q.include_without_main.unwrap_or(false) || !caps.code { script_extras.push("(o.auto_kind IS NULL OR o.auto_kind <> 'lib')".to_string()); } script_extras.push(archived_pred.to_string()); @@ -651,13 +652,8 @@ async fn list_runnables( // have no place in the archived view, and carrying no labels of their own they are // out of scope of a label filter (as in the per-kind endpoints). Operators don't // see other people's drafts and have none of their own, except of what they may build. - let builder = if authed.is_operator { - operator_builder_rights(&db, &w_id).await? - } else { - OperatorBuilderRights::default() - }; let include_drafts = q.include_draft_only.unwrap_or(false) - && (!authed.is_operator || builder.any()) + && ALL_KINDS.iter().any(|k| role_drafts_kind(&caps, k)) && !show_archived && q.label.as_ref().filter(|s| !s.is_empty()).is_none(); let draft_extras_for = |kind: &str| -> Vec<String> { @@ -670,7 +666,7 @@ async fn list_runnables( }; // The lib filter reads the same projected `auto_kind`, so a draft-only library // script hides with the deployed ones. - if kind == "script" && (!q.include_without_main.unwrap_or(false) || authed.is_operator) { + if kind == "script" && (!q.include_without_main.unwrap_or(false) || !caps.code) { extras.push("(o.auto_kind IS NULL OR o.auto_kind <> 'lib')".to_string()); } if let Some(s) = scope { @@ -745,10 +741,7 @@ async fn list_runnables( keyset: Option<&str>, limit: Option<usize>| -> Option<String> { - if !include_drafts - || !kinds.contains(&kind) - || (authed.is_operator && !operator_drafts_kind(builder, kind)) - { + if !include_drafts || !kinds.contains(&kind) || !role_drafts_kind(&caps, kind) { return None; } // `fav` is ignored: with no favorite join there is nothing to filter on, and the @@ -895,6 +888,7 @@ async fn count_runnables_by_owner( Path(w_id): Path<String>, Query(q): Query<CountRunnablesQuery>, ) -> JsonResult<RunnableCountsResponse> { + let caps = caller_capabilities(&db, &w_id, &authed).await?; let kinds: Vec<&str> = match q.kinds.as_deref() { None | Some("") => ALL_KINDS.to_vec(), // Deduplicated: every kind becomes its own count subquery, so a repeated @@ -912,7 +906,7 @@ async fn count_runnables_by_owner( if kinds.is_empty() { return Ok(Json(RunnableCountsResponse { counts: HashMap::new() })); } - let with_libs = q.include_without_main.unwrap_or(false) && !authed.is_operator; + let with_libs = q.include_without_main.unwrap_or(false) && caps.code; // Per-kind predicates shared by both passes. `alias` is the branch's table // alias; `binds` collects the scope values, numbered from `base + 1`. @@ -1006,7 +1000,17 @@ async fn count_runnables_by_owner( for r in query.fetch_all(&db).await? { counts.insert(r.owner, r.count); } - add_draft_counts(&authed, &db, &w_id, &kinds, with_libs, &q, &mut counts).await?; + add_draft_counts( + &caps, + &db, + &w_id, + &authed, + &kinds, + with_libs, + &q, + &mut counts, + ) + .await?; counts.retain(|_, c| *c > 0); return Ok(Json(RunnableCountsResponse { counts })); } @@ -1079,17 +1083,27 @@ async fn count_runnables_by_owner( counts.entry(r.owner).or_insert(r.count); } - add_draft_counts(&authed, &db, &w_id, &kinds, with_libs, &q, &mut counts).await?; + add_draft_counts( + &caps, + &db, + &w_id, + &authed, + &kinds, + with_libs, + &q, + &mut counts, + ) + .await?; counts.retain(|_, c| *c > 0); Ok(Json(RunnableCountsResponse { counts })) } -/// Whether an operator with `builder` rights can have drafts of a `/list` kind. -fn operator_drafts_kind(builder: OperatorBuilderRights, kind: &str) -> bool { +/// Whether a role can have drafts of a `/list` kind: one it may write. +fn role_drafts_kind(caps: &RoleCapabilities, kind: &str) -> bool { match kind { - "flow" => builder.flows, - "app" => builder.apps, - _ => false, + "flow" => caps.flows != AuthorLevel::None, + "app" => caps.apps != AuthorLevel::None, + _ => caps.code, } } @@ -1102,9 +1116,10 @@ fn operator_drafts_kind(builder: OperatorBuilderRights, kind: &str) -> bool { /// Deployed and draft rows can't overlap (the anti-join is what makes a draft /// "draft-only"), so the two counts add. async fn add_draft_counts( - authed: &ApiAuthed, + caps: &RoleCapabilities, db: &DB, w_id: &str, + authed: &ApiAuthed, kinds: &[&str], with_libs: bool, q: &CountRunnablesQuery, @@ -1113,22 +1128,16 @@ async fn add_draft_counts( if !q.include_draft_only.unwrap_or(false) { return Ok(()); } - // An operator has no drafts of their own, except of what they may build. - let builder_kinds: Vec<&str>; - let kinds: &[&str] = if !authed.is_operator { - kinds - } else { - let builder = operator_builder_rights(db, w_id).await?; - builder_kinds = kinds - .iter() - .copied() - .filter(|k| operator_drafts_kind(builder, k)) - .collect(); - if builder_kinds.is_empty() { - return Ok(()); - } - &builder_kinds - }; + // A role has no drafts of its own except of what it may write. + let kinds: Vec<&str> = kinds + .iter() + .copied() + .filter(|k| role_drafts_kind(caps, k)) + .collect(); + if kinds.is_empty() { + return Ok(()); + } + let kinds = kinds.as_slice(); // $1 = workspace, $2 = the caller's email. let mut binds: Vec<String> = vec![]; let branches: Vec<String> = kinds diff --git a/backend/windmill-api/src/slack_agents.rs b/backend/windmill-api/src/slack_agents.rs index 6945955bcb..dae32285df 100644 --- a/backend/windmill-api/src/slack_agents.rs +++ b/backend/windmill-api/src/slack_agents.rs @@ -62,19 +62,190 @@ struct SlackAgentsStatus { signing_secret_set: bool, } -async fn status(_authed: ApiAuthed) -> Json<SlackAgentsStatus> { - Json(SlackAgentsStatus { signing_secret_set: signing_secret_set() }) +async fn status( + _authed: ApiAuthed, + Extension(db): Extension<DB>, + Path(w_id): Path<String>, +) -> JsonResult<SlackAgentsStatus> { + Ok(Json(SlackAgentsStatus { + signing_secret_set: signing_secret_set(&db, &w_id).await?, + })) } -/// Agents answer only when the server verifies Slack's request signatures. -fn signing_secret_set() -> bool { +/// Which of the workspaces connected to a Slack team a request may reach. +#[derive(Clone, Debug, Default)] +pub struct SlackRequest { + /// Those whose app's signing secret verified it or, when none did, those whose app has none + /// set, which take requests unauthenticated. + pub reachable: Vec<String>, + /// Those whose app's signing secret verified it, the only ones agents answer for. + pub verified: Vec<String>, +} + +fn env_signing_secret() -> Option<String> { + std::env::var("SLACK_SIGNING_SECRET") + .ok() + .filter(|s| !s.is_empty()) +} + +fn instance_signing_secrets() -> Vec<String> { #[cfg(feature = "oauth2")] { - crate::SLACK_SIGNING_SECRET.is_some() + env_signing_secret() + .into_iter() + .chain(crate::OAUTH_CLIENTS.load().slack_signing_secret.clone()) + .filter(|s| !s.is_empty()) + .collect() } #[cfg(not(feature = "oauth2"))] { - false + vec![] + } +} + +/// Agents answer only when the server verifies Slack's request signatures, with the secret of the +/// app the workspace is connected through: its own app's, or else the instance's. +async fn signing_secret_set(db: &DB, w_id: &str) -> Result<bool> { + let own_app = sqlx::query!( + "SELECT slack_oauth_client_id IS NOT NULL AS \"own_app!\", + slack_signing_secret IS NOT NULL AS \"own_secret!\" + FROM workspace_settings WHERE workspace_id = $1", + w_id + ) + .fetch_optional(db) + .await?; + Ok(match own_app { + Some(r) if r.own_app => r.own_secret || env_signing_secret().is_some(), + _ => !instance_signing_secrets().is_empty(), + }) +} + +/// Whether a Slack request was signed by the app a workspace is connected through: `None` when that +/// app has no secret set, which leaves the request unauthenticated. A workspace's own app is checked +/// against its own secret, never the instance setting's: the instance's app signs nothing for it, so +/// setting an instance secret must not start rejecting its requests. Without its own secret it falls +/// back to `SLACK_SIGNING_SECRET`, which may hold that app's secret from before workspaces had one. +#[cfg(feature = "oauth2")] +fn workspace_verified( + own_app: bool, + own_secret: Option<String>, + instance_verified: Option<bool>, + matches: impl Fn(&str) -> bool, +) -> Option<bool> { + if own_app { + own_secret.or_else(env_signing_secret).map(|s| matches(&s)) + } else { + instance_verified + } +} + +#[cfg(feature = "oauth2")] +fn slack_signature_matcher<'a>( + sig: &'a str, + ts: &'a str, + body: &'a str, +) -> impl Fn(&str) -> bool + 'a { + // Slack's recommended replay window: a captured request stops verifying after it. + let fresh = ts + .parse::<i64>() + .is_ok_and(|t| chrono::Utc::now().timestamp().abs_diff(t) <= 5 * 60); + move |secret: &str| { + fresh + && windmill_oauth::SlackVerifier::new(secret) + .is_ok_and(|v| v.verify(ts, body, sig).is_ok()) + } +} + +#[cfg(feature = "oauth2")] +fn instance_verified(matches: &impl Fn(&str) -> bool) -> Option<bool> { + let instance = instance_signing_secrets(); + (!instance.is_empty()).then(|| instance.iter().any(|s| matches(s))) +} + +#[cfg(feature = "oauth2")] +fn signature_rejected<T>() -> Result<T> { + Err(Error::BadRequest( + "Slack signature verification failed".to_string(), + )) +} + +/// Checks a Slack request, for each workspace connected to `team_id`, against the signing secret +/// of the app it is connected through (see [`workspace_verified`]). For a team no workspace is +/// connected to, only the instance's secret applies. An error when the request can reach no +/// workspace. +#[cfg(feature = "oauth2")] +pub async fn verify_slack_request( + db: &DB, + team_id: &str, + sig: &str, + ts: &str, + body: &str, +) -> Result<SlackRequest> { + let matches = slack_signature_matcher(sig, ts, body); + let instance_verified = instance_verified(&matches); + + let workspaces = sqlx::query!( + "SELECT workspace_id, slack_oauth_client_id IS NOT NULL AS \"own_app!\", + slack_signing_secret + FROM workspace_settings WHERE slack_team_id = $1", + team_id + ) + .fetch_all(db) + .await?; + if workspaces.is_empty() { + return match instance_verified { + Some(false) => signature_rejected(), + _ => Ok(SlackRequest::default()), + }; + } + let mut req = SlackRequest::default(); + for w in workspaces { + let verified = workspace_verified( + w.own_app, + w.slack_signing_secret, + instance_verified, + &matches, + ); + if verified != Some(false) { + req.reachable.push(w.workspace_id.clone()); + } + if verified == Some(true) { + req.verified.push(w.workspace_id); + } + } + if req.reachable.is_empty() { + return signature_rejected(); + } + // A matching secret proves which app sent the request, so a workspace that merely has no secret + // to rule it out must not take it. + if !req.verified.is_empty() { + req.reachable = req.verified.clone(); + } + Ok(req) +} + +/// Checks a Slack approval callback sent through `w_id`'s Slack connection against the secret of +/// the app it is connected through (see [`workspace_verified`]). +#[cfg(feature = "oauth2")] +pub async fn verify_approval_slack_request( + db: &DB, + w_id: &str, + sig: &str, + ts: &str, + body: &str, +) -> Result<()> { + let matches = slack_signature_matcher(sig, ts, body); + let (own_app, own_secret) = sqlx::query!( + "SELECT slack_oauth_client_id IS NOT NULL AS \"own_app!\", slack_signing_secret + FROM workspace_settings WHERE workspace_id = $1", + w_id + ) + .fetch_optional(db) + .await? + .map_or((false, None), |s| (s.own_app, s.slack_signing_secret)); + match workspace_verified(own_app, own_secret, instance_verified(&matches), &matches) { + Some(false) => signature_rejected(), + _ => Ok(()), } } @@ -199,7 +370,7 @@ async fn get_agent_slack( }; Ok(Json(AgentSlack { slack_team_name, - signing_secret_set: signing_secret_set(), + signing_secret_set: signing_secret_set(&db, &w_id).await?, bot_name, missing_scopes: missing_scopes.unwrap_or_default(), runs_as, @@ -454,9 +625,9 @@ pub struct SlackMessage { pub text: String, pub ts: String, pub thread_ts: Option<String>, - /// Whether this request's Slack signature was verified. Carried from the check rather than - /// re-read from the setting, which can be enabled between the two. - pub signed: bool, + /// The workspaces whose Slack app's signing secret verified this request. Carried from the + /// check rather than re-read from the settings, which can change between the two. + pub verified: Vec<String>, } enum Route { @@ -477,7 +648,7 @@ struct SharedHere { /// `false` leaves the message to the workspace's command script. pub async fn try_answer(db: &DB, msg: SlackMessage) -> Result<bool> { // Without it the Slack endpoints take unsigned requests, and anyone could post as a channel. - if !msg.signed { + if msg.verified.is_empty() { return Ok(false); } let text = decode_entities(&msg.text); @@ -490,9 +661,12 @@ pub async fn try_answer(db: &DB, msg: SlackMessage) -> Result<bool> { "SELECT c.workspace_id, c.agent_path, c.is_default FROM slack_agent_channel c JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id AND ws.slack_team_id = c.slack_team_id - WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path", + WHERE c.slack_team_id = $1 AND c.channel_id = $2 + AND ws.workspace_id = ANY($3) + ORDER BY c.agent_path", msg.team_id, - msg.channel_id + msg.channel_id, + &msg.verified ) .fetch_all(db) .await?; @@ -543,20 +717,22 @@ pub async fn try_answer(db: &DB, msg: SlackMessage) -> Result<bool> { "channel_default" }, ), - None => match workspace_without_command_script(db, &msg.team_id).await? { - Some(w_id) => { - return start_answer( - db, - w_id, - Route::Help { note: None }, - "help", - question, - msg, - ) - .await; + None => { + match workspace_without_command_script(db, &msg.team_id, &msg.verified).await? { + Some(w_id) => { + return start_answer( + db, + w_id, + Route::Help { note: None }, + "help", + question, + msg, + ) + .await; + } + None => return Ok(false), } - None => return Ok(false), - }, + } }, }; let w_id = here.workspace_id.clone(); @@ -671,12 +847,18 @@ fn decode_entities(text: &str) -> String { /// The team's workspace when no workspace of the team has a command script to take the message: /// the only one connected to it. -async fn workspace_without_command_script(db: &DB, team_id: &str) -> Result<Option<String>> { +async fn workspace_without_command_script( + db: &DB, + team_id: &str, + verified: &[String], +) -> Result<Option<String>> { let rows = sqlx::query!( "SELECT workspace_id, slack_command_script IS NOT NULL AS \"has_script!\" - FROM workspace_settings WHERE slack_team_id = $1 + FROM workspace_settings ws WHERE slack_team_id = $1 + AND ws.workspace_id = ANY($2) ORDER BY slack_command_script IS NOT NULL DESC LIMIT 2", - team_id + team_id, + verified ) .fetch_all(db) .await?; @@ -692,9 +874,12 @@ async fn help_text(db: &DB, msg: &SlackMessage, note: Option<String>) -> Result< "SELECT c.agent_path FROM slack_agent_channel c JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id AND ws.slack_team_id = c.slack_team_id - WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path LIMIT 11", + WHERE c.slack_team_id = $1 AND c.channel_id = $2 + AND ws.workspace_id = ANY($3) + ORDER BY c.agent_path LIMIT 11", msg.team_id, - msg.channel_id + msg.channel_id, + &msg.verified ) .fetch_all(db) .await?; diff --git a/backend/windmill-api/src/slack_approvals.rs b/backend/windmill-api/src/slack_approvals.rs index 204b30010d..8635cc3e1e 100644 --- a/backend/windmill-api/src/slack_approvals.rs +++ b/backend/windmill-api/src/slack_approvals.rs @@ -138,37 +138,70 @@ struct PrivateMetadata { skin: ApprovalSkin, } -// Opportunistic transport-level check: when `SLACK_SIGNING_SECRET` is configured we verify -// the Slack request signature (which also defeats replay). It is NOT the primary defense: -// the secret is unset in the default deployment, so authorization of the sensitive actions -// is instead anchored on a per-workspace HMAC over the callback payload itself (see -// `verify_slack_payload`), which holds even when this check is a no-op. -#[cfg(feature = "oauth2")] -fn verify_slack_callback_signature(headers: &HeaderMap, body: &str) -> Result<(), Error> { - if let Some(sv) = crate::SLACK_SIGNING_SECRET.as_ref() { - let sig = headers - .get("X-Slack-Signature") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - let ts = headers - .get("X-Slack-Request-Timestamp") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - sv.verify(ts, body, sig) - .map_err(|_| Error::BadRequest("Slack signature verification failed".to_string()))?; +/// Slack's signature over a callback, checked once the workspace it belongs to is known. +#[cfg_attr(not(feature = "oauth2"), allow(dead_code))] +struct SlackCallbackSignature { + sig: String, + ts: String, + body: String, +} + +impl SlackCallbackSignature { + fn new(headers: &HeaderMap, body: &str) -> Self { + let header = |name: &str| { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_string() + }; + Self { + sig: header("X-Slack-Signature"), + ts: header("X-Slack-Request-Timestamp"), + body: body.to_string(), + } } - Ok(()) +} + +// Transport-level check, which also defeats replay. It is NOT the primary defense: authorization of +// the sensitive actions is anchored on a per-workspace HMAC over the callback payload itself (see +// `verify_slack_payload`). Only an approval sent through the workspace's Slack connection comes from +// an app whose secret Windmill knows; any other resource may belong to any Slack app, so its +// callbacks are left to the HMAC. +#[cfg(feature = "oauth2")] +async fn verify_slack_callback_signature( + db: &DB, + w_id: &str, + resource_path: &str, + request: &SlackCallbackSignature, +) -> Result<(), Error> { + if resource_path != windmill_common::oauth2::WORKSPACE_SLACK_BOT_TOKEN_PATH { + return Ok(()); + } + crate::slack_agents::verify_approval_slack_request( + db, + w_id, + &request.sig, + &request.ts, + &request.body, + ) + .await } #[cfg(not(feature = "oauth2"))] -fn verify_slack_callback_signature(_headers: &HeaderMap, _body: &str) -> Result<(), Error> { +async fn verify_slack_callback_signature( + _db: &DB, + _w_id: &str, + _resource_path: &str, + _request: &SlackCallbackSignature, +) -> Result<(), Error> { Ok(()) } /// HMAC keyed on the per-workspace encryption key (the same trust anchor as resume-URL /// signatures). Used to authenticate the `/api/slack` callback payload itself so the /// unauthenticated route cannot be driven into decrypting arbitrary workspace variables, -/// regardless of whether `SLACK_SIGNING_SECRET` is configured. +/// whether or not a Slack signing secret is set. type SlackPayloadHmac = Hmac<Sha256>; /// Domain-separation tag prepended to every Slack-payload MAC. The workspace key is also used @@ -232,8 +265,7 @@ pub async fn slack_app_callback_handler( headers: HeaderMap, body: Bytes, ) -> Result<StatusCode, Error> { - let body_str = String::from_utf8_lossy(&body); - verify_slack_callback_signature(&headers, &body_str)?; + let request = SlackCallbackSignature::new(&headers, &String::from_utf8_lossy(&body)); let form_data: SlackFormData = serde_urlencoded::from_bytes(&body) .map_err(|e| Error::BadRequest(format!("invalid form data: {}", e)))?; @@ -244,10 +276,10 @@ pub async fn slack_app_callback_handler( match payload.r#type { PayloadType::ViewSubmission => { - handle_submission(authed, opt_tokened, db, &payload, "resume").await? + handle_submission(authed, opt_tokened, db, &payload, &request, "resume").await? } PayloadType::ViewClosed => { - handle_submission(authed, opt_tokened, db, &payload, "cancel").await? + handle_submission(authed, opt_tokened, db, &payload, &request, "cancel").await? } _ => { if let Some(actions) = &payload.actions { @@ -274,8 +306,8 @@ pub async fn slack_app_callback_handler( // payload was minted by `send_slack_message` with an HMAC over // (w_id, job_id, path) keyed on the workspace key. Without a valid // signature an unauthenticated caller cannot reach the decryption - // below for an arbitrary variable, even when SLACK_SIGNING_SECRET - // is unset. + // below for an arbitrary variable, even when no Slack signing + // secret is set. verify_slack_payload( &db, w_id, @@ -283,6 +315,7 @@ pub async fn slack_app_callback_handler( parsed_value.signature.as_deref(), ) .await?; + verify_slack_callback_signature(&db, w_id, path, &request).await?; // Map any lookup/decryption failure to a generic error: the // raw error echoes the probed `path`/`w_id` back, which would be @@ -411,6 +444,7 @@ async fn handle_submission( opt_tokened: OptTokened, db: DB, payload: &Payload, + request: &SlackCallbackSignature, action: &str, ) -> Result<(), Error> { let view = payload @@ -455,6 +489,7 @@ async fn handle_submission( // the resume/cancel and reach the decryption below with a swapped path. Require the // workspace-keyed HMAC minted when the modal was built. verify_slack_payload(&db, w_id, &[resource_path.as_bytes()], signature.as_deref()).await?; + verify_slack_callback_signature(&db, w_id, &resource_path, request).await?; // Use the common handler to process the resume/cancel action handle_resume_action( diff --git a/backend/windmill-api/src/users.rs b/backend/windmill-api/src/users.rs index 9d59a85dee..ecf77b6d5f 100644 --- a/backend/windmill-api/src/users.rs +++ b/backend/windmill-api/src/users.rs @@ -194,6 +194,41 @@ async fn list_guests( Ok(Json(GuestList { usage, guests })) } +/// Shared while issuing an MCP OAuth grant, exclusive while revoking: no grant outlives a revoke. +pub(crate) async fn lock_mcp_oauth_grants( + conn: &mut sqlx::PgConnection, + email: &str, + exclusive: bool, +) -> std::result::Result<(), sqlx::Error> { + let q = if exclusive { + "SELECT pg_advisory_xact_lock(hashtext('mcp_oauth_grant:' || $1))" + } else { + "SELECT pg_advisory_xact_lock_shared(hashtext('mcp_oauth_grant:' || $1))" + }; + sqlx::query(q).bind(email).execute(conn).await?; + Ok(()) +} + +async fn revoke_mcp_oauth_grants(tx: &mut sqlx::PgConnection, email: &str) -> Result<()> { + lock_mcp_oauth_grants(&mut *tx, email, true).await?; + // The token trigger only notifies for sessions, so evict deleted MCP access tokens explicitly. + sqlx::query!( + "WITH revoked AS ( + DELETE FROM token WHERE email = $1 AND label LIKE 'mcp-oauth-%' RETURNING token_prefix + ), refresh AS ( + DELETE FROM mcp_oauth_refresh_token WHERE user_email = $1 + ), code AS ( + DELETE FROM mcp_oauth_server_code WHERE user_email = $1 + ) + INSERT INTO notify_event (channel, payload) + SELECT 'notify_token_invalidation', token_prefix FROM revoked", + email + ) + .execute(&mut *tx) + .await?; + Ok(()) +} + async fn set_password( Extension(db): Extension<DB>, Extension(argon2): Extension<Arc<Argon2<'_>>>, @@ -215,6 +250,9 @@ async fn set_password( ) .execute(&db) .await?; + let mut tx = db.begin().await?; + revoke_mcp_oauth_grants(&mut *tx, &email).await?; + tx.commit().await?; Ok(res) } @@ -235,6 +273,9 @@ async fn set_password_of_user( ) .execute(&db) .await?; + let mut tx = db.begin().await?; + revoke_mcp_oauth_grants(&mut *tx, &email).await?; + tx.commit().await?; Ok(res) } @@ -591,7 +632,7 @@ async fn update_username_in_workpsace<'c>( // Fetch all externally-stored secret variables under this user's path let vault_secrets: Vec<(String, String)> = sqlx::query!( - r#"SELECT path, value FROM variable + r#"SELECT path, value::text AS "value!" FROM variable WHERE path LIKE ('u/' || $1 || '/%') AND workspace_id = $2 AND is_secret = true @@ -630,6 +671,15 @@ async fn update_username_in_workpsace<'c>( ).execute(&mut **tx) .await?; + sqlx::query!( + r#"UPDATE native_trigger SET connection_path = REGEXP_REPLACE(connection_path, 'u/' || $2 || '/(.*)', 'u/' || $1 || '/\1') WHERE connection_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, + new_username, + old_username, + w_id + ) + .execute(&mut **tx) + .await?; + sqlx::query!( r#"UPDATE workspace_integrations SET resource_path = REGEXP_REPLACE(resource_path, 'u/' || $2 || '/(.*)', 'u/' || $1 || '/\1') WHERE resource_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, new_username, @@ -1087,6 +1137,7 @@ async fn reset_password( ) .execute(&mut *tx) .await?; + revoke_mcp_oauth_grants(&mut *tx, &email).await?; // Audit log let audit_author = AuditAuthor { diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index f83ffcb4e8..d222188319 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -60,6 +60,7 @@ struct SettingsRow { webhook: Option<String>, error_handler: Option<Value>, success_handler: Option<Value>, + variable_expiration_handler: Option<Value>, ai_config: Option<Value>, large_file_storage: Option<Value>, git_sync: Option<Value>, @@ -298,7 +299,8 @@ pub async fn load_settings_document( ) -> Result<Map<String, Value>> { let row = sqlx::query_as::<_, SettingsRow>( r#"SELECT - auto_invite, webhook, error_handler, success_handler, ai_config, large_file_storage, + auto_invite, webhook, error_handler, success_handler, variable_expiration_handler, + ai_config, large_file_storage, git_sync, default_app, default_scripts, workspace.name AS name, mute_critical_alerts, color, operator_settings, datatable, slack_team_id, slack_name, slack_command_script, slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, deploy_ui, @@ -341,18 +343,28 @@ pub async fn load_settings_document( }; let datatable_permissions = datatable_permissions_document(row.datatable.as_ref(), &role_names); let protection_rules = protection_rules_document(&mut *conn, w_id).await?; + let git_sync = redact_git_sync(row.git_sync); + let git_sync = match fork_parent(&mut *conn, w_id).await? { + Some(parent) => fork_git_sync_document(git_sync, parent.git_sync), + None => git_sync, + }; // In the order `wmill sync pull` has always written settings.yaml. A key that predates the // document and is not marked `always` is written only when set, as it always was; a key // added since is always written, so a pulled file states it and from then on manages it. - let entries: [(&str, Option<Value>, bool); 31] = [ + let entries: [(&str, Option<Value>, bool); 32] = [ ("auto_invite", row.auto_invite, false), ("webhook", row.webhook.map(Value::String), false), ("error_handler", row.error_handler, true), ("success_handler", row.success_handler, true), + ( + "variable_expiration_handler", + row.variable_expiration_handler, + true, + ), ("ai_config", row.ai_config, false), ("large_file_storage", row.large_file_storage, false), - ("git_sync", redact_git_sync(row.git_sync), false), + ("git_sync", git_sync, false), ("default_app", row.default_app.map(Value::String), false), ("default_scripts", row.default_scripts, false), ("name", Some(json!(row.name.unwrap_or_default())), true), @@ -675,6 +687,7 @@ const KNOWN_KEYS: &[&str] = &[ "webhook", "error_handler", "success_handler", + "variable_expiration_handler", "ai_config", "large_file_storage", "git_sync", @@ -859,11 +872,36 @@ fn normalize_protection_rules(v: &Value, warnings: &mut Vec<String>) -> Result<V Ok(Value::Object(out)) } -async fn plan(db: &DB, w_id: &str, desired: Map<String, Value>, replace: bool) -> Result<Plan> { - let current = { +async fn plan(db: &DB, w_id: &str, mut desired: Map<String, Value>, replace: bool) -> Result<Plan> { + let (mut current, fork) = { let mut conn = db.acquire().await?; - load_settings_document(&mut conn, db, w_id, SecretMode::Plain).await? + let current = load_settings_document(&mut conn, db, w_id, SecretMode::Plain).await?; + (current, fork_parent(&mut conn, w_id).await?) }; + if let Some(fork) = fork { + // Diff against what the fork stores, not the parent's view the document shows it. + let own: Option<Value> = + sqlx::query_scalar("SELECT git_sync FROM workspace_settings WHERE workspace_id = $1") + .bind(w_id) + .fetch_optional(db) + .await? + .flatten(); + let own = redact_git_sync(own); + // A malformed value is left for the endpoint to refuse. + let stated = match desired.get("git_sync") { + Some(v) if v.is_object() || v.is_null() => Some(v), + Some(_) => None, + None => replace.then_some(&Value::Null), + }; + if let Some(stated) = stated { + let applied = fork_git_sync_to_apply(stated, own.as_ref(), fork.is_dev)?; + desired.insert("git_sync".to_string(), applied); + } + match own { + Some(own) => current.insert("git_sync".to_string(), own), + None => current.remove("git_sync"), + }; + } let mc = build_crypt(db, w_id).await?; let names = match desired.get("datatable_permissions") { Some(v) if !v.is_null() => DatatableNames::load(db, w_id, v).await?, @@ -872,6 +910,147 @@ async fn plan(db: &DB, w_id: &str, desired: Map<String, Value>, replace: bool) - plan_document(current, desired, replace, &mc, &names) } +/// A fork's parent, read for its `git_sync`. +struct ForkParent { + /// As the parent's own document states it: a fork of a fork shares the root's file too. + git_sync: Option<Value>, + /// Of the fork itself. + is_dev: bool, +} + +/// `Some` when `w_id` is a fork, by the same test as +/// `reject_parent_only_git_sync_settings_on_fork`. +async fn fork_parent(conn: &mut PgConnection, w_id: &str) -> Result<Option<ForkParent>> { + // The workspace itself, then its ancestors nearest first; the depth bound only guards + // against a cycle. + let mut chain: Vec<(bool, Option<Value>)> = sqlx::query_as( + "WITH RECURSIVE chain AS ( + SELECT id, parent_workspace_id, is_dev_workspace, 0 AS depth + FROM workspace WHERE id = $1 + UNION ALL + SELECT w.id, w.parent_workspace_id, w.is_dev_workspace, c.depth + 1 FROM workspace w + JOIN chain c ON w.id = c.parent_workspace_id WHERE c.depth < 32 + ) + SELECT c.is_dev_workspace, s.git_sync FROM chain c + LEFT JOIN workspace_settings s ON s.workspace_id = c.id + ORDER BY c.depth", + ) + .bind(w_id) + .fetch_all(&mut *conn) + .await?; + let is_dev = !chain.is_empty() && chain.remove(0).0; + if chain.is_empty() && !w_id.starts_with(windmill_common::workspaces::WM_FORK_PREFIX) { + return Ok(None); + } + let git_sync = chain.into_iter().rev().fold(None, |above, (_, own)| { + fork_git_sync_document(redact_git_sync(own), above) + }); + Ok(Some(ForkParent { git_sync, is_dev })) +} + +// A fork shares its parent's settings.yaml (the CLI maps `wm-fork/<branch>/<id>` to the parent's +// entry), so its `git_sync` there is the parent's. Of it, a fork applies only what selects the +// items synced, on the repos it carries: the keys listed here, and a repo's `settings` when +// neither side uses workspace-level filters. Auto-pull, fork PRs and promotion mode are not a +// fork's to take (`reject_parent_only_git_sync_settings_on_fork`), and any other field stays the +// fork's own. The fork's document is the parent's block with the fork's values for the same keys, +// the inverse of the apply, so a merge of the fork's branch changes only them in the parent. +const FORK_SYNCED_REPO_KEYS: [&str; 2] = ["exclude_types_override", "group_by_folder"]; + +fn repos(git_sync: Option<&Value>) -> &[Value] { + git_sync + .and_then(|g| g.get("repositories")) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +fn same_repo<'a>(repos: &'a [Value], repo: &Value) -> Option<&'a Value> { + let path = repo.get("git_repo_resource_path")?; + repos + .iter() + .find(|r| r.get("git_repo_resource_path") == Some(path)) +} + +/// Whether repos fall back to the workspace-level filters, where an empty or missing `settings` +/// list means "use the workspace's". A repo's filters cross only when neither side does, as +/// that layout cannot state some of what the other can. Only these two are fallen back to on +/// their own (`exclude_path`/`extra_include_path` only beside `include_path`), and the save +/// leaves the other two behind once every repo has migrated. +fn uses_workspace_filters(git_sync: &Value) -> bool { + ["include_path", "include_type"] + .iter() + .any(|k| !is_null(git_sync.get(*k))) +} + +/// An unset key and a null one are left as they are: stored blobs differ in which they write, and +/// swapping one for the other would show in settings.yaml as a change. +fn copy_keys(onto: &mut Map<String, Value>, from: &Value, keys: &[&str]) { + for key in keys { + if is_null(from.get(*key)) && is_null(onto.get(*key)) { + continue; + } + match from.get(*key) { + Some(v) => onto.insert(key.to_string(), v.clone()), + None => onto.remove(*key), + }; + } +} + +/// Sets `onto` to `from`'s values for the synced keys, on each repo `from` also lists. +fn copy_synced_keys(onto: &mut Value, from: &Value) { + let filters = !uses_workspace_filters(onto) && !uses_workspace_filters(from); + let from_repos = repos(Some(from)); + let Some(repos) = onto.get_mut("repositories").and_then(Value::as_array_mut) else { + return; + }; + for repo in repos { + let Some(src) = same_repo(from_repos, repo) else { + continue; + }; + if let Some(repo) = repo.as_object_mut() { + copy_keys(repo, src, &FORK_SYNCED_REPO_KEYS); + if filters { + copy_keys(repo, src, &["settings"]); + } + } + } +} + +/// The fork's `git_sync` as its settings.yaml states it. +fn fork_git_sync_document(own: Option<Value>, parent: Option<Value>) -> Option<Value> { + let Some(mut doc) = parent else { + return own; + }; + if let Some(own) = &own { + copy_synced_keys(&mut doc, own); + } + Some(doc) +} + +/// What a fork applies of the `git_sync` its settings.yaml states. Only a dev workspace may hold +/// a promotion repo, and one detached from dev still stores its own: it is dropped so the write +/// passes the save's check. +fn fork_git_sync_to_apply(stated: &Value, own: Option<&Value>, is_dev: bool) -> Result<Value> { + if stated.get("repositories").is_some_and(|r| !r.is_array()) { + return Err(Error::BadRequest( + "git_sync.repositories must be a list".to_string(), + )); + } + let Some(mut applied) = own.cloned() else { + return Ok(Value::Null); + }; + copy_synced_keys(&mut applied, stated); + if !is_dev { + if let Some(repos) = applied + .get_mut("repositories") + .and_then(Value::as_array_mut) + { + repos.retain(|r| r.get("use_individual_branch") != Some(&Value::Bool(true))); + } + } + Ok(applied) +} + fn plan_document( current: Map<String, Value>, mut desired: Map<String, Value>, @@ -888,7 +1067,12 @@ fn plan_document( if !unknown.is_empty() { warnings.push(format!("Ignored unknown settings: {}", unknown.join(", "))); } - for key in ["auto_invite", "error_handler", "success_handler"] { + for key in [ + "auto_invite", + "error_handler", + "success_handler", + "variable_expiration_handler", + ] { if desired .get(key) .is_some_and(|v| !v.is_null() && !v.is_object()) @@ -951,6 +1135,24 @@ fn plan_document( Value::is_boolean, "a boolean", ), + ( + "variable_expiration_handler", + "muted_on_user_path", + Value::is_boolean, + "a boolean", + ), + ( + "variable_expiration_handler", + "notify_before_secs", + |v: &Value| v.as_u64().is_some_and(|n| n <= u32::MAX as u64), + "a non-negative number of seconds", + ), + ( + "variable_expiration_handler", + "remind_every_secs", + |v: &Value| v.as_u64().is_some_and(|n| n <= u32::MAX as u64), + "a non-negative number of seconds", + ), ] { let v = desired.get(parent).and_then(|p| p.get(key)); typed(&format!("{parent}.{key}"), v, ok, ty)?; @@ -964,14 +1166,19 @@ fn plan_document( let v = normalize_protection_rules(v, &mut warnings)?; desired.insert("protection_rules".to_string(), v); } - // The endpoint stores an omitted mute flag as `false`. - if let Some(handler) = desired - .get_mut("error_handler") - .and_then(Value::as_object_mut) - { - for key in ["muted_on_cancel", "muted_on_user_path"] { - if is_null(handler.get(key)) { - handler.insert(key.to_string(), Value::Bool(false)); + // The endpoints store an omitted mute flag as `false`. + for (handler, keys) in [ + ( + "error_handler", + &["muted_on_cancel", "muted_on_user_path"][..], + ), + ("variable_expiration_handler", &["muted_on_user_path"][..]), + ] { + if let Some(handler) = desired.get_mut(handler).and_then(Value::as_object_mut) { + for key in keys { + if is_null(handler.get(*key)) { + handler.insert(key.to_string(), Value::Bool(false)); + } } } } @@ -1118,6 +1325,23 @@ fn plan_document( |v| json!({ "path": v.get("path"), "extra_args": v.get("extra_args") }), ); + // Managed only when stated, like every key added after the document. + let variable_expiration_handler = p.managed("variable_expiration_handler"); + p.simple( + "variable_expiration_handler", + variable_expiration_handler, + Target::Edit(SettingsEdit::VariableExpirationHandler), + |v| { + json!({ + "path": v.get("path"), + "extra_args": v.get("extra_args"), + "muted_on_user_path": v.get("muted_on_user_path").and_then(Value::as_bool).unwrap_or(false), + "notify_before_secs": v.get("notify_before_secs"), + "remind_every_secs": v.get("remind_every_secs"), + }) + }, + ); + let lfs = p.legacy("large_file_storage"); p.simple( "large_file_storage", @@ -1839,6 +2063,29 @@ mod tests { assert!(p.changes.is_empty(), "{:?}", keys(&p)); } + #[test] + fn variable_expiration_handler_is_managed_only_when_stated() { + let mc = WorkspaceCrypt::new("k"); + let names = DatatableNames::default(); + let mut cur = current(); + cur.insert( + "variable_expiration_handler".into(), + json!({ "path": "script/f/x", "muted_on_user_path": false }), + ); + let omitted = doc(json!({ "webhook": "https://b" })); + let p = plan_document(cur.clone(), omitted, true, &mc, &names).unwrap(); + assert!(!keys(&p).contains(&"variable_expiration_handler")); + + let same = doc(json!({ "variable_expiration_handler": { "path": "script/f/x" } })); + let p = plan_document(cur.clone(), same, false, &mc, &names).unwrap(); + assert!(p.changes.is_empty(), "{:?}", keys(&p)); + + let cleared = doc(json!({ "variable_expiration_handler": null })); + let p = plan_document(cur, cleared, false, &mc, &names).unwrap(); + assert_eq!(keys(&p), ["variable_expiration_handler"]); + assert_eq!(p.writes[0].body["path"], Value::Null); + } + #[cfg(all(feature = "private", feature = "enterprise"))] #[test] fn datatable_roles_are_named_in_the_document_and_written_by_id() { @@ -1947,4 +2194,99 @@ mod tests { )); assert_eq!(p.warnings.len(), 1); } + + #[test] + fn a_fork_applies_only_the_synced_keys_of_the_repos_it_carries() { + let parent = json!({ "repositories": [ + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["f/**"] }, + "auto_pull": { "enabled": true, "sync_forks": true }, "fork_open_prs": true }, + { "git_repo_resource_path": "f/promo", "use_individual_branch": true }, + ] }); + // A dev workspace's promotion repo is the repo the parent syncs normally. + let fork = json!({ "repositories": [ + { "git_repo_resource_path": "f/own" }, + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["u/**"] }, + "use_individual_branch": true, "auto_pull": { "enabled": false } }, + ] }); + assert_eq!( + fork_git_sync_to_apply(&parent, Some(&fork), true).unwrap(), + json!({ "repositories": [ + { "git_repo_resource_path": "f/own" }, + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["f/**"] }, + "use_individual_branch": true, "auto_pull": { "enabled": false } }, + ] }) + ); + + // The fork's document is the parent's block with the fork's synced keys, and applying it + // back to the fork is a no-op. + let shown = fork_git_sync_document(Some(fork.clone()), Some(parent.clone())).unwrap(); + assert_eq!( + shown, + json!({ "repositories": [ + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["u/**"] }, + "auto_pull": { "enabled": true, "sync_forks": true }, "fork_open_prs": true }, + { "git_repo_resource_path": "f/promo", "use_individual_branch": true }, + ] }) + ); + assert_eq!( + fork_git_sync_to_apply(&shown, Some(&fork), true).unwrap(), + fork + ); + + // Detached from dev, the fork may no longer hold its promotion repo. + assert_eq!( + fork_git_sync_to_apply(&parent, Some(&fork), false).unwrap(), + json!({ "repositories": [{ "git_repo_resource_path": "f/own" }] }) + ); + + // Filters cross only between two sides on per-repo settings: with workspace-level ones on + // either side, the fork keeps its own and the document keeps the parent's. + let legacy_parent = json!({ "include_path": ["f/**"], "include_type": ["script"], + "repositories": [{ "git_repo_resource_path": "f/r" }] }); + let migrated = json!({ "repositories": [{ "git_repo_resource_path": "f/r", + "settings": { "include_path": ["u/**"], "include_type": [] } }] }); + assert_eq!( + fork_git_sync_to_apply(&legacy_parent, Some(&migrated), false).unwrap(), + migrated + ); + let shown = + fork_git_sync_document(Some(migrated.clone()), Some(legacy_parent.clone())).unwrap(); + assert_eq!(shown, legacy_parent); + assert_eq!( + fork_git_sync_to_apply(&shown, Some(&migrated), false).unwrap(), + migrated + ); + let legacy_fork = json!({ "include_path": ["u/**"], "include_type": ["flow"], + "repositories": [{ "git_repo_resource_path": "f/r" }] }); + let migrated_parent = json!({ "repositories": [{ "git_repo_resource_path": "f/r", + "settings": { "include_path": ["f/**"], "include_type": ["script"] } }] }); + assert_eq!( + fork_git_sync_document(Some(legacy_fork.clone()), Some(migrated_parent.clone())), + Some(migrated_parent.clone()) + ); + assert_eq!( + fork_git_sync_to_apply(&migrated_parent, Some(&legacy_fork), false).unwrap(), + legacy_fork + ); + assert_eq!( + fork_git_sync_to_apply(&Value::Null, Some(&legacy_fork), false).unwrap(), + legacy_fork + ); + // An `exclude_path` the save leaves behind after migrating is no fallback. + let mut leftover = migrated.clone(); + leftover["exclude_path"] = json!(["x/**"]); + assert_eq!( + fork_git_sync_to_apply(&migrated_parent, Some(&leftover), false).unwrap() + ["repositories"][0]["settings"], + migrated_parent["repositories"][0]["settings"] + ); + + assert!( + fork_git_sync_to_apply(&json!({ "repositories": null }), Some(&fork), true).is_err() + ); + assert_eq!( + fork_git_sync_to_apply(&parent, None, true).unwrap(), + Value::Null + ); + } } diff --git a/backend/windmill-api/src/workspaces_export.rs b/backend/windmill-api/src/workspaces_export.rs index 39227e49ee..46b7a7a8dd 100644 --- a/backend/windmill-api/src/workspaces_export.rs +++ b/backend/windmill-api/src/workspaces_export.rs @@ -968,11 +968,13 @@ pub(crate) async fn tarball_workspace( } if !skip_variables.unwrap_or(false) { + // `account` is left out: the variable endpoints ignore it, so a pushed spec carrying it + // would never match the variable it created and every sync would report it changed. let variables = sqlx::query_as::<_, ExportableListableVariable>(if !skip_secrets.unwrap_or(false) { - "SELECT workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" + "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, value_valid_until, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" } else { - "SELECT workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" + "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, value_valid_until, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" }) .bind(&w_id) .fetch_all(&mut *tx) diff --git a/backend/windmill-audit/src/audit_oss.rs b/backend/windmill-audit/src/audit_oss.rs index 02b075af9d..55babc1625 100644 --- a/backend/windmill-audit/src/audit_oss.rs +++ b/backend/windmill-audit/src/audit_oss.rs @@ -64,6 +64,22 @@ impl AuditAuthorable for AuditAuthor { } } +/// Where an audit row is written decides what a failed insert breaks. On a pool connection it +/// breaks nothing else, so it is logged and the action goes on. On a connection, which may hold +/// the action's transaction, the failure has aborted that transaction and its COMMIT would roll +/// back silently, so it is returned. +pub trait AuditExecutor<'c>: sqlx::Executor<'c, Database = sqlx::Postgres> { + const ISOLATED: bool; +} + +impl<'c> AuditExecutor<'c> for &'c sqlx::Pool<sqlx::Postgres> { + const ISOLATED: bool = true; +} + +impl<'c> AuditExecutor<'c> for &'c mut sqlx::PgConnection { + const ISOLATED: bool = false; +} + pub trait AuditAuthorable { fn username(&self) -> &str; fn email(&self) -> &str; @@ -75,7 +91,7 @@ pub trait AuditAuthorable { #[cfg(not(feature = "private"))] #[tracing::instrument(level = "trace", skip_all)] -pub async fn audit_log<'c, E: sqlx::Executor<'c, Database = Postgres>>( +pub async fn audit_log<'c, E: AuditExecutor<'c>>( _db: E, _author: &impl AuditAuthorable, mut _operation: &str, @@ -91,7 +107,7 @@ pub async fn audit_log<'c, E: sqlx::Executor<'c, Database = Postgres>>( /// AUTHORIZATION: records entries, checks nothing. The caller must have authorized `author` /// for the operation on every resource in `w_id` before calling. #[cfg(not(feature = "private"))] -pub async fn audit_log_many<'c, E: sqlx::Executor<'c, Database = Postgres>>( +pub async fn audit_log_many<'c, E: AuditExecutor<'c>>( _db: E, _author: &impl AuditAuthorable, _operation: &str, diff --git a/backend/windmill-common/src/apps.rs b/backend/windmill-common/src/apps.rs index 4e25cec17d..9ce4326212 100644 --- a/backend/windmill-common/src/apps.rs +++ b/backend/windmill-common/src/apps.rs @@ -34,14 +34,23 @@ pub fn app_value_has_inline_script(value: &Value) -> bool { } } -/// Every workspace runnable the app value points a component at, as `(is_flow, path)`. +/// What a path runnable of an app runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum AppRunnableKind { + Script, + Flow, + /// A saved AI agent (an `ai_agent` resource), run as one chat turn. + Agent, +} + +/// Every workspace runnable the app value points a component at, as `(kind, path)`. /// /// This is what the deployed bundle actually asks `execute_component` to run: it resolves a /// `runnable_id` against the stored `runnables` and sends `{runType}/{path}`. The policy's /// triggerables are a separate surface, so both have to be authorized. Anything not plain text /// is refused, never skipped: the editor compares `type` loosely (`["path"] == "path"`) and /// interpolates `path` (`["u/x"]` → `u/x`), so a skipped entry still runs. -pub fn app_value_runnable_paths(value: &Value) -> error::Result<Vec<(bool, String)>> { +pub fn app_value_runnable_paths(value: &Value) -> error::Result<Vec<(AppRunnableKind, String)>> { let bad = |msg: String| error::Error::BadRequest(msg); let runnables = match value.get("runnables") { None | Some(Value::Null) => return Ok(vec![]), @@ -61,12 +70,13 @@ pub fn app_value_runnable_paths(value: &Value) -> error::Result<Vec<(bool, Strin let Some(Value::String(path)) = runnable.get("path") else { return Err(bad(format!("Runnable {id} must name its path as text"))); }; - let is_flow = match runnable.get("runType") { - Some(Value::String(t)) if t == "flow" => true, - Some(Value::String(t)) if t == "script" || t == "hubscript" => false, + let kind = match runnable.get("runType") { + Some(Value::String(t)) if t == "flow" => AppRunnableKind::Flow, + Some(Value::String(t)) if t == "script" || t == "hubscript" => AppRunnableKind::Script, + Some(Value::String(t)) if t == "agent" => AppRunnableKind::Agent, _ => return Err(bad(format!("Unsupported runType for runnable {path}"))), }; - out.push((is_flow, path.clone())); + out.push((kind, path.clone())); } Ok(out) } diff --git a/backend/windmill-common/src/auth.rs b/backend/windmill-common/src/auth.rs index 24d9c99661..78d3b98c48 100644 --- a/backend/windmill-common/src/auth.rs +++ b/backend/windmill-common/src/auth.rs @@ -509,7 +509,7 @@ async fn fetch_authed_from_permissioned_as_inner( let member = match permissioned_as.split_once('/') { Some(("u", name)) => { sqlx::query!( - "SELECT is_admin, operator, email FROM usr where username = $1 AND \ + "SELECT is_admin, operator, workspace_role, email FROM usr where username = $1 AND \ workspace_id = $2 AND disabled = false", name, &w_id @@ -552,7 +552,14 @@ async fn fetch_authed_from_permissioned_as_inner( let (is_admin, is_operator) = if is_super_admin { (true, false) } else if let Some(m) = member.as_ref() { - (m.is_admin, m.operator) + let restricted = crate::roles::member_is_restricted( + &mut *conn, + w_id, + m.workspace_role.clone(), + m.operator, + ) + .await?; + (m.is_admin, restricted && !m.is_admin) } else { return Err(Error::NotFound(format!( "user {name} not found in workspace {w_id}" diff --git a/backend/windmill-common/src/client.rs b/backend/windmill-common/src/client.rs index 985d3bbbfc..54eb486da7 100644 --- a/backend/windmill-common/src/client.rs +++ b/backend/windmill-common/src/client.rs @@ -71,15 +71,32 @@ impl AuthedClient { } pub async fn get_id_token(&self, audience: &str) -> anyhow::Result<String> { + self.get_id_token_expiring_in(audience, None).await + } + + /// `expires_in` caps the token's lifetime below the instance default, for + /// audiences that refuse long-lived assertions. + pub async fn get_id_token_expiring_in( + &self, + audience: &str, + expires_in: Option<i64>, + ) -> anyhow::Result<String> { + // An audience can be a URL, whose slashes would otherwise split the path segment. let url = format!( "{}/api/w/{}/oidc/token/{}", - self.base_internal_url, self.workspace, audience + self.base_internal_url, + self.workspace, + urlencoding::encode(audience) ); - let response = self + let mut request = self .force_client .as_ref() .unwrap_or(&HTTP_CLIENT) - .post(&url) + .post(&url); + if let Some(expires_in) = expires_in { + request = request.query(&[("expires_in", expires_in)]); + } + let response = request .header( reqwest::header::AUTHORIZATION, reqwest::header::HeaderValue::from_str(&format!("Bearer {}", self.token))?, @@ -110,6 +127,30 @@ impl AuthedClient { make_basic_get_request(self, &url, None, Some("decoding resource value as json")).await } + /// The value of the `ai_agent` resource at `path`, refused when the resource there is of another + /// type. Only writes of an agent are checked for operators, so a step linking a path must not run + /// tools from a resource retyped, or recreated as another type, since the link was approved. + pub async fn get_agent_value(&self, path: &str) -> anyhow::Result<serde_json::Value> { + #[derive(serde::Deserialize)] + struct Resource { + resource_type: String, + value: Option<serde_json::Value>, + } + let url = format!( + "{}/api/w/{}/resources/get/{}", + self.base_internal_url, self.workspace, path + ); + let resource: Resource = + make_basic_get_request(self, &url, None, Some("decoding the agent resource")).await?; + if resource.resource_type != "ai_agent" { + anyhow::bail!( + "{path} is a {} resource, not an AI agent", + resource.resource_type + ); + } + Ok(resource.value.unwrap_or_default()) + } + pub async fn get_variable_value(&self, path: &str) -> anyhow::Result<String> { let url = format!( "{}/api/w/{}/variables/get_value/{}", diff --git a/backend/windmill-common/src/ee_oss.rs b/backend/windmill-common/src/ee_oss.rs index 82f99c54fb..24607574f1 100644 --- a/backend/windmill-common/src/ee_oss.rs +++ b/backend/windmill-common/src/ee_oss.rs @@ -72,9 +72,17 @@ pub async fn check_seat_cap_for_reactivation( } #[cfg(all(feature = "enterprise", not(feature = "private")))] -pub async fn check_seat_cap_for_operator_builder( - _db: &DB, - _w_id: &str, +pub struct SeatCapBaseline; + +#[cfg(all(feature = "enterprise", not(feature = "private")))] +pub async fn seat_cap_baseline(_db: &DB) -> anyhow::Result<SeatCapBaseline> { + Ok(SeatCapBaseline) +} + +#[cfg(all(feature = "enterprise", not(feature = "private")))] +pub async fn check_seat_cap_for_role_change( + _baseline: &SeatCapBaseline, + _tx: &mut sqlx::PgConnection, ) -> anyhow::Result<Option<String>> { Ok(None) } diff --git a/backend/windmill-common/src/flow_conversations.rs b/backend/windmill-common/src/flow_conversations.rs index 571877ead2..12b3daf2ec 100644 --- a/backend/windmill-common/src/flow_conversations.rs +++ b/backend/windmill-common/src/flow_conversations.rs @@ -14,6 +14,11 @@ use crate::utils::truncate_with_ellipsis; /// Changing it detaches every memory stored under a string memory id. const MEMORY_ID_NAMESPACE: Uuid = Uuid::from_u128(0x6f1c2d4e_8a3b_5c7d_9e0f_1a2b3c4d5e6f); +/// Owns anonymous app visitors' agent conversations, as `created_by` names an anonymous app run. +/// It is also a valid username, so listing conversations leaves these out: a user of that name +/// would otherwise list every anonymous visitor's. +pub const ANONYMOUS_CONVERSATION_OWNER: &str = "anonymous"; + /// 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 diff --git a/backend/windmill-common/src/flows.rs b/backend/windmill-common/src/flows.rs index 222694aeac..500549c549 100644 --- a/backend/windmill-common/src/flows.rs +++ b/backend/windmill-common/src/flows.rs @@ -252,8 +252,8 @@ pub async fn resolve_modules( /// modules, every branch, and the `tools` of an AI agent step. /// /// Returns what the caller still has to authorize against its own permissions, which this -/// value-only walk cannot: every runnable the steps reference, the worker tags they pin, and the -/// `(path, hash)` pairs of version-pinned steps. See [`ComposedFlowRefs`] for why each one is not +/// value-only walk cannot: every runnable and linked agent the steps reference, the worker tags +/// they pin, and the `(path, hash)` pairs of version-pinned steps. See [`ComposedFlowRefs`] for why each one is not /// already settled by the walk. pub fn check_flow_is_composition_only(value: &FlowValue) -> Result<ComposedFlowRefs, Error> { let mut refs = ComposedFlowRefs::default(); @@ -276,6 +276,65 @@ pub struct ComposedFlowRefs { pub runnables: Vec<(bool, String)>, /// Version-pinned script steps, as `(path, hash)`. pub pinned_scripts: Vec<(String, ScriptHash)>, + /// The `ai_agent` resources that agent steps link. + pub agents: Vec<LinkedAgent>, +} + +/// An agent step's link, with the tool inputs the step binds, keyed by tool id. +pub struct LinkedAgent { + pub path: String, + pub bound_inputs: Vec<(String, Vec<String>)>, +} + +/// A builder's step may bind only the tool inputs its linked agent leaves open, passing them what +/// it could pass a deployed runnable's inputs. An input the agent fills is part of what its author +/// wrote, and the step's binding would replace it at run time. Every tool sharing an id is +/// checked, as the overlay binds them all. +pub fn check_bound_agent_inputs_are_open( + agent: &str, + tools: &[AgentTool], + bound_inputs: &[(String, Vec<String>)], +) -> Result<(), Error> { + for (tool_id, keys) in bound_inputs { + for tool in tools.iter().filter(|t| &t.id == tool_id) { + check_tool_inputs_are_open(agent, tool_id, &tool.value, keys)?; + } + } + Ok(()) +} + +fn check_tool_inputs_are_open( + agent: &str, + tool_id: &str, + value: &ToolValue, + keys: &[String], +) -> Result<(), Error> { + let ToolValue::FlowModule(value) = value else { + return Ok(()); + }; + let input_transforms = match value { + FlowModuleValue::Script { input_transforms, .. } + | FlowModuleValue::RawScript { input_transforms, .. } + | FlowModuleValue::FlowScript { input_transforms, .. } + | FlowModuleValue::AIAgent { input_transforms, .. } + | FlowModuleValue::AIDecision { input_transforms, .. } => input_transforms, + // Fail closed on any other kind, as the worker's `overlay_tool_inputs` skips them. + _ => { + return Err(Error::PermissionDenied(format!( + "Tool {tool_id} of agent {agent} takes no inputs a builder can set" + ))) + } + }; + match keys + .iter() + .find(|k| input_transforms.get(*k).is_some_and(|t| t.is_completed())) + { + Some(key) => Err(Error::PermissionDenied(format!( + "Input {key} of tool {tool_id} is set by agent {agent}, so a builder cannot \ + change it. Bind only the inputs the agent leaves to the model." + ))), + None => Ok(()), + } } fn check_module_is_composition_only( @@ -343,12 +402,20 @@ fn check_module_value_is_composition_only( FlowModuleValue::BranchAll { branches, .. } => { check_branches_are_composition_only(branches, id, refs)? } - FlowModuleValue::AIAgent { tools, tag, agent, .. } => { - // A linked agent resolves its tools from an `ai_agent` resource at run time, and - // operators may write resources, so those tools are outside this check: the list can - // be swapped for a raw script after the flow is deployed. - if agent.is_some() { - return refuse("links an AI agent resource, whose tools live outside the flow"); + FlowModuleValue::AIAgent { tools, tag, agent, tool_inputs, .. } => { + // A linked agent's tools are resolved from its resource at run time, outside this + // walk. That is safe only because an operator's every write of an agent passes this + // same check (`validate_operator_agent`), as a developer's agent is code they wrote. + if let Some(agent) = agent { + let path = agent + .trim_start_matches("$res:") + .trim_start_matches("res://"); + let bound_inputs = tool_inputs + .iter() + .map(|(tool, inputs)| (tool.clone(), inputs.keys().cloned().collect())) + .collect(); + refs.agents + .push(LinkedAgent { path: path.to_string(), bound_inputs }); } push_tag(tag); for tool in tools { @@ -477,15 +544,48 @@ mod tests { #[test] fn composition_check_rejects_code_reachable_through_an_ai_agent() { - for value in [ - serde_json::json!({"modules": [{"id": "a", "value": {"type": "aiagent", - "input_transforms": {}, "tools": [{"id": "t", "value": {"tool_type": "flowmodule", - "type": "rawscript", "content": "x", "language": "bun"}}]}}]}), - serde_json::json!({"modules": [{"id": "a", "value": {"type": "aiagent", - "input_transforms": {}, "tools": [], "agent": "$res:f/x/agent"}}]}), - ] { - assert!(check_flow_is_composition_only(&flow(value)).is_err()); - } + let value = serde_json::json!({"modules": [{"id": "a", "value": {"type": "aiagent", + "input_transforms": {}, "tools": [{"id": "t", "value": {"tool_type": "flowmodule", + "type": "rawscript", "content": "x", "language": "bun"}}]}}]}); + assert!(check_flow_is_composition_only(&flow(value)).is_err()); + } + + /// A builder may link only an agent they can read, which the walk cannot know: it has to + /// surface the path for the caller to check. + #[test] + fn composition_check_reports_linked_agents() { + let refs = check_flow_is_composition_only(&flow(serde_json::json!({"modules": [{ + "id": "a", "value": {"type": "aiagent", "input_transforms": {}, "tools": [], + "agent": "$res:f/x/agent", "tool_inputs": {"t": {}}}}]}))) + .unwrap(); + assert_eq!(refs.agents[0].path, "f/x/agent"); + assert_eq!(refs.agents[0].bound_inputs, vec![("t".to_string(), vec![])]); + } + + #[test] + fn bound_agent_inputs_must_be_left_to_the_model() { + // Two tools share the id: the overlay binds both, so the second's `query` counts. + let tools: Vec<AgentTool> = serde_json::from_value(serde_json::json!([ + {"id": "t", "value": {"tool_type": "flowmodule", "type": "rawscript", "content": "x", + "language": "bun", "input_transforms": {}}}, + {"id": "t", "value": {"tool_type": "flowmodule", "type": "rawscript", "content": "x", + "language": "bun", "input_transforms": { + "query": {"type": "static", "value": "SELECT 1"}, + "limit": {"type": "ai"}, + "note": {"type": "static", "value": null}}}}])) + .unwrap(); + let bind = |keys: &[&str]| { + check_bound_agent_inputs_are_open( + "f/x/agent", + &tools, + &[( + "t".to_string(), + keys.iter().map(|k| k.to_string()).collect(), + )], + ) + }; + assert!(bind(&["limit", "note", "absent"]).is_ok()); + assert!(bind(&["limit", "query"]).is_err()); } #[test] diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 07a05f5ab4..ce33a8aefe 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -432,6 +432,9 @@ pub const WORKSPACE_REGISTRIES_SETTING: &str = "workspace_registries"; pub const RESTART_COORDINATION_SETTING: &str = "_restart_coordination"; 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_max_percent`% of the shared worker pool once it has been // occupying it for more than `workspace_fairness_duration_secs` seconds. See @@ -945,6 +948,7 @@ pub fn workspace_integration_oauth_key(client_name: &str) -> &str { pub fn workspace_integration_token_endpoint(client_name: &str, base_url: &str) -> String { match client_name { "google" => "https://oauth2.googleapis.com/token".to_string(), + "github" => "https://github.com/login/oauth/access_token".to_string(), _ => format!("{}/apps/oauth2/api/v1/token", base_url), } } @@ -953,6 +957,7 @@ pub fn workspace_integration_token_endpoint(client_name: &str, base_url: &str) - pub fn workspace_integration_auth_endpoint(client_name: &str, base_url: &str) -> String { match client_name { "google" => "https://accounts.google.com/o/oauth2/v2/auth".to_string(), + "github" => "https://github.com/login/oauth/authorize".to_string(), _ => format!("{}/apps/oauth2/authorize", base_url), } } diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index 2b476b338a..9fe43e0fe0 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -1006,6 +1006,8 @@ pub struct WorkerGroupConfig { #[serde(skip_serializing_if = "Option::is_none")] pub env_vars_allowlist: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] + pub disable_job_proxy: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] pub min_alive_workers_alert_threshold: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] pub autoscaling: Option<AutoscalingConfig>, @@ -1231,15 +1233,17 @@ fn mask_nested_sensitive(key: &str, value: &serde_json::Value) -> serde_json::Va } } // Settings that are maps-of-objects where each child has a sensitive sub-field. - const NESTED_MAP_SENSITIVE: &[(&str, &str)] = &[("oauths", "secret")]; - for &(parent_key, child_field) in NESTED_MAP_SENSITIVE { + const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[("oauths", &["secret", "signing_secret"])]; + for &(parent_key, child_fields) in NESTED_MAP_SENSITIVE { if key == parent_key { if let serde_json::Value::Object(entries) = value { let mut masked = entries.clone(); for (_entry_key, entry_val) in masked.iter_mut() { if let serde_json::Value::Object(ref mut obj) = entry_val { - if let Some(v) = obj.get(child_field) { - obj.insert(child_field.to_string(), redact_json_value(v)); + for &child_field in child_fields { + if let Some(v) = obj.get(child_field) { + obj.insert(child_field.to_string(), redact_json_value(v)); + } } } } @@ -1573,9 +1577,22 @@ pub async fn sync_global_settings_declarative( .map_err(|e| anyhow::anyhow!("{max_expiration_key}: {e}"))?; let mut diff = diff_global_settings(current, desired, ApplyMode::Replace); + let roles_key = crate::global_settings::WORKSPACE_ROLES_SETTING; + let roles_written = diff.upserts.iter().any(|(k, _)| k == roles_key) + || diff.deletes.iter().any(|k| k == roles_key); + if roles_written { + crate::roles::validate_instance_roles_write(db, desired.get(roles_key)) + .await + .map_err(|e| anyhow::anyhow!("{roles_key}: {e}"))?; + } crate::external_instance_pg::write_external_instance_pg_from_diff(db, &mut diff, observer) .await?; apply_settings_diff(db, &diff, observer).await?; + if roles_written { + crate::roles::after_instance_roles_write(db) + .await + .map_err(|e| anyhow::anyhow!("{roles_key}: {e}"))?; + } Ok(()) } @@ -2899,10 +2916,12 @@ mod tests { #[test] fn format_setting_value_redacts_oauth_secrets() { let val = serde_json::json!({ - "google": {"id": "client-id", "secret": "my-super-secret-12345"} + "google": {"id": "client-id", "secret": "my-super-secret-12345"}, + "slack": {"id": "s", "secret": "s", "signing_secret": "slack-signing-secret-678"} }); let formatted = format_setting_value("oauths", &val); assert!(!formatted.contains("my-super-secret-12345")); + assert!(!formatted.contains("slack-signing-secret-678")); assert!(formatted.contains("client-id")); assert!(formatted.contains("****")); } diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index d7190ff45f..5ca70d3b58 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -16,12 +16,77 @@ use crate::{ flows::get_full_hub_flow_by_path, get_latest_deployed_hash_for_path, get_latest_flow_version_info_for_path, scripts::{get_full_hub_script_by_path, ScriptHash, ScriptLang}, - utils::{StripPath, HTTP_CLIENT}, + utils::{strip_json_nul, StripPath, HTTP_CLIENT}, worker::{custom_tag_matches, to_raw_value, CUSTOM_TAGS_PER_WORKSPACE, WINDMILL_DIR}, workspaces::workspace_with_fork_ancestors, FlowVersionInfo, ScriptHashInfo, Tag, }; +/// Whether `args` already reads the way `push` will store it, i.e. holds no NUL escape in a +/// name or a value. Cheap (one SIMD substring scan per value) so the normalization below can +/// be a no-op on the overwhelmingly common clean case. +pub fn args_contain_nul(args: &HashMap<String, Box<RawValue>>) -> bool { + args.iter().any(|(k, v)| { + k.contains('\0') || memchr::memmem::find(v.get().as_bytes(), b"\\u0000").is_some() + }) +} + +/// Rewrite `args` the way `push` stores it: `push` runs [`strip_json_nul`] over the +/// serialized args just before the INSERT, which removes `\u0000` escapes from **names as +/// well as values** (jsonb rejects them with 22P05). Any decision taken on a name before +/// that — `push`'s own removal of a caller [`MODULES_ARG`], an app policy's `static_inputs` +/// and `one_of_inputs`, the `PushArgs` serializer's "`extra` wins this name" rule — would +/// otherwise compare a name nobody knows against the name that actually lands in the job: +/// an arg sent as `_MODULES\0` is stored as `_MODULES`, and a viewer's `tenant\0` is stored +/// as `tenant`, after the publisher's pinned value, which jsonb then discards as the earlier +/// of two equal keys. +/// +/// Normalizing first makes every such check see the stored name. Values are normalized too, +/// so a check on a value sees what the job will receive. +/// +/// Two names that collide once normalized keep a single value, deterministically: the +/// spelling without NULs wins, then the lexicographically smallest original name — never the +/// one that `HashMap` iteration happened to serialize last. +pub fn normalize_nul_in_args(args: &mut HashMap<String, Box<RawValue>>) { + if !args_contain_nul(args) { + return; + } + let mut entries = args.drain().collect::<Vec<_>>(); + entries.sort_by(|(a, _), (b, _)| { + a.contains('\0') + .cmp(&b.contains('\0')) + .then_with(|| a.cmp(b)) + }); + for (key, value) in entries { + let key = if key.contains('\0') { + key.replace('\0', "") + } else { + key + }; + let stripped = match strip_json_nul(value.get()) { + std::borrow::Cow::Owned(stripped) => RawValue::from_string(stripped).ok(), + std::borrow::Cow::Borrowed(_) => None, + }; + args.entry(key).or_insert(stripped.unwrap_or(value)); + } +} + +/// Drop every [`RESERVED_CONTROL_ARGS`] key from args that a third party supplied for a job +/// running under somebody else's identity (an HTTP route body or native trigger message run +/// as the trigger's owner, a public app viewer's inputs run as the app's publisher). Those +/// keys pick the function the worker calls instead of `main`, the module files written into +/// the job directory, and where workspace imports resolve from: the third party must not +/// choose any of them, while a caller running its own code under its own identity still may. +/// +/// Normalizes first, so a key spelled `_ENTRYPOINT_OVERRIDE\0` — which `push` stores as +/// `_ENTRYPOINT_OVERRIDE` — cannot slip past the comparison. +pub fn sanitize_untrusted_args(args: &mut HashMap<String, Box<RawValue>>) { + normalize_nul_in_args(args); + for key in RESERVED_CONTROL_ARGS { + args.remove(key); + } +} + pub fn get_has_preprocessor_from_content_and_lang( content: &str, language: &ScriptLang, @@ -633,6 +698,97 @@ pub async fn delete_jobs(conn: &mut sqlx::PgConnection, ids: &[uuid::Uuid]) -> e Ok(()) } +#[cfg(test)] +mod reserved_args_tests { + use super::{normalize_nul_in_args, sanitize_untrusted_args}; + use serde_json::value::RawValue; + use std::collections::HashMap; + + fn raw(json: &str) -> Box<RawValue> { + RawValue::from_string(json.to_string()).unwrap() + } + + fn args(entries: &[(&str, &str)]) -> HashMap<String, Box<RawValue>> { + entries + .iter() + .map(|(k, v)| (k.to_string(), raw(v))) + .collect() + } + + fn as_json(args: &HashMap<String, Box<RawValue>>) -> serde_json::Value { + serde_json::to_value(args).unwrap() + } + + /// A clean map must come out byte for byte the same: this runs on every push. + #[test] + fn normalization_leaves_clean_args_alone() { + let mut map = args(&[ + ("tenant", r#""acme""#), + // A legitimately escaped backslash followed by the literal text `u0000` + // (minified JS regexes contain these) is not a NUL and must survive. + ("src", r#""[^\\u0000]+""#), + ]); + let before = as_json(&map); + normalize_nul_in_args(&mut map); + assert_eq!(as_json(&map), before); + } + + /// `push` stores the args with their NUL escapes removed, names included, so a name + /// that only differs by NULs is the same name and must be compared as such. + #[test] + fn normalization_renames_nul_spelled_names_and_cleans_values() { + let mut map = args(&[ + ("_MODULES\u{0}", r#"{"m.py": "evil"}"#), + ("_MOD\u{0}ULES", r#"{"m.py": "evil"}"#), + ("greeting\u{0}", r#""anything""#), + ("note", r#""a\u0000b""#), + ]); + normalize_nul_in_args(&mut map); + let mut names = map.keys().cloned().collect::<Vec<_>>(); + names.sort(); + assert_eq!(names, vec!["_MODULES", "greeting", "note"]); + assert_eq!(map["note"].get(), r#""ab""#); + } + + /// Which of two names that collide once normalized survives may not depend on + /// `HashMap` iteration order: the spelling the publisher/server used wins. + #[test] + fn normalization_keeps_the_nul_free_spelling_on_collision() { + for _ in 0..16 { + let mut map = args(&[ + ("tenant", r#""acme""#), + ("tenant\u{0}", r#""globex""#), + ("\u{0}tenant", r#""initech""#), + ]); + normalize_nul_in_args(&mut map); + assert_eq!(map.len(), 1); + assert_eq!(map["tenant"].get(), r#""acme""#); + } + } + + /// Every reserved control key goes, in every spelling, and nothing else does. + #[test] + fn untrusted_args_lose_every_reserved_control_key() { + let mut map = args(&[ + ("_ENTRYPOINT_OVERRIDE", r#""apply""#), + ("_ENTRYPOINT_OVERRIDE\u{0}", r#""apply""#), + ("_ENTRY\u{0}POINT_OVERRIDE", r#""apply""#), + ("_MODULES", r#"{"m.py": "evil"}"#), + ("_MODULES\u{0}", r#"{"m.py": "evil"}"#), + ("_TEMP_SCRIPT_REFS", r#"{"f/a/b": "deadbeef"}"#), + ("_TEMP_SCRIPT_REFS\u{0}", r#"{"f/a/b": "deadbeef"}"#), + // Neighbours that must not be caught by a prefix/contains match. + ("_TEMP_SCRIPT_REFS_", r#"1"#), + ("entrypoint", r#""main""#), + ("action", r#""refund""#), + ]); + sanitize_untrusted_args(&mut map); + let mut names = map.keys().cloned().collect::<Vec<_>>(); + names.sort(); + assert_eq!(names, vec!["_TEMP_SCRIPT_REFS_", "action", "entrypoint"]); + } +} + #[cfg(test)] mod tests { use super::is_safe_log_file_path; diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 9f1ccf7211..fac05d1fea 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -77,8 +77,8 @@ pub mod flows; pub mod fork_storage; pub mod folders; pub mod global_settings; -pub mod hub_resource_types; pub mod guest_jwt; +pub mod hub_resource_types; pub mod indexer; pub mod instance_config; pub mod job_metrics; @@ -128,6 +128,7 @@ pub mod query_builders; pub mod queue; pub mod queue_metrics; pub mod result_stream; +pub mod roles; pub mod runnable_job_stats; pub mod runnable_settings; pub mod runnables; @@ -174,7 +175,13 @@ pub const DEFAULT_AI_SHARED_ARTIFACT_RETENTION_SECS: i64 = 60 * 60 * 24 * 30; pub const WM_DEPLOYERS_GROUP: &str = "wm_deployers"; /// Groups Windmill creates lazily (`ON CONFLICT DO NOTHING`) and grants permissions to before /// they exist; a member who created one first would inherit those grants. -pub const RESERVED_GROUP_NAMES: &[&str] = &["error_handler", "success_handler", "slack", "teams"]; +pub const RESERVED_GROUP_NAMES: &[&str] = &[ + "error_handler", + "success_handler", + "variable_expiration_handler", + "slack", + "teams", +]; /// A century. Every consumer has to survive `now - retention`, and the ceilings are much lower /// than an `i64`: `DateTime` subtraction panics past year 262143, and the `(<n> s)::interval` @@ -836,6 +843,50 @@ mod validate_dbname_tests { } } +#[cfg(test)] +mod validate_dbname_not_option_like_tests { + use super::validate_dbname_not_option_like; + + /// A source is any database a user already has, so everything `validate_dbname` refuses but + /// Postgres accepts has to keep working. + #[test] + fn accepts_every_name_that_is_not_an_option() { + for name in [ + "mydb", + "My-Db_1", + "2024_archive", + "my.db", + "db with spaces", + "Grüße", + "host=elsewhere port=5433", + "", + "a-dash-inside--it", + ] { + assert!( + validate_dbname_not_option_like(name).is_ok(), + "refused the legitimate name {name:?}" + ); + } + } + + #[test] + fn rejects_a_name_that_an_argument_vector_would_read_as_an_option() { + for name in [ + "--file=/tmp/x", + "--restrict-key=k", + "-f", + "-", + " --file=/tmp/x", + "\t-f", + ] { + let err = validate_dbname_not_option_like(name) + .expect_err(&format!("accepted the option-like name {name:?}")) + .to_string(); + assert!(err.contains("cannot start with '-'"), "{err}"); + } + } +} + #[cfg(test)] mod pg_tls_tests { use super::PgDatabase; @@ -962,6 +1013,13 @@ ta9ELulniZau8zUAtwqwecxodzl+KO8NYj0a9PGgAM64dMqkRtRA8P4UP350Nag3\n\ assert!(pg(None, None).to_uri().contains("sslmode=prefer")); } + #[test] + fn to_uri_sslmode_cannot_add_parameters() { + let uri = pg(Some("disable&hostaddr=127.0.0.2"), None).to_uri(); + assert!(uri.ends_with("?sslmode=disable%26hostaddr%3D127.0.0.2")); + assert!(uri.parse::<tokio_postgres::Config>().is_err()); + } + #[test] fn options_survive_to_uri() { let mut db = pg(Some("require"), None); @@ -1101,7 +1159,9 @@ impl PgDatabase { let sslmode = match self.sslmode.as_deref() { Some("allow") => "prefer".to_string(), Some("require") | Some("verify-ca") | Some("verify-full") => "require".to_string(), - Some(s) => s.to_string(), + // Encoded like the other fields: a raw '&' would append parameters (`hostaddr`, `host`, + // `port`) that send the connection somewhere else than the host this struct names. + Some(s) => urlencoding::encode(s).into_owned(), None => "prefer".to_string(), }; // Encode host/dbname too: an unencoded '@', '/', '?' or '&' would otherwise @@ -1156,6 +1216,14 @@ impl PgDatabase { let on_local_cluster = local.host == self.host && local.port.unwrap_or(5432) == self.port.unwrap_or(5432); if let Some(db) = main_db.filter(|_| on_local_cluster) { + // Only a connection Windmill built carries the stored password (and the + // role's has drifted from it). Anything else is a resource whose author + // named this role and host: retrying it would log them in with a + // credential they were never given, and rotate it on their say-so. + let stored_pwd = crate::utils::get_custom_pg_instance_password(db).await?; + if self.password.as_deref() != Some(stored_pwd.as_str()) { + return Err(e); + } tracing::warn!( "custom_instance_user password auth failed, refreshing and retrying..." ); @@ -1588,6 +1656,26 @@ pub fn validate_dbname(dbname: &str) -> error::Result<()> { Ok(()) } +/// The one restriction on the name of a database Windmill only *reads from*: it may not look like +/// a command-line option. +/// +/// [`validate_dbname`] is the rule for a name Windmill creates or interpolates into SQL, and is +/// far too narrow here: a source is any Postgres resource a user already has, and an existing +/// database may legitimately be named `2024_archive`, `my.db`, `Grüße` or anything else Postgres +/// accepts as a quoted identifier. Refusing those would break working resources. A name opening +/// with `-` is the one shape that is never a database and always a mistake or an attempt to smuggle +/// an option into a `pg_dump`/`psql` argument vector, so it is refused wherever a source is +/// resolved — the commands themselves pass the name through `PGDATABASE` and never on the command +/// line, and this keeps a future caller that forgets from re-opening that door. +pub fn validate_dbname_not_option_like(dbname: &str) -> error::Result<()> { + if dbname.trim_start().starts_with('-') { + return Err(error::Error::BadRequest( + "Database name cannot start with '-'".to_string(), + )); + } + Ok(()) +} + /// Lock the instance databases among `names` until `tx` ends, in a stable order. Taken by every /// settings save naming an instance database, and by [`drop_unused_instance_database`]: a save /// cannot start using a database between that drop's check that nothing does and the drop. @@ -2338,13 +2426,13 @@ pub async fn legacy_on_behalf_of_email( /// Shared by [`ScriptHashInfo::on_behalf_of`] and [`FlowVersionInfo::on_behalf_of`]. /// -/// Reads identity data through the non-RLS pool and enforces nothing itself: it answers who a -/// row already says it runs as. Callers must have authorized `w_id` — and the row they read it +/// Reads identity tables, which carry no RLS (a user transaction reads them as the pool does), +/// and enforces nothing itself: it answers who a row already says it runs as. Callers must have authorized `w_id` — and the row they read it /// from — before dispatching a job with what it returns. -pub async fn on_behalf_of_from_permissioned_as( +pub async fn on_behalf_of_from_permissioned_as<'c>( permissioned_as: Option<&str>, w_id: &str, - db: &DB, + db: impl sqlx::PgExecutor<'c>, ) -> error::Result<Option<jobs::OnBehalfOf>> { let Some(permissioned_as) = permissioned_as else { return Ok(None); @@ -2443,6 +2531,10 @@ pub fn get_latest_deployed_hash_for_path<'e>( ScriptHash(hash), ); } else { + // Release the user-db connection first: holding it while taking a + // second one from the same pool starves the pool under a burst of + // requests for paths the caller cannot see. + drop(conn); let mut conn = db2.acquire().await?; let exists = get_latest_script_hash(&mut *conn, script_path, w_id) .await? @@ -2847,6 +2939,7 @@ where CachedFlowPath(path.to_string()), ); } else { + drop(conn); let mut conn = db.acquire().await?; let exists = get_latest_flow_version_for_path(&mut *conn, w_id, path) .await? @@ -3029,9 +3122,8 @@ async fn get_latest_flow_version_for_path<'e, E: sqlx::PgExecutor<'e>>( Ok(version) } -pub async fn get_latest_hash_for_path<'c, E: sqlx::PgExecutor<'c>>( - db: E, - db2: &DB, +pub async fn get_latest_hash_for_path( + db: &mut sqlx::PgConnection, w_id: &str, script_path: &str, require_locked: bool, @@ -3062,13 +3154,13 @@ pub async fn get_latest_hash_for_path<'c, E: sqlx::PgExecutor<'c>>( w_id, require_locked ) - .fetch_optional(db) + .fetch_optional(&mut *db) .await?; let script = utils::not_found_if_none(r_o, "script", script_path)?; let on_behalf_of = - on_behalf_of_from_permissioned_as(script.on_behalf_of.as_deref(), w_id, db2).await?; + on_behalf_of_from_permissioned_as(script.on_behalf_of.as_deref(), w_id, db).await?; Ok(( scripts::ScriptHash(script.hash), diff --git a/backend/windmill-common/src/min_version.rs b/backend/windmill-common/src/min_version.rs index 3719abd31c..9005ab834a 100644 --- a/backend/windmill-common/src/min_version.rs +++ b/backend/windmill-common/src/min_version.rs @@ -27,9 +27,13 @@ pub const MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES: VC = vc(1, 822, 0, "Restricted // stored secret variables. Reading it ships one release earlier (1.831), so a rollback to // that release still reads every secret; below it, secrets written after the switch stay // unreadable until rolled forward. Only worker versions are seen here, not servers. -// Also gates widening `variable.value`, which needs every process to retire the connections -// the widening poisons (`db::retire_connections_opened_before_now`): that also ships in 1.832. pub const MIN_VERSION_SUPPORTS_AEAD_SECRETS: VC = vc(1, 832, 0, "AES-GCM secret encryption"); +// Gates widening `variable.value`. Every query returning that column casts it to text from +// this release, so the widening changes no result type: before it, each statement prepared on +// the column fails once per connection, and behind PgBouncer until its server connection +// closes. Must name the release this ships in. +pub const MIN_VERSION_SUPPORTS_VARIABLE_VALUE_WIDENING: VC = + vc(1, 848, 0, "variable.value widening"); // A renewed license key replaces the one every process reads, and a worker that predates // Ed25519 support rejects an Ed25519-signed key and stops pulling jobs, so renewal only offers // to accept one once this is met. Only worker versions are seen here, not servers. Must name diff --git a/backend/windmill-common/src/oidc_oss.rs b/backend/windmill-common/src/oidc_oss.rs index 2945f8b87a..60ef4da687 100644 --- a/backend/windmill-common/src/oidc_oss.rs +++ b/backend/windmill-common/src/oidc_oss.rs @@ -98,6 +98,7 @@ pub enum OidcCaller { Vault, Sqs, Bedrock, + Anthropic, } #[cfg(not(feature = "private"))] diff --git a/backend/windmill-common/src/roles.rs b/backend/windmill-common/src/roles.rs new file mode 100644 index 0000000000..b3fd9937f4 --- /dev/null +++ b/backend/windmill-common/src/roles.rs @@ -0,0 +1,998 @@ +//! Workspace roles: what a non-admin member may author, manage and see. +//! +//! `developer` and `operator` are the default roles. An EE instance defines its own list in the +//! [`WORKSPACE_ROLES_SETTING`] global setting (at least one role), and a workspace may override any +//! role's capabilities, or on EE define roles of its own, in `workspace_settings.role_overrides`. +//! Workspace admin is not a role: it is the `is_admin` flag on top of whichever role a member has, +//! and holds every capability. See `docs/workspace-roles.md`. +//! +//! A member's role is `usr.workspace_role`, or, while that is NULL, `operator` / `developer` from the +//! legacy `usr.operator` flag. `ApiAuthed::is_operator` means "this member's role is restricted", +//! computed at authentication from the role, never from `usr.operator` alone: every gate fast-paths +//! on it, so a stale flag would let a restricted member through. + +use std::{collections::HashMap, sync::Arc}; + +use quick_cache::sync::Cache; +use serde::{Deserialize, Serialize}; + +use crate::{ + db::Authable, + error::{Error, Result}, + global_settings::WORKSPACE_ROLES_SETTING, + DB, +}; + +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)] +#[serde(rename_all = "snake_case")] +pub enum AuthorLevel { + #[default] + None, + /// Assemble already-deployed runnables, with no code of one's own. A composed flow is checked + /// in full server-side; a composed full-code app is forced into sandbox isolation. See + /// `docs/operator-builder-rights.md`. + Compose, + Full, +} + +/// 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)] +pub struct RoleVisibility { + pub runs: bool, + pub schedules: bool, + pub resources: bool, + pub variables: bool, + pub assets: bool, + pub triggers: bool, + pub audit_logs: bool, + pub groups: bool, + pub folders: bool, + pub workers: bool, +} + +impl RoleVisibility { + pub const ALL: Self = Self { + runs: true, + schedules: true, + resources: true, + variables: true, + assets: true, + triggers: true, + audit_logs: true, + groups: true, + folders: true, + workers: true, + }; + pub const NONE: Self = Self { + runs: false, + schedules: false, + resources: false, + variables: false, + assets: false, + triggers: false, + audit_logs: false, + groups: false, + folders: false, + workers: false, + }; +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +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. + pub code: bool, + pub flows: AuthorLevel, + pub apps: AuthorLevel, + pub manage_schedules: bool, + pub manage_triggers: bool, + pub visibility: RoleVisibility, +} + +impl RoleCapabilities { + pub const FULL: Self = Self { + code: true, + flows: AuthorLevel::Full, + apps: AuthorLevel::Full, + manage_schedules: true, + manage_triggers: true, + visibility: RoleVisibility::ALL, + }; + + /// The `operator` role as it stood before roles were configurable, and the base any other + /// role's unset keys fall back to. + pub const OPERATOR: Self = Self { + code: false, + flows: AuthorLevel::None, + apps: AuthorLevel::None, + manage_schedules: true, + manage_triggers: true, + visibility: RoleVisibility::ALL, + }; + + /// For a restricted caller whose role cannot be resolved: a guest, a removed member's job, a + /// role name no longer defined. + pub const NONE: Self = Self { + code: false, + flows: AuthorLevel::None, + apps: AuthorLevel::None, + manage_schedules: false, + manage_triggers: false, + visibility: RoleVisibility::NONE, + }; + + /// What a role named `name` holds before any configuration applies. + pub fn base_for(name: &str) -> Self { + if name == DEVELOPER_ROLE { + Self::FULL + } else { + Self::OPERATOR + } + } + + /// Whether a member of this role is gated at all. Every gate skips an unrestricted caller + /// without reading its role, which is what `ApiAuthed::is_operator` carries. Visibility is + /// left out: it only hides pages, and must not turn a full author into an operator for the + /// raw `is_operator` checks, job permissions and credential caches keyed on it. + pub fn is_restricted(&self) -> bool { + Self { visibility: RoleVisibility::ALL, ..*self } != Self::FULL + } + + /// Whether the role authors deployable artifacts and so costs a full seat rather than half. + /// Composing counts: there is no half-author. + pub fn is_author(&self) -> bool { + self.code || self.flows != AuthorLevel::None || self.apps != AuthorLevel::None + } + + pub fn has_manage(&self, kind: crate::workspaces::ManageKind) -> bool { + match kind { + crate::workspaces::ManageKind::Schedules => self.manage_schedules, + crate::workspaces::ManageKind::Triggers => self.manage_triggers, + } + } + + pub fn level(&self, kind: crate::workspaces::BuilderKind) -> AuthorLevel { + match kind { + crate::workspaces::BuilderKind::Flows => self.flows, + crate::workspaces::BuilderKind::Apps => self.apps, + } + } + + fn apply(&mut self, patch: &RoleCapabilitiesPatch) { + if let Some(v) = patch.code { + self.code = v; + } + if let Some(v) = patch.flows { + self.flows = v; + } + if let Some(v) = patch.apps { + self.apps = v; + } + if let Some(v) = patch.manage_schedules { + self.manage_schedules = v; + } + if let Some(v) = patch.manage_triggers { + self.manage_triggers = v; + } + if let Some(v) = &patch.visibility { + v.apply(&mut self.visibility); + } + } + + /// A `Full` flow or app carries inline code, so granting one without `code` would be a way + /// around refusing `code`. + pub fn validate(&self, role: &str) -> Result<()> { + if !self.code && (self.flows == AuthorLevel::Full || self.apps == AuthorLevel::Full) { + return Err(Error::BadRequest(format!( + "role `{role}`: full flow or app authoring requires the code capability" + ))); + } + Ok(()) + } +} + +/// A partial [`RoleCapabilities`]: an unset key falls through to the layer below (workspace +/// override, then instance definition, then [`RoleCapabilities::base_for`]). Stored settings are +/// patches rather than full values so that a key added later reads as "never configured". +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] +pub struct RoleCapabilitiesPatch { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub flows: Option<AuthorLevel>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub apps: Option<AuthorLevel>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub manage_schedules: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub manage_triggers: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub visibility: Option<RoleVisibilityPatch>, +} + +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] +pub struct RoleVisibilityPatch { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub runs: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub schedules: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resources: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variables: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub assets: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub triggers: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub audit_logs: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub groups: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folders: Option<bool>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workers: Option<bool>, +} + +impl RoleVisibilityPatch { + fn apply(&self, v: &mut RoleVisibility) { + macro_rules! set { + ($($f:ident),*) => { $( if let Some(x) = self.$f { v.$f = x; } )* }; + } + set!( + runs, schedules, resources, variables, assets, triggers, audit_logs, groups, folders, + workers + ); + } +} + +/// The smallest patch that turns `base` into `target`: only the keys that differ. +pub fn diff_capabilities( + base: &RoleCapabilities, + target: &RoleCapabilities, +) -> RoleCapabilitiesPatch { + fn d<T: PartialEq + Copy>(b: T, t: T) -> Option<T> { + (b != t).then_some(t) + } + let (b, t) = (&base.visibility, &target.visibility); + let visibility = RoleVisibilityPatch { + runs: d(b.runs, t.runs), + schedules: d(b.schedules, t.schedules), + resources: d(b.resources, t.resources), + variables: d(b.variables, t.variables), + assets: d(b.assets, t.assets), + triggers: d(b.triggers, t.triggers), + audit_logs: d(b.audit_logs, t.audit_logs), + groups: d(b.groups, t.groups), + folders: d(b.folders, t.folders), + workers: d(b.workers, t.workers), + }; + RoleCapabilitiesPatch { + code: d(base.code, target.code), + flows: d(base.flows, target.flows), + apps: d(base.apps, target.apps), + manage_schedules: d(base.manage_schedules, target.manage_schedules), + manage_triggers: d(base.manage_triggers, target.manage_triggers), + visibility: (visibility != RoleVisibilityPatch::default()).then_some(visibility), + } +} + +/// One entry of the instance's [`WORKSPACE_ROLES_SETTING`]. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct RoleDefinition { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option<String>, + #[serde(default)] + pub capabilities: RoleCapabilitiesPatch, +} + +/// One entry of `workspace_settings.role_overrides`, keyed by role name. Naming a role the +/// instance does not define adds a workspace-only role. +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] +pub struct RoleOverride { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option<String>, + #[serde(default)] + pub capabilities: RoleCapabilitiesPatch, +} + +pub type RoleOverrides = HashMap<String, RoleOverride>; + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum RoleSource { + Instance, + Workspace, +} + +/// A role as it applies in one workspace. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct EffectiveRole { + pub name: String, + pub label: String, + pub capabilities: RoleCapabilities, + pub source: RoleSource, + /// Whether the workspace overrides this role. + pub overridden: bool, +} + +/// Whether stored instance roles and workspace-only roles apply: on any EE build. A CE build has +/// `developer` and `operator`, which a workspace may still override. +fn custom_roles_built() -> bool { + cfg!(feature = "enterprise") +} + +/// Whether instance roles and workspace-only roles may be changed: an EE build whose license +/// verified. A lapsed license freezes them instead of dropping them, since falling back to the +/// defaults would hand a restricted `developer` everything. The `cfg` is load-bearing: CE's +/// `LICENSE_KEY_VALID` is always `true`. +pub fn custom_roles_enabled() -> bool { + #[cfg(feature = "enterprise")] + { + crate::ee_oss::LICENSE_KEY_VALID.load(std::sync::atomic::Ordering::Relaxed) + } + #[cfg(not(feature = "enterprise"))] + { + false + } +} + +pub fn default_instance_roles() -> Vec<RoleDefinition> { + vec![ + RoleDefinition { + name: DEVELOPER_ROLE.to_string(), + label: Some("Developer".to_string()), + capabilities: RoleCapabilitiesPatch::default(), + }, + RoleDefinition { + name: OPERATOR_ROLE.to_string(), + label: Some("Operator".to_string()), + capabilities: RoleCapabilitiesPatch::default(), + }, + ] +} + +/// Role names appear in `u/`-free contexts only (settings, group mappings, the `usr` row), but are +/// also shown as-is and compared verbatim, so they are kept to a slug. +pub fn validate_role_name(name: &str) -> Result<()> { + let ok = !name.is_empty() + && name.len() <= 50 + && name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-') + && name != "admin"; + if ok { + Ok(()) + } else { + Err(Error::BadRequest(format!( + "invalid role name `{name}`: use 1-50 lowercase letters, digits, `_` or `-`, and not `admin`" + ))) + } +} + +/// Parses and validates a [`WORKSPACE_ROLES_SETTING`] value: at least one role, unique valid +/// names, capabilities that pass [`RoleCapabilities::validate`]. +pub fn parse_instance_roles(value: &serde_json::Value) -> Result<Vec<RoleDefinition>> { + let roles: Vec<RoleDefinition> = serde_json::from_value(value.clone()) + .map_err(|e| Error::BadRequest(format!("invalid workspace roles: {e}")))?; + if roles.is_empty() { + return Err(Error::BadRequest( + "at least one workspace role must be defined".to_string(), + )); + } + let mut seen = std::collections::HashSet::new(); + for r in &roles { + validate_role_name(&r.name)?; + if !seen.insert(r.name.as_str()) { + return Err(Error::BadRequest(format!("duplicate role `{}`", r.name))); + } + let mut caps = RoleCapabilities::base_for(&r.name); + caps.apply(&r.capabilities); + caps.validate(&r.name)?; + } + Ok(roles) +} + +/// The workspace's roles: the instance's, in their order and with any override applied, then the +/// workspace-only ones by name. Order is precedence where one is needed (instance group mapping). +pub fn effective_roles( + instance: &[RoleDefinition], + overrides: &RoleOverrides, +) -> Result<Vec<EffectiveRole>> { + let mut out = Vec::with_capacity(instance.len() + overrides.len()); + for def in instance { + let mut caps = RoleCapabilities::base_for(&def.name); + caps.apply(&def.capabilities); + let ovr = overrides.get(&def.name); + if let Some(o) = ovr { + caps.apply(&o.capabilities); + } + out.push(EffectiveRole { + label: ovr + .and_then(|o| o.label.clone()) + .or_else(|| def.label.clone()) + .unwrap_or_else(|| def.name.clone()), + name: def.name.clone(), + capabilities: caps, + source: RoleSource::Instance, + overridden: ovr.is_some(), + }); + } + if custom_roles_built() { + let mut extra: Vec<_> = overrides + .iter() + .filter(|(n, _)| !instance.iter().any(|d| &d.name == *n)) + .collect(); + extra.sort_by(|a, b| a.0.cmp(b.0)); + for (name, o) in extra { + let mut caps = RoleCapabilities::base_for(name); + caps.apply(&o.capabilities); + out.push(EffectiveRole { + name: name.clone(), + label: o.label.clone().unwrap_or_else(|| name.clone()), + capabilities: caps, + source: RoleSource::Workspace, + overridden: true, + }); + } + } + Ok(out) +} + +/// Validates a workspace's `role_overrides` against the instance roles. +pub fn validate_overrides(instance: &[RoleDefinition], overrides: &RoleOverrides) -> Result<()> { + for name in overrides.keys() { + validate_role_name(name)?; + if !custom_roles_built() && !instance.iter().any(|d| &d.name == name) { + return Err(Error::BadRequest(format!( + "role `{name}` is not defined: adding workspace roles requires Windmill Enterprise Edition" + ))); + } + } + for r in effective_roles(instance, overrides)? { + r.capabilities.validate(&r.name)?; + } + Ok(()) +} + +/// Refuses, while [`custom_roles_enabled`] is false, a `role_overrides` write that adds, edits or +/// relabels a workspace-only role. Removing one, and overriding instance roles, stay allowed. +pub fn check_frozen_overrides( + instance: &[RoleDefinition], + previous: &RoleOverrides, + next: &RoleOverrides, +) -> Result<()> { + if custom_roles_enabled() { + return Ok(()); + } + for (name, o) in next { + if !instance.iter().any(|d| &d.name == name) && previous.get(name) != Some(o) { + return Err(Error::BadRequest(format!( + "changing workspace role `{name}` requires a valid Windmill Enterprise Edition license" + ))); + } + } + Ok(()) +} + +/// The role a member gets when nothing names one (a legacy non-operator payload, an unmapped +/// instance group, an admin's underlying role): `developer` while it is defined, else the first +/// role, since an instance may drop `developer` and `set_workspace_role` refuses unknown names. +pub fn default_role_name<'a>(names: impl IntoIterator<Item = &'a str>) -> String { + let mut first = None; + for name in names { + if name == DEVELOPER_ROLE { + return DEVELOPER_ROLE.to_string(); + } + first.get_or_insert(name); + } + first.unwrap_or(DEVELOPER_ROLE).to_string() +} + +/// The role a `usr` row holds: its `workspace_role`, or the legacy one its `operator` flag names. +pub fn resolve_role_name(workspace_role: Option<String>, operator: bool) -> String { + workspace_role.unwrap_or_else(|| { + if operator { + OPERATOR_ROLE.to_string() + } else { + DEVELOPER_ROLE.to_string() + } + }) +} + +/// SQL for the role a `usr` / `workspace_invite` row aliased `t` holds; mirrors +/// [`resolve_role_name`]. +pub const ROLE_NAME_SQL: &str = + "COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END)"; + +lazy_static::lazy_static! { + static ref INSTANCE_ROLES: Cache<(), (Arc<Vec<RoleDefinition>>, i64)> = Cache::new(1); + static ref WORKSPACE_ROLES: Cache<String, (Arc<Vec<EffectiveRole>>, i64)> = Cache::new(1000); + static ref MEMBER_ROLE: Cache<(String, String), (Option<String>, i64)> = Cache::new(10000); +} + +const ROLE_CACHE_TTL_SECS: i64 = 60; + +/// The instance's role list. A CE build, or an instance that never configured one, has the +/// default roles. Cached 60s, dropped on every replica when the setting changes. +pub async fn instance_roles(db: &DB) -> Result<Arc<Vec<RoleDefinition>>> { + if let Some(roles) = cached_instance_roles() { + return Ok(roles); + } + let mut conn = db.acquire().await?; + instance_roles_on(&mut conn).await +} + +fn cached_instance_roles() -> Option<Arc<Vec<RoleDefinition>>> { + let now = chrono::Utc::now().timestamp(); + INSTANCE_ROLES + .get(&()) + .filter(|(_, expiry)| *expiry > now) + .map(|(r, _)| r) +} + +async fn instance_roles_on(conn: &mut sqlx::PgConnection) -> Result<Arc<Vec<RoleDefinition>>> { + if let Some(roles) = cached_instance_roles() { + return Ok(roles); + } + let roles = if custom_roles_built() { + let stored = sqlx::query_scalar!( + "SELECT value FROM global_settings WHERE name = $1", + WORKSPACE_ROLES_SETTING + ) + .fetch_optional(&mut *conn) + .await?; + match stored { + Some(v) => parse_instance_roles(&v).unwrap_or_else(|e| { + tracing::error!("ignoring invalid {WORKSPACE_ROLES_SETTING} setting: {e:#}"); + default_instance_roles() + }), + None => default_instance_roles(), + } + } else { + default_instance_roles() + }; + let roles = Arc::new(roles); + INSTANCE_ROLES.insert( + (), + ( + roles.clone(), + chrono::Utc::now().timestamp() + ROLE_CACHE_TTL_SECS, + ), + ); + Ok(roles) +} + +pub async fn load_role_overrides<'c, E: sqlx::PgExecutor<'c>>( + db: E, + workspace_id: &str, +) -> Result<RoleOverrides> { + let v: Option<Option<serde_json::Value>> = sqlx::query_scalar!( + "SELECT role_overrides FROM workspace_settings WHERE workspace_id = $1", + workspace_id + ) + .fetch_optional(db) + .await?; + match v.flatten() { + Some(v) => serde_json::from_value(v).map_err(|e| { + Error::internal_err(format!("invalid role overrides of {workspace_id}: {e:#}")) + }), + None => Ok(RoleOverrides::new()), + } +} + +fn cached_workspace_roles(workspace_id: &str) -> Option<Arc<Vec<EffectiveRole>>> { + let now = chrono::Utc::now().timestamp(); + WORKSPACE_ROLES + .get(workspace_id) + .filter(|(_, expiry)| *expiry > now) + .map(|(r, _)| r) +} + +/// The roles of `workspace_id`. Cached 60s; `role_overrides` writes and the instance setting drop +/// the entry on every replica. +/// +/// Call it before opening an RLS transaction: on a cache miss it takes a connection from the root +/// pool, and a second pooled connection held alongside a transaction self-deadlocks on a +/// one-connection pool. A caller that already holds a connection uses [`workspace_roles_on`]. +pub async fn workspace_roles(db: &DB, workspace_id: &str) -> Result<Arc<Vec<EffectiveRole>>> { + if let Some(roles) = cached_workspace_roles(workspace_id) { + return Ok(roles); + } + let mut conn = db.acquire().await?; + workspace_roles_on(&mut conn, workspace_id).await +} + +pub async fn workspace_roles_on( + conn: &mut sqlx::PgConnection, + workspace_id: &str, +) -> Result<Arc<Vec<EffectiveRole>>> { + if let Some(roles) = cached_workspace_roles(workspace_id) { + return Ok(roles); + } + let instance = instance_roles_on(&mut *conn).await?; + let overrides = load_role_overrides(&mut *conn, workspace_id).await?; + let roles = Arc::new(effective_roles(&instance, &overrides)?); + WORKSPACE_ROLES.insert( + workspace_id.to_string(), + ( + roles.clone(), + chrono::Utc::now().timestamp() + ROLE_CACHE_TTL_SECS, + ), + ); + Ok(roles) +} + +pub async fn find_role(db: &DB, workspace_id: &str, name: &str) -> Result<Option<EffectiveRole>> { + Ok(workspace_roles(db, workspace_id) + .await? + .iter() + .find(|r| r.name == name) + .cloned()) +} + +/// Capabilities of role `name` in `workspace_id`; [`RoleCapabilities::NONE`] for a name no longer +/// defined, so a deleted role fails closed. +pub async fn role_capabilities_by_name( + db: &DB, + workspace_id: &str, + name: &str, +) -> Result<RoleCapabilities> { + Ok(find_role(db, workspace_id, name) + .await? + .map(|r| r.capabilities) + .unwrap_or(RoleCapabilities::NONE)) +} + +/// Whether a member holding the role of this `usr` row is restricted: what authentication puts in +/// `ApiAuthed::is_operator`. Runs on the caller's connection, which authentication already holds. +pub async fn member_is_restricted( + conn: &mut sqlx::PgConnection, + workspace_id: &str, + workspace_role: Option<String>, + operator: bool, +) -> Result<bool> { + let name = resolve_role_name(workspace_role, operator); + Ok(workspace_roles_on(conn, workspace_id) + .await? + .iter() + .find(|r| r.name == name) + .map(|r| r.capabilities) + .unwrap_or(RoleCapabilities::NONE) + .is_restricted()) +} + +/// [`member_is_restricted`] for a caller holding no connection. +pub async fn member_is_restricted_db( + db: &DB, + workspace_id: &str, + workspace_role: Option<String>, + operator: bool, +) -> Result<bool> { + let name = resolve_role_name(workspace_role, operator); + Ok(role_capabilities_by_name(db, workspace_id, &name) + .await? + .is_restricted()) +} + +async fn member_role(db: &DB, workspace_id: &str, username: &str) -> Result<Option<String>> { + let now = chrono::Utc::now().timestamp(); + let key = (workspace_id.to_string(), username.to_string()); + if let Some((role, expiry)) = MEMBER_ROLE.get(&key) { + if expiry > now { + return Ok(role); + } + } + let row = sqlx::query!( + "SELECT workspace_role, operator FROM usr WHERE workspace_id = $1 AND username = $2", + workspace_id, + username + ) + .fetch_optional(db) + .await?; + let role = row.map(|r| resolve_role_name(r.workspace_role, r.operator)); + MEMBER_ROLE.insert(key, (role.clone(), now + ROLE_CACHE_TTL_SECS)); + Ok(role) +} + +/// What the caller may do in `workspace_id`. An admin, and any caller authentication did not mark +/// 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`]. +pub async fn caller_capabilities<A: Authable + ?Sized>( + db: &DB, + workspace_id: &str, + authed: &A, +) -> Result<RoleCapabilities> { + if authed.is_admin() || !authed.is_operator() { + return Ok(RoleCapabilities::FULL); + } + match member_role(db, workspace_id, authed.username()).await? { + Some(role) => role_capabilities_by_name(db, workspace_id, &role).await, + None => Ok(RoleCapabilities::NONE), + } +} + +pub fn invalidate_workspace_roles_cache(workspace_id: &str) { + WORKSPACE_ROLES.remove(workspace_id); +} + +pub const ROLE_OVERRIDES_CHANGE_CHANNEL: &str = "notify_role_overrides_change"; + +/// Tells every replica to drop its cached roles for the workspace. Call it in the transaction +/// that writes `role_overrides`: a replica that missed it keeps authorizing whatever the workspace +/// just withdrew until its entry expires. +pub async fn notify_role_overrides_change( + conn: &mut sqlx::PgConnection, + workspace_id: &str, +) -> Result<()> { + sqlx::query("INSERT INTO notify_event (channel, payload) VALUES ($1, $2)") + .bind(ROLE_OVERRIDES_CHANGE_CHANNEL) + .bind(workspace_id) + .execute(conn) + .await?; + Ok(()) +} + +pub fn invalidate_all_roles_cache() { + INSTANCE_ROLES.clear(); + WORKSPACE_ROLES.clear(); + MEMBER_ROLE.clear(); +} + +pub fn invalidate_member_role_cache(workspace_id: &str, username: &str) { + MEMBER_ROLE.remove(&(workspace_id.to_string(), username.to_string())); +} + +/// Refuses removing role `name` while a member, a pending invite, the domain auto-invite or an +/// instance group mapping still names it: in `w_id`, or, for an instance role (`w_id = None`), in +/// any workspace, and while any workspace still overrides it. +pub async fn ensure_role_unused(db: &DB, w_id: Option<&str>, name: &str) -> Result<()> { + let users = sqlx::query_scalar!( + "SELECT COUNT(*) FROM usr t WHERE ($1::text IS NULL OR t.workspace_id = $1) AND + COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END) = $2", + w_id, + name + ) + .fetch_one(db) + .await? + .unwrap_or(0); + let invites = sqlx::query_scalar!( + "SELECT COUNT(*) FROM workspace_invite t WHERE ($1::text IS NULL OR t.workspace_id = $1) AND + COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END) = $2", + w_id, + name + ) + .fetch_one(db) + .await? + .unwrap_or(0); + let settings = sqlx::query_scalar!( + "SELECT COUNT(*) FROM workspace_settings WHERE ($1::text IS NULL OR workspace_id = $1) AND ( + jsonb_typeof(auto_invite) = 'object' AND COALESCE(auto_invite->>'role', + CASE WHEN (auto_invite->>'operator')::boolean THEN 'operator' ELSE 'developer' END) = $2 + OR EXISTS (SELECT 1 FROM jsonb_each_text( + CASE WHEN jsonb_typeof(auto_invite->'instance_groups_roles') = 'object' + THEN auto_invite->'instance_groups_roles' ELSE '{}'::jsonb END) g + WHERE g.value = $2))", + w_id, + name + ) + .fetch_one(db) + .await? + .unwrap_or(0); + if users + invites + settings > 0 { + return Err(Error::BadRequest(format!( + "role `{name}` is still held by {users} member(s) and {invites} pending invite(s), or named by {settings} workspace auto-invite or instance group mapping(s): reassign them first" + ))); + } + // An override left behind would silently re-base onto `base_for` instead of the instance + // definition it was written against. + if w_id.is_none() { + let overriding = sqlx::query_scalar!( + "SELECT COUNT(*) FROM workspace_settings WHERE COALESCE(role_overrides ? $1, false)", + name + ) + .fetch_one(db) + .await? + .unwrap_or(0); + if overriding > 0 { + return Err(Error::BadRequest(format!( + "role `{name}` is overridden in {overriding} workspace(s): remove those overrides first" + ))); + } + } + Ok(()) +} + +/// Checks a write of the `workspace_roles` setting (`None` or null resets to the defaults) before +/// it is stored. Every writer of the setting must call it, the declarative config sync included. +pub async fn validate_instance_roles_write( + db: &DB, + value: Option<&serde_json::Value>, +) -> Result<()> { + let current = instance_roles(db).await?; + let next = match value { + None | Some(serde_json::Value::Null) => default_instance_roles(), + Some(v) => parse_instance_roles(v)?, + }; + // Resetting stays open so a downgraded instance can always drop the setting. + if !custom_roles_enabled() && *current != next && next != default_instance_roles() { + return Err(Error::BadRequest( + "changing workspace roles requires a valid Windmill Enterprise Edition license" + .to_string(), + )); + } + for removed in current + .iter() + .filter(|r| !next.iter().any(|n| n.name == r.name)) + { + ensure_role_unused(db, None, &removed.name).await?; + } + // An override valid on the old definitions can merge into an invalid role on the new ones + // (`flows: full` kept while the instance withdraws `code`), which the gates would honour. + let stored: Vec<(String, serde_json::Value)> = sqlx::query_as( + "SELECT workspace_id, role_overrides FROM workspace_settings WHERE role_overrides IS NOT NULL", + ) + .fetch_all(db) + .await?; + for (w, overrides) in stored { + let overrides: RoleOverrides = serde_json::from_value(overrides) + .map_err(|e| Error::internal_err(format!("invalid role overrides of {w}: {e:#}")))?; + validate_overrides(&next, &overrides).map_err(|e| { + Error::BadRequest(format!( + "workspace {w}'s role overrides would become invalid: {e}" + )) + })?; + } + Ok(()) +} + +/// Side effects of a stored `workspace_roles` write, owed by every writer. The seat table is read +/// by billing on every replica, so it is rebuilt here rather than on the notify that drops the +/// role caches. +pub async fn after_instance_roles_write(db: &DB) -> Result<()> { + invalidate_all_roles_cache(); + let mut tx = db.begin().await?; + sync_role_seats(&mut tx, None).await?; + tx.commit().await?; + Ok(()) +} + +/// Rewrites `role_seat`, the per-role author flag billing SQL joins on, from the current role +/// configuration: the instance rows (`workspace_id = ''`) and those of every workspace with an +/// override, or only `workspace_id`'s when given. Run after any write to either setting; billing +/// reads nothing else about roles. Reads on `tx` only: a second pooled connection held alongside +/// it self-deadlocks on a one-connection pool. +pub async fn sync_role_seats<'c>( + tx: &mut sqlx::Transaction<'c, sqlx::Postgres>, + workspace_id: Option<&str>, +) -> Result<()> { + let instance = instance_roles_on(&mut **tx).await?; + let workspaces: Vec<(String, Option<serde_json::Value>)> = match workspace_id { + Some(w) => sqlx::query_as( + "SELECT $1::text, (SELECT role_overrides FROM workspace_settings WHERE workspace_id = $1)", + ) + .bind(w) + .fetch_all(&mut **tx) + .await?, + None => { + sqlx::query("DELETE FROM role_seat").execute(&mut **tx).await?; + let rows = effective_roles(&instance, &RoleOverrides::new())?; + write_role_seats(tx, "", &rows).await?; + sqlx::query_as( + "SELECT workspace_id, role_overrides FROM workspace_settings WHERE role_overrides IS NOT NULL", + ) + .fetch_all(&mut **tx) + .await? + } + }; + for (w, overrides) in workspaces { + sqlx::query("DELETE FROM role_seat WHERE workspace_id = $1") + .bind(&w) + .execute(&mut **tx) + .await?; + let overrides: RoleOverrides = match overrides { + Some(v) => serde_json::from_value(v).map_err(|e| { + Error::internal_err(format!("invalid role overrides of {w}: {e:#}")) + })?, + None => continue, + }; + let rows: Vec<_> = effective_roles(&instance, &overrides)? + .into_iter() + .filter(|r| r.overridden) + .collect(); + write_role_seats(tx, &w, &rows).await?; + } + Ok(()) +} + +async fn write_role_seats<'c>( + tx: &mut sqlx::Transaction<'c, sqlx::Postgres>, + workspace_id: &str, + roles: &[EffectiveRole], +) -> Result<()> { + let names: Vec<&str> = roles.iter().map(|r| r.name.as_str()).collect(); + let authors: Vec<bool> = roles.iter().map(|r| r.capabilities.is_author()).collect(); + sqlx::query( + "INSERT INTO role_seat (workspace_id, role, author) + SELECT $1, n, a FROM unnest($2::text[], $3::bool[]) AS x(n, a)", + ) + .bind(workspace_id) + .bind(&names) + .bind(&authors) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// SQL for "the membership row aliased `t` consumes a full (author) seat": an admin always does, +/// whatever role it holds underneath; otherwise from `role_seat`, the workspace's row for the role, +/// else the instance's, else the legacy rule that only a developer is an author. `t` carries +/// `workspace_id`, `is_admin`, `operator` and `workspace_role`. Shared by every seat count so the +/// displayed, enforced and invoiced numbers agree. +pub const AUTHOR_SEAT_SQL: &str = "t.is_admin OR COALESCE( + (SELECT rs.author FROM role_seat rs WHERE rs.workspace_id = t.workspace_id + AND rs.role = COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END)), + (SELECT rs.author FROM role_seat rs WHERE rs.workspace_id = '' + AND rs.role = COALESCE(t.workspace_role, CASE WHEN t.operator THEN 'operator' ELSE 'developer' END)), + NOT t.operator)"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_match_legacy_roles() { + let roles = effective_roles(&default_instance_roles(), &RoleOverrides::new()).unwrap(); + assert_eq!(roles[0].capabilities, RoleCapabilities::FULL); + assert!(!roles[0].capabilities.is_restricted()); + assert_eq!(roles[1].capabilities, RoleCapabilities::OPERATOR); + assert!(roles[1].capabilities.is_restricted()); + assert!(!roles[1].capabilities.is_author()); + + let hidden_page = RoleCapabilities { + visibility: RoleVisibility { workers: false, ..RoleVisibility::ALL }, + ..RoleCapabilities::FULL + }; + assert!(!hidden_page.is_restricted()); + } + + #[test] + fn override_layers_over_instance_definition() { + let instance: Vec<RoleDefinition> = serde_json::from_value(serde_json::json!([ + {"name": "developer"}, + {"name": "operator", "capabilities": {"manage_triggers": false, "visibility": {"runs": false}}} + ])) + .unwrap(); + let overrides: RoleOverrides = serde_json::from_value(serde_json::json!({ + "operator": {"capabilities": {"flows": "compose", "visibility": {"workers": false}}} + })) + .unwrap(); + let op = effective_roles(&instance, &overrides).unwrap().remove(1); + assert!(op.overridden); + assert_eq!(op.capabilities.flows, AuthorLevel::Compose); + assert!(!op.capabilities.manage_triggers); + assert!(!op.capabilities.visibility.runs); + assert!(!op.capabilities.visibility.workers); + assert!(op.capabilities.visibility.folders); + assert!(op.capabilities.is_author()); + } + + #[test] + fn full_authoring_requires_code() { + let err = parse_instance_roles(&serde_json::json!([ + {"name": "builder", "capabilities": {"flows": "full"}} + ])); + assert!(err.is_err()); + assert!(parse_instance_roles(&serde_json::json!([])).is_err()); + assert!(parse_instance_roles(&serde_json::json!([{"name": "admin"}])).is_err()); + } +} diff --git a/backend/windmill-common/src/secret_backend/database.rs b/backend/windmill-common/src/secret_backend/database.rs index b450cc7e15..903ea85e24 100644 --- a/backend/windmill-common/src/secret_backend/database.rs +++ b/backend/windmill-common/src/secret_backend/database.rs @@ -39,7 +39,7 @@ impl DatabaseBackend { impl SecretBackend for DatabaseBackend { async fn get_secret(&self, workspace_id: &str, path: &str) -> Result<String> { let variable = sqlx::query!( - "SELECT value FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", + "SELECT value::text AS \"value!\" FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", path, workspace_id ) diff --git a/backend/windmill-common/src/users.rs b/backend/windmill-common/src/users.rs index 1b696746b0..277a2632f8 100644 --- a/backend/windmill-common/src/users.rs +++ b/backend/windmill-common/src/users.rs @@ -379,44 +379,54 @@ async fn get_email_from_permissioned_as_inner<'c>( } } -/// Compute the highest-precedence workspace role for a user across all their instance groups. +/// The highest-precedence workspace role a user holds across their instance groups. /// -/// Precedence: admin (3) > developer (2) > operator (1). -/// Returns `(best_group_name, is_admin, is_operator)`. +/// `admin` ranks first, then the workspace's roles in `role_order` (earlier is higher). A group +/// with no mapped role grants `roles::default_role_name`; a role name not in `role_order` ranks +/// last. Returns `(best_group_name, is_admin, role)`, where `role` is the role the membership +/// holds and, for an admin, the one it keeps under the admin flag. pub fn compute_highest_workspace_role( user_igroups: &[String], ws_configured_groups: &[String], ws_roles: &std::collections::HashMap<String, String>, -) -> (String, bool, bool) { - let mut best_group = String::new(); - let mut best_precedence = 0u8; + role_order: &[String], +) -> (String, bool, String) { + let rank = |role: &str| -> usize { + if role == "admin" { + 0 + } else { + 1 + role_order + .iter() + .position(|r| r == role) + .unwrap_or(role_order.len()) + } + }; + let default_role = crate::roles::default_role_name(role_order.iter().map(String::as_str)); + let role_of = |group: &str| -> String { + ws_roles + .get(group) + .cloned() + .unwrap_or_else(|| default_role.clone()) + }; + let mut best: Option<(usize, String)> = None; for group in user_igroups { if !ws_configured_groups.contains(group) { continue; } - let default_role = "developer".to_string(); - let role = ws_roles.get(group).unwrap_or(&default_role); - let precedence = match role.as_str() { - "admin" => 3u8, - "operator" => 1, - _ => 2, - }; - if precedence > best_precedence { - best_precedence = precedence; - best_group = group.clone(); + let r = rank(&role_of(group)); + if best.as_ref().map_or(true, |(b, _)| r < *b) { + best = Some((r, group.clone())); } } - let default_role = "developer".to_string(); - let best_role_str = ws_roles.get(&best_group).unwrap_or(&default_role); - let (is_admin, is_operator) = match best_role_str.as_str() { - "admin" => (true, false), - "operator" => (false, true), - _ => (false, false), - }; - - (best_group, is_admin, is_operator) + let best_group = best.map(|(_, g)| g).unwrap_or_default(); + let role = role_of(&best_group); + if role == "admin" { + (best_group, true, default_role) + } else { + (best_group, false, role) + } } pub fn truncate_token(token: &str) -> String { @@ -478,62 +488,46 @@ mod tests { } } - #[test] - fn test_compute_highest_workspace_role_admin_wins() { - let user_groups = vec!["ops".to_string(), "admins".to_string()]; - let ws_groups = vec!["ops".to_string(), "admins".to_string()]; - let mut roles = std::collections::HashMap::new(); - roles.insert("ops".to_string(), "operator".to_string()); - roles.insert("admins".to_string(), "admin".to_string()); - - let (group, is_admin, is_operator) = - compute_highest_workspace_role(&user_groups, &ws_groups, &roles); - assert_eq!(group, "admins"); - assert!(is_admin); - assert!(!is_operator); + fn order() -> Vec<String> { + vec![ + "developer".to_string(), + "builder".to_string(), + "operator".to_string(), + ] } #[test] - fn test_compute_highest_workspace_role_developer_over_operator() { - let user_groups = vec!["devs".to_string(), "ops".to_string()]; - let ws_groups = vec!["devs".to_string(), "ops".to_string()]; + fn test_compute_highest_workspace_role_follows_role_order() { + let user_groups = vec!["ops".to_string(), "builders".to_string()]; + let ws_groups = user_groups.clone(); let mut roles = std::collections::HashMap::new(); - roles.insert("devs".to_string(), "developer".to_string()); roles.insert("ops".to_string(), "operator".to_string()); + roles.insert("builders".to_string(), "builder".to_string()); + assert_eq!( + compute_highest_workspace_role(&user_groups, &ws_groups, &roles, &order()), + ("builders".to_string(), false, "builder".to_string()) + ); - let (group, is_admin, is_operator) = - compute_highest_workspace_role(&user_groups, &ws_groups, &roles); - assert_eq!(group, "devs"); - assert!(!is_admin); - assert!(!is_operator); + roles.insert("ops".to_string(), "admin".to_string()); + assert_eq!( + compute_highest_workspace_role(&user_groups, &ws_groups, &roles, &order()), + ("ops".to_string(), true, "developer".to_string()) + ); } #[test] - fn test_compute_highest_workspace_role_skips_unconfigured_groups() { - let user_groups = vec!["admins".to_string(), "other".to_string()]; - let ws_groups = vec!["ops".to_string()]; // admins not configured for this workspace - let mut roles = std::collections::HashMap::new(); - roles.insert("admins".to_string(), "admin".to_string()); - roles.insert("ops".to_string(), "operator".to_string()); - - let (group, is_admin, is_operator) = - compute_highest_workspace_role(&user_groups, &ws_groups, &roles); - // No user groups match ws_configured_groups, so best_group stays empty - assert_eq!(group, ""); - assert!(!is_admin); - assert!(!is_operator); - } - - #[test] - fn test_compute_highest_workspace_role_defaults_to_developer() { - let user_groups = vec!["team".to_string()]; + fn test_compute_highest_workspace_role_unmapped_group_is_developer() { + let user_groups = vec!["team".to_string(), "other".to_string()]; let ws_groups = vec!["team".to_string()]; - let roles = std::collections::HashMap::new(); // no role configured → developer - - let (group, is_admin, is_operator) = - compute_highest_workspace_role(&user_groups, &ws_groups, &roles); - assert_eq!(group, "team"); - assert!(!is_admin); - assert!(!is_operator); + assert_eq!( + compute_highest_workspace_role(&user_groups, &ws_groups, &Default::default(), &order()), + ("team".to_string(), false, "developer".to_string()) + ); + // An instance that dropped `developer` falls back to its first role. + let no_dev = vec!["builder".to_string(), "operator".to_string()]; + assert_eq!( + compute_highest_workspace_role(&user_groups, &ws_groups, &Default::default(), &no_dev), + ("team".to_string(), false, "builder".to_string()) + ); } } diff --git a/backend/windmill-common/src/utils.rs b/backend/windmill-common/src/utils.rs index c034edc203..074469893d 100644 --- a/backend/windmill-common/src/utils.rs +++ b/backend/windmill-common/src/utils.rs @@ -286,6 +286,13 @@ pub fn sanitize_db_error(e: sqlx::Error) -> Error { Some("23514") if db_err.constraint() == Some("variable_value_length") => { Error::BadRequest("A field exceeds its maximum length".to_string()) } + Some("23514") if db_err.constraint() == Some("variable_oauth_no_value_expiry") => { + Error::BadRequest( + "A variable linked to an OAuth account cannot have a value expiry: Windmill \ + refreshes its token" + .to_string(), + ) + } // check_violation — `proper_id` / `proper_name` and friends Some("23514") => Error::BadRequest( "Invalid path or name: it does not match the required format".to_string(), diff --git a/backend/windmill-common/src/variables.rs b/backend/windmill-common/src/variables.rs index f3ad826136..f3ee17769b 100644 --- a/backend/windmill-common/src/variables.rs +++ b/backend/windmill-common/src/variables.rs @@ -10,21 +10,23 @@ use crate::db::{Authable, UserDB}; use crate::error::{self, Error}; use crate::scripts::ScriptHash; use crate::secret_backend::{get_secret_value, is_external_stored_value}; -use crate::utils::WarnAfterExt; -use crate::worker::Connection; +use crate::utils::{strip_json_nul, WarnAfterExt}; +use crate::worker::{to_raw_value, Connection}; use crate::workspace_crypt::CipherFormat; pub use crate::workspace_crypt::WorkspaceCrypt; use crate::{worker::WORKER_GROUP, BASE_URL, DB}; use chrono::{SecondsFormat, Utc}; use quick_cache::sync::Cache; use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; lazy_static::lazy_static! { pub static ref SECRET_SALT: Option<String> = std::env::var("SECRET_SALT").ok(); static ref RESERVED_WM_VAR_NAME: regex::Regex = regex::Regex::new(r"^WM_[A-Z_]+$").unwrap(); static ref RE_RES_VAR: regex::Regex = - regex::Regex::new(r#"\$(?:var|jsonvar|res|encrypted)\:"#).unwrap(); + regex::Regex::new(r#"\$(var|jsonvar|res|encrypted)\:"#).unwrap(); } /// Whether a job argument, as JSON text, holds a `$var:`/`$jsonvar:`/`$res:`/`$encrypted:` @@ -34,6 +36,106 @@ pub fn arg_needs_interpolation(json: &str) -> bool { RE_RES_VAR.is_match(json) } +/// Whether the worker would interpolate `arg`, which an untrusted user controls on a job that +/// runs as someone else; `true` for one that cannot be read and may hold a reference. +pub fn untrusted_arg_interpolates(arg: &str) -> bool { + may_reference(arg) && decoded(arg).map_or(true, |v| interpolates(&v)) +} + +/// `args`, which an untrusted user controls on a job that runs as someone else, with every one the +/// worker would interpolate rewritten so it no longer is. The others keep their exact text. +pub fn omit_untrusted_interpolation( + args: HashMap<String, Box<RawValue>>, + resource_omitted: &str, +) -> HashMap<String, Box<RawValue>> { + args.into_iter() + .map(|(k, v)| { + if !may_reference(v.get()) { + return (k, v); + } + let v = match decoded(v.get()) { + Some(d) if !interpolates(&d) => v, + Some(mut d) => { + omit(&mut d, resource_omitted); + to_raw_value(&d) + } + None => to_raw_value( + &"This argument has been omitted for security reasons: it could not be checked", + ), + }; + (k, v) + }) + .collect() +} + +/// Without a `$`, spelled out or escaped, an argument holds no reference however jsonb rewrites +/// it, so it needs no decoding, even one serde_json cannot read. +fn may_reference(arg: &str) -> bool { + arg.contains('$') || arg.contains("\\u") +} + +/// `arg` as its jsonb column will hold it: the NUL stripped as `push` strips it, escapes decoded, +/// the last copy of a duplicate key kept. `None` for what serde_json cannot read, which jsonb may +/// still store (`1e400`). +fn decoded(arg: &str) -> Option<serde_json::Value> { + serde_json::from_str(&strip_json_nul(arg)).ok() +} + +/// The worker's own test on the whole argument, plus a reserved `WM_*` key or value at any depth, +/// which a flow step can move into an argument the worker interpolates. A workspace or worker env +/// var name moved that way is still resolved: those names are not known on every path. +fn interpolates(v: &serde_json::Value) -> bool { + fn reserved_name(v: &serde_json::Value) -> bool { + match v { + serde_json::Value::String(s) => reserved(s).is_some(), + serde_json::Value::Array(a) => a.iter().any(reserved_name), + serde_json::Value::Object(m) => m + .iter() + .any(|(k, v)| reserved(k).is_some() || reserved_name(v)), + _ => false, + } + } + arg_needs_interpolation(&v.to_string()) || reserved_name(v) +} + +/// Keys included, since the worker's test reads them too. +fn omit(v: &mut serde_json::Value, resource_omitted: &str) { + match v { + serde_json::Value::String(s) => *s = omitted(s, resource_omitted), + serde_json::Value::Array(a) => a.iter_mut().for_each(|v| omit(v, resource_omitted)), + serde_json::Value::Object(m) => { + *m = std::mem::take(m) + .into_iter() + .map(|(k, mut v)| { + omit(&mut v, resource_omitted); + (omitted(&k, resource_omitted), v) + }) + .collect() + } + _ => {} + } +} + +/// The reserved variable a whole `$WM_*` value names, which the worker replaces with its value. +fn reserved(s: &str) -> Option<&str> { + s.strip_prefix('$') + .filter(|n| RESERVED_WM_VAR_NAME.is_match(n)) +} + +fn omitted(s: &str, resource_omitted: &str) -> String { + let variable = "The following variable has been omitted for security reasons: "; + if let Some(n) = reserved(s) { + return format!("{variable}{n}"); + } + RE_RES_VAR + .replace_all(s, |c: ®ex::Captures| match &c[1] { + "res" => resource_omitted, + "encrypted" => "The following encrypted value has been omitted for security reasons: ", + _ => variable, + }) + .into_owned() +} + /// Escape a string so it can be safely embedded inside a single-quoted JS /// string literal in a generated NativeTS/Bun prologue. pub fn escape_js_single_quoted(s: &str) -> String { @@ -158,6 +260,7 @@ pub struct ListableVariable { pub refresh_error: Option<String>, pub is_linked: Option<bool>, pub expires_at: Option<chrono::DateTime<Utc>>, + pub value_valid_until: Option<chrono::DateTime<Utc>>, #[serde(skip_serializing_if = "Option::is_none")] pub labels: Option<Vec<String>>, /// Labels inherited from the parent folder, computed at read time. @@ -200,6 +303,8 @@ pub struct ExportableListableVariable { #[serde(skip_serializing_if = "Option::is_none")] pub expires_at: Option<chrono::DateTime<Utc>>, #[serde(skip_serializing_if = "Option::is_none")] + pub value_valid_until: Option<chrono::DateTime<Utc>>, + #[serde(skip_serializing_if = "Option::is_none")] pub labels: Option<Vec<String>>, } @@ -215,7 +320,11 @@ pub struct CreateVariable { pub description: String, pub account: Option<i32>, pub is_oauth: Option<bool>, + /// When the row itself is garbage-collected. pub expires_at: Option<chrono::DateTime<Utc>>, + /// When the value stops working. Drives the workspace's variable expiration handler; + /// never deletes the row. + pub value_valid_until: Option<chrono::DateTime<Utc>>, #[serde(default)] pub labels: Option<Vec<String>>, #[serde(default)] @@ -297,9 +406,14 @@ pub async fn generate_approval_token( job_id: uuid::Uuid, db: &DB, ) -> crate::error::Result<String> { + let key = get_workspace_key(w_id, db).await?; + approval_token_from_key(&key, job_id) +} + +/// The token [`generate_approval_token`] mints, from a workspace key already in hand. +pub fn approval_token_from_key(key: &str, job_id: uuid::Uuid) -> crate::error::Result<String> { use hmac::{Hmac, Mac}; use sha2::Sha256; - let key = get_workspace_key(w_id, db).await?; let mut mac = Hmac::<Sha256>::new_from_slice(key.as_bytes()) .map_err(|e| crate::Error::internal_err(format!("HMAC key error: {e}")))?; mac.update(job_id.as_bytes()); @@ -344,7 +458,7 @@ pub async fn get_secret_value_as_admin( path: &str, ) -> crate::error::Result<String> { let variable_o = sqlx::query!( - "SELECT value, is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", path, w_id + "SELECT value::text AS \"value!\", is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", path, w_id ) .fetch_optional(db) .await?; @@ -358,28 +472,32 @@ pub async fn get_secret_value_as_admin( ))); }; - let r = if variable.is_secret { - let value = variable.value; - if !value.is_empty() { - if is_external_stored_value(&value) { - get_secret_value(db, w_id, &variable.path, &value).await? - } else { - let mc = build_crypt(db, w_id).await?; - decrypt(&mc, value).map_err(|e| { - crate::error::Error::internal_err(format!( - "Error decrypting variable {}: {}", - variable.path, e - )) - })? - } - } else { - "".to_string() - } + if variable.is_secret { + decrypt_secret_value(db, w_id, &variable.path, variable.value).await } else { - variable.value - }; + Ok(variable.value) + } +} - Ok(r) +/// Plaintext of a secret variable's stored `value`, read from the external secret backend when it +/// holds a reference to one. Bypasses variable permissions: callers MUST have authorized the +/// reader before returning the plaintext to them. +pub async fn decrypt_secret_value( + db: &DB, + w_id: &str, + path: &str, + value: String, +) -> crate::error::Result<String> { + if value.is_empty() { + Ok(value) + } else if is_external_stored_value(&value) { + get_secret_value(db, w_id, path, &value).await + } else { + let mc = build_crypt(db, w_id).await?; + decrypt(&mc, value).map_err(|e| { + crate::error::Error::internal_err(format!("Error decrypting variable {}: {}", path, e)) + }) + } } /// Marks a workspace setting's secret written into the settings document encrypted with the @@ -431,9 +549,8 @@ pub fn variable_value_widen_pending() -> bool { /// Widen `variable.value` to [`VARIABLE_VALUE_WIDTH`], or `false` when it is too early to. /// Not a migration: changing a column's type, even its length, fails every statement a live -/// process prepared on it until its connection closes. It waits for v2 writes, gated on a -/// worker version that retires such connections on the first failure, so that no process too -/// old to recover is still running. +/// process prepared on it until its connection closes. It waits until no process returns the +/// column uncast. Any new query returning `variable.value` must select `value::text`. async fn widen_variable_value(db: &DB) -> error::Result<bool> { if VARIABLE_VALUE_WIDENED.load(Ordering::Relaxed) { return Ok(true); @@ -445,7 +562,9 @@ async fn widen_variable_value(db: &DB) -> error::Result<bool> { .fetch_one(db) .await?; if typmod >= 0 && typmod - 4 < VARIABLE_VALUE_WIDTH { - if crate::db::process_uptime() < crate::db::PREVIOUS_RELEASE_ROLLOUT_UPTIME { + if !crate::min_version::MIN_VERSION_SUPPORTS_VARIABLE_VALUE_WIDENING.met_conservatively() + || crate::db::process_uptime() < crate::db::PREVIOUS_RELEASE_ROLLOUT_UPTIME + { return Ok(false); } tracing::info!("widening variable.value to VARCHAR({VARIABLE_VALUE_WIDTH})"); @@ -558,7 +677,7 @@ async fn upgrade_workspace_secret_variables(db: &DB, w_id: &str) -> error::Resul }; let mc = crypt_from_key_with_suffix(&key, ""); let rows: Vec<(String, String)> = sqlx::query_as( - "SELECT path, value FROM variable WHERE workspace_id = $1 AND is_secret AND path > $2 \ + "SELECT path, value::text FROM variable WHERE workspace_id = $1 AND is_secret AND path > $2 \ ORDER BY path LIMIT $3", ) .bind(w_id) @@ -898,7 +1017,7 @@ pub async fn get_variable_or_self( let path = path.strip_prefix("$var:").unwrap().to_string(); let record = sqlx::query!( - "SELECT value, is_secret + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", &path, @@ -946,7 +1065,7 @@ pub async fn get_variable_or_self_as<T: Authable + Sync>( // Use an RLS-scoped transaction so the query respects row-level security let mut tx = user_db.clone().begin(authed).await?; let record = sqlx::query!( - "SELECT value, is_secret + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", &var_path, @@ -981,9 +1100,48 @@ pub async fn get_variable_or_self_as<T: Authable + Sync>( #[cfg(test)] mod tests { use super::{ - can_bind_as_prologue_const, decrypt, escape_js_single_quoted, is_valid_js_identifier, - DECRYPT_FAILED, + arg_needs_interpolation, can_bind_as_prologue_const, decrypt, escape_js_single_quoted, + is_valid_js_identifier, omit_untrusted_interpolation, DECRYPT_FAILED, }; + + #[test] + fn omits_every_argument_the_worker_would_interpolate() { + let omit = |s: &str| { + let arg = serde_json::value::RawValue::from_string(s.to_string()).unwrap(); + omit_untrusted_interpolation( + [("a".to_string(), arg)].into(), + "The following resource has been omitted for security reasons: ", + )["a"] + .get() + .to_string() + }; + for kept in [ + r#"{"$match": {"c": "$USD", "_id": "$category"}, "p": 1.10, "id": 18446744073709551617}"#, + r#""$10.00""#, + r#""$WM_TOKEN ""#, + ] { + assert_eq!(omit(kept), kept); + } + for hit in [ + r#""$var:u/a/s""#, + r#""\u0024res:u/a/r""#, + r#"{"key": "$API_KEY", "note": "cost $var:x"}"#, + r#"{"$encrypted:abc": 1}"#, + r#"["$WM_TOKEN"]"#, + r#"{"$WM_TOKEN": 1}"#, + r#""$va\u0000r:x""#, + r#"{"a": "ok", "a": "\u0024jsonvar:x"}"#, + ] { + let out = omit(hit); + assert!( + !arg_needs_interpolation(&out) && !out.contains("$WM_"), + "{hit}: {out}" + ); + assert!(out.contains("omitted for security reasons"), "{hit}: {out}"); + } + assert!(omit(r#"{"n": 1e400, "r": "$var:x"}"#).contains("could not be checked")); + assert_eq!(omit(r#"{"n": 1e400}"#), r#"{"n": 1e400}"#); + } use crate::error::Error; use crate::workspace_crypt::WorkspaceCrypt; use base64::Engine; diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index 41d437c30a..e6a44054d9 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -484,6 +484,7 @@ lazy_static::lazy_static! { additional_python_paths: Default::default(), pip_local_dependencies: Default::default(), env_vars: Default::default(), + disable_job_proxy: false, native_mode: false, object_store_cache_config: Default::default(), paused: false, @@ -2767,6 +2768,7 @@ pub async fn load_worker_config( .additional_python_paths .or_else(|| load_additional_python_paths_from_env()), env_vars: resolved_env_vars, + disable_job_proxy: config.disable_job_proxy.unwrap_or(false), native_mode, object_store_cache_config: config.object_store_cache_config, paused: config.paused.unwrap_or(false), @@ -2945,6 +2947,7 @@ pub struct WorkerConfigOpt { pub pip_local_dependencies: Option<Vec<String>>, pub env_vars_static: Option<HashMap<String, String>>, pub env_vars_allowlist: Option<Vec<String>>, + pub disable_job_proxy: Option<bool>, pub native_mode: Option<bool>, pub object_store_cache_config: Option<serde_json::Value>, pub paused: Option<bool>, @@ -2966,6 +2969,7 @@ impl Default for WorkerConfigOpt { pip_local_dependencies: Default::default(), env_vars_static: Default::default(), env_vars_allowlist: Default::default(), + disable_job_proxy: Default::default(), native_mode: Default::default(), object_store_cache_config: Default::default(), paused: Default::default(), @@ -2987,6 +2991,8 @@ pub struct WorkerConfig { pub additional_python_paths: Option<Vec<String>>, pub pip_local_dependencies: Option<Vec<String>>, pub env_vars: HashMap<String, String>, + /// Job runs get none of the worker's `HTTP(S)_PROXY`/`NO_PROXY`; dependency installs keep them. + pub disable_job_proxy: bool, pub native_mode: bool, /// Object store this group's dependency cache uses instead of the instance one, as stored /// in the group config. Raw JSON: `windmill-common` cannot depend on the object store crate @@ -2999,8 +3005,8 @@ pub struct WorkerConfig { 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: {:?}, 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.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: {:?}, 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, // holds bucket credentials self.object_store_cache_config.as_ref().map(|_| "***").unwrap_or("None")) } diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index 1b9412eb5a..9132c51950 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -7,8 +7,10 @@ use strum::AsRefStr; use crate::{ datatable_roles::{ADMIN_DATATABLE_ROLE, CUSTOM_INSTANCE_USER}, + db::Authable, error::{self, to_anyhow, Error, Result}, get_database_url, + roles::{caller_capabilities, AuthorLevel, RoleCapabilities}, secret_backend::{get_secret_value, is_external_stored_value}, utils::{get_custom_pg_instance_password, get_custom_pg_instance_replication_password}, variables::{build_crypt, decrypt}, @@ -1060,9 +1062,9 @@ pub async fn guest_app_admits<'c, E: sqlx::Executor<'c, Database = sqlx::Postgre } /// Billable members of `w_id` and the seats they cost, as -/// `ceil(developers + (operators + service_accounts)/2)`. A service account is half a seat whatever -/// its role; a disabled member is not billed. In a workspace that granted operators builder rights, -/// every operator counts as a developer. +/// `ceil(authors + (non_authors + service_accounts)/2)`. A service account is half a seat whatever +/// its role; a disabled member is not billed. A member is an author when its role writes or +/// composes scripts, flows or apps (`crate::roles::AUTHOR_SEAT_SQL`). /// /// The workspace is invoiced by a job outside this codebase that counts the same rows with its own /// SQL. The two must be changed together: this rule disagreeing with that one is what bills a @@ -1071,28 +1073,23 @@ pub async fn guest_app_admits<'c, E: sqlx::Executor<'c, Database = sqlx::Postgre /// Unauthenticated metering helper: reads member counts for any `w_id`, so callers must already be /// authorized for that workspace (or run in trusted server-side code). pub async fn billable_seats(db: &crate::DB, w_id: &str) -> Result<BillableSeats> { - let row = sqlx::query!( - r#"SELECT - COUNT(*) FILTER (WHERE NOT operator AND NOT disabled AND NOT is_service_account) AS "developers!", - COUNT(*) FILTER (WHERE operator AND NOT disabled AND NOT is_service_account) AS "operators!", - COUNT(*) FILTER (WHERE is_service_account AND NOT disabled) AS "service_accounts!" - FROM usr WHERE workspace_id = $1"#, - w_id - ) + let (developers, operators, service_accounts): (i64, i64, i64) = sqlx::query_as(&format!( + "SELECT + COUNT(*) FILTER (WHERE ({author}) AND NOT disabled AND NOT is_service_account), + COUNT(*) FILTER (WHERE NOT ({author}) AND NOT disabled AND NOT is_service_account), + COUNT(*) FILTER (WHERE is_service_account AND NOT disabled) + FROM usr t WHERE workspace_id = $1", + author = crate::roles::AUTHOR_SEAT_SQL + )) + .bind(w_id) .fetch_one(db) .await .map_err(|e| Error::internal_err(format!("counting billable seats of {w_id}: {e:#}")))?; - let (developers, operators) = if operator_builder_rights(db, w_id).await?.any() { - (row.developers + row.operators, 0) - } else { - (row.developers, row.operators) - }; Ok(BillableSeats { developers, operators, - service_accounts: row.service_accounts, - seats: ((developers as f64) + 0.5 * ((operators + row.service_accounts) as f64)).ceil() - as i64, + service_accounts, + seats: ((developers as f64) + 0.5 * ((operators + service_accounts) as f64)).ceil() as i64, }) } @@ -1212,25 +1209,10 @@ pub fn invalidate_protection_rules_cache(workspace_id: &str) { PROTECTION_RULES_CACHE.remove(workspace_id); } -// Operator rights cache +// Role rights. What a restricted caller may author or manage comes from its role; see +// `crate::roles`. The gates below keep the operator vocabulary of the call sites that predate roles. -lazy_static::lazy_static! { - static ref OPERATOR_RIGHTS_CACHE: Cache<String, (OperatorRights, i64)> = Cache::new(1000); -} - -/// Every operator right of a workspace, read and cached together because they share one -/// `operator_settings` column and one invalidation. The two groups have opposite polarity: -/// the builder rights are granted on request and cost a seat, the `manage` rights are held by -/// default and cost nothing. -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] -pub struct OperatorRights { - pub builder: OperatorBuilderRights, - pub manage: OperatorManageRights, -} - -/// The two things a workspace can let its operators compose. Granted independently: composing a -/// flow is fully checked server-side, while a full-code app is a browser-built bundle no check can -/// read, so an admin may reasonably want the first without the second. +/// What a caller may compose or author, per kind, at least at the `Compose` level. #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct OperatorBuilderRights { pub flows: bool, @@ -1238,8 +1220,8 @@ pub struct OperatorBuilderRights { } /// Which capability a gate needs. Naming a kind at each call site is what keeps the two rights -/// from collapsing back into one: a gate that takes "either" authorizes an app write on a -/// flows-only workspace. +/// from collapsing back into one: a gate that takes "either" authorizes an app write for a role +/// that may only compose flows. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum BuilderKind { Flows, @@ -1247,8 +1229,8 @@ pub enum BuilderKind { } impl OperatorBuilderRights { - /// Whether either right is granted. Only for surfaces that are genuinely not per-kind: the - /// seat a membership costs, and listing drafts. + /// Whether either right is granted. Only for surfaces that are genuinely not per-kind, such + /// as listing drafts. pub fn any(&self) -> bool { self.flows || self.apps } @@ -1259,23 +1241,9 @@ impl OperatorBuilderRights { BuilderKind::Apps => self.apps, } } -} -/// Writes an operator may perform unless the workspace withdraws them. Unlike the visibility -/// flags beside them in `operator_settings`, these are enforced; unlike a right a workspace -/// grants, they are held by default and cost no seat. -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct OperatorManageRights { - pub schedules: bool, - pub triggers: bool, -} - -/// Granted unless explicitly withdrawn. Every path that materializes these rights without a -/// stored setting - a workspace with no `workspace_settings` row included - has to land here, or -/// an upgrade silently revokes what operators could do the day before. -impl Default for OperatorManageRights { - fn default() -> Self { - Self { schedules: true, triggers: true } + pub fn from_capabilities(caps: &RoleCapabilities) -> Self { + Self { flows: caps.flows != AuthorLevel::None, apps: caps.apps != AuthorLevel::None } } } @@ -1306,77 +1274,25 @@ impl ManageKind { } } -impl OperatorManageRights { - pub fn has(&self, kind: ManageKind) -> bool { - match kind { - ManageKind::Schedules => self.schedules, - ManageKind::Triggers => self.triggers, - } - } -} - -/// What operators of this workspace may still write. Per workspace, not per user. -/// -/// Read on every gated write, so it is cached with a 60s TTL. This gates writes, so a withdrawal -/// cannot wait out that TTL on the rest of the fleet: an `AFTER UPDATE OF operator_settings` -/// trigger publishes `notify_operator_settings_change` and every server drops its entry through -/// `process_notify_event`. [`invalidate_operator_rights_cache`] is the local half of that, and -/// what a test flipping the setting directly has to call itself. -/// -/// Call it before opening an RLS transaction: it takes a connection from the root pool, and a -/// second pooled connection held alongside a transaction self-deadlocks on a one-connection pool. -async fn operator_rights(db: &DB, workspace_id: &str) -> Result<OperatorRights> { - let now = chrono::Utc::now().timestamp(); - - if let Some((rights, expiry)) = OPERATOR_RIGHTS_CACHE.get(workspace_id) { - if expiry > now { - return Ok(rights); - } - } - - // The builder key defaults to false, a right the workspace has to grant; the manage keys to - // true, rights it has to withdraw. An absent key means "never configured" for both, so the - // defaults have to differ here rather than at the call sites. - let row = sqlx::query!( - "SELECT COALESCE((operator_settings->>'builder_flows')::boolean, false) AS \"flows!\", - COALESCE((operator_settings->>'builder_apps')::boolean, false) AS \"apps!\", - COALESCE((operator_settings->>'manage_schedules')::boolean, true) AS \"schedules!\", - COALESCE((operator_settings->>'manage_triggers')::boolean, true) AS \"triggers!\" - FROM workspace_settings WHERE workspace_id = $1", - workspace_id - ) - .fetch_optional(db) - .await - .map_err(|e| { - Error::internal_err(format!( - "Failed to fetch operator settings for {workspace_id}: {e:#}" - )) - })?; - - let rights = row - .map(|r| OperatorRights { - builder: OperatorBuilderRights { flows: r.flows, apps: r.apps }, - manage: OperatorManageRights { schedules: r.schedules, triggers: r.triggers }, - }) - .unwrap_or_default(); - - OPERATOR_RIGHTS_CACHE.insert(workspace_id.to_string(), (rights, now + 60)); - - Ok(rights) -} - -/// What operators of this workspace may compose out of already-deployed runnables. Per workspace, -/// not per user: every operator gets whatever is granted, and consumes a full seat for it. -pub async fn operator_builder_rights(db: &DB, workspace_id: &str) -> Result<OperatorBuilderRights> { - Ok(operator_rights(db, workspace_id).await?.builder) -} - -/// Whether operators of this workspace may save a draft of `kind`: one they could deploy. A -/// resource or variable always, since their routes do not gate operators; a flow or full-code app -/// under its builder right, a schedule or trigger under the matching manage right; nothing else. -pub async fn operator_can_draft( +/// What the caller may compose or author, per kind. Everything for an unrestricted caller. +pub async fn operator_builder_rights<A: Authable + ?Sized>( db: &DB, workspace_id: &str, + authed: &A, +) -> Result<OperatorBuilderRights> { + Ok(OperatorBuilderRights::from_capabilities( + &caller_capabilities(db, workspace_id, authed).await?, + )) +} + +/// Whether the caller may save a draft of `kind`: one they could deploy. A resource or variable +/// always, since their routes do not gate roles; a flow or full-code app at the `Compose` level or +/// above, a low-code app at `Full`, a schedule or trigger under the matching manage right, a +/// script or data pipeline with `code`. +pub async fn operator_can_draft<A: Authable + ?Sized>( + db: &DB, + workspace_id: &str, + authed: &A, kind: crate::user_drafts::UserDraftItemKind, ) -> Result<bool> { use crate::user_drafts::UserDraftItemKind; @@ -1386,64 +1302,108 @@ pub async fn operator_can_draft( ) { return Ok(true); } - let rights = operator_rights(db, workspace_id).await?; + let caps = caller_capabilities(db, workspace_id, authed).await?; + // Exhaustive on purpose: a new kind must pick the capability it needs, or every non-admin + // (unrestricted developers included) is refused its drafts. Ok(match kind { - UserDraftItemKind::Flow => rights.builder.has(BuilderKind::Flows), - UserDraftItemKind::RawApp => rights.builder.has(BuilderKind::Apps), - kind => kind.manage_kind().is_some_and(|m| rights.manage.has(m)), + UserDraftItemKind::Flow => caps.flows != AuthorLevel::None, + UserDraftItemKind::RawApp => caps.apps != AuthorLevel::None, + UserDraftItemKind::Script | UserDraftItemKind::DataPipeline => caps.code, + UserDraftItemKind::App => caps.apps == AuthorLevel::Full, + UserDraftItemKind::Resource | UserDraftItemKind::Variable => true, + UserDraftItemKind::TriggerSchedule + | UserDraftItemKind::TriggerWebhook + | UserDraftItemKind::TriggerDefaultEmail + | UserDraftItemKind::TriggerEmail + | UserDraftItemKind::TriggerHttp + | UserDraftItemKind::TriggerWebsocket + | UserDraftItemKind::TriggerPostgres + | UserDraftItemKind::TriggerKafka + | UserDraftItemKind::TriggerNats + | UserDraftItemKind::TriggerMqtt + | UserDraftItemKind::TriggerAmqp + | UserDraftItemKind::TriggerSqs + | UserDraftItemKind::TriggerGcp + | UserDraftItemKind::TriggerAzure + | UserDraftItemKind::TriggerPoll + | UserDraftItemKind::TriggerCli + | UserDraftItemKind::TriggerNextcloud + | UserDraftItemKind::TriggerGoogle + | UserDraftItemKind::TriggerGithub => { + kind.manage_kind().is_some_and(|m| caps.has_manage(m)) + } }) } -/// Gate for a write only a workspace that granted the builder right covering `kind` lets operators -/// perform. `action` completes "Operators cannot {action} for security reasons". -pub async fn check_operator_can_build( +/// Gate for a flow or app write. Refuses a caller whose role holds no right on `kind`, and returns +/// the level it does hold: at `Compose` the caller MUST then run the composition-only checks, and +/// only at `Full` may skip them. `action` completes "Your role cannot {action}". +pub async fn check_operator_can_build<A: Authable + ?Sized>( db: &DB, workspace_id: &str, - is_operator: bool, + authed: &A, kind: BuilderKind, action: &str, -) -> Result<()> { - if is_operator && !operator_builder_rights(db, workspace_id).await?.has(kind) { +) -> Result<AuthorLevel> { + let level = caller_capabilities(db, workspace_id, authed) + .await? + .level(kind); + if level == AuthorLevel::None { return Err(Error::PermissionDenied(format!( - "Operators cannot {action} for security reasons" + "Your role cannot {action} in this workspace" + ))); + } + Ok(level) +} + +/// Gate for a write that runs or stores code of the caller's own on a worker: scripts, previews, +/// dependency jobs, dynamic selects. `action` completes "Your role cannot {action}". +pub async fn check_role_can_code<A: Authable + ?Sized>( + db: &DB, + workspace_id: &str, + authed: &A, + action: &str, +) -> Result<()> { + if !caller_capabilities(db, workspace_id, authed).await?.code { + return Err(Error::PermissionDenied(format!( + "Your role cannot {action} in this workspace" ))); } Ok(()) } -/// Whether a membership consumes an operator (half) seat rather than an author seat. Either -/// builder right makes an operator an author of deployable artifacts, so both weigh the same full -/// seat: there is no half-author. +/// Whether a member holding role `role` in `workspace_id` consumes an operator (half) seat rather +/// than an author seat: a role that composes counts as an author, there is no half-author. pub async fn consumes_operator_seat( db: &DB, workspace_id: &str, - is_operator: bool, + is_admin: bool, + role: &str, ) -> Result<bool> { - Ok(is_operator && !operator_builder_rights(db, workspace_id).await?.any()) + Ok(!is_admin + && !crate::roles::role_capabilities_by_name(db, workspace_id, role) + .await? + .is_author()) } -/// Invalidate the operator rights cache for a workspace -pub fn invalidate_operator_rights_cache(workspace_id: &str) { - OPERATOR_RIGHTS_CACHE.remove(workspace_id); -} - -/// Gate for a write operators may perform unless the workspace withdrew it. Prefer layering +/// Gate for a write a role may perform unless its configuration withdraws it. Prefer layering /// `gate_operator_writes` on a whole router over calling this per handler; see -/// `docs/operator-write-rights.md`. Both `workspace_id` and `is_operator` MUST come from the -/// authenticated request (the route's workspace, `ApiAuthed::is_operator`): passing `false` skips -/// the check, and another workspace's id checks the wrong settings. -pub async fn check_operator_can_manage( +/// `docs/operator-write-rights.md`. `workspace_id` MUST be the route's workspace. +pub async fn check_operator_can_manage<A: Authable + ?Sized>( db: &DB, workspace_id: &str, - is_operator: bool, + authed: &A, kind: ManageKind, ) -> Result<()> { - if is_operator && !operator_rights(db, workspace_id).await?.manage.has(kind) { + if !caller_capabilities(db, workspace_id, authed) + .await? + .has_manage(kind) + { // 403, not 401: the caller is authenticated and simply lacks the right. The frontend reads // an uncaught 401 as a dead session and logs the user out, so `NotAuthorized` here would - // eject an operator from the app instead of telling them why. + // eject the user from the app instead of telling them why. return Err(Error::PermissionDenied(format!( - "Operators cannot manage {} in this workspace", + "Your role cannot manage {} in this workspace", kind.noun() ))); } @@ -3845,7 +3805,7 @@ async fn transform_json_unchecked( serde_json::Value::String(s) if s.starts_with("$var:") => { let path = &s[5..]; let (value, is_secret): (String, bool) = sqlx::query_as( - "SELECT value, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", + "SELECT value::text, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", ) .bind(&w_id) .bind(path) diff --git a/backend/windmill-common/tests/billing_workspace.rs b/backend/windmill-common/tests/billing_workspace.rs index ccc013d47a..3e962f5840 100644 --- a/backend/windmill-common/tests/billing_workspace.rs +++ b/backend/windmill-common/tests/billing_workspace.rs @@ -125,13 +125,12 @@ async fn paid_seats_and_fork_count(db: Pool<Postgres>) { ); sqlx::query( - "INSERT INTO workspace_settings (workspace_id, operator_settings) - VALUES ('seat-root', '{\"builder_flows\": true}')", + "INSERT INTO role_seat (workspace_id, role, author) VALUES ('seat-root', 'operator', true)", ) .execute(&db) .await .unwrap(); - windmill_common::workspaces::invalidate_operator_rights_cache("seat-root"); + windmill_common::roles::invalidate_all_roles_cache(); let breakdown = billable_seats(&db, "seat-root").await.unwrap(); assert_eq!( ( @@ -141,22 +140,29 @@ async fn paid_seats_and_fork_count(db: Pool<Postgres>) { breakdown.seats ), (4, 0, 1, 5), - "builder rights bill every operator as a developer, service accounts stay half a seat" + "a role that composes bills its members as developers, service accounts stay half a seat" ); + sqlx::query("UPDATE role_seat SET author = false WHERE workspace_id = 'seat-root'") + .execute(&db) + .await + .unwrap(); + windmill_common::roles::invalidate_all_roles_cache(); + let breakdown = billable_seats(&db, "seat-root").await.unwrap(); + assert_eq!( + (breakdown.developers, breakdown.operators, breakdown.seats), + (2, 2, 4), + "a workspace override that authors nothing bills its members at half a seat" + ); + + // An admin holds everything, so it is a full seat whatever role it keeps underneath. sqlx::query( - "UPDATE workspace_settings SET operator_settings = '{\"builder_apps\": true}' - WHERE workspace_id = 'seat-root'", + "UPDATE usr SET is_admin = true WHERE workspace_id = 'seat-root' AND email = 'op1@w.dev'", ) .execute(&db) .await .unwrap(); - windmill_common::workspaces::invalidate_operator_rights_cache("seat-root"); let breakdown = billable_seats(&db, "seat-root").await.unwrap(); - assert_eq!( - (breakdown.developers, breakdown.operators, breakdown.seats), - (4, 0, 5), - "the app right alone also bills every operator as a developer" - ); + assert_eq!((breakdown.developers, breakdown.operators), (3, 1)); insert_ws(&db, "seat-fork1", Some("seat-root"), false).await; insert_ws(&db, "seat-fork2", Some("seat-root"), false).await; diff --git a/backend/windmill-common/tests/instance_group_auto_add.rs b/backend/windmill-common/tests/instance_group_auto_add.rs index 95b20cc842..963b6e7a79 100644 --- a/backend/windmill-common/tests/instance_group_auto_add.rs +++ b/backend/windmill-common/tests/instance_group_auto_add.rs @@ -440,8 +440,13 @@ mod tests { .and_then(|ig| serde_json::from_value(ig).ok()) .unwrap_or_default(); - let (best_group, is_admin, is_operator) = - compute_highest_workspace_role(&user_igroups, &ws_configured_groups, &ws_roles); + let (best_group, is_admin, role) = compute_highest_workspace_role( + &user_igroups, + &ws_configured_groups, + &ws_roles, + &["developer".to_string(), "operator".to_string()], + ); + let is_operator = role == "operator"; let instance_group_source = json!({ "source": "instance_group", @@ -528,8 +533,13 @@ mod tests { let ws_roles: std::collections::HashMap<String, String> = serde_json::from_value(roles).unwrap(); - let (best_group, is_admin, is_operator) = - compute_highest_workspace_role(&user_igroups, &ws_configured_groups, &ws_roles); + let (best_group, is_admin, role) = compute_highest_workspace_role( + &user_igroups, + &ws_configured_groups, + &ws_roles, + &["developer".to_string(), "operator".to_string()], + ); + let is_operator = role == "operator"; let instance_group_source = json!({"source": "instance_group", "group": &best_group}); sqlx::query!( diff --git a/backend/windmill-common/tests/workspace_roles_declarative.rs b/backend/windmill-common/tests/workspace_roles_declarative.rs new file mode 100644 index 0000000000..b3ab777310 --- /dev/null +++ b/backend/windmill-common/tests/workspace_roles_declarative.rs @@ -0,0 +1,80 @@ +#![cfg(feature = "enterprise")] + +use std::collections::BTreeMap; + +use sqlx::{Pool, Postgres}; +use windmill_common::global_settings::WORKSPACE_ROLES_SETTING; +use windmill_common::instance_config::sync_global_settings_declarative; + +/// The declarative config sync writes `workspace_roles` without the HTTP settings handler, so it +/// must validate the value and rebuild `role_seat` itself, or billing misprices the new roles. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn declarative_workspace_roles_validates_and_rebuilds_seats(db: Pool<Postgres>) { + windmill_common::roles::invalidate_all_roles_cache(); + let desired = + |roles: serde_json::Value| BTreeMap::from([(WORKSPACE_ROLES_SETTING.to_string(), roles)]); + + sync_global_settings_declarative( + &db, + &BTreeMap::new(), + &desired(serde_json::json!([{"name": "x", "capabilities": {"flows": "full"}}])), + &(), + ) + .await + .expect_err("full flows without code must be refused"); + + sync_global_settings_declarative( + &db, + &BTreeMap::new(), + &desired(serde_json::json!([ + {"name": "developer"}, + {"name": "builder", "capabilities": {"flows": "compose"}}, + {"name": "operator"} + ])), + &(), + ) + .await + .unwrap(); + let author: bool = sqlx::query_scalar( + "SELECT author FROM role_seat WHERE workspace_id = '' AND role = 'builder'", + ) + .fetch_one(&db) + .await + .unwrap(); + assert!(author, "a role that composes flows costs a full seat"); + + // A workspace grants `builder` full flows on top of an instance definition that codes; the + // instance then withdrawing `code` would leave that workspace with inline code and no code. + sync_global_settings_declarative( + &db, + &BTreeMap::new(), + &desired(serde_json::json!([ + {"name": "developer"}, + {"name": "builder", "capabilities": {"code": true, "flows": "compose"}}, + {"name": "operator"} + ])), + &(), + ) + .await + .unwrap(); + sqlx::query( + "UPDATE workspace_settings SET role_overrides = + '{\"builder\": {\"capabilities\": {\"flows\": \"full\"}}}' + WHERE workspace_id = 'test-workspace'", + ) + .execute(&db) + .await + .unwrap(); + sync_global_settings_declarative( + &db, + &BTreeMap::new(), + &desired(serde_json::json!([ + {"name": "developer"}, + {"name": "builder", "capabilities": {"code": false, "flows": "compose"}}, + {"name": "operator"} + ])), + &(), + ) + .await + .expect_err("an instance change that invalidates a workspace override must be refused"); +} diff --git a/backend/windmill-common/tests/workspace_roles_license.rs b/backend/windmill-common/tests/workspace_roles_license.rs new file mode 100644 index 0000000000..88aa3593cb --- /dev/null +++ b/backend/windmill-common/tests/workspace_roles_license.rs @@ -0,0 +1,70 @@ +#![cfg(feature = "enterprise")] +//! Flips the process-wide `LICENSE_KEY_VALID`, so it keeps a test binary of its own. + +use std::sync::atomic::Ordering; + +use sqlx::{Pool, Postgres}; +use windmill_common::ee_oss::LICENSE_KEY_VALID; +use windmill_common::roles::{ + self, check_frozen_overrides, instance_roles, load_role_overrides, + validate_instance_roles_write, RoleOverrides, +}; + +/// A lapsed license freezes the configured roles: falling back to the defaults would give a +/// restricted `developer` everything and strand the members of workspace-only roles. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn lapsed_license_freezes_roles(db: Pool<Postgres>) { + let restricted = serde_json::json!([ + {"name": "developer", "capabilities": {"code": false, "flows": "none", "apps": "none"}} + ]); + sqlx::query("INSERT INTO global_settings (name, value) VALUES ('workspace_roles', $1)") + .bind(&restricted) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "UPDATE workspace_settings SET role_overrides = '{\"auditor\": {\"label\": \"Auditor\"}}' + WHERE workspace_id = 'test-workspace'", + ) + .execute(&db) + .await + .unwrap(); + + LICENSE_KEY_VALID.store(false, Ordering::Relaxed); + roles::invalidate_all_roles_cache(); + + let ws = roles::workspace_roles(&db, "test-workspace").await.unwrap(); + let dev = ws.iter().find(|r| r.name == "developer").unwrap(); + assert!( + !dev.capabilities.code, + "the restricted developer must not widen" + ); + assert!( + ws.iter().any(|r| r.name == "auditor"), + "workspace-only roles keep applying" + ); + + let changed = serde_json::json!([{"name": "developer"}, {"name": "scripter"}]); + validate_instance_roles_write(&db, Some(&changed)) + .await + .expect_err("changing instance roles needs a license"); + validate_instance_roles_write(&db, Some(&restricted)) + .await + .expect("resaving the stored roles is a no-op"); + validate_instance_roles_write(&db, None) + .await + .expect("resetting to the defaults stays open"); + + let instance = instance_roles(&db).await.unwrap(); + let previous = load_role_overrides(&db, "test-workspace").await.unwrap(); + let mut relabelled = previous.clone(); + relabelled.get_mut("auditor").unwrap().label = Some("Reader".to_string()); + check_frozen_overrides(&instance, &previous, &relabelled) + .expect_err("editing a workspace-only role needs a license"); + check_frozen_overrides(&instance, &previous, &previous).expect("unchanged entries pass"); + check_frozen_overrides(&instance, &previous, &RoleOverrides::new()) + .expect("removing a workspace-only role stays open"); + + LICENSE_KEY_VALID.store(true, Ordering::Relaxed); + check_frozen_overrides(&instance, &previous, &relabelled).expect("licensed again"); +} diff --git a/backend/windmill-mcp/src/common/mod.rs b/backend/windmill-mcp/src/common/mod.rs index 2632a28962..6707943482 100644 --- a/backend/windmill-mcp/src/common/mod.rs +++ b/backend/windmill-mcp/src/common/mod.rs @@ -9,7 +9,7 @@ pub mod transform; pub mod types; pub use schema::convert_schema_to_schema_type; -pub use scope::{is_resource_allowed, parse_mcp_scopes, McpScopeConfig}; +pub use scope::{is_resource_allowed, parse_mcp_scopes, McpScopeConfig, SESSION_SCOPE}; pub use transform::{ apply_key_transformation, extract_hub_version_id_from_hashed, extract_path_prefix_from_hashed, parse_tool_prefix, reverse_transform, reverse_transform_key, transform_hub_path, diff --git a/backend/windmill-mcp/src/common/scope.rs b/backend/windmill-mcp/src/common/scope.rs index 418458d4fe..642c02a2bc 100644 --- a/backend/windmill-mcp/src/common/scope.rs +++ b/backend/windmill-mcp/src/common/scope.rs @@ -20,9 +20,26 @@ pub struct McpScopeConfig { pub granular: bool, /// Hub app filter (if any) pub hub_apps: Option<String>, + /// The workspaces a token without a bound workspace may act in + /// (`mcp:workspaces:a,b`); `None` is every workspace its owner belongs to. + pub workspaces: Option<Vec<String>>, + /// `mcp:read_run`: reads, plus running deployed scripts and flows, and nothing else. + pub read_run: bool, + /// `mcp:read_only`: reads alone, as the token's read-only flag does. An OAuth grant + /// carries scopes and no flag, so this is how a sign-in asks for read-only access. + pub read_only: bool, + /// No endpoint tools on any URL: set by `mcp:read_only`, `mcp:read_run` and + /// `mcp:runnables_as_tools`, and by the server on `/api/mcp` for a selection. + pub no_endpoints: bool, } impl McpScopeConfig { + pub fn allows_workspace(&self, workspace_id: &str) -> bool { + self.workspaces + .as_ref() + .is_none_or(|ws| ws.iter().any(|w| w == workspace_id)) + } + /// Whether the token grants access to *any* concrete resource of this type by /// path. Used to decide whether to advertise the run-by-path tools in /// multi-workspace mode (a `mcp:scripts:*`-only token should see @@ -68,6 +85,21 @@ impl McpScopeConfig { /// semantics), this requires every requested pattern to be covered by some /// caller pattern — so `mcp:scripts:f/x` cannot widen into `mcp:scripts:*`. pub fn contains(&self, requested: &McpScopeConfig) -> bool { + if let Some(caller_ws) = self.workspaces.as_ref() { + match requested.workspaces.as_ref() { + Some(req_ws) if req_ws.iter().all(|w| caller_ws.contains(w)) => {} + _ => return false, + } + } + if self.read_only && !requested.read_only { + return false; + } + if self.read_run && !(requested.read_run || requested.read_only) { + return false; + } + if self.no_endpoints && !requested.no_endpoints { + return false; + } if self.all { return true; } @@ -125,6 +157,15 @@ fn pattern_covers(caller: &str, requested: &str) -> bool { && requested_base.as_bytes().get(prefix.len()) == Some(&b'/')) } +/// Marks a selection made as "scripts and flows as tools": it gets no endpoint tools on any +/// URL, which an older selection, carrying none of the newer scopes, still does. +pub const RUNNABLES_AS_TOOLS_SCOPE: &str = "mcp:runnables_as_tools"; + +/// Added server-side to an `mcp:all` OAuth grant so the tools server's URLs serve it the AI +/// session's toolset. Grants nothing: an un-narrowed `mcp:all` token without it predates the +/// session toolset there, and must keep the tools server's endpoint tools. +pub const SESSION_SCOPE: &str = "mcp:session"; + /// Parse MCP scopes from token scope strings pub fn parse_mcp_scopes(scopes: &[String]) -> Result<McpScopeConfig, String> { let mut config = McpScopeConfig::default(); @@ -180,6 +221,35 @@ pub fn parse_mcp_scopes(scopes: &[String]) -> Result<McpScopeConfig, String> { continue; } + if scope == "mcp:read_run" { + config.read_run = true; + config.no_endpoints = true; + continue; + } + + if scope == "mcp:read_only" { + config.read_only = true; + config.no_endpoints = true; + continue; + } + + if scope == RUNNABLES_AS_TOOLS_SCOPE { + config.no_endpoints = true; + continue; + } + + if scope == SESSION_SCOPE { + continue; + } + + if let Some(ids) = scope.strip_prefix("mcp:workspaces:") { + config + .workspaces + .get_or_insert_with(Vec::new) + .extend(parse_resource_list(ids)); + continue; + } + if let Some(resources) = scope.strip_prefix("mcp:endpoints:") { // New granular endpoint scope: mcp:endpoints:name1,name2 config.endpoints.extend(parse_resource_list(resources)); @@ -409,4 +479,38 @@ mod tests { // mcp:all grants all endpoints. assert!(cfg(&["mcp:all"]).contains(&cfg(&["mcp:endpoints:getResource"]))); } + + #[test] + fn test_workspaces_scope() { + let two = cfg(&["mcp:all", "mcp:workspaces:dev,staging"]); + assert!(two.allows_workspace("dev") && !two.allows_workspace("prod")); + assert!(cfg(&["mcp:all"]).allows_workspace("prod")); + // A workspace list only narrows: it cannot be dropped or widened by a grant. + assert!(two.contains(&cfg(&["mcp:all", "mcp:workspaces:dev"]))); + assert!(!two.contains(&cfg(&["mcp:all", "mcp:workspaces:dev,prod"]))); + assert!(!two.contains(&cfg(&["mcp:all"]))); + assert!(cfg(&["mcp:all"]).contains(&two)); + } + + #[test] + fn test_read_run_scope_only_narrows() { + let read_run = cfg(&["mcp:all", "mcp:read_run"]); + assert!(read_run.read_run && read_run.all); + assert!(read_run.contains(&cfg(&["mcp:all", "mcp:read_run"]))); + assert!(!read_run.contains(&cfg(&["mcp:all"]))); + assert!(read_run.contains(&cfg(&["mcp:all", "mcp:read_only"]))); + let read_only = cfg(&["mcp:all", "mcp:read_only"]); + assert!(!read_only.contains(&cfg(&["mcp:all", "mcp:read_run"]))); + } + + #[test] + fn test_runnables_as_tools_scope_only_narrows() { + let fenced = cfg(&["mcp:favorites", "mcp:runnables_as_tools"]); + assert!(fenced.no_endpoints); + assert!(cfg(&["mcp:all", "mcp:read_only"]).no_endpoints); + assert!(cfg(&["mcp:all", "mcp:read_run"]).no_endpoints); + assert!(fenced.contains(&cfg(&["mcp:favorites", "mcp:runnables_as_tools"]))); + assert!(!fenced.contains(&cfg(&["mcp:favorites"]))); + assert!(cfg(&["mcp:all"]).contains(&fenced)); + } } diff --git a/backend/windmill-mcp/src/common/types.rs b/backend/windmill-mcp/src/common/types.rs index 273a952cbb..7d91e94255 100644 --- a/backend/windmill-mcp/src/common/types.rs +++ b/backend/windmill-mcp/src/common/types.rs @@ -22,6 +22,11 @@ pub struct WorkspaceId(pub String); #[derive(Clone, Debug)] pub struct MultiWorkspaceMcp; +/// Marker extension: the tools server lists a token's scripts and flows and no endpoint +/// tools. Set on `/api/mcp`, where the full toolset is what reaches the API. +#[derive(Clone, Debug)] +pub struct NoEndpointTools; + /// Raw bearer token wrapper for Axum extensions. In multi-workspace mode the /// runner needs the raw token to re-resolve auth for each requested workspace. #[derive(Clone, Debug)] diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 6fa560e377..dc3a23bb51 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -4,6 +4,7 @@ //! (typically windmill-api) to provide the actual functionality for the MCP server. use async_trait::async_trait; +use rmcp::model::{CallToolResult, Tool}; use rmcp::ErrorData; use serde_json::Value; use std::collections::HashMap; @@ -16,6 +17,15 @@ use crate::server::endpoints::EndpointTool; /// Result type for backend operations using rmcp's ErrorData directly pub type BackendResult<T> = Result<T, ErrorData>; +/// What a v2 token may do: read, read and run deployed scripts and flows (`mcp:read_run`), +/// or everything its owner can. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SessionAccess { + ReadOnly, + ReadAndRun, + Full, +} + /// What the backend needs about the HTTP request a tool call arrived on, in order /// to hand a runnable the headers of the call that triggered it. pub struct McpRequest<'a> { @@ -234,4 +244,35 @@ pub trait McpBackend: Send + Sync + Clone + 'static { /// Get all available endpoint tools fn all_endpoint_tools(&self) -> Vec<EndpointTool>; + + // ───────────────────────────────────────────────────────────────── + // Workspace server (`SessionRunner`): the AI-session toolset + // ───────────────────────────────────────────────────────────────── + + /// The instructions a client reaching one workspace receives on connecting, built for + /// this user. + async fn session_instructions( + &self, + auth: &Self::Auth, + workspace_id: &str, + ) -> BackendResult<String>; + + /// The instructions for a client reaching several workspaces: what holds in all of them. + fn generic_session_instructions(&self) -> String; + + /// What `generic_session_instructions` leaves out, for one workspace. + async fn workspace_context(&self, auth: &Self::Auth, workspace_id: &str) -> String; + + /// The tools a token with this access is offered. + fn session_tools(&self, access: SessionAccess) -> Vec<Tool>; + + async fn call_session_tool( + &self, + auth: &Self::Auth, + workspace_id: &str, + name: &str, + args: Value, + access: SessionAccess, + origin: Option<&str>, + ) -> BackendResult<CallToolResult>; } diff --git a/backend/windmill-mcp/src/server/endpoints.rs b/backend/windmill-mcp/src/server/endpoints.rs index 5b08d211a5..7418e23206 100644 --- a/backend/windmill-mcp/src/server/endpoints.rs +++ b/backend/windmill-mcp/src/server/endpoints.rs @@ -113,9 +113,27 @@ pub fn endpoint_tool_to_mcp_tool_multi(tool: &EndpointTool) -> Tool { return mcp_tool; } + // Surface the requirement in the prose description too (the schema is + // authoritative, but some models/clients lean on the text). Kept terse — this + // repeats across every workspace-scoped tool in the list. + if let Some(desc) = mcp_tool.description.take() { + mcp_tool.description = Some(format!("{desc} Requires `workspace_id`.").into()); + } else { + mcp_tool.description = Some("Requires `workspace_id`.".into()); + } + with_workspace_id_arg(mcp_tool) +} + +/// The tool with a required `workspace_id` argument, which the caller strips before +/// dispatching. +pub fn with_workspace_id_arg(mut mcp_tool: Tool) -> Tool { let mut schema = (*mcp_tool.input_schema).clone(); - if let Some(props) = schema.get_mut("properties").and_then(|p| p.as_object_mut()) { + if let Some(props) = schema + .entry("properties") + .or_insert_with(|| serde_json::json!({})) + .as_object_mut() + { props.insert( "workspace_id".to_string(), serde_json::json!({ @@ -136,15 +154,6 @@ pub fn endpoint_tool_to_mcp_tool_multi(tool: &EndpointTool) -> Tool { } } - // Surface the requirement in the prose description too (the schema is - // authoritative, but some models/clients lean on the text). Kept terse — this - // repeats across every workspace-scoped tool in the list. - if let Some(desc) = mcp_tool.description.take() { - mcp_tool.description = Some(format!("{desc} Requires `workspace_id`.").into()); - } else { - mcp_tool.description = Some("Requires `workspace_id`.".into()); - } - mcp_tool.input_schema = Arc::new(schema); mcp_tool } diff --git a/backend/windmill-mcp/src/server/mod.rs b/backend/windmill-mcp/src/server/mod.rs index ad7c14d320..545812a411 100644 --- a/backend/windmill-mcp/src/server/mod.rs +++ b/backend/windmill-mcp/src/server/mod.rs @@ -9,16 +9,18 @@ pub mod backend; pub mod endpoints; mod list_changes; pub mod runner; +mod session; pub mod tools; // Re-export main types -pub use crate::common::types::{McpToken, MultiWorkspaceMcp, WorkspaceInfo}; -pub use backend::{BackendResult, McpAuth, McpBackend, McpRequest, PathFilter}; +pub use crate::common::types::{McpToken, MultiWorkspaceMcp, NoEndpointTools, WorkspaceInfo}; +pub use backend::{BackendResult, McpAuth, McpBackend, McpRequest, PathFilter, 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, EndpointTool, + list_workspaces_tool, non_empty_body_fields, with_workspace_id_arg, EndpointTool, }; -pub use runner::{has_endpoint_path_policy, Runner}; +pub use runner::{has_endpoint_path_policy, Runner, MAX_TOOL_RESULT_BYTES}; +pub use session::SessionRunner; pub use tools::create_tool_from_item; // Re-export rmcp types for convenience @@ -26,8 +28,8 @@ pub use rmcp::handler::server::ServerHandler; pub use rmcp::model::{ CallToolRequestParams, CallToolResult, ContentBlock, Implementation, InitializeRequestParams, InitializeResult, ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult, - ListToolsResult, PaginatedRequestParams, ProtocolVersion, ServerCapabilities, ServerInfo, Tool, - ToolAnnotations, + ListToolsResult, MetaObject, PaginatedRequestParams, ProtocolVersion, ServerCapabilities, + ServerInfo, Tool, ToolAnnotations, }; pub use rmcp::service::{RequestContext, RoleServer}; pub use rmcp::transport::streamable_http_server::{ diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index 2eab72469e..e2ce8b6c04 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -11,7 +11,8 @@ use crate::common::transform::{ short_name_last_segments, }; use crate::common::types::{ - McpToken, MultiWorkspaceMcp, ResourceInfo, SchemaType, ToolableItem, WorkspaceId, + McpToken, MultiWorkspaceMcp, NoEndpointTools, ResourceInfo, SchemaType, ToolableItem, + WorkspaceId, }; use crate::server::backend::{McpAuth, McpBackend, McpRequest, PathFilter}; use crate::server::endpoints::{ @@ -37,7 +38,7 @@ use tokio::sync::broadcast; /// Protocol revisions this server is willing to speak. `2026-07-28` is served /// statelessly with per-request metadata; the older revisions keep the /// `initialize` handshake, so both eras are answered on the same endpoint. -const SUPPORTED_PROTOCOL_VERSIONS: &[ProtocolVersion] = &[ +pub(super) const SUPPORTED_PROTOCOL_VERSIONS: &[ProtocolVersion] = &[ ProtocolVersion::V_2024_11_05, ProtocolVersion::V_2025_03_26, ProtocolVersion::V_2025_06_18, @@ -53,12 +54,12 @@ const SUPPORTED_PROTOCOL_VERSIONS: &[ProtocolVersion] = &[ /// covers only some of what the listing depends on (not resources, favorites or /// permissions), lags by up to a poll interval, and reaches only clients that hold a /// `subscriptions/listen` stream. -const LIST_TTL_MS: u64 = 0; +pub(super) const LIST_TTL_MS: u64 = 0; /// Every listing is filtered by the caller's token scopes and workspace /// membership, so no two callers necessarily see the same tools — a shared /// cache entry would leak one token's view to another. -const LIST_CACHE_SCOPE: CacheScope = CacheScope::Private; +pub(super) const LIST_CACHE_SCOPE: CacheScope = CacheScope::Private; /// How long a `subscriptions/listen` stream waits after a change before notifying, /// collecting the rest of the burst into the same notification. @@ -70,9 +71,9 @@ use http::request::Parts as HttpParts; /// Maximum size in bytes for tool result text content. /// Anthropic enforces a 25,000 token limit per tool result. /// At ~3.5 bytes/token, 87,500 bytes is a safe upper bound. -const MAX_TOOL_RESULT_BYTES: usize = 87_500; +pub const MAX_TOOL_RESULT_BYTES: usize = 87_500; -fn truncate_tool_result(text: String) -> String { +pub(super) fn truncate_tool_result(text: String) -> String { if text.len() <= MAX_TOOL_RESULT_BYTES { return text; } @@ -103,7 +104,7 @@ impl<B: McpBackend> Clone for Runner<B> { /// Whether the request targets one bound workspace or spans every workspace the /// token can access. -enum McpMode { +pub(super) enum McpMode { /// A single workspace, resolved from the URL path or the token's bound /// workspace. Tools operate against this workspace implicitly. Single(String), @@ -114,10 +115,12 @@ enum McpMode { } /// Everything a request carries besides its MCP payload. -struct McpContext<A> { - auth: A, - mode: McpMode, - headers: http::HeaderMap, +pub(super) struct McpContext<A> { + pub(super) auth: A, + pub(super) mode: McpMode, + pub(super) headers: http::HeaderMap, + /// See `McpScopeConfig::no_endpoints`. + pub(super) no_endpoints: bool, } impl<B: McpBackend> Runner<B> { @@ -128,7 +131,7 @@ impl<B: McpBackend> Runner<B> { /// Extract authentication, the workspace mode and the HTTP request itself /// from the request context - fn extract_context( + pub(super) fn extract_context( context: &RequestContext<RoleServer>, ) -> Result<McpContext<B::Auth>, ErrorData> { let http_parts = context.extensions.get::<HttpParts>().ok_or_else(|| { @@ -165,13 +168,31 @@ impl<B: McpBackend> Runner<B> { ErrorData::internal_error("WorkspaceId not found", None) }) .map(|w_id| w_id.0.clone())?; + // A token without a bound workspace reaches a workspace's own URL too. + let scope_config = parse_mcp_scopes(auth.scopes().unwrap_or(&[])) + .map_err(|e| ErrorData::internal_error(e, None))?; + if !scope_config.allows_workspace(&workspace_id) { + return Err(workspace_not_granted(&workspace_id)); + } McpMode::Single(workspace_id) }; - Ok(McpContext { auth: auth.clone(), mode, headers: http_parts.headers.clone() }) + Ok(McpContext { + auth: auth.clone(), + mode, + headers: http_parts.headers.clone(), + no_endpoints: http_parts.extensions.get::<NoEndpointTools>().is_some(), + }) } } +pub(super) fn workspace_not_granted(workspace_id: &str) -> ErrorData { + ErrorData::invalid_params( + format!("This token was not granted workspace '{workspace_id}'"), + None, + ) +} + /// How an endpoint tool interacts with the token's `mcp:scripts:` / `mcp:flows:` /// path scopes. Mirrored in /// `frontend/src/lib/components/mcp/endpointScopePolicy.ts` so the scope picker @@ -301,6 +322,9 @@ fn endpoint_tool_in_scope( scope_config: &crate::common::scope::McpScopeConfig, endpoint_tool: &EndpointTool, ) -> bool { + if scope_config.no_endpoints { + return false; + } let endpoint_allowed = !scope_config.granular || scope_config.is_allowed("endpoint", &endpoint_tool.name); match endpoint_path_policy(&endpoint_tool.name) { @@ -327,6 +351,15 @@ fn authorize_endpoint_call( args: &mut Value, read_only: bool, ) -> Result<(), ErrorData> { + if scope_config.no_endpoints { + return Err(ErrorData::invalid_params( + format!( + "Tool '{}' is not available to this token", + endpoint_tool.name + ), + None, + )); + } // A destination the caller omitted, or left empty because it had to fill in every // argument, means "leave the item where it is". Resolved to the path the item is // already at, so the endpoint receives a body naming its own path rather than one @@ -558,14 +591,16 @@ impl<B: McpBackend> ServerHandler for Runner<B> { _request: Option<PaginatedRequestParams>, context: RequestContext<RoleServer>, ) -> Result<ListToolsResult, ErrorData> { - let McpContext { auth, mode, .. } = Self::extract_context(&context)?; + let McpContext { auth, mode, no_endpoints, .. } = Self::extract_context(&context)?; // Parse MCP scopes to determine what to expose let scopes = auth.scopes().unwrap_or(&[]); - let scope_config = + let mut scope_config = parse_mcp_scopes(scopes).map_err(|e| ErrorData::internal_error(e, None))?; + scope_config.no_endpoints |= no_endpoints; - let read_only = auth.read_only(); + // v1 has no read-and-run access: such a token reads only. + let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only; match mode { McpMode::Single(workspace_id) => { @@ -586,13 +621,14 @@ impl<B: McpBackend> ServerHandler for Runner<B> { request: CallToolRequestParams, context: RequestContext<RoleServer>, ) -> Result<CallToolResponse, ErrorData> { - let McpContext { auth, mode, headers } = Self::extract_context(&context)?; + let McpContext { auth, mode, headers, no_endpoints } = Self::extract_context(&context)?; // Parse MCP scopes for authorization let scopes = auth.scopes().unwrap_or(&[]); - let scope_config = + let mut scope_config = parse_mcp_scopes(scopes).map_err(|e| ErrorData::internal_error(e, None))?; - let read_only = auth.read_only(); + scope_config.no_endpoints |= no_endpoints; + let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only; let args = request.arguments.map(Value::Object).unwrap_or(Value::Null); let mcp_request = McpRequest { headers: &headers, tool_name: request.name.as_ref() }; @@ -1088,11 +1124,12 @@ impl<B: McpBackend> Runner<B> { mut args: Value, ) -> Result<CallToolResult, ErrorData> { if name.as_ref() == "list_workspaces" { - let workspaces = self + let mut workspaces = self .backend .list_accessible_workspaces(base_auth) .await .map_err(|e| ErrorData::internal_error(e.message, None))?; + workspaces.retain(|w| scope_config.allows_workspace(&w.id)); return Ok(CallToolResult::success(vec![ContentBlock::text( serde_json::to_string_pretty(&workspaces).unwrap_or_else(|_| "[]".to_string()), )])); @@ -1140,6 +1177,9 @@ impl<B: McpBackend> Runner<B> { ) })? .to_string(); + if !scope_config.allows_workspace(&workspace_id) { + return Err(workspace_not_granted(&workspace_id)); + } let resolved = self .backend @@ -1281,6 +1321,17 @@ mod tests { ); } + #[test] + fn a_selection_without_endpoints_gets_none() { + // The scope withholds them on every URL, as the server does on `/api/mcp`. + let selection = cfg(&["mcp:favorites", "mcp:endpoints:*", "mcp:runnables_as_tools"]); + assert!(!endpoint_tool_in_scope(&selection, &ep("listJobs", "GET"))); + assert!( + authorize_endpoint_call(&selection, &ep("listJobs", "GET"), &mut json!({}), false) + .is_err() + ); + } + #[test] fn read_only_refuses_non_get_endpoint() { // Reaches the read-only check via mcp:all so scope isn't the blocker. diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs new file mode 100644 index 0000000000..1130a01e84 --- /dev/null +++ b/backend/windmill-mcp/src/server/session.rs @@ -0,0 +1,338 @@ +//! The Windmill MCP server's toolset: an AI session's tools and guidance for an external +//! client. `/api/mcp` serves it to tokens with `mcp:all`, and the tools server (`Runner`) +//! to tokens scoped to a selection of scripts and flows. +//! +//! Every tool takes the workspace it acts in, whether the token reaches one workspace or +//! several, so a client's tool schemas do not change with the token it signed in with. + +use crate::common::scope::{parse_mcp_scopes, McpScopeConfig}; +use crate::common::types::WorkspaceInfo; +use crate::server::backend::{McpAuth, McpBackend, SessionAccess}; +use crate::server::endpoints::{list_workspaces_tool, with_workspace_id_arg}; +use crate::server::runner::{ + truncate_tool_result, workspace_not_granted, McpContext, McpMode, Runner, LIST_CACHE_SCOPE, + LIST_TTL_MS, SUPPORTED_PROTOCOL_VERSIONS, +}; +use rmcp::handler::server::ServerHandler; +use rmcp::model::{ + CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, DiscoverResult, + Implementation, InitializeRequestParams, InitializeResult, ListToolsResult, + PaginatedRequestParams, ProtocolVersion, ServerCapabilities, ServerInfo, Tool, ToolAnnotations, +}; +use rmcp::service::{RequestContext, RoleServer}; +use rmcp::ErrorData; +use serde_json::Value; +use std::borrow::Cow; +use std::sync::Arc; + +/// `mcp:all`, and no scope from outside `mcp:` that confines the token to some routes +/// or paths (`variables:read:f/x/*`): the tools call the API without a route scope, so +/// that confinement would be lost here. The job tag fence is carried through instead. +fn admits(scopes: &[String], all: bool) -> bool { + all && scopes + .iter() + .all(|s| s.starts_with("mcp:") || s.starts_with("if_jobs:filter_tags:")) +} + +fn access<A: McpAuth>(auth: &A, scope: &McpScopeConfig) -> SessionAccess { + if auth.read_only() || scope.read_only { + SessionAccess::ReadOnly + } else if scope.read_run { + SessionAccess::ReadAndRun + } else { + SessionAccess::Full + } +} + +const GET_WORKSPACE_CONTEXT: &str = "get_workspace_context"; + +/// Workspaces named in the instructions before the rest are left to `list_workspaces`. +const MAX_LISTED_WORKSPACES: usize = 40; + +fn get_workspace_context_tool() -> Tool { + let schema = serde_json::json!({ "type": "object", "properties": {} }); + with_workspace_id_arg( + Tool::new( + Cow::Borrowed(GET_WORKSPACE_CONTEXT), + "Your username in a workspace, the folders you can write to there, and the \ + workspace's skills and instructions. Call it before your first action in a \ + workspace.", + Arc::new(schema.as_object().unwrap().clone()), + ) + .with_annotations(ToolAnnotations::new().read_only(true)), + ) +} + +/// A request's caller, and the workspaces its token reaches. +struct Caller<A> { + auth: A, + mode: McpMode, + scope: McpScopeConfig, + /// The scheme and host the client reached, for links to Windmill pages. + origin: Option<String>, +} + +/// `x-forwarded-*` first, since a proxy in front rewrites the host the request names. +fn request_origin(headers: &http::HeaderMap) -> Option<String> { + let header = |name: &str| { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.split(',').next()) + .map(str::trim) + .filter(|v| !v.is_empty()) + }; + let host = header("x-forwarded-host").or_else(|| header("host"))?; + let scheme = header("x-forwarded-proto").unwrap_or("http"); + Some(format!("{scheme}://{host}")) +} + +pub struct SessionRunner<B: McpBackend> { + backend: Arc<B>, +} + +impl<B: McpBackend> Clone for SessionRunner<B> { + fn clone(&self) -> Self { + Self { backend: self.backend.clone() } + } +} + +impl<B: McpBackend> SessionRunner<B> { + pub fn new(backend: B) -> Self { + Self { backend: Arc::new(backend) } + } + + /// This server writes drafts and deploys, so it takes the scope that already reaches + /// the create/update endpoint tools and nothing narrower: a token scoped to a few + /// scripts was never consented for authoring. + fn caller(context: &RequestContext<RoleServer>) -> Result<Caller<B::Auth>, ErrorData> { + let McpContext { auth, mode, headers, .. } = Runner::<B>::extract_context(context)?; + let scope = parse_mcp_scopes(auth.scopes().unwrap_or(&[])) + .map_err(|e| ErrorData::internal_error(e, None))?; + if !admits(auth.scopes().unwrap_or(&[]), scope.all) { + return Err(ErrorData::invalid_request( + "This server needs an `mcp:all` token with no other route or path scope", + None, + )); + } + Ok(Caller { auth, mode, scope, origin: request_origin(&headers) }) + } + + async fn workspaces(&self, caller: &Caller<B::Auth>) -> Result<Vec<WorkspaceInfo>, ErrorData> { + let mut workspaces = self + .backend + .list_accessible_workspaces(&caller.auth) + .await?; + match &caller.mode { + McpMode::Single(bound) => workspaces.retain(|w| &w.id == bound), + McpMode::Multi(_) => workspaces.retain(|w| caller.scope.allows_workspace(&w.id)), + } + Ok(workspaces) + } + + /// The caller as they are in `workspace_id`, if the token reaches it. + async fn auth_in( + &self, + caller: &Caller<B::Auth>, + workspace_id: &str, + ) -> Result<B::Auth, ErrorData> { + match &caller.mode { + McpMode::Single(bound) if bound == workspace_id => Ok(caller.auth.clone()), + McpMode::Multi(token) if caller.scope.allows_workspace(workspace_id) => { + self.backend + .resolve_workspace_auth(token, workspace_id) + .await + } + _ => Err(workspace_not_granted(workspace_id)), + } + } + + async fn info_for( + &self, + context: &RequestContext<RoleServer>, + ) -> Result<ServerInfo, ErrorData> { + let caller = Self::caller(context)?; + let workspaces = self.workspaces(&caller).await?; + let instructions = match workspaces.as_slice() { + [only] => { + let auth = self.auth_in(&caller, &only.id).await?; + format!( + "Every tool takes a `workspace_id`: pass `{}`, the workspace this connection \ + works in.\n\n{}", + only.id, + self.backend.session_instructions(&auth, &only.id).await? + ) + } + _ => { + let mut listed = workspaces + .iter() + .take(MAX_LISTED_WORKSPACES) + .map(|w| format!("`{}` ({})", w.id, w.name)) + .collect::<Vec<_>>() + .join(", "); + if workspaces.len() > MAX_LISTED_WORKSPACES { + listed.push_str(&format!( + " (+{} more)", + workspaces.len() - MAX_LISTED_WORKSPACES + )); + } + format!( + "This connection works across several Windmill workspaces: {listed}. Every \ + tool takes a `workspace_id` naming the one it acts in; list_workspaces lists \ + them. Before your first action in a workspace, call get_workspace_context \ + with its id: it gives your username there (the `<username>` in the paths \ + below), the folders you can write to, and the workspace's skills and \ + instructions. When the user has not said which workspace, ask rather than \ + guess, and name the workspace whenever you change something.\n\n{}", + self.backend.generic_session_instructions() + ) + } + }; + Ok(self.get_info().with_instructions(instructions)) + } +} + +impl<B: McpBackend> ServerHandler for SessionRunner<B> { + /// Without instructions: those are built per caller, in `initialize` and `discover`. + fn get_info(&self) -> ServerInfo { + let server_info = Implementation::new("windmill", env!("CARGO_PKG_VERSION")) + .with_title("Windmill") + .with_website_url("https://windmill.dev"); + InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) + .with_server_info(server_info) + } + + fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> { + Cow::Borrowed(SUPPORTED_PROTOCOL_VERSIONS) + } + + async fn initialize( + &self, + request: InitializeRequestParams, + context: RequestContext<RoleServer>, + ) -> Result<InitializeResult, ErrorData> { + context.peer.set_peer_info(request.clone()); + let mut info = self.info_for(&context).await?; + if SUPPORTED_PROTOCOL_VERSIONS.contains(&request.protocol_version) { + info.protocol_version = request.protocol_version; + } + Ok(info) + } + + async fn discover( + &self, + context: RequestContext<RoleServer>, + ) -> Result<DiscoverResult, ErrorData> { + Ok(DiscoverResult::from_server_info( + SUPPORTED_PROTOCOL_VERSIONS.to_vec(), + self.info_for(&context).await?, + )) + } + + async fn list_tools( + &self, + _request: Option<PaginatedRequestParams>, + context: RequestContext<RoleServer>, + ) -> Result<ListToolsResult, ErrorData> { + let caller = Self::caller(&context)?; + let mut tools = vec![list_workspaces_tool()]; + // A bound token's one workspace is described in the instructions already. + if let McpMode::Multi(_) = caller.mode { + tools.push(get_workspace_context_tool()); + } + tools.extend( + self.backend + .session_tools(access(&caller.auth, &caller.scope)) + .into_iter() + .map(with_workspace_id_arg), + ); + // Without these a `2026-07-28` client rejects the whole listing. + Ok(ListToolsResult::with_all_items(tools) + .with_ttl_ms(LIST_TTL_MS) + .with_cache_scope(LIST_CACHE_SCOPE)) + } + + async fn call_tool( + &self, + request: CallToolRequestParams, + context: RequestContext<RoleServer>, + ) -> Result<CallToolResponse, ErrorData> { + let caller = Self::caller(&context)?; + if request.name == "list_workspaces" { + let workspaces = self.workspaces(&caller).await?; + return Ok(CallToolResult::success(vec![ContentBlock::text( + serde_json::to_string_pretty(&workspaces).unwrap_or_default(), + )]) + .into()); + } + let mut args = request.arguments.unwrap_or_default(); + let workspace_id = + match args.remove("workspace_id") { + Some(Value::String(w)) if !w.is_empty() => w, + _ => return Err(ErrorData::invalid_params( + "Missing required `workspace_id` argument. Call list_workspaces to see the \ + workspaces you can act in.", + None, + )), + }; + let auth = self.auth_in(&caller, &workspace_id).await?; + if request.name == GET_WORKSPACE_CONTEXT { + let text = self.backend.workspace_context(&auth, &workspace_id).await; + return Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into()); + } + let mut result = self + .backend + .call_session_tool( + &auth, + &workspace_id, + request.name.as_ref(), + Value::Object(args), + access(&auth, &caller.scope), + caller.origin.as_deref(), + ) + .await?; + for block in result.content.iter_mut() { + if let Some(text) = block.as_text() { + *block = ContentBlock::text(truncate_tool_result(text.text.clone())); + } + } + Ok(result.into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn origin_prefers_forwarded_headers() { + let mut headers = http::HeaderMap::new(); + headers.insert("host", "backend:8000".parse().unwrap()); + assert_eq!( + request_origin(&headers).as_deref(), + Some("http://backend:8000") + ); + headers.insert("x-forwarded-host", "wm.example.com, proxy".parse().unwrap()); + headers.insert("x-forwarded-proto", "https".parse().unwrap()); + assert_eq!( + request_origin(&headers).as_deref(), + Some("https://wm.example.com") + ); + } + + #[test] + fn only_an_unnarrowed_mcp_all_token_is_admitted() { + let admitted = |scopes: &[&str]| { + let scopes: Vec<String> = scopes.iter().map(|s| s.to_string()).collect(); + let all = parse_mcp_scopes(&scopes).is_ok_and(|c| c.all); + admits(&scopes, all) + }; + assert!(admitted(&["mcp:all"])); + assert!(admitted(&["mcp:all", "if_jobs:filter_tags:gpu"])); + assert!(admitted(&["mcp:all", "mcp:workspaces:dev"])); + assert!(!admitted(&["mcp:all", "variables:read:u/a/safe/*"])); + assert!(!admitted(&["mcp:all:f/x/*"])); + assert!(!admitted(&["mcp:favorites"])); + assert!(!admitted(&[])); + } +} diff --git a/backend/windmill-native-triggers/src/github/external.rs b/backend/windmill-native-triggers/src/github/external.rs index 2c23e02bef..6e34154df3 100644 --- a/backend/windmill-native-triggers/src/github/external.rs +++ b/backend/windmill-native-triggers/src/github/external.rs @@ -33,7 +33,7 @@ impl External for GitHub { async fn create( &self, w_id: &str, - _oauth_data: &Self::OAuthData, + oauth_data: &Self::OAuthData, webhook_token: &str, data: &NativeTriggerData<Self::ServiceConfig>, db: &DB, @@ -69,7 +69,15 @@ impl External for GitHub { }); let response: CreateWebhookResponse = self - .http_client_request(&url, Method::POST, w_id, db, None, Some(&payload)) + .http_client_request( + &url, + Method::POST, + w_id, + &oauth_data.connection_path, + db, + None, + Some(&payload), + ) .await?; Ok(response) @@ -78,7 +86,7 @@ impl External for GitHub { async fn update( &self, w_id: &str, - _oauth_data: &Self::OAuthData, + oauth_data: &Self::OAuthData, external_id: &str, webhook_token: &str, data: &NativeTriggerData<Self::ServiceConfig>, @@ -114,7 +122,15 @@ impl External for GitHub { }); let _: serde_json::Value = self - .http_client_request(&url, Method::PATCH, w_id, db, None, Some(&payload)) + .http_client_request( + &url, + Method::PATCH, + w_id, + &oauth_data.connection_path, + db, + None, + Some(&payload), + ) .await?; // Return the resolved service_config @@ -125,7 +141,7 @@ impl External for GitHub { async fn get( &self, w_id: &str, - _oauth_data: &Self::OAuthData, + oauth_data: &Self::OAuthData, external_id: &str, db: &DB, _tx: &mut PgConnection, @@ -137,7 +153,14 @@ impl External for GitHub { }; let data = self - .get_webhook(w_id, &owner, &repo, external_id, db) + .get_webhook( + w_id, + &oauth_data.connection_path, + &owner, + &repo, + external_id, + db, + ) .await?; Ok(Some(data)) } @@ -145,7 +168,7 @@ impl External for GitHub { async fn delete( &self, w_id: &str, - _oauth_data: &Self::OAuthData, + oauth_data: &Self::OAuthData, external_id: &str, db: &DB, _tx: &mut PgConnection, @@ -165,7 +188,15 @@ impl External for GitHub { // Swallow 404 only (webhook may already be deleted on GitHub); propagate // other errors so callers don't think cleanup succeeded when it didn't. let result: std::result::Result<serde_json::Value, _> = self - .http_client_request::<_, ()>(&url, Method::DELETE, w_id, db, None, None) + .http_client_request::<_, ()>( + &url, + Method::DELETE, + w_id, + &oauth_data.connection_path, + db, + None, + None, + ) .await; match result { @@ -180,7 +211,7 @@ impl External for GitHub { db: &DB, workspace_id: &str, triggers: &[NativeTrigger], - _oauth_data: &Self::OAuthData, + oauth_data: &Self::OAuthData, synced: &mut Vec<crate::sync::TriggerSyncInfo>, errors: &mut Vec<crate::sync::SyncError>, ) { @@ -208,7 +239,15 @@ impl External for GitHub { ); let result: std::result::Result<GithubWebhookApiResponse, _> = self - .http_client_request::<_, ()>(&url, Method::GET, workspace_id, db, None, None) + .http_client_request::<_, ()>( + &url, + Method::GET, + workspace_id, + &oauth_data.connection_path, + db, + None, + None, + ) .await; match result { @@ -295,7 +334,7 @@ impl External for GitHub { fn error_hint(&self, status: StatusCode) -> Option<&'static str> { match status { StatusCode::UNAUTHORIZED => { - Some("reconnect the GitHub integration from Workspace settings > Integrations.") + Some("reconnect the GitHub account this uses with Reconnect next to it, or ask its owner or an admin to.") } StatusCode::FORBIDDEN => Some( "check that the OAuth app is authorized for the organization and that the \ @@ -363,6 +402,7 @@ impl GitHub { async fn get_webhook( &self, w_id: &str, + connection_path: &str, owner: &str, repo: &str, external_id: &str, @@ -374,7 +414,7 @@ impl GitHub { ); let response: GithubWebhookApiResponse = self - .http_client_request::<_, ()>(&url, Method::GET, w_id, db, None, None) + .http_client_request::<_, ()>(&url, Method::GET, w_id, connection_path, db, None, None) .await?; Ok(GithubTriggerData { diff --git a/backend/windmill-native-triggers/src/github/mod.rs b/backend/windmill-native-triggers/src/github/mod.rs index d01fa0020b..45d0ebf257 100644 --- a/backend/windmill-native-triggers/src/github/mod.rs +++ b/backend/windmill-native-triggers/src/github/mod.rs @@ -17,6 +17,7 @@ pub struct GithubOAuthData { pub access_token: String, pub refresh_token: Option<String>, pub token_expires_at: Option<chrono::DateTime<chrono::Utc>>, + pub connection_path: String, } /// User-provided configuration for a GitHub webhook trigger. diff --git a/backend/windmill-native-triggers/src/github/routes.rs b/backend/windmill-native-triggers/src/github/routes.rs index 68de93b6a9..8a20d72693 100644 --- a/backend/windmill-native-triggers/src/github/routes.rs +++ b/backend/windmill-native-triggers/src/github/routes.rs @@ -1,14 +1,15 @@ use std::sync::Arc; -use axum::{extract::Path, routing::get, Extension, Json, Router}; +use axum::{ + extract::{Path, Query}, + routing::get, + Extension, Json, Router, +}; use http::Method; use windmill_api_auth::ApiAuthed; -use windmill_common::{error::JsonResult, DB}; +use windmill_common::{db::UserDB, error::JsonResult, DB}; -use crate::{ - get_workspace_integration, map_external_error, require_native_integration_use, External, - ServiceName, -}; +use crate::{map_external_error, picker_connection, ConnectionQuery, External, ServiceName}; use super::{GitHub, GithubApiRepoResponse, GithubRepoEntry}; @@ -19,10 +20,19 @@ async fn list_repos( authed: ApiAuthed, Extension(handler): Extension<Arc<GitHub>>, Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, Path(workspace_id): Path<String>, + Query(query): Query<ConnectionQuery>, ) -> JsonResult<Vec<GithubRepoEntry>> { - require_native_integration_use(&authed)?; - get_workspace_integration(&db, &workspace_id, ServiceName::Github).await?; + let connection_path = picker_connection( + &authed, + &db, + user_db, + &workspace_id, + ServiceName::Github, + query.connection_path.as_deref(), + ) + .await?; let mut all_entries = Vec::new(); @@ -35,7 +45,15 @@ async fn list_repos( ); let repos: Vec<GithubApiRepoResponse> = handler - .http_client_request::<_, ()>(&url, Method::GET, &workspace_id, &db, None, None) + .http_client_request::<_, ()>( + &url, + Method::GET, + &workspace_id, + &connection_path, + &db, + None, + None, + ) .await .map_err(map_external_error)?; diff --git a/backend/windmill-native-triggers/src/google/external.rs b/backend/windmill-native-triggers/src/google/external.rs index 1c5a2dd9ec..a456a0a0bb 100644 --- a/backend/windmill-native-triggers/src/google/external.rs +++ b/backend/windmill-native-triggers/src/google/external.rs @@ -42,7 +42,7 @@ impl External for Google { async fn create( &self, w_id: &str, - _oauth_data: &Self::OAuthData, + oauth_data: &Self::OAuthData, webhook_token: &str, data: &NativeTriggerData<Self::ServiceConfig>, db: &DB, @@ -51,8 +51,16 @@ impl External for Google { // At creation time, channel_id also becomes the trigger's external_id // (see external_id_and_metadata_from_response). let channel_id = uuid::Uuid::new_v4().to_string(); - self.create_watch_channel(w_id, &channel_id, &channel_id, webhook_token, data, db) - .await + self.create_watch_channel( + w_id, + &oauth_data.connection_path, + &channel_id, + &channel_id, + webhook_token, + data, + db, + ) + .await } async fn update( @@ -72,7 +80,15 @@ impl External for Google { // external_id stays the stable routing key used in the webhook URL. let channel_id = uuid::Uuid::new_v4().to_string(); let resp = self - .create_watch_channel(w_id, external_id, &channel_id, webhook_token, data, db) + .create_watch_channel( + w_id, + &oauth_data.connection_path, + external_id, + &channel_id, + webhook_token, + data, + db, + ) .await?; self.service_config_from_create_response(data, &resp) @@ -86,7 +102,7 @@ impl External for Google { async fn delete( &self, w_id: &str, - _oauth_data: &Self::OAuthData, + oauth_data: &Self::OAuthData, external_id: &str, db: &DB, tx: &mut PgConnection, @@ -122,7 +138,15 @@ impl External for Google { // Stop the channel (ignore errors - channel may have already expired) let result: std::result::Result<serde_json::Value, _> = self - .http_client_request(&url, Method::POST, w_id, db, None, Some(&stop_request)) + .http_client_request( + &url, + Method::POST, + w_id, + &oauth_data.connection_path, + db, + None, + Some(&stop_request), + ) .await; if let Err(e) = result { @@ -203,7 +227,7 @@ impl External for Google { fn error_hint(&self, status: http::StatusCode) -> Option<&'static str> { match status { http::StatusCode::UNAUTHORIZED => { - Some("reconnect the Google integration from Workspace settings > Integrations.") + Some("reconnect the Google account this uses with Reconnect next to it, or ask its owner or an admin to.") } http::StatusCode::FORBIDDEN => Some( "the connected Google account is missing access to this resource or the scope the \ @@ -231,6 +255,7 @@ impl Google { async fn create_watch_channel( &self, w_id: &str, + connection_path: &str, external_id: &str, channel_id: &str, webhook_token: &str, @@ -263,12 +288,24 @@ impl Google { match data.service_config.trigger_type { GoogleTriggerType::Drive => { - self.create_drive_watch(w_id, &data.service_config, &watch_request, db) - .await + self.create_drive_watch( + w_id, + connection_path, + &data.service_config, + &watch_request, + db, + ) + .await } GoogleTriggerType::Calendar => { - self.create_calendar_watch(w_id, &data.service_config, &watch_request, db) - .await + self.create_calendar_watch( + w_id, + connection_path, + &data.service_config, + &watch_request, + db, + ) + .await } } } @@ -276,6 +313,7 @@ impl Google { async fn create_drive_watch( &self, w_id: &str, + connection_path: &str, config: &GoogleServiceConfig, watch_request: &WatchRequest, db: &DB, @@ -285,14 +323,30 @@ impl Google { // Specific file: use files.watch let url = format!("{}/files/{}/watch", endpoints::DRIVE_API_BASE, resource_id); - self.http_client_request(&url, Method::POST, w_id, db, None, Some(watch_request)) - .await + self.http_client_request( + &url, + Method::POST, + w_id, + connection_path, + db, + None, + Some(watch_request), + ) + .await } None => { // All changes: use changes.watch let token_url = format!("{}/changes/startPageToken", endpoints::DRIVE_API_BASE); let token_response: serde_json::Value = self - .http_client_request::<_, ()>(&token_url, Method::GET, w_id, db, None, None) + .http_client_request::<_, ()>( + &token_url, + Method::GET, + w_id, + connection_path, + db, + None, + None, + ) .await?; let start_page_token = token_response @@ -313,6 +367,7 @@ impl Google { &watch_url, Method::POST, w_id, + connection_path, db, None, Some(&watch_body), @@ -325,6 +380,7 @@ impl Google { async fn create_calendar_watch( &self, w_id: &str, + connection_path: &str, config: &GoogleServiceConfig, watch_request: &WatchRequest, db: &DB, @@ -339,8 +395,16 @@ impl Google { urlencoding::encode(calendar_id) ); - self.http_client_request(&url, Method::POST, w_id, db, None, Some(watch_request)) - .await + self.http_client_request( + &url, + Method::POST, + w_id, + connection_path, + db, + None, + Some(watch_request), + ) + .await } /// Renew an expiring Google watch channel. @@ -362,6 +426,12 @@ impl Google { .map(|v| serde_json::from_value(v.clone())) .transpose()? .ok_or_else(|| Error::InternalErr("Missing service config".to_string()))?; + let connection_path = trigger.connection_path.as_deref().ok_or_else(|| { + Error::BadRequest(format!( + "Cannot renew channel {}: the trigger has no Google connection", + trigger.external_id + )) + })?; let rotated = match crate::rotate_webhook_token( db, @@ -430,7 +500,15 @@ impl Google { } }; let result: std::result::Result<serde_json::Value, _> = self - .http_client_request(&url, Method::POST, w_id, db, None, Some(&stop_request)) + .http_client_request( + &url, + Method::POST, + w_id, + connection_path, + db, + None, + Some(&stop_request), + ) .await; if let Err(e) = result { tracing::warn!( @@ -444,11 +522,11 @@ impl Google { // Create new watch channel with a fresh channel ID let resp = match config.trigger_type { GoogleTriggerType::Drive => { - self.create_drive_watch(w_id, &config, &watch_request, db) + self.create_drive_watch(w_id, connection_path, &config, &watch_request, db) .await? } GoogleTriggerType::Calendar => { - self.create_calendar_watch(w_id, &config, &watch_request, db) + self.create_calendar_watch(w_id, connection_path, &config, &watch_request, db) .await? } }; diff --git a/backend/windmill-native-triggers/src/google/mod.rs b/backend/windmill-native-triggers/src/google/mod.rs index 5bd07e5dab..4e8e398cc7 100644 --- a/backend/windmill-native-triggers/src/google/mod.rs +++ b/backend/windmill-native-triggers/src/google/mod.rs @@ -134,6 +134,7 @@ pub struct GoogleOAuthData { pub refresh_token: Option<String>, /// When the access token expires pub token_expires_at: Option<chrono::DateTime<chrono::Utc>>, + pub connection_path: String, } /// Google API endpoints diff --git a/backend/windmill-native-triggers/src/google/routes.rs b/backend/windmill-native-triggers/src/google/routes.rs index 306a7e54e2..dec2010ab2 100644 --- a/backend/windmill-native-triggers/src/google/routes.rs +++ b/backend/windmill-native-triggers/src/google/routes.rs @@ -10,10 +10,9 @@ use serde::{Deserialize, Serialize}; use windmill_api_auth::ApiAuthed; use windmill_common::{error::JsonResult, DB}; -use crate::{ - get_workspace_integration, map_external_error, require_native_integration_use, External, - ServiceName, -}; +use windmill_common::db::UserDB; + +use crate::{map_external_error, picker_connection, ConnectionQuery, External, ServiceName}; use super::Google; @@ -85,16 +84,26 @@ pub struct DriveFilesQuery { pub page_token: Option<String>, #[serde(default)] pub shared_with_me: bool, + pub connection_path: Option<String>, } async fn list_calendars( authed: ApiAuthed, Extension(handler): Extension<Arc<Google>>, Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, Path(workspace_id): Path<String>, + Query(query): Query<ConnectionQuery>, ) -> JsonResult<Vec<GoogleCalendarEntry>> { - require_native_integration_use(&authed)?; - get_workspace_integration(&db, &workspace_id, ServiceName::Google).await?; + let connection_path = picker_connection( + &authed, + &db, + user_db, + &workspace_id, + ServiceName::Google, + query.connection_path.as_deref(), + ) + .await?; let url = format!( "{}/users/me/calendarList", @@ -102,7 +111,15 @@ async fn list_calendars( ); let response: GoogleCalendarListResponse = handler - .http_client_request::<_, ()>(&url, Method::GET, &workspace_id, &db, None, None) + .http_client_request::<_, ()>( + &url, + Method::GET, + &workspace_id, + &connection_path, + &db, + None, + None, + ) .await .map_err(map_external_error)?; @@ -123,11 +140,19 @@ async fn list_drive_files( authed: ApiAuthed, Extension(handler): Extension<Arc<Google>>, Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, Path(workspace_id): Path<String>, Query(query): Query<DriveFilesQuery>, ) -> JsonResult<GoogleDriveFilesResponse> { - require_native_integration_use(&authed)?; - get_workspace_integration(&db, &workspace_id, ServiceName::Google).await?; + let connection_path = picker_connection( + &authed, + &db, + user_db, + &workspace_id, + ServiceName::Google, + query.connection_path.as_deref(), + ) + .await?; let drive_query = if query.shared_with_me { "sharedWithMe = true and trashed = false".to_string() @@ -156,7 +181,15 @@ async fn list_drive_files( } let response: DriveApiResponse = handler - .http_client_request::<_, ()>(&url, Method::GET, &workspace_id, &db, None, None) + .http_client_request::<_, ()>( + &url, + Method::GET, + &workspace_id, + &connection_path, + &db, + None, + None, + ) .await .map_err(map_external_error)?; @@ -199,10 +232,19 @@ async fn list_shared_drives( authed: ApiAuthed, Extension(handler): Extension<Arc<Google>>, Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, Path(workspace_id): Path<String>, + Query(query): Query<ConnectionQuery>, ) -> JsonResult<Vec<SharedDriveEntry>> { - require_native_integration_use(&authed)?; - get_workspace_integration(&db, &workspace_id, ServiceName::Google).await?; + let connection_path = picker_connection( + &authed, + &db, + user_db, + &workspace_id, + ServiceName::Google, + query.connection_path.as_deref(), + ) + .await?; let url = format!( "{}/drives?pageSize=100&fields=drives(id,name)", @@ -210,7 +252,15 @@ async fn list_shared_drives( ); let response: SharedDrivesApiResponse = handler - .http_client_request::<_, ()>(&url, Method::GET, &workspace_id, &db, None, None) + .http_client_request::<_, ()>( + &url, + Method::GET, + &workspace_id, + &connection_path, + &db, + None, + None, + ) .await .map_err(map_external_error)?; diff --git a/backend/windmill-native-triggers/src/handler.rs b/backend/windmill-native-triggers/src/handler.rs index 2c785a4e26..c920c48195 100644 --- a/backend/windmill-native-triggers/src/handler.rs +++ b/backend/windmill-native-triggers/src/handler.rs @@ -1,8 +1,9 @@ use crate::{ classify_read_failure, decrypt_oauth_data, delete_native_trigger, delete_token_by_hash, - get_native_trigger, list_native_triggers, lock::TriggerLock, map_external_error, - map_external_error_with, rotate_webhook_token, set_native_trigger_enabled, - store_native_trigger, sync::EXTERNAL_TRIGGER_MISSING_ERROR, update_native_trigger_error, + get_native_trigger, list_native_triggers, list_usable_connections, lock::TriggerLock, + lock_connection, map_external_error, map_external_error_with, resolve_usable_connection, + rotate_webhook_token, set_native_trigger_enabled, store_native_trigger, + sync::EXTERNAL_TRIGGER_MISSING_ERROR, update_native_trigger_error, update_native_trigger_if_runnable_unchanged, webhook_token_label, webhook_token_scopes, External, ExternalReadFailure, NativeTrigger, NativeTriggerConfig, NativeTriggerData, ServiceName, @@ -187,9 +188,21 @@ async fn create_native_trigger<T: External>( ) .await?; - let integration_service = service_name.integration_service(); - let oauth_data: T::OAuthData = - decrypt_oauth_data(&db, &workspace_id, integration_service).await?; + let connection_path = resolve_usable_connection( + &db, + &mut tx, + &workspace_id, + service_name.integration_service(), + data.connection_path.as_deref(), + ) + .await?; + let oauth_data: T::OAuthData = decrypt_oauth_data( + &db, + &workspace_id, + service_name.integration_service(), + Some(&connection_path), + ) + .await?; let resp = handler .create( @@ -232,6 +245,23 @@ async fn create_native_trigger<T: External>( webhook_token, }; + lock_connection(&mut tx, &workspace_id, &connection_path).await?; + // Through `db`: a member using the workspace connection cannot read its variable. + let still_connected = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2)", + workspace_id, + connection_path, + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if !still_connected { + return Err(Error::BadRequest(format!( + "{connection_path} was disconnected while this trigger was being created. Its \ + registration on {service_name} may remain; connect an account and create it again." + ))); + } + store_native_trigger( &mut *tx, &workspace_id, @@ -241,6 +271,7 @@ async fn create_native_trigger<T: External>( service_config, data.summary.as_deref(), data.enabled, + &connection_path, ) .await?; @@ -282,10 +313,6 @@ async fn update_native_trigger_handler<T: External>( .await?; require_runnable_exists(&db, &workspace_id, &data.script_path, data.is_flow).await?; - let integration_service = service_name.integration_service(); - let oauth_data: T::OAuthData = - decrypt_oauth_data(&db, &workspace_id, integration_service).await?; - let lock = TriggerLock::acquire(&db, &workspace_id, service_name, &external_id).await?; let mut tx = user_db.clone().begin(&authed).await?; @@ -294,6 +321,21 @@ async fn update_native_trigger_handler<T: External>( .await? .ok_or_else(|| Error::NotFound(format!("Native trigger not found: {}", external_id)))?; + // Saving re-registers the webhook as the connection's account, so the editor must be allowed + // to act as it, not just to write the runnable. + let integration_service = service_name.integration_service(); + if let Some(path) = existing.connection_path.as_deref() { + resolve_usable_connection(&db, &mut tx, &workspace_id, integration_service, Some(path)) + .await?; + } + let oauth_data: T::OAuthData = decrypt_oauth_data( + &db, + &workspace_id, + integration_service, + existing.connection_path.as_deref(), + ) + .await?; + let runnable_changed = existing.script_path != data.script_path || existing.is_flow != data.is_flow; @@ -446,9 +488,38 @@ async fn get_native_trigger_handler<T: External>( ) .await?; - let integration_service = service_name.integration_service(); - let oauth_data: T::OAuthData = - decrypt_oauth_data(&db, &workspace_id, integration_service).await?; + // Reading the registration acts as the connection's account, like saving does. + let usable = match windmill_trigger.connection_path.as_deref() { + Some(path) => list_usable_connections( + &db, + &mut tx, + &workspace_id, + service_name.integration_service(), + ) + .await? + .iter() + .any(|c| c.path == path), + None => false, + }; + if !usable { + tx.commit().await?; + return Ok(Json(FullTriggerResponse { + windmill_data: windmill_trigger, + external_data: None, + external_error: Some(format!( + "You cannot use this trigger's {service_name} connection, so its registration was \ + not read." + )), + })); + } + + let oauth_data: T::OAuthData = decrypt_oauth_data( + &db, + &workspace_id, + service_name.integration_service(), + windmill_trigger.connection_path.as_deref(), + ) + .await?; let native_trigger = handler .get(&workspace_id, &oauth_data, &external_id, &db, &mut tx) @@ -554,23 +625,35 @@ async fn delete_native_trigger_handler<T: External>( ) .await?; - let integration_service = service_name.integration_service(); - let oauth_data: T::OAuthData = - decrypt_oauth_data(&db, &workspace_id, integration_service).await?; - - handler - .delete(&workspace_id, &oauth_data, &external_id, &db, &mut tx) - .await - .map_err(|e| { - map_external_error_with(e, |m| { - let end = if m.ends_with(['.', '!', '?']) { - "" - } else { - "." - }; - format!("{m}{end} The trigger was kept in Windmill, so it can still fire.") - }) - })?; + // A connection can be deleted from under its triggers. Without it the registration cannot be + // removed, but deleting the row still revokes the webhook token, so the service's deliveries + // stop starting jobs; refusing would leave a trigger nobody can remove. + match decrypt_oauth_data::<T::OAuthData>( + &db, + &workspace_id, + service_name.integration_service(), + existing.connection_path.as_deref(), + ) + .await + { + Ok(oauth_data) => handler + .delete(&workspace_id, &oauth_data, &external_id, &db, &mut tx) + .await + .map_err(|e| { + map_external_error_with(e, |m| { + let end = if m.ends_with(['.', '!', '?']) { + "" + } else { + "." + }; + format!("{m}{end} The trigger was kept in Windmill, so it can still fire.") + }) + })?, + Err(e @ (Error::NotFound(_) | Error::BadRequest(_))) => tracing::warn!( + "Deleting {service_name} trigger {external_id} without removing its registration: {e}" + ), + Err(e) => return Err(e), + } let deleted = delete_native_trigger(&mut *tx, &workspace_id, service_name, &external_id).await?; diff --git a/backend/windmill-native-triggers/src/lib.rs b/backend/windmill-native-triggers/src/lib.rs index 6398e8a6d9..4a8560d9f0 100644 --- a/backend/windmill-native-triggers/src/lib.rs +++ b/backend/windmill-native-triggers/src/lib.rs @@ -45,6 +45,7 @@ use std::{collections::HashMap, fmt::Debug}; use strum::{EnumIter, IntoEnumIterator}; use tokio::task; use windmill_common::{ + db::UserDB, error::{to_anyhow, Error, Result}, triggers::TriggerKind, utils::HTTP_CLIENT, @@ -230,6 +231,9 @@ pub struct NativeTrigger { /// its initial value and `setenabled` is its only mutator afterwards, so saving a /// configuration can never silently re-enable a trigger someone paused. pub enabled: bool, + /// Path of the connection (the OAuth resource created by the connect flow) the trigger acts + /// through on the external service. + pub connection_path: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -253,6 +257,11 @@ pub struct NativeTriggerData<C> { /// An update ignores it: `setenabled` is the only way to change an existing trigger's state. #[serde(default = "default_true")] pub enabled: bool, + /// Honoured on create only: the webhook is registered under this connection's account, so + /// switching it would leave the registration owned by an account the trigger no longer uses. + /// When omitted, the caller's only readable connection for the service is used. + #[serde(default)] + pub connection_path: Option<String>, } #[derive(Debug, Clone, FromRow, Serialize, Deserialize)] @@ -260,7 +269,6 @@ pub struct WorkspaceIntegration { pub workspace_id: String, pub service_name: ServiceName, pub oauth_data: serde_json::Value, - pub resource_path: Option<String>, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub created_by: String, @@ -399,12 +407,18 @@ pub trait External: Send + Sync + 'static { url: &str, method: Method, workspace_id: &str, + connection_path: &str, db: &DB, headers: Option<HashMap<String, String>>, body: Option<&B>, ) -> Result<T> { - let oauth_config: OAuthConfig = - decrypt_oauth_data(db, workspace_id, Self::SERVICE_NAME).await?; + let oauth_config: OAuthConfig = decrypt_oauth_data( + db, + workspace_id, + Self::SERVICE_NAME.integration_service(), + Some(connection_path), + ) + .await?; let result = make_http_request( url, @@ -446,14 +460,14 @@ pub trait External: Send + Sync + 'static { task::spawn({ let db_clone = db.clone(); let workspace_id_clone = workspace_id.to_string(); - let service_name = Self::SERVICE_NAME; + let account_id = refreshed_oauth_config.account_id; let new_access_token = refreshed_oauth_config.access_token.clone(); let new_refresh_token = refreshed_oauth_config.refresh_token.clone(); async move { update_oauth_token_resource( &db_clone, &workspace_id_clone, - service_name, + account_id, &new_access_token, new_refresh_token.as_deref(), ) @@ -594,6 +608,8 @@ pub struct OAuthConfig { pub refresh_token: Option<String>, pub client_id: String, pub client_secret: String, + pub connection_path: String, + pub account_id: i32, } pub async fn make_http_request<T: DeserializeOwned + Send, B: Serialize>( @@ -776,51 +792,50 @@ async fn get_instance_oauth_credentials( .await } +/// Assemble the credentials of one connection: its token from the variable and account at +/// `connection_path`, and the OAuth client from the workspace (or instance) configuration. +/// +/// Only an account made by the connect flow is accepted, since token refresh goes through this +/// service's OAuth client and any other account would be refreshed against the wrong one. pub async fn decrypt_oauth_data<T: DeserializeOwned>( db: &DB, workspace_id: &str, service_name: ServiceName, + connection_path: Option<&str>, ) -> Result<T> { - let integration = get_workspace_integration(db, workspace_id, service_name).await?; - let oauth_data = integration.oauth_data; - - let resource_path = integration.resource_path.as_deref().ok_or_else(|| { - Error::InternalErr(format!( - "No resource_path in {} integration config. Please reconnect the integration.", - service_name + let connection_path = connection_path.ok_or_else(|| { + Error::BadRequest(format!( + "This trigger has no {service_name} connection. Delete it and create it again with a connection." )) })?; + let integration = get_workspace_integration(db, workspace_id, service_name).await?; + let oauth_data = integration.oauth_data; + let mc = build_crypt(db, workspace_id).await?; - let var_row = sqlx::query!( - "SELECT value, account FROM variable WHERE workspace_id = $1 AND path = $2", + let row = sqlx::query!( + "SELECT v.value::text AS \"value!\", a.id AS account_id, a.refresh_token + FROM variable v + JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account + WHERE v.workspace_id = $1 AND v.path = $2 + AND a.client = $3 AND a.is_workspace_integration = true", workspace_id, - resource_path, + connection_path, + service_name.as_str(), ) .fetch_optional(db) .await? .ok_or_else(|| { - Error::InternalErr(format!( - "Variable at {} not found for {} integration", - resource_path, service_name + Error::NotFound(format!( + "No {service_name} connection at {connection_path}. Connect an account there or pick another connection." )) })?; - let access_token = decrypt(&mc, var_row.value) + let access_token = decrypt(&mc, row.value) .map_err(|e| Error::InternalErr(format!("Failed to decrypt access token: {}", e)))?; - let refresh_token = if let Some(account_id) = var_row.account { - sqlx::query_scalar!( - "SELECT refresh_token FROM account WHERE workspace_id = $1 AND id = $2", - workspace_id, - account_id, - ) - .fetch_optional(db) - .await? - } else { - None - }; + let refresh_token = Some(row.refresh_token); let (client_id, client_secret) = if oauth_data .get("instance_shared") @@ -853,6 +868,8 @@ pub async fn decrypt_oauth_data<T: DeserializeOwned>( "refresh_token": refresh_token, "client_id": client_id, "client_secret": client_secret, + "connection_path": connection_path, + "account_id": row.account_id, }); serde_json::from_value(assembled) @@ -978,6 +995,8 @@ pub async fn refresh_oauth_tokens( .or_else(|| oauth_config.refresh_token.clone()), client_id: oauth_config.client_id.clone(), client_secret: oauth_config.client_secret.clone(), + connection_path: oauth_config.connection_path.clone(), + account_id: oauth_config.account_id, }) } @@ -994,61 +1013,48 @@ pub async fn refresh_oauth_tokens( }) } -async fn update_oauth_token_resource( +/// Write a refreshed token back to the account it was refreshed from, by that account's id, never +/// by service or path: several connections share a service, and a connection's path can be +/// reconnected or renamed while the refresh is in flight. A provider that rotates refresh tokens +/// invalidates the old one, so writing it onto another account would break that account's next +/// refresh. +/// +/// No authorization happens here: it overwrites the account's secrets as the server. Call it only +/// with tokens just refreshed from that account's own refresh token. +pub async fn update_oauth_token_resource( db: &DB, workspace_id: &str, - service_name: ServiceName, + account_id: i32, new_access_token: &str, new_refresh_token: Option<&str>, ) { let result = async { - let integration = get_workspace_integration(db, workspace_id, service_name).await?; - let resource_path = integration.resource_path.ok_or_else(|| { - Error::InternalErr(format!( - "No resource_path in {} integration config", - service_name - )) - })?; - let mc = build_crypt(db, workspace_id).await?; let encrypted_token = encrypt(&mc, new_access_token); sqlx::query!( - "UPDATE variable SET value = $1 WHERE workspace_id = $2 AND path = $3", + "UPDATE variable SET value = $1 WHERE workspace_id = $2 AND account = $3", encrypted_token, workspace_id, - resource_path, + account_id, ) .execute(db) .await?; - if let Some(refresh_token) = new_refresh_token { - sqlx::query!( - "UPDATE account SET - refresh_token = $1, - expires_at = now() + interval '1 hour', - refresh_error = NULL - WHERE workspace_id = $2 AND client = $3 AND is_workspace_integration = true", - refresh_token, - workspace_id, - service_name.as_str(), - ) - .execute(db) - .await?; - } else { - // Even without a new refresh token, update expires_at to prevent - // the background refresh from re-refreshing immediately - sqlx::query!( - "UPDATE account SET - expires_at = now() + interval '1 hour', - refresh_error = NULL - WHERE workspace_id = $1 AND client = $2 AND is_workspace_integration = true", - workspace_id, - service_name.as_str(), - ) - .execute(db) - .await?; - } + // Even without a new refresh token, expires_at moves so the background refresh does not + // re-refresh immediately. + sqlx::query!( + "UPDATE account SET + refresh_token = COALESCE($1, refresh_token), + expires_at = now() + interval '1 hour', + refresh_error = NULL + WHERE workspace_id = $2 AND id = $3", + new_refresh_token, + workspace_id, + account_id, + ) + .execute(db) + .await?; Ok::<(), Error>(()) } @@ -1056,8 +1062,8 @@ async fn update_oauth_token_resource( if let Err(e) = result { tracing::error!( - "Failed to update OAuth tokens for {} in workspace {}: {}", - service_name, + "Failed to update OAuth tokens of account {} in workspace {}: {}", + account_id, workspace_id, e ); @@ -1183,6 +1189,8 @@ pub async fn delete_token_by_hash<'c, E: sqlx::Executor<'c, Database = Postgres> Ok(deleted > 0) } +/// Callers must hold [`lock_connection`] on `connection_path` in the same transaction and check +/// the connection still exists, or a concurrent disconnect can leave this trigger stranded. pub async fn store_native_trigger<'c, E: sqlx::Executor<'c, Database = Postgres>, C: Serialize>( db: E, workspace_id: &str, @@ -1192,6 +1200,7 @@ pub async fn store_native_trigger<'c, E: sqlx::Executor<'c, Database = Postgres> service_config: C, summary: Option<&str>, enabled: bool, + connection_path: &str, ) -> Result<()> { use windmill_common::auth::hash_token; @@ -1211,12 +1220,13 @@ pub async fn store_native_trigger<'c, E: sqlx::Executor<'c, Database = Postgres> webhook_token_hash, service_config, summary, - enabled + enabled, + connection_path ) VALUES ( - $1, $2, $3, $4, $5, $6, $7, $8, $9 + $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 ) ON CONFLICT (external_id, workspace_id, service_name) - DO UPDATE SET script_path = $4, is_flow = $5, webhook_token_hash = $6, service_config = $7, summary = $8, error = NULL, updated_at = NOW() + DO UPDATE SET script_path = $4, is_flow = $5, webhook_token_hash = $6, service_config = $7, summary = $8, connection_path = $10, error = NULL, updated_at = NOW() "#, external_id, workspace_id, @@ -1227,6 +1237,7 @@ pub async fn store_native_trigger<'c, E: sqlx::Executor<'c, Database = Postgres> sqlx::types::Json(service_config) as _, summary, enabled, + connection_path, ) .execute(db) .await?; @@ -1424,7 +1435,8 @@ pub async fn get_native_trigger<'c, E: sqlx::Executor<'c, Database = Postgres>>( created_at, updated_at, summary, - enabled + enabled, + connection_path FROM native_trigger WHERE @@ -1464,7 +1476,8 @@ pub async fn get_native_trigger_by_script<'c, E: sqlx::Executor<'c, Database = P created_at, updated_at, summary, - enabled + enabled, + connection_path FROM native_trigger WHERE @@ -1520,7 +1533,8 @@ pub async fn list_native_triggers<'c, E: sqlx::Executor<'c, Database = Postgres> nt.created_at, nt.updated_at, nt.summary, - nt.enabled + nt.enabled, + nt.connection_path FROM native_trigger nt WHERE @@ -1699,7 +1713,6 @@ pub async fn store_workspace_integration( workspace_id: &str, service_name: ServiceName, oauth_data: serde_json::Value, - resource_path: Option<&str>, ) -> Result<()> { sqlx::query!( r#" @@ -1707,23 +1720,20 @@ pub async fn store_workspace_integration( workspace_id, service_name, oauth_data, - resource_path, created_by, created_at, updated_at ) VALUES ( - $1, $2, $3, $4, $5, now(), now() + $1, $2, $3, $4, now(), now() ) ON CONFLICT (workspace_id, service_name) DO UPDATE SET oauth_data = $3, - resource_path = $4, updated_at = now() "#, workspace_id, service_name as ServiceName, oauth_data, - resource_path, authed.username, ) .execute(&mut *tx) @@ -1732,20 +1742,157 @@ pub async fn store_workspace_integration( Ok(()) } -/// Authorization gate for the integration *use* routes (calendar/drive/repo/event -/// pickers). A workspace admin configures the integration, but any member who can -/// create a native trigger needs the pickers to configure one. Operators are -/// read-only and cannot create triggers, so they must not be able to drive the -/// admin-configured integration's upstream API and enumerate its data. -pub fn require_native_integration_use(authed: &ApiAuthed) -> Result<()> { - if authed.is_operator { - return Err(Error::NotAuthorized( - "Operators cannot use workspace integrations".to_string(), - )); +/// Authorization gate for the integration *use* routes (connecting an account, and the +/// calendar/drive/repo/event pickers). They drive a connected account's upstream API and +/// enumerate its data, so they need both the right to manage triggers and the right to write +/// code: a role that only manages triggers (the default `operator`) must not browse a shared +/// account's Drive or repos. +pub async fn require_native_integration_use(db: &DB, w_id: &str, authed: &ApiAuthed) -> Result<()> { + let caps = windmill_common::roles::caller_capabilities(db, w_id, authed).await?; + if caps.code && caps.manage_triggers { + Ok(()) + } else { + Err(Error::PermissionDenied( + "Your role cannot use this workspace's native trigger integrations".to_string(), + )) } +} + +#[derive(Debug, Serialize)] +pub struct Connection { + pub path: String, + /// Username of whoever connected the account, when the caller can read its resource. + pub owner: Option<String>, + /// The workspace connection, which every member may use. + pub workspace: bool, +} + +/// The connections of a service the caller may use. `tx` must be a user transaction: using a +/// connection means acting as the account behind it, so it is gated on reading its token +/// variable, which the variable's row-level security decides. The one exception is the +/// workspace connection an admin shared, read through `db` since members cannot read its token. +pub async fn list_usable_connections( + db: &DB, + tx: &mut PgConnection, + workspace_id: &str, + service_name: ServiceName, +) -> Result<Vec<Connection>> { + let mut connections = sqlx::query_as!( + Connection, + r#"SELECT v.path, r.created_by AS "owner?", false AS "workspace!" + FROM variable v + JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account + LEFT JOIN resource r ON r.workspace_id = v.workspace_id AND r.path = v.path + WHERE v.workspace_id = $1 AND a.client = $2 AND a.is_workspace_integration = true + ORDER BY v.path"#, + workspace_id, + service_name.as_str(), + ) + .fetch_all(&mut *tx) + .await?; + + if let Some(shared) = workspace_connection(db, workspace_id, service_name).await? { + connections.retain(|c| c.path != shared.path); + connections.insert(0, shared); + } + Ok(connections) +} + +/// The connection an admin shared with the whole workspace, if it still exists. +pub async fn workspace_connection( + db: &DB, + workspace_id: &str, + service_name: ServiceName, +) -> Result<Option<Connection>> { + let connection = sqlx::query_as!( + Connection, + r#"SELECT v.path, r.created_by AS "owner?", true AS "workspace!" + FROM workspace_integrations wi + JOIN variable v ON v.workspace_id = wi.workspace_id AND v.path = wi.resource_path + JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account + LEFT JOIN resource r ON r.workspace_id = v.workspace_id AND r.path = v.path + WHERE wi.workspace_id = $1 AND wi.service_name = $2 + AND a.client = $3 AND a.is_workspace_integration = true"#, + workspace_id, + service_name as ServiceName, + service_name.as_str(), + ) + .fetch_optional(db) + .await?; + Ok(connection) +} + +/// Pick the connection a new trigger acts through: the one asked for if the caller may use it, +/// otherwise the shared account, otherwise the caller's only usable connection. Clients and +/// trigger specs that predate connections send none and expect the shared account, so it wins +/// over a lone personal one. `tx` must be a user transaction. +pub async fn resolve_usable_connection( + db: &DB, + tx: &mut PgConnection, + workspace_id: &str, + service_name: ServiceName, + requested: Option<&str>, +) -> Result<String> { + let usable = list_usable_connections(db, tx, workspace_id, service_name).await?; + match requested { + Some(path) if usable.iter().any(|c| c.path == path) => Ok(path.to_string()), + Some(path) => Err(Error::NotAuthorized(format!( + "No {service_name} connection you can use at {path}. Connect an account at that \ + path, or ask for read access to the connection there." + ))), + None if usable.first().is_some_and(|c| c.workspace) => Ok(usable[0].path.clone()), + None => match usable.as_slice() { + [only] => Ok(only.path.clone()), + [] => Err(Error::BadRequest(format!( + "You have no {service_name} connection. Connect your account first." + ))), + _ => Err(Error::BadRequest(format!( + "You can use several {service_name} connections; pick one with connection_path." + ))), + }, + } +} + +/// Serialize, until `tx` ends, the operations that must agree on whether a connection exists: +/// storing a trigger that uses it and disconnecting it. Whichever comes second waits and then +/// sees the other's outcome. +pub async fn lock_connection( + tx: &mut PgConnection, + workspace_id: &str, + connection_path: &str, +) -> Result<()> { + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(format!( + "native_connection:{workspace_id}:{connection_path}" + )) + .execute(&mut *tx) + .await?; Ok(()) } +#[derive(Debug, Deserialize)] +pub struct ConnectionQuery { + pub connection_path: Option<String>, +} + +/// Gate for the pickers that browse the service while configuring a trigger: returns the +/// connection to browse through, which the caller must be allowed to use. +pub async fn picker_connection( + authed: &ApiAuthed, + db: &DB, + user_db: UserDB, + workspace_id: &str, + service_name: ServiceName, + requested: Option<&str>, +) -> Result<String> { + require_native_integration_use(db, workspace_id, authed).await?; + let mut tx = user_db.begin(authed).await?; + let path = + resolve_usable_connection(db, &mut tx, workspace_id, service_name, requested).await?; + tx.commit().await?; + Ok(path) +} + pub async fn get_workspace_integration<'c, E: sqlx::Executor<'c, Database = Postgres>>( db: E, workspace_id: &str, @@ -1758,7 +1905,6 @@ pub async fn get_workspace_integration<'c, E: sqlx::Executor<'c, Database = Post workspace_id, service_name AS "service_name!: ServiceName", oauth_data, - resource_path, created_at, updated_at, created_by diff --git a/backend/windmill-native-triggers/src/nextcloud/external.rs b/backend/windmill-native-triggers/src/nextcloud/external.rs index 763ad6fbb6..4ae3798867 100644 --- a/backend/windmill-native-triggers/src/nextcloud/external.rs +++ b/backend/windmill-native-triggers/src/nextcloud/external.rs @@ -131,11 +131,25 @@ impl External for NextCloud { &url, Method::POST, w_id, + &oauth_data.connection_path, db, Some(headers), Some(&full_nextcloud_payload), ) - .await?; + .await + .map_err(|e| { + // Nextcloud lets only its admins register webhooks. + if http_error_status(&e) == Some(StatusCode::FORBIDDEN) { + Error::BadRequest( + "This Nextcloud account isn't a Nextcloud admin, so it can't register \ + webhooks. Use the shared account, or ask a workspace admin to share a \ + Nextcloud admin account." + .to_string(), + ) + } else { + e + } + })?; Ok(ocs_response.ocs.data) } @@ -167,6 +181,7 @@ impl External for NextCloud { &url, Method::POST, w_id, + &oauth_data.connection_path, db, Some(headers), Some(&full_nextcloud_payload), @@ -214,7 +229,15 @@ impl External for NextCloud { headers.insert("OCS-APIRequest".to_string(), "true".to_string()); let ocs_response: OcsResponse<NextCloudTriggerData> = self - .http_client_request::<_, ()>(&url, Method::GET, w_id, db, Some(headers), None) + .http_client_request::<_, ()>( + &url, + Method::GET, + w_id, + &oauth_data.connection_path, + db, + Some(headers), + None, + ) .await?; Ok(Some(ocs_response.ocs.data)) @@ -239,7 +262,15 @@ impl External for NextCloud { // A webhook already removed in Nextcloud is the outcome this call wants, so only 404 is // swallowed; anything else would leave a live webhook behind while Windmill forgets it. let _: serde_json::Value = self - .http_client_request::<_, ()>(&url, Method::DELETE, w_id, db, Some(headers), None) + .http_client_request::<_, ()>( + &url, + Method::DELETE, + w_id, + &oauth_data.connection_path, + db, + Some(headers), + None, + ) .await .or_else(|e| match http_error_status(&e) { Some(StatusCode::NOT_FOUND) => Ok(serde_json::Value::Null), @@ -320,13 +351,13 @@ impl External for NextCloud { fn error_hint(&self, status: StatusCode) -> Option<&'static str> { match status { StatusCode::UNAUTHORIZED => { - Some("reconnect the Nextcloud integration from Workspace settings > Integrations.") + Some("reconnect the Nextcloud account this uses with Reconnect next to it, or ask its owner or an admin to.") } StatusCode::FORBIDDEN => Some( "Nextcloud grants webhook management to administrators only, and a Windmill \ admin is a different thing. If the connected Nextcloud account is not an admin \ - there and holds no delegated admin rights for the Webhooks setting, reconnect \ - the integration from Workspace settings > Integrations with one that does.", + there and holds no delegated admin rights for the Webhooks setting, use one that \ + does, such as the workspace's shared account.", ), _ => None, } @@ -353,6 +384,7 @@ impl NextCloud { &url, Method::GET, w_id, + &oauth_data.connection_path, db, Some(headers), None, diff --git a/backend/windmill-native-triggers/src/nextcloud/mod.rs b/backend/windmill-native-triggers/src/nextcloud/mod.rs index fda8ad9f6e..7546211283 100644 --- a/backend/windmill-native-triggers/src/nextcloud/mod.rs +++ b/backend/windmill-native-triggers/src/nextcloud/mod.rs @@ -9,6 +9,7 @@ pub struct NextCloudOAuthData { pub access_token: String, pub refresh_token: Option<String>, pub token_expires_at: Option<chrono::DateTime<chrono::Utc>>, + pub connection_path: String, } #[derive(Debug, Serialize, Deserialize)] diff --git a/backend/windmill-native-triggers/src/nextcloud/routes.rs b/backend/windmill-native-triggers/src/nextcloud/routes.rs index a1c679602c..11e9f59227 100644 --- a/backend/windmill-native-triggers/src/nextcloud/routes.rs +++ b/backend/windmill-native-triggers/src/nextcloud/routes.rs @@ -1,8 +1,13 @@ use std::{collections::HashMap, sync::Arc}; -use axum::{extract::Path, routing::get, Extension, Json, Router}; +use axum::{ + extract::{Path, Query}, + routing::get, + Extension, Json, Router, +}; use http::Method; use windmill_common::{ + db::UserDB, error::{Error, JsonResult}, DB, }; @@ -12,16 +17,26 @@ use windmill_api_auth::ApiAuthed; use crate::{ get_workspace_integration, map_external_error, nextcloud::{NextCloudEventType, OcsResponse}, - require_native_integration_use, External, ServiceName, + picker_connection, ConnectionQuery, External, ServiceName, }; async fn list_available_events<T: External>( authed: ApiAuthed, Extension(handler): Extension<Arc<T>>, Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, Path(workspace_id): Path<String>, + Query(query): Query<ConnectionQuery>, ) -> JsonResult<Vec<NextCloudEventType>> { - require_native_integration_use(&authed)?; + let connection_path = picker_connection( + &authed, + &db, + user_db, + &workspace_id, + ServiceName::Nextcloud, + query.connection_path.as_deref(), + ) + .await?; let integration = get_workspace_integration(&db, &workspace_id, ServiceName::Nextcloud).await?; let base_url = integration @@ -43,6 +58,7 @@ async fn list_available_events<T: External>( &url, Method::GET, &workspace_id, + &connection_path, &db, Some(headers), None, diff --git a/backend/windmill-native-triggers/src/rename.rs b/backend/windmill-native-triggers/src/rename.rs index caae99028c..3c273bc57f 100644 --- a/backend/windmill-native-triggers/src/rename.rs +++ b/backend/windmill-native-triggers/src/rename.rs @@ -69,19 +69,8 @@ async fn reregister_service<T: External>( moved: &[&MovedNativeTrigger], handler: T, ) { - let oauth_data: T::OAuthData = - match decrypt_oauth_data(db, w_id, T::SERVICE_NAME.integration_service()).await { - Ok(oauth_data) => oauth_data, - Err(e) => { - for trigger in moved { - record_failure::<T>(db, w_id, &trigger.external_id, &e).await; - } - return; - } - }; - for trigger in moved { - if let Err(e) = reregister_one(db, authed, w_id, &handler, &oauth_data, trigger).await { + if let Err(e) = reregister_one(db, authed, w_id, &handler, trigger).await { record_failure::<T>(db, w_id, &trigger.external_id, &e).await; } } @@ -99,7 +88,6 @@ async fn reregister_one<T: External>( authed: &ApiAuthed, w_id: &str, handler: &T, - oauth_data: &T::OAuthData, moved: &MovedNativeTrigger, ) -> Result<()> { let external_id = moved.external_id.as_str(); @@ -136,8 +124,17 @@ async fn reregister_one<T: External>( service_config, summary: trigger.summary.clone(), enabled: trigger.enabled, + connection_path: trigger.connection_path.clone(), }; + let oauth_data: T::OAuthData = decrypt_oauth_data( + db, + w_id, + T::SERVICE_NAME.integration_service(), + trigger.connection_path.as_deref(), + ) + .await?; + // The token is scoped to the runnable path and only its hash is kept, so pointing the webhook // at the new path means minting a replacement rather than reusing the old one. Commit it // before handing it out: a service may call back the moment it accepts the new URL. @@ -157,7 +154,7 @@ async fn reregister_one<T: External>( let updated = handler .update( w_id, - oauth_data, + &oauth_data, external_id, &webhook_token, &data, diff --git a/backend/windmill-native-triggers/src/sync.rs b/backend/windmill-native-triggers/src/sync.rs index 4f75845429..074703f1b8 100644 --- a/backend/windmill-native-triggers/src/sync.rs +++ b/backend/windmill-native-triggers/src/sync.rs @@ -6,6 +6,9 @@ use serde::Serialize; use crate::ServiceName; +#[cfg(feature = "native_trigger")] +use itertools::Itertools; + #[cfg(feature = "native_trigger")] use crate::{ decrypt_oauth_data, list_native_triggers, update_native_trigger_error, @@ -238,38 +241,50 @@ pub async fn sync_workspace_triggers<T: External>( let mut synced = Vec::new(); let mut errors = Vec::new(); - // Use the integration service for OAuth lookup (e.g., GoogleDrive/GoogleCalendar -> Google) - let integration_service = T::SERVICE_NAME.integration_service(); + // Maintenance runs per connection: each one's triggers are registered under its account, and + // Nextcloud reconciles against that account's own list of webhooks. + let by_connection = windmill_triggers + .into_iter() + .into_group_map_by(|t| t.connection_path.clone()); - let oauth_data = { - match decrypt_oauth_data(db, workspace_id, integration_service).await { + for (connection_path, triggers) in by_connection { + let oauth_data = match decrypt_oauth_data( + db, + workspace_id, + T::SERVICE_NAME.integration_service(), + connection_path.as_deref(), + ) + .await + { Ok(oauth_data) => oauth_data, Err(e) => { tracing::error!( - "Failed to get workspace integration OAuth data for {}: {}", + "Failed to get the OAuth data of connection {:?} in {}: {}", + connection_path, workspace_id, e ); errors.push(SyncError { - resource_path: format!("workspace:{}", workspace_id), - error_message: format!("Failed to get workspace integration OAuth data: {}", e), + resource_path: connection_path + .unwrap_or_else(|| format!("workspace:{}", workspace_id)), + error_message: format!("Failed to get connection OAuth data: {}", e), error_type: "oauth_error".to_string(), }); - return Ok((Vec::new(), errors)); + continue; } - } - }; + }; - handler - .maintain_triggers( - db, - workspace_id, - &windmill_triggers, - &oauth_data, - &mut synced, - &mut errors, - ) - .await; + handler + .maintain_triggers( + db, + workspace_id, + &triggers, + &oauth_data, + &mut synced, + &mut errors, + ) + .await; + } tracing::info!( "Sync completed for {} in workspace '{}'. Updated: {}, Errors: {}", diff --git a/backend/windmill-native-triggers/src/workspace_integrations.rs b/backend/windmill-native-triggers/src/workspace_integrations.rs index eccfa56f19..f2e2e1cb23 100644 --- a/backend/windmill-native-triggers/src/workspace_integrations.rs +++ b/backend/windmill-native-triggers/src/workspace_integrations.rs @@ -2,7 +2,7 @@ use axum::Router; #[cfg(feature = "native_trigger")] use axum::{ - extract::Path, + extract::{Path, Query}, routing::{delete, get, post}, Extension, Json, }; @@ -30,14 +30,18 @@ use windmill_common::{ }; #[cfg(feature = "native_trigger")] -use windmill_api_auth::ApiAuthed; +use windmill_api_auth::{check_scopes, require_is_writer, ApiAuthed}; #[cfg(feature = "native_trigger")] use crate::{ - decrypt_oauth_data, delete_token_by_hash, delete_workspace_integration, nextcloud::OcsResponse, - resolve_endpoint, store_workspace_integration, ServiceName, + decrypt_oauth_data, delete_token_by_hash, delete_workspace_integration, + list_usable_connections, lock_connection, nextcloud::OcsResponse, + require_native_integration_use, resolve_endpoint, Connection, ServiceName, }; +#[cfg(feature = "native_trigger")] +use std::collections::HashMap; + #[cfg(feature = "native_trigger")] use windmill_oauth::{OClient, Url, OAUTH_HTTP_CLIENT}; @@ -57,24 +61,31 @@ type HmacSha256 = Hmac<Sha256>; const STATE_EXPIRATION_SECONDS: i64 = 600; // 10 minutes /// Generate a signed OAuth state that is cluster-safe. -/// The state contains: workspace_id, service_name, timestamp, and nonce. +/// The state contains: workspace_id, service_name, timestamp, nonce, the path the connection +/// will be saved at, and the user it was issued to. The path makes the callback independent of the +/// page the provider redirects to; the user stops anyone else from finishing the flow, which would +/// save their account at a path the issuer chose. /// It's signed with HMAC-SHA256 using the workspace key. #[cfg(feature = "native_trigger")] async fn generate_signed_state( db: &DB, workspace_id: &str, service_name: ServiceName, + connection_path: &str, + username: &str, ) -> Result<String> { use windmill_common::variables::get_workspace_key; let nonce = uuid::Uuid::new_v4().to_string(); let timestamp = chrono::Utc::now().timestamp(); let payload = format!( - "{}:{}:{}:{}", + "{}:{}:{}:{}:{}:{}", workspace_id, service_name.as_str(), timestamp, - nonce + nonce, + URL_SAFE_NO_PAD.encode(connection_path), + URL_SAFE_NO_PAD.encode(username) ); // Get workspace key for signing @@ -91,65 +102,63 @@ async fn generate_signed_state( Ok(format!("{}:{}", encoded_payload, encoded_signature)) } -/// Validate a signed OAuth state. -/// Returns true if the state is valid (correct signature and not expired). +/// Validate a signed OAuth state (correct signature, workspace, service and user, not expired) +/// and return the connection path it was issued for. #[cfg(feature = "native_trigger")] -async fn validate_signed_state(db: &DB, state: &str, workspace_id: &str) -> Result<bool> { +async fn validate_signed_state( + db: &DB, + state: &str, + workspace_id: &str, + service_name: ServiceName, + username: &str, +) -> Result<String> { use windmill_common::variables::get_workspace_key; - let parts: Vec<&str> = state.split(':').collect(); - if parts.len() != 2 { - return Ok(false); + let invalid = || Error::BadRequest("Invalid or expired state parameter".to_string()); + + let (encoded_payload, encoded_signature) = state.split_once(':').ok_or_else(invalid)?; + + let payload = URL_SAFE_NO_PAD + .decode(encoded_payload) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + .ok_or_else(invalid)?; + + // Parse payload: workspace_id:service_name:timestamp:nonce:connection_path:username + let [state_workspace_id, state_service, timestamp, _nonce, encoded_path, encoded_user] = + payload + .split(':') + .collect::<Vec<_>>() + .try_into() + .map_err(|_| invalid())?; + + if state_workspace_id != workspace_id + || state_service != service_name.as_str() + || encoded_user != URL_SAFE_NO_PAD.encode(username) + { + return Err(invalid()); } - let encoded_payload = parts[0]; - let encoded_signature = parts[1]; - - // Decode payload - let payload_bytes = match URL_SAFE_NO_PAD.decode(encoded_payload) { - Ok(bytes) => bytes, - Err(_) => return Ok(false), - }; - let payload = match String::from_utf8(payload_bytes) { - Ok(s) => s, - Err(_) => return Ok(false), - }; - - // Parse payload: workspace_id:service_name:timestamp:nonce - let payload_parts: Vec<&str> = payload.split(':').collect(); - if payload_parts.len() != 4 { - return Ok(false); + let timestamp: i64 = timestamp.parse().map_err(|_| invalid())?; + if chrono::Utc::now().timestamp() - timestamp > STATE_EXPIRATION_SECONDS { + return Err(invalid()); } - let state_workspace_id = payload_parts[0]; - let timestamp: i64 = match payload_parts[2].parse() { - Ok(ts) => ts, - Err(_) => return Ok(false), - }; - - // Verify workspace_id matches - if state_workspace_id != workspace_id { - return Ok(false); - } - - // Check expiration - let now = chrono::Utc::now().timestamp(); - if now - timestamp > STATE_EXPIRATION_SECONDS { - return Ok(false); - } - - // Verify signature let key = get_workspace_key(workspace_id, db).await?; let mut mac = HmacSha256::new_from_slice(key.as_bytes()) .map_err(|e| Error::InternalErr(e.to_string()))?; mac.update(payload.as_bytes()); + let received_signature = URL_SAFE_NO_PAD + .decode(encoded_signature) + .map_err(|_| invalid())?; + mac.verify_slice(&received_signature) + .map_err(|_| invalid())?; - let received_signature = match URL_SAFE_NO_PAD.decode(encoded_signature) { - Ok(bytes) => bytes, - Err(_) => return Ok(false), - }; - - Ok(mac.verify_slice(&received_signature).is_ok()) + URL_SAFE_NO_PAD + .decode(encoded_path) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + .ok_or_else(invalid) } #[cfg(feature = "native_trigger")] @@ -194,20 +203,114 @@ pub struct OAuthConfigResponse { pub redirect_uri: Option<String>, } +/// The OAuth client a connection is made with: the workspace's own when an admin configured one, +/// otherwise the instance's when the instance admin shares it. The flag says which. +#[cfg(feature = "native_trigger")] +async fn resolve_oauth_client( + db: &DB, + workspace_id: &str, + service_name: ServiceName, +) -> Result<(WorkspaceOAuthConfig, bool)> { + let workspace_config = + get_workspace_oauth_config::<WorkspaceOAuthConfig>(db, workspace_id, service_name) + .await + .ok() + .filter(|c| !c.instance_shared && !c.client_id.is_empty()); + match workspace_config { + Some(config) => Ok((config, false)), + None => Ok((get_instance_oauth_config(db, service_name).await?, true)), + } +} + +/// Connecting writes the connection's variable and resource at `path`, so a path-scoped token must +/// cover both, whatever the user behind it may write. +#[cfg(feature = "native_trigger")] +fn check_connection_scopes(authed: &ApiAuthed, path: &str) -> Result<()> { + check_scopes(authed, || format!("variables:write:{path}"))?; + check_scopes(authed, || format!("resources:write:{path}")) +} + +/// Reconnecting at a path swaps the account every trigger using it acts as, including the shared +/// account's, so only whoever connected it or an admin may replace what is there. Writing the +/// path is not enough: a folder writer would otherwise turn other members' triggers into their own. +#[cfg(feature = "native_trigger")] +async fn check_can_replace( + db: &DB, + authed: &ApiAuthed, + workspace_id: &str, + path: &str, +) -> Result<()> { + if authed.is_admin { + return Ok(()); + } + let existing = sqlx::query!( + r#"SELECT + (SELECT created_by FROM resource WHERE workspace_id = $1 AND path = $2) AS "owner?", + EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2) + OR EXISTS(SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2) AS "taken!""#, + workspace_id, + path, + ) + .fetch_one(db) + .await?; + if existing.taken && existing.owner.as_deref() != Some(authed.username.as_str()) { + return Err(Error::NotAuthorized(format!( + "{path} holds a connection someone else created. Connect at another path, or ask an \ + admin to reconnect it." + ))); + } + Ok(()) +} + +#[cfg(feature = "native_trigger")] +fn default_connection_path(authed: &ApiAuthed, service_name: ServiceName) -> String { + format!( + "u/{}/native_{}", + authed.username, + service_name.resource_type() + ) +} + #[cfg(feature = "native_trigger")] async fn generate_connect_url( authed: ApiAuthed, Extension(db): Extension<DB>, Path((workspace_id, service_name)): Path<(String, ServiceName)>, - Json(RedirectUri { redirect_uri }): Json<RedirectUri>, + Json(body): Json<ConnectUrlBody>, ) -> JsonResult<String> { - require_admin(authed.is_admin, &workspace_id)?; + require_native_integration_use(&db, &workspace_id, &authed).await?; - let oauth_config = - get_workspace_oauth_config_as_oauth_config(&db, &workspace_id, service_name).await?; + let (oauth_config, is_instance_shared) = + resolve_oauth_client(&db, &workspace_id, service_name).await?; + + let connection_path = body + .resource_path + .filter(|p| !p.is_empty()) + .unwrap_or_else(|| default_connection_path(&authed, service_name)); + check_connection_scopes(&authed, &connection_path)?; + check_can_replace(&db, &authed, &workspace_id, &connection_path).await?; + + // A GitHub OAuth app only redirects under its one registered callback, and the instance app's + // is the resource connect callback, so its connections land on a page below that one. + let redirect_uri = if is_instance_shared && service_name == ServiceName::Github { + let origin = Url::parse(&body.redirect_uri) + .map_err(|e| Error::BadRequest(format!("Invalid redirect URI: {e}")))? + .origin() + .ascii_serialization(); + format!("{origin}/oauth/callback/github/native_trigger") + } else { + body.redirect_uri + }; // Generate a signed state that is cluster-safe - let state = generate_signed_state(&db, &workspace_id, service_name).await?; + let state = generate_signed_state( + &db, + &workspace_id, + service_name, + &connection_path, + &authed.username, + ) + .await?; let auth_url = build_authorization_url(&oauth_config, service_name, &state, &redirect_uri); Ok(Json(auth_url)) } @@ -287,14 +390,26 @@ async fn fetch_nextcloud_user_id(base_url: &str, access_token: &str) -> anyhow:: Ok(ocs.ocs.data.id) } -/// Delete all native triggers for a workspace+service, including remote webhook cleanup. +/// Delete the native triggers of a workspace+service, including remote webhook cleanup. When `only` +/// gives `(external_ids, script_paths)`, just the triggers still at those paths: a trigger moved +/// since its path was checked is left alone. /// This is best-effort: errors during remote cleanup or token deletion are logged but ignored. #[cfg(feature = "native_trigger")] -async fn delete_triggers_for_service(db: &DB, workspace_id: &str, service_name: ServiceName) { +async fn delete_triggers_for_service( + db: &DB, + workspace_id: &str, + service_name: ServiceName, + only: Option<(&[String], &[String])>, +) { + let (external_ids, script_paths) = only.unzip(); let triggers = sqlx::query!( - "SELECT external_id, webhook_token_hash FROM native_trigger WHERE workspace_id = $1 AND service_name = $2", + "SELECT external_id, connection_path FROM native_trigger + WHERE workspace_id = $1 AND service_name = $2 AND ($3::text[] IS NULL + OR (external_id, script_path) IN (SELECT * FROM unnest($3::text[], $4::text[])))", workspace_id, - service_name as ServiceName + service_name as ServiceName, + external_ids, + script_paths, ) .fetch_all(db) .await; @@ -311,27 +426,33 @@ async fn delete_triggers_for_service(db: &DB, workspace_id: &str, service_name: return; } - // For Nextcloud: try to delete webhooks on the remote instance (best-effort) - if service_name == ServiceName::Nextcloud { - if let Ok(oauth_data) = - decrypt_oauth_data::<BasicOAuthData>(db, workspace_id, service_name).await - { - for trigger in &triggers { + // Nextcloud and GitHub: try to delete the webhooks remotely (best-effort). + // Google: skip remote cleanup (watch channels expire naturally). + if service_name != ServiceName::Google { + let mut credentials: HashMap<Option<String>, Option<BasicOAuthData>> = HashMap::new(); + for trigger in &triggers { + if !credentials.contains_key(&trigger.connection_path) { + let oauth_data = decrypt_oauth_data::<BasicOAuthData>( + db, + workspace_id, + service_name, + trigger.connection_path.as_deref(), + ) + .await + .ok(); + credentials.insert(trigger.connection_path.clone(), oauth_data); + } + let Some(Some(oauth_data)) = credentials.get(&trigger.connection_path) else { + continue; + }; + if service_name == ServiceName::Nextcloud { try_delete_nextcloud_webhook( &oauth_data.base_url, &oauth_data.access_token, &trigger.external_id, ) .await; - } - } - } - // For GitHub: try to delete webhooks on GitHub (best-effort) - if service_name == ServiceName::Github { - if let Ok(oauth_data) = - decrypt_oauth_data::<BasicOAuthData>(db, workspace_id, service_name).await - { - for trigger in &triggers { + } else { try_delete_github_webhook( db, workspace_id, @@ -342,15 +463,19 @@ async fn delete_triggers_for_service(db: &DB, workspace_id: &str, service_name: } } } - // For Google: skip remote cleanup (watch channels expire naturally) // Revoke the tokens the deleted rows actually named, not the ones listed above: a // re-registration running concurrently mints a replacement, and leaving that alive would let a // disconnected integration keep starting jobs. let deleted_token_hashes = sqlx::query_scalar!( - "DELETE FROM native_trigger WHERE workspace_id = $1 AND service_name = $2 RETURNING webhook_token_hash", + "DELETE FROM native_trigger + WHERE workspace_id = $1 AND service_name = $2 AND ($3::text[] IS NULL + OR (external_id, script_path) IN (SELECT * FROM unnest($3::text[], $4::text[]))) + RETURNING webhook_token_hash", workspace_id, - service_name as ServiceName + service_name as ServiceName, + external_ids, + script_paths, ) .fetch_all(db) .await @@ -378,13 +503,60 @@ async fn delete_integration( ) -> JsonResult<String> { require_admin(authed.is_admin, &workspace_id)?; - // Delete triggers first (needs OAuth data that cleanup_oauth_resource will remove) - delete_triggers_for_service(&db, &workspace_id, service_name).await; + // This deletes every trigger and connection of the service, so a path-scoped token must + // cover each of them, as for a single disconnect. + let script_paths = sqlx::query_scalar!( + "SELECT script_path FROM native_trigger WHERE workspace_id = $1 AND service_name = $2", + workspace_id, + service_name as ServiceName, + ) + .fetch_all(&db) + .await?; + for script_path in &script_paths { + check_scopes(&authed, || format!("native_triggers:write:{script_path}"))?; + } + let mut paths = sqlx::query_scalar!( + "SELECT v.path FROM variable v + JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account + WHERE v.workspace_id = $1 AND a.client = $2 AND a.is_workspace_integration = true", + workspace_id, + service_name.as_str(), + ) + .fetch_all(&db) + .await?; + for path in &paths { + check_connection_scopes(&authed, path)?; + } + + // Delete triggers first: removing their registrations needs the connections cleaned up below + delete_triggers_for_service(&db, &workspace_id, service_name, None).await; let mut tx = user_db.begin(&authed).await?; - // Clean up account+variable+resource - cleanup_oauth_resource(&mut *tx, &workspace_id, service_name).await; + // Same serialization as a single disconnect: a trigger created meanwhile either committed + // before these locks, and is caught below, or waits and then finds its connection gone. + paths.sort(); + for path in &paths { + lock_connection(&mut tx, &workspace_id, path).await?; + } + + cleanup_service_connections(&mut *tx, &workspace_id, service_name).await?; + + let created_meanwhile = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM native_trigger WHERE workspace_id = $1 AND service_name = $2)", + workspace_id, + service_name as ServiceName, + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false); + if created_meanwhile { + tx.rollback().await?; + return Err(Error::BadRequest(format!( + "A {service_name} trigger was created while removing the integration, so it was kept. \ + Remove it again." + ))); + } let deleted = delete_workspace_integration(&mut *tx, &workspace_id, service_name).await?; @@ -419,7 +591,6 @@ async fn delete_integration( struct WorkspaceIntegrations { service_name: ServiceName, oauth_data: Option<sqlx::types::Json<WorkspaceOAuthConfig>>, - resource_path: Option<String>, } #[cfg(feature = "native_trigger")] @@ -436,8 +607,7 @@ async fn list_integrations( r#" SELECT oauth_data as "oauth_data: sqlx::types::Json<WorkspaceOAuthConfig>", - service_name as "service_name!: ServiceName", - resource_path + service_name as "service_name!: ServiceName" FROM workspace_integrations WHERE @@ -450,23 +620,14 @@ async fn list_integrations( let key_value = integrations .into_iter() - .map(|integration| { - ( - integration.service_name, - (integration.oauth_data, integration.resource_path), - ) - }) + .map(|integration| (integration.service_name, integration.oauth_data)) .collect::<std::collections::HashMap<_, _>>(); use strum::IntoEnumIterator; let integrations = ServiceName::iter() .map(|service_name| { - let (oauth_data, resource_path) = key_value - .get(&service_name) - .cloned() - .map(|(od, rp)| (od, rp)) - .unwrap_or((None, None)); - WorkspaceIntegrations { service_name, oauth_data, resource_path } + let oauth_data = key_value.get(&service_name).cloned().flatten(); + WorkspaceIntegrations { service_name, oauth_data } }) .collect::<Vec<_>>(); @@ -475,12 +636,18 @@ async fn list_integrations( Ok(Json(integrations)) } +/// Whether members can connect an account for this service: the workspace has an OAuth client, +/// or the instance shares one. #[cfg(feature = "native_trigger")] async fn integration_exist( authed: ApiAuthed, + Extension(db): Extension<DB>, Extension(user_db): Extension<UserDB>, Path((workspace_id, service_name)): Path<(String, ServiceName)>, ) -> JsonResult<bool> { + if is_instance_sharing_enabled(&db, service_name).await? { + return Ok(Json(true)); + } let mut tx = user_db.begin(&authed).await?; let exists = sqlx::query_scalar!( r#" @@ -504,8 +671,10 @@ async fn integration_exist( #[cfg(feature = "native_trigger")] #[derive(Debug, Deserialize)] -struct RedirectUri { +struct ConnectUrlBody { redirect_uri: String, + /// Where to save the connection; defaults to `u/<caller>/native_<resource type>`. + resource_path: Option<String>, } #[cfg(feature = "native_trigger")] @@ -514,7 +683,6 @@ struct OAuthCallbackBody { redirect_uri: String, code: String, state: String, - resource_path: Option<String>, } #[cfg(feature = "native_trigger")] @@ -531,60 +699,34 @@ async fn oauth_callback( Path((workspace_id, service_name)): Path<(String, ServiceName)>, Json(body): Json<OAuthCallbackBody>, ) -> JsonResult<String> { - require_admin(authed.is_admin, &workspace_id)?; + require_native_integration_use(&db, &workspace_id, &authed).await?; - let state_was_valid = validate_signed_state(&db, &body.state, &workspace_id).await?; - - if !state_was_valid { - return Err(Error::BadRequest( - "Invalid or expired state parameter".to_string(), - )); - } - - // Check if this integration uses instance-shared credentials - let existing_oauth_data = sqlx::query_scalar!( - r#"SELECT oauth_data FROM workspace_integrations - WHERE workspace_id = $1 AND service_name = $2"#, - workspace_id, - service_name as ServiceName + let resource_path = validate_signed_state( + &db, + &body.state, + &workspace_id, + service_name, + &authed.username, ) - .fetch_optional(&db) - .await? - .flatten(); + .await?; + check_connection_scopes(&authed, &resource_path)?; + check_can_replace(&db, &authed, &workspace_id, &resource_path).await?; - let is_instance_shared = existing_oauth_data - .as_ref() - .and_then(|v| v.get("instance_shared")) - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - let oauth_config = if is_instance_shared { - get_instance_oauth_config(&db, service_name).await? - } else { - get_workspace_oauth_config::<WorkspaceOAuthConfig>(&db, &workspace_id, service_name).await? - }; + let (oauth_config, is_instance_shared) = + resolve_oauth_client(&db, &workspace_id, service_name).await?; let token_response = exchange_code_for_token(&oauth_config, service_name, &body.code, &body.redirect_uri) .await?; - let resource_path = body - .resource_path - .filter(|p| !p.is_empty()) - .unwrap_or_else(|| { - format!( - "u/{}/native_{}", - authed.username, - service_name.resource_type() - ) - }); - let expires_in = token_response.expires_in.unwrap_or(3600); + // A user transaction, so the variable and resource policies decide whether the caller may + // write a connection at this path. let mut tx = user_db.begin(&authed).await?; - // Clean up any previous account+variable+resource for this integration - cleanup_oauth_resource(&mut *tx, &workspace_id, service_name).await; + // Reconnecting at a path replaces the connection there; triggers using it keep working. + let replaced_account = cleanup_connection(&mut *tx, &workspace_id, &resource_path).await?; // 1. Create account record for token refresh let account_id = sqlx::query_scalar!( @@ -658,25 +800,21 @@ async fn oauth_callback( .await .map_err(|e| Error::InternalErr(format!("Failed to create resource: {}", e)))?; - // 4. Store config + resource_path in workspace_integrations (no tokens). - // For instance-shared integrations, store the flag instead of credentials. - let stored_data = if is_instance_shared { - json!({ - "instance_shared": true, - "base_url": "", - }) - } else { - to_value(&oauth_config).unwrap() - }; - store_workspace_integration( - &mut *tx, - &authed, - &workspace_id, - service_name, - stored_data, - Some(&resource_path), - ) - .await?; + // 4. The first connection made with the instance's client records that in the workspace. + // Token refresh reads the client from this row, so it must exist for every connection. + if is_instance_shared { + sqlx::query!( + "INSERT INTO workspace_integrations (workspace_id, service_name, oauth_data, created_by) + VALUES ($1, $2, $3, $4) + ON CONFLICT (workspace_id, service_name) DO NOTHING", + workspace_id, + service_name as ServiceName, + json!({ "instance_shared": true, "base_url": "" }), + authed.username, + ) + .execute(&mut *tx) + .await?; + } audit_log( &mut *tx, @@ -684,17 +822,15 @@ async fn oauth_callback( &format!("workspace_integrations.{}.connect", service_name), ActionKind::Create, &workspace_id, - Some(&format!("Connected {} integration via OAuth", service_name)), + Some(&resource_path), None, ) .await?; tx.commit().await?; + delete_unlinked_account(&db, &workspace_id, replaced_account).await; - Ok(Json(format!( - "{} integration connected successfully via OAuth", - service_name - ))) + Ok(Json(resource_path)) } /// Token response from OAuth token exchange @@ -806,7 +942,6 @@ pub async fn create_workspace_integration( &workspace_id, service_name, to_value(oauth_data).unwrap(), - None, ) .await?; @@ -815,16 +950,6 @@ pub async fn create_workspace_integration( Ok(()) } -#[cfg(feature = "native_trigger")] -#[inline] -async fn get_workspace_oauth_config_as_oauth_config( - db: &DB, - workspace_id: &str, - service_name: ServiceName, -) -> Result<WorkspaceOAuthConfig> { - get_workspace_oauth_config::<WorkspaceOAuthConfig>(db, workspace_id, service_name).await -} - #[cfg(feature = "native_trigger")] fn build_authorization_url( config: &WorkspaceOAuthConfig, @@ -855,73 +980,96 @@ fn build_authorization_url( format!("{}?{}", base_auth_url, query_string) } +/// Remove the connection at `path`: its variable and its resource. +/// +/// Returns the account the variable linked. The caller removes it with +/// [`delete_unlinked_account`] once `tx` is committed. #[cfg(feature = "native_trigger")] -pub async fn cleanup_oauth_resource( +pub async fn cleanup_connection( + tx: &mut sqlx::PgConnection, + workspace_id: &str, + path: &str, +) -> Result<Option<i32>> { + let account_id = sqlx::query_scalar!( + "DELETE FROM variable WHERE workspace_id = $1 AND path = $2 RETURNING account", + workspace_id, + path, + ) + .fetch_optional(&mut *tx) + .await? + .flatten(); + + sqlx::query!( + "DELETE FROM resource WHERE workspace_id = $1 AND path = $2", + workspace_id, + path, + ) + .execute(&mut *tx) + .await?; + + Ok(account_id) +} + +/// Delete a connection's account once no variable links it any more. Any variable can link any +/// account, so another one may still hold it; the check needs `db`, since the caller's own +/// transaction does not see variables it cannot read. +#[cfg(feature = "native_trigger")] +pub async fn delete_unlinked_account(db: &DB, workspace_id: &str, account_id: Option<i32>) { + let Some(account_id) = account_id else { + return; + }; + if let Err(e) = sqlx::query!( + "DELETE FROM account WHERE workspace_id = $1 AND id = $2 AND is_workspace_integration = true + AND NOT EXISTS (SELECT 1 FROM variable WHERE workspace_id = $1 AND account = $2)", + workspace_id, + account_id, + ) + .execute(db) + .await + { + tracing::error!("Failed to delete account {account_id} in {workspace_id}: {e}"); + } +} + +/// Remove every connection of a service in the workspace. +#[cfg(feature = "native_trigger")] +pub async fn cleanup_service_connections( tx: &mut sqlx::PgConnection, workspace_id: &str, service_name: ServiceName, -) { - // Look up the stored resource_path from workspace_integrations - let stored_resource_path: Option<String> = sqlx::query_scalar!( - r#"SELECT resource_path FROM workspace_integrations WHERE workspace_id = $1 AND service_name = $2"#, - workspace_id, - service_name as ServiceName, - ) - .fetch_optional(&mut *tx) - .await - .ok() - .flatten() - .flatten(); - - // Find and delete any existing account+variable+resource for this integration - let account_ids: Vec<i32> = sqlx::query_scalar!( +) -> Result<()> { + let account_ids = sqlx::query_scalar!( "DELETE FROM account WHERE workspace_id = $1 AND client = $2 AND is_workspace_integration = true RETURNING id", workspace_id, service_name.as_str(), ) .fetch_all(&mut *tx) - .await - .unwrap_or_default(); + .await?; - if !account_ids.is_empty() { - // Delete variables linked to these accounts - let _ = sqlx::query!( - "DELETE FROM variable WHERE workspace_id = $1 AND account = ANY($2)", - workspace_id, - &account_ids, - ) - .execute(&mut *tx) - .await; - } + let paths = sqlx::query_scalar!( + "DELETE FROM variable WHERE workspace_id = $1 AND account = ANY($2) RETURNING path", + workspace_id, + &account_ids, + ) + .fetch_all(&mut *tx) + .await?; - // Delete resource by exact stored path, or fall back to legacy pattern - let resource_type = service_name.resource_type(); - if let Some(ref path) = stored_resource_path { - let _ = sqlx::query!( - "DELETE FROM resource WHERE workspace_id = $1 AND path = $2", - workspace_id, - path, - ) - .execute(&mut *tx) - .await; - } else { - // Legacy fallback for integrations created before user-chosen paths - let _ = sqlx::query!( - "DELETE FROM resource WHERE workspace_id = $1 AND resource_type = $2 AND path LIKE 'u/%/native_%'", - workspace_id, - resource_type, - ) - .execute(&mut *tx) - .await; - } + sqlx::query!( + "DELETE FROM resource WHERE workspace_id = $1 AND path = ANY($2)", + workspace_id, + &paths, + ) + .execute(&mut *tx) + .await?; + + Ok(()) } /// Check if the instance admin has enabled sharing of OAuth credentials for a given service. -/// Currently only supported for Google (gworkspace). #[cfg(feature = "native_trigger")] async fn is_instance_sharing_enabled(db: &DB, service_name: ServiceName) -> Result<bool> { - // Only Google supports instance sharing for now - if service_name != ServiceName::Google { + // Each Nextcloud client belongs to one Nextcloud server, which is a workspace choice. + if service_name == ServiceName::Nextcloud { return Ok(false); } @@ -930,7 +1078,7 @@ async fn is_instance_sharing_enabled(db: &DB, service_name: ServiceName) -> Resu None => return Ok(false), }; - let key = service_name.resource_type(); // "gworkspace" + let key = service_name.resource_type(); let entry = match oauths_value.get(key) { Some(v) => v, None => return Ok(false), @@ -953,9 +1101,10 @@ async fn get_instance_oauth_config( service_name: ServiceName, ) -> Result<WorkspaceOAuthConfig> { if !is_instance_sharing_enabled(db, service_name).await? { - return Err(Error::BadRequest( - "Instance credential sharing is not enabled for this service".to_string(), - )); + return Err(Error::BadRequest(format!( + "No {service_name} OAuth app is configured for this workspace. A workspace admin can \ + configure one in the workspace settings, under native triggers." + ))); } let (client_id, client_secret) = @@ -985,36 +1134,213 @@ async fn check_instance_sharing_available( } #[cfg(feature = "native_trigger")] -async fn generate_instance_connect_url( +async fn list_connections( authed: ApiAuthed, Extension(db): Extension<DB>, Extension(user_db): Extension<UserDB>, Path((workspace_id, service_name)): Path<(String, ServiceName)>, - Json(RedirectUri { redirect_uri }): Json<RedirectUri>, +) -> JsonResult<Vec<Connection>> { + let mut tx = user_db.begin(&authed).await?; + let connections = list_usable_connections(&db, &mut tx, &workspace_id, service_name).await?; + tx.commit().await?; + Ok(Json(connections)) +} + +#[cfg(feature = "native_trigger")] +#[derive(Debug, Deserialize)] +struct ConnectionPathQuery { + path: String, +} + +#[cfg(feature = "native_trigger")] +#[derive(Debug, Deserialize)] +struct WorkspaceConnectionBody { + /// The connection to share with every member, or none to stop sharing. + path: Option<String>, +} + +/// Share one connection with the whole workspace: every member may then create and edit triggers +/// through it, without being able to read its token. +#[cfg(feature = "native_trigger")] +async fn set_workspace_connection( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Path((workspace_id, service_name)): Path<(String, ServiceName)>, + Json(WorkspaceConnectionBody { path }): Json<WorkspaceConnectionBody>, ) -> JsonResult<String> { require_admin(authed.is_admin, &workspace_id)?; - let instance_config = get_instance_oauth_config(&db, service_name).await?; + if let Some(path) = path.as_deref() { + // Sharing lets every member act as the account, so a path-scoped token must cover it. + check_connection_scopes(&authed, path)?; + let exists = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM variable v + JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account + WHERE v.workspace_id = $1 AND v.path = $2 AND a.client = $3 + AND a.is_workspace_integration = true)", + workspace_id, + path, + service_name.as_str(), + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if !exists { + return Err(Error::BadRequest(format!( + "No {service_name} connection at {path}" + ))); + } + } - // Store a marker in workspace_integrations — NOT the actual credentials. - // The callback and token refresh will read credentials from global settings - // when they see instance_shared=true. - let mut tx = user_db.begin(&authed).await?; - crate::store_workspace_integration( - &mut tx, + let mut tx = db.begin().await?; + let updated = sqlx::query!( + "UPDATE workspace_integrations SET resource_path = $3, updated_at = now() + WHERE workspace_id = $1 AND service_name = $2", + workspace_id, + service_name as ServiceName, + path, + ) + .execute(&mut *tx) + .await? + .rows_affected(); + if updated == 0 { + return Err(Error::NotFound(format!( + "{service_name} is not set up in this workspace" + ))); + } + + audit_log( + &mut *tx, &authed, + &format!("workspace_integrations.{}.share", service_name), + ActionKind::Update, &workspace_id, - service_name, - json!({ "instance_shared": true, "base_url": "" }), + Some(path.as_deref().unwrap_or("none")), None, ) .await?; tx.commit().await?; - // Generate signed state and build authorization URL - let state = generate_signed_state(&db, &workspace_id, service_name).await?; - let auth_url = build_authorization_url(&instance_config, service_name, &state, &redirect_uri); - Ok(Json(auth_url)) + Ok(Json(match path { + Some(path) => format!("{path} is now the shared account"), + None => "No shared account".to_string(), + })) +} + +/// Disconnect one account: its triggers are deleted with it, since nothing else can act on +/// their registrations. +#[cfg(feature = "native_trigger")] +async fn delete_connection( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path((workspace_id, service_name)): Path<(String, ServiceName)>, + Query(ConnectionPathQuery { path }): Query<ConnectionPathQuery>, +) -> JsonResult<String> { + check_connection_scopes(&authed, &path)?; + require_is_writer( + &authed, + &path, + &workspace_id, + db.clone(), + "SELECT extra_perms FROM variable WHERE path = $1 AND workspace_id = $2", + "variable", + ) + .await?; + + let mut tx = user_db.clone().begin(&authed).await?; + let usable = list_usable_connections(&db, &mut tx, &workspace_id, service_name).await?; + tx.commit().await?; + if !usable.iter().any(|c| c.path == path) { + return Err(Error::NotFound(format!( + "No {service_name} connection at {path}" + ))); + } + + // Disconnecting deletes these triggers, so a path-scoped token must cover each of them. Only + // the rows checked here, at the paths checked, are deleted: one created or moved meanwhile is + // never removed unchecked. + let triggers = sqlx::query!( + "SELECT external_id, script_path FROM native_trigger + WHERE workspace_id = $1 AND service_name = $2 AND connection_path = $3", + workspace_id, + service_name as ServiceName, + path, + ) + .fetch_all(&db) + .await?; + for trigger in &triggers { + check_scopes(&authed, || { + format!("native_triggers:write:{}", trigger.script_path) + })?; + } + let (external_ids, script_paths): (Vec<String>, Vec<String>) = triggers + .into_iter() + .map(|t| (t.external_id, t.script_path)) + .unzip(); + + // Before the connection goes: removing the registrations needs its token. + delete_triggers_for_service( + &db, + &workspace_id, + service_name, + Some((&external_ids, &script_paths)), + ) + .await; + + let mut tx = user_db.begin(&authed).await?; + lock_connection(&mut tx, &workspace_id, &path).await?; + let account = cleanup_connection(&mut *tx, &workspace_id, &path).await?; + + // A trigger moved or created meanwhile was skipped above and still acts through this + // connection, so removing the connection would strand it. `lock_connection` is what makes + // this check sound: a create stores its trigger under the same lock, so it either committed + // before this transaction took the lock, and is seen here, or it waits and finds the + // connection gone. + let still_used = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM native_trigger + WHERE workspace_id = $1 AND service_name = $2 AND connection_path = $3)", + workspace_id, + service_name as ServiceName, + path, + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false); + if still_used { + tx.rollback().await?; + return Err(Error::BadRequest(format!( + "A trigger using {path} changed while disconnecting, so the connection was kept. \ + Disconnect again to remove it." + ))); + } + + // A connection made later at this path must not inherit the sharing. + sqlx::query!( + "UPDATE workspace_integrations SET resource_path = NULL + WHERE workspace_id = $1 AND service_name = $2 AND resource_path = $3", + workspace_id, + service_name as ServiceName, + path, + ) + .execute(&mut *tx) + .await?; + + audit_log( + &mut *tx, + &authed, + &format!("workspace_integrations.{}.disconnect", service_name), + ActionKind::Delete, + &workspace_id, + Some(&path), + None, + ) + .await?; + + tx.commit().await?; + delete_unlinked_account(&db, &workspace_id, account).await; + + Ok(Json(format!("Disconnected {path}"))) } #[cfg(feature = "native_trigger")] @@ -1031,9 +1357,14 @@ pub fn workspaced_service() -> Router { "/{service_name}/instance_sharing_available", get(check_instance_sharing_available), ) + .route("/{service_name}/connections", get(list_connections)) .route( - "/{service_name}/generate_instance_connect_url", - post(generate_instance_connect_url), + "/{service_name}/connections/delete", + delete(delete_connection), + ) + .route( + "/{service_name}/workspace_connection", + post(set_workspace_connection), ) .route("/{service_name}/delete", delete(delete_integration)) .route("/{service_name}/callback", post(oauth_callback)); diff --git a/backend/windmill-oauth/src/lib.rs b/backend/windmill-oauth/src/lib.rs index 9768911813..57fe97eac2 100644 --- a/backend/windmill-oauth/src/lib.rs +++ b/backend/windmill-oauth/src/lib.rs @@ -20,12 +20,10 @@ use std::fmt::Debug; use anyhow::anyhow; use hmac::Mac; use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use sqlx::{Postgres, Transaction}; use tower_cookies::{Cookie, Cookies}; use windmill_common::error::{self, to_anyhow, Error}; use windmill_common::more_serde::maybe_number_opt; use windmill_common::oauth2::*; -use windmill_common::utils::now_from_db; use windmill_common::BASE_URL; pub type DB = sqlx::Pool<sqlx::Postgres>; @@ -53,7 +51,8 @@ lazy_static::lazy_static! { pub static ref OAUTH_CLIENTS: arc_swap::ArcSwap<AllClients> = arc_swap::ArcSwap::from_pointee(AllClients { logins: HashMap::new(), connects: HashMap::new(), - slack: None + slack: None, + slack_signing_secret: None, }); } @@ -67,6 +66,8 @@ pub struct ClientWithScopes { pub extra_params_callback: Option<HashMap<String, String>>, pub allowed_domains: Option<Vec<String>>, pub userinfo_url: Option<String>, + /// See [`OAuthConfig::connect_fields`]. + pub connect_fields: Option<HashMap<String, String>>, pub grant_types: Vec<String>, pub token_response_path: Option<String>, /// Resolved token endpoint, exposed so the connect dialog can prefill and @@ -89,6 +90,15 @@ pub struct OAuthConfig { #[serde(default = "empty_string")] pub token_url: String, pub userinfo_url: Option<String>, + /// Resource fields the connect callback fills from what the provider returns, + /// as field -> path (see [`connect_resource_fields`]). A path starts with its + /// source: `token.` (the raw token response, before `token_response_path` + /// unwraps it), `userinfo.` (`userinfo_url`'s response, fetched only when a + /// path needs it) or `callback.` (the callback URL's query params). The browser + /// relays `callback.` values, so they only prefill the user's own resource: + /// nothing server-side may trust them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub connect_fields: Option<HashMap<String, String>>, /// The registry JSON may also carry frontend-only keys for the connect /// dialog, deliberately not modelled here: `scope_options`, a scope pick /// list, `resource_fields`, the fields of the resource type the dialog @@ -254,6 +264,13 @@ pub struct OAuthClient { pub tenant: Option<String>, #[serde(default = "default_grant_types")] pub grant_types: Vec<String>, + /// The Slack app's signing secret, which authenticates the requests Slack sends Windmill. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "windmill_common::utils::empty_as_none" + )] + pub signing_secret: Option<String>, } impl std::fmt::Debug for OAuthClient { @@ -267,6 +284,10 @@ impl std::fmt::Debug for OAuthClient { .field("login_config", &self.login_config) .field("tenant", &self.tenant) .field("grant_types", &self.grant_types) + .field( + "signing_secret", + &self.signing_secret.as_ref().map(|_| "***"), + ) .finish() } } @@ -288,11 +309,23 @@ fn default_grant_types() -> Vec<String> { } /// Container for all OAuth clients (login, connect, and slack) -#[derive(Debug)] pub struct AllClients { pub logins: BasicClientsMap, pub connects: BasicClientsMap, pub slack: Option<OClient>, + /// The instance Slack app's signing secret, from its OAuth setting. + pub slack_signing_secret: Option<String>, +} + +impl std::fmt::Debug for AllClients { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AllClients") + .field("logins", &self.logins) + .field("connects", &self.connects) + .field("slack", &self.slack) + .field("slack_signing_secret", &self.slack_signing_secret.as_ref().map(|_| "***")) + .finish() + } } /// Slack token response from OAuth flow @@ -331,6 +364,10 @@ pub struct SlackTeam { pub struct OAuthCallback { pub code: String, pub state: String, + /// The callback URL's other query params (QuickBooks' `realmId`), read by + /// `connect_fields` paths under `callback.`. + #[serde(default)] + pub params: HashMap<String, String>, } /// Build a basic OAuth client from configuration @@ -517,6 +554,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()), + signing_secret: None, }; let base_url = (**BASE_URL.load()).clone(); @@ -879,6 +917,48 @@ pub fn parse_token_response( }) } +/// What the connect callback returns: the token, and the resource fields its +/// `connect_fields` picked, which the connect dialog prefills. +#[derive(Debug, Serialize)] +pub struct ConnectCallbackResponse { + #[serde(flatten)] + pub token: TokenResponse, + #[serde(skip_serializing_if = "HashMap::is_empty")] + pub resource_fields: HashMap<String, serde_json::Value>, +} + +/// Picks each field's value out of `sources` (`{token, userinfo, callback}`). A path +/// is dot-separated keys, and a `key[k=v]` segment takes the element of array `key` +/// whose `k` is `v` (`userinfo.accounts[is_default=true].base_uri`). Only the listed +/// paths leave the server, and fields whose path misses are left out. +pub fn connect_resource_fields( + sources: &serde_json::Value, + fields: &HashMap<String, String>, +) -> HashMap<String, serde_json::Value> { + fn get<'a>(v: &'a serde_json::Value, path: &str) -> Option<&'a serde_json::Value> { + path.split('.') + .try_fold(v, |v, seg| match seg.split_once('[') { + Some((key, filter)) => { + let (k, want) = filter.strip_suffix(']')?.split_once('=')?; + v.get(key)?.as_array()?.iter().find(|e| match e.get(k) { + Some(serde_json::Value::String(s)) => s == want, + Some(other) => other.to_string() == want, + None => false, + }) + } + None => v.get(seg), + }) + } + fields + .iter() + .filter_map(|(field, path)| { + get(sources, path) + .filter(|v| !v.is_null()) + .map(|v| (field.clone(), v.clone())) + }) + .collect() +} + /// Pre-fetched account fields needed for token refresh. pub struct OAuthAccountInfo { pub client: String, @@ -890,61 +970,39 @@ pub struct OAuthAccountInfo { pub scopes: Option<Vec<String>>, } -/// Refresh an OAuth token and update the `account` row. -/// Fetches the account from DB, then delegates to `refresh_token_for_account`. -/// -/// Returns the freshly minted access token. Persisting it to the secret variable -/// backing the resource is the caller's responsibility (it must route through the -/// configured secret backend — see `store_oauth_token_value` in `windmill-store`). -pub async fn refresh_token<'c>( - mut tx: Transaction<'c, Postgres>, - w_id: &str, - id: i32, - db: &DB, - oauth_clients: &AllClients, - http_client: &reqwest::Client, - connect_configs_json: &str, -) -> error::Result<String> { - let account = sqlx::query_as!( - OAuthAccountInfo, - "SELECT client, refresh_token, grant_type, cc_client_id, cc_client_secret, cc_token_url, scopes FROM account WHERE workspace_id = $1 AND id = $2", - w_id, - id, - ) - .fetch_optional(&mut *tx) - .await?; - let account = windmill_common::utils::not_found_if_none(account, "Account", &id.to_string())?; - - refresh_token_for_account( - tx, - w_id, - id, - db, - account, - oauth_clients, - http_client, - connect_configs_json, - ) - .await +/// A refresh the provider answered with a new access token. +pub struct RefreshedToken { + pub access_token: String, + /// The rotated refresh token, when the provider issued one. + pub refresh_token: Option<String>, + pub expires_in: i64, } -/// Refresh an OAuth token given pre-fetched account info (no additional SELECT). +pub enum RefreshError { + /// The provider refused the exchange: recorded on the account as `refresh_error`. + Provider(String), + Other(Error), +} + +impl From<Error> for RefreshError { + fn from(e: Error) -> Self { + RefreshError::Other(e) + } +} + +/// Exchange an account's refresh token (or client credentials) with its provider. /// -/// Exchanges the refresh token, updates the `account` row (`refresh_token`, -/// `expires_at`, `refresh_error`) and returns the new access token. It does NOT -/// persist the token to the secret variable — the caller must do that through the -/// configured secret backend (`store_oauth_token_value`), otherwise an external -/// secret backend would keep serving the stale connect-time token. -pub async fn refresh_token_for_account<'c>( - mut tx: Transaction<'c, Postgres>, +/// Holds no connection across the HTTP call and writes nothing: the caller records the +/// outcome on the `account` row and persists the access token through the secret backend. +pub async fn exchange_account_token( + db: &DB, w_id: &str, id: i32, - db: &DB, - account: OAuthAccountInfo, + account: &OAuthAccountInfo, oauth_clients: &AllClients, http_client: &reqwest::Client, connect_configs_json: &str, -) -> error::Result<String> { +) -> Result<RefreshedToken, RefreshError> { // Instance-configured client: required for authorization_code (the refresh // token exchange uses the instance app's credentials). For client_credentials // it is resolved inside `build_client_credentials_oauth_client` instead. @@ -1043,48 +1101,13 @@ pub async fn refresh_token_for_account<'c>( ) .await; - if let Err(token_err) = token { - sqlx::query!( - "UPDATE account SET refresh_error = $1 WHERE workspace_id = $2 AND id = $3", - token_err.alt(), - w_id, - id, - ) - .execute(&mut *tx) - .await?; - tx.commit().await?; - return Err(error::Error::BadRequest(format!( - "Error refreshing token: {}", - token_err.alt() - ))); - }; + let token = token.map_err(|e| RefreshError::Provider(e.alt()))?; - let token = token.unwrap(); - - let expires_at = now_from_db(&mut *tx).await? - + chrono::Duration::try_seconds( - token - .expires_in - .ok_or_else(|| Error::InternalErr("expires_in expected and not found".to_string()))? - .try_into() - .unwrap(), - ) - .unwrap_or_default(); - sqlx::query!( - "UPDATE account SET refresh_token = $1, expires_at = $2, refresh_error = NULL WHERE workspace_id = $3 AND id = $4", - token - .refresh_token - .map(|x| x.to_string()) - .unwrap_or(account.refresh_token), - expires_at, - w_id, - id, - ) - .execute(&mut *tx) - .await?; - tx.commit().await?; - - let token_str = token.access_token.to_string(); + let expires_in = token + .expires_in + .ok_or_else(|| Error::InternalErr("expires_in expected and not found".to_string()))? + .try_into() + .unwrap_or(i64::MAX); tracing::info!( grant_type = %account.grant_type, @@ -1094,7 +1117,11 @@ pub async fn refresh_token_for_account<'c>( "OAuth token refreshed successfully" ); - Ok(token_str) + Ok(RefreshedToken { + access_token: token.access_token.to_string(), + refresh_token: token.refresh_token.map(|t| t.to_string()), + expires_in, + }) } /// Generate OAuth redirect URL with CSRF protection @@ -1290,11 +1317,50 @@ mod tests { assert_eq!(&*token.access_token, "xoxe.xoxp-new"); } + #[test] + fn connect_fields_pick_from_each_source() { + let registry: HashMap<String, OAuthConfig> = + serde_json::from_str(include_str!("../../oauth_connect.json")).unwrap(); + let fields = |p: &str| registry[p].connect_fields.clone().unwrap(); + + let docusign = serde_json::json!({"userinfo": {"accounts": [ + {"account_id": "a1", "is_default": false, "base_uri": "https://na2.docusign.net"}, + {"account_id": "a2", "is_default": true, "base_uri": "https://demo.docusign.net"} + ]}}); + let got = connect_resource_fields(&docusign, &fields("docusign")); + assert_eq!(got["account_id"], "a2"); + assert_eq!(got["base_uri"], "https://demo.docusign.net"); + let no_account = serde_json::json!({"userinfo": {"accounts": []}}); + assert!(connect_resource_fields(&no_account, &fields("docusign")).is_empty()); + + let salesforce = serde_json::json!({"token": { + "access_token": "t", "instance_url": "https://acme.my.salesforce.com", "id_token": "x" + }}); + let want = HashMap::from([( + "instance_url".to_string(), + serde_json::json!("https://acme.my.salesforce.com"), + )]); + assert_eq!( + connect_resource_fields(&salesforce, &fields("salesforce")), + want + ); + let sandbox = registry["salesforce"].as_sandbox().unwrap(); + 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")); + assert_eq!( + got, + HashMap::from([("realmId".to_string(), serde_json::json!("9130"))]) + ); + } + fn sample_oauth_config(with_sandbox: bool) -> OAuthConfig { OAuthConfig { auth_url: "https://account.example.com/oauth/auth".to_string(), token_url: "https://account.example.com/oauth/token".to_string(), userinfo_url: Some("https://account.example.com/userinfo".to_string()), + connect_fields: None, scopes: Some(vec!["signature".to_string()]), cc_scopes: None, extra_params: None, diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index eafb344870..b78da75edf 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -42,8 +42,8 @@ use windmill_common::auth::JobPerms; #[cfg(feature = "benchmark")] use windmill_common::bench::BenchmarkIter; use windmill_common::jobs::{ - script_path_to_payload, JobTriggerKind, TriggerKindLabel, EMAIL_ERROR_HANDLER_USER_EMAIL, - MODULES_ARG, + args_contain_nul, normalize_nul_in_args, sanitize_untrusted_args, script_path_to_payload, + JobTriggerKind, TriggerKindLabel, EMAIL_ERROR_HANDLER_USER_EMAIL, MODULES_ARG, }; use windmill_common::min_version::{ MIN_VERSION_SUPPORTS_DEBOUNCING, MIN_VERSION_SUPPORTS_DEBOUNCING_V2, @@ -54,6 +54,7 @@ use windmill_common::runnable_settings::{ }; use windmill_common::triggers::TriggerMetadata; use windmill_common::utils::{calculate_hash, configure_client, now_from_db, strip_json_nul}; +use windmill_common::variables::omit_untrusted_interpolation; use windmill_common::worker::Connection; use windmill_common::otel_oss::{ @@ -169,12 +170,15 @@ const ERROR_HANDLER_USERNAME: &str = "error_handler"; pub const SCHEDULE_ERROR_HANDLER_USERNAME: &str = "schedule_error_handler"; const GLOBAL_ERROR_HANDLER_USERNAME: &str = "global"; const SUCCESS_HANDLER_USERNAME: &str = "success_handler"; +const VARIABLE_EXPIRATION_HANDLER_USERNAME: &str = "variable_expiration_handler"; pub const ERROR_HANDLER_USER_GROUP: &str = "g/error_handler"; pub const ERROR_HANDLER_USER_EMAIL: &str = "error_handler@windmill.dev"; pub const SCHEDULE_ERROR_HANDLER_USER_EMAIL: &str = "schedule_error_handler@windmill.dev"; pub const SUCCESS_HANDLER_USER_GROUP: &str = "g/success_handler"; pub const SUCCESS_HANDLER_USER_EMAIL: &str = "success_handler@windmill.dev"; +pub const VARIABLE_EXPIRATION_HANDLER_USER_GROUP: &str = "g/variable_expiration_handler"; +pub const VARIABLE_EXPIRATION_HANDLER_USER_EMAIL: &str = "variable_expiration_handler@windmill.dev"; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CanceledBy { @@ -479,6 +483,9 @@ pub const PERIODIC_SCRIPT_TAG: &str = "periodic_bash_script"; pub const INIT_SCRIPT_TAG: &str = "init_script"; pub const INIT_SCRIPT_PATH_PREFIX: &str = "init_script_"; pub const PERIODIC_SCRIPT_PATH_PREFIX: &str = "periodic_script_"; +/// The email the worker's own init/periodic scripts are pushed under by [`push_init_job`] +/// and [`push_periodic_bash_job`]. +pub const WORKER_SCRIPT_EMAIL: &str = "worker@windmill.dev"; pub async fn push_init_job<'c>( db: &Pool<Postgres>, @@ -507,7 +514,7 @@ pub async fn push_init_job<'c>( }), PushArgs::from(&ehm), worker_name, - "worker@windmill.dev", + WORKER_SCRIPT_EMAIL, SUPERADMIN_SECRET_EMAIL.to_string(), Some("worker_init_job"), None, @@ -568,7 +575,7 @@ pub async fn push_periodic_bash_job<'c>( }), PushArgs::from(&ehm), worker_name, - "worker@windmill.dev", + WORKER_SCRIPT_EMAIL, SUPERADMIN_SECRET_EMAIL.to_string(), Some("worker_periodic_script_job"), None, @@ -1641,6 +1648,7 @@ async fn commit_completed_job<T: Serialize + Send + Sync + ValidableJson>( } let mut _skip_downstream_error_handlers = false; + let mut schedule_for_handlers = None; if completed_job.is_flow_step() { if let Some(parent_job) = monitor_parent { let r = sqlx::query_scalar!( @@ -1720,49 +1728,9 @@ async fn commit_completed_job<T: Serialize + Send + Sync + ValidableJson>( // per-occurrence failure/recovery status across the whole retry // chain, so multi-count/exact handler policies work even though // each attempt is its own completed job. - #[cfg(all(feature = "enterprise", feature = "private"))] if !retry_pending { - if let Err(err) = crate::jobs_ee::apply_schedule_handlers( - db, - &schedule, - &script_path, - &completed_job.workspace_id, - success, - result, - job_id, - // Current occurrence's root: the terminal native-retry - // attempt's parent, else the job itself. - completed_job.parent_job.unwrap_or(job_id), - completed_job.started_at.unwrap_or(chrono::Utc::now()), - completed_job.priority, - ) - .warn_after_seconds(10) - .await - { - if !success { - tracing::error!("Could not apply schedule error handler: {}", err); - let base_url = windmill_common::BASE_URL.load(); - let w_id: &String = &completed_job.workspace_id; - if !matches!(err, Error::QuotaExceeded(_)) { - report_error_to_workspace_handler_or_critical_side_channel( - &completed_job, - db, - format!( - "Failed to push schedule error handler job to handle failed job ({base_url}/run/{}?workspace={w_id}): {}", - completed_job.id, - err - ), - ) - .warn_after_seconds(10) - .await; - } - } else { - tracing::error!("Could not apply schedule recovery handler: {}", err); - } - }; + schedule_for_handlers = Some((schedule, script_path)); } - #[cfg(not(all(feature = "enterprise", feature = "private")))] - let _ = retry_pending; } else { tracing::error!( "Schedule {schedule_path} in {} not found. Impossible to schedule again and apply schedule handlers", @@ -1824,6 +1792,52 @@ async fn commit_completed_job<T: Serialize + Send + Sync + ValidableJson>( tx.commit().warn_after_seconds(10).await?; + // The handlers read and push through `db`, so they run after the commit: inside the + // transaction they would hold its connection while waiting for more from the same pool. + #[cfg(all(feature = "enterprise", feature = "private"))] + if let Some((schedule, script_path)) = schedule_for_handlers { + if let Err(err) = crate::jobs_ee::apply_schedule_handlers( + db, + &schedule, + script_path, + &completed_job.workspace_id, + success, + result, + job_id, + // Current occurrence's root: the terminal native-retry + // attempt's parent, else the job itself. + completed_job.parent_job.unwrap_or(job_id), + completed_job.started_at.unwrap_or(chrono::Utc::now()), + completed_job.priority, + ) + .warn_after_seconds(10) + .await + { + if !success { + tracing::error!("Could not apply schedule error handler: {}", err); + let base_url = windmill_common::BASE_URL.load(); + let w_id: &String = &completed_job.workspace_id; + if !matches!(err, Error::QuotaExceeded(_)) { + report_error_to_workspace_handler_or_critical_side_channel( + &completed_job, + db, + format!( + "Failed to push schedule error handler job to handle failed job ({base_url}/run/{}?workspace={w_id}): {}", + completed_job.id, + err + ), + ) + .warn_after_seconds(10) + .await; + } + } else { + tracing::error!("Could not apply schedule recovery handler: {}", err); + } + }; + } + #[cfg(not(all(feature = "enterprise", feature = "private")))] + let _ = schedule_for_handlers; + log_completed_job(completed_job, completed.duration_ms, success); // tracing::info!("completed job: {:?}", start.elapsed().as_micros()); Ok(( @@ -3591,6 +3605,100 @@ pub async fn push_error_handler<'a, 'c, T: Serialize + Send + Sync>( return Ok(uuid); } +/// Handler arguments, so the field names are wire format. Never add the value: job args and +/// results are stored in cleartext and shown in Runs. +#[derive(Serialize)] +pub struct ExpiringVariable { + pub workspace_id: String, + pub variable_path: String, + pub description: String, + pub value_valid_until: DateTime<Utc>, + pub is_secret: bool, +} + +/// Takes and returns the caller's transaction so the claim and the push commit together. +pub(crate) async fn push_variable_expiration_handler<'c>( + db: &Pool<Postgres>, + tx: Transaction<'c, Postgres>, + w_id: &str, + (payload, tag, on_behalf_of): ( + JobPayload, + Option<String>, + Option<windmill_common::jobs::OnBehalfOf>, + ), + expiring: &ExpiringVariable, + extra_args: Option<Json<Box<RawValue>>>, +) -> windmill_common::error::Result<(Uuid, Transaction<'c, Postgres>)> { + // Serialized whole so a new `ExpiringVariable` field reaches handlers. Any writer of the + // variable controls these, so only they are neutralized: the admin's `extra_args` keep their + // `$res:` references, which is how the handler gets its token. + let mut extra = omit_untrusted_interpolation( + serde_json::from_value(serde_json::to_value(expiring)?)?, + "The following resource has been omitted for security reasons: ", + ); + + if let Some(args_v) = extra_args { + if let Ok(args_m) = serde_json::from_str::<HashMap<String, Box<RawValue>>>(args_v.get()) { + extra.extend(args_m); + } else { + return Err(error::Error::ExecutionErr( + "args of scripts needs to be dict".to_string(), + )); + } + } + + let (email, permissioned_as) = if let Some(on_behalf_of) = on_behalf_of.as_ref() { + ( + on_behalf_of.email.as_str(), + on_behalf_of.permissioned_as.clone(), + ) + } else { + ( + VARIABLE_EXPIRATION_HANDLER_USER_EMAIL, + VARIABLE_EXPIRATION_HANDLER_USER_GROUP.to_string(), + ) + }; + + let empty: HashMap<String, Box<RawValue>> = HashMap::new(); + let args = PushArgs { extra: Some(extra), args: &empty }; + push( + db, + PushIsolationLevel::Transaction(tx), + w_id, + payload, + args, + VARIABLE_EXPIRATION_HANDLER_USERNAME, + email, + permissioned_as, + Some(&format!( + "variable.expiration.{}", + expiring.variable_path.replace('/', ".") + )), + None, + None, + None, + None, + None, + None, + None, + false, + false, + None, + true, + tag, + None, + None, + None, + None, + false, + None, + None, + None, + None, + ) + .await +} + pub async fn push_success_handler<'a, 'c, T: Serialize + Send + Sync>( db: &Pool<Postgres>, job_id: Uuid, @@ -3681,10 +3789,16 @@ pub async fn push_success_handler<'a, 'c, T: Serialize + Send + Sync>( return Ok(uuid); } +/// A handler's args from the job's result, which the job's author controls while the handler +/// runs as its own identity. fn sanitize_result<T: Serialize + Send + Sync>(result: Json<&T>) -> HashMap<String, Box<RawValue>> { let as_str = serde_json::to_string(result.0).unwrap_or_else(|_| "{}".to_string()); - serde_json::from_str::<HashMap<String, Box<RawValue>>>(&as_str) - .unwrap_or_else(|_| [("error".to_string(), RawValue::from_string(as_str).unwrap())].into()) + let args = serde_json::from_str::<HashMap<String, Box<RawValue>>>(&as_str) + .unwrap_or_else(|_| [("error".to_string(), RawValue::from_string(as_str).unwrap())].into()); + omit_untrusted_interpolation( + args, + "The following resource has been omitted for security reasons: ", + ) } // #[derive(Serialize)] @@ -3744,6 +3858,25 @@ pub struct MiniPulledJob { } impl MiniPulledJob { + /// Whether this is an init or periodic script a worker queued for itself + /// ([`push_init_job`], [`push_periodic_bash_job`]). These run outside any sandbox, so every + /// executor that skips isolation uses this check. + pub fn is_worker_own_script(&self) -> bool { + let own_script = |own_tag: &str, path_prefix: &str| { + self.tag == own_tag + && self + .runnable_path + .as_ref() + .is_some_and(|p| p.starts_with(path_prefix)) + }; + self.workspace_id == "admins" + && self.permissioned_as == SUPERADMIN_SECRET_EMAIL + && self.permissioned_as_email == WORKER_SCRIPT_EMAIL + && self.parent_job.is_none() + && (own_script(INIT_SCRIPT_TAG, INIT_SCRIPT_PATH_PREFIX) + || own_script(PERIODIC_SCRIPT_TAG, PERIODIC_SCRIPT_PATH_PREFIX)) + } + pub fn new_inline( workspace_id: String, args: Option<HashMap<String, Box<RawValue>>>, @@ -6020,6 +6153,18 @@ impl PushArgsOwned { pub fn empty() -> Self { PushArgsOwned { extra: None, args: HashMap::new() } } + + /// Mark these args as coming from an untrusted third party: see + /// [`windmill_common::jobs::sanitize_untrusted_args`]. Applied to both maps, because a + /// name in `extra` wins over the same name in `args` when the job is serialized, and no + /// source that builds args from a third party's payload sets a reserved control key of + /// its own. + pub fn sanitize_untrusted(&mut self) { + sanitize_untrusted_args(&mut self.args); + if let Some(extra) = self.extra.as_mut() { + sanitize_untrusted_args(extra); + } + } } pub fn empty_result() -> Box<RawValue> { @@ -6200,6 +6345,38 @@ pub async fn push<'c, 'd>( .await } +/// Reads a flow version through the pool unless the caller handed `push` its own transaction, +/// which may hold that version uncommitted. Opening a transaction just for this read would hold +/// its connection while `push` still writes the runnable settings through the pool. +async fn fetch_pushed_flow_version( + tx: &mut PushIsolationLevel<'_>, + db: &Pool<Postgres>, + version: i64, +) -> error::Result<Arc<FlowData>> { + // Do not use the lite version unless all workers are updated. + let lite = + !(*DISABLE_FLOW_SCRIPT || (!MIN_VERSION_IS_AT_LEAST_1_432.met().await && !*CLOUD_HOSTED)); + // Fallback to the original version if the lite version is not found. + // This also prevent a race condition where the flow is run just after deploy and + // the lite version is still being created. + macro_rules! fetch { + ($e:expr) => { + if lite { + match cache::flow::fetch_version_lite($e, version).await { + Ok(data) => Ok(data), + Err(_) => cache::flow::fetch_version($e, version).await, + } + } else { + cache::flow::fetch_version($e, version).await + } + }; + } + match tx { + PushIsolationLevel::Transaction(ntx) => fetch!(&mut **ntx), + PushIsolationLevel::Isolated(..) | PushIsolationLevel::IsolatedRoot(_) => fetch!(db), + } +} + // #[instrument(level = "trace", skip_all)] async fn push_inner<'c, 'd>( db: &Pool<Postgres>, @@ -6233,21 +6410,34 @@ async fn push_inner<'c, 'd>( suspended_mode: Option<bool>, scope_ceiling: Option<&[String]>, ) -> Result<(Uuid, Transaction<'c, Postgres>), Error> { - // The worker builds a preview's `_MODULES` arg into the job as its module code. Every - // caller-reachable value lands in `args` or `extra` (webhook query and headers go to - // `extra`, WAC children copy their parent's args), so it is dropped from both and only - // the `JobPayload::Code` arm below sets it, from the server-side `RawCode::modules`. - let args_without_modules; + // Normalize the names and values to what the INSERT below will actually store before + // anything here goes by a name: `strip_json_nul` runs over the serialized args just + // before that INSERT and removes `\u0000` escapes from keys as well as values, so a + // name compared as sent is not the name that lands in the job. Without this, `_MODULES` + // is dropped below while `_MODULES\0` is stored as `_MODULES` and built into a preview's + // job directory as module code; likewise the serializer's "`extra` wins this name" rule + // (which is how an app policy's `static_inputs` override a viewer's args) compares the + // name as sent, so `tenant\0` is written after the pinned `tenant` and jsonb keeps the + // viewer's, as the later of two equal keys. The final strip stays, harmless once this + // has run. + let normalized_args; let mut args = { let mut extra = args.extra; if let Some(extra) = extra.as_mut() { + normalize_nul_in_args(extra); + // The worker builds a preview's `_MODULES` arg into the job as its module code. + // Every caller-reachable value lands in `args` or `extra` (webhook query and + // headers go to `extra`, WAC children copy their parent's args), so it is + // dropped from both and only the `JobPayload::Code` arm below sets it, from the + // server-side `RawCode::modules`. extra.remove(MODULES_ARG); } - let args = if args.args.contains_key(MODULES_ARG) { + let args = if args_contain_nul(args.args) || args.args.contains_key(MODULES_ARG) { let mut stripped = args.args.clone(); + normalize_nul_in_args(&mut stripped); stripped.remove(MODULES_ARG); - args_without_modules = stripped; - &args_without_modules + normalized_args = stripped; + &normalized_args } else { args.args }; @@ -6311,6 +6501,7 @@ async fn push_inner<'c, 'd>( if !team_plan_status.premium && email != ERROR_HANDLER_USER_EMAIL && email != SCHEDULE_ERROR_HANDLER_USER_EMAIL + && email != VARIABLE_EXPIRATION_HANDLER_USER_EMAIL && email != recovery_email && email != "worker@windmill.dev" && email != SUPERADMIN_SECRET_EMAIL @@ -6763,9 +6954,7 @@ async fn push_inner<'c, 'd>( restarted_from_val.branch_or_iteration_n, restarted_from_val.flow_version, restarted_from_val.nested.is_some(), - // RawFlow queues the request's (possibly edited) definition, not the - // stored one, so zombie reuse of the stored step is unsafe here. - false, + Some(&value), ) .await?; FlowStatus { @@ -7078,22 +7267,7 @@ async fn push_inner<'c, 'd>( labels, job_token_scopes, } => { - let mut ntx = tx.into_tx().await?; - // Do not use the lite version unless all workers are updated. - let data = if *DISABLE_FLOW_SCRIPT - || (!MIN_VERSION_IS_AT_LEAST_1_432.met().await && !*CLOUD_HOSTED) - { - cache::flow::fetch_version(&mut *ntx, version).await - } else { - // Fallback to the original version if the lite version is not found. - // This also prevent a race condition where the flow is run just after deploy and - // the lite version is still being created. - match cache::flow::fetch_version_lite(&mut *ntx, version).await { - Ok(data) => Ok(data), - Err(_) => cache::flow::fetch_version(&mut *ntx, version).await, - } - }?; - tx = PushIsolationLevel::Transaction(ntx); + let data = fetch_pushed_flow_version(&mut tx, db, version).await?; let mut value = data.value().clone(); refuse_step_scopes_on_outdated_workers(&value).await?; @@ -7176,7 +7350,7 @@ async fn push_inner<'c, 'd>( nested.is_some(), // RestartedFlow resolves and queues the completed job's stored definition, so the // step validated for reuse is the one that will run. - true, + None, ) .await?; @@ -7463,6 +7637,19 @@ async fn push_inner<'c, 'd>( crate::tags::apply_dev_workspace_suffix(tag, workspace_id, db).await? }; + // Before `into_tx`: these write through the pool on a cache miss, and a burst of pushes each + // holding its transaction would then wait on each other for a second connection. They stay + // off `tx` because they are cached as written, which a rollback would undo. + let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( + RunnableSettings { + debouncing_settings: debouncing_settings.insert_cached(db).await?, + concurrency_settings: concurrency_settings.insert_cached(db).await?, + retry_settings: retry_settings.insert_cached(db).await?, + }, + db, + ) + .await?; + let mut tx = tx.into_tx().await?; let job_id: Uuid = if let Some(job_id) = job_id { @@ -7642,16 +7829,6 @@ async fn push_inner<'c, 'd>( (job_kind, scheduled_for_o) }; - let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( - RunnableSettings { - debouncing_settings: debouncing_settings.insert_cached(db).await?, - concurrency_settings: concurrency_settings.insert_cached(db).await?, - retry_settings: retry_settings.insert_cached(db).await?, - }, - db, - ) - .await?; - let (guarded_concurrent_limit, guarded_concurrency_time_window_s) = if windmill_common::runnable_settings::min_version_supports_runnable_settings_v0().await { (None, None) @@ -8382,6 +8559,29 @@ pub async fn fetch_restart_flow_version( cache::flow::fetch_version(db, version).await } +// A restart copies the steps before the restart step as completed, and the worker only gates the +// restart step on a copied approval when that gate opened in the original run. So a copied step +// whose gate never opened (timed out, disapproved) would let the restart skip its approval. +fn refuse_restart_past_unopened_suspend_gate( + flow_value: &FlowValue, + copied_modules: &[FlowStatusModule], +) -> Result<(), Error> { + for module in copied_modules { + let id = module.id(); + let suspend = flow_value + .modules + .iter() + .find(|m| m.id == id) + .and_then(|m| m.suspend.as_ref()); + if module.suspend_gate_never_opened(suspend) { + return Err(Error::BadRequest(format!( + "Step {id} was never approved. Restart the flow from step {id} to request the approval again." + ))); + } + } + Ok(()) +} + async fn restarted_flows_resolution( db: &Pool<Postgres>, workspace_id: &str, @@ -8392,12 +8592,12 @@ async fn restarted_flows_resolution( // A nested restart chain (RestartedFrom.nested) descends into the restart step's child to // re-run an inner step; zombie reuse would skip the whole container and ignore it. nested_restart: bool, - // Zombie reuse validates the restart step against the completed job's STORED definition and - // synthesizes Success from its recorded children. That is only sound when the run being queued - // uses that same definition (JobPayload::RestartedFlow). A JobPayload::RawFlow restart queues - // the editor's current, possibly EDITED, definition instead, so reuse would skip the edited - // step and reuse the old child result; disable it there. - allow_zombie_reuse: bool, + // The definition the restart queues when it is not the completed job's stored one + // (JobPayload::RawFlow queues the editor's, possibly EDITED, definition). Approval gates are + // read from it. Zombie reuse validates the restart step against the STORED definition and + // synthesizes Success from its recorded children, so it is disabled when this is set: reuse + // would skip the edited step and reuse the old child result. + queued_flow: Option<&FlowValue>, ) -> Result< ( Option<i64>, @@ -8458,6 +8658,8 @@ async fn restarted_flows_resolution( }; let flow_value = flow_data.value(); + let allow_zombie_reuse = queued_flow.is_none(); + let gate_flow = queued_flow.unwrap_or(flow_value); let flow_status = row .flow_status .as_ref() @@ -8478,6 +8680,7 @@ async fn restarted_flows_resolution( let module_id = &module_definition.id; if module_id == restart_step_id { + refuse_restart_past_unopened_suspend_gate(gate_flow, &truncated_modules)?; // Mark this and all following modules as WaitingForPriorSteps if branch_or_iteration_n.is_none() || branch_or_iteration_n.unwrap() == 0 { truncated_modules @@ -8529,6 +8732,7 @@ async fn restarted_flows_resolution( continue; }; if module.id() == restart_step_id { + refuse_restart_past_unopened_suspend_gate(gate_flow, &truncated_modules)?; // Reuse is only safe when there is a NEXT step to advance into (advancing past the // last module lands on the failure step) and the step's definition carries no // completion/arming semantics that reuse would skip (stop predicates, skip_if, @@ -8802,6 +9006,111 @@ mod git_sync_concurrency_key_tests { } } +#[cfg(test)] +mod worker_own_script_tests { + use super::*; + + const WK: &str = "wk-default-host-a1b2c"; + + /// Built exactly as [`push_init_job`] and [`push_periodic_bash_job`] queue them. + fn own_script(path: &str, tag: &str) -> MiniPulledJob { + MiniPulledJob::new_inline( + "admins".to_string(), + None, + WK.to_string(), + SUPERADMIN_SECRET_EMAIL.to_string(), + WORKER_SCRIPT_EMAIL.to_string(), + Some(path.to_string()), + JobKind::Preview, + None, + tag.to_string(), + Some(ScriptLang::Bash), + ) + } + + /// The init and periodic scripts the worker queues for itself are recognised. + #[test] + fn what_the_worker_queues_for_itself_is_recognized() { + assert!( + own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}{WK}"), INIT_SCRIPT_TAG) + .is_worker_own_script() + ); + assert!(own_script( + &format!("{PERIODIC_SCRIPT_PATH_PREFIX}{WK}_1700000000"), + PERIODIC_SCRIPT_TAG + ) + .is_worker_own_script()); + } + + /// Only the exact shape the worker queues is recognised. + #[test] + fn other_job_shapes_are_not_recognized() { + let init = || own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}x"), INIT_SCRIPT_TAG); + let periodic = || { + own_script( + &format!("{PERIODIC_SCRIPT_PATH_PREFIX}x"), + PERIODIC_SCRIPT_TAG, + ) + }; + for (what, job) in [ + ( + "other workspace", + MiniPulledJob { workspace_id: "ws-a".to_string(), ..init() }, + ), + ( + "other permissioned_as", + MiniPulledJob { permissioned_as: "u/deva".to_string(), ..init() }, + ), + ( + "other email", + MiniPulledJob { permissioned_as_email: "deva@example.com".to_string(), ..init() }, + ), + ( + "flow step", + MiniPulledJob { parent_job: Some(Uuid::from_u128(1)), ..init() }, + ), + ( + "flow step", + MiniPulledJob { parent_job: Some(Uuid::from_u128(1)), ..periodic() }, + ), + ( + "user tag", + own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}x"), "bash"), + ), + ( + "crossed tag", + own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}x"), PERIODIC_SCRIPT_TAG), + ), + ( + "crossed tag", + own_script(&format!("{PERIODIC_SCRIPT_PATH_PREFIX}x"), INIT_SCRIPT_TAG), + ), + ("ordinary path", own_script("u/admin/s", INIT_SCRIPT_TAG)), + ( + "ordinary path", + own_script("u/admin/s", PERIODIC_SCRIPT_TAG), + ), + ] { + assert!( + !job.is_worker_own_script(), + "{what}: {:?}/{:?}/{} must not be recognised as a worker script", + job.workspace_id, + job.runnable_path, + job.tag + ); + } + } + + /// A job without a path is not a worker script. + #[test] + fn a_job_without_a_path_is_not_an_own_script() { + assert!( + !MiniPulledJob { runnable_path: None, ..own_script("x", INIT_SCRIPT_TAG) } + .is_worker_own_script() + ); + } +} + #[cfg(test)] mod preset_handler_path_tests { use super::is_preset_handler_path; @@ -8827,7 +9136,8 @@ mod preset_handler_path_tests { let hub_paths: std::collections::HashMap<String, String> = serde_json::from_str(include_str!("../../../frontend/src/lib/hubPaths.json")).unwrap(); for (name, path) in hub_paths { - if path.contains("-handler-") { + // Variable expiration handlers run as their own group whatever their path. + if path.contains("-handler-") && !path.contains("variable-expiration") { assert!( is_preset_handler_path(&path), "{name}: {path} is not pinned" @@ -8916,3 +9226,38 @@ mod render_tag_path_tests { RawValue::from_string(json.to_string()).unwrap() } } + +#[cfg(test)] +mod restart_past_suspend_gate_tests { + use super::refuse_restart_past_unopened_suspend_gate; + use serde_json::json; + use windmill_common::{flow_status::FlowStatusModule, flows::FlowValue}; + + #[test] + fn refuses_only_a_blocking_gate_that_never_opened() { + let flow = |suspend: serde_json::Value| -> FlowValue { + serde_json::from_value(json!({"modules": [ + {"id": "a", "value": {"type": "identity"}, "suspend": suspend}, + {"id": "b", "value": {"type": "identity"}}, + ]})) + .unwrap() + }; + let copied_a = |approvers: serde_json::Value| -> Vec<FlowStatusModule> { + vec![serde_json::from_value(json!({ + "type": "Success", "id": "a", "job": uuid::Uuid::new_v4(), "approvers": approvers + })) + .unwrap()] + }; + let blocking = flow(json!({"required_events": 1})); + let approved = json!([{"resume_id": 0, "approver": "admin"}]); + + assert!( + refuse_restart_past_unopened_suspend_gate(&blocking, &copied_a(json!([]))).is_err() + ); + assert!(refuse_restart_past_unopened_suspend_gate(&blocking, &copied_a(approved)).is_ok()); + let continues = flow(json!({"required_events": 1, "continue_on_disapprove_timeout": true})); + assert!( + refuse_restart_past_unopened_suspend_gate(&continues, &copied_a(json!([]))).is_ok() + ); + } +} diff --git a/backend/windmill-queue/src/lib.rs b/backend/windmill-queue/src/lib.rs index ff93ea2665..5358960635 100644 --- a/backend/windmill-queue/src/lib.rs +++ b/backend/windmill-queue/src/lib.rs @@ -34,6 +34,7 @@ pub mod jobs; pub mod jobs_ee; pub mod jobs_oss; pub mod schedule; +pub mod variable_expiration; pub use jobs::*; pub mod flow_status; pub mod tags; diff --git a/backend/windmill-queue/src/schedule.rs b/backend/windmill-queue/src/schedule.rs index 0041dceea0..e404e07f05 100644 --- a/backend/windmill-queue/src/schedule.rs +++ b/backend/windmill-queue/src/schedule.rs @@ -42,7 +42,6 @@ use windmill_common::{ /// Helper to fetch metadata for a schedule's script or flow async fn get_schedule_metadata<'c>( tx: &mut sqlx::Transaction<'c, sqlx::Postgres>, - db: &DB, schedule: &Schedule, ) -> Result<( Option<String>, // tag @@ -78,7 +77,12 @@ async fn get_schedule_metadata<'c>( Ok(( flow_info.tag.clone(), None, - flow_info.on_behalf_of(&schedule.workspace_id, db).await?, + windmill_common::on_behalf_of_from_permissioned_as( + flow_info.on_behalf_of.as_deref(), + &schedule.workspace_id, + &mut **tx, + ) + .await?, None, Some(version), parsed_retry, @@ -106,7 +110,6 @@ async fn get_schedule_metadata<'c>( _job_token_scopes, ) = windmill_common::get_latest_hash_for_path( &mut **tx, - db, &schedule.workspace_id, &schedule.script_path, false, @@ -117,6 +120,10 @@ async fn get_schedule_metadata<'c>( } } +/// Read identity and runnable settings through `tx` rather than `db`: every caller holds `tx` +/// open on the same pool, so a second checkout per tick starves it when a burst of schedules +/// fires at once. `tx` may run as `windmill_user` (schedule and flow API); those tables carry +/// no RLS, so they resolve the same as on the pool. pub async fn push_scheduled_job<'c>( db: &DB, mut tx: Transaction<'c, Postgres>, @@ -319,7 +326,7 @@ pub async fn push_scheduled_job<'c>( // Get metadata from the scheduled script/flow for tag, timeout, etc. let (tag, timeout, on_behalf_of, hash, flow_version, retry) = - get_schedule_metadata(&mut tx, db, schedule).await?; + get_schedule_metadata(&mut tx, schedule).await?; ( JobPayload::SingleStepFlow { @@ -373,7 +380,12 @@ pub async fn push_scheduled_job<'c>( ) .warn_after_seconds_with_sql(1, "get_flow_version_info_from_version".to_string()) .await?; - let on_behalf_of = flow_info.on_behalf_of(&schedule.workspace_id, db).await?; + let on_behalf_of = windmill_common::on_behalf_of_from_permissioned_as( + flow_info.on_behalf_of.as_deref(), + &schedule.workspace_id, + &mut *tx, + ) + .await?; let FlowVersionInfo { version, tag, dedicated_worker, labels, job_token_scopes, .. } = flow_info; @@ -453,7 +465,6 @@ pub async fn push_scheduled_job<'c>( job_token_scopes, ) = windmill_common::get_latest_hash_for_path( &mut *tx, - db, &schedule.workspace_id, &schedule.script_path, false, @@ -461,17 +472,11 @@ pub async fn push_scheduled_job<'c>( .warn_after_seconds_with_sql(1, "get_latest_hash_for_path".to_string()) .await?; - // NB: read on the non-RLS pool (`db`), not `tx`. push_scheduled_job is - // also invoked with an RLS user_db transaction (api-schedule/api-flows), - // under which these lookups would resolve against the caller's row - // visibility rather than the full table. The dual-connection here is - // intentional and required for correctness. + let rs = + windmill_common::runnable_settings::from_handle(runnable_settings_handle, &mut *tx) + .await?; let (debouncing_settings, concurrency_settings) = - windmill_common::runnable_settings::prefetch_cached_from_handle( - runnable_settings_handle, - db, - ) - .await?; + windmill_common::runnable_settings::prefetch_cached_tx(&rs, &mut tx).await?; if schedule.retry.is_some() { let parsed_retry = serde_json::from_value::<Retry>(schedule.retry.clone().unwrap()) @@ -598,7 +603,7 @@ pub async fn push_scheduled_job<'c>( let resolved_email = windmill_common::users::get_email_from_permissioned_as( &permissioned_as, &schedule.workspace_id, - db, + &mut *tx, ) .await?; (resolved_email, permissioned_as, authed, false) @@ -621,7 +626,7 @@ pub async fn push_scheduled_job<'c>( }; if let Some(tag) = tag.as_deref().filter(|t| !t.is_empty()) { - let is_super_admin = windmill_common::auth::is_super_admin_email(db, &email).await?; + let is_super_admin = windmill_common::auth::is_super_admin_email(&mut *tx, &email).await?; crate::check_tag_available_for_push( db, &schedule.workspace_id, diff --git a/backend/windmill-queue/src/variable_expiration.rs b/backend/windmill-queue/src/variable_expiration.rs new file mode 100644 index 0000000000..74c0eaf393 --- /dev/null +++ b/backend/windmill-queue/src/variable_expiration.rs @@ -0,0 +1,309 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2022 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! Dispatches the workspace variable expiration handler for variables coming due. + +use std::collections::{HashMap, HashSet}; + +use serde_json::value::RawValue; +use sqlx::types::Json; +use windmill_common::jobs::get_payload_tag_from_prefixed_path; +use windmill_common::utils::{report_critical_error, report_recovered_critical_error}; +use windmill_common::DB; + +use crate::jobs::{push_variable_expiration_handler, ExpiringVariable}; + +/// Lead time when the handler setting has no `notify_before_secs`. +const VARIABLE_EXPIRATION_DEFAULT_NOTIFY_BEFORE_SECS: i64 = 24 * 3600; + +/// Subtracted from `remind_every_secs` so a reminder whose interval is a multiple of the +/// sweep's period is not skipped by tick jitter. +const VARIABLE_EXPIRATION_REMINDER_SLACK_SECS: i64 = 30; + +/// Advisory lock id ensuring only one server replica sweeps at a time. Must not reuse one of +/// the other monitor pass locks (737_483_920..=737_483_925): both sides try-lock and skip. +const VARIABLE_EXPIRATION_LOCK_ID: i64 = 737_483_926; + +/// System caller only: dispatches across every workspace. A handler job that fails is not +/// re-dispatched before its next reminder, as re-running it would repeat its side effects +/// against the third party it rotates; retrying is the handler's job. +pub async fn dispatch_expiring_variables(db: &DB) { + // Transaction-scoped, not session-scoped: a session lock would go back to the pool still + // held if this future were dropped mid-pass, wedging the sweep on every replica. + let mut lock_tx = match db.begin().await { + Ok(tx) => tx, + Err(e) => { + tracing::error!("variable expiration: failed to begin lock tx: {e:#}"); + return; + } + }; + let locked: bool = match sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)") + .bind(VARIABLE_EXPIRATION_LOCK_ID) + .fetch_one(&mut *lock_tx) + .await + { + Ok(v) => v, + Err(e) => { + tracing::error!("variable expiration: advisory lock failed: {e:#}"); + return; + } + }; + if !locked { + return; + } + + dispatch_expiring_variables_inner(db).await; + + if let Err(e) = lock_tx.rollback().await { + tracing::error!("variable expiration: releasing lock failed: {e:#}"); + } +} + +async fn dispatch_expiring_variables_inner(db: &DB) { + resolve_removed_handlers(db).await; + + // No lower bound on `value_valid_until`, so a downed instance catches up. No cap either: + // everything due is tried every pass, so no workspace or kind of notice can be crowded out. + let due = sqlx::query!( + r#"SELECT v.workspace_id, v.path, v.description, v.value_valid_until AS "value_valid_until!", + v.is_secret, v.expiration_dispatched_for, v.expiration_notified_at, + ws.variable_expiration_handler->>'path' AS "handler_path!", + (ws.variable_expiration_handler->'extra_args')::text::json + AS "extra_args: Json<Box<RawValue>>" + FROM variable v + JOIN workspace_settings ws ON ws.workspace_id = v.workspace_id + JOIN workspace w ON w.id = v.workspace_id + WHERE NOT w.deleted + AND v.value_valid_until IS NOT NULL + AND (v.value_valid_until IS DISTINCT FROM v.expiration_dispatched_for + OR (v.value_valid_until > now() + AND v.expiration_notified_at <= now() - make_interval(secs => + NULLIF((ws.variable_expiration_handler->>'remind_every_secs')::bigint, 0) - $2))) + AND v.value_valid_until <= now() + make_interval(secs => + COALESCE((ws.variable_expiration_handler->>'notify_before_secs')::bigint, $1)) + AND ws.variable_expiration_handler->>'path' IS NOT NULL + AND (NOT COALESCE((ws.variable_expiration_handler->>'muted_on_user_path')::boolean, false) + OR v.path NOT LIKE 'u/%')"#, + VARIABLE_EXPIRATION_DEFAULT_NOTIFY_BEFORE_SECS, + VARIABLE_EXPIRATION_REMINDER_SLACK_SECS, + ) + .fetch_all(db) + .await; + + let due = match due { + Ok(due) => due, + Err(e) => { + tracing::error!("Error listing expiring variables: {e:#}"); + return; + } + }; + + let mut dispatched = 0usize; + // A handler fails alike for every variable of its workspace: try it once per pass. + let mut failed_this_pass: HashSet<String> = HashSet::new(); + // Hub handlers are shared by every workspace using them, so a hub outage is fetched once + // per pass rather than once per workspace. + let mut failed_hub_handlers: HashMap<String, String> = HashMap::new(); + + for row in due { + if failed_this_pass.contains(&row.workspace_id) { + continue; + } + // Resolved before the claim's transaction opens, so a pass never holds one connection + // while waiting on another. + let handler = match failed_hub_handlers.get(&row.handler_path) { + Some(error) => Err(error.clone()), + None => get_payload_tag_from_prefixed_path(&row.handler_path, db, &row.workspace_id) + .await + .map_err(|e| { + let error = format!("{e:#}"); + if row.handler_path.starts_with("script/hub/") + || row.handler_path.starts_with("flow/hub/") + { + failed_hub_handlers.insert(row.handler_path.clone(), error.clone()); + } + error + }), + }; + let handler = match handler { + Ok(handler) => handler, + Err(error) => { + failed_this_pass.insert(row.workspace_id.clone()); + record_failure(db, &row.workspace_id, &row.handler_path, &error).await; + continue; + } + }; + + // Claim and push in one transaction. The claim matches the row as it was read, so it + // loses both to a concurrent re-arm and to whichever replica got there first. + let mut tx = match db.begin().await { + Ok(tx) => tx, + Err(e) => { + tracing::error!("Error opening tx for expiring variable {}: {e:#}", row.path); + continue; + } + }; + + let claimed = sqlx::query_scalar!( + "UPDATE variable SET expiration_dispatched_for = $3, expiration_notified_at = now() + WHERE workspace_id = $1 AND path = $2 AND value_valid_until = $3 + AND expiration_dispatched_for IS NOT DISTINCT FROM $4 + AND expiration_notified_at IS NOT DISTINCT FROM $5 + RETURNING 1", + row.workspace_id, + row.path, + row.value_valid_until, + row.expiration_dispatched_for, + row.expiration_notified_at, + ) + .fetch_optional(&mut *tx) + .await; + + match claimed { + Ok(Some(_)) => {} + Ok(None) => continue, + Err(e) => { + tracing::error!("Error claiming expiring variable {}: {e:#}", row.path); + continue; + } + } + + let expiring = ExpiringVariable { + workspace_id: row.workspace_id.clone(), + variable_path: row.path.clone(), + description: row.description, + value_valid_until: row.value_valid_until, + is_secret: row.is_secret, + }; + + let pushed = push_variable_expiration_handler( + db, + tx, + &row.workspace_id, + handler, + &expiring, + row.extra_args, + ) + .await; + + let tx = match pushed { + Ok((_job_id, tx)) => tx, + Err(e) => { + // Dropping the tx un-claims the variable, so the next pass retries it. + failed_this_pass.insert(row.workspace_id.clone()); + record_failure(db, &row.workspace_id, &row.handler_path, &format!("{e:#}")).await; + continue; + } + }; + + if let Err(e) = tx.commit().await { + tracing::error!("Error committing dispatch for {}: {e:#}", row.path); + continue; + } + windmill_common::feature_usage::log_feature_usage( + "variable_expiration", + "dispatched", + if row.is_secret { "secret" } else { "plain" }, + ); + dispatched += 1; + recover(db, &row.workspace_id, &row.handler_path).await; + } + + if dispatched > 0 { + tracing::info!("Dispatched {dispatched} variable expiration handler job(s)"); + } +} + +/// Alerts once per failure, not per pass: the alert is resolved when the handler next starts. +async fn record_failure(db: &DB, w_id: &str, handler_path: &str, error: &str) { + let newly_failing = sqlx::query_scalar!( + "UPDATE workspace_settings SET variable_expiration_failed_at = now() + WHERE workspace_id = $1 AND variable_expiration_failed_at IS NULL + RETURNING 1", + w_id, + ) + .fetch_optional(db) + .await; + match newly_failing { + Ok(Some(_)) => { + report_critical_error( + format!( + "The variable expiration handler {handler_path} of workspace {w_id} failed to \ + start, so variables in this workspace are not being notified. It is retried \ + on every check, and this alert is resolved once it starts: {error}" + ), + db.clone(), + Some(w_id), + Some(&alert_resource(w_id)), + ) + .await + } + Ok(None) => {} + Err(e) => { + tracing::error!("Error recording variable expiration handler failure of {w_id}: {e:#}") + } + } +} + +/// Tags a failing handler's critical alerts, so they can be resolved together. +fn alert_resource(w_id: &str) -> String { + format!("variable_expiration_handler:{w_id}") +} + +/// A removed handler has nothing left to retry, so its failure would never be resolved. +async fn resolve_removed_handlers(db: &DB) { + let removed = sqlx::query_scalar!( + "UPDATE workspace_settings SET variable_expiration_failed_at = NULL + WHERE variable_expiration_failed_at IS NOT NULL AND variable_expiration_handler IS NULL + RETURNING workspace_id", + ) + .fetch_all(db) + .await; + match removed { + Ok(removed) => { + for w_id in removed { + report_recovered_critical_error( + format!("The variable expiration handler of workspace {w_id} was removed"), + db.clone(), + Some(&w_id), + Some(&alert_resource(&w_id)), + ) + .await; + } + } + Err(e) => tracing::error!("Error resolving removed variable expiration handlers: {e:#}"), + } +} + +async fn recover(db: &DB, w_id: &str, handler_path: &str) { + let cleared = sqlx::query_scalar!( + "UPDATE workspace_settings SET variable_expiration_failed_at = NULL + WHERE workspace_id = $1 AND variable_expiration_failed_at IS NOT NULL + RETURNING 1", + w_id, + ) + .fetch_optional(db) + .await; + match cleared { + Ok(Some(_)) => { + report_recovered_critical_error( + format!( + "The variable expiration handler {handler_path} of workspace {w_id} started again" + ), + db.clone(), + Some(w_id), + Some(&alert_resource(w_id)), + ) + .await + } + Ok(None) => {} + Err(e) => { + tracing::error!("Error clearing variable expiration handler failure of {w_id}: {e:#}") + } + } +} diff --git a/backend/windmill-queue/tests/native_retry_test.rs b/backend/windmill-queue/tests/native_retry_test.rs index 4cf278cf83..949a3cf4f6 100644 --- a/backend/windmill-queue/tests/native_retry_test.rs +++ b/backend/windmill-queue/tests/native_retry_test.rs @@ -339,7 +339,7 @@ mod native_retry { // -> failure: handler child must NOT count as a recovery // f: root fails, only a WAC inline child (unmarked) succeeds // -> failure: WAC inline child must NOT count as a recovery - // d: the current occurrence (excluded by `j.id != $4`) + // d: the current occurrence (excluded with any later one by the created_at bound) let (a, b, c, e, f, d) = ( Uuid::new_v4(), Uuid::new_v4(), @@ -371,7 +371,8 @@ mod native_retry { )) FROM v2_job j JOIN v2_job_completed USING (id) WHERE j.workspace_id = $1 AND trigger_kind = 'schedule' AND trigger = $2 - AND parent_job IS NULL AND runnable_path = $3 AND j.id != $4 + AND parent_job IS NULL AND runnable_path = $3 + AND j.created_at < (SELECT created_at FROM v2_job WHERE id = $4) ORDER BY created_at DESC", ) .bind(WS) diff --git a/backend/windmill-queue/tests/schedule_push.rs b/backend/windmill-queue/tests/schedule_push.rs index ed50215473..e79d4ff976 100644 --- a/backend/windmill-queue/tests/schedule_push.rs +++ b/backend/windmill-queue/tests/schedule_push.rs @@ -222,6 +222,43 @@ mod schedule_push { Ok(()) } + // Callers hold `tx` on the pool they pass in, so a burst of schedules the size of the pool + // starves it if a push checks out a second connection. On a one-connection pool any such + // checkout hangs until the acquire timeout. + #[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))] + async fn test_push_holds_one_connection(db: Pool<Postgres>) -> anyhow::Result<()> { + 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 schedules = [ + make_schedule(|s| { + s.script_path = "f/system/tagged_script".to_string(); + s.path = "f/system/tagged_schedule".to_string(); + }), + make_schedule(|s| { + s.script_path = "f/system/obo_script".to_string(); + s.path = "f/system/obo_schedule".to_string(); + }), + make_schedule(|s| { + s.is_flow = true; + s.script_path = "f/system/obo_flow".to_string(); + s.path = "f/system/obo_flow_schedule".to_string(); + }), + ]; + for schedule in &schedules { + let tx = one.begin().await?; + let push = push_scheduled_job(&one, tx, schedule, None, None); + let tx = tokio::time::timeout(std::time::Duration::from_secs(15), push).await??; + tx.commit().await?; + } + + assert_eq!(count_queued_jobs(&db).await, 3); + Ok(()) + } + // ----------------------------------------------------------------------- // push_scheduled_job: with retry wraps in SingleStepFlow // ----------------------------------------------------------------------- diff --git a/backend/windmill-store/src/oauth_refresh_oss.rs b/backend/windmill-store/src/oauth_refresh_oss.rs index 13e24dfd8b..a0d0926510 100644 --- a/backend/windmill-store/src/oauth_refresh_oss.rs +++ b/backend/windmill-store/src/oauth_refresh_oss.rs @@ -6,39 +6,221 @@ * LICENSE-AGPL for a copy of the license. */ +use std::future::Future; +use std::sync::Arc; + +use windmill_common::db::DB; +use windmill_common::error::{self, Error}; +use windmill_oauth::{OAuthAccountInfo, RefreshError, RefreshedToken}; + #[cfg(feature = "private")] pub use crate::oauth_refresh_ee::_refresh_token; -#[cfg(not(feature = "private"))] -use sqlx::{Postgres, Transaction}; -#[cfg(not(feature = "private"))] -use windmill_common::db::DB; -#[cfg(not(feature = "private"))] -use windmill_common::error; +/// The `account` row a refresh starts from. +pub struct RefreshAccount { + pub mcp_server_url: Option<String>, + pub is_workspace_integration: bool, + pub info: OAuthAccountInfo, +} -#[cfg(not(feature = "private"))] -pub async fn _refresh_token<'c>( - tx: Transaction<'c, Postgres>, - path: &str, - w_id: &str, - id: i32, +lazy_static::lazy_static! { + static ref REFRESH_LOCKS: dashmap::DashMap<(String, i32), Arc<tokio::sync::Mutex<()>>> = + dashmap::DashMap::new(); +} + +/// Refresh the token of account `id`, which backs the secret variable at `path`. +/// +/// No connection is held across `exchange`: it does its own config reads and the provider +/// call, and every write here is a single autocommit statement. Concurrent refreshers of one +/// account are serialized within a process, and across processes the account is only +/// committed if its refresh token is still the one exchanged, so a rotated refresh token is +/// never overwritten by a stale one. An account refreshed by someone else while we waited for +/// the lock is not refreshed again: without `force` any fresh account counts, with it only one +/// whose expiry moved since we asked. Callers must have authorized `w_id`/`path`/`id`. +pub(crate) async fn refresh_account_token<F, Fut>( db: &DB, -) -> error::Result<String> { - let token = windmill_oauth::refresh_token( - tx, + w_id: &str, + path: &str, + id: i32, + force: bool, + exchange: F, +) -> error::Result<String> +where + F: FnOnce(RefreshAccount) -> Fut, + Fut: Future<Output = Result<RefreshedToken, RefreshError>>, +{ + let seen_expiry = if force { + sqlx::query_scalar!( + "SELECT expires_at FROM account WHERE workspace_id = $1 AND id = $2", + w_id, + id + ) + .fetch_optional(db) + .await? + } else { + None + }; + + let lock = REFRESH_LOCKS + .entry((w_id.to_string(), id)) + .or_default() + .clone(); + let _guard = lock.lock().await; + + let row = sqlx::query!( + "SELECT mcp_server_url, is_workspace_integration, client, refresh_token, grant_type, + cc_client_id, cc_client_secret, cc_token_url, scopes, expires_at, + now() > expires_at AS \"expired!\" + FROM account WHERE workspace_id = $1 AND id = $2", w_id, id, + ) + .fetch_optional(db) + .await? + .ok_or_else(|| Error::NotFound(format!("Account {id} not found")))?; + + // A failed store moves `expires_at` too, into the past: only a fresh account counts. + let refreshed_meanwhile = !row.expired && (!force || Some(row.expires_at) != seen_expiry); + if refreshed_meanwhile { + return current_token(db, w_id, path).await; + } + + let used = row.refresh_token.clone(); + let account = RefreshAccount { + mcp_server_url: row.mcp_server_url, + is_workspace_integration: row.is_workspace_integration, + info: OAuthAccountInfo { + client: row.client, + refresh_token: row.refresh_token, + grant_type: row.grant_type, + cc_client_id: row.cc_client_id, + cc_client_secret: row.cc_client_secret, + cc_token_url: row.cc_token_url, + scopes: row.scopes, + }, + }; + + let token = match exchange(account).await { + Ok(token) => token, + Err(RefreshError::Other(e)) => return Err(e), + Err(RefreshError::Provider(msg)) => { + let recorded = sqlx::query!( + "UPDATE account SET refresh_error = $1 + WHERE workspace_id = $2 AND id = $3 AND refresh_token = $4", + msg, + w_id, + id, + used, + ) + .execute(db) + .await? + .rows_affected(); + // Another process rotated the refresh token first, so the one we sent was spent: + // its token is the one to serve, unless storing it failed too. + if recorded == 0 { + let expired = sqlx::query_scalar!( + "SELECT now() > expires_at AS \"expired!\" FROM account + WHERE workspace_id = $1 AND id = $2", + w_id, + id + ) + .fetch_optional(db) + .await?; + if expired == Some(false) { + return current_token(db, w_id, path).await; + } + } + return Err(Error::BadRequest(format!("Error refreshing token: {msg}"))); + } + }; + + // The lifetime runs from the exchange, not from the end of the stores below. + let expires_at = windmill_common::utils::now_from_db(db).await? + + chrono::Duration::try_seconds(token.expires_in).unwrap_or_default(); + + // Store at every secret variable of the account before marking it fresh, so no reader of + // any of them sees the account fresh with the old token. A failed store already marks the + // account for a retry; the rotated refresh token must still be saved, or the next refresh + // sends one the provider has revoked. + let mut paths = sqlx::query_scalar!( + "SELECT path FROM variable WHERE workspace_id = $1 AND account = $2 AND is_secret", + w_id, + id + ) + .fetch_all(db) + .await?; + if !paths.iter().any(|p| p == path) { + paths.push(path.to_string()); + } + let mut stored = Ok(()); + for p in &paths { + stored = + crate::secret_backend_ext::store_oauth_token_value(db, w_id, p, &token.access_token) + .await; + if stored.is_err() { + break; + } + } + sqlx::query!( + "UPDATE account SET refresh_token = COALESCE($1, refresh_token), + expires_at = CASE WHEN $2 THEN $3 ELSE expires_at END, + refresh_error = CASE WHEN $2 THEN NULL ELSE refresh_error END + WHERE workspace_id = $4 AND id = $5 AND refresh_token = $6", + token.refresh_token, + stored.is_ok(), + expires_at, + w_id, + id, + used, + ) + .execute(db) + .await?; + stored?; + + Ok(token.access_token) +} + +async fn current_token(db: &DB, w_id: &str, path: &str) -> error::Result<String> { + let value = sqlx::query_scalar!( + "SELECT value::text AS \"value!\" FROM variable WHERE workspace_id = $1 AND path = $2", + w_id, + path + ) + .fetch_optional(db) + .await? + .ok_or_else(|| Error::NotFound(format!("Variable {path} not found")))?; + crate::secret_backend_ext::get_secret_value(db, w_id, path, &value).await +} + +/// The standard OAuth / client-credentials exchange. +pub(crate) async fn exchange_standard( + db: &DB, + w_id: &str, + id: i32, + account: &OAuthAccountInfo, +) -> Result<RefreshedToken, RefreshError> { + windmill_oauth::exchange_account_token( db, + w_id, + id, + account, &*windmill_oauth::OAUTH_CLIENTS.load(), &windmill_oauth::OAUTH_HTTP_CLIENT, include_str!("../../oauth_connect.json"), ) - .await?; + .await +} - // Persist the refreshed token through the configured secret backend so an - // external backend (Vault / Azure KV / AWS Secrets Manager) is updated too, - // not just the in-DB variable mirror. - crate::secret_backend_ext::store_oauth_token_value(db, w_id, path, &token).await?; - - Ok(token) +#[cfg(not(feature = "private"))] +pub async fn _refresh_token( + path: &str, + w_id: &str, + id: i32, + db: &DB, + force: bool, +) -> error::Result<String> { + refresh_account_token(db, w_id, path, id, force, |account| async move { + exchange_standard(db, w_id, id, &account.info).await + }) + .await } diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index 010eb0a90b..541369f327 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -439,9 +439,10 @@ async fn list_resources( if let Some(broad_filter) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(broad_filter)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(resource.path ILIKE ? OR resource.description ILIKE ? OR resource_type ILIKE ? OR resource.value::text ILIKE ?)" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } @@ -455,10 +456,10 @@ async fn list_resources( if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(resource.labels @> ARRAY[?] OR folder_labels(resource.workspace_id, resource.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } @@ -488,8 +489,7 @@ async fn list_resources( && lq.broad_filter.is_none() && lq.label.is_none() && !lq.starred_only.unwrap_or(false) - && (!authed.is_operator - || operator_can_draft(&db, &w_id, UserDraftItemKind::Resource).await?) + && operator_can_draft(&db, &w_id, &authed, UserDraftItemKind::Resource).await? { let rt_filter: Option<Vec<&str>> = lq .resource_type @@ -2190,7 +2190,7 @@ async fn update_resource( // Handle Vault secret rename if the linked variable is a Vault-stored secret let linked_var = sqlx::query!( - "SELECT value, is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", path, w_id ) @@ -2225,6 +2225,15 @@ async fn update_resource( .execute(&mut *tx) .await?; + sqlx::query!( + "UPDATE native_trigger SET connection_path = $1 WHERE workspace_id = $2 AND connection_path = $3", + npath, + w_id, + path + ) + .execute(&mut *tx) + .await?; + sqlx::query!( "UPDATE workspace_integrations SET resource_path = $1 WHERE workspace_id = $2 AND resource_path = $3", npath, @@ -2481,6 +2490,9 @@ async fn update_resource_value( /// `run_on_behalf_of` is set: then the writer's own, unless one allowed to keep the one the value /// names asks to, and a folder's default for a new agent. The value is written by anyone who can /// write the agent, so the key it arrives with is only a request. +/// +/// Every write of an agent passes here, so this is also where an operator's is held to the +/// composed-flow rules: a flow step linking the agent runs its tools unchecked. async fn resolve_agent_on_behalf_of( tx: &mut Transaction<'_, Postgres>, authed: &ApiAuthed, @@ -2491,6 +2503,9 @@ async fn resolve_agent_on_behalf_of( preserve: bool, created: bool, ) -> Result<()> { + if authed.is_operator { + windmill_api_auth::composed::validate_operator_agent(value, authed, db, tx, w_id).await?; + } let Some(obj) = value.as_object_mut() else { return Ok(()); }; diff --git a/backend/windmill-store/src/secret_backend_ext.rs b/backend/windmill-store/src/secret_backend_ext.rs index d5272384c0..814a3174a9 100644 --- a/backend/windmill-store/src/secret_backend_ext.rs +++ b/backend/windmill-store/src/secret_backend_ext.rs @@ -77,14 +77,13 @@ pub async fn store_secret_value( /// here instead would leave the external store frozen at its connect-time token /// while reads (which resolve through the backend) keep serving the stale value. /// -/// The caller has already committed the `account` row as fresh (advanced -/// `expires_at`) by the time we get here. If persisting the token fails — most -/// likely a transient error talking to an external backend — that would leave -/// the account marked fresh while the served secret is stale, so the on-fetch -/// refresh gate (`now() > expires_at`) would skip refresh and keep serving the -/// stale token for the whole token lifetime. To avoid that we reset `expires_at` -/// to the past (and record `refresh_error`) on failure — looking the account up -/// via `variable.account` — so the very next fetch retries the refresh instead. +/// If persisting the token fails — most likely a transient error talking to an +/// external backend — the account must not end up marked fresh while the served +/// secret is stale, or the on-fetch refresh gate (`now() > expires_at`) would keep +/// serving the stale token for the whole token lifetime. So on failure we reset +/// `expires_at` to the past and record `refresh_error` — looking the account up via +/// `variable.account` — and the very next fetch retries the refresh. This also +/// covers another refresher of the account having marked it fresh meanwhile. /// /// Authorization contract: this performs NO access control. It writes the /// caller-supplied token into the secret variable at `path` and may mutate the diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index fca29736e6..e9aa3ab60d 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -149,6 +149,7 @@ async fn list_variables( "resource.path IS NOT NULL as is_linked", "account.refresh_token != '' as is_refreshed", "variable.expires_at", + "variable.value_valid_until", "variable.labels", "folder_labels(variable.workspace_id, variable.path) as inherited_labels", "ws_specific.path IS NOT NULL as ws_specific", @@ -199,18 +200,19 @@ async fn list_variables( if let Some(broad_filter) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(broad_filter)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(variable.path ILIKE ? OR variable.description ILIKE ? OR (is_secret = FALSE AND variable.value ILIKE ?))" - .bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(variable.labels @> ARRAY[?] OR folder_labels(variable.workspace_id, variable.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } @@ -236,8 +238,7 @@ async fn list_variables( && lq.value.is_none() && lq.broad_filter.is_none() && lq.label.is_none() - && (!authed.is_operator - || operator_can_draft(&db, &w_id, UserDraftItemKind::Variable).await?) + && operator_can_draft(&db, &w_id, &authed, UserDraftItemKind::Variable).await? { let draft_only_rows = fetch_draft_only_list_rows(&db, &w_id, &authed.email, UserDraftItemKind::Variable) @@ -246,7 +247,7 @@ async fn list_variables( for row in draft_only_rows { let v: serde_json::Value = serde_json::from_str(row.value.0.get()).unwrap_or(serde_json::Value::Null); - // VariableEditor's `VariableState`: { path, variable: { value, is_secret, description }, labels?, wsSpecific } + // VariableEditor's `VariableState`: { path, variable: { value, is_secret, description }, labels?, wsSpecific, value_valid_until? } let path = v .get("path") .and_then(|s| s.as_str()) @@ -285,6 +286,11 @@ async fn list_variables( }) }); let ws_specific = v.get("wsSpecific").and_then(|x| x.as_bool()); + let value_valid_until = v + .get("value_valid_until") + .and_then(|x| x.as_str()) + .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) + .map(|dt| dt.with_timezone(&chrono::Utc)); rows.push(ListableVariable { workspace_id: w_id.clone(), @@ -300,6 +306,7 @@ async fn list_variables( refresh_error: None, is_linked: None, expires_at: None, + value_valid_until, labels, // No deployed row to inherit folder labels from. inherited_labels: None, @@ -338,9 +345,9 @@ async fn get_variable( let mut tx = user_db.begin(&authed).await?; let variable_o = sqlx::query_as::<_, ListableVariable>( - "SELECT variable.workspace_id, variable.path, variable.value, variable.is_secret, + "SELECT variable.workspace_id, variable.path, variable.value::text AS value, variable.is_secret, variable.description, variable.extra_perms, variable.account, variable.is_oauth, - variable.expires_at, variable.labels, + variable.expires_at, variable.value_valid_until, variable.labels, folder_labels(variable.workspace_id, variable.path) as inherited_labels, variable.edited_at, variable.edited_by, (now() > account.expires_at) as is_expired, account.refresh_error, @@ -373,42 +380,42 @@ async fn get_variable( explain_variable_perm_error(&path, &w_id, &db, Some(&authed)).await?; unreachable!() } else { + drop(tx); explain_variable_perm_error(&path, &w_id, &db, Some(&authed)).await?; unreachable!() }; let decrypt_secret = q.decrypt_secret.unwrap_or(true); - let r = if variable.is_secret { - if decrypt_secret { - audit_log( - &mut *tx, - &authed, - "variables.decrypt_secret", - ActionKind::Execute, - &w_id, - Some(&variable.path), - None, - ) - .await?; - } + if variable.is_secret && decrypt_secret { + audit_log( + &mut *tx, + &authed, + "variables.decrypt_secret", + ActionKind::Execute, + &w_id, + Some(&variable.path), + None, + ) + .await?; + } + // Everything below reads the pool: holding this connection meanwhile would make each + // concurrent request wait on a second one. + tx.commit().await?; + let r = if variable.is_secret { let value = variable.value.unwrap_or_else(|| "".to_string()); ListableVariable { value: if variable.is_expired.unwrap_or(false) && variable.account.is_some() { #[cfg(feature = "oauth2")] { - let refresh_tx = db - .begin() - .await - .map_err(|e| Error::InternalErr(e.to_string()))?; Some( crate::oauth_refresh_oss::_refresh_token( - refresh_tx, &variable.path, &w_id, variable.account.unwrap(), &db, + false, ) .await?, ) @@ -416,7 +423,6 @@ async fn get_variable( #[cfg(not(feature = "oauth2"))] return Err(Error::internal_err("Require oauth2 feature".to_string())); } else if !value.is_empty() && decrypt_secret { - let _ = tx.commit().await; // Use secret backend for decryption (supports both DB and Vault) Some(get_secret_value(&db, &w_id, &variable.path, &value).await?) } else if q.include_encrypted.unwrap_or(false) { @@ -596,6 +602,49 @@ async fn create_variable( Query(AlreadyEncrypted { already_encrypted }): Query<AlreadyEncrypted>, Json(variable): Json<CreateVariable>, ) -> Result<(StatusCode, String)> { + let path = variable.path.clone(); + create_variable_with_account( + authed, + &db, + user_db, + &webhook, + w_id, + variable, + already_encrypted.unwrap_or(false), + None, + ) + .await?; + Ok((StatusCode::CREATED, format!("variable {path} created"))) +} + +/// An OAuth account to create with the variable that holds its access token. +pub struct NewOAuthAccount { + pub client: String, + pub expires_in: i64, + pub refresh_token: Option<String>, + pub grant_type: String, + pub cc_client_id: Option<String>, + pub cc_client_secret: Option<String>, + pub cc_token_url: Option<String>, + pub mcp_server_url: Option<String>, + pub scopes: Option<Vec<String>>, +} + +/// Creates a variable and, given `account`, the OAuth account it refreshes through, linked in the +/// same transaction. Reading a linked variable refreshes through its account and hands the reader +/// the fresh token, so this is the only way a variable gets a link: `variable.account` is ignored. +/// Returns the new account's id. +pub async fn create_variable_with_account( + authed: ApiAuthed, + db: &DB, + user_db: UserDB, + webhook: &WebhookShared, + w_id: String, + variable: CreateVariable, + already_encrypted: bool, + account: Option<NewOAuthAccount>, +) -> Result<Option<i32>> { + let db = db.clone(); check_scopes(&authed, || format!("variables:write:{}", variable.path))?; check_proper_path(&variable.path)?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( @@ -627,7 +676,7 @@ async fn create_variable( let authed = maybe_refresh_folders(&variable.path, &w_id, authed, &db).await; check_path_conflict(&db, &w_id, &variable.path).await?; - let value = if variable.is_secret && !already_encrypted.unwrap_or(false) { + let value = if variable.is_secret && !already_encrypted { // A restored draft sends the `$encrypted:` marker as-is; decrypt it back // (validating against the workspace key) before the secret backend re-stores it. let plain = if variable.value.starts_with(ENCRYPTED_DRAFT_PREFIX) { @@ -648,18 +697,40 @@ async fn create_variable( let mut tx = user_db.begin(&authed).await?; + let account_id = match account { + Some(a) => Some( + sqlx::query_scalar!( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token, grant_type, cc_client_id, cc_client_secret, cc_token_url, mcp_server_url, scopes) VALUES ($1, $2, now() + ($3 || ' seconds')::interval, $4, $5, $6, $7, $8, $9, $10) RETURNING id", + &w_id, + a.client, + a.expires_in.to_string(), + a.refresh_token, + a.grant_type, + a.cc_client_id, + a.cc_client_secret, + a.cc_token_url, + a.mcp_server_url, + a.scopes.as_deref() + ) + .fetch_one(&mut *tx) + .await?, + ), + None => None, + }; + sqlx::query!( "INSERT INTO variable - (workspace_id, path, value, is_secret, description, account, is_oauth, expires_at, labels, edited_by) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", + (workspace_id, path, value, is_secret, description, account, is_oauth, expires_at, value_valid_until, labels, edited_by) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", &w_id, variable.path, value, variable.is_secret, variable.description, - variable.account, + account_id, variable.is_oauth.unwrap_or(false), variable.expires_at, + variable.value_valid_until, variable.labels.as_deref() as Option<&[String]>, &authed.username ) @@ -707,10 +778,7 @@ async fn create_variable( WebhookMessage::CreateVariable { workspace: w_id, path: variable.path.clone() }, ); - Ok(( - StatusCode::CREATED, - format!("variable {} created", variable.path), - )) + Ok(account_id) } async fn encrypt_value( @@ -1061,9 +1129,15 @@ struct EditVariable { value: Option<String>, is_secret: Option<bool>, description: Option<String>, - account: Option<i32>, labels: Option<Vec<String>>, ws_specific: Option<bool>, + /// Absent leaves the stored expiry alone and `null` clears it, so a partial update + /// never clears it by omission. + #[serde( + default, + deserialize_with = "windmill_common::more_serde::double_option" + )] + value_valid_until: Option<Option<chrono::DateTime<chrono::Utc>>>, } #[derive(Deserialize)] @@ -1158,8 +1232,13 @@ async fn update_variable( has_sql_updates = true; } - if let Some(account_id) = ns.account { - sqlb.set_str("account", account_id); + if let Some(nvalue_valid_until) = ns.value_valid_until { + // Nothing to reset: the sweep compares the date with `expiration_dispatched_for`, so + // moving it re-arms the handler and rewriting the same date does not. + match nvalue_valid_until { + Some(ts) => sqlb.set("value_valid_until", "?".bind(&ts.to_rfc3339())), + None => sqlb.set("value_valid_until", "NULL"), + }; has_sql_updates = true; } @@ -1181,20 +1260,6 @@ async fn update_variable( has_sql_updates = true; } - // Get old account_id if we're updating the account field - let old_account_id = if ns.account.is_some() { - sqlx::query_scalar!( - "SELECT account FROM variable WHERE path = $1 AND workspace_id = $2", - &path, - &w_id - ) - .fetch_optional(&db) - .await? - .flatten() - } else { - None - }; - let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; if let Some(npath) = ns.path.clone() { @@ -1204,7 +1269,7 @@ async fn update_variable( // Handle Vault secret rename if the variable is a secret stored in Vault let current_var = sqlx::query!( - "SELECT value, is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", path, w_id ) @@ -1257,6 +1322,15 @@ async fn update_variable( .execute(&mut *tx) .await?; + sqlx::query!( + "UPDATE native_trigger SET connection_path = $1 WHERE workspace_id = $2 AND connection_path = $3", + npath, + w_id, + path + ) + .execute(&mut *tx) + .await?; + sqlx::query!( "UPDATE workspace_integrations SET resource_path = $1 WHERE workspace_id = $2 AND resource_path = $3", npath, @@ -1368,32 +1442,6 @@ async fn update_variable( ) .await?; - // Clean up old account if it's no longer referenced and different from new account - if let Some(old_acc_id) = old_account_id { - if ns.account.is_some() && ns.account != Some(old_acc_id) { - // Check if old account is still referenced by other variables or resources - let account_still_used = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM variable WHERE account = $1 AND workspace_id = $2)", - old_acc_id, - &w_id - ) - .fetch_one(&mut *tx) - .await? - .unwrap_or(true); - - if !account_still_used { - // Delete the orphaned account - sqlx::query!( - "DELETE FROM account WHERE id = $1 AND workspace_id = $2", - old_acc_id, - &w_id - ) - .execute(&mut *tx) - .await?; - } - } - } - tx.commit().await?; // Detect if this was a rename operation @@ -1515,7 +1563,7 @@ pub async fn get_value_internal<'a>( let mut tx = db_with_opt_authed.begin().await?; let variable_o = sqlx::query!( - "SELECT value, account, (now() > account.expires_at) as is_expired, is_secret, path from variable + "SELECT value::text AS \"value!\", account, (now() > account.expires_at) as is_expired, is_secret, path from variable LEFT JOIN account ON variable.account = account.id WHERE variable.path = $1 AND variable.workspace_id = $2", path, w_id ) .fetch_optional(&mut *tx) @@ -1543,17 +1591,12 @@ pub async fn get_value_internal<'a>( if variable.is_expired.unwrap_or(false) && variable.account.is_some() { #[cfg(feature = "oauth2")] { - let db = db_with_opt_authed.db(); - let refresh_tx = db - .begin() - .await - .map_err(|e| Error::InternalErr(e.to_string()))?; crate::oauth_refresh_oss::_refresh_token( - refresh_tx, &variable.path, &w_id, variable.account.unwrap(), - db, + db_with_opt_authed.db(), + false, ) .await? } diff --git a/backend/windmill-test-utils/src/lib.rs b/backend/windmill-test-utils/src/lib.rs index f05fff66f8..5f804cee75 100644 --- a/backend/windmill-test-utils/src/lib.rs +++ b/backend/windmill-test-utils/src/lib.rs @@ -71,6 +71,22 @@ fn next_worker_name() -> String { format!("{id}/worker-{thread_name}") } +/// The migration only creates audit partitions for the day it ran and the next three, and the +/// monitor that rolls new ones does not run in tests. A test database cloned from an older +/// template therefore has no partition for today, and a failed audit insert fails the request. +pub async fn ensure_today_audit_partition(db: &Pool<Postgres>) { + let today = chrono::Utc::now().date_naive(); + let next = today + chrono::Duration::days(1); + let partition = format!("audit_{}", today.format("%Y%m%d")); + sqlx::query(&format!( + "CREATE TABLE IF NOT EXISTS \"{partition}\" PARTITION OF audit_partitioned \ + FOR VALUES FROM ('{today}') TO ('{next}')" + )) + .execute(db) + .await + .expect("creating today's audit partition"); +} + pub struct ApiServer { pub addr: std::net::SocketAddr, #[allow(unused)] @@ -104,6 +120,7 @@ impl ApiServer { server_mode: bool, mcp_mode: bool, ) -> anyhow::Result<Self> { + ensure_today_audit_partition(&db).await; let (tx, rx) = tokio::sync::broadcast::channel::<()>(1); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") @@ -212,6 +229,7 @@ impl RunJob { } pub async fn push(self, db: &Pool<Postgres>) -> Uuid { + ensure_today_audit_partition(db).await; let RunJob { payload, args, scheduled_for_o, username, email, job_id, workspace_id } = self; let mut hm_args = std::collections::HashMap::new(); for (k, v) in args { @@ -260,6 +278,7 @@ impl RunJob { /// Push the job as a specific user (for testing permissions) pub async fn push_as(self, db: &Pool<Postgres>, username: &str, email: &str) -> Uuid { + ensure_today_audit_partition(db).await; let RunJob { payload, args, scheduled_for_o, job_id, workspace_id, .. } = self; let mut hm_args = std::collections::HashMap::new(); for (k, v) in args { diff --git a/backend/windmill-trigger/src/handler.rs b/backend/windmill-trigger/src/handler.rs index 7395a5e8a3..fec3180801 100644 --- a/backend/windmill-trigger/src/handler.rs +++ b/backend/windmill-trigger/src/handler.rs @@ -700,13 +700,13 @@ async fn list_triggers<T: TriggerCrud>( && query.is_flow.is_none() && query.path_start.is_none() && query.label.is_none() - && (!authed.is_operator - || windmill_common::workspaces::operator_can_draft( - &db, - &workspace_id, - T::user_draft_item_kind(), - ) - .await?) + && windmill_common::workspaces::operator_can_draft( + &db, + &workspace_id, + &authed, + T::user_draft_item_kind(), + ) + .await? { let draft_only_rows = fetch_draft_only_list_rows( &db, diff --git a/backend/windmill-trigger/src/trigger_helpers.rs b/backend/windmill-trigger/src/trigger_helpers.rs index ae805d195e..4056ae85e6 100644 --- a/backend/windmill-trigger/src/trigger_helpers.rs +++ b/backend/windmill-trigger/src/trigger_helpers.rs @@ -512,7 +512,7 @@ pub async fn trigger_runnable_inner<'c>( workspace_id: &str, runnable_path: &str, is_flow: bool, - args: PushArgsOwned, + mut args: PushArgsOwned, retry: Option<&sqlx::types::Json<Retry>>, error_handler_path: Option<&str>, error_handler_args: Option<&sqlx::types::Json<HashMap<String, serde_json::Value>>>, @@ -527,6 +527,18 @@ pub async fn trigger_runnable_inner<'c>( bool, Option<sqlx::Transaction<'c, sqlx::Postgres>>, )> { + // A trigger's args are built from a third party's payload — for an HTTP route without + // preprocessor the request body's keys *are* the job's top-level args — and the job runs + // as the trigger's owner, not as whoever sent that payload. So the sender may not steer + // how the runnable runs: pick the function called instead of `main` (and skip whatever + // `main` authenticates, e.g. the signature check of a `custom_script` route), plant + // module files in the job directory, or redirect where its workspace imports resolve. + // Every trigger kind funnels through here on its way to `push`, and none of them sets + // one of those keys itself, so this is the single place to do it rather than each args + // builder. It does not restrict what the runnable is *given*: ordinary inputs pass + // through untouched. + args.sanitize_untrusted(); + let error_handler_args = error_handler_args.map(|args| { let args = args .0 diff --git a/backend/windmill-types/src/flow_status.rs b/backend/windmill-types/src/flow_status.rs index 6dff8430b7..2fd5ef1184 100644 --- a/backend/windmill-types/src/flow_status.rs +++ b/backend/windmill-types/src/flow_status.rs @@ -4,7 +4,7 @@ use std::time::Duration; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use crate::flows::FlowValue; +use crate::flows::{FlowValue, Suspend}; const MINUTES: Duration = Duration::from_secs(60); const HOURS: Duration = MINUTES.saturating_mul(60); @@ -409,6 +409,21 @@ pub enum JobResult { } impl FlowStatusModule { + /// Whether this completed step's suspend gate could block and never opened (it timed out or + /// was disapproved): `approvers` is written when the gate opens, and is the only record of it + /// that outlives the run, since its resume_job rows are deleted with its queue row. + pub fn suspend_gate_never_opened(&self, suspend: Option<&Suspend>) -> bool { + let Some(suspend) = suspend else { + return false; + }; + if suspend.required_events.unwrap_or(0) == 0 + || suspend.continue_on_disapprove_timeout.unwrap_or(false) + { + return false; + } + matches!(self, FlowStatusModule::Success { skipped: false, approvers, .. } if approvers.is_empty()) + } + pub fn job(&self) -> Option<Uuid> { match self { FlowStatusModule::WaitingForPriorSteps { .. } => None, diff --git a/backend/windmill-types/src/flows.rs b/backend/windmill-types/src/flows.rs index 890318b8aa..59f06ae4e9 100644 --- a/backend/windmill-types/src/flows.rs +++ b/backend/windmill-types/src/flows.rs @@ -843,6 +843,19 @@ impl InputTransform { pub fn new_javascript_expr(expr: &str) -> InputTransform { InputTransform::Javascript { expr: expr.to_owned() } } + + /// Whether this transform fills its input. On an agent tool, an input it does not fill is + /// left to the model, which sees only those. + pub fn is_completed(&self) -> bool { + match self { + InputTransform::Static { value } => { + let val = value.get().trim(); + !val.is_empty() && val != "null" + } + InputTransform::Javascript { expr } => !expr.trim().is_empty(), + InputTransform::Ai => false, + } + } } impl TryFrom<UntaggedInputTransform> for InputTransform { diff --git a/backend/windmill-types/src/jobs.rs b/backend/windmill-types/src/jobs.rs index 9768373b91..17e5235c5f 100644 --- a/backend/windmill-types/src/jobs.rs +++ b/backend/windmill-types/src/jobs.rs @@ -724,6 +724,26 @@ pub const ENTRYPOINT_OVERRIDE: &str = "_ENTRYPOINT_OVERRIDE"; /// `RawCode::modules`: a caller-supplied one is dropped there. pub const MODULES_ARG: &str = "_MODULES"; +/// Job-arg key mapping a runnable's workspace imports to contents of the temporary script +/// store (`scripts/raw_temp/store`, writable by any workspace member). The preview routes +/// set it server-side from their `temp_script_refs` field; the bun and python executors +/// honor it on every `JobKind::Preview` job. +pub const TEMP_SCRIPT_REFS_ARG: &str = "_TEMP_SCRIPT_REFS"; + +/// Job-arg keys that steer *how* a runnable runs rather than what it is given: which +/// function the worker calls instead of `main` ([`ENTRYPOINT_OVERRIDE`]), what module files +/// are written into the job directory ([`MODULES_ARG`]) and where its workspace imports +/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]). +/// +/// Each is legitimate for a caller that runs code it authored under its own identity (the +/// script editor's preprocessor test, dynamic-select helpers, the CLI, workflow-as-code), so +/// they are not dropped for every job. None of them may come from a third party whose +/// payload runs under somebody else's identity — an HTTP route body, a native trigger +/// message, a public app viewer's inputs — which is what `sanitize_untrusted_args` in +/// `windmill_common::jobs` drops. +pub const RESERVED_CONTROL_ARGS: [&str; 3] = + [ENTRYPOINT_OVERRIDE, MODULES_ARG, TEMP_SCRIPT_REFS_ARG]; + /// Reserved job-arg key holding the inbound W3C `traceparent` captured from the /// request that enqueued the job (run endpoints). It rides the `args` jsonb like /// [`ENTRYPOINT_OVERRIDE`]; normal scripts never see it because args are bound by diff --git a/backend/windmill-worker/nsjail/download.py.config.proto b/backend/windmill-worker/nsjail/download.py.config.proto index 18957bb4a5..a68d96eb92 100644 --- a/backend/windmill-worker/nsjail/download.py.config.proto +++ b/backend/windmill-worker/nsjail/download.py.config.proto @@ -30,7 +30,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/download.ruby.config.proto b/backend/windmill-worker/nsjail/download.ruby.config.proto index 31eefae766..3a3a6f3b74 100644 --- a/backend/windmill-worker/nsjail/download.ruby.config.proto +++ b/backend/windmill-worker/nsjail/download.ruby.config.proto @@ -23,7 +23,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/download_deps.py.sh b/backend/windmill-worker/nsjail/download_deps.py.sh index 6b4cd8cfd8..8f0ebd1cd0 100755 --- a/backend/windmill-worker/nsjail/download_deps.py.sh +++ b/backend/windmill-worker/nsjail/download_deps.py.sh @@ -20,20 +20,22 @@ then echo "\$TRUSTED_HOST is set to $TRUSTED_HOST" fi -CMD="/usr/local/bin/uv pip install -\"$REQ\" ---target \"$TARGET\" ---no-cache ---no-config ---no-color ---no-deps ---link-mode=copy -$PY_PATH -$INDEX_URL_ARG $EXTRA_INDEX_URL_ARG $TRUSTED_HOST_ARG ---system ---reinstall ---compile-bytecode -" +# Build the argv directly so each value reaches uv as a single argument, quoting +# intact (e.g. PEP 508 markers). The unquoted expansions are worker configuration +# and split into separate arguments on purpose. +set -- /usr/local/bin/uv pip install \ + "$REQ" \ + --target "$TARGET" \ + --no-cache \ + --no-config \ + --no-color \ + --no-deps \ + --link-mode=copy \ + $PY_PATH \ + $INDEX_URL_ARG $EXTRA_INDEX_URL_ARG $TRUSTED_HOST_ARG \ + --system \ + --reinstall \ + --compile-bytecode -echo $CMD -eval $CMD +echo "$@" +exec "$@" diff --git a/backend/windmill-worker/nsjail/install.r.config.proto b/backend/windmill-worker/nsjail/install.r.config.proto index dff9acde15..e844b2e720 100644 --- a/backend/windmill-worker/nsjail/install.r.config.proto +++ b/backend/windmill-worker/nsjail/install.r.config.proto @@ -16,7 +16,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/lock.py.config.proto b/backend/windmill-worker/nsjail/lock.py.config.proto index 14119c4089..60c5573f40 100644 --- a/backend/windmill-worker/nsjail/lock.py.config.proto +++ b/backend/windmill-worker/nsjail/lock.py.config.proto @@ -23,7 +23,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/lock.ruby.config.proto b/backend/windmill-worker/nsjail/lock.ruby.config.proto index 6f82f3b748..bcca74e77e 100644 --- a/backend/windmill-worker/nsjail/lock.ruby.config.proto +++ b/backend/windmill-worker/nsjail/lock.ruby.config.proto @@ -19,7 +19,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/src/ai/compaction.rs b/backend/windmill-worker/src/ai/compaction.rs index b933348a2e..82a79985e8 100644 --- a/backend/windmill-worker/src/ai/compaction.rs +++ b/backend/windmill-worker/src/ai/compaction.rs @@ -610,12 +610,24 @@ async fn summarize_prefix( request .query_builder .get_endpoint(base_url, request.model, &OutputType::Text); - let auth_headers = retain_effective_credentials( + // Summaries are rare enough that exchanging afresh costs less than threading + // the agent loop's cached token through. + let mut federated_token = None; + let auth_headers = match windmill_ai::providers::anthropic::refresh_federated_access_token( request.credentials, - request - .query_builder - .get_auth_headers(api_key, base_url, &OutputType::Text), - ); + &mut federated_token, + request.client, + ) + .await? + { + Some(token) => windmill_ai::providers::anthropic::federated_auth_headers(token), + None => retain_effective_credentials( + request.credentials, + request + .query_builder + .get_auth_headers(api_key, base_url, &OutputType::Text), + ), + }; // As in the agent loop, `endpoint` derives from the user-controlled provider // base_url, so DNS is pinned to the SSRF-validated address. diff --git a/backend/windmill-worker/src/ai/tools.rs b/backend/windmill-worker/src/ai/tools.rs index 0bc7bf6777..35075566b7 100644 --- a/backend/windmill-worker/src/ai/tools.rs +++ b/backend/windmill-worker/src/ai/tools.rs @@ -1,8 +1,8 @@ use crate::ai::stream_event_processor::StreamEventProcessor; use crate::ai::utils::{ add_message_to_conversation, execute_mcp_tool, get_step_name_from_flow, - is_completed_input_transform, update_flow_status_module_with_actions, - update_flow_status_module_with_actions_success, FlowContext, + 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; @@ -19,7 +19,7 @@ use std::{collections::HashMap, sync::Arc, time::Duration}; use uuid::Uuid; use windmill_ai::{ai_types::OpenAIToolCall, query_builder::StreamEventSink, types::*}; use windmill_common::jobs::JobPayload; -use windmill_common::variables::arg_needs_interpolation; +use windmill_common::variables::untrusted_arg_interpolates; #[cfg(feature = "mcp")] use windmill_mcp::McpClient; @@ -199,8 +199,9 @@ pub async fn execute_tool_calls( /// which may be an identity it runs on behalf of. Only the step's own input transforms may name /// variables and resources; the model's arguments are text from whoever talks to it. fn interpolating_args(tool_call: &OpenAIToolCall) -> bool { - serde_json::from_str::<serde_json::Value>(&tool_call.function.arguments) - .is_ok_and(|v| arg_needs_interpolation(&v.to_string())) + // Empty for a tool called without arguments, which runs as `{}`. + let args = &tool_call.function.arguments; + !args.is_empty() && untrusted_arg_interpolates(args) } async fn refuse_tool_call( @@ -209,8 +210,8 @@ async fn refuse_tool_call( messages: &mut Vec<OpenAIMessage>, final_events_str: &mut String, ) -> Result<(), Error> { - let error_msg = "Tool call refused: its arguments cannot reference variables or resources \ - ($var:, $jsonvar:, $res:, $encrypted:)" + let error_msg = "Tool call refused: its arguments could not be read, or reference variables, \ + resources or reserved names ($var:, $jsonvar:, $res:, $encrypted:, $WM_)" .to_string(); messages.push(OpenAIMessage { role: "tool".to_string(), @@ -443,7 +444,7 @@ async fn enqueue_windmill_tool( // Evaluate each input transform and merge with AI-provided args for (key, transform) in input_transforms.iter() { // We skip static empty / null values, those are the one the AI will fill in - if !is_completed_input_transform(transform) { + if !transform.is_completed() { continue; } let result = evaluate_input_transform::<Box<RawValue>>( diff --git a/backend/windmill-worker/src/ai/utils.rs b/backend/windmill-worker/src/ai/utils.rs index 44513c806e..ccf2e0ef88 100644 --- a/backend/windmill-worker/src/ai/utils.rs +++ b/backend/windmill-worker/src/ai/utils.rs @@ -62,17 +62,6 @@ pub async fn parse_raw_script_schema( Ok(to_raw_value(&schema)) } -pub fn is_completed_input_transform(transform: &InputTransform) -> bool { - match transform { - InputTransform::Static { value } => { - let val = value.get().trim(); - !val.is_empty() && val != "null" - } - InputTransform::Javascript { expr } => !expr.trim().is_empty(), - InputTransform::Ai => false, - } -} - /// Filters out properties from a JSON schema that have completed input transforms. /// This allows AI agents to only see and fill parameters that don't have user-configured values. pub fn filter_schema_by_input_transforms( @@ -88,7 +77,7 @@ pub fn filter_schema_by_input_transforms( let keys_to_remove: HashSet<String> = input_transforms .iter() .filter_map(|(key, transform)| { - let is_completed = is_completed_input_transform(transform); + let is_completed = transform.is_completed(); if is_completed { Some(key.clone()) } else { @@ -779,7 +768,12 @@ mod tests { .unwrap(); let preset = ["a", "c", "f"] .iter() - .map(|k| (k.to_string(), InputTransform::Static { value: to_raw_value(&1) })) + .map(|k| { + ( + k.to_string(), + InputTransform::Static { value: to_raw_value(&1) }, + ) + }) .collect(); let filtered = filter_schema_by_input_transforms(schema, &preset).unwrap(); diff --git a/backend/windmill-worker/src/ai_executor.rs b/backend/windmill-worker/src/ai_executor.rs index 01ac2becdd..6c37f67f2e 100644 --- a/backend/windmill-worker/src/ai_executor.rs +++ b/backend/windmill-worker/src/ai_executor.rs @@ -467,14 +467,11 @@ async fn find_ai_agent_tool_module_in_parent_agent( .trim_start_matches("$res:") .trim_start_matches("res://"); // Definitions only: resolving their defaults here would hit the same inaccessible resources. - let resource_value = client - .get_resource_value::<serde_json::Value>(agent_path) - .await - .map_err(|e| { - Error::internal_err(format!( - "failed to load ai_agent resource {agent_path}: {e}" - )) - })?; + let resource_value = client.get_agent_value(agent_path).await.map_err(|e| { + Error::internal_err(format!( + "failed to load ai_agent resource {agent_path}: {e}" + )) + })?; match resource_value { serde_json::Value::Object(mut map) => match map.remove("tools") { Some(t) => serde_json::from_value::<Vec<AgentTool>>(t).map_err(|e| { @@ -819,14 +816,11 @@ pub async fn handle_ai_agent_job( // Read raw and interpolate only the brain below. Interpolating the whole resource would also // resolve each tool's default `$res:`/`$var:`, which a host flow may be overriding and which // may be unreadable to whoever runs this flow — an unused tool could then fail the agent. - let resource_value = client - .get_resource_value::<serde_json::Value>(agent_path) - .await - .map_err(|e| { - Error::internal_err(format!( - "failed to load ai_agent resource {agent_path}: {e}" - )) - })?; + let resource_value = client.get_agent_value(agent_path).await.map_err(|e| { + Error::internal_err(format!( + "failed to load ai_agent resource {agent_path}: {e}" + )) + })?; let mut config = match resource_value { serde_json::Value::Object(map) => map, _ => { @@ -1041,8 +1035,7 @@ pub async fn handle_ai_agent_job( Ok(Some(hub_script.schema)) } else { let hash = get_latest_hash_for_path( - db, - db, + &mut *db.acquire().await?, &job.workspace_id, path.as_str(), true, @@ -1673,6 +1666,9 @@ pub async fn run_agent( // re-assumed only near expiry, rather than on every model turn. #[cfg(feature = "bedrock")] let mut bedrock_assumed_role: Option<windmill_ai::ai_bedrock::AssumedRoleCredentials> = None; + let mut anthropic_federated_token: Option< + windmill_ai::providers::anthropic::FederatedAccessToken, + > = None; // Main agent loop for i in 0..max_iterations { @@ -1811,6 +1807,15 @@ pub async fn run_agent( ))); } + let federated_token = + windmill_ai::providers::anthropic::refresh_federated_access_token( + &credentials, + &mut anthropic_federated_token, + client, + ) + .await? + .map(str::to_string); + let timeout = resolve_job_timeout(conn, &job.workspace_id, job.id, job.timeout) .await .0; @@ -1862,10 +1867,15 @@ pub async fn run_agent( }; let endpoint = query_builder.get_endpoint(base_url, args.provider.get_model(), output_type); - let auth_headers = retain_effective_credentials( - &credentials, - query_builder.get_auth_headers(api_key, base_url, output_type), - ); + let auth_headers = match federated_token.as_deref() { + Some(token) => { + windmill_ai::providers::anthropic::federated_auth_headers(token) + } + None => retain_effective_credentials( + &credentials, + query_builder.get_auth_headers(api_key, base_url, output_type), + ), + }; let resp = build_http_request(&endpoint, &auth_headers, request_body) .send() diff --git a/backend/windmill-worker/src/ansible_executor.rs b/backend/windmill-worker/src/ansible_executor.rs index b577097c9d..0613032678 100644 --- a/backend/windmill-worker/src/ansible_executor.rs +++ b/backend/windmill-worker/src/ansible_executor.rs @@ -2098,7 +2098,7 @@ fi nsjail_cmd .current_dir(job_dir) .env_clear() - .envs(PROXY_ENVS.clone()) + .envs(crate::job_proxy_envs()) // inject PYTHONPATH here - for some reason I had to do it in nsjail conf .envs(reserved_variables) .env("PATH", PATH_ENV.as_str()) diff --git a/backend/windmill-worker/src/bash_executor.rs b/backend/windmill-worker/src/bash_executor.rs index 7ec2f4fd33..217d1927f8 100644 --- a/backend/windmill-worker/src/bash_executor.rs +++ b/backend/windmill-worker/src/bash_executor.rs @@ -21,9 +21,7 @@ use windmill_common::{ #[cfg(feature = "dind")] use windmill_common::error::to_anyhow; -use windmill_queue::{ - append_logs, CanceledBy, MiniPulledJob, INIT_SCRIPT_PATH_PREFIX, PERIODIC_SCRIPT_PATH_PREFIX, -}; +use windmill_queue::{append_logs, CanceledBy, MiniPulledJob}; lazy_static::lazy_static! { pub static ref BIN_BASH: String = std::env::var("BASH_PATH").unwrap_or_else(|_| { @@ -148,14 +146,9 @@ pub async fn handle_bash_job( )); } - // Init/periodic scripts need full system access without isolation - let is_regular_job = job - .runnable_path - .as_ref() - .map(|x| { - !x.starts_with(INIT_SCRIPT_PATH_PREFIX) && !x.starts_with(PERIODIC_SCRIPT_PATH_PREFIX) - }) - .unwrap_or(true); + // Init/periodic scripts need full system access without isolation; see + // `MiniPulledJob::is_worker_own_script`. + let is_regular_job = !job.is_worker_own_script(); // Use nsjail if globally enabled OR if script has #sandbox annotation let nsjail = (is_sandboxing_enabled() || annotation.sandbox) && is_regular_job; diff --git a/backend/windmill-worker/src/bun_executor.rs b/backend/windmill-worker/src/bun_executor.rs index 6da968e422..f2d683bcbf 100644 --- a/backend/windmill-worker/src/bun_executor.rs +++ b/backend/windmill-worker/src/bun_executor.rs @@ -1961,6 +1961,32 @@ async fn pull_codebase(w_id: &str, id: &str, job_dir: &str) -> Result<PulledCode Ok(PulledCodebase { is_esm }) } +/// Unpack a codebase tar into the job dir, refusing anything but regular files and +/// directories. +/// +/// The archive comes from the caller (`preview_bundle`, `create_snapshot`) and lands next to +/// the files the worker writes and nsjail bind-mounts by name (`args.json`, `result.json`, +/// `node_modules`, ...). A symlink or hard link entry with one of those names would redirect +/// the write, or the mount, to an arbitrary host path: `tar::Archive::unpack` keeps entry +/// names inside the destination but creates links with whatever target they carry. The +/// archives the CLI and the frontend build contain regular files only. +fn extract_codebase_tar(tar: &[u8], job_dir: &str) -> Result<()> { + let mut ar = tar::Archive::new(tar); + for entry in ar.entries()? { + let mut entry = entry?; + let kind = entry.header().entry_type(); + if !(kind.is_file() || kind.is_dir()) { + return Err(error::Error::ExecutionErr(format!( + "codebase archive entry {} is a {:?}, only regular files and directories are allowed", + entry.path()?.display(), + kind + ))); + } + entry.unpack_in(job_dir)?; + } + Ok(()) +} + fn extract_saved_codebase( job_dir: &str, bun_cache_path: &String, @@ -1968,10 +1994,8 @@ fn extract_saved_codebase( dst: &str, copy: bool, ) -> Result<()> { - use crate::global_cache::extract_tar; - Ok(if is_tar { - extract_tar(fs::read(bun_cache_path)?.into(), job_dir)?; + extract_codebase_tar(&fs::read(bun_cache_path)?, job_dir)?; } else { if copy { std::fs::copy(bun_cache_path, dst)?; @@ -2828,6 +2852,14 @@ try {{ if (step_id) {{ err["step_id"] = step_id; }} + let job_id = process.env.WM_JOB_ID; + if (job_id) {{ + err["job_id"] = job_id; + }} + let flow_path = process.env.WM_FLOW_PATH; + if (flow_path) {{ + err["flow_path"] = flow_path; + }} const extra = {{}}; Object.getOwnPropertyNames(e).forEach((key) => {{ if (['line', 'name', 'stack', 'column', 'message', 'sourceURL', 'originalLine', 'originalColumn'].includes(key)) {{ @@ -2894,6 +2926,14 @@ try {{ if (step_id) {{ err["step_id"] = step_id; }} + let job_id = process.env.WM_JOB_ID; + if (job_id) {{ + err["job_id"] = job_id; + }} + let flow_path = process.env.WM_FLOW_PATH; + if (flow_path) {{ + err["flow_path"] = flow_path; + }} const extra = {{}}; Object.getOwnPropertyNames(e).forEach((key) => {{ if (['line', 'name', 'stack', 'column', 'message', 'sourceURL', 'originalLine', 'originalColumn'].includes(key)) {{ @@ -3130,7 +3170,8 @@ try {{ None, has_stream, ) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; let preprocessed: HashMap<String, Box<RawValue>> = serde_json::from_str(pre_result.get()).map_err(|e| { @@ -3162,7 +3203,8 @@ try {{ stream_notifier, has_stream, ) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; tracing::info!( "Executed native code (with preprocessor) in {}ms", started_at.elapsed().as_millis() @@ -3190,7 +3232,8 @@ try {{ stream_notifier, has_stream, ) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; tracing::info!( "Executed native code in {}ms", started_at.elapsed().as_millis() @@ -4142,6 +4185,42 @@ pub async fn handle_wac_v2_output( job_ids: serde_json::Map::new(), }); + // Generate resume URLs for the inline approval buttons. The resume_id + // is derived from the step key so each waitForApproval() in the same + // workflow gets a unique resume_job record, and so URLs the workflow + // minted for this step ahead of time (getApprovalUrls) address the + // same one. + let resume_id: u32 = windmill_common::wac::approval_resume_id(&key); + // Read before the tx: it holds the queue row lock, and a pool checkout under it + // waits on the connections every other suspending parent is holding. + let wkey = windmill_common::variables::get_workspace_key(&job.workspace_id, db).await?; + let approval_token = + windmill_common::variables::approval_token_from_key(&wkey, job.id)?; + + let (resume_url, cancel_url, approval_page_url) = { + use hmac::{Hmac, Mac}; + use sha2::Sha256; + let mut mac = Hmac::<Sha256>::new_from_slice(wkey.as_bytes()) + .map_err(|e| error::Error::internal_err(format!("HMAC key error: {e}")))?; + mac.update(job.id.as_bytes()); + mac.update(resume_id.to_be_bytes().as_ref()); + let signature = hex::encode(mac.finalize().into_bytes()); + + let base_url = (**windmill_common::BASE_URL.load()).clone(); + let w_id = &job.workspace_id; + let job_id = &job.id; + + let resume = format!( + "{base_url}/api/w/{w_id}/jobs_u/resume/{job_id}/{resume_id}/{signature}" + ); + let cancel = format!( + "{base_url}/api/w/{w_id}/jobs_u/cancel/{job_id}/{resume_id}/{signature}" + ); + let approval_page = + format!("{base_url}/approve/{w_id}/{job_id}?token={approval_token}"); + (resume, cancel, approval_page) + }; + let mut tx = db.begin().await?; // Park first: the queue row is locked before the status row, the order every @@ -4216,44 +4295,6 @@ pub async fn handle_wac_v2_output( } } - // Generate resume URLs for the inline approval buttons. The resume_id - // is derived from the step key so each waitForApproval() in the same - // workflow gets a unique resume_job record, and so URLs the workflow - // minted for this step ahead of time (getApprovalUrls) address the - // same one. - let resume_id: u32 = windmill_common::wac::approval_resume_id(&key); - // Generate stateless approval token using shared utility - let approval_token = - windmill_common::variables::generate_approval_token(&job.workspace_id, job.id, db) - .await?; - - let (resume_url, cancel_url, approval_page_url) = { - use hmac::{Hmac, Mac}; - use sha2::Sha256; - use windmill_common::variables::get_workspace_key; - - let wkey = get_workspace_key(&job.workspace_id, db).await?; - let mut mac = Hmac::<Sha256>::new_from_slice(wkey.as_bytes()) - .map_err(|e| error::Error::internal_err(format!("HMAC key error: {e}")))?; - mac.update(job.id.as_bytes()); - mac.update(resume_id.to_be_bytes().as_ref()); - let signature = hex::encode(mac.finalize().into_bytes()); - - let base_url = (**windmill_common::BASE_URL.load()).clone(); - let w_id = &job.workspace_id; - let job_id = &job.id; - - let resume = format!( - "{base_url}/api/w/{w_id}/jobs_u/resume/{job_id}/{resume_id}/{signature}" - ); - let cancel = format!( - "{base_url}/api/w/{w_id}/jobs_u/cancel/{job_id}/{resume_id}/{signature}" - ); - let approval_page = - format!("{base_url}/approve/{w_id}/{job_id}?token={approval_token}"); - (resume, cancel, approval_page) - }; - // Store approval form metadata for the approval page endpoint let mut approval_meta = serde_json::json!({ "key": key, @@ -5502,4 +5543,56 @@ export function main(x: number) { return x; }"#; assert_eq!(key_for(None).await, key_for(Some(&HashMap::new())).await); assert_ne!(key_for(None).await, attacker); } + + /// Build a codebase tar in memory; `link` adds a symlink entry named after a file the + /// worker writes and nsjail bind-mounts. + fn codebase_tar(link: Option<(&str, &str)>) -> Vec<u8> { + let mut builder = tar::Builder::new(Vec::new()); + let main = b"export async function main() {}\n"; + let mut header = tar::Header::new_gnu(); + header.set_size(main.len() as u64); + header.set_mode(0o644); + header.set_path("main.js").unwrap(); + header.set_cksum(); + builder.append(&header, &main[..]).unwrap(); + if let Some((name, target)) = link { + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_mode(0o777); + header.set_entry_type(tar::EntryType::Symlink); + header.set_path(name).unwrap(); + header.set_link_name(target).unwrap(); + header.set_cksum(); + builder.append(&header, &[][..]).unwrap(); + } + builder.into_inner().unwrap() + } + + #[test] + fn extract_codebase_tar_unpacks_regular_files() { + let dir = tempfile::tempdir().unwrap(); + let job_dir = dir.path().to_str().unwrap(); + + extract_codebase_tar(&codebase_tar(None), job_dir).unwrap(); + + assert_eq!( + std::fs::read_to_string(dir.path().join("main.js")).unwrap(), + "export async function main() {}\n" + ); + } + + #[test] + fn extract_codebase_tar_refuses_links() { + let dir = tempfile::tempdir().unwrap(); + let job_dir = dir.path().to_str().unwrap(); + + let err = extract_codebase_tar(&codebase_tar(Some(("args.json", "/etc/passwd"))), job_dir) + .unwrap_err(); + + assert!(err.to_string().contains("args.json"), "{err}"); + assert!( + std::fs::symlink_metadata(dir.path().join("args.json")).is_err(), + "the link must not be created" + ); + } } diff --git a/backend/windmill-worker/src/dbt_executor.rs b/backend/windmill-worker/src/dbt_executor.rs index 28db2753e1..4db8201e9b 100644 --- a/backend/windmill-worker/src/dbt_executor.rs +++ b/backend/windmill-worker/src/dbt_executor.rs @@ -2343,7 +2343,12 @@ pub(crate) fn dbt_command(p: &PreparedProject, args: &[&str]) -> Command { } cmd.current_dir(&p.project_dir) .env_clear() - .envs(PROXY_ENVS.clone()) + // `deps` is a dependency install, which keeps the proxy whatever the group says. + .envs(if args == ["deps"] { + PROXY_ENVS.clone() + } else { + crate::job_proxy_envs() + }) .env("PATH", PATH_ENV.as_str()) .env("TZ", TZ_ENV.as_str()) .env("GIT_PATH", GIT_PATH.as_str()) diff --git a/backend/windmill-worker/src/deno_executor.rs b/backend/windmill-worker/src/deno_executor.rs index 58388c3cfd..de2098392e 100644 --- a/backend/windmill-worker/src/deno_executor.rs +++ b/backend/windmill-worker/src/deno_executor.rs @@ -244,6 +244,40 @@ pub async fn generate_deno_lock( } } +/// SECURITY: a sandboxed deno job is not nsjail-wrapped; its confinement is +/// `--allow-read=./` / `--allow-write=./`, which Deno checks against the path +/// as written and then hands to the kernel, which follows symlinks. `./shared` +/// is the worker's own link to the flow's shared directory, and every other +/// step of a `same_worker` flow gets that directory bind-mounted read-write +/// inside its jail. A link planted there (`ln -s / /tmp/shared/root` from a +/// bash step) would let the following deno step read and write the whole +/// worker host through `./shared/root/...`. Links pointing inside the +/// directory are not safe either: Deno collapses `..` textually before the +/// check while the kernel applies it to the resolved target. So nothing but +/// regular files and directories may be in there when the job starts. +/// `DirEntry::file_type` reports a link's own type without following it. +async fn refuse_links_in_shared_dir(job_dir: &str) -> error::Result<()> { + let shared = format!("{job_dir}/shared"); + let mut dirs = vec![std::path::PathBuf::from(&shared)]; + while let Some(dir) = dirs.pop() { + let mut entries = tokio::fs::read_dir(&dir).await?; + while let Some(entry) = entries.next_entry().await? { + let file_type = entry.file_type().await?; + if file_type.is_dir() { + dirs.push(entry.path()); + } else if !file_type.is_file() { + let path = entry.path(); + return Err(error::Error::ExecutionErr(format!( + "the flow's shared directory contains ./{}, which is not a regular file \ + or directory: a sandboxed deno step cannot run with it", + path.strip_prefix(job_dir).unwrap_or(&path).display() + ))); + } + } + } + Ok(()) +} + #[tracing::instrument(level = "trace", skip_all)] pub async fn handle_deno_job( requirements_o: Option<&String>, @@ -265,6 +299,10 @@ pub async fn handle_deno_job( ensure_deno_installed()?; let annotations = TypeScriptAnnotations::parse(inner_content); + if job.same_worker && (is_sandboxing_enabled() || annotations.sandbox) { + refuse_links_in_shared_dir(job_dir).await?; + } + // let mut start = Instant::now(); let mut logs1 = "\n\n--- DENO CODE EXECUTION ---\n".to_string(); if annotations.sandbox { @@ -387,6 +425,14 @@ try {{ if (step_id) {{ err["step_id"] = step_id; }} + let job_id = Deno.env.get("WM_JOB_ID"); + if (job_id) {{ + err["job_id"] = job_id; + }} + let flow_path = Deno.env.get("WM_FLOW_PATH"); + if (flow_path) {{ + err["flow_path"] = flow_path; + }} await Deno.writeTextFile("result.json", JSON.stringify(err)); Deno.exit(1); }} @@ -445,6 +491,12 @@ try {{ conn, ) .await; + // The only deno.json deno may honour is the one the worker writes here. Script modules + // are written verbatim into the job dir, so without an explicit choice deno would + // discover a `deno.json(c)` the job shipped as a module, and a config is applied by + // the runtime itself, outside the --allow-* permissions: its `lock` key alone makes + // deno write a file wherever it points, past --allow-write. + let mut deno_config_path: Option<String> = None; if let Some(ref npmrc_content) = npmrc { if !npmrc_content.trim().is_empty() { write_file(job_dir, ".npmrc", npmrc_content)?; @@ -453,8 +505,16 @@ try {{ // routinely serve just-published versions, so the guard would break them. // Older Deno ignores the unknown field, so this is safe across versions. write_file(job_dir, "deno.json", r#"{"minimumDependencyAge":"0"}"#)?; + deno_config_path = Some(format!("{job_dir}/deno.json")); } } + // An admin may pass a config of their own through DENO_FLAGS; deno refuses it next + // to --no-config or a second --config, so it then stands on its own. + let config_in_deno_flags = DENO_FLAGS.as_ref().is_some_and(|flags| { + flags + .iter() + .any(|f| f == "-c" || f == "--config" || f.starts_with("--config=")) + }); //do not cache local dependencies let child = { @@ -464,6 +524,15 @@ try {{ let mut args = Vec::with_capacity(12); args.push("run"); args.push("--no-check"); + if !config_in_deno_flags { + match deno_config_path.as_deref() { + Some(config) => { + args.push("--config"); + args.push(config); + } + None => args.push("--no-config"), + } + } args.push("--import-map"); args.push(&import_map_path); args.push(&reload); diff --git a/backend/windmill-worker/src/duckdb_executor.rs b/backend/windmill-worker/src/duckdb_executor.rs index 05c35fce8d..0db954d85f 100644 --- a/backend/windmill-worker/src/duckdb_executor.rs +++ b/backend/windmill-worker/src/duckdb_executor.rs @@ -1792,6 +1792,8 @@ pub async fn do_duckdb( return Err(Error::ExecutionRawError(to_raw_value(&json!({ "message": message, "name": "ExecutionErr", + "flow_path": reserved_variables.get("WM_FLOW_PATH").filter(|p| !p.is_empty()), + "job_id": job.id, "step_id": job.flow_step_id, "data_tests": data_tests, })))); diff --git a/backend/windmill-worker/src/duckdb_runner.rs b/backend/windmill-worker/src/duckdb_runner.rs index b7c0bc6321..56b3c1f5cc 100644 --- a/backend/windmill-worker/src/duckdb_runner.rs +++ b/backend/windmill-worker/src/duckdb_runner.rs @@ -167,28 +167,37 @@ fn needed_extensions(blocks: &[String]) -> Vec<String> { static INSTALLED: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Default::default); -/// Installs, outside the jail, what the job will load inside it. The runner only runs -/// `INSTALL` here, and only of statements built above, so no script SQL and no extension -/// code runs unjailed. Once per extension per worker process. -async fn install_missing_extensions(blocks: &[String], job_dir: &str) -> Result<()> { +/// Installs, ahead of the job and with the worker's proxy, what the job will load: into the +/// jail's cache for a jailed run, or into the runner's default one for a run that does not get +/// the proxy and so could not download them itself. The runner only runs `INSTALL` here, and +/// only of statements built above, so no script SQL and no extension code runs unjailed. Once +/// per extension per cache per worker process. +async fn install_missing_extensions( + blocks: &[String], + job_dir: &str, + jail_cache: bool, +) -> Result<()> { + let key = |s: &String| format!("{jail_cache}:{s}"); let missing: Vec<String> = { let installed = INSTALLED.lock().unwrap(); needed_extensions(blocks) .into_iter() - .filter(|s| s.starts_with("FORCE ") || !installed.contains(s)) + .filter(|s| s.starts_with("FORCE ") || !installed.contains(&key(s))) .collect() }; if missing.is_empty() { return Ok(()); } - let ext_dir = extension_dir(); - tokio::fs::create_dir_all(&ext_dir).await?; - let blocks: Vec<String> = std::iter::once(format!( - "SET extension_directory='{}';", - ext_dir.replace('\'', "''") - )) - .chain(missing.iter().cloned()) - .collect(); + let mut blocks = Vec::with_capacity(missing.len() + 1); + if jail_cache { + let ext_dir = extension_dir(); + tokio::fs::create_dir_all(&ext_dir).await?; + blocks.push(format!( + "SET extension_directory='{}';", + ext_dir.replace('\'', "''") + )); + } + blocks.extend(missing.iter().cloned()); let out = spawn_runner( RunnerMode::Plain, &RunnerRequest { @@ -210,10 +219,13 @@ async fn install_missing_extensions(blocks: &[String], job_dir: &str) -> Result< if let Some(raw) = out.result.strip_prefix("ERROR ") { let msg = serde_json::from_str::<String>(raw).unwrap_or_else(|_| raw.to_string()); return Err(Error::ExecutionErr(format!( - "Installing DuckDB extensions for the jailed runner failed: {msg}" + "Installing DuckDB extensions ahead of the job failed: {msg}" ))); } - INSTALLED.lock().unwrap().extend(missing.into_iter().filter(|s| !s.starts_with("FORCE "))); + INSTALLED + .lock() + .unwrap() + .extend(missing.iter().filter(|s| !s.starts_with("FORCE ")).map(key)); Ok(()) } @@ -289,10 +301,10 @@ pub(crate) async fn run( let spill_dir = format!("{}/spill", work_dir(job_dir)); tokio::fs::create_dir_all(&spill_dir).await?; let req = RunnerRequest { temp_directory: &spill_dir, ..*req }; - if mode != RunnerMode::Jailed { + if mode != RunnerMode::Jailed && crate::passes_proxy_to_jobs() { return spawn_runner(mode, &req, job_dir).await; } - install_missing_extensions(req.blocks, job_dir).await?; + install_missing_extensions(req.blocks, job_dir, mode == RunnerMode::Jailed).await?; let blocks = unforce_installs(req.blocks); spawn_runner(mode, &RunnerRequest { blocks: &blocks, ..req }, job_dir).await } @@ -438,19 +450,24 @@ async fn spawn_runner( if let Some(cap) = &spill_cap { cmd.env("DUCKDB_MAX_TEMP_DIRECTORY_SIZE", cap); } - for var in [ - "GOOGLE_APPLICATION_CREDENTIALS", - "HTTP_PROXY", - "HTTPS_PROXY", - "NO_PROXY", - "ALL_PROXY", - "http_proxy", - "https_proxy", - "no_proxy", - "all_proxy", - ] { - if let Ok(v) = std::env::var(var) { - cmd.env(var, v); + if let Ok(v) = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") { + cmd.env("GOOGLE_APPLICATION_CREDENTIALS", v); + } + // An `Install` request only fetches extensions, a dependency install that keeps the proxy. + if matches!(req.mode, RequestMode::Install) || crate::passes_proxy_to_jobs() { + for var in [ + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "ALL_PROXY", + "http_proxy", + "https_proxy", + "no_proxy", + "all_proxy", + ] { + if let Ok(v) = std::env::var(var) { + cmd.env(var, v); + } } } diff --git a/backend/windmill-worker/src/global_cache.rs b/backend/windmill-worker/src/global_cache.rs index 1c3bbf870f..622f021fcb 100644 --- a/backend/windmill-worker/src/global_cache.rs +++ b/backend/windmill-worker/src/global_cache.rs @@ -1,3 +1,6 @@ +// Only the enterprise object-store tar helpers use this; `load_cache` below qualifies +// `std::time::Instant` directly, so the import is dead in other builds. +#[cfg(all(feature = "enterprise", feature = "parquet"))] use tokio::time::Instant; use windmill_common::error; @@ -199,6 +202,10 @@ pub async fn pull_from_tar( Ok(()) } +// Only `pull_from_tar` (the enterprise object-store cache path) still unpacks a tar +// through this helper; the codebase-bundle path uses `extract_codebase_tar` instead. +// Gate it with the caller's cfg so it is not dead code in other builds. +#[cfg(all(feature = "enterprise", feature = "parquet"))] pub fn extract_tar(tar: bytes::Bytes, folder: &str) -> error::Result<()> { use bytes::Buf; diff --git a/backend/windmill-worker/src/java_executor.rs b/backend/windmill-worker/src/java_executor.rs index 39c8804cd5..c4678cfe83 100644 --- a/backend/windmill-worker/src/java_executor.rs +++ b/backend/windmill-worker/src/java_executor.rs @@ -252,7 +252,7 @@ pub async fn resolve<'a>( // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(PROXY_ENVS.clone())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -417,7 +417,7 @@ async fn install<'a>( .envs(PROXY_ENVS.clone()); // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(PROXY_ENVS.clone())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -803,7 +803,7 @@ async fn run<'a>( } // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(crate::job_proxy_envs())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -882,7 +882,7 @@ async fn run<'a>( } // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(crate::job_proxy_envs())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -943,9 +943,9 @@ struct JavaProxySettings { https_port: Option<String>, no_proxy: Option<String>, } -fn parse_proxy() -> anyhow::Result<JavaProxySettings> { +fn parse_proxy(proxy_envs: Vec<(&'static str, String)>) -> anyhow::Result<JavaProxySettings> { let mut jps = JavaProxySettings::default(); - for (ident, mut val) in PROXY_ENVS.clone() { + for (ident, mut val) in proxy_envs { match ident { "HTTPS_PROXY" => { if !val.contains("://") { diff --git a/backend/windmill-worker/src/js_eval.rs b/backend/windmill-worker/src/js_eval.rs index bc8b33a5f2..2e78f0aae8 100644 --- a/backend/windmill-worker/src/js_eval.rs +++ b/backend/windmill-worker/src/js_eval.rs @@ -107,6 +107,31 @@ pub async fn eval_timeout( } } +/// 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( + e: windmill_common::error::Error, + reserved_variables: &HashMap<String, String>, +) -> windmill_common::error::Error { + use windmill_common::error::Error; + 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; + }; + for (key, var) in [ + ("step_id", "WM_FLOW_STEP_ID"), + ("job_id", "WM_JOB_ID"), + ("flow_path", "WM_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())); + } + } + Error::ExecutionRawError(windmill_common::worker::to_raw_value(&err)) +} + #[cfg(feature = "deno_core")] pub fn transpile_ts(expr: String) -> anyhow::Result<String> { windmill_runtime_nativets::transpile_ts(expr) diff --git a/backend/windmill-worker/src/nsjail_compat.rs b/backend/windmill-worker/src/nsjail_compat.rs index 3069dcee52..e3b1f7656f 100644 --- a/backend/windmill-worker/src/nsjail_compat.rs +++ b/backend/windmill-worker/src/nsjail_compat.rs @@ -46,4 +46,90 @@ mod tests { assert_eq!(twice.matches("gvisor_compat").count(), 1); assert!(twice.ends_with("\nclone_newcgroup: false\ngvisor_compat: true\n")); } + + /// Every nsjail profile drops its capabilities. + #[test] + fn every_nsjail_config_drops_capabilities() { + let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/nsjail"); + let mut checked = 0; + for entry in std::fs::read_dir(dir).expect("nsjail config dir") { + let path = entry.expect("dir entry").path(); + if path.extension().and_then(|e| e.to_str()) != Some("proto") { + continue; + } + let content = std::fs::read_to_string(&path).expect("read config"); + let settings = content + .lines() + .map(str::trim) + .filter(|l| l.starts_with("keep_caps")) + .collect::<Vec<_>>(); + assert_eq!( + settings, + vec!["keep_caps: false"], + "{} must set keep_caps: false exactly once", + path.display() + ); + checked += 1; + } + assert!( + checked >= 20, + "only {checked} nsjail configs found in {dir}, expected all of them" + ); + } + + /// `REQ` and `TARGET` reach uv as single, unaltered argv words. + #[cfg(unix)] + #[test] + fn download_deps_passes_the_requirement_as_a_literal_argv_word() { + use std::os::unix::fs::PermissionsExt; + + let dir = std::env::temp_dir().join(format!("wm_download_deps_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + + // Stand-in for uv that prints each argument it receives on its own line. + let uv = dir.join("uv_argv_dump"); + std::fs::write( + &uv, + "#!/bin/sh\nfor a in \"$@\"; do printf '<%s>\\n' \"$a\"; done\n", + ) + .expect("write stub"); + std::fs::set_permissions(&uv, std::fs::Permissions::from_mode(0o755)).expect("chmod stub"); + + let script = dir.join("download_deps.sh"); + std::fs::write( + &script, + include_str!("../nsjail/download_deps.py.sh") + .replace("/usr/local/bin/uv", uv.to_str().unwrap()), + ) + .expect("write script"); + + let marker = dir.join("marker"); + let req = format!("x==$(touch {})", marker.display()); + let target = dir.join("target dir with spaces"); + let out = std::process::Command::new("/bin/sh") + .arg(&script) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("REQ", &req) + .env("TARGET", &target) + .output() + .expect("run download_deps.sh"); + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + + assert!( + !marker.exists(), + "REQ was not passed through verbatim; stdout was:\n{stdout}" + ); + assert!( + stdout.contains(&format!("<{req}>\n")), + "the requirement must be one literal argv word; stdout was:\n{stdout}" + ); + assert!( + stdout.contains(&format!("<--target>\n<{}>\n", target.display())), + "--target must be followed by the target dir as one argv word; stdout was:\n{stdout}" + ); + + std::fs::remove_dir_all(&dir).expect("cleanup scratch dir"); + } } diff --git a/backend/windmill-worker/src/php_executor.rs b/backend/windmill-worker/src/php_executor.rs index 26559e8b37..fad3a7ce56 100644 --- a/backend/windmill-worker/src/php_executor.rs +++ b/backend/windmill-worker/src/php_executor.rs @@ -2,7 +2,7 @@ use convert_case::{Case, Casing}; use itertools::Itertools; use regex::Regex; use serde_json::value::RawValue; -use std::{collections::HashMap, process::Stdio}; +use std::{collections::HashMap, path::Path, process::Stdio}; use tokio::{fs::File, io::AsyncReadExt, process::Command}; use uuid::Uuid; use windmill_common::{ @@ -20,10 +20,9 @@ use windmill_queue::{append_logs, CanceledBy}; use crate::common::DEV_CONF_NSJAIL; use crate::{ common::{ - build_command_with_isolation, check_executor_binary_exists, create_args_and_out_file, - get_reserved_variables, read_result, resolve_nsjail_timeout, - resolve_nsjail_tmp_mount_block, script_envars, start_child_process, MaybeLock, - OccupancyMetrics, + build_command_with_isolation, create_args_and_out_file, get_reserved_variables, + read_result, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, script_envars, + start_child_process, MaybeLock, OccupancyMetrics, }, handle_child::handle_child, is_sandboxing_enabled, COMPOSER_CACHE_DIR, COMPOSER_PATH, DISABLE_NUSER, NSJAIL_PATH, PATH_ENV, @@ -44,6 +43,22 @@ lazy_static::lazy_static! { const COMPOSER_LOCK_SPLIT: &str = "\nLOCK\n"; +fn ensure_php_tool_installed(tool: &str, path: &str) -> Result<()> { + // A bare name is resolved through PATH when the process starts, not here. + let path_ref = Path::new(path); + if !path_ref.is_absolute() || path_ref.exists() { + return Ok(()); + } + Err(error::Error::ExecutionErr(format!( + "{tool} is not installed on this worker (looked for it at {path}). PHP and Composer are no \ + longer included in the standard windmill and windmill-ee images: they ship only in the \ + full images. To run PHP scripts, switch the workers that run PHP jobs to \ + ghcr.io/windmill-labs/windmill-full (Community Edition) or \ + ghcr.io/windmill-labs/windmill-ee-full (Enterprise Edition), or install PHP and Composer \ + on them and point PHP_PATH and COMPOSER_PATH at them." + ))) +} + static PHP_PARSER_SLOT: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1); pub(crate) async fn parse_php_signature( @@ -123,7 +138,8 @@ pub async fn composer_install( lock: Option<String>, occupancy_metrics: &mut OccupancyMetrics, ) -> Result<String> { - check_executor_binary_exists("php", PHP_PATH.as_str(), "php")?; + ensure_php_tool_installed("PHP", PHP_PATH.as_str())?; + ensure_php_tool_installed("Composer", COMPOSER_PATH.as_str())?; // When no lock is provided (previews), try to reuse a previously resolved // lockfile from the DB so we can hit the same vendor cache as deployed scripts. @@ -415,7 +431,7 @@ pub async fn handle_php_job( shared_mount: &str, occupancy_metrics: &mut OccupancyMetrics, ) -> error::Result<Box<RawValue>> { - check_executor_binary_exists("php", PHP_PATH.as_str(), "php")?; + ensure_php_tool_installed("PHP", PHP_PATH.as_str())?; let (composer_json, composer_lock) = match &maybe_lock { MaybeLock::Resolved { lock } if !lock.is_empty() => split_reqs_and_lock(lock)?, @@ -513,6 +529,14 @@ try {{ if ($step_id) {{ $err["step_id"] = $step_id; }} + $job_id = getenv('WM_JOB_ID'); + if ($job_id) {{ + $err["job_id"] = $job_id; + }} + $flow_path = getenv('WM_FLOW_PATH'); + if ($flow_path) {{ + $err["flow_path"] = $flow_path; + }} file_put_contents("result.json", json_encode($err)); exit(1); }} diff --git a/backend/windmill-worker/src/pwsh_executor.rs b/backend/windmill-worker/src/pwsh_executor.rs index c089930b42..4572a868a8 100644 --- a/backend/windmill-worker/src/pwsh_executor.rs +++ b/backend/windmill-worker/src/pwsh_executor.rs @@ -9,9 +9,7 @@ use windmill_common::error::Error; use windmill_common::scripts::ScriptLang; use windmill_common::worker::{to_raw_value, write_file, Connection}; use windmill_common::workspace_dependencies::clean_lock_from_annotations; -use windmill_queue::{ - append_logs, CanceledBy, MiniPulledJob, INIT_SCRIPT_PATH_PREFIX, PERIODIC_SCRIPT_PATH_PREFIX, -}; +use windmill_queue::{append_logs, CanceledBy, MiniPulledJob}; #[cfg(windows)] use crate::SYSTEM_ROOT; @@ -36,7 +34,7 @@ use crate::{ handle_child::handle_child, is_sandboxing_enabled, read_ee_registry_with_workspace_override, DISABLE_NUSER, HOME_ENV, NSJAIL_PATH, PATH_ENV, POWERSHELL_CACHE_DIR, POWERSHELL_PATH, POWERSHELL_REPO_PAT, - POWERSHELL_REPO_URL, PROXY_ENVS, TZ_ENV, + POWERSHELL_REPO_URL, TZ_ENV, }; fn val_to_pwsh_param(v: serde_json::Value) -> String { @@ -690,15 +688,9 @@ $env:PSModulePath = \"{};$PSModulePathBackup\"", let _ = write_file(job_dir, "result.out", "")?; let _ = write_file(job_dir, "result2.out", "")?; - // Check if this is a regular job (not init or periodic script) - // Init/periodic scripts need full system access without isolation - let is_regular_job = job - .runnable_path - .as_ref() - .map(|x| { - !x.starts_with(INIT_SCRIPT_PATH_PREFIX) && !x.starts_with(PERIODIC_SCRIPT_PATH_PREFIX) - }) - .unwrap_or(true); + // Init/periodic scripts need full system access without isolation; see + // `MiniPulledJob::is_worker_own_script`. + let is_regular_job = !job.is_worker_own_script(); let nsjail = is_sandboxing_enabled() && is_regular_job; let child = if nsjail { @@ -728,7 +720,7 @@ $env:PSModulePath = \"{};$PSModulePathBackup\"", let mut cmd = Command::new(NSJAIL_PATH.as_str()); cmd.current_dir(job_dir) .env_clear() - .envs(PROXY_ENVS.clone()) + .envs(crate::job_proxy_envs()) .envs(reserved_variables) .env("TZ", TZ_ENV.as_str()) .env("PATH", PATH_ENV.as_str()) diff --git a/backend/windmill-worker/src/python_executor.rs b/backend/windmill-worker/src/python_executor.rs index 430d6e82ef..aea9bd4af6 100644 --- a/backend/windmill-worker/src/python_executor.rs +++ b/backend/windmill-worker/src/python_executor.rs @@ -117,7 +117,7 @@ async fn handle_piptar_uploads(mut rx: tokio::sync::mpsc::UnboundedReceiver<Pipt const NSJAIL_CONFIG_DOWNLOAD_PY_CONTENT: &str = include_str!("../nsjail/download.py.config.proto"); const NSJAIL_CONFIG_RUN_PYTHON3_CONTENT: &str = include_str!("../nsjail/run.python3.config.proto"); const NSJAIL_CONFIG_LOCK_PY_CONTENT: &str = include_str!("../nsjail/lock.py.config.proto"); -pub const RELATIVE_PYTHON_LOADER: &str = include_str!("../loader.py"); +const RELATIVE_PYTHON_LOADER: &str = include_str!("../loader.py"); /// Every file exchanged with a job is UTF-8 by construction, so the interpreter /// must agree. A job env carries no locale: Linux then picks UTF-8 on its own @@ -129,7 +129,9 @@ pub const PYTHON_UTF8_ENVS: [(&str, &str); 1] = [("PYTHONUTF8", "1")]; /// Python dict literal. Preview jobs pass a path -> temp-hash map so relative /// imports resolve from not-yet-deployed local content; deployed runs pass /// `None` which renders an empty dict (deployed resolution unchanged). -fn render_relative_python_loader(temp_script_refs: &Option<HashMap<String, String>>) -> String { +pub(crate) fn render_relative_python_loader( + temp_script_refs: &Option<HashMap<String, String>>, +) -> String { let temp_refs_py = temp_script_refs .as_ref() .and_then(|m| serde_json::to_string(m).ok()) @@ -1001,6 +1003,12 @@ except BaseException as e: flow_node_id = os.environ.get('WM_FLOW_STEP_ID') if flow_node_id: err['step_id'] = flow_node_id + job_id = os.environ.get('WM_JOB_ID') + if job_id: + err['job_id'] = job_id + flow_path = os.environ.get('WM_FLOW_PATH') + if flow_path: + err['flow_path'] = flow_path err_json = json.dumps(err, separators=(',', ':'), default=str).replace('\n', '') f.write(err_json) sys.exit(1) @@ -1071,6 +1079,12 @@ except BaseException as e: flow_node_id = os.environ.get('WM_FLOW_STEP_ID') if flow_node_id: err['step_id'] = flow_node_id + job_id = os.environ.get('WM_JOB_ID') + if job_id: + err['job_id'] = job_id + flow_path = os.environ.get('WM_FLOW_PATH') + if flow_path: + err['flow_path'] = flow_path err_json = json.dumps(err, separators=(',', ':'), default=str).replace('\n', '') f.write(err_json) sys.exit(1) diff --git a/backend/windmill-worker/src/r_executor.rs b/backend/windmill-worker/src/r_executor.rs index 214cf35525..4220feba91 100644 --- a/backend/windmill-worker/src/r_executor.rs +++ b/backend/windmill-worker/src/r_executor.rs @@ -627,7 +627,7 @@ async fn run<'a>( .env("PATH", PATH_ENV.as_str()) .env("BASE_INTERNAL_URL", base_internal_url) .envs(&reserved_variables) - .envs(if no_network { + .envs(if no_network || !crate::passes_proxy_to_jobs() { vec![] } else { R_PROXY_ENVS.clone() @@ -703,7 +703,11 @@ async fn run<'a>( .env("PATH", PATH_ENV.as_str()) .env("BASE_INTERNAL_URL", base_internal_url) .envs(reserved_variables) - .envs(R_PROXY_ENVS.clone()) + .envs(if crate::passes_proxy_to_jobs() { + R_PROXY_ENVS.clone() + } else { + vec![] + }) .envs( get_proxy_envs_for_lang( &ScriptLang::Rlang, diff --git a/backend/windmill-worker/src/ruby_executor.rs b/backend/windmill-worker/src/ruby_executor.rs index 1cd477e1fd..c5828f192a 100644 --- a/backend/windmill-worker/src/ruby_executor.rs +++ b/backend/windmill-worker/src/ruby_executor.rs @@ -825,7 +825,11 @@ mount {{ .env("BASE_INTERNAL_URL", base_internal_url) .env("RUBYLIB", rubylib.as_str()) .envs(&reserved_variables) - .envs(RUBY_PROXY_ENVS.clone()) + .envs(if crate::passes_proxy_to_jobs() { + RUBY_PROXY_ENVS.clone() + } else { + vec![] + }) .envs( get_proxy_envs_for_lang( &ScriptLang::Ruby, @@ -900,7 +904,11 @@ mount {{ .env("RUBYLIB", rubylib.as_str()) .env("BASE_INTERNAL_URL", base_internal_url) .envs(reserved_variables) - .envs(RUBY_PROXY_ENVS.clone()) + .envs(if crate::passes_proxy_to_jobs() { + RUBY_PROXY_ENVS.clone() + } else { + vec![] + }) .envs( get_proxy_envs_for_lang( &ScriptLang::Ruby, diff --git a/backend/windmill-worker/src/rust_executor.rs b/backend/windmill-worker/src/rust_executor.rs index fabea34499..bba1be8ad4 100644 --- a/backend/windmill-worker/src/rust_executor.rs +++ b/backend/windmill-worker/src/rust_executor.rs @@ -87,6 +87,8 @@ lazy_static::lazy_static! { static ref CARGO_PATH: String = find_cargo_path(); static ref SWEEP_MAXSIZE: String = std::env::var("CARGO_SWEEP_MAXSIZE").unwrap_or("25GB".to_owned()); static ref NO_SHARED_BUILD_DIR: bool = std::env::var("RUST_NO_SHARED_BUILD_DIR").ok().map(|flag| flag == "true").unwrap_or(false); + /// Parent of the worker-owned working directories of host-side cargo invocations, see [`HostCargoCwd`]. + static ref HOST_CARGO_CWD_DIR: String = format!("{}/host_cargo_cwd", *RUST_CACHE_DIR); } #[cfg(windows)] @@ -242,13 +244,10 @@ pub fn __WINDMILL_RUN__(_args: __WINDMILL_ARGS__) -> Result<String, Box<dyn std: Ok(()) } -async fn write_cargo_config( - job_dir: &str, - job_id: &Uuid, - w_id: &str, - conn: &Connection, -) -> anyhow::Result<()> { - if let Some(cargo_registries) = read_ee_registry_with_workspace_override( +/// The instance/workspace cargo registry configuration, if any is set, as the body of a +/// `.cargo/config.toml`. +async fn cargo_registries_config(job_id: &Uuid, w_id: &str, conn: &Connection) -> Option<String> { + read_ee_registry_with_workspace_override( CARGO_REGISTRIES.read().await.clone(), "cargo_registries", "cargo registries", @@ -257,16 +256,150 @@ async fn write_cargo_config( conn, ) .await - { - if !cargo_registries.trim().is_empty() { - let cargo_dir = format!("{job_dir}/.cargo"); - create_dir_all(&cargo_dir).await?; - write_file(&cargo_dir, "config.toml", &cargo_registries)?; - } + .filter(|cargo_registries| !cargo_registries.trim().is_empty()) +} + +/// Write `{dir}/.cargo/config.toml`. cargo only reads it when `dir` is the working +/// directory of the invocation (or an ancestor of it), never because `dir` holds the +/// manifest the invocation was pointed at. +async fn write_cargo_registries_config(dir: &str, registries: &str) -> anyhow::Result<()> { + let cargo_dir = format!("{dir}/.cargo"); + create_dir_all(&cargo_dir).await?; + write_file(&cargo_dir, "config.toml", registries)?; + Ok(()) +} + +async fn write_cargo_config( + job_dir: &str, + job_id: &Uuid, + w_id: &str, + conn: &Connection, +) -> anyhow::Result<()> { + if let Some(cargo_registries) = cargo_registries_config(job_id, w_id, conn).await { + write_cargo_registries_config(job_dir, &cargo_registries).await?; } Ok(()) } +/// Stub manifest for a [`HostCargoCwd`]. Nothing is ever built from it; `cargo sweep` +/// only needs *a* manifest in its working directory to ask `cargo metadata` where the +/// target directory is, and `[workspace]` keeps cargo from walking further up. +const HOST_CARGO_CWD_MANIFEST: &str = r#"# Worker-owned stub crate. Host-side cargo invocations run from here so that their +# configuration discovery never reaches a job directory. Nothing is built from it. +[workspace] + +[package] +name = "windmill_host_cargo_cwd" +version = "0.0.0" + +[lib] +path = "src/lib.rs" +"#; + +/// Working directory for cargo invocations that run outside the build jail. cargo reads +/// `.cargo/config.toml` from its working directory and that directory's ancestors (not +/// from the manifest's directory), so this is a worker-owned directory under the rust +/// cache dir, outside any job directory and outside the build dirs. +struct HostCargoCwd { + path: String, +} + +impl HostCargoCwd { + /// `registries` is the worker's own cargo registry configuration (never the job's), to + /// be made visible to the invocation as this directory's `.cargo/config.toml`. + async fn new(kind: &str, registries: Option<&str>) -> anyhow::Result<Self> { + let path = format!("{}/{kind}-{}", *HOST_CARGO_CWD_DIR, Uuid::new_v4()); + create_dir_all(format!("{path}/src")).await.map_err(|e| { + anyhow::anyhow!("Could not create host cargo working dir {path}.\ne: {e}") + })?; + let cwd = HostCargoCwd { path }; + write_file(&cwd.path, "Cargo.toml", HOST_CARGO_CWD_MANIFEST)?; + write_file(&format!("{}/src", cwd.path), "lib.rs", "")?; + if let Some(registries) = registries { + write_cargo_registries_config(&cwd.path, registries).await?; + } + Ok(cwd) + } + + fn path(&self) -> &str { + &self.path + } +} + +impl Drop for HostCargoCwd { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// `cargo generate-lockfile` for the crate in `job_dir`, run from `cwd`. +/// +/// `cwd` is a [`HostCargoCwd`] and not `job_dir`, so the crate is named with +/// `--manifest-path`; cargo writes `Cargo.lock` next to that manifest, i.e. still at +/// `{job_dir}/Cargo.lock`. +fn build_generate_lockfile_command(cwd: &str, job_dir: &str) -> Command { + let mut gen_lockfile_cmd = Command::new(CARGO_PATH.as_str()); + gen_lockfile_cmd + .current_dir(cwd) + .env_clear() + .env("PATH", PATH_ENV.as_str()) + .env("HOME", HOME_ENV.as_str()) + .env("CARGO_HOME", CARGO_HOME.as_str()) + .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) + .envs(PROXY_ENVS.clone()) + .args([ + "generate-lockfile", + "--manifest-path", + &format!("{job_dir}/Cargo.toml"), + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + gen_lockfile_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); + gen_lockfile_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); + gen_lockfile_cmd.env( + "TMP", + std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), + ); + } + gen_lockfile_cmd +} + +/// `cargo sweep` over the shared build dir's target dir, run from `cwd`. +/// +/// `cwd` is a [`HostCargoCwd`] and not `job_dir`. `cargo sweep` resolves the target +/// directory to prune by running `cargo metadata` for the manifest in its working +/// directory, and `CARGO_TARGET_DIR` overrides what that resolves to — which is how this +/// invocation has always reached `{build_dir}/target`, the stub manifest in `cwd` standing +/// in for the job's crate. +fn build_cargo_sweep_command(cwd: &str, build_dir: &str) -> Command { + let mut sweep_cmd = Command::new(CARGO_PATH.as_str()); + let sweep_path = format!("{}/bin:{}", CARGO_HOME.as_str(), PATH_ENV.as_str()); + sweep_cmd + .current_dir(cwd) + .env_clear() + .env("PATH", &sweep_path) + .env("CARGO_HOME", CARGO_HOME.as_str()) + .env("HOME", HOME_ENV.as_str()) + .env("CARGO_TARGET_DIR", &format!("{build_dir}/target")) + .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) + .args(["sweep", "--maxsize", SWEEP_MAXSIZE.as_str()]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + #[cfg(windows)] + { + sweep_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); + sweep_cmd.env( + "TMP", + std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), + ); + sweep_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); + } + sweep_cmd +} + pub async fn generate_cargo_lockfile( job_id: &Uuid, code: &str, @@ -282,29 +415,14 @@ pub async fn generate_cargo_lockfile( check_executor_binary_exists("cargo", CARGO_PATH.as_str(), "rust")?; gen_cargo_crate(code, job_dir)?; - write_cargo_config(job_dir, job_id, w_id, conn).await?; - - let mut gen_lockfile_cmd = Command::new(CARGO_PATH.as_str()); - gen_lockfile_cmd - .current_dir(job_dir) - .env_clear() - .env("PATH", PATH_ENV.as_str()) - .env("HOME", HOME_ENV.as_str()) - .env("CARGO_HOME", CARGO_HOME.as_str()) - .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) - .envs(PROXY_ENVS.clone()) - .args(vec!["generate-lockfile"]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - #[cfg(windows)] - { - gen_lockfile_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); - gen_lockfile_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); - gen_lockfile_cmd.env( - "TMP", - std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), - ); + let registries = cargo_registries_config(job_id, w_id, conn).await; + if let Some(registries) = registries.as_deref() { + write_cargo_registries_config(job_dir, registries).await?; } + + // Run outside `job_dir`; the registry configuration is carried over explicitly. + let cwd = HostCargoCwd::new("lockfile", registries.as_deref()).await?; + let gen_lockfile_cmd = build_generate_lockfile_command(cwd.path(), job_dir); let gen_lockfile_process = start_child_process(gen_lockfile_cmd, CARGO_PATH.as_str(), false).await?; handle_child( @@ -334,7 +452,6 @@ pub async fn generate_cargo_lockfile( async fn get_build_dir( job: &MiniPulledJob, - job_dir: &str, conn: &Connection, worker_name: &str, is_preview: bool, @@ -387,38 +504,29 @@ async fn get_build_dir( if run_sweep { // Also run sweep to make sure target isn't using too much disk - let mut sweep_cmd = Command::new(CARGO_PATH.as_str()); - let sweep_path = format!("{}/bin:{}", CARGO_HOME.as_str(), PATH_ENV.as_str()); - sweep_cmd - .current_dir(job_dir) - .env_clear() - .env("PATH", &sweep_path) - .env("CARGO_HOME", CARGO_HOME.as_str()) - .env("HOME", HOME_ENV.as_str()) - .env("CARGO_TARGET_DIR", &(bd.clone() + "/target")) - .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) - .args(["sweep", "--maxsize", SWEEP_MAXSIZE.as_str()]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - - #[cfg(windows)] - { - sweep_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); - sweep_cmd.env( - "TMP", - std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), - ); - sweep_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); - } - - let (job_id, conn, w_id, wk_name) = ( + let (job_id, conn, w_id, wk_name, build_dir) = ( job.id.clone(), conn.clone(), job.workspace_id.clone(), worker_name.to_owned(), + bd.clone(), ); tokio::spawn(async move { + // Run from a dedicated directory rather than the job directory. `cwd` is held + // for the whole sweep; dropping it removes the directory. + let cwd = match HostCargoCwd::new("sweep", None).await { + Ok(cwd) => cwd, + Err(e) => { + tracing::warn!( + workspace_id = %w_id, + job_id = %job_id, + "Failed to prepare working directory for `cargo sweep`. Rust cache may grow over time, cargo sweep is meant to clean up unused cache.\ne: {e}\n" + ); + return; + } + }; + let sweep_cmd = build_cargo_sweep_command(cwd.path(), &build_dir); if let Err(e) = match start_child_process(sweep_cmd, CARGO_PATH.as_str(), false).await { Ok(sweep_process) => { handle_child( @@ -467,7 +575,7 @@ pub async fn build_rust_crate( ensure_rust_runtime_dirs(); let bin_path = format!("{}/{hash}", *RUST_CACHE_DIR); - let build_dir = get_build_dir(job, job_dir, conn, worker_name, is_preview).await?; + let build_dir = get_build_dir(job, conn, worker_name, is_preview).await?; let child = if is_sandboxing_enabled() { let _ = write_file( @@ -851,3 +959,153 @@ pub async fn handle_rust_job( .await?; read_result(job_dir, None).await } + +#[cfg(test)] +mod host_cargo_cwd_tests { + use super::*; + use std::ffi::OsStr; + use std::path::Path; + + /// A plausible job directory: `{TMP}/windmill/{worker}/{job_id}`. + const JOB_DIR: &str = "/tmp/windmill/wk-default-xyz-AbCdE/01a12c99-6620-74b9-a4ca-189c60de272c"; + + fn args(cmd: &Command) -> Vec<String> { + cmd.as_std() + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect() + } + + fn env(cmd: &Command, key: &str) -> Option<String> { + cmd.as_std() + .get_envs() + .find(|(k, _)| *k == OsStr::new(key)) + .map(|(_, v)| v.unwrap_or(OsStr::new("")).to_string_lossy().into_owned()) + } + + /// The working directory is neither inside the job directory nor an ancestor of it. + fn assert_cwd_is_isolated_from_job_dir(cmd: &Command, job_dir: &str) { + let cwd = cmd + .as_std() + .get_current_dir() + .expect("host-side cargo must set an explicit working directory"); + let job_dir = Path::new(job_dir); + assert!( + cwd.ancestors().all(|a| a != job_dir), + "cwd {cwd:?} is inside the job dir {job_dir:?}" + ); + assert!( + job_dir.ancestors().all(|a| a != cwd), + "cwd {cwd:?} is an ancestor of the job dir {job_dir:?}" + ); + assert!( + cwd.starts_with(Path::new(HOST_CARGO_CWD_DIR.as_str())), + "cwd {cwd:?} is not one of the worker-owned dirs under {}", + *HOST_CARGO_CWD_DIR + ); + } + + #[test] + fn generate_lockfile_runs_outside_the_job_dir_and_names_the_manifest() { + let cwd = format!("{}/lockfile-deadbeef", *HOST_CARGO_CWD_DIR); + let cmd = build_generate_lockfile_command(&cwd, JOB_DIR); + + assert_eq!(cmd.as_std().get_current_dir(), Some(Path::new(&cwd))); + assert_cwd_is_isolated_from_job_dir(&cmd, JOB_DIR); + // Cargo writes Cargo.lock next to the manifest it is given, which is where + // `generate_cargo_lockfile` reads it back from. + assert_eq!( + args(&cmd), + vec![ + "generate-lockfile".to_string(), + "--manifest-path".to_string(), + format!("{JOB_DIR}/Cargo.toml"), + ] + ); + } + + #[test] + fn cargo_sweep_runs_outside_the_job_dir_and_still_targets_the_build_dir() { + let cwd = format!("{}/sweep-deadbeef", *HOST_CARGO_CWD_DIR); + let build_dir = format!("{}/build/acme@u.dev.script@dev", *RUST_CACHE_DIR); + let cmd = build_cargo_sweep_command(&cwd, &build_dir); + + assert_eq!(cmd.as_std().get_current_dir(), Some(Path::new(&cwd))); + assert_cwd_is_isolated_from_job_dir(&cmd, JOB_DIR); + assert_eq!( + args(&cmd), + vec![ + "sweep".to_string(), + "--maxsize".to_string(), + SWEEP_MAXSIZE.to_string(), + ] + ); + // `cargo sweep` prunes the target dir that `cargo metadata` reports, and + // CARGO_TARGET_DIR is what decides that -- not the cwd's manifest. + assert_eq!( + env(&cmd, "CARGO_TARGET_DIR").as_deref(), + Some(format!("{build_dir}/target").as_str()) + ); + } + + #[tokio::test] + async fn host_cargo_cwd_is_a_worker_owned_stub_crate_removed_on_drop() { + let registries = "[registries.acme]\nindex = \"sparse+https://acme.test/index/\"\n"; + let path = { + let cwd = HostCargoCwd::new("unittest", Some(registries)) + .await + .expect("could not create host cargo cwd"); + let path = cwd.path().to_string(); + + assert!( + path.starts_with(&format!("{}/unittest-", *HOST_CARGO_CWD_DIR)), + "unexpected host cargo cwd {path}" + ); + assert!( + !path.starts_with(&format!("{}/build/", *RUST_CACHE_DIR)), + "host cargo cwd {path} is under the build dirs" + ); + + // `cargo sweep` needs a manifest in its cwd to ask `cargo metadata` for the + // target dir; `[workspace]` keeps cargo from walking further up. + let manifest = std::fs::read_to_string(format!("{path}/Cargo.toml")) + .expect("stub Cargo.toml missing"); + assert!( + manifest.contains("[workspace]"), + "stub manifest is not its own workspace root: {manifest}" + ); + assert!( + manifest.contains("path = \"src/lib.rs\""), + "stub manifest does not point at its stub target: {manifest}" + ); + assert_eq!( + std::fs::read_to_string(format!("{path}/src/lib.rs")).expect("stub lib.rs missing"), + "" + ); + // The worker's own registry configuration has to follow the invocation out + // of the job dir, since cargo only reads it from the cwd and CARGO_HOME. + assert_eq!( + std::fs::read_to_string(format!("{path}/.cargo/config.toml")) + .expect("registry config missing"), + registries + ); + path + }; + + assert!( + !Path::new(&path).exists(), + "host cargo cwd {path} outlived its guard" + ); + } + + #[tokio::test] + async fn host_cargo_cwd_has_no_config_when_no_registries_are_set() { + let cwd = HostCargoCwd::new("unittest", None) + .await + .expect("could not create host cargo cwd"); + assert!( + !Path::new(&format!("{}/.cargo", cwd.path())).exists(), + "host cargo cwd has a .cargo dir although no registries are configured" + ); + } +} diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index 4048a3603c..beeac41a5c 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -1055,6 +1055,7 @@ enum NsjailProbeError { fn probe_nsjail(nsjail_path: &str) -> Result<std::process::Output, NsjailProbeError> { // A fresh private directory: the worker runs what this config says, as itself. let dir = std::env::temp_dir().join(format!("windmill-nsjail-probe-{}", uuid::Uuid::new_v4())); + #[cfg_attr(not(unix), allow(unused_mut))] let mut builder = std::fs::DirBuilder::new(); #[cfg(unix)] std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); @@ -1198,6 +1199,21 @@ pub fn nsjail_clone_newnet(no_network: bool) -> &'static str { } } +/// Whether job runs get the worker's proxy settings. Dependency installs always do: they read +/// [`PROXY_ENVS`] directly, so a group that turns the proxy off for jobs still installs through it. +pub fn passes_proxy_to_jobs() -> bool { + !WORKER_CONFIG.load().disable_job_proxy +} + +/// [`PROXY_ENVS`] as a job run sees them; see [`passes_proxy_to_jobs`]. +pub fn job_proxy_envs() -> Vec<(&'static str, String)> { + if passes_proxy_to_jobs() { + PROXY_ENVS.clone() + } else { + vec![] + } +} + /// [`get_proxy_envs_for_lang`] for a run step. A `no_network` one reaches no proxy, the /// OTel tracing proxy included, so it gets only the trace context. pub async fn get_run_proxy_envs( @@ -1371,12 +1387,12 @@ pub async fn get_proxy_envs_for_lang( { envs = get_otel_tracing_proxy_envs(job_id, w_id, conn).await?; } else { - envs = PROXY_ENVS.clone(); + envs = job_proxy_envs(); } #[cfg(not(all(feature = "private", feature = "enterprise")))] { let _ = (lang, job_kind, w_id, conn); - envs = PROXY_ENVS.clone(); + envs = job_proxy_envs(); } envs.extend(get_otel_context_envs(job_id)); Ok(envs) @@ -1398,7 +1414,7 @@ async fn get_otel_tracing_proxy_envs( This job's HTTP requests will not be traced."; tracing::warn!("{}", reason); append_logs(job_id, w_id, format!("\n[warning] {reason}\n"), conn).await; - return Ok(PROXY_ENVS.clone()); + return Ok(job_proxy_envs()); } }; let proxy_url = format!("http://127.0.0.1:{}", port); @@ -2874,14 +2890,6 @@ pub async fn run_worker( killpill_tx: KillpillSender, base_internal_url: &str, ) { - #[cfg(not(feature = "enterprise"))] - if is_sandboxing_enabled() { - tracing::warn!( - worker = %worker_name, hostname = %hostname, - "NSJAIL to sandbox process in untrusted environments is an enterprise feature but allowed to be used for testing purposes" - ); - } - // Force UNSHARE_PATH and NSJAIL_AVAILABLE initialization now for clear startup logging let _ = &*UNSHARE_PATH; let _ = &*NSJAIL_AVAILABLE; @@ -5439,8 +5447,8 @@ pub fn build_envs( hm }; - for (k, v) in PROXY_ENVS.iter() { - envs.insert(k.to_string(), v.clone()); + for (k, v) in job_proxy_envs() { + envs.insert(k.to_string(), v); } Ok(envs) @@ -6687,7 +6695,8 @@ pub async fn run_language_executor( occupancy_metrics, has_stream, )) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; return Ok(result); } diff --git a/backend/windmill-worker/src/worker_flow.rs b/backend/windmill-worker/src/worker_flow.rs index c188f8de58..e0c4026804 100644 --- a/backend/windmill-worker/src/worker_flow.rs +++ b/backend/windmill-worker/src/worker_flow.rs @@ -110,8 +110,8 @@ lazy_static::lazy_static! { /// Helper function to write itered data to separate table /// Returns None if data was written to separate table, Some(itered) if it should be stored in JSONB -async fn write_itered_to_db( - db: &DB, +async fn write_itered_to_db<'c>( + db: impl sqlx::PgExecutor<'c>, job_id: Uuid, itered: &Vec<Box<RawValue>>, ) -> error::Result<Option<Vec<Box<RawValue>>>> { @@ -328,6 +328,25 @@ fn get_stop_after_if_data(stop_after_if: Option<&StopAfterIf>) -> (bool, Option< return (false, None, false); } +/// Takes the caller's executor: under the status-update tx a pool read would wait on a second +/// connection, which a burst of completions holding every one never frees. +async fn fetch_flow_args<'c>( + db: impl sqlx::PgExecutor<'c>, + flow: Uuid, +) -> Result<HashMap<String, Box<RawValue>>, sqlx::Error> { + let args = sqlx::query_scalar!( + r#" + SELECT args AS "args: Json<HashMap<String, Box<RawValue>>>" + FROM v2_job + WHERE id = $1 + "#, + flow + ) + .fetch_one(db) + .await; + args.map(|flow_args| flow_args.map(|flow_args| flow_args.0).unwrap_or_default()) +} + async fn get_id_ctx_for_expr<'c>( expr: &str, flow: uuid::Uuid, @@ -633,22 +652,7 @@ pub async fn update_flow_status_after_job_completion_internal( } }; - let args = Arc::pin(Lazy::new(async move { - let args = sqlx::query_scalar!( - r#" - SELECT args AS "args: Json<HashMap<String, Box<RawValue>>>" - FROM v2_job - WHERE id = $1 - "#, - flow - ) - .fetch_one(db) - .await; - let args = - args.map(|flow_args| flow_args.map(|flow_args| flow_args.0).unwrap_or_default()); - - args - })); + let args = Arc::pin(Lazy::new(fetch_flow_args(db, flow))); let from_result_to_args = |args: &Result<HashMap<String, Box<RawValue>>, sqlx::Error>| { let args = args @@ -992,7 +996,7 @@ pub async fn update_flow_status_after_job_completion_internal( .as_ref() .and_then(|x| x.stop_after_all_iters_if.as_ref()) { - let args = from_result_to_args(args.as_ref().await.get_ref())?; + let args = from_result_to_args(&fetch_flow_args(&mut *tx, flow).await)?; // Isolate the reads in a savepoint on the same connection: the // caller below swallows our error and keeps using `tx`, so a DB // read failure must not leave the outer transaction aborted (that @@ -1227,7 +1231,7 @@ pub async fn update_flow_status_after_job_completion_internal( .as_ref() .and_then(|x| x.stop_after_all_iters_if.as_ref()) { - let args = from_result_to_args(args.as_ref().await.get_ref())?; + let args = from_result_to_args(&fetch_flow_args(&mut *tx, flow).await)?; // See the matching savepoint comment above: isolate the reads so a // DB read failure (whose error the caller swallows) cannot abort @@ -1329,7 +1333,7 @@ pub async fn update_flow_status_after_job_completion_internal( .unwrap_or_default(); tracing::info!("update flow status on retry: {retry:#?} "); - let args = from_result_to_args(args.as_ref().await.get_ref())?; + let args = from_result_to_args(&fetch_flow_args(&mut *tx, flow).await)?; evaluate_retry( &retry, @@ -4780,7 +4784,8 @@ async fn push_next_flow_job( { // A step with its own on-behalf-of carries a cached dispatch address, up to one // notify poll stale; accepted, see `get_email_from_permissioned_as`. - let is_super_admin = windmill_common::auth::is_super_admin_email(db, email).await?; + let is_super_admin = + windmill_common::auth::is_super_admin_email(&mut *tx, email).await?; check_tag_written_as_available_for_push( db, &flow_job.workspace_id, @@ -5046,7 +5051,7 @@ async fn push_next_flow_job( // Conditionally write itered to separate table if all workers support it // Returns None if written to table, Some(itered) if should be in JSONB - let itered_for_status = write_itered_to_db(db, flow_job.id, &itered).await?; + let itered_for_status = write_itered_to_db(&mut *tx, flow_job.id, &itered).await?; FlowStatusModule::InProgress { job: uuid, diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 61315e1683..41d2fe87c0 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.841.0"; +export const VERSION = "v1.849.0"; 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 006d5407d8..2106d35bee 100644 --- a/chat-sdk/README.md +++ b/chat-sdk/README.md @@ -148,6 +148,45 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) - **`wmill app dev`**: there is no viewer session on the dev server, so pass `baseUrl`, `workspace` and `token` explicitly during development. +### A saved agent, through an agent runnable + +To chat with a saved AI agent (an `ai_agent` resource), give the app an **agent +runnable**: a path runnable of type `agent` naming the agent, picked under "AI agents" +in the editor, or in `raw_app.yaml`: + +```yaml +runnables: + chat: + type: agent + path: f/support/agent +``` + +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. +Name the runnable and pass the app's generated `wmill.ts`, which the chat goes through: + +```tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +``` + +`runnable` is checked against the runnables `wmill.ts` declares, and names the local +history, so two agent runnables in one app keep separate conversations. Going through +`wmill.ts` is what makes the same code work in a deployed app and under `wmill app dev`. + +`createChat` and the assistant-ui runtime take the same options; the AI SDK transport +does not. The runnable takes `user_message` and `memory_id`, the conversation id, which +the agent's memory is keyed by, so it remembers earlier turns (called from `wmill.ts` +without `memory_id`, it is a single run with no conversation). The agent needs managed +memory: one whose memory is off takes `previous_messages` instead, the history you keep. A signed-in viewer's turns +are filed under them, so nobody else can continue their conversations; an anonymous +visitor's are kept apart per app. The chat makes no request of its own: history is +`'local'` (the app's own storage), `stop()` stops following without cancelling the turn, +a message sent while it still runs is refused with `TurnRunningError`, and attachments +are refused. + ## Any framework `createChat` returns a store: `subscribe` calls the listener immediately and on every @@ -178,7 +217,7 @@ await chat.sendMessage('Hello') | Option | | |---|---| -| `flowPath` | Path of the deployed flow, e.g. `f/support/assistant`. Required. | +| `flowPath` | Path of the deployed flow, e.g. `f/support/assistant`. Required unless `follow` is set. | | `baseUrl` | The Windmill origin. Detected inside a raw app. | | `workspace` | Detected inside a raw app. | | `token` | A token, or a function returning one (called before every request, so it can fetch a short-lived token from your backend). Omit it inside a raw app. | @@ -190,6 +229,8 @@ await chat.sendMessage('Hello') | `pollDelayMs` | How often, in ms, the server polls a running turn for the stream (Enterprise; 50 at the fastest, other servers ignore it). Unset, the server relaxes from 100 ms to 3 s over a long turn; set it when tokens must keep flowing at that pace. | | `onFinish`, `onError` | Called when a turn has its answer, or could not run at all. | | `run` | Runs the flow for a turn yourself and returns the job id, instead of the deployed flow at `flowPath` (Windmill's editor chats with an undeployed flow through a preview run this way). Pass `memory_id` = the conversation id. | +| `follow` | With `run`: follows the job through your own client, calling `onStream` with each chunk of its result stream and resolving with its result. The chat then makes no request of its own; `runnable` sets both for a raw app's agent runnable, see [A saved agent](#a-saved-agent-through-an-agent-runnable). | +| `runnable`, `wmill` | In a raw app, chat through the agent runnable of that name, going through the app's generated module (`import * as wmill from './wmill'`). Replaces `flowPath`, `run` and `follow`. | ## State @@ -294,7 +335,8 @@ That store is keyed by the **Windmill user**, so it fits a viewer session or a t issued per user. With one token shared by every visitor of a site, all visitors would see each other's conversations. For that setup use `history: 'local'` (the default with an explicit `token`): the conversation list and messages stay in the browser's -`localStorage`, per Windmill instance, workspace and flow. `'none'` keeps nothing +`localStorage`, per Windmill instance, workspace and flow, and the chat starts with that +list in `state.conversations`, without a `loadConversations()` call. `'none'` keeps nothing beyond the page. When the default `'server'` mode turns out unreadable (a token or sandboxed app @@ -333,7 +375,8 @@ custom integrations. When asked to add a chat over a Windmill flow: the flow must be deployed with chat mode on. Pick the entry point from the table at the top (`useChat` → `@windmill-labs/chat-sdk/ai-sdk`, assistant-ui → `@windmill-labs/chat-sdk/assistant-ui`, otherwise `@windmill-labs/chat-sdk/react`). Inside a -Windmill raw app pass only `flowPath`. Elsewhere pass `baseUrl`, `workspace` and a +Windmill raw app pass only `flowPath`; for a saved agent, use an `agent` runnable and pass +`{ wmill, runnable }`. Elsewhere pass `baseUrl`, `workspace` and a `token`; for a public page use a token scoped to `jobs:run:flows:<flowPath>` and leave `history` at its default. Render `role`, `content`, `pending`, `success` and `tool.status`; never build the SSE handling yourself. diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 93d3e00348..61ed2382a8 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.841.0", + "version": "1.849.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.841.0", + "version": "1.849.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index ca4b73df45..992d52b207 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.841.0", + "version": "1.849.0", "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/assistant-ui.ts b/chat-sdk/src/assistant-ui.ts index b9a76db679..04ab23793e 100644 --- a/chat-sdk/src/assistant-ui.ts +++ b/chat-sdk/src/assistant-ui.ts @@ -7,7 +7,7 @@ import { } from '@assistant-ui/react' import { useEffect, useMemo } from 'react' import { useWindmillChat } from './react' -import type { ChatMessage, ChatOptions } from './types' +import type { ChatMessage, RawAppWmill, TypedChatOptions } from './types' import { parseJsonOr } from './utils' /** One assistant turn: the assistant and tool rows between two user messages. */ @@ -17,7 +17,7 @@ export interface WindmillTurn { messages: ChatMessage[] } -export interface WindmillRuntimeOptions extends ChatOptions { +export type WindmillRuntimeOptions<W extends RawAppWmill = RawAppWmill> = TypedChatOptions<W> & { /** Load the conversation list on mount so `ThreadListPrimitive` has something to show. Default true. */ threadList?: boolean } @@ -27,7 +27,7 @@ export interface WindmillRuntimeOptions extends ChatOptions { * Conversations become threads, so the thread list primitives switch, create and * delete Windmill conversations. */ -export function useWindmillRuntime(options: WindmillRuntimeOptions): AssistantRuntime { +export function useWindmillRuntime<W extends RawAppWmill>(options: WindmillRuntimeOptions<W>): AssistantRuntime { const chat = useWindmillChat(options) const turns = useMemo(() => groupTurns(chat.messages), [chat.messages]) const withThreadList = options.threadList !== false diff --git a/chat-sdk/src/attachments.ts b/chat-sdk/src/attachments.ts index ac5e71c7d3..a11b0106ba 100644 --- a/chat-sdk/src/attachments.ts +++ b/chat-sdk/src/attachments.ts @@ -88,10 +88,9 @@ export async function uploadAttachments( attachments.map(async (attachment, index) => { try { const blob = attachmentBlob(attachment) - const filename = storedAttachmentName( - attachment.name || `attachment-${index + 1}`, - blob.type - ) + // The last segment only: the name may come from whoever sent the file. + const name = attachment.name?.split(/[\\/]/).pop()?.replace(/^\.+$/, '') + const filename = storedAttachmentName(name || `attachment-${index + 1}`, blob.type) const { file_key } = await api.uploadFile(`${prefix}/${index}/${filename}`, blob, { contentType: blob.type, signal: batch.signal diff --git a/chat-sdk/src/chat.ts b/chat-sdk/src/chat.ts index dfef438f33..2d48d383a0 100644 --- a/chat-sdk/src/chat.ts +++ b/chat-sdk/src/chat.ts @@ -11,11 +11,13 @@ import { resolveConfig, type ResolvedConfig } from './config' import { followJob } from './follow' import { createLocalHistory, type LocalHistory } from './history' import { uploadAttachments } from './attachments' -import type { AgentStreamEvent } from './stream' +import { createStreamEventParser, type AgentStreamEvent } from './stream' import type { Chat, ChatMessage, ChatOptions, + RawAppWmill, + TypedChatOptions, ChatState, Conversation, SendMessageOptions, @@ -62,7 +64,7 @@ interface Turn { streamedText: boolean } -export function createChat(options: ChatOptions): Chat { +export function createChat<W extends RawAppWmill>(options: TypedChatOptions<W>): Chat { return new ChatImpl(options) } @@ -102,7 +104,9 @@ class ChatImpl implements Chat { messages: [], status: 'idle', error: undefined, - conversations: [], + // Browser history is read synchronously, so a chat starts with its list as server history + // cannot: an app that never calls `loadConversations` still shows its conversations. + conversations: this.#config.history === 'local' ? this.#local.listConversations() : [], history: this.#config.history, loadingMessages: false, hasMoreMessages: false @@ -134,6 +138,9 @@ class ChatImpl implements Chat { if (attachments.length > 0 && !attachmentsInput) { throw new Error('windmill-chat: attachments need `attachmentsInput`, the flow input that takes them') } + if (attachments.length > 0 && this.#config.follow) { + throw new Error('windmill-chat: attachments upload with the SDK\'s own requests, which `follow` replaces') + } if (attachmentsInput && !attachmentsInput.multiple && attachments.length > 1) { // Uploading all of them would run with the first and leave the rest stranded in storage. throw new Error(`windmill-chat: \`${attachmentsInput.name}\` holds one file; got ${attachments.length}`) @@ -338,7 +345,7 @@ class ChatImpl implements Chat { this.#set({ messages: finalized(this.#state.messages), status: 'idle' }) this.#persistLocal() } - if (turn.jobId) { + if (turn.jobId && !this.#config.follow) { // Needs `jobs:write` on a token; the stream is closed either way. await this.#api.cancelJob(turn.jobId).catch(() => {}) } @@ -577,6 +584,27 @@ class ChatImpl implements Chat { async #follow(turn: Turn, onStreamStart: () => void): Promise<unknown> { let started = false + const { follow } = this.#config + if (follow) { + const { signal } = turn.controller + const parser = createStreamEventParser() + const onStream = (chunk: string) => { + if (signal.aborted) return + if (!started) { + started = true + onStreamStart() + } + this.#applyEvents(turn, parser.push(chunk)) + } + // A caller's follow may not honor the signal; the turn stops waiting on it either way. + const aborted = new Promise<never>((_, reject) => { + if (signal.aborted) reject(abortError()) + signal.addEventListener('abort', () => reject(abortError()), { once: true }) + }) + const result = await Promise.race([follow(turn.jobId!, onStream, { signal }), aborted]) + this.#applyEvents(turn, parser.flush()) + return result + } for await (const event of followJob(this.#api, turn.jobId!, { signal: turn.controller.signal })) { if (event.type === 'completed') { if (event.streamLost) this.#dropCutRound(turn) @@ -722,8 +750,9 @@ class ChatImpl implements Chat { let messages = this.#state.messages let failed = false if (isErrorResult(result)) { - // The envelope is also a legitimate result shape; the job's own status decides. - failed = await this.#api + // The envelope is also a legitimate result shape; the job's own status decides, when it + // can be read. + failed = this.#config.follow ? true : await this.#api .getCompletedResult(turn.jobId!, turn.controller.signal) .then((r) => r.success === false) .catch(() => true) diff --git a/chat-sdk/src/config.ts b/chat-sdk/src/config.ts index 1903149d58..98cf97f2b2 100644 --- a/chat-sdk/src/config.ts +++ b/chat-sdk/src/config.ts @@ -1,4 +1,5 @@ import type { ChatOptions, FetchLike, HistoryMode, StorageLike, TokenSource } from './types' +import { rawAppRunnable } from './runnable' export interface ResolvedConfig { flowPath: string @@ -15,6 +16,7 @@ export interface ResolvedConfig { pageSize: number pollDelayMs: number | undefined run: ChatOptions['run'] + follow: ChatOptions['follow'] onFinish: ChatOptions['onFinish'] onError: ChatOptions['onError'] } @@ -51,13 +53,31 @@ export function detectRawApp(): RawAppContext | undefined { } export function resolveConfig(options: ChatOptions): ResolvedConfig { - if (!options.flowPath) throw new Error('windmill-chat: flowPath is required') + if (options.runnable !== undefined) { + if (!options.wmill) throw new Error('windmill-chat: `runnable` needs `wmill`, the app\'s generated module') + if (options.flowPath || options.run || options.follow) { + throw new Error('windmill-chat: `runnable` replaces `flowPath`, `run` and `follow`') + } + // Unsandboxed apps share their origin's storage, so the app's path keeps their histories apart. + const app = (globalThis as { ctx?: { path?: unknown } }).ctx?.path + options = { + ...options, + ...rawAppRunnable(options.wmill.backendAsync[options.runnable], options.wmill.streamJob), + flowPath: `runnable:${typeof app === 'string' ? `${app}:` : ''}${options.runnable}` + } + } + const follow = options.follow + if (follow && !options.run) throw new Error('windmill-chat: `follow` needs `run`, which starts the job it follows') + if (follow && options.history === 'server') { + throw new Error('windmill-chat: server history is read with the SDK\'s own requests, which `follow` replaces') + } + if (!options.flowPath && !follow) throw new Error('windmill-chat: flowPath is required') const explicitToken = options.token !== undefined const detected = options.baseUrl && options.workspace && explicitToken ? undefined : detectRawApp() const baseUrl = options.baseUrl ?? detected?.baseUrl const workspace = options.workspace ?? detected?.workspace - if (!baseUrl || !workspace) { + if ((!baseUrl || !workspace) && !follow) { throw new Error( 'windmill-chat: pass baseUrl and workspace. They are only detected inside a raw app: an unsandboxed one on the Windmill origin, or a sandboxed one whose policy declares frontend SDK scopes.' ) @@ -66,11 +86,11 @@ export function resolveConfig(options: ChatOptions): ResolvedConfig { const token = options.token ?? (options.baseUrl === undefined || options.baseUrl === detected?.baseUrl ? detected?.token : undefined) return { - flowPath: options.flowPath, - baseUrl, - workspace, + flowPath: options.flowPath ?? '', + baseUrl: baseUrl ?? '', + workspace: workspace ?? '', token, - history: options.history ?? (explicitToken ? 'local' : 'server'), + history: options.history ?? (explicitToken || follow ? 'local' : 'server'), historyExplicit: options.history !== undefined, inputs: options.inputs ?? {}, fetch: options.fetch, @@ -79,6 +99,7 @@ export function resolveConfig(options: ChatOptions): ResolvedConfig { pageSize: options.pageSize ?? 50, pollDelayMs: options.pollDelayMs, run: options.run, + follow, onFinish: options.onFinish, onError: options.onError } diff --git a/chat-sdk/src/index.ts b/chat-sdk/src/index.ts index a050edce37..d05a5ab217 100644 --- a/chat-sdk/src/index.ts +++ b/chat-sdk/src/index.ts @@ -31,6 +31,8 @@ export type { Conversation, FetchLike, HistoryMode, + RawAppWmill, + TypedChatOptions, SendMessageOptions, StorageLike, TokenSource, diff --git a/chat-sdk/src/react.ts b/chat-sdk/src/react.ts index c32324ee18..4159008ce7 100644 --- a/chat-sdk/src/react.ts +++ b/chat-sdk/src/react.ts @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react' import { createChat } from './chat' -import type { Chat, ChatOptions, ChatState } from './types' +import type { Chat, ChatOptions, ChatState, RawAppWmill, TypedChatOptions } from './types' export type UseWindmillChat = ChatState & Pick< @@ -19,22 +19,23 @@ export type UseWindmillChat = ChatState & /** * A chat on a chat-mode flow. The chat is created once per `flowPath`, `baseUrl`, - * `workspace`, `history`, `storageKey`, credential and presence of `run`, and + * `workspace`, `history`, `storageKey`, credential and presence of `run` and `follow`, and * destroyed on unmount. A credential change is a new user, whose chat must not * carry the previous one's state: a different token string, or a switch between no * token, a token string and a token function, all recreate it. A token function is * read through a ref on every call, so a new closure per render changes what the * next call runs and nothing else; pass a `storageKey` per user when local history - * must not be shared. `run`, the callbacks and `inputs` are read the same way: the + * must not be shared. `run`, `follow`, the callbacks and `inputs` are read the same way: the * latest render's values go with the next message. */ -export function useWindmillChat(options: ChatOptions): UseWindmillChat { - const latest = useRef(options) +export function useWindmillChat<W extends RawAppWmill>(options: TypedChatOptions<W>): UseWindmillChat { + const latest = useRef<ChatOptions>(options) latest.current = options const credential = typeof options.token === 'function' ? 'fn' : typeof options.token === 'string' ? `str:${options.token}` : 'none' // A custom runner replaces the deployed flow call, so its presence is part of what the chat is. const customRun = options.run !== undefined + const customFollow = options.follow !== undefined const chat = useMemo( () => createChat({ @@ -49,11 +50,14 @@ export function useWindmillChat(options: ChatOptions): UseWindmillChat { } : options.token, run: customRun ? (args, turn) => (latest.current.run ?? options.run!)(args, turn) : undefined, + follow: customFollow + ? (jobId, onStream, turn) => (latest.current.follow ?? options.follow!)(jobId, onStream, turn) + : undefined, onFinish: (turn) => latest.current.onFinish?.(turn), onError: (error, turn) => latest.current.onError?.(error, turn) }), // eslint-disable-next-line react-hooks/exhaustive-deps - [options.flowPath, options.baseUrl, options.workspace, options.history, options.storageKey, credential, customRun] + [options.flowPath, options.runnable, options.wmill, options.baseUrl, options.workspace, options.history, options.storageKey, credential, customRun, customFollow] ) useEffect(() => () => chat.destroy(), [chat]) const state = useSyncExternalStore(chat.subscribe, chat.getState, chat.getState) diff --git a/chat-sdk/src/runnable.ts b/chat-sdk/src/runnable.ts new file mode 100644 index 0000000000..08ddf592e7 --- /dev/null +++ b/chat-sdk/src/runnable.ts @@ -0,0 +1,29 @@ +import { turnRunningError } from './api' +import type { ChatOptions } from './types' + +/** + * `run` and `follow` over a raw app's agent runnable (a path runnable of type `agent`, naming + * a saved AI agent), behind the `runnable` option. `memory_id` is the conversation id, the + * agent's memory key. + */ +export function rawAppRunnable( + // The generated signature is the runnable's own. + start: (args: any) => Promise<string>, + streamJob: (jobId: string, onUpdate?: (update: { new_result_stream?: string }) => void) => Promise<unknown> +): Required<Pick<ChatOptions, 'run' | 'follow'>> { + return { + run: async (args, { conversationId }) => { + try { + return String(await start({ ...args, memory_id: conversationId })) + } catch (e) { + // The host relays the server's refusal as the error's text, possibly behind a stack. + const text = e instanceof Error ? e.message : String(e) + throw turnRunningError(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)) ?? e + } + }, + follow: (jobId, onStream) => + streamJob(jobId, (update) => { + if (update.new_result_stream) onStream(update.new_result_stream) + }) + } +} diff --git a/chat-sdk/src/types.ts b/chat-sdk/src/types.ts index 180238e50c..ad9f30cbfb 100644 --- a/chat-sdk/src/types.ts +++ b/chat-sdk/src/types.ts @@ -88,9 +88,33 @@ export type StorageLike = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response> +/** A raw app's generated `wmill.ts`, as far as a chat uses it. */ +export interface RawAppWmill { + backendAsync: Record<string, (args: any) => Promise<string>> + streamJob: (jobId: string, onUpdate?: (update: { new_result_stream?: string }) => void) => Promise<unknown> +} + +/** `ChatOptions` whose `runnable` must name one of `wmill`'s runnables. */ +export type TypedChatOptions<W extends RawAppWmill> = ChatOptions & { + wmill?: W + runnable?: keyof W['backendAsync'] & string +} + export interface ChatOptions { - /** Path of a deployed flow with chat mode enabled, e.g. `f/support/assistant`. */ - flowPath: string + /** + * Path of a deployed flow with chat mode enabled, e.g. `f/support/assistant`. Required + * unless `runnable` or `follow` is set, where it only names the local history. + */ + flowPath?: string + /** + * In a raw app, chat through its agent runnable of this name instead of a flow: + * `{ wmill, runnable: 'chat' }`. Each turn runs as the app, so a sandboxed app needs no + * frontend SDK scope and its viewers no access to the agent; the chat follows it as + * with `follow`. It also names the local history, so each runnable keeps its own. + */ + runnable?: string + /** The app's generated module, `import * as wmill from './wmill'`, which `runnable` goes through. */ + wmill?: RawAppWmill /** Windmill origin, e.g. `https://app.windmill.dev`. Detected inside a raw app. */ baseUrl?: string /** Detected inside a raw app. */ @@ -128,6 +152,15 @@ export interface ChatOptions { * Windmill's own editor uses this to chat with an undeployed flow through a preview run. */ run?: (args: Record<string, unknown>, turn: { conversationId: string; signal: AbortSignal }) => Promise<string> + /** + * Follows the job `run` returned through your own client instead of the SDK's requests: + * call `onStream` with each chunk of the job's result stream and resolve with its result. + * With it the chat makes no request of its own, so it needs no credential, `baseUrl` or + * `workspace`, and in exchange history is `local` (or `none`), `stop()` stops following + * without cancelling the job, and attachments are refused. `runnable` sets both for a raw + * app's agent runnable. + */ + follow?: (jobId: string, onStream: (chunk: string) => void, turn: { signal: AbortSignal }) => Promise<unknown> /** Called once a turn has its answer (a failed flow included: its error is the answer). */ onFinish?: (turn: { conversationId: string; jobId?: string; messages: ChatMessage[] }) => void /** Called when a turn could not run or be followed; `state.error` holds the same error. */ diff --git a/chat-sdk/test/chat.test.ts b/chat-sdk/test/chat.test.ts index 3845c91ac7..6c88af5a36 100644 --- a/chat-sdk/test/chat.test.ts +++ b/chat-sdk/test/chat.test.ts @@ -1829,6 +1829,7 @@ describe('createChat with server history', () => { await chat.selectConversation(older) await new Promise((r) => setTimeout(r, 400)) const again = createChat(options({ token: 'tok', storage }, fetch)) + expect(again.getState().conversations.map((c) => c.id)).toEqual([newer, older]) expect((await again.loadConversations()).map((c) => c.id)).toEqual([newer, older]) }) diff --git a/chat-sdk/test/runnable.test.ts b/chat-sdk/test/runnable.test.ts new file mode 100644 index 0000000000..4dcaa60b84 --- /dev/null +++ b/chat-sdk/test/runnable.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from 'bun:test' +import { TurnRunningError } from '../src/api' +import { createChat } from '../src/chat' +import { memoryStorage, ndjson } from './support' + +describe('raw app agent runnable', () => { + test('chats through the runnable without a request of its own', async () => { + const calls: unknown[] = [] + let refuse = false + const start = async (args: unknown) => { + // As the host relays a 409: the server's body behind the error's stack. + if (refuse) { + const body = { error: 'still answering', running_turn: { job_id: 'job-1', user_seq: 1 } } + throw new Error(`Error: ${JSON.stringify(body)}\n at x`) + } + calls.push(args) + return `job-${calls.length}` + } + const streamJob = async (jobId: string, onUpdate?: (u: { new_result_stream?: string }) => void) => { + const stream = ndjson({ type: 'token_delta', content: 'answer ' }, { type: 'token_delta', content: jobId }) + onUpdate?.({ new_result_stream: stream.slice(0, 10) }) + onUpdate?.({ new_result_stream: stream.slice(10) }) + if (jobId === 'job-3') return { error: { name: 'Error', message: 'agent failed' } } + return { output: `answer ${jobId}`, messages: [] } + } + const storage = memoryStorage() + const wmill = { backendAsync: { chat: start, other: start }, streamJob } + const chat = createChat({ + wmill, + runnable: 'chat', + storage, + fetch: () => Promise.reject(new Error('no request expected')) + }) + expect(chat.getState().history).toBe('local') + await chat.sendMessage('hi') + await chat.sendMessage('again') + const conversationId = chat.getState().conversationId + expect(calls).toEqual([ + { user_message: 'hi', memory_id: conversationId }, + { user_message: 'again', memory_id: conversationId } + ]) + expect(chat.getState().messages.map((m) => m.content)).toEqual(['hi', 'answer job-1', 'again', 'answer job-2']) + + await chat.sendMessage('third') + const messages = chat.getState().messages + const last = messages[messages.length - 1] + expect([last.content, last.success]).toEqual(['agent failed', false]) + + // A turn still running elsewhere takes the message back rather than failing a turn. + refuse = true + await expect(chat.sendMessage('fourth')).rejects.toBeInstanceOf(TurnRunningError) + expect(chat.getState().messages).toEqual(messages) + + // Each runnable keeps its own history: another agent never sees this conversation. + expect(createChat({ wmill, runnable: 'chat', storage }).getState().conversations).toHaveLength(1) + expect(createChat({ wmill, runnable: 'other', storage }).getState().conversations).toEqual([]) + // Nor does the same runnable name in another app, whose path the host puts in `ctx`. + const g = globalThis as { ctx?: unknown } + g.ctx = { path: 'u/admin/other_app' } + try { + expect(createChat({ wmill, runnable: 'chat', storage }).getState().conversations).toEqual([]) + } finally { + delete g.ctx + } + // @ts-expect-error a name the app's module does not declare + createChat({ wmill, runnable: 'missing', storage }) + }) +}) diff --git a/cli/src/commands/app/dev.ts b/cli/src/commands/app/dev.ts index fbeba2914f..eb9bb055d6 100644 --- a/cli/src/commands/app/dev.ts +++ b/cli/src/commands/app/dev.ts @@ -1711,6 +1711,49 @@ export function buildWmillTs( return windmillUtils.genWmillTs(runnables); } +/** + * The inputs of an agent runnable, after the agent's memory (see the frontend's + * `agentRunnableSchema`): `memory_id` when it keeps managed memory, `previous_messages` when it + * is off, and neither for an older `manual` setting. + */ +function agentRunnableSchema(memory: any) { + const managed = + memory?.kind === "compaction" || + ((memory?.kind === "window" || memory?.kind === "auto") && + Boolean(memory.context_length)); + const legacy = memory?.kind === "manual"; + const history: Record<string, any> = {}; + if (managed) { + history.memory_id = { + type: "string", + description: + "The conversation the message belongs to: reuse it to continue one, or omit it for a single run", + }; + } else if (!legacy) { + history.previous_messages = { + type: "array", + description: + "The history to answer from, as chat messages: this agent keeps no memory", + items: { type: "object" }, + }; + } + return { + $schema: "https://json-schema.org/draft/2020-12/schema", + type: "object", + properties: { + user_message: { type: "string", description: "The message to answer" }, + ...history, + user_attachments: { + type: "array", + description: "Files the message carries, as object storage references", + items: { type: "object", resourceType: "s3object" }, + }, + }, + required: ["user_message"], + order: ["user_message", ...Object.keys(history), "user_attachments"], + }; +} + /** * Fetches schemas from the Windmill API for path-based runnables (script / flow). * Returns a map of runnableId -> schema. Path-based runnables don't store their @@ -1741,6 +1784,12 @@ export async function fetchPathRunnableSchemas( path: runnable.path, }); if (script.schema) schemas[runnableId] = script.schema; + } else if (runnable.runType === "agent") { + const agent = await wmill.getResource({ + workspace: workspaceId, + path: runnable.path, + }); + schemas[runnableId] = agentRunnableSchema((agent.value as any)?.memory); } else if (runnable.runType === "flow") { const flow = await wmill.getFlowByPath({ workspace: workspaceId, @@ -1771,7 +1820,8 @@ function convertRunnablesToApiFormat(runnables: Record<string, any>): void { if ( runnable?.type === "script" || runnable?.type === "hubscript" || - runnable?.type === "flow" + runnable?.type === "flow" || + runnable?.type === "agent" ) { // Convert from file format to API format // { type: "script" } -> { type: "path", runType: "script" } @@ -2029,9 +2079,11 @@ async function streamJobWithSSE( ws: WebSocket, baseUrl: string, token: string, + streamOffset?: number, ): Promise<void> { const sseUrl = - `${baseUrl}api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?fast=true`; + `${baseUrl}api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?fast=true` + + (streamOffset !== undefined ? `&stream_offset=${streamOffset}` : ""); const extraHeaders = getHeaders(); const response = await fetch(sseUrl, { @@ -2057,6 +2109,7 @@ async function streamJobWithSSE( const decoder = new TextDecoder(); let buffer = ""; + let lastOffset = streamOffset; try { while (true) { @@ -2076,8 +2129,17 @@ async function streamJobWithSSE( if (type === "ping" || type === "timeout") { if (type === "timeout") { + // The server ends every stream after a while; the job goes on, so it is resumed. reader.cancel(); - return; + return streamJobWithSSE( + workspace, + jobId, + reqId, + ws, + baseUrl, + token, + lastOffset, + ); } continue; } @@ -2108,6 +2170,9 @@ async function streamJobWithSSE( return; } + if (update.stream_offset !== undefined) { + lastOffset = update.stream_offset; + } // Send stream update if there's new stream data if (update.new_result_stream !== undefined) { ws.send( diff --git a/cli/src/commands/app/metadata.ts b/cli/src/commands/app/metadata.ts index 1981949404..5f16e84220 100644 --- a/cli/src/commands/app/metadata.ts +++ b/cli/src/commands/app/metadata.ts @@ -14,7 +14,7 @@ export type Runnable = } | { type: "path" | "runnableByPath"; - runType: "script" | "hubscript" | "flow"; + runType: "script" | "hubscript" | "flow" | "agent"; path: string; fields?: Record<string, any>; }; diff --git a/cli/src/commands/app/raw_apps.ts b/cli/src/commands/app/raw_apps.ts index ec526f2af2..570b03f949 100644 --- a/cli/src/commands/app/raw_apps.ts +++ b/cli/src/commands/app/raw_apps.ts @@ -230,7 +230,8 @@ export async function loadRunnablesFromBackend( } else if ( runnable?.type === "script" || runnable?.type === "hubscript" || - runnable?.type === "flow" + runnable?.type === "flow" || + runnable?.type === "agent" ) { // For path-based runnables, convert from file format to API format // { type: "script" } -> { type: "path", runType: "script" } diff --git a/cli/src/commands/trigger/trigger.ts b/cli/src/commands/trigger/trigger.ts index 4e6b0eeb16..b46897b9b5 100644 --- a/cli/src/commands/trigger/trigger.ts +++ b/cli/src/commands/trigger/trigger.ts @@ -281,6 +281,8 @@ export async function pushNativeTrigger( is_flow: localTrigger.is_flow, service_config: localTrigger.service_config, summary: localTrigger.summary, + // Used on create only; an update keeps the connection the webhook was registered under. + connection_path: localTrigger.connection_path, }; if (remoteTrigger) { diff --git a/cli/src/commands/variable/variable.ts b/cli/src/commands/variable/variable.ts index 88ad108a1a..c79630d1de 100644 --- a/cli/src/commands/variable/variable.ts +++ b/cli/src/commands/variable/variable.ts @@ -98,6 +98,7 @@ export interface VariableFile { description: string; account?: number; is_oauth?: boolean; + value_valid_until?: string; extra_perms?: Record<string, boolean>; } @@ -162,7 +163,14 @@ export async function pushVariable( const { extra_perms: localPerms, ...localVariableBody } = localVariable; if (variable) { - if (isSuperset(localVariableBody, variable)) { + // An expiry removed from the file is sent as `null` (absent keeps the stored date), and + // `isSuperset` cannot see a removed key, so the clear is detected here. + const clearsValueValidUntil = + localVariableBody.value_valid_until === undefined && + variable.value_valid_until !== undefined && + variable.value_valid_until !== null; + + if (!clearsValueValidUntil && isSuperset(localVariableBody, variable)) { log.debug(`Variable ${remotePath} is up-to-date`); } else { log.debug(`Variable ${remotePath} is not up-to-date, updating`); @@ -188,6 +196,7 @@ export async function pushVariable( ...localVariableBody, is_secret: nextIsSecret, ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}), + ...(clearsValueValidUntil ? { value_valid_until: null } : {}), }, }); } diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index d65b343bfe..bf083042d9 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.841.0"; +export const VERSION = "1.849.0"; diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index 502d0037bb..94875d2659 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -34,12 +34,21 @@ export interface SuccessHandlerConfig { extra_args?: any; } +export interface VariableExpirationHandlerConfig { + path?: string; + extra_args?: any; + muted_on_user_path?: boolean; + notify_before_secs?: number; + remind_every_secs?: number; +} + export interface SimplifiedSettings { // Grouped format (current). Explicit `null` on error_handler / success_handler // signals "clear the remote value"; `undefined` means "not managed by git". auto_invite?: AutoInviteConfig; error_handler?: ErrorHandlerConfig | null; success_handler?: SuccessHandlerConfig | null; + variable_expiration_handler?: VariableExpirationHandlerConfig | null; // Other fields webhook?: string; @@ -85,6 +94,7 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ "guest_jwt_jwks_url", "error_handler_fallback_to_instance_alerts", "add_admins_and_developers_to_forks", + "variable_expiration_handler", ] as const; // Legacy settings interface for reading old settings.yaml files diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 7d0cf5c1cc..6a0d6f47f4 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -6839,7 +6839,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply 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. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`@windmill-labs/chat-sdk\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. @@ -6852,9 +6852,31 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) \`@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. +#### A saved agent: an \`agent\` runnable + +Chat 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: + +In \`raw_app.yaml\`: + +\`\`\`yaml +runnables: + chat: + type: agent + path: f/support/agent +\`\`\` + +\`\`\`tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +\`\`\` + +\`runnable\` is the runnable's key; each runnable keeps its own conversations. The runnable takes \`user_message\` and \`memory_id\`, the conversation id, which the chat fills in: 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 })\` without \`memory_id\`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes \`previous_messages\` (chat messages) instead of \`memory_id\`, 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. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -6862,6 +6884,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | \`script\` | Reference to an existing workspace script by path. | | \`flow\` | Reference to an existing workspace flow by path. | | \`hubscript\` | Reference to a hub script by path. | +| \`agent\` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -6903,9 +6926,9 @@ An inline runnable runs as an ordinary Windmill job. \`import * as wmill from 'w Use 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. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When \`type\` is \`script\`, \`flow\`, or \`hubscript\`, 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. +When \`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 \`memory_id\` when the agent keeps managed memory or \`previous_messages\` when its memory is off. Before 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. @@ -6914,7 +6937,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **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. -- **Path runnables (\`script\` / \`flow\` / \`hubscript\`) 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. +- **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. So 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. @@ -7024,7 +7047,7 @@ def main(user_id: str): 7. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow 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 }\`. `, "triggers": `--- name: triggers @@ -8341,7 +8364,7 @@ write a secret you were not given: keep the placeholder. | \`ai_config\` | Providers, default and completion models, custom prompts, \`copilot_disabled\`. | | \`large_file_storage\` | Workspace object storage: \`{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }\`. | | \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | -| \`datatable\` | \`{ datatables: { <name>: { database: { resource_type, resource_path? } } } }\`. Role permissions are \`datatable_permissions\`. | +| \`datatable\` | \`{ 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\`. | | \`datatable_permissions\` | \`{ <data table>: { default_role, roles: { <role>: [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/<user>\`, \`g/<group>\`, \`f/<folder>\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | | \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...] } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { <name>: { catalog, storage, ... } } }\`. | diff --git a/cli/test/deploy_variable_expiry_unit.test.ts b/cli/test/deploy_variable_expiry_unit.test.ts new file mode 100644 index 0000000000..5569883121 --- /dev/null +++ b/cli/test/deploy_variable_expiry_unit.test.ts @@ -0,0 +1,60 @@ +import { expect, test } from "bun:test"; +import { deployItem } from "../windmill-utils-internal/src/deploy.ts"; + +// Workspace deploy builds the variable body field by field, so a forgotten field is +// dropped silently on promotion, and a source with no expiry must send `null`. +function recordingProvider( + captured: [string, any][], + exists: boolean, + value_valid_until: string | null, +) { + return { + existsVariable: async () => exists, + getVariable: async () => ({ + path: "f/x/v", + value: "secret", + is_secret: true, + description: "d", + value_valid_until, + }), + createVariable: async (p: any) => + void captured.push(["createVariable", p.requestBody]), + updateVariable: async (p: any) => + void captured.push(["updateVariable", p.requestBody]), + } as any; +} + +test("deployItem: carries value_valid_until, and clears it explicitly", async () => { + const captured: [string, any][] = []; + + // Written once per branch: create and update. + for (const exists of [false, true]) { + await deployItem( + recordingProvider(captured, exists, "2027-03-15T08:00:00Z"), + "variable" as any, + "f/x/v", + "src", + "dst", + ); + await deployItem( + recordingProvider(captured, exists, null), + "variable" as any, + "f/x/v", + "src", + "dst", + ); + } + + expect(captured.map(([fn]) => fn)).toEqual([ + "createVariable", + "createVariable", + "updateVariable", + "updateVariable", + ]); + expect(captured.map(([, body]) => body.value_valid_until)).toEqual([ + "2027-03-15T08:00:00Z", + null, + "2027-03-15T08:00:00Z", + null, + ]); +}); diff --git a/cli/test/variable_resource_push.test.ts b/cli/test/variable_resource_push.test.ts index b77ed48b50..67be8bf3b7 100644 --- a/cli/test/variable_resource_push.test.ts +++ b/cli/test/variable_resource_push.test.ts @@ -133,6 +133,70 @@ describe("variable", () => { }); }); + test("push clears value_valid_until when the key is dropped from the file", async () => { + await withTestBackend(async (backend, tempDir) => { + await setupWorkspaceProfile(backend); + + const uniqueId = Date.now(); + const path = `f/test/expiry_var_${uniqueId}`; + + const createResp = await backend.apiRequest!( + `/api/w/${backend.workspace}/variables/create`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + path, + value: "original_value", + is_secret: false, + description: "Expiring", + value_valid_until: "2027-03-15T08:00:00Z", + }), + } + ); + expect(createResp.status).toBeLessThan(300); + await createResp.text(); + const created = await backend.apiRequest!( + `/api/w/${backend.workspace}/variables/get/${path}` + ); + expect((await created.json()).value_valid_until).toBe("2027-03-15T08:00:00Z"); + + await writeFile( + join(tempDir, "wmill.yaml"), + `defaultTs: bun\nincludes:\n - "**"\nexcludes: []\n`, + "utf-8" + ); + await mkdir(join(tempDir, "f", "test"), { recursive: true }); + // No value_valid_until: the CLI must send an explicit null to clear it. + await writeFile( + join(tempDir, `${path}.variable.yaml`), + `value: "original_value"\nis_secret: false\ndescription: "Expiring"\n`, + "utf-8" + ); + + const pushResult = await backend.runCLICommand( + ["sync", "push", "--yes", "--includes", `${path}**`], + tempDir + ); + expect(pushResult.code).toEqual(0); + + const apiResp = await backend.apiRequest!( + `/api/w/${backend.workspace}/variables/get/${path}` + ); + expect(apiResp.status).toEqual(200); + const varData = await apiResp.json(); + expect(varData.value_valid_until ?? null).toBeNull(); + + // A clear that did not land leaves the diff pending, so push success is not proof. + const secondPush = await backend.runCLICommand( + ["sync", "push", "--yes", "--includes", `${path}**`], + tempDir + ); + expect(secondPush.code).toEqual(0); + expect(secondPush.stdout).toContain("0 changes to apply"); + }); + }); + test("add creates secret by default and preserves fields on update", async () => { await withTestBackend(async (backend, tempDir) => { await setupWorkspaceProfile(backend); diff --git a/cli/windmill-utils-internal/package-lock.json b/cli/windmill-utils-internal/package-lock.json index a2fb09f3dc..3babfd3631 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.7.0", + "version": "1.8.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-utils-internal", - "version": "1.7.0", + "version": "1.8.4", "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 525bb0fc0b..4b3c96903d 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.2", + "version": "1.8.4", "description": "Internal utility functions for Windmill", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index d73cb3562c..3478fa8b0b 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -617,6 +617,8 @@ export async function deployItem( is_secret: variable.is_secret, description: variable.description ?? "", labels: variable.labels, + // `null` clears; absent would keep the target's stored date. + value_valid_until: variable.value_valid_until ?? null, }, alreadyEncrypted: false, }); @@ -629,6 +631,7 @@ export async function deployItem( is_secret: variable.is_secret, description: variable.description ?? "", labels: variable.labels, + value_valid_until: variable.value_valid_until ?? null, }, }); } @@ -926,7 +929,12 @@ export async function getItemValue( path, decryptSecret: true, }); - return variable.value; + return { + value: variable.value, + is_secret: variable.is_secret, + description: variable.description, + value_valid_until: variable.value_valid_until ?? undefined, + }; } else if (kind === "resource") { const resource = await provider.getResource({ workspace, path }); // Each workspace resolves its own agent identity, which a deploy never copies. diff --git a/cli/windmill-utils-internal/src/inline-scripts/replacer.ts b/cli/windmill-utils-internal/src/inline-scripts/replacer.ts index d926467b86..b6ed4a4376 100644 --- a/cli/windmill-utils-internal/src/inline-scripts/replacer.ts +++ b/cli/windmill-utils-internal/src/inline-scripts/replacer.ts @@ -190,7 +190,7 @@ export async function replacePathScriptsWithLocal( } const localScript = await scriptReader(toolValue.path); if (localScript) { - (tool as AiAgent["tools"][number]).value = { + (tool as NonNullable<AiAgent["tools"]>[number]).value = { tool_type: "flowmodule", type: "rawscript", content: localScript.content, diff --git a/cli/windmill-utils-internal/src/path-utils/path-assigner.ts b/cli/windmill-utils-internal/src/path-utils/path-assigner.ts index 6aaeea4db1..c718e64e0c 100644 --- a/cli/windmill-utils-internal/src/path-utils/path-assigner.ts +++ b/cli/windmill-utils-internal/src/path-utils/path-assigner.ts @@ -5,7 +5,7 @@ const INLINE_SCRIPT_PREFIX = "inline_script"; /** * Union type of all supported programming languages in Windmill */ -export type SupportedLanguage = RawScript["language"] | "frontend" | "bunnative" | "oracledb" | "rust" | "csharp" | "nu" | "ansible" | "java" | "duckdb"; +export type SupportedLanguage = RawScript["language"] | "frontend" | "bunnative" | "oracledb" | "rust" | "csharp" | "nu" | "ansible" | "java" | "duckdb" | "dbt"; /** * Mapping of supported languages to their file extensions diff --git a/debugger/Dockerfile b/debugger/Dockerfile index 6b423920a0..be30570425 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.0 AS runtime +FROM oven/bun:1.4.4 AS runtime # Install Python and required system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ diff --git a/docker/DockerfileFull b/docker/DockerfileFull index c3a82c8312..d145a5ffff 100644 --- a/docker/DockerfileFull +++ b/docker/DockerfileFull @@ -25,6 +25,10 @@ RUN wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh \ && ./dotnet-install.sh --channel 9.0 --install-dir /usr/share/dotnet \ && ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet \ && rm dotnet-install.sh +# PHP +COPY --from=php:8.3.36-cli-trixie /usr/local/bin/php /usr/bin/php +COPY --from=composer:2.9.5 /usr/bin/composer /usr/bin/composer + # Nushell COPY --from=ghcr.io/nushell/nushell:0.101.0-bookworm /usr/bin/nu /usr/bin/nu diff --git a/docker/DockerfileFullEe b/docker/DockerfileFullEe index bb83195f62..8ca1067f7a 100644 --- a/docker/DockerfileFullEe +++ b/docker/DockerfileFullEe @@ -53,6 +53,10 @@ RUN apt-get -y update && apt-get install -y libaio1t64 \ && ln -s "$(basename "$libaio")" "$(dirname "$libaio")/libaio.so.1" RUN echo /opt/oracle/23/lib > /etc/ld.so.conf.d/oracle-instantclient.conf && ldconfig +# PHP +COPY --from=php:8.3.36-cli-trixie /usr/local/bin/php /usr/bin/php +COPY --from=composer:2.9.5 /usr/bin/composer /usr/bin/composer + # Nushell COPY --from=ghcr.io/nushell/nushell:0.101.0-bookworm /usr/bin/nu /usr/bin/nu diff --git a/docker/DockerfileSlim b/docker/DockerfileSlim index 630f454f01..daeb64b637 100644 --- a/docker/DockerfileSlim +++ b/docker/DockerfileSlim @@ -44,7 +44,10 @@ ENV UV_TOOL_DIR=/usr/local/uv ENV PATH=/usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH # Install system dependencies -RUN apt-get update \ +# Bump to force a fresh apt-get upgrade past the build cache; keep in step with ../Dockerfile. +ARG APT_REFRESH=1 +RUN echo "apt refresh ${APT_REFRESH}" \ + && apt-get update \ && apt-get upgrade -y \ && apt-get install -y --no-install-recommends ca-certificates wget curl git jq unzip unixodbc xmlsec1 gnupg lsb-release libgnutls30t64 libgcrypt20 \ && apt-get clean \ @@ -61,7 +64,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.0/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.4/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 @@ -77,7 +80,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.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /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 8189e74bf9..3edff33038 100644 --- a/docker/DockerfileSlimEe +++ b/docker/DockerfileSlimEe @@ -44,7 +44,10 @@ ENV UV_TOOL_DIR=/usr/local/uv ENV PATH=/usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH # Install system dependencies -RUN apt-get update \ +# Bump to force a fresh apt-get upgrade past the build cache; keep in step with ../Dockerfile. +ARG APT_REFRESH=1 +RUN echo "apt refresh ${APT_REFRESH}" \ + && apt-get update \ && apt-get upgrade -y \ && apt-get install -y --no-install-recommends ca-certificates wget curl git jq unzip unixodbc xmlsec1 gnupg lsb-release libgnutls30t64 libgcrypt20 \ && apt-get clean \ @@ -61,7 +64,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.0/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.4/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 @@ -77,7 +80,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.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /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/feature-telemetry.md b/docs/feature-telemetry.md index 8e658eda3f..0862453020 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,10 +4,12 @@ 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 62 registered actions across twenty-one features (`ai_session`, `ai_chat`, +It currently carries 78 registered actions across twenty-nine features (`ai_session`, `ai_chat`, `ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`, -`flow_run`, `flow_step`, `home`, `run_form`, `debugger`, `trigger`, `command_script`, -`hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`). Nearly all of the +`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `debugger`, `trigger`, `command_script`, +`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`). 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 8ace42a1e5..d4dc42b2d3 100644 --- a/docs/operator-builder-rights.md +++ b/docs/operator-builder-rights.md @@ -1,8 +1,8 @@ # Operator builder rights Two workspace settings, `operator_settings.builder_flows` and `operator_settings.builder_apps`, -that let every operator of that workspace compose flows and full-code apps out of runnables that -already exist. Neither lets them author backend code or run arbitrary code on a worker, the +that let every operator of that workspace compose flows (and AI agents, under the flow right) and +full-code apps out of runnables that already exist. Neither lets them author backend code or run arbitrary code on a worker, the boundary the operator role draws. The app right does let them write the app's frontend code, which runs in the viewer's browser and is why that right rests on sandbox isolation. @@ -14,12 +14,12 @@ without the second, so **never gate on "either"**: a gate that does authorizes t workspace never granted, which is the whole point of the split. `BuilderKind` exists to make each call site say which one it means. -These are write rights, unlike the visibility flags beside them, and unlike the withdrawable -rights in `docs/operator-write-rights.md` they are granted on request and cost a seat. Read them -with `windmill_common::workspaces::operator_builder_rights` (60s cache, shared with the -withdrawable rights), which returns an `OperatorBuilderRights { flows, apps }`, and gate a write -with `check_operator_can_build`, naming the `BuilderKind`. `.any()` is only for surfaces that are -genuinely not per-kind: the seat a membership costs, and listing drafts. +These rights are now the `compose` level of a role's `flows` and `apps` capabilities +(`docs/workspace-roles.md`): `builder_flows` / `builder_apps` in the legacy operator settings set +the `operator` role to it. Gate a write with `check_operator_can_build`, naming the `BuilderKind`: +it refuses `none` and returns the level held, and the caller MUST run the composition-only checks +below at `compose` and may skip them only at `full`. `OperatorBuilderRights::any()` is only for +surfaces that are genuinely not per-kind, such as listing drafts. ## What the check has to cover @@ -32,13 +32,24 @@ anything that carries code. Three of its rules exist because the obvious walk mi past it. - **An AI agent step's `tools`.** `ToolValue::FlowModule` wraps a whole `FlowModuleValue`, so a tool can be a raw script. -- **An AI agent step's `agent` link.** A linked agent resolves its tools from an `ai_agent` - resource at run time, and operators may write resources, so the tool list is outside this check - and can be swapped for a raw script after the flow is approved. - It also returns what a value-only walk cannot authorize, for the caller to check against its own permissions: +- **every agent a step links**. A linked agent resolves its tools from its `ai_agent` resource at + run time, outside this walk, so the link is allowed only to an agent the builder can read. That + is safe because of the agent rule below: an agent's tools are either a developer's code or + passed this same check when an operator saved them. Two things keep it safe: + - The step's `tool_inputs` replace a tool's inputs at run time, including the ones the agent's + author set. A builder's step may bind only the inputs the agent leaves open + (`check_bound_agent_inputs_are_open`, on `InputTransform::is_completed`), and the flow editor + lets a builder edit only those, showing the rest read-only. What it binds there, a `$var:` or + a JavaScript expression included, is what its own steps may already pass a deployed runnable; an input the author set + stays theirs. The check runs on the flow's write, so a tool or input the agent gains later is + open to a binding written before it, like the retyped path below. + - The worker refuses a linked path whose resource is no longer an `ai_agent` + (`get_agent_value`). Only writes of an agent are checked, so a path retyped, or recreated as + another type, after the link was approved would otherwise run whatever `tools` it now holds. + - **the worker tags the steps pin**, or a builder routes a job onto a privileged worker group; - **every runnable a step references**. `script_to_payload` resolves a step's path with the root DB handle (`db_authed = None`) and returns the referenced runnable's `on_behalf_of`, which @@ -61,12 +72,27 @@ Call it on every write **and** every preview: `run_preview_flow_job` and it the way to run what the write path refuses. A flow draft goes through `validate_operator_flow` too: a developer who loads a builder's draft in the editor runs its code as themselves. +## Agents + +An agent is an `ai_agent` resource, and operators may write resources, so the `flows` capability +is also the right to build agents. Without it a restricted role writes no agent at all. Its tools run in the +agent's own runs, which take only inputs and run what is stored, and in every flow step linking +it. So `validate_operator_agent` holds an operator's agent to the composed-flow rules by checking +its tools as the tools of a one-step flow. It is called from `resolve_agent_on_behalf_of`, which +every write of an agent's value passes through: create, update, retype, update-value and version +restore. An operator's resource draft is checked the same way when it names `ai_agent` **or** an +agent is deployed at its path, whatever type the draft names: deploying a draft from the resource +editor keeps the row's type. A draft saved before an agent is created at its path is not +re-checked when someone else deploys it. A new route that writes an agent's value must go through +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 run would pick: grants are per version, and a path reused after its versions were archived starts with none while the archived ones keep theirs. But it has to check **two** surfaces, -because they are not the same list: the policy's `script/<path>` and `flow/<path>` triggerables, +because they are not the same list: the policy's `script/<path>`, `flow/<path>` and +`agent/<path>` triggerables (an agent is checked as an `ai_agent` resource the caller can read), and the by-path entries of the app value's `runnables` map, which is what the editor resolves a `runnable_id` against and sends. Read only that map, and refuse an entry whose `type`, `path` or `runType` is not text. @@ -77,8 +103,8 @@ at run time for `component = "a:b"`. Every colon is a possible split, so the che suffix that parses as a runnable rather than guessing which one a request will use. What makes those checks bind is that **`ExecutionMode::Viewer` is refused for a builder app**. In -Viewer mode `execute_component` falls back to a default triggerable for any `script/`/`flow/` -path, so the policy stops being the list of what the app may invoke, and the job runs as the +Viewer mode `execute_component` falls back to a default triggerable for any `script/`/`flow/`/ +`agent/` path, so the policy stops being the list of what the app may invoke, and the job runs as the *viewer*: an admin who merely opened the app would run anything in the workspace as themselves. `Publisher`, `Guest` and `Anonymous` have no such fallback; all three run as the publisher. If you ever relax the Viewer refusal, the deploy-time path checks above stop being an authorization boundary. @@ -103,12 +129,19 @@ ignored into `inlineScript`. `update_app` takes a builder too, but settings only: the deploy panel saves a deployed full-code app's access and frontend scopes through it with no value. It reaches the same check, so a builder -can no more switch the sandbox off there than on deploy. +can no more switch the sandbox off there than on deploy. A change of `execution_mode` alone runs +`check_operator_composed_app` on the deployed policy under the row lock, but not the readability +check, which resolves script versions on a second pool connection. It is therefore refused when +the app runs as anyone but the builder, `wm_deployers` or not: what an app running as its builder +invokes runs as that builder, who can already run it as themselves by opening the app. It is also +refused on an app whose stored policy is not sandboxed: the check would fill in the sandbox, and a +change of the mode alone keeps every other field of the policy. A builder's **draft** goes through the same `check_operator_composed_app` as its deploy, with `BuilderAppWrite::Draft`: an admin may open it in the editor or deploy it as it stands, so any rule added for deploys must hold for drafts too. Where the two differ, `write` decides: a deploy -fills in an omitted sandbox or mode, since it stores the policy it checked, while a draft skips +fills in an omitted sandbox, since it stores the policy it checked, and an omitted mode inherits the +deployed one, except that `Viewer` becomes `Publisher`, while a draft skips `triggerables_v2` and must not name another user's run identity. Every frontend writer of a builder draft must conform the policy first with `conformBuilderAppPolicy`, since a policy loaded from someone else's app breaks these rules: the raw-app editor component does, which covers both @@ -146,16 +179,13 @@ artifacts, and there is no half-author, so granting both costs no more than gran introduce per-right pricing — it turns one boolean into a capability matrix that billing, the cap check and the displayed count would each have to agree on. -`consumes_operator_seat` is the seat-role helper; the EE counting queries share -`OPERATOR_SEAT_SQL` so the displayed, enforced and reported numbers agree. The one exception is -`get_user_usage` in `stats_ee.rs`: it is a compile-checked `query!`, which cannot interpolate the -constant, so it spells the predicate out. Change both together. On cloud, `billable_seats` applies -the same rule; see its doc for the out-of-repo invoice it must match. +Every count reads the role's author flag from `role_seat` through `AUTHOR_SEAT_SQL`; see +`docs/workspace-roles.md`. On cloud, `billable_seats` applies the same rule; see its doc for the +out-of-repo invoice it must match. -Granting the first right runs `check_seat_cap_for_operator_builder`, which prices the change by -counting seats twice rather than by counting the workspace's operators: an operator who already -authors elsewhere must not be charged again. Adding the second right later, or re-saving settings -that already have one on, is a zero delta and never blocks. +A role change runs `check_seat_cap_for_role_change` inside the transaction that writes it, which +prices the change by counting seats twice rather than by counting the role's members: a member who +already authors elsewhere must not be charged again. A change that adds no seat never blocks. ## Accepted risks @@ -186,7 +216,6 @@ that already have one on, is a zero delta and never blocks. carries none makes the deployer its run identity, as any deploy does. An admin deploying such a draft, from the editor or Compare & Deploy, therefore publishes the builder's code running as that admin; the deploy is the admin's explicit act, as it is for a developer's draft. -- All-or-nothing per workspace: there is no per-user builder role. - `operator_settings` is git-synced, so a pull can flip every operator's class in a workspace and the billed seat count with it. - A builder writes JavaScript expressions: step inputs, branch predicates, `stop_after_if` and diff --git a/docs/operator-write-rights.md b/docs/operator-write-rights.md index a1421400f0..5fda1547f0 100644 --- a/docs/operator-write-rights.md +++ b/docs/operator-write-rights.md @@ -95,20 +95,22 @@ toolbar, which takes its permissions from `can_write`, needs no lock of its own. `ShareModal`, which locks itself off the kind it was opened on rather than relying on each of the dozen menu entries that open it. -The cache is per process, so withdrawing a right has to reach every replica: an `AFTER UPDATE OF -operator_settings` trigger writes a `notify_operator_settings_change` row and `process_notify_event` -drops the entry. Keep both ends if you touch either, or a workspace that withdrew a right keeps -authorizing writes on every other replica until its own entry expires. +These rights are now capabilities of a member's role (`docs/workspace-roles.md`), and the legacy +operator settings write them as an override of the `operator` role. The roles cache is per process, +so withdrawing a right has to reach every replica: `write_role_overrides` calls +`roles::notify_role_overrides_change` in its transaction and `process_notify_event` drops the +entry. A new writer of `role_overrides` has to call it too, or a workspace that withdrew a right +keeps authorizing writes on every other replica until its own entry expires. ## Granted unless withdrawn These name capabilities operators already hold, so absence has to mean "never configured", not a value. That is easy to get wrong in two places, and the obvious implementation gets both wrong: -- The read coalesces to **true** (`operator_rights`), including for a workspace with no - `workspace_settings` row, which is what `OperatorManageRights::default` is for. Coalescing to - false instead revokes the right on upgrade for every workspace that ever saved operator settings, - since those rows carry explicit keys and none of them is this one. +- An unset key falls through to **true** (`RoleCapabilities::OPERATOR`), including for a + workspace with no override. A default of false instead revokes the right on upgrade for every + workspace that ever saved operator settings, since those rows carry explicit keys and none of + them is this one. - The update endpoint **merges** into the stored jsonb and takes these two as `Option<bool>`, so an omitted key keeps its stored value. It has to: `operator_settings` is git-synced as a whole object (`cli/src/core/settings.ts` posts the file's contents verbatim), so a settings file diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md new file mode 100644 index 0000000000..9ce3294c54 --- /dev/null +++ b/docs/workspace-roles.md @@ -0,0 +1,66 @@ +# Workspace roles + +What a non-admin member may author, manage and see is its **role**. `developer` and `operator` are +the default roles; a licensed EE instance defines its own list in the `workspace_roles` global +setting (at least one role), and any workspace may override a role's capabilities in +`workspace_settings.role_overrides`, or, when licensed, add roles of its own there. A lapsed +license freezes them rather than dropping them (`custom_roles_enabled`): the stored list and the +workspace-only roles keep applying, writes that change them are refused, and resetting the list to +the defaults or removing a workspace-only role stays open. Falling back to the defaults instead +would hand a restricted `developer` everything. Workspace admin is not a +role: it is the `is_admin` flag on top of whichever role a member holds, and holds everything. The +code is `windmill_common::roles`. + +## Capabilities + +| Capability | Values | Enforced | +|---|---|---| +| `code` | bool | yes: scripts, previews, dependency jobs, dynamic selects, resolving jobs, data table migrations, eval datasets | +| `flows` | `none` / `compose` / `full` | yes; also AI agents, whose tools are checked as composed steps | +| `apps` | `none` / `compose` / `full` | yes; low-code apps and worker-built apps need `full` | +| `manage_schedules`, `manage_triggers` | bool | yes, see `docs/operator-write-rights.md` | +| `visibility.*` | bool per page | no, UI only | + +`compose` is the former operator builder right: the composition-only checks of +`docs/operator-builder-rights.md` run for it and are skipped only at `full`. `full` flows or apps +without `code` is refused at write, since both carry inline code. + +Stored values are **patches**: an unset key falls through to the layer below, so a key added later +reads as "never configured". The layers, top first: the workspace override, the instance +definition, then `RoleCapabilities::base_for` (`FULL` for `developer`, the legacy operator for any +other name). A role name no longer defined resolves to `NONE`, so deleting a role fails closed; +deleting one that a member, invite, auto-invite or instance group mapping still names is refused, +and so is deleting an instance role that a workspace still overrides (the override would fall onto +`base_for` instead of the definition it was written against). + +## Who is restricted + +`ApiAuthed::is_operator` means "this member's role is restricted", computed at authentication from +the role, never from `usr.operator` alone. Every gate fast-paths on it (`caller_capabilities` +returns `FULL` for an unrestricted or admin caller without reading the role), so it must stay +derived from the role: a stale flag lets a restricted member through. The authentication cache +holds it for up to 120s. + +`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. +The old `usr.role` column is unrelated and holds legacy display strings. + +## Seats + +A role that writes or composes anything costs a full seat; anything else half. Billing SQL cannot +merge capability patches, so `role_seat` materializes the author flag per role +(`workspace_id = ''` for the instance, a row per workspace override), rewritten by +`sync_role_seats` after every write to either setting. Every count reads it through +`AUTHOR_SEAT_SQL`, and usage telemetry reports builders (authors anywhere) against non-builders the +same way. A change that adds seats under an offline license is priced inside the transaction that +writes it, by `check_seat_cap_for_role_change`. + +## Legacy `operator_settings` + +`/operator_settings` still works: it is applied as an override of the `operator` role, dropping any +key equal to what the instance gives that role, and the payload is mirrored into the +`operator_settings` column for git sync and older servers. The migration moved every key a +workspace had changed from its default into `role_overrides.operator` the same way. The workspace +list still returns an `operator_settings` object for a restricted member, synthesized from its +role, alongside `role` and `capabilities`. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 30ac859fce..206f8bb476 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.841.0", + "version": "1.849.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.841.0", + "version": "1.849.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { @@ -110,7 +110,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.2", + "windmill-utils-internal": "1.8.4", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", @@ -14719,9 +14719,9 @@ "integrity": "sha512-uHNL8F72/Tf96xF3hOHnPDjkEyqXw7fNjcPJiUhth9sTQkcwUIoJMOdwm8/cs+j9kKVRJ4tgNYMHEBLylazp6g==" }, "node_modules/windmill-utils-internal": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.2.tgz", - "integrity": "sha512-Otdn4iCE0QiOtMKPdHX5I89oECfZa3vmO2jdLdSETf7MBSv/gw9gvQm3oUQ29ymIHXLeuhQk/ebPD+WYolQJEA==", + "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==", "license": "Apache 2.0" }, "node_modules/word-wrap": { diff --git a/frontend/package.json b/frontend/package.json index 7320d9c5f6..86b73762fa 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.841.0", + "version": "1.849.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", @@ -16,6 +16,7 @@ "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: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", "test:unit": "vitest", @@ -176,7 +177,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.2", + "windmill-utils-internal": "1.8.4", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", diff --git a/frontend/src/lib/assets/app.css b/frontend/src/lib/assets/app.css index 4217c95831..f7f9b53972 100644 --- a/frontend/src/lib/assets/app.css +++ b/frontend/src/lib/assets/app.css @@ -426,3 +426,46 @@ input[type='time']::-webkit-calendar-picker-indicator { .svelte-flow__edges { z-index: -10; } + +/* The composer's glide, defined once: the Home ↔ AI Sessions view transition below and the + in-page move on a session's first message (the spacer under AIChatDisplay's composer) both + read it. */ +:root { + --composer-glide-duration: 380ms; + --composer-glide-easing: cubic-bezier(0.2, 0.8, 0.2, 1); +} + +/* Home ↔ AI Sessions (homeSessionsTransition.svelte.ts). The composer glides from where it + was to where it lands; everything else, Home's list and the session's greeting included, is + the page cross-fading, kept short. The pseudo-elements hang off :root itself, so no space + before `::view-transition-*`: with one, the selector looks for a descendant and never + matches. */ +:root[data-home-sessions-transition]::view-transition-group(composer) { + animation-duration: var(--composer-glide-duration); + animation-timing-function: var(--composer-glide-easing); +} +:root[data-home-sessions-transition]::view-transition-old(root), +:root[data-home-sessions-transition]::view-transition-new(root) { + animation-duration: 150ms; +} +/* The session's greeting sits above where the composer lands, so it waits for the composer: + shown while the composer is still gliding, it reads as text placed in mid-air. It starts as + the composer settles and rises into place on the same easing, so the two read as one motion. + Leaving, it goes with the page. */ +:root[data-home-sessions-transition='enter']::view-transition-new(greeting) { + animation: greeting-in 260ms var(--composer-glide-easing) + calc(var(--composer-glide-duration) * 0.6) both; +} +:root[data-home-sessions-transition]::view-transition-old(greeting) { + animation-duration: 150ms; +} +@keyframes greeting-in { + from { + opacity: 0; + transform: translateY(4px); + filter: blur(2px); + } +} +:root[data-home-sessions-transition='fade'] * { + view-transition-name: none !important; +} diff --git a/frontend/src/lib/components/AIProviderPicker.svelte b/frontend/src/lib/components/AIProviderPicker.svelte index 67afad9be6..0d23ab55a3 100644 --- a/frontend/src/lib/components/AIProviderPicker.svelte +++ b/frontend/src/lib/components/AIProviderPicker.svelte @@ -9,6 +9,7 @@ } from './copilot/lib' import type { AIProvider, ProviderConfig } from '$lib/gen' import ResourcePicker from './ResourcePicker.svelte' + import { aiResourceProvider } from './copilot/aiResourceProvider' import Toggle from './Toggle.svelte' import { saveConfig, removeConfig, isSameAsStoredConfig } from './aiProviderStorage' import AIReasoningEffortPicker from './AIReasoningEffortPicker.svelte' @@ -57,7 +58,11 @@ const offeredProviders = Object.keys( untrack(() => decision) ? DECISION_AI_PROVIDERS : AI_PROVIDERS ) - const providerResourceTypes = offeredProviders.join(',') + // Federated Anthropic resources authenticate the anthropic provider without a key of their own. + const providerResourceTypes = [ + ...offeredProviders, + ...(offeredProviders.includes('anthropic') ? ['anthropic_federated'] : []) + ].join(',') if (!_uncheckedValue) { _uncheckedValue = { @@ -143,13 +148,14 @@ function onResourcePicked(_path: string | undefined, type: string | undefined) { // 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. - if (!value || !type || !offeredProviders.includes(type)) { + const provider = aiResourceProvider(type) + if (!value || !provider || !offeredProviders.includes(provider)) { return } - if (value.kind === type) { + if (value.kind === provider) { return } - value.kind = type as AIProvider + value.kind = provider // Models are per provider, and a reasoning token is per model. value.model = '' value.reasoning_effort = undefined diff --git a/frontend/src/lib/components/AddUser.svelte b/frontend/src/lib/components/AddUser.svelte index 1369e33fb2..8cf1693bc7 100644 --- a/frontend/src/lib/components/AddUser.svelte +++ b/frontend/src/lib/components/AddUser.svelte @@ -1,7 +1,7 @@ <script lang="ts"> import { createEventDispatcher } from 'svelte' import { globalEmailInvite, superadmin, workspaceStore, enterpriseLicense } from '$lib/stores' - import { SettingService, UserService, WorkspaceService } from '$lib/gen' + import { SettingService, UserService, WorkspaceService, type EffectiveRole } from '$lib/gen' import { Button } from './common' import Popover from './meltComponents/Popover.svelte' import { sendUserToast } from '$lib/toast' @@ -14,6 +14,15 @@ import { UserPlus } from 'lucide-svelte' import Select from './select/Select.svelte' import { resource } from 'runed' + import RolePicker from './settings/RolePicker.svelte' + import { roleRequestFields, validRoleOr } from '$lib/workspaceRoles' + + interface Props { + /** The workspace's roles; undefined while loading. */ + roles: EffectiveRole[] | undefined + } + + let { roles }: Props = $props() const dispatch = createEventDispatcher() @@ -84,7 +93,7 @@ getAutomateUsernameCreationSetting() async function addUser() { - if (selected === 'service_account') { + if (isServiceAccount) { if (!username) return await WorkspaceService.createServiceAccount({ workspace: $workspaceStore!, @@ -99,15 +108,19 @@ } else { // Read once: the picker's own state changes as soon as the request lands. const email = effectiveEmail! - await WorkspaceService.addUser({ - workspace: $workspaceStore!, - requestBody: { - email, - username: automateUsernameCreation ? undefined : username, - is_admin: selected == 'admin', - operator: selected == 'operator' - } - }) + try { + await WorkspaceService.addUser({ + workspace: $workspaceStore!, + requestBody: { + email, + username: automateUsernameCreation ? undefined : username, + ...roleRequestFields(selected) + } + }) + } catch (e) { + sendUserToast(`Failed to add ${email}: ${e?.body ?? e}`, true) + return + } sendUserToast(`Added ${email}`) // The picker excludes members server-side, so it has to refetch to drop this one. addedCount++ @@ -140,12 +153,13 @@ dispatch('new') } - type UserRole = 'operator' | 'developer' | 'admin' | 'service_account' type ServiceAccountRole = 'operator' | 'developer' | 'admin' - let selected: UserRole = $state('developer' as UserRole) + // A role name, or `admin`. + let picked: string | undefined = $state(undefined) + const selected = $derived(validRoleOr(roles, picked)) let serviceAccountRole: ServiceAccountRole = $state('operator' as ServiceAccountRole) let addToDeployers: boolean = $state(true) - let isServiceAccount = $derived(selected === 'service_account') + let isServiceAccount = $state(false) </script> <Popover placement="bottom-end" bind:isOpen={popoverOpen} onClose={() => (typedEmail = '')}> @@ -157,6 +171,18 @@ {#snippet content()} <div class="flex flex-col w-[28rem] p-4"> <span class="text-sm mb-2 leading-6 font-semibold">Add a new user</span> + <div class="mb-2"> + <Toggle + bind:checked={isServiceAccount} + disabled={!$enterpriseLicense} + size="xs" + options={{ + right: $enterpriseLicense ? 'Service account' : 'Service account (EE)', + rightTooltip: + 'A service account is a workspace-scoped identity for automation. It cannot log in directly and can be impersonated by admins.' + }} + /> + </div> {#if isServiceAccount} <span class="text-xs mb-1 leading-6">Username</span> @@ -217,38 +243,12 @@ {/if} {/if} - <span class="text-xs mb-1 pt-6 leading-6">Role</span> - <ToggleButtonGroup bind:selected class="mb-4"> - {#snippet children({ item })} - <ToggleButton - value="operator" - label="Operator" - tooltip="An operator can only execute and view scripts/flows/apps from your workspace, and only those that he has visibility on." - {item} - /> - <ToggleButton - value="developer" - label="Developer" - tooltip="A Developer can execute and view scripts/flows/apps, but they can also create new ones and edit those they are allowed to by their path (either u/ or Writer or Admin of their folder found at /f)." - {item} - /> - <ToggleButton - value="admin" - label="Admin" - tooltip="An admin has full control over a specific Windmill workspace, including the ability to manage users, edit entities, and control permissions within the workspace." - {item} - /> - <ToggleButton - value="service_account" - label={$enterpriseLicense ? 'Service Account' : 'Service Account (EE)'} - tooltip="A service account is a workspace-scoped identity for automation. It cannot log in directly and can be impersonated by admins." - disabled={!$enterpriseLicense} - {item} - /> - {/snippet} - </ToggleButtonGroup> - - {#if isServiceAccount} + {#if !isServiceAccount} + <span class="text-xs mb-1 pt-6 leading-6">Role</span> + <div class="mb-4"> + <RolePicker {roles} disablePortal value={selected} onchange={(v) => (picked = v)} /> + </div> + {:else} <span class="text-xs mb-1 leading-6">Service account role</span> <ToggleButtonGroup bind:selected={serviceAccountRole} class="mb-4"> {#snippet children({ item })} diff --git a/frontend/src/lib/components/AppConnectDrawer.svelte b/frontend/src/lib/components/AppConnectDrawer.svelte index 8de484929e..6cdfdc2998 100644 --- a/frontend/src/lib/components/AppConnectDrawer.svelte +++ b/frontend/src/lib/components/AppConnectDrawer.svelte @@ -9,17 +9,20 @@ import GoogleSigninButton from './GoogleSigninButton.svelte' import IconedResourceType from './IconedResourceType.svelte' import { addResourceTitle } from './resourceTypeDisplay' + import type { NativeConnect } from './triggers/native/utils' interface Props { expressOAuthSetup?: boolean workspace?: string disableChatOffset?: boolean + native?: NativeConnect } let { expressOAuthSetup = false, workspace = undefined, - disableChatOffset = false + disableChatOffset = false, + native = undefined }: Props = $props() /** Set by `open(rt, fillPath)`, not by the parent: which resource this run fills is a @@ -82,7 +85,7 @@ {disableChatOffset} > <DrawerContent - title={addResourceTitle(step > 1 ? resourceType : undefined)} + title={native?.title ?? addResourceTitle(step > 1 ? resourceType : undefined)} id="add-resource-drawer" on:close={drawer?.closeDrawer} tooltip="Resources represent connections to third party systems. Learn more on how to integrate external APIs." @@ -105,6 +108,7 @@ express={expressOAuthSetup} {workspace} {fillPath} + {native} /> {#snippet actions()} <div class="flex gap-1"> @@ -124,7 +128,7 @@ {disabled} onClick={() => appConnectInner?.next()} > - {#if step == 2 && !manual} + {#if (step == 2 && !manual) || native} Connect {:else if step == 1} Next diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index 4dc05972ca..069965b4e7 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -53,6 +53,8 @@ import ResourcePathHint from './ResourcePathHint.svelte' 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' const operatingWorkspace = useOperatingWorkspace() @@ -73,6 +75,11 @@ * Opt-in: without it this flow still refuses to write over anything. */ fillPath?: string + /** + * Connect a native trigger account: only the path is asked, and `connect` runs the + * popup through the trigger service's OAuth app, whose callback saves the connection. + */ + native?: NativeConnect } let { @@ -83,7 +90,8 @@ manual = $bindable(true), express = false, workspace = undefined, - fillPath = undefined + fillPath = undefined, + native = undefined }: Props = $props() let effectiveWorkspace = $derived(workspace ?? $operatingWorkspace!) @@ -178,7 +186,6 @@ * toggling back from client-credentials can restore them. */ let instanceScopes: string[] = $state([]) let extra_params: [string, string][] = [] - let responseExtra: Record<string, string> = $state({}) let path: string = $state('') let description = $state('') let labels: string[] | undefined = $state(undefined) @@ -252,6 +259,16 @@ return registryEntryFor(connectClient, resourceType) } + let resourceTypeAlternative = $derived(AI_RESOURCE_TYPE_ALTERNATIVES[resourceType]) + + function switchToResourceType(rt: string) { + connectClient = rt + resourceType = rt + linkedSecrets = [] + args = {} + getResourceTypeInfo() + } + /** The static registry declares this provider supports client credentials */ function registryCcCapable(): boolean { return registryCcCapableFor(connectClient, resourceType) @@ -419,6 +436,13 @@ let pathError = $state('') export async function open(rt?: string) { + if (native) { + resourceType = rt ?? '' + manual = false + path = '' + step = 4 + return + } if (!rt) { loadResourceTypes() loadPopularity() @@ -507,7 +531,7 @@ // authorize endpoint counts; `google` itself is a login provider, not a registry entry. run(() => { isGoogleSignin = - step == 2 && + (step == 2 || (!!native && step == 4)) && !manual && (resourceType == 'google' || (registryEntryFor(resourceType)?.auth_url?.startsWith('https://accounts.google.com/') ?? @@ -532,7 +556,7 @@ clientSecret.trim() == '' || (!!ccInstanceMeta && ccInstance.trim() == '')))) || step == 3 || - (step == 4 && pathError != '') || + (step == 4 && (pathError != '' || (!!native && !path))) || !isValid }) @@ -658,7 +682,7 @@ resourceType = stripSandboxSuffix(connectClient) value = data.res.access_token! valueToken = data.res - responseExtra = data.extra ?? {} + Object.assign(args, data.res.resource_fields ?? {}) fillGeneratedDescription() step = 4 // `fillPath` decides the path as surely as express does, so neither stops here. @@ -729,6 +753,16 @@ } } export async function next() { + if (native) { + step = 3 + try { + await native.connect(path) + dispatch('close') + } catch { + step = 4 + } + return + } if (step == 1) { linkedSecrets = [] // Both branches: the OAuth one fills `resourceFields` into the same map, and fields @@ -935,13 +969,10 @@ } } } - if (resourceType === 'quickbooks' && responseExtra['realmId']) { - args['realmId'] = responseExtra['realmId'] - } - let account: number | undefined = undefined + let accountData: any = undefined if (valueToken?.expires_in != undefined) { - const accountData: any = { + accountData = { refresh_token: valueToken.refresh_token ?? '', expires_in: valueToken.expires_in, client: connectClient, @@ -970,13 +1001,6 @@ accountData.cc_token_url = tokenUrl.trim() } } - - account = Number( - await OauthService.createAccount({ - workspace: effectiveWorkspace, - requestBody: accountData - }) - ) } // A copy: the form is still mounted and bound to `args` across the awaits below, and @@ -995,21 +1019,27 @@ // OAuth flow: single secret variable for the token if (typeof value == 'string' && value != '' && !value.startsWith('$var:')) { savedVariableCount++ - await VariableService.createVariable({ - workspace: effectiveWorkspace, - requestBody: { - path, - value: value, - is_secret: true, - description: emptyString(description) - ? `OAuth token for ${resourceType}` - : description, - is_oauth: true, - account: account, - ws_specific: wsSpecific - } - }) - resourceValue['token'] = `$var:${path}` + const tokenVariable = { + path, + value: value, + is_secret: true, + description: emptyString(description) ? `OAuth token for ${resourceType}` : description, + is_oauth: true, + ws_specific: wsSpecific + } + if (accountData) { + // Creates the variable with the account it refreshes through, in one transaction. + await OauthService.createAccount({ + workspace: effectiveWorkspace, + requestBody: { ...accountData, variable: tokenVariable } + }) + } else { + await VariableService.createVariable({ + workspace: effectiveWorkspace, + requestBody: tokenVariable + }) + } + resourceValue['token'] = `$var:${tokenVariable.path}` } } else if (linkedSecrets.length === 1) { // Single secret: use the resource path as variable name (original behavior) @@ -1458,6 +1488,14 @@ Acquire the token automatically via client credentials instead </button> {/if} + {#if resourceTypeAlternative} + <button + onclick={() => switchToResourceType(resourceTypeAlternative.resourceType)} + class="text-xs font-normal text-accent w-fit -mt-4" + > + {resourceTypeAlternative.label} + </button> + {/if} <!-- The form is a section of its own, not just the next field: it needs more of a break from the description than the uniform gap gives. --> <div class="mt-2"> @@ -1654,47 +1692,56 @@ <Label label="Path"> <Path initialPath="" - namePlaceholder={defaultName} + namePlaceholder={native?.defaultName ?? defaultName} + fullNamePlaceholder={native?.defaultName} bind:error={pathError} bind:path kind="resource" /> </Label> - <LabelsInput bind:labels class="-mt-5" /> - {#if deployTo} - <Label - label="Workspace specific" - tooltip="Prevents this resource from being deployed to prod/staging" - > - <Toggle bind:checked={wsSpecific} /> - </Label> - {/if} - <!-- Not for express or `fillPath`, which save as soon as the token arrives: the fields + {#if native} + <p class="text-xs text-secondary"> + The account is saved as a resource and its token as a variable at this path. Anyone who can + read them can create triggers that act as this account. + </p> + {:else} + <LabelsInput bind:labels class="-mt-5" /> + {#if deployTo} + <Label + label="Workspace specific" + tooltip="Prevents this resource from being deployed to prod/staging" + > + <Toggle bind:checked={wsSpecific} /> + </Label> + {/if} + <!-- Not for express or `fillPath`, which save as soon as the token arrives: the fields are then filled by editing the resource. --> - {#if step == 4 && !manual && !express && !fillPath && resourceFields.length > 0} - <Label - label="Connection details" - tooltip="Saved on the resource with the token, and editable later" - class="mt-6" - > - <SchemaForm onlyMaskPassword noDelete schema={resourceFieldsSchema} bind:args /> - </Label> - {/if} - {#if apiTokenApps[resourceType] || !manual} - <ul class="mt-6"> - <li class="text-xs text-primary font-normal"> - 1. A secret variable containing the {apiTokenApps[resourceType]?.linkedSecret ?? 'token'} - <span class="font-semibold text-emphasis">{truncateRev(value, 5, '*****')}</span> - will be stored a - <span class="font-mono whitespace-nowrap text-emphasis">{path}</span>. - </li> - <li class="mt-2 text-xs text-primary font-normal"> - 2. The resource containing that token will be stored at the same path <span - class="font-mono whitespace-nowrap text-emphasis">{path}</span - >. The Variable and Resource will be "linked together", they will be deleted and renamed - together. - </li></ul - > + {#if step == 4 && !manual && !express && !fillPath && resourceFields.length > 0} + <Label + label="Connection details" + tooltip="Saved on the resource with the token, and editable later" + class="mt-6" + > + <SchemaForm onlyMaskPassword noDelete schema={resourceFieldsSchema} bind:args /> + </Label> + {/if} + {#if apiTokenApps[resourceType] || !manual} + <ul class="mt-6"> + <li class="text-xs text-primary font-normal"> + 1. A secret variable containing the {apiTokenApps[resourceType]?.linkedSecret ?? + 'token'} + <span class="font-semibold text-emphasis">{truncateRev(value, 5, '*****')}</span> + will be stored a + <span class="font-mono whitespace-nowrap text-emphasis">{path}</span>. + </li> + <li class="mt-2 text-xs text-primary font-normal"> + 2. The resource containing that token will be stored at the same path <span + class="font-mono whitespace-nowrap text-emphasis">{path}</span + >. The Variable and Resource will be "linked together", they will be deleted and renamed + together. + </li></ul + > + {/if} {/if} {/if} {/if} diff --git a/frontend/src/lib/components/AutosaveIndicator.svelte b/frontend/src/lib/components/AutosaveIndicator.svelte index 1e318ed9b2..c6aa20ab48 100644 --- a/frontend/src/lib/components/AutosaveIndicator.svelte +++ b/frontend/src/lib/components/AutosaveIndicator.svelte @@ -25,7 +25,8 @@ // Count of OTHER users with a draft here. >0 makes the on-mount hint // take priority over "Loaded from draft" and offers "See others' drafts". othersDraftsCount = 0, - onOpenOthersDrafts + onOpenOthersDrafts, + compact = false }: { workspace: string itemKind: UserDraftItemKind @@ -35,6 +36,8 @@ loadedFromDraft?: boolean othersDraftsCount?: number onOpenOthersDrafts?: () => void + /** The icon alone, for a bar with no room for the label, which stays for screen readers. */ + compact?: boolean } = $props() // Reactive to the in-memory draft appearing/disappearing. @@ -365,7 +368,7 @@ </Popover> {#if label} <span - class="relative text-2xs pr-1.5 {labelIsError + class="{compact ? 'sr-only' : 'relative'} text-2xs pr-1.5 {labelIsError ? 'text-red-500 font-semibold' : 'text-secondary'}">{label}</span > diff --git a/frontend/src/lib/components/AutoscalingConfigEditor.svelte b/frontend/src/lib/components/AutoscalingConfigEditor.svelte index 885b6dd55c..a8884657cd 100644 --- a/frontend/src/lib/components/AutoscalingConfigEditor.svelte +++ b/frontend/src/lib/components/AutoscalingConfigEditor.svelte @@ -16,8 +16,12 @@ import ScriptPicker from './ScriptPicker.svelte' import { sendUserToast } from '$lib/toast' import { untrack } from 'svelte' + import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte' + import { createAsyncConfirmationModal } from './common/confirmationModal/asyncConfirmationModal.svelte' + import Portal from './Portal.svelte' interface Props { + worker_group: string config: AutoscalingConfig | undefined worker_tags: string[] | undefined /** Whether the draft config gives the group any tags (worker_tags or dedicated workers). */ @@ -29,6 +33,7 @@ } let { + worker_group, config = $bindable(), worker_tags, group_has_tags, @@ -66,6 +71,54 @@ } } + const confirmationModal = createAsyncConfirmationModal() + + async function testScaling() { + const integration = config?.integration + if (!integration) return + if (integration.type === 'script' && !integration['path']) { + sendUserToast('Please select a script before testing scaling', true) + return + } + const desired_workers = test_input + let job_id: string | null | undefined + let failed = false + const confirmed = await confirmationModal.ask({ + title: `Scale ${worker_group} to ${desired_workers} workers?`, + confirmationText: 'Scale now', + type: 'reload', + children: + integration.type === 'kubernetes' + ? `This sets the worker group's replica count to ${desired_workers} now. If autoscaling is enabled, it adjusts the count again on its next pass.` + : `This runs the integration script once with desired_workers set to ${desired_workers}, and it scales the group if the script does. If autoscaling is enabled, it adjusts the count again on its next pass.`, + onConfirmed: async () => { + try { + job_id = ( + await ConfigService.testAutoscaling({ + workerGroup: worker_group, + requestBody: { desired_workers, integration: $state.snapshot(integration) } + }) + ).job_id + } catch (e: any) { + failed = true + sendUserToast('Test scaling failed', true, [], e?.body ?? e?.message) + } + } + }) + if (!confirmed || failed) return + if (job_id) { + const id = job_id + sendUserToast('Autoscaling script queued in the admins workspace', false, [ + { + label: 'See job', + callback: () => window.open('/run/' + id + '?workspace=admins', '_blank') + } + ]) + } else { + sendUserToast(`Scaled ${worker_group} to ${desired_workers} workers`) + } + } + let noTagsToCount = $derived(!!config?.enabled && !group_has_tags && !config.custom_tags?.length) let collapsed: boolean = $state(untrack(() => !noTagsToCount)) @@ -266,22 +319,11 @@ /> <div class="flex flex-row gap-2 justify-end mt-4"> - <Button - variant="default" - unifiedSize="md" - onclick={() => { - if (!config?.integration?.['path']) { - sendUserToast('Please select a script before testing scaling', true) - return - } - if (!config?.integration?.['tag']) { - sendUserToast('Please select a custom tag before testing scaling', true) - return - } - }}>Test scaling</Button + <Button variant="default" unifiedSize="md" {disabled} onclick={testScaling} + >Test scaling</Button > <div class="flex text-xs flex-row gap-2 items-center"> - <input class="!w-16" type="number" bind:value={test_input} /> + <input class="!w-16" type="number" min="0" bind:value={test_input} /> workers </div> </div> @@ -317,9 +359,11 @@ </div> <div class="flex flex-row gap-2 justify-end"> - <Button unifiedSize="md" variant="default">Test scaling</Button> + <Button unifiedSize="md" variant="default" {disabled} onclick={testScaling} + >Test scaling</Button + > <div class="flex text-xs flex-row gap-2 items-center"> - <input class="!w-16" type="number" bind:value={test_input} /> + <input class="!w-16" type="number" min="0" bind:value={test_input} /> workers </div> </div> @@ -547,3 +591,7 @@ </Label> </Section> </Section> + +<Portal> + <ConfirmationModal {...confirmationModal.props} /> +</Portal> diff --git a/frontend/src/lib/components/CompareDrafts.svelte b/frontend/src/lib/components/CompareDrafts.svelte index a05511ea42..976f82c382 100644 --- a/frontend/src/lib/components/CompareDrafts.svelte +++ b/frontend/src/lib/components/CompareDrafts.svelte @@ -34,6 +34,7 @@ } from '$lib/workspaceDrafts.svelte' import type { Kind as LayoutKind } from '$lib/utils_deployable' import { userStore, userWorkspaces } from '$lib/stores' + import { capabilitiesIn } from '$lib/roleCapabilities' import { childWorkspaceNoun } from '$lib/utils/devWorkspaceLabel' interface Props { @@ -329,7 +330,12 @@ workspaceDeployPerm, visibleItems .filter((i) => selectedItems.includes(i.key) && isDeployable(i)) - .map((i) => i.draftKind) + .map((i) => i.draftKind), + capabilitiesIn( + // Superadmin is global; a workspace's admin flag is not. + { is_super_admin: $userStore?.is_super_admin }, + $userWorkspaces.find((w) => w.id === currentWorkspaceId) + ) ) ) // Select all on the first non-empty load (acting on everything is the common diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 5a22ed012d..096bc290c4 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -37,6 +37,7 @@ import WorkspaceDeployItemSummary from './WorkspaceDeployItemSummary.svelte' import ParentWorkspaceProtectionAlert from './ParentWorkspaceProtectionAlert.svelte' import { userWorkspaces, workspaceStore } from '$lib/stores' + import { capabilitiesIn } from '$lib/roleCapabilities' import type { Kind } from '$lib/utils_deployable' import { @@ -289,7 +290,8 @@ path, value: v.value ?? '', is_secret: v.is_secret ?? false, - description: v.description ?? '' + description: v.description ?? '', + value_valid_until: v.value_valid_until ?? undefined } }) } @@ -1090,7 +1092,12 @@ workspaceDeployPerm, (comparison?.diffs ?? []) .filter((d) => selectedItems.includes(getItemKey(d))) - .map((d) => d.kind) + .map((d) => d.kind), + capabilitiesIn( + // Superadmin is global; a workspace's admin flag is not. + { is_super_admin: $userStore?.is_super_admin }, + $userWorkspaces.find((w) => w.id == deployTargetWorkspace) + ) ) ) diff --git a/frontend/src/lib/components/ContextualVariableEditor.svelte b/frontend/src/lib/components/ContextualVariableEditor.svelte index 9adde76e74..f09b52b571 100644 --- a/frontend/src/lib/components/ContextualVariableEditor.svelte +++ b/frontend/src/lib/components/ContextualVariableEditor.svelte @@ -9,9 +9,14 @@ import autosize from '$lib/autosize' import Label from './Label.svelte' import TextInput from './text_input/TextInput.svelte' - import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { + useOperatingWorkspace, + useReadOnlyWorkspace + } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() + // An editor opened in Build stays open when the session switches to Use. + const readOnly = useReadOnlyWorkspace() const dispatch = createEventDispatcher() @@ -36,6 +41,7 @@ let drawer: Drawer | undefined = $state() async function updateVariable(): Promise<void> { + if (readOnly($operatingWorkspace)) return await WorkspaceService.setEnvironmentVariable({ workspace: $operatingWorkspace!, requestBody: { @@ -79,7 +85,7 @@ {#snippet actions()} <Button on:click={() => updateVariable()} - disabled={value === '' || name === ''} + disabled={value === '' || name === '' || readOnly($operatingWorkspace)} startIcon={{ icon: Save }} variant="accent" unifiedSize="md" diff --git a/frontend/src/lib/components/DeployWorkspace.svelte b/frontend/src/lib/components/DeployWorkspace.svelte index daf944ff37..4c7fae7ccd 100644 --- a/frontend/src/lib/components/DeployWorkspace.svelte +++ b/frontend/src/lib/components/DeployWorkspace.svelte @@ -283,6 +283,8 @@ result.push({ kind: 'script', path: runnable.path }) } else if (runnable.runType == 'flow') { result.push({ kind: 'flow', path: runnable.path }) + } else if (runnable.runType == 'agent') { + result.push({ kind: 'resource', path: runnable.path }) } } } diff --git a/frontend/src/lib/components/DraftBadge.svelte b/frontend/src/lib/components/DraftBadge.svelte index 22f7c4e55a..4d21e81b29 100644 --- a/frontend/src/lib/components/DraftBadge.svelte +++ b/frontend/src/lib/components/DraftBadge.svelte @@ -18,7 +18,8 @@ import { goto } from '$lib/navigation' import { OtherUserDraftLoad, editRouteFor } from '$lib/components/otherUserDraftLoad.svelte' import { fetchDeployedValueForDiff } from '$lib/components/otherUserDraftDiff' - import { userStore } from '$lib/stores' + import { roleCapabilities, userStore } from '$lib/stores' + import { roleCanAuthor } from '$lib/editRights' type DraftUser = { username?: string | null } @@ -116,6 +117,10 @@ // Inline actions need full context to fetch and fork drafts. 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) + ) const kindLabel = $derived( itemKind === 'flow' ? 'flow' : itemKind === 'app' || itemKind === 'raw_app' ? 'app' : 'script' @@ -303,7 +308,7 @@ </span> {#if actionsEnabled && isSelf} <!-- Own draft: jump straight into the editor. --> - {#if !$userStore?.operator && itemKind && path} + {#if canOpenEditor && itemKind && path} <Button variant="subtle" size="xs3" @@ -326,9 +331,9 @@ View Diff </Button> {/if} - <!-- Operators can't edit items, so Load is hidden (View Diff stays, it's - read-only). `allowFork=false` (deploy/review page) hides it too. --> - {#if allowFork && !$userStore?.operator} + <!-- Load is hidden from a role that can't edit the item (View Diff stays, + it's read-only). `allowFork=false` (deploy/review page) hides it too. --> + {#if allowFork && canOpenEditor} <Button variant="subtle" size="xs3" diff --git a/frontend/src/lib/components/DropdownV2.svelte b/frontend/src/lib/components/DropdownV2.svelte index 1d86519293..e9fbf71ab8 100644 --- a/frontend/src/lib/components/DropdownV2.svelte +++ b/frontend/src/lib/components/DropdownV2.svelte @@ -99,7 +99,10 @@ } = createDropdownMenu({ portal: untrack(() => hostPortal()), positioning: { - placement: untrack(() => placement) + placement: untrack(() => placement), + // Caps the menu at the room the viewport has left, so a list taller than that scrolls + // instead of flipping past the screen edge. A custom menu sizes itself. + fitViewport: untrack(() => !customMenu) }, closeOnItemClick: untrack(() => closeOnItemClick), loop: true, @@ -137,13 +140,12 @@ if (afterClose) setTimeout(afterClose, 10) } - async function computeItems(): Promise<Item[]> { - if (typeof items === 'function') { - const result = await items() - return Array.isArray(result) ? result.filter((item) => !item.hide) : [] - } else { - return items.filter((item) => !item.hide) - } + function visible(result: Item[] | undefined): Item[] { + return Array.isArray(result) ? result.filter((item) => !item.hide) : [] + } + function computeItems(): Item[] | Promise<Item[]> { + const result = typeof items === 'function' ? items() : items + return result instanceof Promise ? result.then(visible) : visible(result) } async function getMenuElements(): Promise<HTMLElement[]> { // Runs on every pointerdown anywhere, for every mounted dropdown. Skip the @@ -200,15 +202,15 @@ <div use:melt={$menuEl} data-menu - class="z-[6000] transition-all duration-100" + class="z-[6000] transition-all duration-100 flex flex-col" transition:placementFly={{ duration: enableFlyTransition ? 100 : 0, placement }} > {#if customMenu} {@render menu?.({ item, close, builders })} {:else} <div - class="bg-surface-tertiary dark:border w-56 origin-top-right rounded-lg shadow-lg focus:outline-none overflow-y-auto py-1" - style={`${customWidth ? `width: ${customWidth}px;` : ''} max-height: ${maxHeight || '50vh'};`} + class="bg-surface-tertiary dark:border w-56 min-h-0 origin-top-right rounded-lg shadow-lg focus:outline-none overflow-y-auto py-1" + style={`${customWidth ? `width: ${customWidth}px;` : ''} max-height: ${maxHeight || '80vh'};`} > <DropdownV2Inner {aiId} items={computeItems} meltItem={item} {builders} {close} /> </div> diff --git a/frontend/src/lib/components/DropdownV2Inner.svelte b/frontend/src/lib/components/DropdownV2Inner.svelte index 70ed83398d..138fd072b6 100644 --- a/frontend/src/lib/components/DropdownV2Inner.svelte +++ b/frontend/src/lib/components/DropdownV2Inner.svelte @@ -7,10 +7,11 @@ import type { MenubarMenuElements, createDropdownMenu } from '@melt-ui/svelte' import type { Item } from '$lib/utils' import { Tooltip } from './meltComponents' + import { untrack } from 'svelte' interface Props { aiId?: string - items?: Item[] | (() => Item[]) | (() => Promise<Item[]>) + items?: Item[] | (() => Item[] | Promise<Item[]>) meltItem: MenubarMenuElements['item'] builders?: ReturnType<typeof createDropdownMenu>['builders'] close?: (afterClose?: () => void) => void @@ -18,16 +19,17 @@ let { aiId, items = [], meltItem, builders, close }: Props = $props() - let computedItems: Item[] | undefined = $state(undefined) - async function computeItems() { - if (typeof items === 'function') { - computedItems = ((await items()) ?? []).filter((item) => !item.hide) - } else { - computedItems = items.filter((item) => !item.hide) - } + function visible(result: Item[] | undefined): Item[] { + return (result ?? []).filter((item) => !item.hide) } - computeItems() + // Items returned synchronously render on the first frame: awaiting them would show the + // spinner first, the popover would be placed for the spinner's height, then flip. + const initial = untrack(() => (typeof items === 'function' ? items() : items)) + let computedItems: Item[] | undefined = $state( + initial instanceof Promise ? undefined : visible(initial) + ) + if (initial instanceof Promise) initial.then((result) => (computedItems = visible(result))) </script> {#snippet menuItem(item: Item)} @@ -45,7 +47,8 @@ item?.disabled && 'text-disabled cursor-not-allowed pointer-events-none', item?.type === 'delete' && !item?.disabled && - 'text-red-600 dark:text-red-400 data-[highlighted]:bg-red-500/10 dark:data-[highlighted]:bg-red-900/80 dark:data-[highlighted]:text-red-300 ' + 'text-red-600 dark:text-red-400 data-[highlighted]:bg-red-500/10 dark:data-[highlighted]:bg-red-900/80 dark:data-[highlighted]:text-red-300 ', + item?.type === 'ai' && !item?.disabled && 'text-ai' )} item={meltItem} aiId={`${aiId ? `${aiId}-${item.displayName}` : undefined}`} @@ -103,6 +106,11 @@ {#if item.separatorTop} <div class="my-1 border-t border-border-light"></div> {/if} + {#if item.sectionTitle} + <p class="px-4 pt-1.5 pb-1 text-2xs uppercase tracking-wide text-secondary"> + {item.sectionTitle} + </p> + {/if} {#if (item.submenuItems || item.customSubmenu) && builders} <DropdownSubmenuItem {item} {builders} {meltItem} close={close ?? (() => {})} /> {:else if item.disabled && item.tooltip} diff --git a/frontend/src/lib/components/EditableSchemaForm.svelte b/frontend/src/lib/components/EditableSchemaForm.svelte index 11429cb6fe..fd15c7f9e7 100644 --- a/frontend/src/lib/components/EditableSchemaForm.svelte +++ b/frontend/src/lib/components/EditableSchemaForm.svelte @@ -19,7 +19,7 @@ import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import Label from './Label.svelte' import { sendUserToast } from '$lib/toast' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import Toggle from './Toggle.svelte' import { DynamicInput, @@ -36,14 +36,12 @@ import Section from '$lib/components/Section.svelte' import Editor from './Editor.svelte' import AddPropertyV2 from './schema/AddPropertyV2.svelte' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() - const operatorBuilderFlows = useOperatorBuilderFlows() + const roleCaps = useRoleCapabilities() + // Dynamic input functions are inline code a compose-only flow role cannot author. + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') // export let openEditTab: () => void = () => {} const dispatch = createEventDispatcher() @@ -482,7 +480,7 @@ dynCode, dynLang, deployedFlowPath, - operatingUser.current?.operator + !$roleCaps.code )} prettifyHeader={isAppInput} disabled={!!previewSchema} @@ -496,7 +494,7 @@ {@render runButton?.()} - {#if dynamicFunctions.length > 0 && !$operatorBuilderFlows} + {#if dynamicFunctions.length > 0 && !composeOnlyFlows} <Section label="Dynamic input functions" collapsable={true} @@ -825,7 +823,7 @@ {#each typeOptions as x} <ToggleButton value={x[1]} label={x[0]} {item} /> {/each} - {#if showDynOpt && !$operatorBuilderFlows} + {#if showDynOpt && !composeOnlyFlows} {#each DYNAMIC_OPTIONS as x} <ToggleButton value={x[1]} label={x[0]} {item} /> {/each} diff --git a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte index 6d95ad0c82..bddf68fc0d 100644 --- a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte +++ b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte @@ -16,6 +16,15 @@ 'trigger_path' ] + /** Arguments the variable expiration sweep always sends. */ + const variableExpirationHandlerArgs = [ + 'workspace_id', + 'variable_path', + 'description', + 'value_valid_until', + 'is_secret' + ] + export const slackErrorHandlerHubPathEnding = '/workspace-or-schedule-error-handler-slack' </script> @@ -78,6 +87,7 @@ /** Offer the instance critical alert channels as a destination. Workspace-level * error handling only: schedules and triggers have no such setting. */ showInstanceAlerts?: boolean + customRequiresEE?: boolean } let { @@ -90,9 +100,15 @@ customTabTooltip, noMargin = false, workspace = undefined, - showInstanceAlerts = false + showInstanceAlerts = false, + customRequiresEE = true }: Props = $props() + let isVariableExpiration = $derived(errorOrRecovery === 'variableExpiration') + let handlerArgs = $derived( + isVariableExpiration ? variableExpirationHandlerArgs : errorHandlerArgs + ) + let effectiveWorkspace = $derived(workspace ?? $operatingWorkspace) // Carry the workspace onto the "create from template" route, so the handler script is // created where this handler is saved. `customScriptTemplate` already has a query string. @@ -156,7 +172,11 @@ let submitted_job = await testJobFunction({ workspace: effectiveWorkspace!, requestBody: { - hub_script_path: draft[platform].path, + // Ours are not test-runnable presets; the error handler's checks the same + // token and channel. + hub_script_path: isVariableExpiration + ? builtinHubPath('error', platform) + : draft[platform].path, channel: channel, test_msg: `This is a notification to test the connection between ${platform} and Windmill workspace '${effectiveWorkspace!}'` } @@ -250,7 +270,7 @@ $effect(() => { const { path, kind } = draft.custom path && - loadHandlerScriptArgs(path, kind, errorHandlerArgs).then( + loadHandlerScriptArgs(path, kind, handlerArgs).then( (schema) => (customHandlerSchema = schema) ) }) @@ -258,7 +278,7 @@ $effect(() => { const path = draft.slack.path path && - loadHandlerScriptArgs(path, 'script', [...errorHandlerArgs, 'slack']).then( + loadHandlerScriptArgs(path, 'script', [...handlerArgs, 'slack']).then( (schema) => (slackHandlerSchema = schema) ) }) @@ -269,7 +289,9 @@ {#snippet children({ item })} <ToggleButton label="Slack" value="slack" {item} disabled={!isEditable} /> <ToggleButton label="Teams" value="teams" {item} disabled={!isEditable} /> - <ToggleButton label="Email" value="email" {item} disabled={!isEditable} /> + {#if !isVariableExpiration} + <ToggleButton label="Email" value="email" {item} disabled={!isEditable} /> + {/if} <ToggleButton label="Custom" value="custom" @@ -294,7 +316,7 @@ <div class="flex flex-col gap-1"> <div class="flex flex-row"> <ScriptPicker - disabled={!isEditable || !$enterpriseLicense} + disabled={!isEditable || (customRequiresEE && !$enterpriseLicense)} kinds={['script', 'failure']} allowFlow={true} bind:scriptPath={draft.custom.path} @@ -343,7 +365,7 @@ /> {/await} {#if customHandlerSchema && customHandlerSchema.properties && Object.keys(customHandlerSchema.properties).length === 0} - <div class="text-xs text-secondary">This error handler takes no extra arguments</div> + <div class="text-xs text-secondary">This handler takes no extra arguments</div> {/if} </div> {/if} @@ -381,6 +403,7 @@ }} bind:args={draft.slack.args} shouldHideNoInputs + compact className="text-xs" /> {/await} diff --git a/frontend/src/lib/components/ExploreAssetButton.svelte b/frontend/src/lib/components/ExploreAssetButton.svelte index d48688a871..de0d70e26e 100644 --- a/frontend/src/lib/components/ExploreAssetButton.svelte +++ b/frontend/src/lib/components/ExploreAssetButton.svelte @@ -37,14 +37,11 @@ import { isS3Uri } from '$lib/utils' import { Database, File, HardDriveIcon } from 'lucide-svelte' import DucklakeIcon from './icons/DucklakeIcon.svelte' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) + const roleCaps = useRoleCapabilities() const { asset, @@ -83,7 +80,7 @@ </script> <Button - disabled={actingUser?.operator || disabled} + disabled={!$roleCaps.code || disabled} unifiedSize={'md'} variant={buttonVariant} wrapperClasses={className} diff --git a/frontend/src/lib/components/FilterSearchbar.svelte b/frontend/src/lib/components/FilterSearchbar.svelte index 0a65701b06..b496ac1088 100644 --- a/frontend/src/lib/components/FilterSearchbar.svelte +++ b/frontend/src/lib/components/FilterSearchbar.svelte @@ -71,6 +71,19 @@ return Object.values(val).some((v) => v !== undefined && v !== null && v !== '' && v !== false) } + /** + * Whether typed text names a filter: every word of the query must occur in its label or + * key, in any order, so "archive" and "archived only" both find "Only archived". + */ + export function filterMatchesQuery(key: string, filter: FilterSchema, query: string): boolean { + const words = query.replace(/\\(.)/g, '$1').toLowerCase().split(/\s+/).filter(Boolean) + const haystack = [filter.label, key, key.replaceAll('_', ' ')] + .filter(Boolean) + .join(' ') + .toLowerCase() + return words.every((w) => haystack.includes(w)) + } + /** * Converts a FilterSchemaRec to a Zod schema for validation */ @@ -437,12 +450,7 @@ return Object.entries(schema) .filter(([_, s]) => !s.hidden) .filter(([k, _]) => !(k in value)) - .filter(([k, filterSchema]) => { - if (!searchText) return true - const label = (filterSchema.label || k).toLowerCase() - const key = k.toLowerCase() - return label.includes(searchText) || key.includes(searchText) - }) + .filter(([k, filterSchema]) => filterMatchesQuery(k, filterSchema, searchText)) .map(([key, filterSchema]) => ({ type: 'filter' as const, key, @@ -542,6 +550,15 @@ return [] }) + // Free-text mode keeps the keyboard for the surrounding list, but a term that names a + // filter ("archive" → "Only archived") still lists the matching filters, click-only. + let freeTextFilterHint = $derived( + open && + !dropdownVisible && + currentTextSegment.text.trim().length >= 3 && + menuItems.some((i) => i.type === 'filter') + ) + // Reset highlighted index when menu items change $effect(() => { menuItems @@ -647,7 +664,13 @@ function handleKeyDown(e: KeyboardEvent) { // In free-text mode the dropdown is hidden; let arrow/enter keys pass through to // the surrounding UI (e.g. list navigation) rather than steering a hidden menu. - if (!dropdownVisible) return + if (!dropdownVisible) { + // The hint sits over the list's first rows, so it gets out of the way once the list + // is being navigated; the next typed character brings it back. + if (freeTextFilterHint && ['Escape', 'ArrowUp', 'ArrowDown', 'Enter'].includes(e.key)) + open = false + return + } if (e.key === 'Escape') { open = false return @@ -786,7 +809,7 @@ </div> <GenericDropdown - open={dropdownVisible} + open={dropdownVisible || freeTextFilterHint} instantClose={hideDropdownOnFreeText} getInputRect={() => { const r = inputElement?.getBoundingClientRect() ?? new DOMRect() @@ -800,15 +823,19 @@ <!-- svelte-ignore a11y_click_events_have_key_events --> <div class="py-1 p-2 overflow-y-auto" onmousedown={(e) => e.stopPropagation()}> {#if !currentTag || !schema[currentTag]} - {#if presets.length} - <div class="text-xs px-2 my-2 font-bold">Presets</div> + {#if presets.length && !freeTextFilterHint} + <div class="text-2xs uppercase tracking-wide font-semibold text-secondary px-2 my-2"> + Presets + </div> <div class="mb-3 px-2 flex gap-2 flex-wrap max-h-24 overflow-y-auto"> {#each presets as preset} {@render presetTag(preset)} {/each} </div> {/if} - <div class="text-xs px-2 my-2 font-bold">Filters</div> + <div class="text-2xs uppercase tracking-wide font-semibold text-secondary px-2 my-2"> + Filters + </div> {#each menuItems as item, index} {#if item.type === 'filter' && item.filterSchema} {@render menuItem({ @@ -816,7 +843,7 @@ onClick: item.onClick, label: item.filterSchema.label || item.key, description: item.filterSchema.description, - highlighted: index === highlightedIndex + highlighted: index === highlightedIndex && !freeTextFilterHint })} {/if} {/each} @@ -947,18 +974,18 @@ <!-- svelte-ignore a11y_click_events_have_key_events --> <div class={twMerge( - 'py-1.5 px-2 rounded-md hover:bg-surface-hover cursor-pointer text-sm flex items-center gap-3', + 'py-1.5 px-2 rounded-md hover:bg-surface-hover cursor-pointer text-xs text-primary flex items-center gap-2', highlighted && 'bg-surface-hover' )} onclick={onClick} > {#if Icon} - <Icon size={16} class="inline" /> + <Icon size={14} class="inline shrink-0" /> {/if} <div class="inline flex-1 relative min-w-0"> - <div class="text-sm ellipsize">{label}</div> + <div class="ellipsize">{label}</div> {#if description} - <div class="text-xs text-hint">{description}</div> + <div class="text-2xs text-hint">{description}</div> {/if} </div> {#if onNegativeClick} diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index 73ce91083d..a3d70a157c 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -84,6 +84,7 @@ import { type TriggerContext, type ScheduleTrigger } from './triggers' import type { SavedAndModifiedValue } from './common/confirmationModal/unsavedTypes' import DeployButton from './DeployButton.svelte' + import OpenInSessionButton from './sessions/OpenInSessionButton.svelte' import { invalidateWorkspacePaths } from './PathNameAutocomplete.svelte' import type { Trigger } from './triggers/utils' import { deployTriggers, handleSelectTriggerFromKind } from './triggers/utils' @@ -117,13 +118,14 @@ import { UserDraft } from '$lib/userDraft.svelte' import { setOpenInSessionHandoff } from './sessions/openInSessionContext' import { getEditorStoragePath, setEditorStoragePath } from './editorStoragePathContext' - import { useEditRights, useOperatorBuilderFlows, useTriggerLock } from '$lib/operatorWriteRights' + import { useEditRights, useRoleCapabilities, useTriggerLock } from '$lib/operatorWriteRights' + import { capabilitiesIn } from '$lib/roleCapabilities' import { useOperatingUser, useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const triggerLock = useTriggerLock() - const operatorBuilderFlows = useOperatorBuilderFlows() + const roleCaps = useRoleCapabilities() const editRights = useEditRights() const operatingWorkspace = useOperatingWorkspace() @@ -133,8 +135,8 @@ let { initialPath = $bindable(''), /** The draft row's own path (the URL path). Unlike `initialPath`, which the - * route re-seeds from `draft_path` so the topbar shows the pending name, - * this stays where the item actually is. */ + * route re-seeds from a draft-only flow's `draft_path` so the topbar shows + * the pending name, this stays where the item actually is. */ userDraftPath = '', onTakeLatest = undefined, pathStoreInit = undefined, @@ -512,8 +514,7 @@ // the draft's `draft_path` so the topbar shows the pending name, which after // someone renames the item still names the old location. Comparing against // that fetches the row left behind there instead of the live one. - path: userDraftPath || initialPath, - withStarredInfo: true + path: userDraftPath || initialPath }) // A superseded opening must not write these: the current one would then render // and offer Take latest against the older head. @@ -561,11 +562,12 @@ const user = (await getUserExt(opWorkspace ?? '')) ?? (opWorkspace === $workspaceStore ? $userStore : undefined) - const operatorSettings = $userWorkspaces.find( - (w) => w.id === opWorkspace - )?.operator_settings + const caps = capabilitiesIn( + user, + $userWorkspaces.find((w) => w.id === opWorkspace) + ) agentCanWrite = Object.fromEntries( - draftAgents.map((a) => [a.path, agentDraftCanWrite(a, user, operatorSettings)]) + draftAgents.map((a) => [a.path, agentDraftCanWrite(a, user, caps)]) ) // The path is passed, so a draft that renames the agent is refused here too: a rename is // the agent editor's to deploy, and this dialog lists the agent under the path the flow @@ -906,6 +908,9 @@ // falling back to `$pathStore` in drawer mounts that carry no storage path. const sessionTargetPath = $derived(liveEditorDraftStoragePath || $pathStore) + const aiBuilderShown = $derived(!disableAi && customUi?.topBar?.aiBuilder != false) + const showFlowAiButton = $derived(aiBuilderShown && $roleCaps.flows !== 'compose') + const sessionOpen = $derived( sessionTargetPath ? { @@ -915,6 +920,7 @@ } : undefined ) + const headerSessionOpen = $derived(aiBuilderShown ? sessionOpen : undefined) // Reaches the AI entry point in a step's inline-editor toolbar, which the // recursive module wrapper sits too deep under to be handed a prop. `selected` @@ -1429,18 +1435,17 @@ readFieldsRecursively(flowStore.val) } }) - // Sync `$pathStore` from `flowStore.val.path` (which `initFlow` populates - // from the loaded flow — including the draft's rename, when there is one). - // This effect only tracks `flowStore.val.path`, so popover edits that go - // straight to `$pathStore` don't trigger it and aren't overwritten. - // Replaces the previous `$pathStore = initialPath` push (added in #2536 for - // the VSCode extension), which silently dropped any draft-renamed path - // because `initialPath` is the URL, not the loaded path. + // Sync `$pathStore` from the loaded flow: its staged `draft_path` when the + // draft has one, else its `path`. Seeding from `path` alone would make the + // effect below drop a staged move on every reload, and deploy would then + // create at a taken path. Only `flowStore.val.path` is tracked, so popover + // edits that go straight to `$pathStore` aren't overwritten. $effect.pre(() => { // `flowStore.val` is typed `OpenFlow` here but `initFlow` actually puts a // `Flow` (with `path`) in it. - const p = (flowStore.val as Flow | undefined)?.path - if (p) untrack(() => ($pathStore = p)) + const flow = flowStore.val as (Flow & { draft_path?: string }) | undefined + const p = flow?.path + if (p) untrack(() => ($pathStore = flow?.draft_path || p)) }) // Persist the user-typed path into the draft JSON as `draft_path` @@ -1609,6 +1614,7 @@ : undefined }} actions={flowHeaderActions} + sessionSource={headerSessionOpen} actionFolds={2} contexts={headerContexts} separator="none" @@ -1791,6 +1797,7 @@ {@render previewButtons()} {/if} + <OpenInSessionButton source={headerSessionOpen} /> <DeployButton on:save={async ({ detail }) => await handleSaveFlow(detail)} {loading} @@ -1873,9 +1880,7 @@ {forceTestTab} {highlightArg} aiChatOpen={aiChatManager.open} - showFlowAiButton={!disableAi && - customUi?.topBar?.aiBuilder != false && - !$operatorBuilderFlows} + {showFlowAiButton} toggleAiChat={() => aiChatManager.toggleOpen()} {sessionOpen} onOpenPreview={flowPreviewButtons?.openPreview} diff --git a/frontend/src/lib/components/FlowPreviewContent.svelte b/frontend/src/lib/components/FlowPreviewContent.svelte index e2de124c1d..67b1dbadff 100644 --- a/frontend/src/lib/components/FlowPreviewContent.svelte +++ b/frontend/src/lib/components/FlowPreviewContent.svelte @@ -49,9 +49,11 @@ useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { previewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' + import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const roleCaps = useRoleCapabilities() interface Props { previewMode: 'upTo' | 'whole' @@ -568,7 +570,7 @@ | ScriptLang | undefined, $initialPathStore, - operatingUser.current?.operator + !$roleCaps.code )} /> </div> diff --git a/frontend/src/lib/components/ForkWorkspaceBanner.svelte b/frontend/src/lib/components/ForkWorkspaceBanner.svelte index 11779afb11..1736520eed 100644 --- a/frontend/src/lib/components/ForkWorkspaceBanner.svelte +++ b/frontend/src/lib/components/ForkWorkspaceBanner.svelte @@ -3,7 +3,13 @@ import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import { Badge } from './common' import { AlertTriangle, ArrowDown, ArrowUp, Pencil } from 'lucide-svelte' - import { workspaceStore, userWorkspaces, userStore, type UserExt } from '$lib/stores' + import { + roleCapabilities, + workspaceStore, + userWorkspaces, + userStore, + type UserExt + } from '$lib/stores' import type { WorkspaceComparison } from '$lib/gen' import { fetchWorkspaceComparison } from '$lib/workspaceComparison' import { Button } from './common' @@ -27,18 +33,18 @@ // prefix) also avoids a parentless "Fork of ()" banner when the linkage is dropped. let isFork = $derived(parentWorkspaceId != null) let currentNoun = $derived(childWorkspaceNoun(currentWorkspaceData)) - // Operators run scripts and flows, they never deploy a fork, so the banner and - // its CTA are noise for them. Gates the fetches too, not just the markup: the - // fork/parent comparison is an expensive tally no operator can act on. + // A role without `code` never deploys a fork, so the banner and its CTA are noise + // for it. Gates the fetches too, not just the markup: the fork/parent comparison + // is an expensive tally such a role cannot act on. // - // Only a role fetched for the workspace we are on answers this. `$workspaceStore` + // Only a user fetched for the workspace we are on answers this. `$workspaceStore` // flips synchronously on a switch while `$userStore` still holds the workspace we // left, so trusting it unqualified would flash the banner at (and start the tally - // for) an operator entering a fork from a workspace where they are not one. - function isConfirmedNonOperator(user: UserExt | undefined, ws: string | undefined): boolean { - return !!user && !!ws && user.workspace_id === ws && !user.operator + // for) a restricted member entering a fork from a workspace where they are not one. + function isUserFor(user: UserExt | undefined, ws: string | undefined): boolean { + return !!user && !!ws && user.workspace_id === ws } - let isNotOperator = $derived(isConfirmedNonOperator($userStore, $workspaceStore)) + let isNotOperator = $derived(isUserFor($userStore, $workspaceStore) && $roleCapabilities.code) let showBanner = $derived(isFork && isNotOperator) // Drafts in this fork. When the fork is otherwise in sync with its parent, a diff --git a/frontend/src/lib/components/GroupEditor.svelte b/frontend/src/lib/components/GroupEditor.svelte index 2c256207e1..44d7dc5eb1 100644 --- a/frontend/src/lib/components/GroupEditor.svelte +++ b/frontend/src/lib/components/GroupEditor.svelte @@ -97,7 +97,10 @@ ) let group: Group | undefined let instance_group: InstanceGroup | undefined = $state() - let usernames: string[] = $state([]) + // Every username of the workspace, for the Add member picker: loaded on its first open, + // since it grows with the workspace and most opens of this editor add no one. + let usernames: string[] | undefined = $state() + let usernamesLoading = $state(false) let groupNames: string[] = $state([]) let loaded = $state(false) let reloadHistory = $state(0) @@ -140,9 +143,41 @@ } async function loadUsernames(): Promise<void> { - usernames = await UserService.listUsernames({ workspace: $operatingWorkspace! }) + if (usernames !== undefined || usernamesLoading) return + usernamesLoading = true + try { + usernames = await UserService.listUsernames({ workspace: $operatingWorkspace! }) + } catch (e) { + sendUserToast(`Could not load users: ${e?.body ?? e}`, true) + } finally { + usernamesLoading = false + } } + // From this many rows a table no longer fits its 320px box: it scrolls, and a search shows. + // Both follow every row, not the matching ones, so typing never resizes the drawer. + const MANY_ROWS = 8 + let memberSearch = $state('') + const memberQuery = $derived( + draft.members.length >= MANY_ROWS ? memberSearch.trim().toLowerCase() : '' + ) + const shownMembers = $derived( + draft.members + .filter((m) => !memberQuery || m.member_name.toLowerCase().includes(memberQuery)) + .sort((a, b) => a.member_name.localeCompare(b.member_name)) + ) + + let emailSearch = $state('') + const instanceEmails = $derived(instance_group?.emails ?? []) + const emailQuery = $derived( + instanceEmails.length >= MANY_ROWS ? emailSearch.trim().toLowerCase() : '' + ) + const shownEmails = $derived( + instanceEmails + .filter((e) => !emailQuery || e.toLowerCase().includes(emailQuery)) + .sort((a, b) => a.localeCompare(b)) + ) + async function loadGroupNames(): Promise<void> { groupNames = (await GroupService.listGroupNames({ workspace: $operatingWorkspace! })) ?? [] } @@ -156,7 +191,6 @@ } async function load() { - loadAside(loadUsernames) if (isNew) { loadAside(loadGroupNames) writeVerdict = true @@ -410,69 +444,87 @@ <Label label={`Members (${draft.members.length})`} tooltip={MEMBERS_EXPLAINER}> {#snippet action()} - {#if can_write && !restricted} - <Popover - placement="bottom-end" - onClose={() => { - memberToAdd = '' - newMemberRole = 'member' - }} - > - {#snippet trigger()} - <Button - variant="default" - unifiedSize="sm" - nonCaptureEvent={true} - startIcon={{ icon: Plus }} - > - Add member - </Button> - {/snippet} - {#snippet content({ close })} - <div class="flex flex-col w-72 p-4 gap-4"> - <span class="text-sm leading-6 font-semibold">Add a member</span> - <Label label="User"> - <Select - items={safeSelectItems( - usernames.filter((x) => !draft.members.some((m) => m.member_name === x)) - )} - bind:value={memberToAdd} - size="sm" - class="grow min-w-0" - /> - </Label> - <Label label="Role"> - <ToggleButtonGroup bind:selected={newMemberRole}> - {#snippet children({ item })} - <ToggleButton - value="member" - label="Member" - tooltip={ROLE_TOOLTIPS.member} - {item} - size="sm" - /> - <ToggleButton - value="admin" - label="Admin" - tooltip={ROLE_TOOLTIPS.admin} - {item} - size="sm" - /> - {/snippet} - </ToggleButtonGroup> - </Label> + <div class="flex items-center gap-2 min-w-0"> + {#if draft.members.length >= MANY_ROWS} + <TextInput + size="sm" + class="w-56 min-w-0" + bind:value={memberSearch} + inputProps={{ + type: 'search', + placeholder: `Search ${draft.members.length} members`, + 'aria-label': 'Search members' + }} + /> + {/if} + {#if can_write && !restricted} + <Popover + placement="bottom-end" + on:openChange={(e) => e.detail && loadUsernames()} + onClose={() => { + memberToAdd = '' + newMemberRole = 'member' + }} + > + {#snippet trigger()} <Button - variant="accent" + variant="default" unifiedSize="sm" - disabled={memberToAdd == ''} - onClick={() => addMember(close)} + nonCaptureEvent={true} + startIcon={{ icon: Plus }} > - Add + Add member </Button> - </div> - {/snippet} - </Popover> - {/if} + {/snippet} + {#snippet content({ close })} + <div class="flex flex-col w-72 p-4 gap-4"> + <span class="text-sm leading-6 font-semibold">Add a member</span> + <Label label="User"> + <Select + items={safeSelectItems( + (usernames ?? []).filter( + (x) => !draft.members.some((m) => m.member_name === x) + ) + )} + loading={usernamesLoading} + bind:value={memberToAdd} + size="sm" + class="grow min-w-0" + /> + </Label> + <Label label="Role"> + <ToggleButtonGroup bind:selected={newMemberRole}> + {#snippet children({ item })} + <ToggleButton + value="member" + label="Member" + tooltip={ROLE_TOOLTIPS.member} + {item} + size="sm" + /> + <ToggleButton + value="admin" + label="Admin" + tooltip={ROLE_TOOLTIPS.admin} + {item} + size="sm" + /> + {/snippet} + </ToggleButtonGroup> + </Label> + <Button + variant="accent" + unifiedSize="sm" + disabled={memberToAdd == ''} + onClick={() => addMember(close)} + > + Add + </Button> + </div> + {/snippet} + </Popover> + {/if} + </div> {/snippet} <div class="flex flex-col gap-2"> {#if can_write && restricted} @@ -480,19 +532,31 @@ {/if} {#if loaded} - <DataTable size="sm"> + <!-- A definite height, not a max: it is what lets the table's own box scroll under + its sticky header. Fixed column widths keep the columns still as rows change. --> + <DataTable + size="sm" + tableFixed + containerClass={draft.members.length >= MANY_ROWS ? 'h-80' : ''} + > <Head> <tr> <Cell head first class="text-secondary">Name</Cell> - <Cell head class="text-secondary">Role</Cell> - <Cell head last actions class="text-secondary">Actions</Cell> + <Cell head class="text-secondary {can_write && !restricted ? 'w-60' : 'w-24'}"> + Role + </Cell> + <Cell head last actions class="text-secondary {isNew ? 'w-40' : 'w-20'}"> + Actions + </Cell> </tr> </Head> <tbody class="divide-y"> - {#each draft.members as member, idx (member.member_name)} + {#each shownMembers as member (member.member_name)} <Row> <Cell first> - <span class="text-emphasis font-medium">{member.member_name}</span> + <span class="block truncate text-emphasis font-medium" title={member.member_name}> + {member.member_name} + </span> </Cell> <Cell> {#if can_write && !restricted} @@ -501,7 +565,7 @@ disabled={isFixedCreatorRow(member.member_name)} selected={member.role} on:selected={(e) => { - draft.members[idx].role = e.detail + member.role = e.detail }} > {#snippet children({ item })} @@ -559,6 +623,13 @@ </Cell> </Row> {/each} + {#if memberQuery && shownMembers.length === 0} + <Row> + <Cell first last colspan={3} class="text-hint truncate"> + No one matches “{memberSearch.trim()}” + </Cell> + </Row> + {/if} </tbody> </DataTable> {:else} @@ -573,18 +644,45 @@ {#if instance_group?.emails} <Label label="Members from the instance group"> - <DataTable size="sm"> + {#snippet action()} + {#if instanceEmails.length >= MANY_ROWS} + <TextInput + size="sm" + class="w-56 min-w-0" + bind:value={emailSearch} + inputProps={{ + type: 'search', + placeholder: `Search ${instanceEmails.length} members`, + 'aria-label': 'Search members from the instance group' + }} + /> + {/if} + {/snippet} + <DataTable + size="sm" + tableFixed + containerClass={instanceEmails.length >= MANY_ROWS ? 'h-80' : ''} + > <Head> <tr> <Cell head first last class="text-secondary">Email</Cell> </tr> </Head> <tbody class="divide-y"> - {#each instance_group?.emails ?? [] as email} + {#each shownEmails as email (email)} <Row> - <Cell first last>{email}</Cell> + <Cell first last> + <span class="block truncate" title={email}>{email}</span> + </Cell> </Row> {/each} + {#if emailQuery && shownEmails.length === 0} + <Row> + <Cell first last class="text-hint truncate"> + No one matches “{emailSearch.trim()}” + </Cell> + </Row> + {/if} </tbody> </DataTable> </Label> diff --git a/frontend/src/lib/components/InheritedLabels.svelte b/frontend/src/lib/components/InheritedLabels.svelte index bfc8190ea4..f15aaf5567 100644 --- a/frontend/src/lib/components/InheritedLabels.svelte +++ b/frontend/src/lib/components/InheritedLabels.svelte @@ -1,33 +1,15 @@ <script lang="ts"> - import Badge from './common/badge/Badge.svelte' + import LabelList from './common/badge/LabelList.svelte' + import type { BadgeColor } from './common/badge/model' import { Folder } from 'lucide-svelte' interface Props { labels: string[] | undefined max?: number + color?: BadgeColor } - let { labels, max = 3 }: Props = $props() + let { labels, max, color }: Props = $props() </script> -{#if labels?.length} - <div class="flex items-center gap-0.5"> - {#each labels.slice(0, max) as label (label)} - <Badge color="gray" small class="px-1" title="Label inherited from folder: {label}"> - <Folder size={10} class="mr-0.5 shrink-0" /> - {label} - </Badge> - {/each} - {#if labels.length > max} - <Badge - color="gray" - small - class="px-1" - title={labels - .slice(max) - .map((l) => 'Label inherited from folder: ' + l) - .join('\n')}>+{labels.length - max}</Badge - > - {/if} - </div> -{/if} +<LabelList {labels} icon={Folder} titlePrefix="Label inherited from folder" {max} {color} /> diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index a3a2d19fd6..ad2ee14b99 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -22,6 +22,7 @@ import CriticalAlertChannels from './instanceSettings/CriticalAlertChannels.svelte' import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' + import WorkspaceRolesSetting from './instanceSettings/WorkspaceRolesSetting.svelte' import SmtpSettings from './instanceSettings/SmtpSettings.svelte' import SecretBackendConfig from './instanceSettings/SecretBackendConfig.svelte' import ExternalInstancePgSettings from './instanceSettings/ExternalInstancePgSettings.svelte' @@ -342,6 +343,8 @@ getInstanceConfig() has populated the persisted overrides (which would let a save drop them). --> <RetentionPeriodOverrides {values} disabled={!$enterpriseLicense || loading} /> + {:else if setting.fieldType == 'workspace_roles'} + <WorkspaceRolesSetting {values} {loading} unlicensed={!$enterpriseLicense} /> {:else} <SettingCard label={setting.key === 'disable_stats' diff --git a/frontend/src/lib/components/InstanceSettings.svelte b/frontend/src/lib/components/InstanceSettings.svelte index 0883d9fb5e..d60cbeda56 100644 --- a/frontend/src/lib/components/InstanceSettings.svelte +++ b/frontend/src/lib/components/InstanceSettings.svelte @@ -1140,6 +1140,12 @@ description="Configure default timeouts and retention policies for job execution." link="https://www.windmill.dev/docs/advanced/instance_settings#jobs" /> + {:else if category == 'Workspace roles'} + <SettingsPageHeader + title="Workspace roles" + description="Define the roles workspace members can hold and what each one may author, manage and see. Workspace admin is separate and holds everything." + link="https://www.windmill.dev/docs/core_concepts/roles_and_permissions" + /> {:else if category == 'Service logs'} <SettingsPageHeader title="Service logs" diff --git a/frontend/src/lib/components/InviteUser.svelte b/frontend/src/lib/components/InviteUser.svelte index 7aded95461..83093d969f 100644 --- a/frontend/src/lib/components/InviteUser.svelte +++ b/frontend/src/lib/components/InviteUser.svelte @@ -1,16 +1,19 @@ <script lang="ts"> import { Button } from './common' import Popover from './meltComponents/Popover.svelte' - - import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' - import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' + import RolePicker from './settings/RolePicker.svelte' + import type { EffectiveRole } from '$lib/gen' + import { validRoleOr } from '$lib/workspaceRoles' import { MailPlus } from 'lucide-svelte' interface Props { - inviteUser: (email: string, selected: 'operator' | 'developer' | 'admin') => Promise<void> + /** `selected` is a role name, or `admin`. */ + inviteUser: (email: string, selected: string) => Promise<void> + /** The workspace's roles; undefined while loading. */ + roles: EffectiveRole[] | undefined } - const { inviteUser }: Props = $props() + const { inviteUser, roles }: Props = $props() let email: string = $state('') @@ -23,7 +26,8 @@ } } - let selected: 'operator' | 'developer' | 'admin' = $state('developer') + let picked: string | undefined = $state(undefined) + const selected = $derived(validRoleOr(roles, picked)) </script> <Popover floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}> @@ -46,30 +50,7 @@ bind:value={email} class="mr-4" /> - <ToggleButtonGroup bind:selected> - {#snippet children({ item })} - <ToggleButton - value="operator" - label="Operator" - tooltip="An operator can only execute and view scripts/flows/apps from your workspace, and only those that he has visibility on." - {item} - /> - - <ToggleButton - value="developer" - label="Developer" - tooltip="A Developer can execute and view scripts/flows/apps, but they can also create new ones and edit those they are allowed to by their path (either u/ or Writer or Admin of their folder found at /f)." - {item} - /> - - <ToggleButton - value="admin" - label="Admin" - tooltip="An admin has full control over a specific Windmill workspace, including the ability to manage users, edit entities, and control permissions within the workspace." - {item} - /> - {/snippet} - </ToggleButtonGroup> + <RolePicker {roles} disablePortal value={selected} onchange={(v) => (picked = v)} /> <Button variant="accent" unifiedSize="md" diff --git a/frontend/src/lib/components/Login.svelte b/frontend/src/lib/components/Login.svelte index 1199d01079..d76136c728 100644 --- a/frontend/src/lib/components/Login.svelte +++ b/frontend/src/lib/components/Login.svelte @@ -28,7 +28,7 @@ import PocketIdIcon from '$lib/components/icons/PocketIdIcon.svelte' import { OauthService, UserService, WorkspaceService } from '$lib/gen' - import { usersWorkspaceStore, workspaceStore, userStore } from '$lib/stores' + import { usersWorkspaceStore, workspaceStore, userStore, roleCapabilities } from '$lib/stores' import { emptyString, escapeHtml, parseQueryParams } from '$lib/utils' import { getUserExt } from '$lib/user' import { sendUserToast } from '$lib/toast' @@ -337,7 +337,7 @@ workspaceStore.set(allWorkspaces[0].id) $userStore = await getUserExt($workspaceStore!) - if (!$userStore?.is_super_admin && $userStore?.operator) { + if (!$roleCapabilities.code) { let defaultApp = await WorkspaceService.getWorkspaceDefaultApp({ workspace: $workspaceStore! }) @@ -350,9 +350,10 @@ } else { goto(resolvedRd ?? '/') } - // See (root)/+layout.svelte for why /projects/import skips the picker. + // See (root)/+layout.svelte for why these skip the picker. } else if ( resolvedRd?.startsWith('/user/workspaces') || + resolvedRd?.startsWith('/oauth/mcp_authorize') || resolvedRd?.startsWith('/projects/import') ) { goto(resolvedRd) diff --git a/frontend/src/lib/components/NoDirectDeployAlert.svelte b/frontend/src/lib/components/NoDirectDeployAlert.svelte index a3a249caf5..1e1256241e 100644 --- a/frontend/src/lib/components/NoDirectDeployAlert.svelte +++ b/frontend/src/lib/components/NoDirectDeployAlert.svelte @@ -23,11 +23,15 @@ import { GitFork, Lock, ShieldOff } from 'lucide-svelte' import { useOperatingWorkspace, - useOperatingUser + useOperatingUser, + useReadOnlyWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const roleCaps = useRoleCapabilities() + const readOnly = useReadOnlyWorkspace() // The shared rules state holds the navigation workspace's rules, so a host acting on another // workspace (an AI session's fork) has to ask for that one's. @@ -59,12 +63,16 @@ ? 'You will need to either fork the workspace, or make your changes locally and submit a PR to an authorized user.' : 'You will need to make your changes locally and submit a PR to an authorized user.' ) + // A session in Use edits nothing, so no rule or bypass opens the lists' create, edit and + // delete actions there. + let sessionReadOnly = $derived(readOnly($operatingWorkspace)) let overrideChecked = $state(false) // The toggle is only offered to a user who can bypass, but the answer can change under a // workspace switch, so the checked flag alone never grants the edit. - let bypassActive = $derived(canBypass && overrideChecked) + let bypassActive = $derived(canBypass && !sessionReadOnly && overrideChecked) let canEdit = $derived( - !isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment') || bypassActive + !sessionReadOnly && + (!isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment') || bypassActive) ) let { @@ -97,7 +105,7 @@ ) </script> -{#if !operatingUser.current?.operator && activeDeployRulesets.length > 0} +{#if ($roleCaps.code || $roleCaps.flows !== 'none' || $roleCaps.apps !== 'none') && activeDeployRulesets.length > 0} <div class="my-2"> <Popover placement="bottom-start" @@ -144,7 +152,7 @@ {editAdvice} </p> {/if} - {#if canBypass} + {#if canBypass && !sessionReadOnly} <Toggle size="xs" bind:checked={overrideChecked} diff --git a/frontend/src/lib/components/OAuthSetting.svelte b/frontend/src/lib/components/OAuthSetting.svelte index 0aa1de0025..974cae68e5 100644 --- a/frontend/src/lib/components/OAuthSetting.svelte +++ b/frontend/src/lib/components/OAuthSetting.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { ExternalLink, Plus, X } from 'lucide-svelte' + import { Plus, X } from 'lucide-svelte' import CollapseLink from './CollapseLink.svelte' import IconedResourceType from './IconedResourceType.svelte' import Toggle from './Toggle.svelte' @@ -9,9 +9,7 @@ import TextInput from './text_input/TextInput.svelte' import Password from './Password.svelte' import SettingCard from './instanceSettings/SettingCard.svelte' - import CopyableCodeBlock from './details/CopyableCodeBlock.svelte' - import { slackAppManifest } from './common/slack/slackAppManifest' - import { yaml } from 'svelte-highlight/languages' + import SlackAppSetup from './common/slack/SlackAppSetup.svelte' interface Props { name: string @@ -133,6 +131,20 @@ bind:password={value['secret']} /> </label> + {#if name == 'slack'} + <label for="slack_signing_secret" class="flex flex-col gap-1"> + <span class="text-emphasis font-semibold text-xs">Signing Secret</span> + <Password + id="slack_signing_secret" + placeholder="Signing Secret" + bind:password={value['signing_secret']} + /> + <span class="text-2xs text-hint"> + Lets Windmill check that requests come from Slack. Required for AI agents; recommended + for <code>/windmill</code> commands. + </span> + </label> + {/if} {#if name == 'microsoft' || name == 'ms_teams'} <label class="flex flex-col gap-1"> <span class="text-emphasis font-semibold text-xs">Tenant Id</span> @@ -206,22 +218,7 @@ </CollapseLink> {:else if name == 'slack'} <CollapseLink text="Set up slack"> - <div class="flex flex-col gap-2 text-xs text-primary"> - <span> - Create a Slack app <a href="https://api.slack.com/apps?new_app=1" target="_blank" - >in the Slack API console <ExternalLink size={12} class="inline-block" /></a - >: pick "From a manifest", then YAML, and paste the manifest below. Then copy the - Client ID and Client Secret here. Socket Mode and token rotation must stay off. For AI - agents to answer in Slack, set the app's Signing Secret as the server's - <code>SLACK_SIGNING_SECRET</code> environment variable. More in the - <a href="https://www.windmill.dev/docs/misc/setup_oauth#slack" target="_blank" - >Windmill docs <ExternalLink size={12} class="inline-block" /></a - >. - </span> - <div class="flex flex-col max-h-80 [&>div]:min-h-0"> - <CopyableCodeBlock code={slackAppManifest(window.location.origin)} language={yaml} /> - </div> - </div> + <SlackAppSetup /> </CollapseLink> {:else if name == 'microsoft'} <CollapseLink text="Instructions"> @@ -294,11 +291,12 @@ Follow this guide on <a href="https://www.windmill.dev/docs/misc/setup_oauth#microsoft-teams" target="_blank">Windmill Docs</a - > to create a new Microsoft Teams App. Then paste Client ID, Tenant ID, and Client Secret - here. The same app serves the Teams bot (Enterprise Edition) and the Microsoft Teams - OAuth resource: to connect that resource, also add the redirect URI - <code>BASE_URL/oauth/callback/ms_teams</code> and the delegated Microsoft Graph - permissions you need to the app. + > + to create a new Microsoft Teams App. Then paste Client ID, Tenant ID, and Client Secret here. + The same app serves the Teams bot (Enterprise Edition) and the Microsoft Teams OAuth resource: + to connect that resource, also add the redirect URI + <code>BASE_URL/oauth/callback/ms_teams</code> and the delegated Microsoft Graph permissions + you need to the app. </div> </CollapseLink> {/if} diff --git a/frontend/src/lib/components/PageHeaderBar.svelte b/frontend/src/lib/components/PageHeaderBar.svelte index 1ad2602d8e..e7e32df604 100644 --- a/frontend/src/lib/components/PageHeaderBar.svelte +++ b/frontend/src/lib/components/PageHeaderBar.svelte @@ -33,6 +33,7 @@ The row's height matches the sidebar's own header row, so the two read as one ba const content = $derived(pageHeader.content) const actions = $derived(pageHeader.actions) + const hasActions = $derived(actions.length > 0) const item = $derived(content?.item) const section = $derived(content?.section) @@ -82,8 +83,8 @@ The row's height matches the sidebar's own header row, so the two read as one ba trail: trailMeasures.trail, summary: BAR_STAGES.map(() => (hasSummary ? GAP + summaryFloorWidth : 0)), actions: - actions.length === 0 ? [0] : actionsRigid ? actionWidths : [GAP + FLEXIBLE_ACTIONS_RESERVE], - folds: actions.length > 0 && actionsRigid ? (content?.actionFolds ?? 0) : 0, + !hasActions ? [0] : actionsRigid ? actionWidths : [GAP + FLEXIBLE_ACTIONS_RESERVE], + folds: hasActions && actionsRigid ? (content?.actionFolds ?? 0) : 0, earlyFolds: content?.earlyActionFolds, summaryNamesItem, natural: { @@ -314,7 +315,7 @@ The row's height matches the sidebar's own header row, so the two read as one ba </div> {/if} - {#if actions.length > 0} + {#if hasActions} <!-- A plain row of buttons holds its width (shrink-0): squeezing it only pushes buttons out of the bar, so the bar makes room by dropping breadcrumb parts and then by asking the page to fold (`actionFolds`). Flexible actions (the Runs filter row) are a control that diff --git a/frontend/src/lib/components/PageHeaderContent.svelte b/frontend/src/lib/components/PageHeaderContent.svelte index cc37b727cb..94450cf9ab 100644 --- a/frontend/src/lib/components/PageHeaderContent.svelte +++ b/frontend/src/lib/components/PageHeaderContent.svelte @@ -15,6 +15,7 @@ the header, so nesting is decided by the caller rather than guessed from context section, afterName, actions, + sessionSource, actionsOrder, actionsFlexible, actionsFill, @@ -35,6 +36,7 @@ the header, so nesting is decided by the caller rather than guessed from context section, afterName, actions, + sessionSource, actionsOrder, actionsFlexible, actionsFill, diff --git a/frontend/src/lib/components/ParentWorkspaceProtectionAlert.svelte b/frontend/src/lib/components/ParentWorkspaceProtectionAlert.svelte index cd3c208813..f3d1fce472 100644 --- a/frontend/src/lib/components/ParentWorkspaceProtectionAlert.svelte +++ b/frontend/src/lib/components/ParentWorkspaceProtectionAlert.svelte @@ -1,6 +1,6 @@ <script lang="ts"> import type { ProtectionRuleset } from '$lib/gen' - import { userStore, type UserExt } from '$lib/stores' + import { roleCapabilities, type UserExt } from '$lib/stores' import { getUserExt } from '$lib/user' import { fetchProtectionRulesForWorkspace, @@ -71,7 +71,7 @@ }) </script> -{#if !$userStore?.operator && activeDeployRulesets.length > 0} +{#if ($roleCapabilities.code || $roleCapabilities.flows !== 'none' || $roleCapabilities.apps !== 'none') && activeDeployRulesets.length > 0} <!-- Named for the deploy destination, not the lineage: the merge UI also points this at a target outside the fork lineage. --> <Alert type="info" title="Target workspace protection active" class="my-2"> diff --git a/frontend/src/lib/components/ResourceEditor.svelte b/frontend/src/lib/components/ResourceEditor.svelte index 33ab00abbf..3e842e040f 100644 --- a/frontend/src/lib/components/ResourceEditor.svelte +++ b/frontend/src/lib/components/ResourceEditor.svelte @@ -9,6 +9,7 @@ } from '$lib/gen' import { canEditItem } from '$lib/editRights' import { userWorkspaces } from '$lib/stores' + import { capabilitiesIn } from '$lib/roleCapabilities' import { createEventDispatcher, onDestroy, untrack } from 'svelte' import { sendUserToast } from '$lib/toast' import { clearJsonSchemaResourceCache } from './schema/jsonSchemaResource.svelte' @@ -269,8 +270,12 @@ path: string, extraPerms: Record<string, boolean> | undefined ): boolean { - const settings = $userWorkspaces.find((w) => w.id === ws)?.operator_settings - return canEditItem('resource', path, extraPerms, acting.in(ws), settings) + const user = acting.in(ws) + const caps = capabilitiesIn( + user, + $userWorkspaces.find((w) => w.id === ws) + ) + return canEditItem('resource', path, extraPerms, user, caps) } const dirtyWorkspaces = $derived( diff --git a/frontend/src/lib/components/ResourcePicker.svelte b/frontend/src/lib/components/ResourcePicker.svelte index b396bd6dee..d766e5a51f 100644 --- a/frontend/src/lib/components/ResourcePicker.svelte +++ b/frontend/src/lib/components/ResourcePicker.svelte @@ -20,6 +20,9 @@ value?: string | undefined valueType?: string | undefined resourceType?: string | undefined + /** Further resource types whose resources are offered alongside `resourceType`'s. New + * resources are still created as `resourceType`. */ + additionalResourceTypes?: string[] disabled?: boolean disablePortal?: boolean showSchemaExplorer?: boolean @@ -46,6 +49,7 @@ value = $bindable(undefined), valueType = $bindable(undefined), resourceType = undefined, + additionalResourceTypes = [], disabled = false, disablePortal = false, showSchemaExplorer = false, @@ -114,8 +118,10 @@ async function loadResources(resourceType: string | undefined) { loading = true try { - const resourceTypesToQuery = - resourceType === 'snowflake' ? ['snowflake', 'snowflake_oauth'] : [resourceType] + const resourceTypesToQuery = [ + ...(resourceType === 'snowflake' ? ['snowflake', 'snowflake_oauth'] : [resourceType]), + ...additionalResourceTypes + ] const resources = await Promise.all( resourceTypesToQuery.map((rt) => diff --git a/frontend/src/lib/components/RunFormAdvancedPopup.svelte b/frontend/src/lib/components/RunFormAdvancedPopup.svelte index 8bf1bd1481..5513e70538 100644 --- a/frontend/src/lib/components/RunFormAdvancedPopup.svelte +++ b/frontend/src/lib/components/RunFormAdvancedPopup.svelte @@ -3,31 +3,30 @@ import Label from './Label.svelte' import Toggle from './Toggle.svelte' import Tooltip from './Tooltip.svelte' - import { userStore, workerTags, workspaceStore } from '$lib/stores' + import { roleCapabilities, userStore, workerTags, workspaceStore } from '$lib/stores' import { Button } from './common' import { WorkerService } from '$lib/gen' import DateTimeInput from './DateTimeInput.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - interface Props { - runnable: - | { - summary?: string - description?: string - path?: string - is_template?: boolean - hash?: string - kind?: string - can_write?: boolean - created_at?: string - created_by?: string - extra_perms?: Record<string, boolean> - } - | undefined; - scheduledForStr: string | undefined; - invisible_to_owner: boolean | undefined; - overrideTag: string | undefined; + runnable: + | { + summary?: string + description?: string + path?: string + is_template?: boolean + hash?: string + kind?: string + can_write?: boolean + created_at?: string + created_by?: string + extra_perms?: Record<string, boolean> + } + | undefined + scheduledForStr: string | undefined + invisible_to_owner: boolean | undefined + overrideTag: string | undefined } let { @@ -35,7 +34,7 @@ scheduledForStr = $bindable(), invisible_to_owner = $bindable(), overrideTag = $bindable() - }: Props = $props(); + }: Props = $props() // As in WorkerTagPicker: the shared `workerTags` cache is the navigation workspace's, so // tags of another operating workspace live in a local list rather than overwriting it. const operatingWorkspace = useOperatingWorkspace() @@ -87,7 +86,7 @@ </div> {/if} </div> - {#if !$userStore?.operator} + {#if $roleCapabilities.code} {#if currentTags && currentTags.length > 0} <div class="w-full"> <select diff --git a/frontend/src/lib/components/RunsPage.svelte b/frontend/src/lib/components/RunsPage.svelte index 9019c2d16e..db30073c44 100644 --- a/frontend/src/lib/components/RunsPage.svelte +++ b/frontend/src/lib/components/RunsPage.svelte @@ -11,12 +11,10 @@ import { sendUserToast } from '$lib/toast' import { displayDate } from '$lib/utils' - import { userWorkspaces, superadmin, devopsRole, enterpriseLicense } from '$lib/stores' + import { superadmin, devopsRole, enterpriseLicense } from '$lib/stores' import { useHostedPage } from '$lib/components/hostedPage' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { Button, Drawer, DrawerContent, Skeleton, Tab, Tabs } from '$lib/components/common' import TextInput from '$lib/components/text_input/TextInput.svelte' import RunChart from '$lib/components/RunChart.svelte' @@ -33,10 +31,12 @@ import Toggle from '$lib/components/Toggle.svelte' import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' import RunsQueue from '$lib/components/runs/RunsQueue.svelte' - import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import { RUNS_PATH } from '$lib/components/sessions/previewPaths' + import OpenInSessionButton, { + type OpenInSessionSource + } from '$lib/components/sessions/OpenInSessionButton.svelte' import { computeJobKinds, useJobsLoader } from '$lib/components/runs/useJobsLoader.svelte' import ConcurrentJobsChart from '$lib/components/ConcurrentJobsChart.svelte' import BatchLoadProgress from '$lib/components/BatchLoadProgress.svelte' @@ -83,7 +83,7 @@ // the filter row renders in the page, and requests go to the workspace it names. const hosted = useHostedPage() const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() + const roleCaps = useRoleCapabilities() let paths: string[] = $state([]) let usernames: string[] = $state([]) @@ -178,9 +178,7 @@ let manualTimeframe = $derived(timeframe.type === 'manual' ? timeframe : undefined) let graph: 'RunChart' | 'ConcurrencyChart' = $state( - typeOfChart( - (hosted ? new URLSearchParams(hosted.search) : page.url.searchParams).get('graph') - ) + typeOfChart((hosted ? new URLSearchParams(hosted.search) : page.url.searchParams).get('graph')) ) let innerWidth = $state(window.innerWidth) let jobsLoader = useJobsLoader(() => ({ @@ -230,7 +228,9 @@ } async function loadPaths() { - const npaths_scripts = await ScriptService.listScriptPaths({ workspace: $operatingWorkspace ?? '' }) + const npaths_scripts = await ScriptService.listScriptPaths({ + workspace: $operatingWorkspace ?? '' + }) const npaths_flows = await FlowService.listFlowPaths({ workspace: $operatingWorkspace ?? '' }) paths = npaths_scripts.concat(npaths_flows).sort() } @@ -452,11 +452,14 @@ // workaround because EventSource does not support POST requests // https://medium.com/@david.richards.tech/sse-server-sent-events-using-a-post-request-without-eventsource-1c0bd6f14425 - const response = await fetch(`${OpenAPI.BASE}/w/${$operatingWorkspace}/jobs/run/batch_rerun_jobs`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body) - }) + const response = await fetch( + `${OpenAPI.BASE}/w/${$operatingWorkspace}/jobs/run/batch_rerun_jobs`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + } + ) await new Promise(async (resolve) => { const reader = response?.body?.pipeThrough(new TextDecoderStream()).getReader() let reRanUuids: string[] = [] @@ -572,8 +575,8 @@ askingForConfirmation = { title: `Confirm re-running the selected jobs`, confirmBtnText: `Re-run ${jobIdsToReRun.length} jobs`, - // The server skips resolution for operators, who cannot resolve. - description: operatingUser.current?.operator + // The server skips resolution for a role without `code`, which cannot resolve. + description: !$roleCaps.code ? undefined : "Failed or canceled jobs among them will be marked resolved, with the new run's id as the note.", type: 'reload', @@ -650,11 +653,19 @@ } let resolutionNote = $state('') // The bar folds this row (`actionFolds` below) once its breadcrumb has given all it can: first - // the counters, which are a glance and repeat the chart below; then the session button; then - // the filter field moves to a row of its own rather than shrinking past usable. Hosted, the row - // is the page's own and wraps instead. + // the counters, which are a glance and repeat the chart below; then the filter field moves to a + // row of its own rather than shrinking past usable. Hosted, the row is the page's own and wraps + // instead. const fold = $derived(hosted ? 0 : pageHeader.actionFold) - const filterBelow = $derived(fold >= 3) + const filterBelow = $derived(fold >= 2) + + const sessionSource: OpenInSessionSource = $derived({ + // The filters are shallow-routed, so the search has to come off `window.location` at click + // time — `page.url` never sees them. Always the canonical `/runs`: only that is a recognized + // preview page, and the `/runs/<path>` route mirrors its path into `?path=` anyway. + page: () => RUNS_PATH + window.location.search, + workspaceId: $operatingWorkspace ?? undefined + }) </script> {#snippet runsHint()} @@ -875,19 +886,11 @@ items={runsTimeframes} bind:value={_timeframe.val} /> - <!-- The filters are shallow-routed, so the search has to come off `window.location` at click - time — `page.url` never sees them. Always the canonical `/runs`: only that is a recognized - preview page, and the `/runs/<path>` route mirrors its path into `?path=` anyway. --> - <div class={fold >= 2 || hosted ? 'hidden' : 'contents'}> - <OpenInSessionButton - source={{ - page: () => RUNS_PATH + window.location.search, - workspaceId: $operatingWorkspace ?? undefined - }} - btnProps={{ unifiedSize: 'sm' }} - /> - </div> </div> + {#if !hosted} + <!-- No main action on this page: the session button ends the row. --> + <OpenInSessionButton source={sessionSource} /> + {/if} {/snippet} <ConfirmationModal @@ -955,10 +958,10 @@ }} /> -{#if operatingUser.current?.operator && $operatingWorkspace && !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.runs} +{#if $operatingWorkspace && !$roleCaps.visibility.runs} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <div class="w-full h-full flex flex-col" bind:clientWidth={innerWidth}> @@ -970,9 +973,10 @@ <PageHeaderContent afterName={runsHint} actions={headerActions} - actionFolds={3} + {sessionSource} + actionFolds={2} belowBar={filterRow} - belowBarFold={3} + belowBarFold={2} /> {/if} @@ -1166,10 +1170,10 @@ batchRerunOptionsIsOpen = true } }, - ...(!operatingUser.current?.operator + ...($roleCaps.code ? [ { - // Operators are rejected by the endpoint, so offering it would only 403. + // A role without `code` is rejected by the endpoint, so offering it would only 403. displayName: 'Resolve failed or canceled jobs', action: () => ( (manualSelectionMode = 'resolve'), diff --git a/frontend/src/lib/components/SaveButton.svelte b/frontend/src/lib/components/SaveButton.svelte index 87084f460c..b83af769f5 100644 --- a/frontend/src/lib/components/SaveButton.svelte +++ b/frontend/src/lib/components/SaveButton.svelte @@ -52,7 +52,9 @@ }) .catch((error) => { console.error('Save failed:', error) - sendUserToast(error?.message ?? 'Save failed', true) + // An API error's message is only the status text; the server's reason is its body. + const body = typeof error?.body === 'string' && error.body ? error.body : undefined + sendUserToast(body ?? error?.message ?? 'Save failed', true) saveStatus = 'error' statusTimeout = setTimeout(() => { saveStatus = null diff --git a/frontend/src/lib/components/ScriptBuilder.svelte b/frontend/src/lib/components/ScriptBuilder.svelte index 247382d6d4..7c6db7b242 100644 --- a/frontend/src/lib/components/ScriptBuilder.svelte +++ b/frontend/src/lib/components/ScriptBuilder.svelte @@ -22,6 +22,10 @@ } from '$lib/script_helpers' import { isWorkflowAsCode } from './graph/wacToFlow' import AIFormSettings from './copilot/AIFormSettings.svelte' + import { SUPPORTED_CHAT_SCRIPT_LANGUAGES } from './copilot/chat/script/core' + import OpenInSessionButton, { + type OpenInSessionSource + } from './sessions/OpenInSessionButton.svelte' import { defaultScripts, enterpriseLicense, @@ -212,9 +216,13 @@ const compactTopbar = $derived( ownsPageHeader ? pageHeader.actionFold >= 1 : topbarWidth > 0 && topbarWidth < 900 ) - // The second fold holds the trail and one button. Diff and Settings join the menu that compact + // In the page header no fold drops a button's label: what does not fit goes into the menu. The + // second fold holds the trail and one button. Diff and Settings join the menu that compact // already shows, and Deploy stays out: it is what this page is for. const phoneTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 2) + // The third fold leaves the autosave indicator as its icon, so the AI session button still fits + // right before Deploy on a phone. + const narrowTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 3) // The workspace this editor operates on: deploy, save-draft, trigger loading // and the AutosaveIndicator all target it. Falls back to the full-page @@ -685,8 +693,7 @@ // the user has typed, so after someone renames the item it still names // the old location and this would compare against the archived row left // there. Resolving by the row is what lets the diff show the rename. - path: userDraftPath || initialPath, - withStarredInfo: true + path: userDraftPath || initialPath }) // A superseded opening must not write these: the current one would then render @@ -915,6 +922,24 @@ } } + const sessionOpen: OpenInSessionSource | undefined = $derived( + userDraftPath + ? { + // URL draft path the editor loads/saves by, not the friendly + // `script.path` (a new script's has no row → "not found"). + target: { kind: 'script', path: userDraftPath }, + workspaceId: opWorkspace ?? undefined, + beforeOpen: persistDraftForSession + } + : undefined + ) + // The header's button, gated like the code editor's AI entry point it stands in for. + function headerSessionOpen(): OpenInSessionSource | undefined { + if (disableAi || customUi?.editorBar?.aiGen == false) return undefined + if (!SUPPORTED_CHAT_SCRIPT_LANGUAGES.includes(script?.language ?? '')) return undefined + return sessionOpen + } + // Inside an AI session pane (which injects an aiChatManager via context) the // extra deploy-dropdown options — Deploy & Stay here, Fork, Edit in workspace // fork, Export — don't make sense: the session always stays put and is already @@ -2323,7 +2348,8 @@ }} afterName={scriptMarks} actions={scriptHeaderActions} - actionFolds={2} + sessionSource={headerSessionOpen()} + actionFolds={3} separator="none" /> {:else} @@ -2481,6 +2507,7 @@ {loadedFromDraft} {othersDraftsCount} {onOpenOthersDrafts} + compact={narrowTopbar} /> {/if} {/snippet} @@ -2510,7 +2537,7 @@ unifiedSize={headerBtnSize} on:click={() => (metadataOpen = true)} startIcon={{ icon: Settings }} - iconOnly={compactTopbar} + iconOnly={compactTopbar && !ownsPageHeader} title="Settings" > <span> Settings </span> @@ -2534,7 +2561,7 @@ on:click={() => openDiffDrawer()} disabled={diffDisabled} btnClasses={diffDisabled ? 'pointer-events-none' : undefined} - iconOnly={compactTopbar} + iconOnly={compactTopbar && !ownsPageHeader} title={diffTitle} startIcon={{ icon: DiffIcon }} > @@ -2580,6 +2607,9 @@ {@render settingsButton()} {/if} + {#if ownsPageHeader} + <OpenInSessionButton source={headerSessionOpen()} /> + {/if} <DeployButton loading={!fullyLoaded} {loadingSave} @@ -2652,15 +2682,7 @@ script.on_behalf_of_email )} workspaceOverride={opWorkspace} - sessionOpen={userDraftPath - ? { - // URL draft path the editor loads/saves by, not the friendly - // `script.path` (a new script's has no row → "not found"). - target: { kind: 'script', path: userDraftPath }, - workspaceId: opWorkspace ?? undefined, - beforeOpen: persistDraftForSession - } - : undefined} + {sessionOpen} bind:selectedTab={selectedInputTab} {customUi} {onTestJob} diff --git a/frontend/src/lib/components/ScriptEditor.svelte b/frontend/src/lib/components/ScriptEditor.svelte index 880ffbaad6..cedc274f4c 100644 --- a/frontend/src/lib/components/ScriptEditor.svelte +++ b/frontend/src/lib/components/ScriptEditor.svelte @@ -2720,7 +2720,7 @@ {/if} {#if !aiChatManager.open && !disableAi && !inSessionPane} {#if customUi?.editorBar?.aiGen != false && SUPPORTED_CHAT_SCRIPT_LANGUAGES.includes(lang ?? '')} - <OpenInSessionButton source={sessionOpen}> + <OpenInSessionButton source={sessionOpen} deferToHeader> {#snippet fallback()} <HideButton hidden={true} diff --git a/frontend/src/lib/components/ShareModal.svelte b/frontend/src/lib/components/ShareModal.svelte index dfb5892b03..082fbcce2e 100644 --- a/frontend/src/lib/components/ShareModal.svelte +++ b/frontend/src/lib/components/ShareModal.svelte @@ -25,13 +25,15 @@ import { useScheduleLock, useTriggerLock } from '$lib/operatorWriteRights' import { useOperatingWorkspace, - useOperatingUser + useOperatingUser, + useReadOnlyWorkspace } from '$lib/components/operatingWorkspace.svelte' const scheduleLock = useScheduleLock() const triggerLock = useTriggerLock() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const readOnly = useReadOnlyWorkspace() const dispatch = createEventDispatcher() @@ -170,7 +172,9 @@ } } - let own = $state(false) + let ownsItem = $state(false) + // A session can switch to Use while the drawer is open, so read-only is read live. + const own = $derived(ownsItem && !readOnly($operatingWorkspace)) export async function openDrawer(newPath: string, kind_l: Kind, isOwnerOverride?: boolean) { path = newPath kind = kind_l @@ -181,7 +185,7 @@ loadLinkedVarPaths() loadDefaultPerms() if (isOwnerOverride !== undefined) { - own = isOwnerOverride + ownsItem = isOwnerOverride } else { loadOwner() } @@ -189,7 +193,7 @@ } async function loadOwner() { - own = isOwner(path, operatingUser.current!, $operatingWorkspace!) + ownsItem = isOwner(path, operatingUser.current!, $operatingWorkspace!) } async function loadAcls() { @@ -292,9 +296,15 @@ </div> {/if} {#if !own} - <Alert type="warning" title="Not owner" - >Since you do not own this item, you cannot modify its permission</Alert - > + {#if readOnly($operatingWorkspace)} + <Alert type="info" title="Use mode"> + This session cannot change permissions while it is in Use mode. + </Alert> + {:else} + <Alert type="warning" title="Not owner" + >Since you do not own this item, you cannot modify its permission</Alert + > + {/if} {/if} <div> {#if own && sharingDisabled} diff --git a/frontend/src/lib/components/Star.svelte b/frontend/src/lib/components/Star.svelte index 4f0f169109..127bd66efa 100644 --- a/frontend/src/lib/components/Star.svelte +++ b/frontend/src/lib/components/Star.svelte @@ -10,9 +10,10 @@ summary?: string workspaceId?: string size?: number + class?: string } - let { path, kind, workspaceId, summary, size = 16 }: Props = $props() + let { path, kind, workspaceId, summary, size = 16, class: className = 'p-1' }: Props = $props() let buttonHover = $state(false) let starred = $derived(favoriteManager.isStarred(path, kind)) @@ -28,7 +29,9 @@ onclick={preventDefault(onClick)} onmouseenter={() => (buttonHover = true)} onmouseleave={() => (buttonHover = false)} - class="p-1" + class={className} + data-starred={starred || undefined} + title={starred ? 'Remove from favorites' : 'Add to favorites'} > {#if starred} {#if buttonHover} diff --git a/frontend/src/lib/components/TimeAgo.svelte b/frontend/src/lib/components/TimeAgo.svelte index 6138cdb6da..1e5515f144 100644 --- a/frontend/src/lib/components/TimeAgo.svelte +++ b/frontend/src/lib/components/TimeAgo.svelte @@ -9,7 +9,8 @@ noDate?: boolean isRecent?: boolean noSeconds?: boolean - /** Single-unit form ("2m", "3h", "5d") for rows too narrow for "2 mins ago". */ + /** Single-unit form ("2m", "3h", "5d") for rows too narrow for "2 mins ago". With + * `noSeconds`, the first minute reads "1m" rather than counting seconds. */ compact?: boolean } @@ -71,7 +72,9 @@ const secs = secondsAgo(new Date(dateString)) const left = secs < 60 - ? 1 + ? compact && noSeconds + ? 60 - secs + : 1 : secs < 3600 ? 60 - (secs % 60) : secs < 86_400 @@ -125,7 +128,7 @@ // (PipelineEventLog, PipelineActivityPanel, IndexerMemorySettings): seconds stay // meaningful right up to the minute mark. const secs = secondsAgo(date) - if (secs < 60) return `${secs}s` + if (secs < 60) return noSeconds ? '1m' : `${secs}s` const mins = minutesAgo(date) if (mins < 60) return `${mins}m` const hours = hoursAgo(date) diff --git a/frontend/src/lib/components/UserSettings.svelte b/frontend/src/lib/components/UserSettings.svelte index d5811e737b..306ce3505e 100644 --- a/frontend/src/lib/components/UserSettings.svelte +++ b/frontend/src/lib/components/UserSettings.svelte @@ -6,7 +6,8 @@ import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import TokensTable from './settings/TokensTable.svelte' - import { createEventDispatcher } from 'svelte' + import { createEventDispatcher, tick } from 'svelte' + import CreateToken from './settings/CreateToken.svelte' import UserInfoSettings from './settings/UserInfoSettings.svelte' import AIUserSettings from './settings/AIUserSettings.svelte' import AiUsagePanel from './workspaceSettings/AiUsagePanel.svelte' @@ -36,14 +37,18 @@ }: Props = $props() let drawer: Drawer | undefined = $state() - let openWithMcpMode = $state(false) + let mcpSection: HTMLDivElement | undefined = $state() + let tokensTable: TokensTable | undefined = $state() let darkVariant = $state<DarkModeVariant>(getDarkModeVariant()) const dispatch = createEventDispatcher() - export function openDrawer(mcpMode: boolean = false) { - openWithMcpMode = mcpMode + export async function openDrawer(mcpMode: boolean = false) { drawer?.openDrawer() + if (mcpMode) { + await tick() + mcpSection?.scrollIntoView({ block: 'start' }) + } } export function closeDrawer() { @@ -120,10 +125,22 @@ {/if} {/if} + {#if showMcpMode} + <div bind:this={mcpSection} class="flex flex-col p-4 border border-border-light rounded-md"> + <h2 class="text-emphasis text-sm font-semibold mb-1"> + Build and run from your AI client + </h2> + <div class="text-xs text-secondary mb-2"> + Connect Claude, ChatGPT or Cursor to Windmill over MCP: build scripts, flows and apps, + run your automations and check their runs, from your chat. + </div> + <CreateToken mcpOnly onTokenCreated={() => tokensTable?.listTokens()} /> + </div> + {/if} + <div class="grow min-h-0"> <TokensTable - {showMcpMode} - {openWithMcpMode} + bind:this={tokensTable} defaultNewTokenLabel={newTokenLabel} defaultNewTokenWorkspace={newTokenWorkspace} {scopes} diff --git a/frontend/src/lib/components/VariableEditor.svelte b/frontend/src/lib/components/VariableEditor.svelte index 901bf119cc..a308237f5a 100644 --- a/frontend/src/lib/components/VariableEditor.svelte +++ b/frontend/src/lib/components/VariableEditor.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { VariableService, WorkspaceService } from '$lib/gen' + import { VariableService, WorkspaceService, type ListableVariable } from '$lib/gen' import { createEventDispatcher, onDestroy, untrack } from 'svelte' import { Button } from './common' import Drawer from './common/drawer/Drawer.svelte' @@ -15,6 +15,7 @@ import { sendUserToast } from '$lib/toast' import { canEditItem } from '$lib/editRights' import { userWorkspaces } from '$lib/stores' + import { capabilitiesIn } from '$lib/roleCapabilities' import { Save } from 'lucide-svelte' import VariableForm from './VariableForm.svelte' import { invalidateWorkspacePaths } from './PathNameAutocomplete.svelte' @@ -28,17 +29,37 @@ import { useDraftConflictSession } from '$lib/draftConflictSession.svelte' import { isEncryptedDraftValue } from '$lib/encryptedDraft' import { setLocalDraftHint } from '$lib/localDraftHints.svelte' + import { logFeatureUsage } from '$lib/utils/featureUsage' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() const dispatch = createEventDispatcher() + // Subset of VariableDraftState (copilot/chat/global/workspaceItems.ts) — the same + // localStorage rows back both, so a field this shape omits is dropped on save. type VariableState = { path: string variable: { value: string; is_secret: boolean; description: string } labels: string[] | undefined wsSpecific: boolean + value_valid_until?: string + } + + // The deployed baseline every dirty check and save diff runs against: a field it + // leaves out reads as unchanged, so its edits are never sent. + function deployedVariableState(v: ListableVariable): VariableState { + return { + path: v.path, + variable: { + value: v.value ?? '', + is_secret: v.is_secret, + description: v.description ?? '' + }, + labels: v.labels ?? undefined, + wsSpecific: v.ws_specific ?? false, + value_valid_until: v.value_valid_until ?? undefined + } } // The "current" workspace this editor defaults New/Edit actions to. Session @@ -78,6 +99,7 @@ let initialStates: Record<string, VariableState> = $state({}) let existedInitially: Record<string, boolean> = $state({}) let extraPerms: Record<string, Record<string, boolean>> = $state({}) + let oauthLinked: Record<string, boolean> = $state({}) let selected: string | undefined = $state(undefined) let pathError = $state('') const acting = useActingUser(() => selected) @@ -141,8 +163,12 @@ return canEditVariableIn(selected, perms) }) function canEditVariableIn(ws: string, perms: Record<string, boolean>): boolean { - const settings = $userWorkspaces.find((w) => w.id === ws)?.operator_settings - return canEditItem('variable', editPath ?? '', perms, acting.in(ws), settings) + const user = acting.in(ws) + const caps = capabilitiesIn( + user, + $userWorkspaces.find((w) => w.id === ws) + ) + return canEditItem('variable', editPath ?? '', perms, user, caps) } const dirtyWorkspaces = $derived( Object.keys(states).filter((ws) => !draftValuesEqual(states[ws].draft, initialStates[ws])) @@ -219,16 +245,7 @@ decryptSecret: false, getDraft: true }) - const deployedState: VariableState = { - path: v.path, - variable: { - value: v.value ?? '', - is_secret: v.is_secret, - description: v.description ?? '' - }, - labels: v.labels ?? undefined, - wsSpecific: v.ws_specific ?? false - } + const deployedState = deployedVariableState(v) // Everything below writes shared editor state, so first make sure it is still this // variable's: the drawer stays closable while the read is out, and another variable // opened meanwhile would otherwise get this one's baseline — and with it this one's @@ -252,6 +269,7 @@ // displayed would leave those deciding on the version the user just replaced. existedInitially[ws] = !(v as any).no_deployed extraPerms[ws] = v.extra_perms ?? {} + oauthLinked[ws] = v.account != null UserDraftDbSyncer.recordRemoteSync(query, (v as any).draft_saved_at) UserDraft.seed( 'variable', @@ -327,16 +345,7 @@ const savedDraftState = (v as any).draft as VariableState | undefined // Deployed baseline as the dirty-check reference, so the banner // compares draft-vs-deployed and fires immediately when a draft exists. - const deployedState: VariableState = { - path: v.path, - variable: { - value: v.value ?? '', - is_secret: v.is_secret, - description: v.description ?? '' - }, - labels: v.labels ?? undefined, - wsSpecific: v.ws_specific ?? false - } + const deployedState = deployedVariableState(v) // A refused save leaves this tab's own version parked. `.draft` is the version // that refused it, so opening on that would quietly drop the edit the alert is // about and leave "Keep mine" offering to keep the other one. @@ -358,6 +367,7 @@ // CREATE, not update (update 404s). existedInitially[ws] = !(v as any).no_deployed extraPerms[ws] = v.extra_perms ?? {} + oauthLinked[ws] = v.account != null }) }) }) @@ -371,6 +381,7 @@ initialStates = {} existedInitially = {} extraPerms = {} + oauthLinked = {} pathError = '' acting.forgetFailures() } @@ -430,6 +441,11 @@ async function save(): Promise<void> { const dirty = dirtyWorkspaces const savedPath = (curWs ? states[curWs]?.draft?.path : undefined) ?? editPath ?? '' + // Before the loop rewrites the baselines; once per save, not per workspace. + const expiryChanged = dirty.filter( + (ws) => initialStates[ws]?.value_valid_until !== states[ws].draft?.value_valid_until + ) + const expiryNowSet = expiryChanged.some((ws) => !!states[ws].draft?.value_valid_until) try { for (const ws of dirty) { const s = states[ws].draft! @@ -447,6 +463,11 @@ ini.variable.description != s.variable.description ? s.variable.description : undefined, + // Tri-state: absent leaves the stored date alone, `null` clears it. + value_valid_until: + ini.value_valid_until != s.value_valid_until + ? (s.value_valid_until ?? null) + : undefined, labels: s.labels, ws_specific: s.wsSpecific } @@ -459,6 +480,7 @@ value: s.variable.value, is_secret: s.variable.is_secret, description: s.variable.description, + value_valid_until: s.value_valid_until, labels: s.labels, ws_specific: s.wsSpecific } @@ -475,6 +497,11 @@ // it shows up immediately instead of after the 60s TTL. invalidateWorkspacePaths(ws) } + if (expiryChanged.length > 0) { + logFeatureUsage('variable_expiration', 'expiry_edited', { + key: expiryNowSet ? 'set' : 'cleared' + }) + } sendUserToast(edit ? `Updated variable in ${dirty.length} workspace(s)` : `Created variable`) dispatch('create') onSaved?.(savedPath) @@ -562,6 +589,7 @@ bind:variable={current.variable} bind:labels={current.labels} bind:wsSpecific={current.wsSpecific} + bind:valueValidUntil={current.value_valid_until} {initialPath} deployTo={deployTo.current} can_write={can_write === true} @@ -573,6 +601,7 @@ !!initialStates[selected]?.variable.is_secret} workspace={selected} actingUser={acting.in(selected) ?? null} + oauthLinked={!!selected && !!oauthLinked[selected]} /> {/key} {/if} diff --git a/frontend/src/lib/components/VariableForm.svelte b/frontend/src/lib/components/VariableForm.svelte index 272004396c..8bebd55953 100644 --- a/frontend/src/lib/components/VariableForm.svelte +++ b/frontend/src/lib/components/VariableForm.svelte @@ -3,17 +3,19 @@ import LabelsInput from './LabelsInput.svelte' import Toggle from './Toggle.svelte' import Alert from './common/alert/Alert.svelte' - import { Button } from './common' + import { Button, Section } from './common' import Tooltip from './Tooltip.svelte' import Label from './Label.svelte' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import { Loader2, RotateCcw } from 'lucide-svelte' import autosize from '$lib/autosize' - import { type UserExt } from '$lib/stores' + import { type UserExt, userWorkspaces } from '$lib/stores' + import { capabilitiesIn } from '$lib/roleCapabilities' import { isOwner } from '$lib/utils' import { isEncryptedDraftValue } from '$lib/encryptedDraft' import EncryptedDraftField from './EncryptedDraftField.svelte' + import DateTimeInput from './DateTimeInput.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -31,6 +33,7 @@ variable: Variable labels: string[] | undefined wsSpecific: boolean + valueValidUntil: string | undefined deployTo: string | undefined can_write: boolean edit: boolean @@ -46,6 +49,8 @@ * refuses, rather than answering with the navigation user's rights in another * workspace. */ actingUser: UserExt | null + /** Linked to an OAuth account, whose token Windmill refreshes on its own. */ + oauthLinked?: boolean } let { @@ -55,6 +60,7 @@ variable = $bindable(), labels = $bindable(), wsSpecific = $bindable(), + valueValidUntil = $bindable(), deployTo, can_write, edit, @@ -62,10 +68,26 @@ onSecretChange, deployedSecret = false, workspace = undefined, - actingUser + actingUser, + oauthLinked = false }: Props = $props() let ws = $derived(workspace ?? $operatingWorkspace) + let caps = $derived( + capabilitiesIn( + actingUser ?? undefined, + $userWorkspaces.find((w) => w.id === ws) + ) + ) + + // Enabling seeds a date: an empty DateTimeInput still shows 12:00, which reads as set. + const DEFAULT_EXPIRY_DAYS = 90 + + function defaultValueExpiry(): string { + const d = new Date() + d.setDate(d.getDate() + DEFAULT_EXPIRY_DAYS) + return d.toISOString() + } // Loading the deployed secret overwrites the draft row this form shares with the AI // chat, so every path that would trigger it has to be blocked while that row stages a @@ -115,9 +137,9 @@ stretch the hit area over the whole row and the alert. The toggle carries its na on:change={(e) => onSecretChange?.(e.detail)} bind:checked={variable.is_secret} disabled={unsecureNeedsLoad || - (edit && (!actingUser || actingUser.operator || isEncryptedDraftValue(variable.value)))} + (edit && (!actingUser || !caps.code || isEncryptedDraftValue(variable.value)))} /> - {#if unsecureNeedsLoad && can_write && !actingUser?.operator} + {#if unsecureNeedsLoad && can_write && caps.code} <span class="text-2xs text-secondary"> Load the secret value or enter a new one to make it non-secret </span> @@ -163,8 +185,8 @@ stretch the hit area over the whole row and the alert. The toggle carries its na > Reset </Button> - {:else if actingUser?.operator} - <div class="p-2 border">Operators cannot load secret value</div> + {:else if !caps.code} + <div class="p-2 border">Your role cannot load secret values</div> {:else} <Button size="xs" variant="default" on:click={() => onLoadSecret?.()}> Load secret value<Tooltip>Will generate an audit log</Tooltip> @@ -236,3 +258,44 @@ stretch the hit area over the whole row and the alert. The toggle carries its na <textarea rows="4" use:autosize bind:value={variable.description} placeholder="Used for X" ></textarea> </label> + +{#if !oauthLinked} + <Section label="Advanced" small collapsable initiallyCollapsed={!valueValidUntil}> + <Label + label="Value expiration" + tooltip="When the value stored here stops working, such as the expiry date of an API key. Ahead of it (1 day by default), Windmill runs the workspace's variable expiration handler if one is set, so the value can be rotated. The variable itself is never deleted." + > + <Toggle + size="sm" + checked={Boolean(valueValidUntil)} + disabled={!can_write} + on:change={() => (valueValidUntil = valueValidUntil ? undefined : defaultValueExpiry())} + options={{ right: 'Set a date on which this value expires' }} + /> + {#if valueValidUntil} + <span class="text-xs font-semibold text-emphasis leading-none mt-2">Expires on</span> + <!-- Unbound: DateTimeInput writes `null` when emptied, which reads as an edit, + so empty states become `undefined`. Not `clearable`: the toggle means "no expiry". --> + <DateTimeInput + value={valueValidUntil} + useDropdown + disabled={!can_write} + on:change={(e) => (valueValidUntil = e.detail ?? undefined)} + /> + <span class="text-2xs font-normal text-hint"> + {#if new Date(valueValidUntil).getTime() <= Date.now()} + This date has passed. Set a new one once the value is rotated. + {:else} + Runs the workspace's <a + href="/workspace_settings?tab=variable_expiration&workspace={ws}" + >variable expiration handler</a + > + ahead of this date, if the workspace has one{path.startsWith('u/') + ? ' and does not skip u/ paths' + : ''}. + {/if} + </span> + {/if} + </Label> + </Section> +{/if} diff --git a/frontend/src/lib/components/WorkerGroup.svelte b/frontend/src/lib/components/WorkerGroup.svelte index 1f6b271602..3ee0807c50 100644 --- a/frontend/src/lib/components/WorkerGroup.svelte +++ b/frontend/src/lib/components/WorkerGroup.svelte @@ -105,6 +105,7 @@ periodic_script_interval_seconds?: number env_vars_static?: Map<string, string> env_vars_allowlist?: string[] + disable_job_proxy?: boolean additional_python_paths?: string[] pip_local_dependencies?: string[] min_alive_workers_alert_threshold?: number @@ -212,6 +213,7 @@ init_bash?: string env_vars_static?: Map<string, string> env_vars_allowlist?: string[] + disable_job_proxy?: boolean additional_python_paths?: string[] pip_local_dependencies?: string[] min_alive_workers_alert_threshold?: number @@ -327,6 +329,7 @@ 'priority_tags', 'additional_python_paths', 'pip_local_dependencies', + 'disable_job_proxy', 'object_store_cache_config', 'serves_dev_workspaces' ] as const @@ -909,6 +912,30 @@ disabled={!canEditConfig} /> </Label> + <div class="mt-8"></div> + <Label label="Worker proxy"> + {#snippet header()} + <Tooltip> + {#snippet text()} + Whether jobs get the worker's HTTP_PROXY, HTTPS_PROXY and NO_PROXY. Dependency + installs always go through the proxy, whatever this is set to. Removing the variables + does not stop a job from reaching the proxy if it knows its address. Workers pick the + change up without restarting. + {/snippet} + </Tooltip> + {/snippet} + <Toggle + size="sm" + options={{ right: "Pass the worker's proxy to jobs" }} + checked={nconfig?.disable_job_proxy !== true} + on:change={(ev) => { + if (nconfig !== undefined) { + nconfig.disable_job_proxy = ev.detail ? undefined : true + } + }} + disabled={!canEditConfig} + /> + </Label> {/if} <div class="mt-8"></div> @@ -1051,6 +1078,7 @@ <div class="mt-8"></div> <AutoscalingConfigEditor + worker_group={name} worker_tags={config?.worker_tags} group_has_tags={nconfig.worker_tags !== undefined ? nconfig.worker_tags.length > 0 diff --git a/frontend/src/lib/components/apps/editor/AppEditor.svelte b/frontend/src/lib/components/apps/editor/AppEditor.svelte index ac0d2b1cb6..643cd074d3 100644 --- a/frontend/src/lib/components/apps/editor/AppEditor.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditor.svelte @@ -26,7 +26,7 @@ import { Alert, Button, Tab } from '$lib/components/common' import TabContent from '$lib/components/common/tabs/TabContent.svelte' import Tabs from '$lib/components/common/tabs/TabsV2.svelte' - import { userStore, workspaceStore } from '$lib/stores' + import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' import { classNames, getModifierKey, @@ -883,7 +883,7 @@ /> <!-- {$focusedGrid?.parentComponentId} --> -{#if !$userStore?.operator} +{#if $roleCapabilities.apps === 'full'} {#if $appStore} <AppEditorHeader {ownsPageHeader} diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte index e5613a71a1..b6e0134eff 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte @@ -380,8 +380,7 @@ async function syncWithDeployed(opening?: number) { const deployedApp = await AppService.getAppByPath({ workspace: $workspaceStore!, - path: $appPath!, - withStarredInfo: true + path: $appPath! }) // A superseded opening must not write these: the current one would then render @@ -1326,7 +1325,7 @@ { label: 'Fork', onClick: () => { - window.open(`/apps/add?template=${appPath}`) + window.open(`/apps/add?template=${encodeURIComponent($appPath)}`) } }, ...(!isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte index 41e0c5c3f2..6118f6626d 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte @@ -3,7 +3,7 @@ import Toggle from '$lib/components/Toggle.svelte' import Badge from '$lib/components/Badge.svelte' import { enterpriseLicense, userStore } from '$lib/stores' - import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { AlertTriangle, Loader2 } from 'lucide-svelte' import Tooltip from '$lib/components/Tooltip.svelte' @@ -34,7 +34,9 @@ const operatingWorkspaceStore = useOperatingWorkspace() const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) - const operatorBuilderApps = useOperatorBuilderApps() + const roleCaps = useRoleCapabilities() + // The server forces a composed app into sandbox isolation. + const composeOnlyApps = $derived($roleCaps.apps === 'compose') const WM_DEPLOYERS_GROUP = 'wm_deployers' @@ -383,7 +385,7 @@ rightTooltip: "Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects." }} - checked={$operatorBuilderApps || policy.sandbox == true} + checked={composeOnlyApps || policy.sandbox == true} on:change={(e) => { policy.sandbox = e.detail || undefined // Counted where the toggle is flipped rather than where the policy is @@ -406,19 +408,19 @@ setPublishState(e.detail ? 'Sandbox isolation enabled' : 'Sandbox isolation disabled') } }} - disabled={!savedApp || $operatorBuilderApps} + disabled={!savedApp || composeOnlyApps} /> - {#if $operatorBuilderApps || newApp} + {#if composeOnlyApps || newApp} <div class="text-2xs text-secondary mt-1"> - {#if $operatorBuilderApps} - Required for apps built by operators, and cannot be turned off. + {#if composeOnlyApps} + Required for apps composed by your role, and cannot be turned off. {/if} {#if newApp} Takes effect when you first deploy this app. {/if} </div> {/if} - {#if !$operatorBuilderApps && policy.sandbox != true} + {#if !composeOnlyApps && policy.sandbox != true} <div class="mt-3"> <Alert type="warning" title="Not isolated" size="xs"> The app's frontend code runs with each viewer's full Windmill permissions. A future diff --git a/frontend/src/lib/components/apps/editor/AppJsonEditor.svelte b/frontend/src/lib/components/apps/editor/AppJsonEditor.svelte index e60a149cfa..8078e6cc7f 100644 --- a/frontend/src/lib/components/apps/editor/AppJsonEditor.svelte +++ b/frontend/src/lib/components/apps/editor/AppJsonEditor.svelte @@ -8,7 +8,7 @@ import { UserDraft } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { sendUserToast } from '$lib/toast' - import { userStore, workspaceStore } from '$lib/stores' + import { roleCapabilities, workspaceStore } from '$lib/stores' import { createEventDispatcher } from 'svelte' import { Globe, Loader2, Save } from 'lucide-svelte' import { deployRawAppValue } from '$lib/rawAppDeploy' @@ -111,7 +111,7 @@ {/if} {#snippet actions()} - {#if !$userStore?.operator} + {#if $roleCapabilities.apps === 'full'} <Button on:click={saveApp} startIcon={{ icon: isDraftOnly ? Save : Globe }} diff --git a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte index 0d4fb03704..d86713253a 100644 --- a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte +++ b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte @@ -25,6 +25,7 @@ import { isMenuHidden } from '$lib/components/sessions/sessionMode.svelte' import { setOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { useEditRights } from '$lib/operatorWriteRights' + import { recentItems } from '$lib/components/home/recentItems.svelte' let { workspace, @@ -179,6 +180,15 @@ isRawApp = !!lite?.raw_app executionMode = lite?.policy?.execution_mode ?? lite?.execution_mode summary = lite?.summary || undefined + // Only the route's own page is a visit; a session's preview tab opens it on its own. + if (ownsPageHeader) { + recentItems.record(workspace, { + kind: isRawApp ? 'raw_app' : 'app', + path: appPerms.path, + summary, + via: 'view' + }) + } } catch (_) { appPerms = undefined summary = undefined diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte index 1d3d46fc35..ff15d6a4fc 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte @@ -15,7 +15,7 @@ import WorkspaceScriptList from '../settingsPanel/mainInput/WorkspaceScriptList.svelte' import RunnableSelector from '../settingsPanel/mainInput/RunnableSelector.svelte' import { defaultScripts } from '$lib/stores' - import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import DefaultScripts from '$lib/components/DefaultScripts.svelte' import type { Preview } from '$lib/gen' import type { InlineScript } from '../../sharedTypes' @@ -39,7 +39,8 @@ let picker: Drawer | undefined = $state(undefined) const dispatch = createEventDispatcher() - const operatorBuilderApps = useOperatorBuilderApps() + const roleCaps = useRoleCapabilities() + const composeOnlyApps = $derived($roleCaps.apps === 'compose') async function inferInlineScriptSchema( language: Preview['language'], @@ -100,14 +101,14 @@ </script> <Drawer bind:this={picker} size="1000px"> - <DrawerContent title="Script/Flow Picker" on:close={picker.closeDrawer}> + <DrawerContent title="Fork a script" on:close={picker.closeDrawer}> <div> <div class="max-w-6xl"> <Tabs bind:selected={tab}> - <Tab value="workspacescripts" label="Workspace Scripts" icon={Building} /> + <Tab value="workspacescripts" label="Workspace scripts" icon={Building} /> - {#if !$operatorBuilderApps} - <Tab value="hubscripts" label="Hub Scripts" icon={Globe2} /> + {#if !composeOnlyApps} + <Tab value="hubscripts" label="Hub scripts" icon={Globe2} /> {/if} </Tabs> <div class="my-2"></div> @@ -128,13 +129,13 @@ <div class="flex flex-col px-4 gap-2 text-sm" id="app-editor-empty-runnable"> <div class="mt-2 flex justify-between gap-4" id="app-editor-runnable-header"> <div class="font-bold items-baseline truncate"> - {$operatorBuilderApps ? 'Choose a script or flow' : 'Choose a language'} + {composeOnlyApps ? 'Choose a script or flow' : 'Choose a language'} </div> <div class="flex gap-2"> {#if showScriptPicker} <RunnableSelector {unusedInlineScripts} {rawApps} on:pick hideCreateScript /> {/if} - {#if !$operatorBuilderApps} + {#if !composeOnlyApps} <Button on:click={() => picker?.openDrawer()} size="xs" @@ -161,7 +162,7 @@ <!-- Operators with builder rights compose runnables that already exist: the language pickers below all author code, which the backend refuses from them. --> - <div class="flex flex-row w-full gap-8" class:hidden={$operatorBuilderApps}> + <div class="flex flex-row w-full gap-8" class:hidden={composeOnlyApps}> <div id="app-editor-backend-runnables"> <div class="mb-1 text-sm font-semibold flex gap-4">Backend <DefaultScripts /> </div> diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte index 45dbe82c14..e3552d0e79 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte @@ -2,7 +2,7 @@ import { createBubbler, stopPropagation } from 'svelte/legacy' const bubble = createBubbler() - import { Button, Drawer, DrawerContent } from '$lib/components/common' + import { Alert, Button, Drawer, DrawerContent } from '$lib/components/common' import FlowGraphViewer from '$lib/components/FlowGraphViewer.svelte' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import FlowModuleScript from '$lib/components/flows/content/FlowModuleScript.svelte' @@ -18,7 +18,7 @@ CtxAppInput } from '../../inputType' import type { AppViewerContext } from '../../types' - import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { createEventDispatcher } from 'svelte' import { deepEqual } from 'fast-equals' import { computeFields } from './utils' @@ -32,12 +32,16 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import ScriptEditorDrawer from '$lib/components/flows/content/ScriptEditorDrawer.svelte' import FlowEditorDrawer from '$lib/components/flows/content/FlowEditorDrawer.svelte' - import { FlowService, ScriptService, type OpenFlow } from '$lib/gen' + import { FlowService, ResourceService, ScriptService, type OpenFlow } from '$lib/gen' + import Badge from '$lib/components/common/badge/Badge.svelte' + import { summarizeAgentBrain, type AgentTool } from '$lib/components/flows/agentResourceUtils' + import { agentRunnableSchema } from '$lib/components/raw_apps/agentRunnable' + import { agentMemoryMode } from '$lib/components/flows/agentFormFields' import { replaceScriptPlaceholderWithItsValues } from '$lib/hub' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderApps = useOperatorBuilderApps() + const roleCaps = useRoleCapabilities() interface Props { runnable: RunnableByPath @@ -149,6 +153,47 @@ } } + let agentInfo: + | { + description?: string + rows: { label: string; value: string }[] + tools: string[] + memoryOff: boolean + } + | undefined = $state() + + async function refreshAgent(runnable: RunnableByPath) { + hubFlowPreview = undefined + try { + const agent = await ResourceService.getResource({ + workspace: $operatingWorkspace ?? '', + path: runnable.path + }) + const config = agent.value as any + agentInfo = { + description: agent.description ?? undefined, + rows: summarizeAgentBrain(config), + tools: ((config?.tools ?? []) as AgentTool[]).map( + (t) => t.summary || t.value?.tool_type || t.id + ), + memoryOff: agentMemoryMode(config?.memory) === 'off' + } + const schema = agentRunnableSchema(config?.memory) + if (!deepEqual(runnable.schema, schema)) runnable.schema = schema + // Every input of a turn comes from its caller: a static one would be pinned by the + // deployed policy, answering every viewer's message with the same one. + if ( + Object.values(fields ?? {}).some((f) => f?.type !== 'user') || + !deepEqual(Object.keys(fields ?? {}).sort(), Object.keys(schema.properties).sort()) + ) { + fields = computeFields(schema, true, {}) + } + } catch (e) { + notFound = true + console.error(e) + } + } + async function fork(path: string) { let { content, language, schema } = await getScriptByPath(path) if (!schema || typeof schema == 'string' || Object.keys(schema).length == 0) { @@ -205,6 +250,8 @@ refreshScript(runnable) } else if (runnable.runType == 'flow') { refreshFlow(runnable) + } else if (runnable.runType == 'agent') { + refreshAgent(runnable) } else { hubFlowPreview = undefined } @@ -352,6 +399,17 @@ Details </Button> {/if} + {:else if runnable.runType == 'agent'} + <Button + variant="default" + unifiedSize="md" + startIcon={{ icon: Pen }} + endIcon={{ icon: ExternalLink }} + target="_blank" + href="/agents/edit/{runnable.path}?workspace={$operatingWorkspace}" + > + Edit + </Button> {:else} <Button size="xs" @@ -363,7 +421,7 @@ > Edit </Button> - {#if !$operatorBuilderApps} + {#if $roleCaps.apps !== 'compose'} <Button size="xs" variant="default" @@ -376,45 +434,47 @@ </Button> {/if} {/if} - <Popover - floatingConfig={{ - middleware: [ - autoPlacement({ - allowedPlacements: [ - 'bottom-start', - 'bottom-end', - 'top-start', - 'top-end', - 'top', - 'bottom' - ] - }) - ] - }} - closeButton - contentClasses="block text-primary text-xs p-4 w-[20vh]" - > - {#snippet trigger()} - <Button - nonCaptureEvent={true} - btnClasses={'bg-surface text-primay hover:bg-hover'} - variant="default" - size="xs" - > - Cache - </Button> - {/snippet} - {#snippet content()} - {#if runnable.runType == 'flow' && isHubFlowPath(runnable.path)} - Since this is a reference to a hub flow, cache settings are managed from the flow after - you fork it into your workspace. - {:else} - Since this is a reference to a workspace {runnable.runType}, set the cache in the - {runnable.runType} settings directly by editing it. The cache will be shared by any app or - flow that uses this {runnable.runType}. - {/if} - {/snippet} - </Popover> + {#if runnable.runType != 'agent'} + <Popover + floatingConfig={{ + middleware: [ + autoPlacement({ + allowedPlacements: [ + 'bottom-start', + 'bottom-end', + 'top-start', + 'top-end', + 'top', + 'bottom' + ] + }) + ] + }} + closeButton + contentClasses="block text-primary text-xs p-4 w-[20vh]" + > + {#snippet trigger()} + <Button + nonCaptureEvent={true} + btnClasses={'bg-surface text-primay hover:bg-hover'} + variant="default" + size="xs" + > + Cache + </Button> + {/snippet} + {#snippet content()} + {#if runnable.runType == 'flow' && isHubFlowPath(runnable.path)} + Since this is a reference to a hub flow, cache settings are managed from the flow after + you fork it into your workspace. + {:else} + Since this is a reference to a workspace {runnable.runType}, set the cache in the + {runnable.runType} settings directly by editing it. The cache will be shared by any app or + flow that uses this {runnable.runType}. + {/if} + {/snippet} + </Popover> + {/if} <input onkeydown={stopPropagation(bubble('keydown'))} @@ -454,6 +514,36 @@ {:else} <FlowPathViewer path={runnable.path} fillAvailableHeight /> {/if} + {:else if runnable.runType == 'agent'} + <div class="flex flex-col gap-2 p-2"> + {#if agentInfo?.memoryOff} + <Alert type="info" size="xs" title="Managed memory is off"> + Each call is answered on its own inputs, so a chat would forget every turn. Pass + <code>previous_messages</code> to give it the history. + </Alert> + {/if} + {#if agentInfo?.description} + <p class="text-xs text-secondary">{agentInfo.description}</p> + {/if} + <dl class="flex flex-col gap-1"> + {#each agentInfo?.rows ?? [] as row (row.label)} + <div class="flex items-baseline gap-2 text-2xs"> + <dt class="text-tertiary shrink-0 w-28">{row.label}</dt> + <dd class="text-secondary truncate" title={row.value}>{row.value}</dd> + </div> + {/each} + {#if agentInfo?.tools.length} + <div class="flex items-baseline gap-2 text-2xs"> + <dt class="text-tertiary shrink-0 w-28">Tools</dt> + <dd class="flex flex-wrap gap-1"> + {#each agentInfo.tools as tool, i (i)} + <Badge color="gray">{tool}</Badge> + {/each} + </dd> + </div> + {/if} + </dl> + </div> {:else} Unrecognized runType {runnable.runType} {/if} 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 44f2adb9ac..f741f5511d 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte @@ -2,23 +2,35 @@ import { Button, Drawer, DrawerContent, Tab, Tabs } from '$lib/components/common' import PickHubScript from '$lib/components/flows/pickers/PickHubScript.svelte' import PickHubFlow from '$lib/components/flows/pickers/PickHubFlow.svelte' - import { Building, Globe2, MousePointer, Plus } from 'lucide-svelte' + import { Bot, Building, Globe2, MousePointer, Plus } from 'lucide-svelte' import InlineScriptList from './InlineScriptList.svelte' - import type { InlineScript, Runnable, StaticAppInput } from '$lib/components/apps/inputType' + import type { + InlineScript, + PathRunType, + Runnable, + StaticAppInput + } from '$lib/components/apps/inputType' import WorkspaceScriptList from './WorkspaceScriptList.svelte' import WorkspaceFlowList from './WorkspaceFlowList.svelte' + import WorkspaceAgentList from './WorkspaceAgentList.svelte' import { createEventDispatcher, untrack } from 'svelte' import type { Schema } from '$lib/common' import { emptySchema } from '$lib/utils' import { loadSchema } from '$lib/infer' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderApps = useOperatorBuilderApps() + const roleCaps = useRoleCapabilities() import { buildPathRunnableSelection } from './runnableSelectorUtils' - type TabType = 'hubscripts' | 'hubflows' | 'workspacescripts' | 'workspaceflows' | 'inlinescripts' + type TabType = + | 'hubscripts' + | 'hubflows' + | 'workspacescripts' + | 'workspaceflows' + | 'workspaceagents' + | 'inlinescripts' interface Props { defaultUserInput?: boolean @@ -47,6 +59,13 @@ ) let filter: string = $state('') let picker: Drawer | undefined = $state() + const selectLabel = $derived( + onlyFlow + ? 'Select a flow' + : rawApps + ? 'Select a script, flow or agent' + : 'Select a script or flow' + ) const dispatch = createEventDispatcher<{ pick: { @@ -57,7 +76,7 @@ async function loadSchemaFromTriggerable( path: string, - runType: 'script' | 'flow' | 'hubscript' + runType: PathRunType ): Promise<{ schema: Schema; summary: string | undefined }> { const schema = await loadSchema($operatingWorkspace!, path, runType) if (!schema.schema.order) { @@ -94,6 +113,20 @@ }) } + async function pickAgent(path: string) { + const selection = buildPathRunnableSelection( + path, + 'agent', + await loadSchemaFromTriggerable(path, 'agent'), + defaultUserInput, + rawApps + ) + dispatch('pick', { + runnable: selection.runnable, + fields: selection.fields + }) + } + async function pickHubScript(path: string) { const selection = buildPathRunnableSelection( path, @@ -154,22 +187,25 @@ </script> <Drawer bind:this={picker} size="1000px"> - <DrawerContent title="Script/Flow Picker" on:close={picker.closeDrawer}> + <DrawerContent title={selectLabel} on:close={picker.closeDrawer}> <div> <div class="max-w-6xl"> <Tabs bind:selected={tab}> {#if !onlyFlow} {#if !rawApps} - <Tab value="inlinescripts" label="Detached Inline Scripts" icon={Building} /> + <Tab value="inlinescripts" label="Detached inline scripts" icon={Building} /> {/if} - <Tab value="workspacescripts" label="Workspace Scripts" icon={Building} /> + <Tab value="workspacescripts" label="Workspace scripts" icon={Building} /> {/if} - <Tab value="workspaceflows" label="Workspace Flows" icon={Building} /> - {#if !$operatorBuilderApps} + <Tab value="workspaceflows" label="Workspace flows" icon={Building} /> + {#if rawApps && !onlyFlow} + <Tab value="workspaceagents" label="AI agents" icon={Bot} /> + {/if} + {#if $roleCaps.apps !== 'compose'} {#if !onlyFlow} - <Tab value="hubscripts" label="Hub Scripts" icon={Globe2} /> + <Tab value="hubscripts" label="Hub scripts" icon={Globe2} /> {/if} - <Tab value="hubflows" label="Hub Flows" icon={Globe2} /> + <Tab value="hubflows" label="Hub flows" icon={Globe2} /> {/if} </Tabs> <div class="my-2"></div> @@ -186,6 +222,8 @@ <WorkspaceScriptList on:pick={(e) => pickScript(e.detail)} /> {:else if tab == 'workspaceflows'} <WorkspaceFlowList on:pick={(e) => pickFlow(e.detail)} /> + {:else if tab == 'workspaceagents'} + <WorkspaceAgentList on:pick={(e) => pickAgent(e.detail)} /> {:else if tab == 'hubscripts'} <PickHubScript bind:filter on:pick={(e) => pickHubScript(e.detail.path)} /> {:else if tab == 'hubflows'} @@ -218,6 +256,6 @@ startIcon={{ icon: MousePointer }} btnClasses="truncate w-full" > - {#if onlyFlow}Select a flow{:else}Select a script or flow{/if} + {selectLabel} </Button> </div> diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceAgentList.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceAgentList.svelte new file mode 100644 index 0000000000..4335fedaf8 --- /dev/null +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceAgentList.svelte @@ -0,0 +1,83 @@ +<script lang="ts"> + import { createEventDispatcher, onMount } from 'svelte' + 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 { ResourceService, type ListableResource } from '$lib/gen' + import { emptyString } from '$lib/utils' + import { Skeleton } from '$lib/components/common' + import TextInput from '$lib/components/text_input/TextInput.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + + const operatingWorkspace = useOperatingWorkspace() + + let filter = $state('') + let agents: ListableResource[] | undefined = $state(undefined) + let filteredItems: (ListableResource & { marked?: string })[] = $state([]) + let prefilteredItems = $derived(agents ?? []) + + const dispatch = createEventDispatcher() + + onMount(async () => { + agents = await ResourceService.listResource({ + workspace: $operatingWorkspace!, + resourceType: 'ai_agent', + perPage: 300 + }) + }) +</script> + +<SearchItems + {filter} + items={prefilteredItems} + bind:filteredItems + f={(x) => (emptyString(x.description) ? x.path : x.description + ' (' + x.path + ')')} +/> +<div class="w-full mt-1 mb-4"> + <TextInput + bind:value={filter} + inputProps={{ + placeholder: 'Search workspace AI agents', + // The picker's drawer must not take the keys typed into its search. + onkeydown: (e) => e.stopPropagation() + }} + /> +</div> + +{#if agents} + {#if filteredItems.length == 0} + <NoItemFound /> + {:else} + <ul class="divide-y border rounded-md"> + {#each filteredItems as item (item)} + <li class="flex flex-row w-full"> + <button + class="p-4 gap-4 flex flex-row grow justify-between hover:bg-surface-hover bg-surface transition-all items-center rounded-md" + onclick={() => dispatch('pick', item.path)} + > + <div class="flex items-center gap-4"> + <RowIcon kind="agent" /> + + <div class="w-full text-left font-normal"> + <div class="text-primary flex-wrap text-md font-semibold mb-1"> + {#if item.marked} + {@html item.marked ?? ''} + {:else} + {emptyString(item.description) ? item.path : item.description} + {/if} + </div> + <div class="text-primary text-xs"> + {item.path} + </div> + </div> + </div> + </button> + </li> + {/each} + </ul> + {/if} +{:else} + {#each Array(10).fill(0) as _} + <Skeleton layout={[[4], 0.5]} /> + {/each} +{/if} diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts index 44e989e925..66eb1e21cf 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts @@ -1,5 +1,5 @@ import type { Schema } from '$lib/common' -import type { Runnable, StaticAppInput } from '$lib/components/apps/inputType' +import type { PathRunType, Runnable, StaticAppInput } from '$lib/components/apps/inputType' import { schemaToInputsSpec } from '$lib/components/apps/utils' import { defaultIfEmptyString } from '$lib/utils' @@ -10,7 +10,7 @@ export type LoadedRunnableSchema = { export function buildPathRunnableSelection( path: string, - runType: 'script' | 'flow' | 'hubscript', + runType: PathRunType, loadedSchema: LoadedRunnableSchema, defaultUserInput: boolean, rawApps: boolean diff --git a/frontend/src/lib/components/apps/inputType.ts b/frontend/src/lib/components/apps/inputType.ts index 8501372216..99aa5d8418 100644 --- a/frontend/src/lib/components/apps/inputType.ts +++ b/frontend/src/lib/components/apps/inputType.ts @@ -136,11 +136,14 @@ export type TemplateV2Input = { connections: InputConnectionEval[] } +/** `agent` (a saved AI agent run as one chat turn) exists in raw apps only. */ +export type PathRunType = 'script' | 'flow' | 'hubscript' | 'agent' + export type RunnableByPath = { name: string path: string schema: any - runType: 'script' | 'flow' | 'hubscript' + runType: PathRunType type: 'runnableByPath' | 'path' } diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte index 52772ce515..3c7abca060 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { userStore, workspaceStore } from '$lib/stores' + import { roleCapabilities, workspaceStore } from '$lib/stores' import { goto } from '$app/navigation' import Button from '$lib/components/common/button/Button.svelte' import FolderPicker from '$lib/components/FolderPicker.svelte' @@ -91,8 +91,8 @@ </section> {/if} - {#if !$userStore?.operator} - <!-- Operators only view existing pipelines — opening an arbitrary + {#if $roleCapabilities.code} + <!-- A role without code only views existing pipelines: opening an arbitrary folder is a build-a-new-pipeline affordance. --> <section class="flex flex-col gap-1"> <h3 class="text-sm font-semibold text-emphasis">Pick or create a folder</h3> diff --git a/frontend/src/lib/components/common/badge/Badge.svelte b/frontend/src/lib/components/common/badge/Badge.svelte index 09a56c427a..77d59ce6d4 100644 --- a/frontend/src/lib/components/common/badge/Badge.svelte +++ b/frontend/src/lib/components/common/badge/Badge.svelte @@ -65,7 +65,8 @@ ['dark-indigo']: 'bg-indigo-500 text-indigo-100 dark:bg-indigo-600 dark:text-indigo-200', ['dark-orange']: 'bg-orange-500 text-orange-100 dark:bg-orange-600 dark:text-orange-200', ['dark-violet']: 'bg-violet-500 text-violet-100 dark:bg-violet-600 dark:text-violet-200', - transparent: 'bg-transparent border' + transparent: 'bg-transparent border', + subtle: 'bg-transparent' } const selectedColors: Record<BadgeColor, string> = { @@ -86,7 +87,8 @@ ['dark-orange']: 'bg-orange-700 text-orange-100 dark:bg-orange-800 dark:text-orange-200', ['dark-violet']: 'bg-violet-700 text-violet-100 dark:bg-violet-800 dark:text-violet-200', // Keeps the unselected chip's border, so selecting one does not change its height. - transparent: 'bg-surface-accent-selected text-accent border border-surface-accent-selected' + transparent: 'bg-surface-accent-selected text-accent border border-surface-accent-selected', + subtle: 'bg-surface-accent-selected text-accent' } const hovers: Partial<Record<BadgeColor, string>> = { @@ -106,7 +108,8 @@ ['dark-indigo']: 'hover:bg-indigo-600 dark:hover:bg-indigo-700', ['dark-orange']: 'hover:bg-orange-600 dark:hover:bg-orange-700', ['dark-violet']: 'hover:bg-violet-600 dark:hover:bg-violet-700', - transparent: 'hover:bg-surface-hover dark:hover:border-gray-500' + transparent: 'hover:bg-surface-hover dark:hover:border-gray-500', + subtle: 'hover:bg-surface-hover' } let badgeClass = $derived( diff --git a/frontend/src/lib/components/common/badge/LabelBadge.svelte b/frontend/src/lib/components/common/badge/LabelBadge.svelte new file mode 100644 index 0000000000..698a585e82 --- /dev/null +++ b/frontend/src/lib/components/common/badge/LabelBadge.svelte @@ -0,0 +1,36 @@ +<script lang="ts"> + import type { Snippet } from 'svelte' + import Badge from './Badge.svelte' + import type { BadgeColor, BadgeIconProps } from './model' + + /** + * How a label, an owner or a folder reads wherever an item is tagged with it: the row's own + * labels and Home's quick filters both draw it, so the two cannot drift apart. + */ + interface Props { + icon?: BadgeIconProps['icon'] + color?: BadgeColor + title?: string + /** Makes it a filter: clickable, and marked with × once selected. */ + onclick?: (event: MouseEvent) => void + selected?: boolean + children?: Snippet + } + + let { icon: Icon, color = 'subtle', title, onclick, selected = false, children }: Props = $props() +</script> + +<Badge + {color} + {title} + {onclick} + clickable={!!onclick} + {selected} + class="inline-flex items-center gap-1 px-1.5 align-middle" +> + {#if Icon} + <Icon size={12} class="shrink-0" /> + {/if} + {@render children?.()} + {#if selected}✗{/if} +</Badge> diff --git a/frontend/src/lib/components/common/badge/LabelList.svelte b/frontend/src/lib/components/common/badge/LabelList.svelte new file mode 100644 index 0000000000..8fb15f8186 --- /dev/null +++ b/frontend/src/lib/components/common/badge/LabelList.svelte @@ -0,0 +1,33 @@ +<script lang="ts"> + import LabelBadge from './LabelBadge.svelte' + import type { BadgeColor, BadgeIconProps } from './model' + + interface Props { + labels: string[] | undefined | null + icon: BadgeIconProps['icon'] + /** Names where each label comes from in its tooltip, e.g. "Label". */ + titlePrefix: string + /** Shown as badges; the rest are counted, and named in the count's tooltip. */ + max?: number + color?: BadgeColor + } + + let { labels, icon, titlePrefix, max = 3, color = 'gray' }: Props = $props() +</script> + +{#if labels?.length} + <div class="flex items-center gap-0.5"> + {#each labels.slice(0, max) as label (label)} + <LabelBadge {color} {icon} title="{titlePrefix}: {label}">{label}</LabelBadge> + {/each} + {#if labels.length > max} + <LabelBadge + {color} + title={labels + .slice(max) + .map((l) => `${titlePrefix}: ${l}`) + .join('\n')}>+{labels.length - max}</LabelBadge + > + {/if} + </div> +{/if} diff --git a/frontend/src/lib/components/common/badge/model.ts b/frontend/src/lib/components/common/badge/model.ts index 03adf9f195..4ecfdd8ea4 100644 --- a/frontend/src/lib/components/common/badge/model.ts +++ b/frontend/src/lib/components/common/badge/model.ts @@ -1,6 +1,11 @@ type BaseColor = 'blue' | 'gray' | 'red' | 'green' | 'yellow' | 'indigo' | 'orange' | 'violet' export const ColorModifier = 'dark-' -export type BadgeColor = BaseColor | 'transparent' | `${typeof ColorModifier}${BaseColor}` +/** `transparent` is outlined; `subtle` has neither fill nor border. */ +export type BadgeColor = + | BaseColor + | 'transparent' + | 'subtle' + | `${typeof ColorModifier}${BaseColor}` export interface BadgeIconProps { position?: 'left' | 'right' diff --git a/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte b/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte index 6958de0338..49421e78b3 100644 --- a/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte +++ b/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte @@ -22,7 +22,7 @@ disabled?: boolean onClick?: () => void divider?: boolean - type?: 'action' | 'delete' + type?: 'action' | 'delete' | 'ai' shortcut?: string } @@ -129,7 +129,8 @@ ? CONTEXT_MENU_ITEM_DISABLED_CLASS : menuItem.type === 'delete' ? CONTEXT_MENU_ITEM_DELETE_CLASS - : CONTEXT_MENU_ITEM_HOVER_MELT_CLASS + : CONTEXT_MENU_ITEM_HOVER_MELT_CLASS, + menuItem.type === 'ai' && !menuItem.disabled && 'text-ai' )} use:melt={$item} onclick={() => handleItemClick(menuItem)} diff --git a/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte b/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte index 7635b900bb..96eb682456 100644 --- a/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte +++ b/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte @@ -16,7 +16,7 @@ import MSSqlServerIcon from '$lib/components/icons/MSSqlServerIcon.svelte' import BunIcon from '$lib/components/icons/BunIcon.svelte' import DenoIcon from '$lib/components/icons/DenoIcon.svelte' - import type { Script } from '$lib/gen' + import { languageLabel } from './languageLabels' import PHPIcon from '$lib/components/icons/PHPIcon.svelte' import RustIcon from '$lib/components/icons/RustIcon.svelte' import AnsibleIcon from '$lib/components/icons/AnsibleIcon.svelte' @@ -52,40 +52,6 @@ let { lang, width = 30, height = 30, scale = 1, size = undefined, ...rest }: Props = $props() - const languageLabel: Record< - Script['language'] | 'bunnative' | 'claudesandbox' | 'pisandbox', - String - > = { - python3: 'Python', - deno: 'TypeScript', - go: 'Go', - bash: 'Bash', - powershell: 'PowerShell', - nativets: 'HTTP', - bunnative: 'HTTP', - graphql: 'GraphQL', - postgresql: 'Postgresql', - bigquery: 'BigQuery', - oracledb: 'Oracle Database', - duckdb: 'DuckDB', - snowflake: 'Snowflake', - mysql: 'MySQL', - mssql: 'MS SQL Server', - bun: 'TypeScript', - php: 'PHP', - rust: 'Rust', - ansible: 'Ansible', - csharp: 'C#', - nu: 'Nu', - java: 'Java', - ruby: 'Ruby', - rlang: 'R', - dbt: 'dbt', - claudesandbox: 'Claude Sandbox', - pisandbox: 'Pi Sandbox' - // for related places search: ADD_NEW_LANG - } - const langToComponent: Record< | SupportedLanguage | 'pgsql' diff --git a/frontend/src/lib/components/common/languageIcons/LanguageTag.svelte b/frontend/src/lib/components/common/languageIcons/LanguageTag.svelte new file mode 100644 index 0000000000..610af5b0e8 --- /dev/null +++ b/frontend/src/lib/components/common/languageIcons/LanguageTag.svelte @@ -0,0 +1,11 @@ +<script lang="ts"> + import { languageLabel, languageShortLabel, type LabelledLanguage } from './languageLabels' + + let { lang }: { lang: LabelledLanguage } = $props() +</script> + +<!-- Quiet on purpose: it sits beside a title, and the title is what the eye is reading. --> +<span + class="shrink-0 text-3xs font-medium text-hint tracking-wide" + title={languageLabel[lang] ?? lang}>{languageShortLabel[lang] ?? lang}</span +> diff --git a/frontend/src/lib/components/common/languageIcons/languageLabels.ts b/frontend/src/lib/components/common/languageIcons/languageLabels.ts new file mode 100644 index 0000000000..142a2790ee --- /dev/null +++ b/frontend/src/lib/components/common/languageIcons/languageLabels.ts @@ -0,0 +1,68 @@ +import type { Script } from '$lib/gen' + +export type LabelledLanguage = Script['language'] | 'bunnative' | 'claudesandbox' | 'pisandbox' + +/** A language's name, as a tooltip or anywhere the full word fits. */ +export const languageLabel: Record<LabelledLanguage, string> = { + python3: 'Python', + deno: 'TypeScript', + go: 'Go', + bash: 'Bash', + powershell: 'PowerShell', + nativets: 'HTTP', + bunnative: 'HTTP', + graphql: 'GraphQL', + postgresql: 'Postgresql', + bigquery: 'BigQuery', + oracledb: 'Oracle Database', + duckdb: 'DuckDB', + snowflake: 'Snowflake', + mysql: 'MySQL', + mssql: 'MS SQL Server', + bun: 'TypeScript', + php: 'PHP', + rust: 'Rust', + ansible: 'Ansible', + csharp: 'C#', + nu: 'Nu', + java: 'Java', + ruby: 'Ruby', + rlang: 'R', + dbt: 'dbt', + claudesandbox: 'Claude Sandbox', + pisandbox: 'Pi Sandbox' + // for related places search: ADD_NEW_LANG +} + +/** A few letters for a list row, where a logo per row is more than the eye needs. Every SQL + * dialect reads "SQL": which one is the tooltip's job (`languageLabel`). */ +export const languageShortLabel: Record<LabelledLanguage, string> = { + python3: 'Py', + deno: 'TS', + bun: 'TS', + go: 'Go', + bash: 'Sh', + powershell: 'PS', + nativets: 'Rest', + bunnative: 'Rest', + graphql: 'GQL', + postgresql: 'SQL', + bigquery: 'SQL', + oracledb: 'SQL', + duckdb: 'SQL', + snowflake: 'SQL', + mysql: 'SQL', + mssql: 'SQL', + php: 'PHP', + rust: 'Rs', + ansible: 'Ans', + csharp: 'C#', + nu: 'Nu', + java: 'Java', + ruby: 'Rb', + rlang: 'R', + dbt: 'dbt', + claudesandbox: 'AI', + pisandbox: 'AI' + // for related places search: ADD_NEW_LANG +} diff --git a/frontend/src/lib/components/common/seconds/SecondsInput.svelte b/frontend/src/lib/components/common/seconds/SecondsInput.svelte index 9ca42379d4..ad4c0abee7 100644 --- a/frontend/src/lib/components/common/seconds/SecondsInput.svelte +++ b/frontend/src/lib/components/common/seconds/SecondsInput.svelte @@ -23,6 +23,10 @@ size?: ButtonType.UnifiedSize clearable?: boolean defaultValue?: number | undefined + /** For a value consumed at a coarser granularity, where seconds would have no effect. */ + hideSeconds?: boolean + /** Hides the "= N seconds" caption below the input. */ + hideTotal?: boolean onfocus?: (e: FocusEvent) => void } @@ -33,6 +37,8 @@ size = 'md', clearable = false, defaultValue = undefined, + hideSeconds = false, + hideTotal = false, onfocus }: Props = $props() @@ -193,30 +199,32 @@ ><span class="invisible">mins</span><span>{min && min > 1 ? 'mins' : 'min'}</span></span > </div> - <div class="flex items-baseline"> - <input - type="number" - class={segmentClass} - value={hasValue ? sec || 0 : ''} - placeholder="_ _" - min="0" - max="59" - {disabled} - oninput={(e) => handleInput(e, (v) => (sec = v), 59)} - onkeydown={(e) => - handleKeydown( - e, - () => sec, - (v) => (sec = v), - 59 - )} - onfocus={handleFocus} - onblur={handleBlur} - /> - <span class="text-secondary text-2xs inline-grid [&>*]:col-start-1 [&>*]:row-start-1" - ><span class="invisible">secs</span><span>{sec && sec > 1 ? 'secs' : 'sec'}</span></span - > - </div> + {#if !hideSeconds} + <div class="flex items-baseline"> + <input + type="number" + class={segmentClass} + value={hasValue ? sec || 0 : ''} + placeholder="_ _" + min="0" + max="59" + {disabled} + oninput={(e) => handleInput(e, (v) => (sec = v), 59)} + onkeydown={(e) => + handleKeydown( + e, + () => sec, + (v) => (sec = v), + 59 + )} + onfocus={handleFocus} + onblur={handleBlur} + /> + <span class="text-secondary text-2xs inline-grid [&>*]:col-start-1 [&>*]:row-start-1" + ><span class="invisible">secs</span><span>{sec && sec > 1 ? 'secs' : 'sec'}</span></span + > + </div> + {/if} </div> {#if clearable && !disabled && seconds != null && seconds !== defaultValue} <CloseButton @@ -229,11 +237,13 @@ /> {/if} </div> - {#if seconds != null} - <span class="text-2xs text-hint"> - = {seconds.toLocaleString()} second{seconds === 1 ? '' : 's'} - </span> - {:else} - <span class="text-2xs text-hint"> no time set </span> + {#if !hideTotal} + {#if seconds != null} + <span class="text-2xs text-hint"> + = {seconds.toLocaleString()} second{seconds === 1 ? '' : 's'} + </span> + {:else} + <span class="text-2xs text-hint"> no time set </span> + {/if} {/if} </div> diff --git a/frontend/src/lib/components/common/slack/SlackAppSetup.svelte b/frontend/src/lib/components/common/slack/SlackAppSetup.svelte new file mode 100644 index 0000000000..195893058f --- /dev/null +++ b/frontend/src/lib/components/common/slack/SlackAppSetup.svelte @@ -0,0 +1,21 @@ +<script lang="ts"> + import { ExternalLink } from 'lucide-svelte' + import { yaml } from 'svelte-highlight/languages' + import CopyableCodeBlock from '$lib/components/details/CopyableCodeBlock.svelte' + import { slackAppManifest } from './slackAppManifest' +</script> + +<div class="flex flex-col gap-2 text-xs text-primary"> + <span> + Create a Slack app <a href="https://api.slack.com/apps?new_app=1" target="_blank" + >in the Slack API console <ExternalLink size={12} class="inline-block" /></a + >: pick "From a manifest", then YAML, and paste the manifest below. Then copy the Client ID, + Client Secret and Signing Secret here. Socket Mode and token rotation must stay off. More in the + <a href="https://www.windmill.dev/docs/misc/setup_oauth#slack" target="_blank" + >Windmill docs <ExternalLink size={12} class="inline-block" /></a + >. + </span> + <div class="flex flex-col max-h-80 [&>div]:min-h-0"> + <CopyableCodeBlock code={slackAppManifest(window.location.origin)} language={yaml} /> + </div> +</div> diff --git a/frontend/src/lib/components/common/table/AgentRow.svelte b/frontend/src/lib/components/common/table/AgentRow.svelte index 05c15a582a..061112dec4 100644 --- a/frontend/src/lib/components/common/table/AgentRow.svelte +++ b/frontend/src/lib/components/common/table/AgentRow.svelte @@ -4,9 +4,9 @@ import DraftBadge from '$lib/components/DraftBadge.svelte' import type ShareModal from '$lib/components/ShareModal.svelte' import type DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' - import InheritedLabels from '$lib/components/InheritedLabels.svelte' + import RowLabels from './RowLabels.svelte' import type { ListableResource } from '$lib/gen' - import { userStore, workspaceStore } from '$lib/stores' + import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' import { createEventDispatcher } from 'svelte' import { Pen } from 'lucide-svelte' import Button from '../button/Button.svelte' @@ -14,7 +14,7 @@ import { keepsManagedMemory } from '$lib/components/flows/agentFormFields' import { agentMenuItems, deleteAgent } from '$lib/components/flows/agentActions' import AgentHistory from '$lib/components/flows/AgentHistory.svelte' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' import Row from './Row.svelte' import { selectMenuItems, type RowSelection } from './rowSelection' @@ -48,6 +48,8 @@ const dispatch = createEventDispatcher() + warmDeployUiSettings() + async function remove(path: string) { if (await deleteAgent($workspaceStore!, path)) dispatch('change') } @@ -84,6 +86,7 @@ > {#snippet badges()} <SharedBadge canWrite={agent.canWrite} extraPerms={agent.extra_perms} /> + <RowLabels inherited={agent.inherited_labels} /> <DraftBadge is_draft={agent.is_draft} draft_only={agent.draft_only} @@ -93,33 +96,27 @@ path={agent.path} onMigrated={() => dispatch('change')} /> - <InheritedLabels labels={agent.inherited_labels} /> {/snippet} {#snippet actions()} {#if agent.canWrite} <span class="hidden md:inline-flex"> - <Button - variant="subtle" - wrapperClasses="w-20" - unifiedSize="md" - startIcon={{ icon: Pen }} - href={editHref} - > + <Button variant="subtle" unifiedSize="sm" startIcon={{ icon: Pen }} href={editHref}> Edit </Button> </span> {/if} <Dropdown - items={async () => [ + size="sm" + items={() => [ ...selectMenuItems(rowSelection), ...agentMenuItems({ - deployUiSettings: await getDeployUiSettings(), + deployUiSettings: cachedDeployUiSettings(), path: agent.path, canWrite: agent.canWrite, draftOnly: Boolean(agent.draft_only), wsSpecific: agent.ws_specific, - operator: $userStore?.operator, + noCode: !$roleCapabilities.code, onPermissions: () => shareModal.openDrawer?.(agent.path, 'resource'), onDeploy: () => deploymentDrawer.openDrawer(agent.path, 'resource'), onHistory: () => history?.open(), diff --git a/frontend/src/lib/components/common/table/AppRow.svelte b/frontend/src/lib/components/common/table/AppRow.svelte index a318c1f412..7553b61870 100644 --- a/frontend/src/lib/components/common/table/AppRow.svelte +++ b/frontend/src/lib/components/common/table/AppRow.svelte @@ -5,14 +5,15 @@ import DraftBadge from '$lib/components/DraftBadge.svelte' import type ShareModal from '$lib/components/ShareModal.svelte' import { AppService, type ListableApp } from '$lib/gen' - import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' - import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { roleCapabilities, userStore, userWorkspaces, workspaceStore } from '$lib/stores' + import { roleCanAuthor } from '$lib/editRights' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { createEventDispatcher } from 'svelte' import Button from '../button/Button.svelte' import Row from './Row.svelte' import { selectMenuItems, type RowSelection } from './rowSelection' - import InheritedLabels from '$lib/components/InheritedLabels.svelte' + import RowLabels from './RowLabels.svelte' + import AskAiRowButton from './AskAiRowButton.svelte' import Badge from '../badge/Badge.svelte' import { ExternalLink, @@ -34,7 +35,8 @@ import { copyToClipboard } from '$lib/utils' import AppDeploymentHistory from '$lib/components/apps/editor/AppDeploymentHistory.svelte' import { isDeployable } from '$lib/utils_deployable' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' + import { menuGroups } from './menuGroups' import { editInForkAllowed, editInForkLabel, onEditInForkClick } from '$lib/utils/editInFork' import EditInForkButton from './EditInForkButton.svelte' import { isCloudHosted } from '$lib/cloud' @@ -68,7 +70,11 @@ }: Props = $props() const dispatch = createEventDispatcher() - const operatorBuilderApps = useOperatorBuilderApps() + + warmDeployUiSettings() + // A compose-only app role authors full-code apps, never low-code ones. + const canAuthorApp = $derived(roleCanAuthor(app.raw_app ? 'raw_app' : 'app', $roleCapabilities)) + const fullApps = $derived($roleCapabilities.apps === 'full') let appExport: { open: (path: string, rawApp?: boolean) => void } | undefined = $state(undefined) let appDeploymentHistory: AppDeploymentHistory | undefined = $state(undefined) @@ -127,6 +133,7 @@ <Badge small icon={{ icon: FileJson }}>Raw</Badge> {/if} <SharedBadge canWrite={app.canWrite} extraPerms={app.extra_perms} /> + <RowLabels labels={app.labels} inherited={app.inherited_labels} /> <DraftBadge is_draft={app.is_draft} draft_only={app.draft_only} @@ -137,36 +144,17 @@ path={app.path} onMigrated={() => dispatch('change')} /> - {#if app.labels?.length} - <div class="flex items-center gap-0.5"> - {#each app.labels.slice(0, 3) as label} - <Badge color="blue" small class="px-1" title="Label: {label}">{label}</Badge> - {/each} - {#if app.labels.length > 3} - <Badge - color="blue" - small - class="px-1" - title={app.labels - .slice(3) - .map((l) => 'Label: ' + l) - .join('\n')}>+{app.labels.length - 3}</Badge - > - {/if} - </div> - {/if} - <InheritedLabels labels={app.inherited_labels} /> - <div class="w-8 center-center"></div> {/snippet} {#snippet actions()} - <span class="hidden md:inline-flex gap-x-1"> + <span class="hidden md:inline-flex"> + <AskAiRowButton kind="app" path={app.path} summary={app.summary} rawApp={!!app.raw_app} /> {#if showEditButton && app.canWrite} <div> <Button aiId={`edit-app-button-${app.summary?.length > 0 ? app.summary : app.path}`} aiDescription={`Edits the app ${app.summary?.length > 0 ? app.summary : app.path}`} variant="subtle" - wrapperClasses="w-20" + unifiedSize="sm" startIcon={{ icon: Pen }} href="/apps{app.raw_app ? '_raw' : ''}/edit/{app.path}" > @@ -174,34 +162,163 @@ </Button> </div> {/if} - {#if !$userStore?.operator && !isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) && (!showEditButton || !app.canWrite)} + {#if $roleCapabilities.code && !isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) && (!showEditButton || !app.canWrite)} <EditInForkButton itemType={app.raw_app ? 'raw_app' : 'app'} path={app.path} /> {/if} </span> <Dropdown + size="sm" aiId={`app-row-dropdown-${app.summary?.length > 0 ? app.summary : app.path}`} aiDescription={`Open dropdown for app ${app.summary?.length > 0 ? app.summary : app.path} options`} - items={async () => { + items={() => { let { draft_only, canWrite, summary, execution_mode, path } = app const canEdit = canWrite && showEditButton if (draft_only) { - return [ - ...selectMenuItems(rowSelection), + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: fullApps ? 'View/Edit JSON' : 'View JSON', + icon: File, + action: () => { + loadAppJson() + } + }, + { + displayName: 'Move/Rename', + icon: FolderOpen, + action: () => { + // Addressed by the generated path its draft row sits at, but + // named by the path typed in the editor. + moveDrawer.openDrawer((app as any).draft_path ?? path, summary, 'app', { + storagePath: path, + rawApp: !!app.raw_app + }) + }, + disabled: !showEditButton, + hide: !fullApps + } + ], + [ + { + displayName: 'Delete', + icon: Trash, + action: async (event) => { + // TODO + // @ts-ignore + if (event?.shiftKey) { + await deleteApp(path) + dispatch('change') + } else { + deleteConfirmedCallback = async () => { + await deleteApp(path) + dispatch('change') + } + } + }, + type: 'delete', + // A draft-only row is always the authed user's own draft (the + // list endpoint only surfaces own/legacy draft-only rows), so + // discarding it never requires write permission on the path. The server + // lets one's own draft go without authoring rights; only a legacy one needs them. + disabled: !showEditButton, + hide: + !canAuthorApp && + app.draft_users?.length === 1 && + app.draft_users[0]?.username == null + } + ] + ) + } + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: fullApps ? 'View/Edit JSON' : 'View JSON', + icon: FileJson, + action: () => { + loadAppJson() + } + }, + { + displayName: 'Go to public page', + icon: ExternalLink, + action: async () => { + let secretUrl = await AppService.getPublicSecretOfApp({ + workspace: $workspaceStore ?? '', + path + }) + let url = + page.url.protocol + + '//' + + `${page.url.hostname}/public/${$workspaceStore}/${secretUrl}` + gotoUrl(url) + }, + hide: execution_mode != 'anonymous' + }, + { + displayName: 'Versions', + icon: History, + action: () => appDeploymentHistory?.open(), + hide: !canAuthorApp + } + ], + [ + { + displayName: 'Duplicate/Fork', + icon: GitFork, + href: `/apps${app.raw_app ? '_raw' : ''}/add?template=${path}`, + disabled: !showEditButton, + hide: !fullApps + }, + { + displayName: editInForkLabel($workspaceStore, $userWorkspaces), + icon: Pen, + // No `href`: the handler resolves the destination asynchronously, and a melt + // menu item's anchor navigates before a delegated onclick can preventDefault it. + action: (e) => onEditInForkClick(e, app.raw_app ? 'raw_app' : 'app', path), + hide: + !$roleCapabilities.code || + isCloudHosted() || + !editInForkAllowed($workspaceStore, $userWorkspaces) + }, + { + displayName: 'Copy path', + icon: Copy, + action: () => { + copyToClipboard(path) + } + } + ], + [ { displayName: 'Move/Rename', icon: FolderOpen, action: () => { - // Addressed by the generated path its draft row sits at, but - // named by the path typed in the editor. - moveDrawer.openDrawer((app as any).draft_path ?? path, summary, 'app', { - storagePath: path, - rawApp: !!app.raw_app - }) + moveDrawer.openDrawer(path, summary, 'app') }, - disabled: !showEditButton, - hide: $userStore?.operator + disabled: !canEdit, + hide: !fullApps }, + { + displayName: 'Permissions', + icon: Shield, + action: () => { + shareModal.openDrawer && shareModal.openDrawer(path, 'app') + }, + hide: !canAuthorApp + }, + { + displayName: 'Deploy to staging/prod', + icon: ChevronUpSquare, + action: () => { + deploymentDrawer.openDrawer(path, 'app') + }, + hide: !fullApps || !isDeployable('app', path, cachedDeployUiSettings()) + } + ], + [ { displayName: 'Delete', icon: Trash, @@ -219,130 +336,11 @@ } }, type: 'delete', - // A draft-only row is always the authed user's own draft (the - // list endpoint only surfaces own/legacy draft-only rows), so - // discarding it never requires write permission on the path. - disabled: !showEditButton, - hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) - }, - { - displayName: $userStore?.operator ? 'View JSON' : 'View/Edit JSON', - icon: File, - action: () => { - loadAppJson() - } + disabled: !canEdit, + hide: !canAuthorApp } ] - } - return [ - ...selectMenuItems(rowSelection), - { - displayName: 'Duplicate/Fork', - icon: GitFork, - href: `/apps${app.raw_app ? '_raw' : ''}/add?template=${path}`, - disabled: !showEditButton, - hide: $userStore?.operator - }, - { - displayName: editInForkLabel($workspaceStore, $userWorkspaces), - icon: Pen, - // No `href`: the handler resolves the destination asynchronously, and a melt - // menu item's anchor navigates before a delegated onclick can preventDefault it. - action: (e) => onEditInForkClick(e, app.raw_app ? 'raw_app' : 'app', path), - hide: - $userStore?.operator || - isCloudHosted() || - !editInForkAllowed($workspaceStore, $userWorkspaces) - }, - { - displayName: 'Move/Rename', - icon: FolderOpen, - action: () => { - moveDrawer.openDrawer(path, summary, 'app') - }, - disabled: !canEdit, - hide: $userStore?.operator - }, - ...(isDeployable('app', path, await getDeployUiSettings()) - ? [ - { - displayName: 'Deploy to staging/prod', - icon: ChevronUpSquare, - action: () => { - deploymentDrawer.openDrawer(path, 'app') - }, - hide: $userStore?.operator - } - ] - : []), - { - displayName: $userStore?.operator ? 'View JSON' : 'View/Edit JSON', - icon: FileJson, - action: () => { - loadAppJson() - } - }, - { - displayName: 'Deployments', - icon: History, - action: () => appDeploymentHistory?.open(), - hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) - }, - { - displayName: 'Permissions', - icon: Shield, - action: () => { - shareModal.openDrawer && shareModal.openDrawer(path, 'app') - }, - hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) - }, - { - displayName: 'Copy path', - icon: Copy, - action: () => { - copyToClipboard(path) - } - }, - ...(execution_mode == 'anonymous' - ? [ - { - displayName: 'Go to public page', - icon: ExternalLink, - action: async () => { - let secretUrl = await AppService.getPublicSecretOfApp({ - workspace: $workspaceStore ?? '', - path - }) - let url = - page.url.protocol + - '//' + - `${page.url.hostname}/public/${$workspaceStore}/${secretUrl}` - gotoUrl(url) - } - } - ] - : []), - { - displayName: 'Delete', - icon: Trash, - action: async (event) => { - // TODO - // @ts-ignore - if (event?.shiftKey) { - await deleteApp(path) - dispatch('change') - } else { - deleteConfirmedCallback = async () => { - await deleteApp(path) - dispatch('change') - } - } - }, - type: 'delete', - disabled: !canEdit, - hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) - } - ] + ) }} on:open={() => { menuOpen = true diff --git a/frontend/src/lib/components/common/table/AskAiRowButton.svelte b/frontend/src/lib/components/common/table/AskAiRowButton.svelte new file mode 100644 index 0000000000..cc950d6c87 --- /dev/null +++ b/frontend/src/lib/components/common/table/AskAiRowButton.svelte @@ -0,0 +1,30 @@ +<script lang="ts"> + import Button from '../button/Button.svelte' + import { + homeComposerContext, + itemContextElement + } from '$lib/components/sessions/homeComposerContext.svelte' + import type { BulkKind } from '$lib/components/home/homeSelection.svelte' + + let { + kind, + path, + summary, + rawApp + }: { kind: BulkKind; path: string; summary?: string; rawApp?: boolean } = $props() + + let element = $derived(itemContextElement({ kind, path, summary: summary || undefined, rawApp })) +</script> + +{#if element && homeComposerContext.available} + <Button + variant="subtle" + unifiedSize="sm" + btnClasses="!text-ai font-medium" + title="Add to AI session context" + aria-label="Add to AI session context" + onClick={() => element && homeComposerContext.attach(element)} + > + +@ + </Button> +{/if} diff --git a/frontend/src/lib/components/common/table/EditInForkButton.svelte b/frontend/src/lib/components/common/table/EditInForkButton.svelte index fe5c6bc193..22156409b7 100644 --- a/frontend/src/lib/components/common/table/EditInForkButton.svelte +++ b/frontend/src/lib/components/common/table/EditInForkButton.svelte @@ -35,7 +35,7 @@ <Button variant="subtle" wrapperClasses="max-w-56" - unifiedSize="md" + unifiedSize="sm" startIcon={{ icon: Pen }} {href} onClick={(e) => onEditInForkClick(e, itemType, path, { hasHref: true })} diff --git a/frontend/src/lib/components/common/table/FlowRow.svelte b/frontend/src/lib/components/common/table/FlowRow.svelte index 65690121ab..eb58ecbc3f 100644 --- a/frontend/src/lib/components/common/table/FlowRow.svelte +++ b/frontend/src/lib/components/common/table/FlowRow.svelte @@ -7,7 +7,7 @@ import DraftBadge from '$lib/components/DraftBadge.svelte' import type ShareModal from '$lib/components/ShareModal.svelte' import { FlowService, type Flow } from '$lib/gen' - import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' + import { roleCapabilities, userStore, userWorkspaces, workspaceStore } from '$lib/stores' import { useEditRights } from '$lib/operatorWriteRights' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { createEventDispatcher } from 'svelte' @@ -32,12 +32,15 @@ Archive, Copy, Eye, - HistoryIcon + HistoryIcon, + Clock } from 'lucide-svelte' import FlowHistory from '$lib/components/flows/FlowHistory.svelte' import ChatFlowBadge from '$lib/components/flows/ChatFlowBadge.svelte' - import InheritedLabels from '$lib/components/InheritedLabels.svelte' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import RowLabels from './RowLabels.svelte' + import AskAiRowButton from './AskAiRowButton.svelte' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' + import { menuGroups, submenu } from './menuGroups' import { editInForkAllowed, editInForkLabel, onEditInForkClick } from '$lib/utils/editInFork' import EditInForkButton from './EditInForkButton.svelte' import { isCloudHosted } from '$lib/cloud' @@ -85,6 +88,8 @@ const dispatch = createEventDispatcher() + warmDeployUiSettings() + async function archiveFlow(path: string, archived: boolean): Promise<void> { try { await FlowService.archiveFlowByPath({ @@ -159,6 +164,7 @@ <Badge color="red" baseClass="border">archived</Badge> {/if} <SharedBadge canWrite={flow.canWrite} extraPerms={flow.extra_perms} /> + <RowLabels labels={flow.labels} inherited={flow.inherited_labels} /> <DraftBadge is_draft={flow.is_draft} draft_only={flow.draft_only} @@ -169,35 +175,15 @@ path={flow.path} onMigrated={() => dispatch('change')} /> - {#if flow.labels?.length} - <div class="flex items-center gap-0.5"> - {#each flow.labels.slice(0, 3) as label} - <Badge color="blue" small class="px-1" title="Label: {label}">{label}</Badge> - {/each} - {#if flow.labels.length > 3} - <Badge - color="blue" - small - class="px-1" - title={flow.labels - .slice(3) - .map((l) => 'Label: ' + l) - .join('\n')}>+{flow.labels.length - 3}</Badge - > - {/if} - </div> - {/if} - <InheritedLabels labels={flow.inherited_labels} /> - <div class="w-8 center-center"></div> {/snippet} {#snippet actions()} - <span class="hidden md:inline-flex gap-x-1"> + <span class="hidden md:inline-flex"> + <AskAiRowButton kind="flow" path={flow.path} summary={flow.summary} /> {#if !hideForOperator && showEditButton && flow.canWrite && !flow.archived} <div> <Button variant="subtle" - wrapperClasses="w-20" - unifiedSize="md" + unifiedSize="sm" startIcon={{ icon: Pen }} href="/flows/edit/{flow.path}" aiId={`edit-flow-button-${flow.summary?.length > 0 ? flow.summary : flow.path}`} @@ -207,34 +193,163 @@ </Button> </div> {/if} - <!-- Hidden from every operator, builder rights included. --> - {#if !$userStore?.operator && !isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) && (!showEditButton || !flow.canWrite)} + <!-- Hidden from every role without code, flow composers included. --> + {#if $roleCapabilities.code && !isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) && (!showEditButton || !flow.canWrite)} <EditInForkButton itemType="flow" path={flow.path} /> {/if} </span> <Dropdown + size="sm" aiId={`flow-row-dropdown-${flow.summary?.length > 0 ? flow.summary : flow.path}`} aiDescription={`Open dropdown for flow ${flow.summary?.length > 0 ? flow.summary : flow.path} options`} - items={async () => { + items={() => { let { draft_only, path, archived } = flow let owner = isOwner(path, $userStore, $workspaceStore) const canEdit = flow.canWrite && showEditButton if (draft_only) { - return [ - ...selectMenuItems(rowSelection), + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: 'Move/Rename', + icon: FolderOpen, + action: () => { + // Addressed by the generated path its draft row sits at, but + // named by the path typed in the editor. + moveDrawer.openDrawer((flow as any).draft_path ?? path, flow.summary, 'flow', { + storagePath: path + }) + }, + disabled: !showEditButton, + hide: hideForOperator + } + ], + [ + { + displayName: 'Delete', + icon: Trash, + action: (event) => { + // @ts-ignore + if (event?.shiftKey) { + deleteFlow(path) + } else { + deleteConfirmedCallback = () => { + deleteFlow(path) + } + } + }, + type: 'delete', + // A draft-only row is always the authed user's own draft (the + // list endpoint only surfaces own/legacy draft-only rows), so + // discarding it never requires write permission on the path. + disabled: !showEditButton, + hide: hideForOperator + } + ] + ) + } + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: 'View runs', + icon: List, + href: `/runs/${path}` + }, + submenu('History', Clock, [ + { + displayName: 'Versions', + icon: HistoryIcon, + action: () => { + flowHistory?.open() + }, + hide: hideForOperator + }, + { + displayName: 'Audit logs', + icon: Eye, + href: `/audit_logs?resource=${path}`, + hide: !$roleCapabilities.code || !$roleCapabilities.visibility.audit_logs + } + ]) + ], + [ + { + displayName: 'Duplicate/Fork', + icon: GitFork, + href: `/flows/add?template=${path}`, + disabled: !showEditButton, + hide: hideForOperator + }, + { + displayName: editInForkLabel($workspaceStore, $userWorkspaces), + icon: Pen, + // No `href`: the handler resolves the destination asynchronously, and a melt + // menu item's anchor navigates before a delegated onclick can preventDefault it. + action: (e) => onEditInForkClick(e, 'flow', path), + hide: + !$roleCapabilities.code || + isCloudHosted() || + !editInForkAllowed($workspaceStore, $userWorkspaces) + }, + { + displayName: 'Copy path', + icon: Copy, + action: () => { + copyToClipboard(path) + } + } + ], + [ { displayName: 'Move/Rename', icon: FolderOpen, action: () => { - // Addressed by the generated path its draft row sits at, but - // named by the path typed in the editor. - moveDrawer.openDrawer((flow as any).draft_path ?? path, flow.summary, 'flow', { - storagePath: path - }) + moveDrawer.openDrawer(path, flow.summary, 'flow') }, - disabled: !showEditButton, - hide: $userStore?.operator + disabled: !owner || archived || !canEdit, + hide: hideForOperator + }, + { + displayName: 'Schedule', + icon: Calendar, + action: () => { + scheduleEditor?.openNew(true, path) + }, + disabled: archived, + hide: hideForOperator || !$roleCapabilities.manage_schedules + }, + { + displayName: 'Permissions', + icon: Shield, + action: () => { + shareModal.openDrawer && shareModal.openDrawer(path, 'flow') + }, + hide: hideForOperator + }, + { + displayName: 'Deploy to staging/prod', + icon: ChevronUpSquare, + action: () => { + deploymentDrawer.openDrawer(path, 'flow') + }, + disabled: archived, + hide: + $roleCapabilities.flows !== 'full' || + !isDeployable('flow', path, cachedDeployUiSettings()) + } + ], + [ + { + displayName: archived ? 'Unarchive' : 'Archive', + icon: Archive, + action: () => { + path && archiveFlow(path, !archived) + }, + type: 'delete', + disabled: !owner || !canEdit, + hide: hideForOperator }, { displayName: 'Delete', @@ -250,127 +365,11 @@ } }, type: 'delete', - // A draft-only row is always the authed user's own draft (the - // list endpoint only surfaces own/legacy draft-only rows), so - // discarding it never requires write permission on the path. - disabled: !showEditButton, + disabled: !owner || !canEdit, hide: hideForOperator } ] - } - return [ - ...selectMenuItems(rowSelection), - { - displayName: 'View runs', - icon: List, - href: `/runs/${path}` - }, - { - displayName: 'Duplicate/Fork', - icon: GitFork, - href: `/flows/add?template=${path}`, - disabled: !showEditButton, - hide: hideForOperator - }, - { - displayName: editInForkLabel($workspaceStore, $userWorkspaces), - icon: Pen, - // No `href`: the handler resolves the destination asynchronously, and a melt - // menu item's anchor navigates before a delegated onclick can preventDefault it. - action: (e) => onEditInForkClick(e, 'flow', path), - hide: - $userStore?.operator || - isCloudHosted() || - !editInForkAllowed($workspaceStore, $userWorkspaces) - }, - { - displayName: 'Audit logs', - icon: Eye, - href: `/audit_logs?resource=${path}`, - hide: $userStore?.operator - }, - { - displayName: 'Move/Rename', - icon: FolderOpen, - action: () => { - moveDrawer.openDrawer(path, flow.summary, 'flow') - }, - disabled: !owner || archived || !canEdit, - hide: hideForOperator - }, - { - displayName: 'Copy path', - icon: Copy, - action: () => { - copyToClipboard(path) - } - }, - ...(isDeployable('flow', path, await getDeployUiSettings()) - ? [ - { - displayName: 'Deploy to staging/prod', - icon: ChevronUpSquare, - action: () => { - deploymentDrawer.openDrawer(path, 'flow') - }, - disabled: archived, - hide: $userStore?.operator - } - ] - : []), - { - displayName: 'Deployments', - icon: HistoryIcon, - action: () => { - flowHistory?.open() - }, - hide: hideForOperator - }, - { - displayName: 'Schedule', - icon: Calendar, - action: () => { - scheduleEditor?.openNew(true, path) - }, - disabled: archived, - hide: hideForOperator - }, - { - displayName: 'Permissions', - icon: Shield, - action: () => { - shareModal.openDrawer && shareModal.openDrawer(path, 'flow') - }, - hide: hideForOperator - }, - { - displayName: archived ? 'Unarchive' : 'Archive', - icon: Archive, - action: () => { - path && archiveFlow(path, !archived) - }, - type: 'delete', - disabled: !owner || !canEdit, - hide: hideForOperator - }, - { - displayName: 'Delete', - icon: Trash, - action: (event) => { - // @ts-ignore - if (event?.shiftKey) { - deleteFlow(path) - } else { - deleteConfirmedCallback = () => { - deleteFlow(path) - } - } - }, - type: 'delete', - disabled: !owner || !canEdit, - hide: hideForOperator - } - ] + ) }} on:open={() => { menuOpen = true diff --git a/frontend/src/lib/components/common/table/PipelineRow.svelte b/frontend/src/lib/components/common/table/PipelineRow.svelte index 334c8fb5fd..8a17b18c3c 100644 --- a/frontend/src/lib/components/common/table/PipelineRow.svelte +++ b/frontend/src/lib/components/common/table/PipelineRow.svelte @@ -6,7 +6,7 @@ planPipelineDelete, type PipelineDeletePlan } from '$lib/components/assets/AssetGraph/pipelineDelete' - import { userStore, workspaceStore } from '$lib/stores' + import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' import { Loader2, Trash } from 'lucide-svelte' import Row from './Row.svelte' @@ -78,8 +78,9 @@ {depth} > {#snippet actions()} - {#if !$userStore?.operator} + {#if $roleCapabilities.code} <Dropdown + size="sm" items={[ { displayName: 'Delete', diff --git a/frontend/src/lib/components/common/table/RawAppRow.svelte b/frontend/src/lib/components/common/table/RawAppRow.svelte index be1c9f0150..c1feaa2a38 100644 --- a/frontend/src/lib/components/common/table/RawAppRow.svelte +++ b/frontend/src/lib/components/common/table/RawAppRow.svelte @@ -8,7 +8,7 @@ import type DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' import { Globe, Shield } from 'lucide-svelte' import { isDeployable } from '$lib/utils_deployable' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' interface Props { app: ListableRawApp & { canWrite: boolean } @@ -29,6 +29,8 @@ menuOpen = $bindable(false), keyboardSelected = false }: Props = $props() + + warmDeployUiSettings() </script> <Row @@ -47,11 +49,12 @@ {/snippet} {#snippet actions()} <Dropdown - items={async () => { + size="sm" + items={() => { let { path } = app return [ - ...(isDeployable('app', path, await getDeployUiSettings()) + ...(isDeployable('app', path, cachedDeployUiSettings()) ? [ { displayName: 'Deploy to prod/staging', diff --git a/frontend/src/lib/components/common/table/Row.svelte b/frontend/src/lib/components/common/table/Row.svelte index 01fb70e118..2d27f89851 100644 --- a/frontend/src/lib/components/common/table/Row.svelte +++ b/frontend/src/lib/components/common/table/Row.svelte @@ -9,6 +9,9 @@ import Tooltip from '../../meltComponents/Tooltip.svelte' import Checkbox from '../checkbox/Checkbox.svelte' import type { RowSelection } from './rowSelection' + import { HOVER_ACTIONS_CLASS, inUnruledList } from './unruledList' + + const unruled = inUnruledList() interface Props { marked: string | undefined @@ -180,8 +183,11 @@ data-row-selection-key={rowSelection?.key} data-row-keyboard-selected={keyboardSelected ? 'true' : undefined} class={twMerge( - 'group/row w-full inline-flex items-center gap-4 first-of-type:!border-t-0 first-of-type:rounded-t-md last-of-type:rounded-b-md [*:not(:last-child)]:border-b px-4 py-3 border-b last:border-b-0', - depth > 0 ? '!rounded-none' : '', + 'group/row w-full inline-flex items-center gap-4 px-4 py-3', + unruled + ? 'rounded-md' + : 'first-of-type:!border-t-0 first-of-type:rounded-t-md last-of-type:rounded-b-md [*:not(:last-child)]:border-b border-b last:border-b-0', + depth > 0 && !unruled ? '!rounded-none' : '', disabled ? 'opacity-25' : 'hover:bg-surface-hover', clickToSelect || inSelectionMode ? 'cursor-pointer select-none' : '', selected || rowSelection?.selected @@ -255,20 +261,15 @@ {/if} {#if badges} - <div class="hidden lg:flex flex-row gap-4 items-center"> + <div class="hidden lg:flex shrink-0 flex-row gap-4 items-center"> {@render badges?.()} </div> {/if} - {#if canFavorite && (kind == 'app' || kind == 'raw_app' || kind == 'script' || kind == 'flow' || kind == 'agent')} - <div class="center-center h-full text-xs font-semibold text-secondary w-9 shrink-0"> - <Star {kind} {path} {workspaceId} {summary} /> - </div> - {:else} - <div class="w-9 shrink-0"></div> - {/if} - - <div data-row-actions class="flex gap-1 items-center justify-end pr-2"> + <div + data-row-actions + class="flex shrink-0 items-center justify-end {unruled ? HOVER_ACTIONS_CLASS : ''}" + > {@render actions?.()} </div> </div> @@ -280,7 +281,7 @@ </div> {/if} <div class="grow min-w-0"> - <div class="text-emphasis flex items-center gap-2 text-left text-xs font-semibold"> + <div class="text-emphasis flex items-center gap-1.5 text-left text-xs font-semibold"> {#if customSummary} <div class="min-w-0">{@render customSummary()}</div> {:else} @@ -295,6 +296,19 @@ {#if titleBadge} <span class="shrink-0">{@render titleBadge()}</span> {/if} + {#if canFavorite && (kind == 'app' || kind == 'raw_app' || kind == 'script' || kind == 'flow' || kind == 'agent')} + <!-- Beside the title it marks: a star already set stays, an unset one shows on the + row's hover or keyboard focus only, so a list of titles doesn't read as a column of + outlines. Opacity, not visibility: a hidden button drops out of the Tab order. --> + <Star + {kind} + {path} + {workspaceId} + {summary} + size={13} + class="inline-flex shrink-0 p-px text-yellow-500 opacity-0 data-[starred]:opacity-100 group-hover/row:opacity-100 group-has-[:focus-visible]/row:opacity-100" + /> + {/if} </div> <div class="text-hint text-3xs truncate text-left font-normal" title={path}> {#if pathDisplay} diff --git a/frontend/src/lib/components/common/table/RowLabels.svelte b/frontend/src/lib/components/common/table/RowLabels.svelte new file mode 100644 index 0000000000..e07684f7cf --- /dev/null +++ b/frontend/src/lib/components/common/table/RowLabels.svelte @@ -0,0 +1,17 @@ +<script lang="ts"> + import { Folder, Tag } from 'lucide-svelte' + import LabelList from '../badge/LabelList.svelte' + + let { labels, inherited }: { labels?: string[] | null; inherited: string[] | undefined } = + $props() +</script> + +<!-- A row has little room beside its title: one of each kind shows, the rest are counted. --> +<LabelList {labels} icon={Tag} titlePrefix="Label" max={1} color="subtle" /> +<LabelList + labels={inherited} + icon={Folder} + titlePrefix="Label inherited from folder" + max={1} + color="subtle" +/> diff --git a/frontend/src/lib/components/common/table/ScriptRow.svelte b/frontend/src/lib/components/common/table/ScriptRow.svelte index 7ba327f343..5044cf4339 100644 --- a/frontend/src/lib/components/common/table/ScriptRow.svelte +++ b/frontend/src/lib/components/common/table/ScriptRow.svelte @@ -11,6 +11,7 @@ import { disableHubStore, hubBaseUrlStore, + roleCapabilities, userStore, userWorkspaces, workspaceStore @@ -28,7 +29,7 @@ import { isDeployable } from '$lib/utils_deployable' import type DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' - import { LanguageIcon } from '../languageIcons' + import LanguageTag from '../languageIcons/LanguageTag.svelte' import { Archive, Calendar, @@ -44,16 +45,20 @@ Shield, Trash, History, - FileText + FileText, + Clock, + Send } from 'lucide-svelte' import ScriptVersionHistory from '$lib/components/ScriptVersionHistory.svelte' import WacExportDrawer from '$lib/components/scripts/WacExportDrawer.svelte' import { Drawer, DrawerContent } from '..' import NoMainFuncBadge from '$lib/components/NoMainFuncBadge.svelte' - import InheritedLabels from '$lib/components/InheritedLabels.svelte' + import RowLabels from './RowLabels.svelte' + import AskAiRowButton from './AskAiRowButton.svelte' import Popover from '$lib/components/Popover.svelte' import Tooltip from '$lib/components/Tooltip.svelte' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' + import { menuGroups, submenu } from './menuGroups' import { claimTab, editInForkAllowed, @@ -103,6 +108,8 @@ const dispatch = createEventDispatcher() + warmDeployUiSettings() + async function archiveScript(path: string): Promise<void> { await ScriptService.archiveScriptByPath({ workspace: $workspaceStore!, path }) dispatch('change') @@ -207,6 +214,8 @@ > {/if} <SharedBadge canWrite={script.canWrite} extraPerms={script.extra_perms} /> + <RowLabels labels={script.labels} inherited={script.inherited_labels} /> + <!-- Last, so the draft badges line up down the list whatever labels each row has. --> <DraftBadge is_draft={script.is_draft} draft_only={script.draft_only} @@ -217,33 +226,16 @@ path={script.path} onMigrated={() => dispatch('change')} /> - {#if script.labels?.length} - <div class="flex items-center gap-0.5"> - {#each script.labels.slice(0, 3) as label} - <Badge color="blue" small class="px-1" title="Label: {label}">{label}</Badge> - {/each} - {#if script.labels.length > 3} - <Badge - color="blue" - small - class="px-1" - title={script.labels - .slice(3) - .map((l) => 'Label: ' + l) - .join('\n')}>+{script.labels.length - 3}</Badge - > - {/if} - </div> - {/if} - <InheritedLabels labels={script.inherited_labels} /> - <div class="w-8 center-center"> - <LanguageIcon lang={script.language} width={16} height={16} /> - </div> + {/snippet} + + {#snippet titleBadge()} + <LanguageTag lang={script.language} /> {/snippet} {#snippet actions()} - <span class="hidden md:inline-flex gap-x-1"> - {#if !$userStore?.operator} + <span class="hidden md:inline-flex"> + <AskAiRowButton kind="script" path={script.path} summary={script.summary} /> + {#if $roleCapabilities.code} {#if showEditButton} {#if script.use_codebase} <Badge @@ -257,8 +249,7 @@ aiId={`edit-script-button-${script.summary?.length > 0 ? script.summary : script.path}`} aiDescription={`Edits the script ${script.summary?.length > 0 ? script.summary : script.path}`} variant="subtle" - wrapperClasses="w-20" - unifiedSize="md" + unifiedSize="sm" startIcon={{ icon: Pen }} href="/scripts/edit/{script.path}" > @@ -273,14 +264,69 @@ {/if} </span> <Dropdown + size="sm" aiId={`script-row-dropdown-${script.summary?.length > 0 ? script.summary : script.path}`} aiDescription={`Open dropdown for script ${script.summary?.length > 0 ? script.summary : script.path} options`} - items={async () => { + items={() => { let owner = isOwner(script.path, $userStore, $workspaceStore) const canEdit = script.canWrite && showEditButton if (script.draft_only) { - return [ - ...selectMenuItems(rowSelection), + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: 'View code', + icon: Code, + action: () => { + showCode(script.path, script.summary) + } + }, + { + displayName: 'Move/Rename', + icon: FolderOpen, + action: () => { + // Addressed by the generated path its draft row sits at, but + // named by the path typed in the editor. + moveDrawer.openDrawer( + script.draft_path ?? script.path, + script.summary, + 'script', + { + storagePath: script.path + } + ) + }, + disabled: !showEditButton, + hide: !$roleCapabilities.code + } + ], + [ + { + displayName: 'Delete', + icon: Trash, + action: (event) => { + // TODO + // @ts-ignore + if (event?.shiftKey) { + deleteScript(script.path) + } else { + deleteConfirmedCallback = () => { + deleteScript(script.path) + } + } + }, + type: dlt, + // A draft-only row is always the authed user's own draft (the + // list endpoint only surfaces own/legacy draft-only rows), so + // discarding it never requires write permission on the path. + disabled: !showEditButton + } + ] + ) + } + return menuGroups( + selectMenuItems(rowSelection), + [ { displayName: 'View code', icon: Code, @@ -288,25 +334,154 @@ showCode(script.path, script.summary) } }, + { + displayName: 'View JSON/YAML', + icon: FileText, + action: async () => { + const fullScript = await ScriptService.getScriptByPath({ + workspace: $workspaceStore!, + path: script.path + }) + wacExportDrawer?.open(fullScript) + }, + hide: script.auto_kind !== 'wac' + }, + { + displayName: 'View runs', + icon: List, + href: `/runs/${script.path}` + }, + submenu('History', Clock, [ + { + displayName: 'Versions', + icon: History, + action: () => { + versionsDrawerOpen = true + } + }, + { + displayName: 'Audit logs', + icon: Eye, + href: `/audit_logs?resource=${script.path}`, + hide: !$roleCapabilities.code || !$roleCapabilities.visibility.audit_logs + } + ]) + ], + [ + { + displayName: 'Duplicate/Fork', + icon: GitFork, + href: `/scripts/add?template=${script.path}`, + disabled: !showEditButton, + hide: !$roleCapabilities.code + }, + { + displayName: editInForkLabel($workspaceStore, $userWorkspaces), + icon: Pen, + // No `href`: the handler resolves the destination asynchronously, and a melt + // menu item's anchor navigates before a delegated onclick can preventDefault it. + action: (e) => onEditInForkClick(e, 'script', script.path), + hide: + !$roleCapabilities.code || + isCloudHosted() || + !editInForkAllowed($workspaceStore, $userWorkspaces) + }, + { + displayName: 'Copy path', + icon: Copy, + action: () => { + copyToClipboard(script.path) + } + } + ], + [ { displayName: 'Move/Rename', icon: FolderOpen, action: () => { - // Addressed by the generated path its draft row sits at, but - // named by the path typed in the editor. - moveDrawer.openDrawer(script.draft_path ?? script.path, script.summary, 'script', { - storagePath: script.path - }) + moveDrawer.openDrawer(script.path, script.summary, 'script') }, - disabled: !showEditButton, - hide: $userStore?.operator + disabled: !owner || script.archived || !canEdit, + hide: !$roleCapabilities.code + }, + { + displayName: 'Schedule', + icon: Calendar, + action: () => { + scheduleEditor?.openNew(false, script.path) + }, + disabled: script.archived, + hide: !$roleCapabilities.code || !$roleCapabilities.manage_schedules + }, + { + displayName: 'Permissions', + icon: Shield, + action: () => { + shareModal.openDrawer && shareModal.openDrawer(script.path, 'script') + }, + disabled: script.archived, + hide: !$roleCapabilities.code + }, + submenu('Deploy & publish', Send, [ + { + displayName: 'Deploy to staging/prod', + icon: ChevronUpSquare, + action: () => { + deploymentDrawer.openDrawer(script.path, 'script') + }, + disabled: script.archived, + hide: + !$roleCapabilities.code || + !isDeployable('script', script.path, cachedDeployUiSettings()) + }, + { + displayName: 'Publish to Hub', + icon: Globe2, + action: async () => { + // The row only carries metadata, so the code has to be fetched first; the tab is + // claimed before that, since Safari won't open one after an await. + const tab = claimTab() + try { + const fullScript = await ScriptService.getScriptByPath({ + workspace: $workspaceStore!, + path: script.path + }) + const url = scriptToHubUrl(fullScript, $hubBaseUrlStore).toString() + if (tab) { + tab.show(url) + } else if (!window.open(url)) { + sendUserToast('Allow popups to publish this script to the Hub', true) + } + } catch (e: any) { + tab?.discard() + sendUserToast( + `Could not load ${script.path}: ${e?.body ?? e?.message ?? e}`, + true + ) + } + }, + // Operators can't write scripts, so they have nothing to publish. + hide: $disableHubStore || !$roleCapabilities.code + } + ]) + ], + [ + { + displayName: script.archived ? 'Unarchive' : 'Archive', + icon: Archive, + action: () => { + script.archived + ? script.path && unarchiveScript(script.path) + : script.path && archiveScript(script.path) + }, + type: 'delete', + disabled: !owner || !canEdit, + hide: !$roleCapabilities.code }, { displayName: 'Delete', icon: Trash, action: (event) => { - // TODO - // @ts-ignore if (event?.shiftKey) { deleteScript(script.path) } else { @@ -316,180 +491,11 @@ } }, type: dlt, - // A draft-only row is always the authed user's own draft (the - // list endpoint only surfaces own/legacy draft-only rows), so - // discarding it never requires write permission on the path. - disabled: !showEditButton + disabled: !canEdit, + hide: !$roleCapabilities.code || !($userStore?.is_admin || $userStore?.is_super_admin) } ] - } - return [ - ...selectMenuItems(rowSelection), - { - displayName: 'View code', - icon: Code, - action: () => { - showCode(script.path, script.summary) - } - }, - ...(script.auto_kind === 'wac' - ? [ - { - displayName: 'View JSON/YAML', - icon: FileText, - action: async () => { - const fullScript = await ScriptService.getScriptByPath({ - workspace: $workspaceStore!, - path: script.path - }) - wacExportDrawer?.open(fullScript) - } - } - ] - : []), - { - displayName: 'Duplicate/Fork', - icon: GitFork, - href: `/scripts/add?template=${script.path}`, - disabled: !showEditButton, - hide: $userStore?.operator - }, - { - displayName: editInForkLabel($workspaceStore, $userWorkspaces), - icon: Pen, - // No `href`: the handler resolves the destination asynchronously, and a melt - // menu item's anchor navigates before a delegated onclick can preventDefault it. - action: (e) => onEditInForkClick(e, 'script', script.path), - hide: - $userStore?.operator || - isCloudHosted() || - !editInForkAllowed($workspaceStore, $userWorkspaces) - }, - { - displayName: 'Move/Rename', - icon: FolderOpen, - action: () => { - moveDrawer.openDrawer(script.path, script.summary, 'script') - }, - disabled: !owner || script.archived || !canEdit, - hide: $userStore?.operator - }, - ...(isDeployable('script', script.path, await getDeployUiSettings()) - ? [ - { - displayName: 'Deploy to staging/prod', - icon: ChevronUpSquare, - action: () => { - deploymentDrawer.openDrawer(script.path, 'script') - }, - disabled: script.archived, - hide: $userStore?.operator - } - ] - : []), - { - displayName: 'View runs', - icon: List, - href: `/runs/${script.path}` - }, - { - displayName: 'Versions', - icon: History, - action: () => { - versionsDrawerOpen = true - } - }, - { - displayName: 'Audit logs', - icon: Eye, - href: `/audit_logs?resource=${script.path}`, - hide: $userStore?.operator - }, - { - displayName: 'Schedule', - icon: Calendar, - action: () => { - scheduleEditor?.openNew(false, script.path) - }, - disabled: script.archived, - hide: $userStore?.operator - }, - { - displayName: 'Permissions', - icon: Shield, - action: () => { - shareModal.openDrawer && shareModal.openDrawer(script.path, 'script') - }, - disabled: script.archived, - hide: $userStore?.operator - }, - { - displayName: 'Copy path', - icon: Copy, - action: () => { - copyToClipboard(script.path) - } - }, - { - displayName: 'Publish to Hub', - icon: Globe2, - action: async () => { - // The row only carries metadata, so the code has to be fetched first; the tab is - // claimed before that, since Safari won't open one after an await. - const tab = claimTab() - try { - const fullScript = await ScriptService.getScriptByPath({ - workspace: $workspaceStore!, - path: script.path - }) - const url = scriptToHubUrl(fullScript, $hubBaseUrlStore).toString() - if (tab) { - tab.show(url) - } else if (!window.open(url)) { - sendUserToast('Allow popups to publish this script to the Hub', true) - } - } catch (e: any) { - tab?.discard() - sendUserToast(`Could not load ${script.path}: ${e?.body ?? e?.message ?? e}`, true) - } - }, - // Operators can't write scripts, so they have nothing to publish. - hide: $disableHubStore || $userStore?.operator - }, - { - displayName: script.archived ? 'Unarchive' : 'Archive', - icon: Archive, - action: () => { - script.archived - ? script.path && unarchiveScript(script.path) - : script.path && archiveScript(script.path) - }, - type: 'delete', - disabled: !owner || !canEdit, - hide: $userStore?.operator - }, - - ...($userStore?.is_admin || $userStore?.is_super_admin - ? [ - { - displayName: 'Delete', - icon: Trash, - action: (event) => { - if (event?.shiftKey) { - deleteScript(script.path) - } else { - deleteConfirmedCallback = () => { - deleteScript(script.path) - } - } - }, - type: dlt, - disabled: !canEdit, - hide: $userStore?.operator - } - ] - : []) - ] + ) }} on:open={() => { menuOpen = true diff --git a/frontend/src/lib/components/common/table/menuGroups.ts b/frontend/src/lib/components/common/table/menuGroups.ts new file mode 100644 index 0000000000..7071b6f11e --- /dev/null +++ b/frontend/src/lib/components/common/table/menuGroups.ts @@ -0,0 +1,25 @@ +import type { Item } from '$lib/utils' + +/** + * Joins a row menu's groups into one list with a divider above each group. The divider rides on + * the group's first visible item, so a group whose items are all hidden leaves no stray line. + */ +export function menuGroups(...groups: Item[][]): Item[] { + const out: Item[] = [] + for (const group of groups) { + const visible = group.filter((item) => !item.hide) + if (visible.length === 0) continue + out.push({ ...visible[0], separatorTop: out.length > 0 }, ...visible.slice(1)) + } + return out +} + +/** + * A submenu for actions that share a heading. With a single visible child the child is shown + * in place, since a submenu of one is an extra hover for nothing. + */ +export function submenu(displayName: string, icon: any, children: Item[]): Item { + const visible = children.filter((item) => !item.hide) + if (visible.length === 1) return visible[0] + return { displayName, icon, submenuItems: visible, hide: visible.length === 0 } +} diff --git a/frontend/src/lib/components/common/table/unruledList.ts b/frontend/src/lib/components/common/table/unruledList.ts new file mode 100644 index 0000000000..9e7ef59caa --- /dev/null +++ b/frontend/src/lib/components/common/table/unruledList.ts @@ -0,0 +1,27 @@ +import { getContext, setContext } from 'svelte' + +const KEY = Symbol('unruledList') + +/** Marks the rows below as one unruled list (Home's items): no line between rows, a rounded + * hover, and row actions shown only on the row in use. Every other list keeps its ruled rows. */ +export function setUnruledList() { + setContext(KEY, true) +} + +export function inUnruledList(): boolean { + return getContext<boolean | undefined>(KEY) ?? false +} + +/** The divider an ordinary list row draws, or none in an unruled list. */ +export function rowRule(unruled: boolean): string { + return unruled ? 'rounded-md' : 'border-b' +} + +/** Row actions in an unruled list: shown for the row hovered, tabbed into, keyboard-selected, + * or with one of its menus open. Opacity rather than visibility, so Tab still reaches them; + * focus counts only when visible, since a menu hands focus back to its trigger on close and a + * mouse user would otherwise keep that row's actions up after leaving it. Needs `group/row` + * on the row. Set per child, not on the container: the menu trigger (`button[data-menu]`) + * stays visible so every row ends on the same control. */ +export const HOVER_ACTIONS_CLASS = + '*:opacity-0 *:transition-opacity *:duration-100 group-hover/row:*:opacity-100 group-has-[:focus-visible]/row:*:opacity-100 group-data-[row-keyboard-selected=true]/row:*:opacity-100 *:has-[[aria-expanded=true]]:opacity-100 [&>button[data-menu]]:opacity-100' diff --git a/frontend/src/lib/components/copilot/AIFormAssistant.svelte b/frontend/src/lib/components/copilot/AIFormAssistant.svelte index 48a46ad182..8b5daefa9d 100644 --- a/frontend/src/lib/components/copilot/AIFormAssistant.svelte +++ b/frontend/src/lib/components/copilot/AIFormAssistant.svelte @@ -55,7 +55,7 @@ {#snippet aiButton(unifiedSize: 'sm' | 'md')} <!-- The fallback is a plain Button rather than AskAiButton, whose own session branch would fire here too and open an empty session. --> - <OpenInSessionButton source={sessionSource} btnProps={{ unifiedSize }}> + <OpenInSessionButton source={sessionSource} btnProps={{ unifiedSize }} deferToHeader> {#snippet fallback()} <Button {unifiedSize} diff --git a/frontend/src/lib/components/copilot/AskAiButton.svelte b/frontend/src/lib/components/copilot/AskAiButton.svelte index 95ff47fb52..4b40c021a5 100644 --- a/frontend/src/lib/components/copilot/AskAiButton.svelte +++ b/frontend/src/lib/components/copilot/AskAiButton.svelte @@ -5,7 +5,7 @@ import { AIBtnClasses } from './chat/AIButtonStyle' import { prefersSessionHandoff } from './chat/global/gate' import { startSessionWithPrompt } from '$lib/components/sessions/sessionSwitch.svelte' - import { userStore } from '$lib/stores' + import { roleCapabilities } from '$lib/stores' interface Props { label?: string initialInput?: string @@ -16,7 +16,7 @@ // The label stays short ("Ask AI") for the search bar's inline row; the hover // text is where "new AI session" fits. - const handsOffToSession = $derived(prefersSessionHandoff($userStore?.operator)) + const handsOffToSession = $derived(prefersSessionHandoff(!$roleCapabilities.code)) export function onClick() { // No item to preview here — this carries a question, not a target — so the diff --git a/frontend/src/lib/components/copilot/ChatModelSettings.svelte b/frontend/src/lib/components/copilot/ChatModelSettings.svelte index a1e677d46b..70745eee1c 100644 --- a/frontend/src/lib/components/copilot/ChatModelSettings.svelte +++ b/frontend/src/lib/components/copilot/ChatModelSettings.svelte @@ -98,7 +98,12 @@ title={config.readOnly ? config.readOnlyReason : config.title} > <span class="flex items-center gap-1 min-w-0"> - <span class="truncate">{config.label}</span> + {#if config.shortLabel} + <span class="truncate hidden xl:inline">{config.label}</span> + <span class="truncate xl:hidden">{config.shortLabel}</span> + {:else} + <span class="truncate">{config.label}</span> + {/if} {#if effortLabel} <span class="shrink-0 text-tertiary">· {effortLabel}</span> {/if} diff --git a/frontend/src/lib/components/copilot/aiResourceProvider.ts b/frontend/src/lib/components/copilot/aiResourceProvider.ts index 91ae926dfc..cd80bb21c0 100644 --- a/frontend/src/lib/components/copilot/aiResourceProvider.ts +++ b/frontend/src/lib/components/copilot/aiResourceProvider.ts @@ -1,9 +1,20 @@ 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' } +} + /** The AI provider a resource of this type holds credentials for, if any. */ export function aiResourceProvider(resourceType: string | undefined): AIProvider | undefined { if (resourceType === 'openai_client_credentials_oauth') return 'openai' + if (resourceType === 'anthropic_federated') return 'anthropic' return resourceType && Object.hasOwn(AI_PROVIDERS, resourceType) ? (resourceType as AIProvider) : undefined diff --git a/frontend/src/lib/components/copilot/chat/AIChat.svelte b/frontend/src/lib/components/copilot/chat/AIChat.svelte index 301a8dba54..51a8dfa55b 100644 --- a/frontend/src/lib/components/copilot/chat/AIChat.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChat.svelte @@ -10,6 +10,7 @@ import HideButton from '$lib/components/apps/editor/settingsPanel/HideButton.svelte' import { SUPPORTED_CHAT_SCRIPT_LANGUAGES } from './script/core' import { copilotInfo } from '$lib/aiStore' + import type { ComposerSelection } from './composerBox' let { hideHeader = false, @@ -18,9 +19,17 @@ forceDisabledMessage = '', wideLayout = false, emptyHint, + starter = undefined, + viewTransitionNames = false, + onSent = undefined, inputPreface, + actingOn, + workModeLock = undefined, initialInstructions = undefined, - onDraftChange = undefined + onDraftChange = undefined, + initialAttachments = undefined, + onAttachmentsChange = undefined, + placeholder = undefined }: { hideHeader?: boolean hideModeSelector?: boolean @@ -35,10 +44,20 @@ // in; the narrow global-chat panel leaves it off. wideLayout?: boolean emptyHint?: import('svelte').Snippet + starter?: import('./starter/starterPrompts.svelte').ChatStarter + viewTransitionNames?: boolean + onSent?: () => void inputPreface?: import('svelte').Snippet - // Seed / observe the composer's draft text (forwarded to AIChatDisplay). + /** Forwarded to AIChatDisplay: where the session acts, first among the controls. */ + actingOn?: import('svelte').Snippet + workModeLock?: import('./workMode').WorkModeLock + // Seed / observe the composer's draft (forwarded to AIChatDisplay). initialInstructions?: string onDraftChange?: (text: string) => void + initialAttachments?: import('./messageDraft.svelte').DraftAttachments + onAttachmentsChange?: (attachments: import('./messageDraft.svelte').DraftAttachments) => void + /** Composer placeholder for the first message. Falls back to the per-AI-mode wording. */ + placeholder?: string } = $props() const isAdmin = $derived($userStore?.is_admin || $userStore?.is_super_admin) @@ -106,8 +125,12 @@ aiChatManager.sendRequest(options) } - export function focusInput() { - aiChatDisplay?.focusInput() + export function focusInput(selection?: ComposerSelection) { + aiChatDisplay?.focusInput(selection) + } + + export async function attachContext(element: import('./context').ContextElement) { + await aiChatDisplay?.attachContext(element) } const historyManager = aiChatManager.historyManager @@ -198,7 +221,15 @@ {hideModeSelector} {wideLayout} {emptyHint} + {starter} + {viewTransitionNames} + {onSent} {inputPreface} + {actingOn} + {workModeLock} {initialInstructions} {onDraftChange} + {initialAttachments} + {onAttachmentsChange} + {placeholder} ></AIChatDisplay> diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index b233728a19..a740c5fb5f 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -10,13 +10,9 @@ ArrowDown, AtSign, BookOpen, - ChevronDown, - ChevronsRight, CheckIcon, - ClipboardList, FileText, Folder, - Hand, HistoryIcon, KeyRound, MousePointer2, @@ -31,8 +27,8 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import { pendingUserAction, pendingUserActionDetail, type DisplayMessage } from './shared' - import { PLAN_MODE_TEXT_COLOR, PLAN_MODE_TRIGGER_CLASS } from './planMode' - import { PLAN_MODE_MESSAGES } from './planModeMessages' + import AutonomyModePicker from './AutonomyModePicker.svelte' + import { availableAutonomyModeOptions, resolveAutonomyMode } from './autonomyModes' import type { ContextElement } from './context' import ChatQuickActions from './ChatQuickActions.svelte' import ContextUsageIndicator from './ContextUsageIndicator.svelte' @@ -47,12 +43,18 @@ import Markdown from 'svelte-exmarkdown' import { twMerge } from 'tailwind-merge' import { AIAutonomyMode, AIMode } from './AIChatManager.svelte' + import { AIWorkMode, type WorkModeLock } from './workMode' import { getChatViewHost } from './chatViewHost' import { getAiChatManager } from './aiChatManagerContext' import ChatTypingIndicator from './ChatTypingIndicator.svelte' import ToolGroupDisplay from './ToolGroupDisplay.svelte' - import { chatItemKey, groupToolRuns } from './toolGroups' + import { chatItemKey, createChatItemGrouper } from './toolGroups' import AIChatInput from './AIChatInput.svelte' + import { + STARTER_PLACEHOLDER, + USE_STARTER_PLACEHOLDER, + type ComposerSelection + } from './composerBox' import AttachedFilesBar from './files/AttachedFilesBar.svelte' import QueuedMessageChip from './QueuedMessageChip.svelte' import JobsSegment from './JobsSegment.svelte' @@ -71,6 +73,12 @@ import { sendUserToast } from '$lib/toast' import Alert from '$lib/components/common/alert/Alert.svelte' import { copilotInfo } from '$lib/aiStore' + import SessionGreeting from './starter/SessionGreeting.svelte' + import ComposerSuggestions from './starter/ComposerSuggestions.svelte' + import type { DraftAttachments } from './messageDraft.svelte' + import type { ChatStarter } from './starter/starterPrompts.svelte' + import { isComposerOverlay } from './starter/composerCollapse' + import { smoothHeight } from './starter/smoothHeight' const MAX_YOLO_TOOLTIP_TOOLS = 8 const chatHost = getChatViewHost() @@ -89,80 +97,6 @@ let freeTierUsedPct = $derived(Math.min(100, Math.round((freeTier?.used_ratio ?? 0) * 100))) let showFreeTierUsage = $derived(!!freeTier && !freeTier.exhausted) - // One row per autonomy posture, in picker order, so adding one touches only this - // table. `isAvailable` hides the postures that would do nothing in the current AI - // mode, which is why the picker can be shorter than this list. - type AutonomyAvailability = { - autoAcceptEditsAvailable: boolean - autoAcceptToolConfirmationsAvailable: boolean - planModeAvailable: boolean - } - type AutonomyModeOption = { - mode: AIAutonomyMode - label: string - shortLabel?: string - icon: typeof Hand - iconColor: string - /** Tints the whole trigger, not just its icon. Only plan mode needs it. */ - triggerClass?: string - tooltip: (a: AutonomyAvailability) => string - isAvailable: (a: AutonomyAvailability) => boolean - } - // The one posture available everywhere, so also the fallback for a mode the - // current AI mode does not offer. - const askPermissionOption: AutonomyModeOption = { - mode: AIAutonomyMode.DEFAULT, - label: 'Ask permission', - icon: Hand, - iconColor: 'text-secondary', - tooltip: (a) => - a.autoAcceptEditsAvailable - ? 'Requires confirmation for edits and tool calls.' - : 'Requires confirmation for tool calls.', - isAvailable: () => true - } - const autonomyModeOptions: AutonomyModeOption[] = [ - { - mode: AIAutonomyMode.PLAN, - label: 'Plan (read-only)', - shortLabel: 'Plan', - icon: ClipboardList, - iconColor: PLAN_MODE_TEXT_COLOR, - triggerClass: PLAN_MODE_TRIGGER_CLASS, - tooltip: () => - 'Read-only: the assistant researches and drafts a plan for your approval before it can change anything.', - isAvailable: (a) => a.planModeAvailable - }, - askPermissionOption, - { - mode: AIAutonomyMode.ACCEPT_EDIT, - label: 'Auto-accept edits', - icon: ChevronsRight, - iconColor: 'text-accent', - tooltip: () => - 'Automatically accepts script and flow edits. Tool calls still ask for confirmation.', - isAvailable: (a) => a.autoAcceptEditsAvailable - }, - { - mode: AIAutonomyMode.YOLO, - label: 'Yolo (bypass permissions)', - shortLabel: 'Yolo', - icon: ChevronsRight, - iconColor: 'text-red-500', - tooltip: (a) => - a.autoAcceptEditsAvailable - ? 'Automatically accepts script and flow edits plus tool confirmations.' - : 'Automatically accepts tool confirmations.', - isAvailable: (a) => a.autoAcceptToolConfirmationsAvailable - } - ] - const autonomyModeOption = (mode: AIAutonomyMode) => - autonomyModeOptions.find((o) => o.mode === mode) ?? askPermissionOption - const autonomyModeLabel = (mode: AIAutonomyMode) => { - const option = autonomyModeOption(mode) - return option.shortLabel ?? option.label - } - let { messages, pastChats, @@ -183,10 +117,17 @@ hideModeSelector = false, wideLayout = false, emptyHint, + starter = undefined, + viewTransitionNames = false, + onSent = undefined, inputPreface, + actingOn, + workModeLock = undefined, footerSettings, initialInstructions = undefined, onDraftChange = undefined, + initialAttachments = undefined, + onAttachmentsChange = undefined, placeholder = undefined, scrollElement = $bindable(), onTranscriptScroll = undefined @@ -215,13 +156,30 @@ // off there. wideLayout?: boolean emptyHint?: Snippet + /** Open an empty chat as the block that starts a session: Home and an empty session + * both mount it, so the two are one entry point rather than look-alikes. Replaces + * `emptyHint`. */ + starter?: ChatStarter + /** Names the composer for the view transition between Home and AI Sessions, so it + * glides between its two places, a send from Home included: that lands it under the + * session's first message. Only one chat on the page may carry the name: a duplicate + * makes the browser skip the transition. */ + viewTransitionNames?: boolean + /** After the composer hands a new turn to the host. */ + onSent?: () => void inputPreface?: Snippet + /** Where the session acts: first among the controls after the attach button. */ + actingOn?: Snippet + /** Holds a session chat in Use, and says why in the picker. */ + workModeLock?: WorkModeLock /** The settings control at the footer's right edge, where the copilot puts its * model picker. A host that configures its turn elsewhere replaces it here. */ footerSettings?: Snippet - // Seed / observe the main composer's draft text (see AIChatInput). + // Seed / observe the main composer's draft (see AIChatInput). initialInstructions?: string onDraftChange?: (text: string) => void + initialAttachments?: DraftAttachments + onAttachmentsChange?: (attachments: DraftAttachments) => void /** Composer placeholder. Falls back to the per-AI-mode wording. */ placeholder?: string /** The transcript's scroll container. A host that paginates older messages @@ -238,7 +196,8 @@ const mcpMenu = new McpMenu(aiChatManager, () => assistantSettings?.open('mcp')) let plusMenuOpen = $state(false) let editingMessageIndex = $state<number | null>(null) - const chatItems = $derived(groupToolRuns(messages)) + const groupChatItems = createChatItemGrouper() + const chatItems = $derived(groupChatItems(messages)) // 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). @@ -357,18 +316,22 @@ chatHost.sendRequest({ instructions: suggestion }) } - export function focusInput() { + export function focusInput(selection?: ComposerSelection) { + aiChatInput?.focusInput(selection) + } + + /** Mention a workspace item in the draft, as "+" → Mention file does, and hand the user + * the caret after it. Focusing is what opens Home's one-line composer. */ + export async function attachContext(element: ContextElement) { + await mentionWorkspaceItem(element) aiChatInput?.focusInput() } $effect(() => { - if (aiChatInput) { - chatHost.setAiChatInput(aiChatInput) - } - - return () => { - chatHost.setAiChatInput(null) - } + const input = aiChatInput + if (!input) return + chatHost.setAiChatInput(input) + return () => chatHost.releaseAiChatInput(input) }) // Also shown for a run held by another tab, labeled with where it is: the @@ -601,7 +564,7 @@ function mentionWorkspaceItem(element: ContextElement) { void aiChatInput?.addContextToSelection(element) - aiChatInput?.insertMention(element.title) + return aiChatInput?.insertMention(element.title) } function onFolderInputChange(e: Event) { @@ -613,21 +576,15 @@ } const autonomyAvailability = $derived({ autoAcceptEditsAvailable: chatHost.autoAcceptEditsAvailable, - autoAcceptToolConfirmationsAvailable: chatHost.autoAcceptToolConfirmationsAvailable, - planModeAvailable: chatHost.planModeAvailable + autoAcceptToolConfirmationsAvailable: chatHost.autoAcceptToolConfirmationsAvailable }) - const availableAutonomyModeOptions = $derived( - autonomyModeOptions.filter((option) => option.isAvailable(autonomyAvailability)) - ) - // Fall back to ask-permission when the persisted mode isn't applicable in the - // current AI mode (e.g. auto-accept edits while in a mode without edits). const effectiveAutonomyMode = $derived( - availableAutonomyModeOptions.some((option) => option.mode === chatHost.autonomyMode) - ? chatHost.autonomyMode - : AIAutonomyMode.DEFAULT + resolveAutonomyMode(chatHost.autonomyMode, autonomyAvailability) + ) + const showAutonomyModeSelector = $derived( + !disabled && + (chatHost.workModesAvailable || availableAutonomyModeOptions(autonomyAvailability).length > 1) ) - const showAutonomyModeSelector = $derived(!disabled && availableAutonomyModeOptions.length > 1) - const effectiveAutonomyModeOption = $derived(autonomyModeOption(effectiveAutonomyMode)) // The typing-dots indicator implies the AI is busy, which is misleading while // the loop is parked on the user; surface a text pill instead so users know to @@ -635,10 +592,58 @@ // A step name hangs its icon in the column's left padding (see AssistantMessage), so a // transcript carrying one widens the padding, on both sides to keep the column centred. const agentGutter = $derived(messages.some((m) => m.role === 'assistant' && m.stepName)) + // The block's layout holds while the chat is empty, usable or not; only the taller box + // and the suggestions need a composer that can send. + const starterLayout = $derived(!!starter && messages.length === 0) + const heldInUse = $derived( + chatHost.workModesAvailable && (!!workModeLock || chatHost.workMode === AIWorkMode.USE) + ) + // Home is a page, not a pane: nothing there to centre in. + const centreComposer = $derived(starterLayout && starter?.where === 'session') + + // Home's composer at rest is one line. Focusing the field opens it; a press outside it or + // Escape puts it back, but only with nothing in the draft: leaving it open then means + // clearing the text later cannot fold it up under the caret. Opened by the field rather + // than any focus inside: the one-line row's model button would otherwise unmount under the + // menu it is opening. + let composerEl: HTMLDivElement | undefined = $state() + let composerOpened = $state(false) + const homeComposer = $derived(starterLayout && starter?.where === 'home') + // Anything the user has started (text, an attachment) or is in the middle of (they opened it + // and have not left) keeps it open, and so does a workspace small enough that the composer is + // the page's main way in. + // Until the input is bound, the draft it starts with is the one it is seeded with: reading + // it as empty collapses a remounted composer that holds text for a frame, and the box then + // animates open as if the user had opened it. + const seededDraftEmpty = $derived( + !initialInstructions?.trim() && + !initialAttachments?.pastes.length && + !initialAttachments?.images.length && + !initialAttachments?.files.length && + !initialAttachments?.blobs.length + ) + const composerCollapsed = $derived( + homeComposer && + !disabled && + !(starter?.where === 'home' && starter.fewItems) && + !composerOpened && + (aiChatInput ? aiChatInput.isDraftEmpty() : seededDraftEmpty) + ) + function closeComposer() { + if (aiChatInput?.isDraftEmpty() ?? true) composerOpened = false + } + function onComposerPointerDown(e: PointerEvent) { + if (!homeComposer || !composerOpened || composerEl?.contains(e.target as Node)) return + if (!isComposerOverlay(e.target)) closeComposer() + } + + // Home's composer is one block of the page and takes the page's column as it is. const columnClass = $derived( - wideLayout - ? `w-full max-w-3xl mx-auto ${agentGutter ? 'px-8' : 'px-7'}` - : `w-full max-w-2xl mx-auto ${agentGutter ? 'px-8' : 'px-3'}` + starter?.where === 'home' + ? 'w-full' + : wideLayout + ? `w-full max-w-3xl mx-auto ${agentGutter ? 'px-8' : 'px-7'}` + : `w-full max-w-2xl mx-auto ${agentGutter ? 'px-8' : 'px-3'}` ) const waitingForUserAction = $derived(chatHost.loading && !!pendingUserAction(messages)) @@ -694,6 +699,7 @@ const showFooterLeftControls = $derived( !footerMessageShown && (canAttachFiles || + !!actingOn || attachmentsOffReason !== undefined || showContextPicker || showAutonomyModeSelector || @@ -739,10 +745,12 @@ </div> {/snippet} +<svelte:document onpointerdown={onComposerPointerDown} /> + <!-- tabindex="-1": clicks on non-focusable chat content must move focus into the panel, or the Escape-to-stop focus check would wrongly reject them. --> <div - class="flex flex-col h-full relative outline-none" + class="flex flex-col h-full relative outline-none {starterLayout ? 'justify-center' : ''}" tabindex="-1" bind:this={panelEl} ondragenter={onPanelDragEnter} @@ -851,7 +859,21 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> </div> {/if} {#if messages.length === 0} - {#if emptyHint} + {#if starter} + <!-- The greeting rides on top of the centred composer instead of being centred with + it: it takes the space above, the spacer after the composer the same below. Home + has none: there the composer is one control among the page's. --> + {#if centreComposer} + <div class="flex-1 min-h-0 flex flex-col justify-end"> + <div + class={columnClass} + style:view-transition-name={viewTransitionNames ? 'greeting' : undefined} + > + <SessionGreeting /> + </div> + </div> + {/if} + {:else if emptyHint} {@render emptyHint()} {:else} <span class="text-2xs text-gray-500 dark:text-gray-400 text-center px-2 my-2" @@ -972,7 +994,27 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> <!-- Same horizontal padding as the transcript above: the composer's edges line up with the messages rather than sitting closer to the panel edge. --> - <div class="relative {columnClass} pb-2"> + <!-- The focus and key handlers take events bubbling from the field inside, which is the + interactive element; the group itself is never focused. --> + <!-- svelte-ignore a11y_no_noninteractive_element_interactions --> + <div + data-session-composer + role="group" + aria-label="Message composer" + bind:this={composerEl} + class="relative {columnClass} pb-2" + style:view-transition-name={viewTransitionNames ? 'composer' : undefined} + onfocusin={(e) => { + if (homeComposer && e.target instanceof HTMLTextAreaElement) composerOpened = true + }} + onkeydown={(e) => { + // A prevented Escape closed something inside first, such as the @-mention picker. + if (e.key !== 'Escape' || e.defaultPrevented) return + if (!homeComposer || !composerOpened) return + closeComposer() + if (aiChatInput?.isDraftEmpty() ?? true) (document.activeElement as HTMLElement)?.blur() + }} + > {#if showFlowPendingActionControls} <div class="absolute -top-10 w-full flex flex-row justify-center gap-2"> <Button @@ -1018,354 +1060,372 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> {#if inputPreface} {@render inputPreface()} {/if} - {#if showFreeTierUsage} + {#if showFreeTierUsage && !starterLayout} {@render freeTierUsageBanner()} {/if} <AIChatInput bind:this={aiChatInput} bind:selectedContext {availableContext} - {placeholder} + placeholder={starterLayout + ? heldInUse + ? USE_STARTER_PLACEHOLDER + : STARTER_PLACEHOLDER + : placeholder} {initialInstructions} {onDraftChange} + {initialAttachments} + {onAttachmentsChange} showContext={chatHost.mode !== AIMode.GLOBAL} {disabled} {pendingQuestionToolCallId} isFirstMessage={messages.length === 0} - /> - <div - class="mt-1 flex flex-row flex-wrap items-center gap-x-1.5 gap-y-1" - class:justify-between={showFooterLeftControls} - class:justify-end={!showFooterLeftControls} + hero={starterLayout} + collapsed={composerCollapsed} + chatIcon={homeComposer} + {onSent} > - {#if showFooterLeftControls} - <div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap"> - {#if showContextPicker && !disabled} - <Popover placement="bottom-start"> - {#snippet trigger()} - <Button - nonCaptureEvent - unifiedSize="2xs" - variant="default" - title="Add context" - iconOnly - startIcon={{ icon: AtSign }} - /> - {/snippet} - {#snippet content({ close })} - {#if chatHost.mode === AIMode.APP} - <AppAvailableContextList - {availableContext} - {selectedContext} - onSelect={(element) => { - void aiChatInput?.addContextToSelection(element) - close() - }} - /> - {:else} - <ChatContextPicker - {availableContext} - {selectedContext} - onSelect={(element) => { - void aiChatInput?.addContextToSelection(element) - aiChatInput?.insertMention(element.title) - close() - aiChatInput?.focusInput() - }} - onSelectWorkspaceItem={(element) => { - void aiChatInput?.addContextToSelection(element) - aiChatInput?.insertMention(element.title) - close() - aiChatInput?.focusInput() - }} - setShowing={(showing) => { - if (!showing) close() - }} - onSelectFile={(name) => { - aiChatInput?.insertFileMention(name) - close() - }} - /> - {/if} - {/snippet} - </Popover> - {/if} - {#if attachmentsOffReason} - <Tooltip small placement="top"> - <Button - nonCaptureEvent - unifiedSize="2xs" - variant="default" - iconOnly - disabled - startIcon={{ icon: Plus }} - /> - {#snippet text()} - <div class="max-w-64 text-xs">{attachmentsOffReason}</div> - {/snippet} - </Tooltip> - {:else if canAttachFiles} - <DropdownV2 - items={() => { - const closeMenu = () => (plusMenuOpen = false) - const inGlobal = chatHost.mode === AIMode.GLOBAL - if (inGlobal) { - skillsMenu.refresh() - mcpMenu.refresh() - } - return [ - { - displayName: 'Attach file or image', - icon: FileText, - action: () => { - plusMenuOpen = false - linkFiles() - } - }, - ...(canLinkFolders - ? [ - { - // A real (live) link needs the File System Access API; without it the - // folder is only snapshotted, so call it "Add folder", not "Link folder". - displayName: canUseFsAccess ? 'Link folder' : 'Add folder', - icon: Folder, - tooltip: canUseFsAccess - ? 'Linked live — the assistant reads the folder’s current files from disk and refreshes each turn.' - : 'Loaded as a snapshot — the folder’s files are copied into your browser (they won’t auto-update). For a live link that refreshes from disk, use a Chromium-based browser (Chrome, Edge).', - action: () => { - plusMenuOpen = false - linkFolder() - } - } - ] - : []), - ...(inGlobal - ? [ - { - displayName: 'Mention file', - icon: AtSign, - customSubmenu: WorkspaceMentionPicker, - customSubmenuProps: { - onSelect: mentionWorkspaceItem, - onAfterClose: () => aiChatInput?.focusInput() - } - } - ] - : []), - ...(inGlobal - ? [ - { - displayName: 'Skills', - icon: BookOpen, - separatorTop: true, - // Getters so the submenus fill in when their fetch lands - // rather than the whole menu waiting on it. - get submenuItems() { - return skillsMenu.items(closeMenu) - } - }, - { - displayName: 'MCP connections', - icon: Plug, - get submenuItems() { - return mcpMenu.items(closeMenu) - } - } - ] - : []) - ] - }} - placement="bottom-start" - fixedHeight={false} - closeOnItemClick={false} - bind:open={plusMenuOpen} - > - {#snippet buttonReplacement()} + {#snippet collapsedControls()} + {#if chatHost.supportsModelSettings} + <AIChatModelSettings promptSettings={false} /> + {/if} + {/snippet} + {#snippet toolbar()} + <div + class="flex flex-row flex-wrap items-center gap-x-1.5 gap-y-1" + class:justify-between={showFooterLeftControls} + class:justify-end={!showFooterLeftControls} + > + {#if showFooterLeftControls} + <div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap"> + {#if showContextPicker && !disabled} + <Popover placement="bottom-start"> + {#snippet trigger()} + <Button + nonCaptureEvent + unifiedSize="2xs" + variant="default" + title="Add context" + iconOnly + startIcon={{ icon: AtSign }} + /> + {/snippet} + {#snippet content({ close })} + {#if chatHost.mode === AIMode.APP} + <AppAvailableContextList + {availableContext} + {selectedContext} + onSelect={(element) => { + void aiChatInput?.addContextToSelection(element) + close() + }} + /> + {:else} + <ChatContextPicker + {availableContext} + {selectedContext} + onSelect={(element) => { + void mentionWorkspaceItem(element) + close() + aiChatInput?.focusInput() + }} + onSelectWorkspaceItem={(element) => { + void mentionWorkspaceItem(element) + close() + aiChatInput?.focusInput() + }} + setShowing={(showing) => { + if (!showing) close() + }} + onSelectFile={(name) => { + aiChatInput?.insertFileMention(name) + close() + }} + /> + {/if} + {/snippet} + </Popover> + {/if} + {#if attachmentsOffReason} <Tooltip small placement="top"> <Button nonCaptureEvent unifiedSize="2xs" - variant="default" + variant="subtle" iconOnly + disabled startIcon={{ icon: Plus }} /> + {#snippet text()} + <div class="max-w-64 text-xs">{attachmentsOffReason}</div> + {/snippet} + </Tooltip> + {:else if canAttachFiles} + <DropdownV2 + items={() => { + const closeMenu = () => (plusMenuOpen = false) + const inGlobal = chatHost.mode === AIMode.GLOBAL + if (inGlobal) { + skillsMenu.refresh() + mcpMenu.refresh() + } + return [ + { + displayName: 'Attach file or image', + icon: FileText, + action: () => { + plusMenuOpen = false + linkFiles() + } + }, + ...(canLinkFolders + ? [ + { + // A real (live) link needs the File System Access API; without it the + // folder is only snapshotted, so call it "Add folder", not "Link folder". + displayName: canUseFsAccess ? 'Link folder' : 'Add folder', + icon: Folder, + tooltip: canUseFsAccess + ? 'Linked live — the assistant reads the folder’s current files from disk and refreshes each turn.' + : 'Loaded as a snapshot — the folder’s files are copied into your browser (they won’t auto-update). For a live link that refreshes from disk, use a Chromium-based browser (Chrome, Edge).', + action: () => { + plusMenuOpen = false + linkFolder() + } + } + ] + : []), + ...(inGlobal + ? [ + { + displayName: 'Mention file', + icon: AtSign, + customSubmenu: WorkspaceMentionPicker, + customSubmenuProps: { + onSelect: mentionWorkspaceItem, + onAfterClose: () => aiChatInput?.focusInput() + } + } + ] + : []), + ...(inGlobal + ? [ + { + displayName: 'Skills', + icon: BookOpen, + separatorTop: true, + // Getters so the submenus fill in when their fetch lands + // rather than the whole menu waiting on it. + get submenuItems() { + return skillsMenu.items(closeMenu) + } + }, + { + displayName: 'MCP connections', + icon: Plug, + get submenuItems() { + return mcpMenu.items(closeMenu) + } + } + ] + : []) + ] + }} + placement="bottom-start" + fixedHeight={false} + closeOnItemClick={false} + bind:open={plusMenuOpen} + > + {#snippet buttonReplacement()} + <Tooltip small placement="top"> + <Button + nonCaptureEvent + unifiedSize="2xs" + variant="subtle" + iconOnly + startIcon={{ icon: Plus }} + /> + {#snippet text()} + <div class="max-w-64 text-xs"> + <p class="font-semibold">Attach files or link a folder</p> + <p class="mt-1"> + Files and images attach to your next message. Images are seen + directly; file contents stay in your browser and are read on demand. + </p> + <p class="mt-1"> + A linked folder is a session-wide resource: the assistant lists, + searches, and reads its files whenever it needs them. + </p> + </div> + {/snippet} + </Tooltip> + {/snippet} + </DropdownV2> + <!-- Fallback file picker (used when the File System Access API is unavailable). + `accept` only steers the picker; the content sniff at attach is authoritative. --> + <input + bind:this={fileInputEl} + type="file" + multiple + accept={chatHost.attachmentAccept} + class="hidden no-default-style" + onchange={onFileInputChange} + /> + <!-- Fallback folder picker (no File System Access API): webkitdirectory selects a + whole folder; its files carry webkitRelativePath and are snapshotted. --> + <input + bind:this={folderInputEl} + type="file" + multiple + webkitdirectory + class="hidden no-default-style" + onchange={onFolderInputChange} + /> + {/if} + {@render actingOn?.()} + {#if showAutonomyModeSelector} + <AutonomyModePicker + mode={chatHost.autonomyMode} + availability={autonomyAvailability} + onChange={chatHost.setAutonomyMode} + work={chatHost.workModesAvailable + ? { + mode: chatHost.workMode, + planAvailable: chatHost.planModeAvailable, + lock: workModeLock, + onChange: chatHost.setWorkMode + } + : undefined} + /> + {/if} + {#if effectiveAutonomyMode === AIAutonomyMode.YOLO && chatHost.autoAcceptToolConfirmationsAvailable} + <Tooltip small placement="top"> + <AlertTriangle class="w-3 h-3 text-red-500" /> {#snippet text()} <div class="max-w-64 text-xs"> - <p class="font-semibold">Attach files or link a folder</p> - <p class="mt-1"> - Files and images attach to your next message. Images are seen directly; - file contents stay in your browser and are read on demand. + <p class="font-semibold"> + {chatHost.autoAcceptEditsAvailable + ? 'Bypass permissions auto-accepts edits and tool usage.' + : 'Bypass permissions auto-accepts tool usage.'} </p> <p class="mt-1"> - A linked folder is a session-wide resource: the assistant lists, searches, - and reads its files whenever it needs them. + {chatHost.autoAcceptEditsAvailable + ? 'This can result in edits being applied or tools being called without user confirmation.' + : 'This can result in tools being called without user confirmation.'} </p> + {#if yoloBypassedTools.length > 0} + <p class="mt-2 font-semibold">Bypassed in current mode:</p> + <ul class="mt-1 list-disc pl-4 space-y-0.5"> + {#each visibleYoloBypassedTools as tool (tool.name)} + <li class="break-words">{tool.label}</li> + {/each} + </ul> + {#if hiddenYoloBypassedToolCount > 0} + <p class="mt-1">+ {hiddenYoloBypassedToolCount} more</p> + {/if} + {:else} + <p class="mt-2">No tools in the current mode require confirmation.</p> + {/if} </div> {/snippet} </Tooltip> - {/snippet} - </DropdownV2> - <!-- Fallback file picker (used when the File System Access API is unavailable). - `accept` only steers the picker; the content sniff at attach is authoritative. --> - <input - bind:this={fileInputEl} - type="file" - multiple - accept={chatHost.attachmentAccept} - class="hidden no-default-style" - onchange={onFileInputChange} - /> - <!-- Fallback folder picker (no File System Access API): webkitdirectory selects a - whole folder; its files carry webkitRelativePath and are snapshotted. --> - <input - bind:this={folderInputEl} - type="file" - multiple - webkitdirectory - class="hidden no-default-style" - onchange={onFolderInputChange} - /> + {/if} + {#if chatHost.mode === AIMode.SCRIPT && hasDiff && !disabled} + <ChatQuickActions {askAi} {diffMode} /> + {/if} + </div> {/if} - {#if showAutonomyModeSelector} - <DropdownV2 - items={() => - availableAutonomyModeOptions.map((option) => ({ - displayName: option.label, - selected: effectiveAutonomyMode === option.mode, - action: () => chatHost.setAutonomyMode(option.mode) - }))} - placement="bottom-start" - fixedHeight={false} - customWidth={240} - > - {#snippet buttonReplacement()} - <Button - nonCaptureEvent - unifiedSize="2xs" - variant="default" - title={effectiveAutonomyModeOption.tooltip(autonomyAvailability)} - btnClasses={effectiveAutonomyModeOption.triggerClass ?? ''} - startIcon={{ - icon: effectiveAutonomyModeOption.icon, - classes: effectiveAutonomyModeOption.iconColor - }} - endIcon={{ icon: ChevronDown }} - > - {autonomyModeLabel(effectiveAutonomyMode)} - </Button> - {/snippet} - </DropdownV2> - {/if} - {#if effectiveAutonomyMode === AIAutonomyMode.PLAN} - <span class="text-2xs text-secondary">{PLAN_MODE_MESSAGES.modeNote}</span> - {/if} - {#if effectiveAutonomyMode === AIAutonomyMode.YOLO && chatHost.autoAcceptToolConfirmationsAvailable} - <Tooltip small placement="top"> - <AlertTriangle class="w-3 h-3 text-red-500" /> - {#snippet text()} - <div class="max-w-64 text-xs"> - <p class="font-semibold"> - {chatHost.autoAcceptEditsAvailable - ? 'Bypass permissions auto-accepts edits and tool usage.' - : 'Bypass permissions auto-accepts tool usage.'} - </p> - <p class="mt-1"> - {chatHost.autoAcceptEditsAvailable - ? 'This can result in edits being applied or tools being called without user confirmation.' - : 'This can result in tools being called without user confirmation.'} - </p> - {#if yoloBypassedTools.length > 0} - <p class="mt-2 font-semibold">Bypassed in current mode:</p> - <ul class="mt-1 list-disc pl-4 space-y-0.5"> - {#each visibleYoloBypassedTools as tool (tool.name)} - <li class="break-words">{tool.label}</li> - {/each} - </ul> - {#if hiddenYoloBypassedToolCount > 0} - <p class="mt-1">+ {hiddenYoloBypassedToolCount} more</p> - {/if} - {:else} - <p class="mt-2">No tools in the current mode require confirmation.</p> - {/if} - </div> - {/snippet} - </Tooltip> - {/if} - {#if chatHost.mode === AIMode.SCRIPT && hasDiff && !disabled} - <ChatQuickActions {askAi} {diffMode} /> - {/if} - </div> - {/if} - {#if footerMessageShown} - <div class="text-primary text-xs my-2 px-2"> - <Markdown md={disabledMessage} /> - </div> - {:else} - <div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center"> - {#if chatHost.mode === AIMode.GLOBAL} - <AttachedFilesBar /> - {/if} - {#if !hideModeSelector} - <ChatMode /> - {/if} - {#if chatHost.mode === AIMode.APP} - <DatatableCreationPolicy /> - {/if} - <ContextUsageIndicator /> - {#if chatHost.supportsModelSettings} - <!-- `promptSettings={false}`: in a session, GLOBAL, the settings modal's + {#if footerMessageShown} + <!-- The workspace picker stays: picking another workspace is how a chat that + cannot run here becomes usable again. --> + <div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap"> + {@render actingOn?.()} + <div class="text-primary text-xs my-2 px-2"> + <Markdown md={disabledMessage} /> + </div> + </div> + {:else} + <div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center"> + {#if chatHost.mode === AIMode.GLOBAL} + <AttachedFilesBar /> + {/if} + {#if !hideModeSelector} + <ChatMode /> + {/if} + {#if chatHost.mode === AIMode.APP} + <DatatableCreationPolicy /> + {/if} + <ContextUsageIndicator /> + {#if chatHost.supportsModelSettings} + <!-- `promptSettings={false}`: in a session, GLOBAL, the settings modal's Instructions section owns the prompt entries. --> - <AIChatModelSettings promptSettings={false} /> - {/if} - {@render footerSettings?.()} - {#if chatHost.mode === AIMode.GLOBAL} - <AssistantSettingsModal bind:this={assistantSettings} /> - {/if} + <AIChatModelSettings promptSettings={false} /> + {/if} + {@render footerSettings?.()} + {#if chatHost.mode === AIMode.GLOBAL} + <AssistantSettingsModal bind:this={assistantSettings} /> + {/if} - {#if chatHost.mode === AIMode.APP && appContext && (appContext.inspectorElement || appContext.codeSelection)} - {#if appContext.inspectorElement} - <div - class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-2xs" - title={appContext.inspectorElement.path} - > - <MousePointer2 class="w-3 h-3" /> - <span class="truncate max-w-[60px]"> - {appContext.inspectorElement.tagName.toLowerCase()}{appContext.inspectorElement - .id - ? `#${appContext.inspectorElement.id}` - : ''}{appContext.inspectorElement.className - ? `.${appContext.inspectorElement.className.split(' ')[0]}` - : ''} - </span> - <button - class="hover:bg-purple-200 dark:hover:bg-purple-800/50 rounded p-0.5 -mr-0.5" - onclick={() => appContext.clearInspector?.()} - title="Clear element selection" - > - <X class="w-2.5 h-2.5" /> - </button> - </div> - {/if} - {#if appContext.codeSelection} - <div - class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-2xs" - title={`${appContext.codeSelection.source}: lines ${appContext.codeSelection.startLine}-${appContext.codeSelection.endLine}`} - > - <TextSelect class="w-3 h-3" /> - <span class="truncate max-w-[80px]"> - L{appContext.codeSelection.startLine}-{appContext.codeSelection.endLine} - </span> - <button - class="hover:bg-amber-200 dark:hover:bg-amber-800/50 rounded p-0.5 -mr-0.5" - onclick={() => appContext.clearCodeSelection?.()} - title="Clear code selection" - > - <X class="w-2.5 h-2.5" /> - </button> - </div> - {/if} + {#if chatHost.mode === AIMode.APP && appContext && (appContext.inspectorElement || appContext.codeSelection)} + {#if appContext.inspectorElement} + <div + class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-2xs" + title={appContext.inspectorElement.path} + > + <MousePointer2 class="w-3 h-3" /> + <span class="truncate max-w-[60px]"> + {appContext.inspectorElement.tagName.toLowerCase()}{appContext + .inspectorElement.id + ? `#${appContext.inspectorElement.id}` + : ''}{appContext.inspectorElement.className + ? `.${appContext.inspectorElement.className.split(' ')[0]}` + : ''} + </span> + <button + class="hover:bg-purple-200 dark:hover:bg-purple-800/50 rounded p-0.5 -mr-0.5" + onclick={() => appContext.clearInspector?.()} + title="Clear element selection" + > + <X class="w-2.5 h-2.5" /> + </button> + </div> + {/if} + {#if appContext.codeSelection} + <div + class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-2xs" + title={`${appContext.codeSelection.source}: lines ${appContext.codeSelection.startLine}-${appContext.codeSelection.endLine}`} + > + <TextSelect class="w-3 h-3" /> + <span class="truncate max-w-[80px]"> + L{appContext.codeSelection.startLine}-{appContext.codeSelection.endLine} + </span> + <button + class="hover:bg-amber-200 dark:hover:bg-amber-800/50 rounded p-0.5 -mr-0.5" + onclick={() => appContext.clearCodeSelection?.()} + title="Clear code selection" + > + <X class="w-2.5 h-2.5" /> + </button> + </div> + {/if} + {/if} + </div> {/if} </div> + {/snippet} + </AIChatInput> + </div> + <!-- Opens and closes with the box, so the page under it slides rather than jumps. --> + <div use:smoothHeight={{ enabled: starterLayout, key: composerCollapsed }}> + <div> + {#if starterLayout && starter && !disabled && !composerCollapsed && starter.suggestions.length > 0} + <div class="pt-2"> + <ComposerSuggestions + suggestions={starter.suggestions} + wrap={starter.where === 'session'} + onPick={(prompt) => aiChatInput?.setText(prompt)} + /> + </div> {/if} </div> </div> @@ -1386,4 +1446,12 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> </div> {/if} </div> + <!-- Equal to the space above while the session is empty, so the composer sits centred. + Always mounted and shrunk on the first message rather than removed: flex-grow + transitions, so the composer slides down to the bottom instead of jumping. --> + <div + class="min-h-0 basis-0 transition-[flex-grow] duration-[var(--composer-glide-duration)] ease-[var(--composer-glide-easing)] motion-reduce:transition-none {centreComposer + ? 'grow' + : 'grow-0'}" + ></div> </div> diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index 41ea788fac..ac6f21844e 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -13,7 +13,18 @@ import { AIMode } from './AIChatManager.svelte' import { CHAT_INPUT_PADDING, getAiChatManager } from './aiChatManagerContext' import { getChatViewHost } from './chatViewHost' - import { composerBoxClass, COMPOSER_FIELD_RESET } from './composerBox' + import { + composerBoxClass, + COMPOSER_FIELD_RESET, + globalComposerSuggestion, + type ComposerSelection + } from './composerBox' + + // The send button sits in the toolbar row, not over the field, so the text needs no + // room reserved on its right, and the row right below it stands in for most of its + // bottom padding. The top padding is the one-line row's, so the text holds still as Home's + // composer opens. + const FIELD_PADDING_WITH_TOOLBAR = '!pl-4 !pr-4 !pt-3 !pb-1' import { formatMention, hasMention, removeMentionFromText } from './mention' import { twMerge } from 'tailwind-merge' import { tick, untrack, type Snippet } from 'svelte' @@ -49,7 +60,7 @@ MAX_BLOB_BYTES, type AttachedBlob } from './blobUtils' - import { MessageDraft } from './messageDraft.svelte' + import { MessageDraft, type DraftAttachments } from './messageDraft.svelte' import { useSessionPermissions } from '$lib/components/sessions/sessionPermissions.svelte' import ExpandableImage, { isImageViewerOpen @@ -89,10 +100,30 @@ // `chatHost.instructions` only carries programmatic prompts). Used by // sessions to persist the typed-but-unsent prompt with the session draft. onDraftChange?: (text: string) => void + /** The rest of the draft — collapsed pastes, images, files — seeded and observed the + * same way. The text alone is not the draft: a collapsed paste is a token in it whose + * content lives here, so a composer remounted elsewhere needs both. */ + initialAttachments?: DraftAttachments + onAttachmentsChange?: (attachments: DraftAttachments) => void // tool_call_id of the askUserQuestion the turn is parked on, when it is. A // plain-text draft sent from here answers it instead of queueing behind a // turn that only the answer can resume. pendingQuestionToolCallId?: string + /** The composer that opens a session (Home, an empty session): `toolbar` is drawn in the + * box's bottom row with the send button at its end, and a usable box is taller. Otherwise + * the controls sit under the box and the send button floats over the field's corner, as a + * chat under way reads more clearly. */ + hero?: boolean + /** With `hero`: one row, the field then `collapsedControls` and the send button, in + * place of the toolbar. */ + collapsed?: boolean + collapsedControls?: Snippet + /** A chat mark before the field, where the box alone doesn't say it is the assistant's. */ + chatIcon?: boolean + /** After a new turn is handed to the host — not an edit, a queued message or an answer. */ + onSent?: () => void + /** The composer's controls. */ + toolbar?: Snippet } let { @@ -116,47 +147,29 @@ loading, onCancel, onDraftChange = undefined, - pendingQuestionToolCallId = undefined + initialAttachments = undefined, + onAttachmentsChange = undefined, + pendingQuestionToolCallId = undefined, + onSent = undefined, + toolbar = undefined, + hero = false, + collapsed = false, + collapsedControls = undefined, + chatIcon = false }: Props = $props() - // GLOBAL-mode suggestion pool. We pick one at mount-time so each new - // session lands on a different prompt; the choice stays stable for - // the lifetime of this input so the placeholder doesn't shuffle as - // the user is reading it. - const GLOBAL_PLACEHOLDER_SUGGESTIONS = [ - 'Write a hello-world flow', - 'Create a script that lists files in an S3 bucket', - 'Build a CRUD app for a customer table', - 'Schedule a daily cleanup of old runs', - 'Wrap an existing script into a flow with retries', - 'Add an HTTP trigger to an existing script', - 'Generate a report from a SQL query and email it', - 'Create a Postgres resource and a script that queries it', - 'Refactor a script to add error handling', - 'List my workspace flows and scripts' - ] - // An operator authors nothing, so nothing above is theirs to ask for; one with the - // workspace's builder right can compose flows out of deployed scripts as well. - const OPERATOR_PLACEHOLDER_SUGGESTIONS = [ - 'List my workspace flows and scripts', - 'Show the runs that failed today and why', - 'Find the script that sends a report and run it', - 'Rerun the last failed run of a flow' - ] - const BUILDER_PLACEHOLDER_SUGGESTIONS = [ - ...OPERATOR_PLACEHOLDER_SUGGESTIONS, - 'Compose a flow that chains two deployed scripts' - ] - const permissions = useSessionPermissions(() => chatHost.operatingWorkspace) + const oneLine = $derived(hero && collapsed) + const toolbarInBox = $derived(!!toolbar && hero) + + // Picked at mount-time so each new session lands on a different prompt. + const permissions = useSessionPermissions( + () => chatHost.operatingWorkspace, + () => chatHost + ) const suggestionPick = Math.random() - const globalSuggestion = $derived.by(() => { - const pool = permissions.canOpenEditor('script') - ? GLOBAL_PLACEHOLDER_SUGGESTIONS - : permissions.canOpenEditor('flow') - ? BUILDER_PLACEHOLDER_SUGGESTIONS - : OPERATOR_PLACEHOLDER_SUGGESTIONS - return pool[Math.floor(suggestionPick * pool.length)] - }) + const globalSuggestion = $derived( + globalComposerSuggestion(suggestionPick, permissions.canOpenEditor) + ) // Generate mode-specific placeholder const modePlaceholder = $derived.by(() => { @@ -207,9 +220,10 @@ const draft = new MessageDraft( untrack(() => ({ text: initialInstructions, - pastes: initialPastes ?? [], - images: initialImages ?? [], - files: initialFiles ?? [] + pastes: initialPastes ?? initialAttachments?.pastes ?? [], + images: initialImages ?? initialAttachments?.images ?? [], + files: initialFiles ?? initialAttachments?.files ?? [], + blobs: initialAttachments?.blobs ?? [] })) ) // Report edits, never the mount-time value. The first run carries whatever the @@ -228,6 +242,24 @@ onDraftChange?.(text) }) }) + // Same rule for the rest of the draft. + let attachmentsReported = false + $effect(() => { + // Copied, not passed: the paste lane is edited in place, and a copy reads every item. + const attachments = { + pastes: [...draft.pastes], + images: [...draft.images], + files: [...draft.files], + blobs: [...draft.blobs] + } + untrack(() => { + if (!attachmentsReported) { + attachmentsReported = true + return + } + onAttachmentsChange?.(attachments) + }) + }) // A parked askUserQuestion is a request for input, so a plain-text draft sent // from the composer answers it rather than being queued behind a turn that can @@ -613,10 +645,12 @@ * auto-remove items when the user deletes them. No-op when the same * standalone mention is already present, so picking the same item * again doesn't leave duplicate tokens. */ - export function insertMention(title: string) { + /** Resolves once the caret sits after the mention, so mentions inserted one after another + * land in that order. */ + export async function insertMention(title: string) { if (hasMention(draft.text, title)) return if (contextTextareaComponent) { - void contextTextareaComponent.insertMention(title) + await contextTextareaComponent.insertMention(title) return } const sep = draft.text.length === 0 || /\s$/.test(draft.text) ? '' : ' ' @@ -636,11 +670,26 @@ draft.text = removeMentionFromText(draft.text, title) } - export function focusInput() { + /** Replace the draft's text, keeping its attachments: a starter prompt fills the box, it + * never sends. */ + export function setText(text: string) { + draft.text = text + focusInput() + } + + /** Whether nothing would ship with a send: no text and no attachment. */ + export function isDraftEmpty(): boolean { + return draft.isEmpty + } + + export function focusInput(selection?: ComposerSelection) { if (isContextEnabledMode) { - contextTextareaComponent?.focus() + contextTextareaComponent?.focus(selection) } else { instructionsTextareaComponent?.focus() + if (selection) { + instructionsTextareaComponent?.setSelectionRange(selection.start, selection.end) + } } } @@ -977,6 +1026,7 @@ // textarea still rely on the draft reset alone (no `@`-mention state to // coordinate). contextTextareaComponent?.clearForSend() + onSent?.() } } @@ -1207,7 +1257,23 @@ } </script> -{#snippet sendStopButton()} +{#snippet toolbarRow()} + {#if oneLine} + <div class="flex flex-row items-center gap-1 pr-3 shrink-0"> + {@render collapsedControls?.()} + {@render sendStopButton('sm')} + </div> + {:else if toolbarInBox} + <!-- The send button sets the row's height and the smaller controls centre on it, which + already puts them a few pixels further from the box's bottom edge than the padding. --> + <div class="flex flex-row items-center gap-1.5 px-3 pb-1.5"> + <div class="flex-1 min-w-0">{@render toolbar?.()}</div> + {@render sendStopButton('sm')} + </div> + {/if} +{/snippet} + +{#snippet sendStopButton(size: 'sm' | 'md' = 'md')} <!-- The turn stays `loading` while parked on a question, but a drafted answer is what the button should ship then — otherwise the only pointer action on a typed answer would be Stop. Anything else keeps Stop. --> @@ -1232,9 +1298,11 @@ (onSendRequest !== undefined || chatHost.mode !== AIMode.GLOBAL || selectedContext.length === 0))} + <!-- Accent only once there is something to send, so the button lights up as the draft + becomes sendable; idle and Stop stay quiet. --> <Button - variant="subtle" - unifiedSize="md" + variant={!isLoading && !sendDisabled ? 'accent' : 'subtle'} + unifiedSize={size} iconOnly title={isLoading ? 'Stop' @@ -1402,6 +1470,9 @@ {availableContext} {selectedContext} placeholder={modePlaceholder} + hero={hero && !disabled} + {oneLine} + {chatIcon} onAddContext={(contextElement) => void addContextToSelection(contextElement)} onRemoveContext={(element) => { selectedContext = selectedContext?.filter((c) => !isSameContextElement(c, element)) @@ -1414,13 +1485,21 @@ }} {disabled} {onKeyDown} + className={twMerge( + oneLine ? '!pl-4 !pr-2 !py-3' : toolbarInBox ? FIELD_PADDING_WITH_TOOLBAR : '', + // A set line height, not the font's own: the chat icon is placed against it. + chatIcon && '!pl-2 !leading-5' + )} > {#snippet leading()} {@render badgeRow()} {@render imageChipsRow()} {/snippet} + {#snippet trailing()} + {@render toolbarRow()} + {/snippet} </ContextTextarea> - {#if !bottomRightSnippet} + {#if !bottomRightSnippet && !toolbarInBox} <div class="absolute bottom-1 right-1"> {@render sendStopButton()} </div> @@ -1529,6 +1608,9 @@ </div> </div> {/if} + {#if toolbar && !toolbarInBox} + <div class="mt-1">{@render toolbar()}</div> + {/if} {#if bottomRightSnippet} <div class="absolute bottom-1 right-1"> {@render bottomRightSnippet()} diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 8bbc45721d..89a00c06bc 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -97,7 +97,7 @@ import { untrack } from 'svelte' import { fromStore, get } from 'svelte/store' import type { ProviderToolSummary } from './agentContext' import { BROWSER } from 'esm-env' -import { workspaceStore, type DBSchemas } from '$lib/stores' +import { roleCapabilities, workspaceStore, type DBSchemas } from '$lib/stores' import { copilotInfo, copilotSessionModel } from '$lib/aiStore' import { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot' import { askTools, prepareAskSystemMessage, prepareAskUserMessage } from './ask/core' @@ -119,6 +119,7 @@ import { prepareApiSystemMessage, prepareApiUserMessage } from './api/core' import { closeInterruptedToolBatch, runChatLoop, + type ChatLoopConfig, sendsWebSearch, truncateToToolPairedPrefix } from './chatLoop' @@ -138,8 +139,23 @@ import { } from '$lib/aiStore' import type { WorkspaceMutationTarget } from './workspaceTools' import { resolveSessionAccess } from './global/sessionAccess' -import type { SessionAccess } from './sessionCapabilities' -import { filterSessionTools } from './global/sessionToolset' +import { + canBuild, + isReadOnlyAccess, + USE_MODE_ACCESS, + type SessionAccess, + type SessionTool +} from './sessionCapabilities' +import { + AIWorkMode, + ENTER_BUILD_MODE_TOOL, + ENTER_USE_MODE_TOOL, + isWorkModeSwitchTool, + WORK_MODE_SWITCH_TARGET, + type WorkModeSwitchTool +} from './workMode' +import { workModeSwitchTools } from './workModeSwitch' +import { filterSessionTools, sessionToolAllowed } from './global/sessionToolset' import { listFolderInstructions, type FolderInstruction, @@ -173,11 +189,6 @@ import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRout import { appendAttachedFilesRoster } from './files/fileTools' import { ENTER_PLAN_MODE_TOOL, EXIT_PLAN_MODE_TOOL } from './planMode' import { PlanModeController, type PlanModeHost } from './planModeController.svelte' -import { - navigationOperatorBuilderApps, - navigationOperatorBuilderFlows, - navigationOperatorBuilderRights -} from '$lib/operatorWriteRights' // Compaction of the stored history: once the projected request size // (contextTokens — the provider's report when current, a fresh chars/4 @@ -273,7 +284,6 @@ export enum AIMode { } export enum AIAutonomyMode { - PLAN = 'plan', DEFAULT = 'default', ACCEPT_EDIT = 'acceptedit', YOLO = 'yolo' @@ -310,9 +320,7 @@ export function supportsPlanMode(mode: AIMode): boolean { return PLAN_MODES.has(mode) } -const isOperatorBuilder = fromStore(navigationOperatorBuilderRights) -const isOperatorBuilderFlows = fromStore(navigationOperatorBuilderFlows) -const isOperatorBuilderApps = fromStore(navigationOperatorBuilderApps) +const navCapabilities = fromStore(roleCapabilities) export function isAIModeVisible(mode: AIMode): boolean { return mode !== AIMode.GLOBAL || isGlobalAiEnabled() @@ -338,7 +346,7 @@ function getPersistedAutonomyMode(): AIAutonomyMode { return AIAutonomyMode.ACCEPT_EDIT } const persistedMode = getLocalSetting(key) - if (isAIAutonomyMode(persistedMode) && persistedMode !== AIAutonomyMode.PLAN) { + if (isAIAutonomyMode(persistedMode)) { return persistedMode } // No stored preference: default to auto-accepting edits (tool calls still @@ -351,11 +359,6 @@ function getPersistedAutonomyMode(): AIAutonomyMode { } function persistAutonomyMode(mode: AIAutonomyMode) { - // Plan is session-only: persisting it would re-block a later session where the - // picker never offered Plan. The stored pre-plan baseline is what a reload restores. - if (mode === AIAutonomyMode.PLAN) { - return - } const key = scopedKey(AI_AUTONOMY_MODE_STORAGE_KEY) if (!BROWSER || !key) { return @@ -472,8 +475,8 @@ function planModeHostFor(m: AIChatManager): PlanModeHost { return m.artifacts }, openArtifact: (id, name, version) => m.openArtifact?.(id, name, version), - enter: () => m.setAutonomyMode(AIAutonomyMode.PLAN), - restore: () => m.setAutonomyMode(m.prePlanAutonomyMode ?? AIAutonomyMode.DEFAULT) + enter: () => m.setWorkMode(AIWorkMode.PLAN), + build: () => m.setWorkMode(AIWorkMode.BUILD) } } @@ -767,12 +770,48 @@ export class AIChatManager implements ChatViewHost { this.autonomyMode === AIAutonomyMode.YOLO) ) autoAcceptToolConfirmationsAvailable = $derived(supportsAutoAcceptToolConfirmations(this.mode)) + /** 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) + 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. */ + #useOnly = $derived(this.workModesAvailable && !canBuild(this.sessionAccess)) + // A plan ends in edits, which neither case allows. The user's own Use mode leaves Plan open: + // it is one click away from Build anyway. + planModeAvailable = $derived(this.workModesAvailable && !this.#useOnly) + planModeActive = $derived(this.workMode === AIWorkMode.PLAN && this.planModeAvailable) + // Not while planning: approving the plan is the user's to do, and Yolo applies once they have. autoAcceptToolConfirmationsActive = $derived( - this.autonomyMode === AIAutonomyMode.YOLO && this.autoAcceptToolConfirmationsAvailable + this.autonomyMode === AIAutonomyMode.YOLO && + this.autoAcceptToolConfirmationsAvailable && + !this.planModeActive ) - planModeAvailable = $derived(this.isSessionChat && supportsPlanMode(this.mode)) - planModeActive = $derived(this.autonomyMode === AIAutonomyMode.PLAN && this.planModeAvailable) - prePlanAutonomyMode = $state<AIAutonomyMode | undefined>(undefined) + /** The chat is in Use, by the user's pick or because Use is the only mode. */ + useModeActive = $derived( + this.workModesAvailable && (this.workMode === AIWorkMode.USE || this.#useOnly) + ) + /** 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 => { + if (!this.useModeActive) return undefined + if (isReadOnlyAccess(this.sessionAccess)) return 'protected' + return this.#useOnly ? 'role' : 'chosen' + }) + #workModeSwitches: Record<WorkModeSwitchTool, SessionTool<any>> = workModeSwitchTools({ + offers: (tool) => this.workModeSwitchOffered === tool, + setWorkMode: (mode) => this.setWorkMode(mode) + }) + /** The switch the current mode offers between Use and Use & build. None from Plan, which + * leaves through its plan's approval, from a session held in Use, or while confirmations are + * auto-accepted: the switch is the user's answer, which that posture would give for them. */ + workModeSwitchOffered = $derived.by((): WorkModeSwitchTool | undefined => { + if (!this.workModesAvailable || this.autoAcceptToolConfirmationsActive) return undefined + if (this.#useReason === 'chosen') return ENTER_BUILD_MODE_TOOL + 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) // 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)) @@ -789,15 +828,33 @@ export class AIChatManager implements ChatViewHost { /** Both views narrow the same way — concatenate every source, then filter — so a tool * reaching either one can never arrive unfiltered. A session withholds what its user's * capabilities do not cover; elsewhere `sessionAccess` is unset and nothing is dropped. */ - #shipped = (planTools: Tool<any>[]): Tool<any>[] => - filterSessionTools([...this.#assembledTools, ...planTools], this.sessionAccess) - /** What the request carries: the assembled tools plus the plan-mode transition the current + #shipped = (modeTools: Tool<any>[]): Tool<any>[] => + filterSessionTools([...this.#assembledTools, ...modeTools], this.#toolAccess) + /** What the request carries: the assembled tools plus the mode transitions the current * posture offers. Read by the request path and by the YOLO disclosure. */ - tools: Tool<any>[] = $derived(this.#shipped(this.planMode.tools)) + tools: Tool<any>[] = $derived( + this.#shipped([ + ...this.planMode.tools, + ...(this.workModeSwitchOffered ? [this.#workModeSwitches[this.workModeSwitchOffered]] : []) + ]) + ) /** What the assistant can call in this session, posture-independent: both plan-mode - * transitions, whichever one is offered right now. A reference answer, so flipping the - * autonomy picker must not change it. */ - availableTools: Tool<any>[] = $derived(this.#shipped(this.planMode.availableTools)) + * transitions and both switches, whichever one is offered right now. A reference answer, so + * flipping the autonomy picker must not change it. */ + availableTools: Tool<any>[] = $derived( + this.#shipped([ + ...this.planMode.availableTools, + ...(this.workModesAvailable && !this.#useOnly ? Object.values(this.#workModeSwitches) : []) + ]) + ) + /** Whether a tool the call was made with is no longer shipped: a switch to Use withdraws + * every write while its card waits. The mode transitions are not assembled, so never are. */ + isToolWithdrawn = (toolName: string): boolean => { + const access = this.#toolAccess + if (!access) return false + const tool = this.#assembledTools.find((t) => t.def.function.name === toolName) + return !!tool && !sessionToolAllowed(tool, access) + } #copilotInfo = fromStore(copilotInfo) #sessionModel = fromStore(copilotSessionModel) /** Capabilities the provider runs on its own servers, attached by the adapter at send @@ -1486,23 +1543,22 @@ export class AIChatManager implements ChatViewHost { .map((s) => ({ ...s, kind: 'skill' as const })) ]) - // The flow, app and script builders all write code, which the backend refuses from an - // operator with builder rights: leaving them reachable would only produce work that cannot be - // deployed. + // The flow, app and script builders all write code, which the backend refuses from a role + // that only composes: leaving them reachable would only produce work that cannot be deployed. allowedModes: Record<AIMode, boolean> = $derived({ script: this.flowAiChatHelpers === undefined && this.scriptEditorOptions !== undefined && !this.disabledModes.script && - !isOperatorBuilder.current, + navCapabilities.current.code, flow: this.flowAiChatHelpers !== undefined && !this.disabledModes.flow && - !isOperatorBuilderFlows.current, + navCapabilities.current.flows === 'full', app: this.appAiChatHelpers !== undefined && !this.disabledModes.app && - !isOperatorBuilderApps.current, + navCapabilities.current.apps === 'full', navigator: !this.disabledModes.navigator, ask: !this.disabledModes.ask, API: !this.disabledModes.API, @@ -1727,8 +1783,15 @@ export class AIChatManager implements ChatViewHost { * Returns true on success. Returns false — caller falls back to drop-oldest — * when summarization isn't worthwhile or fails (user abort, empty summary, or * the circuit breaker being tripped). + * + * `inFlightTokens` is the running turn's output, which is not in `messages` but + * rides on every request after it: the tail shrinks by that much, or the next + * tool result re-triggers at once and drop-oldest discards this summary. */ - private summarizeAndCompact = async (contextWindow: number): Promise<boolean> => { + private summarizeAndCompact = async ( + contextWindow: number, + inFlightTokens = 0 + ): Promise<boolean> => { if (this.consecutiveCompactionFailures >= MAX_CONSECUTIVE_COMPACTION_FAILURES) { return false } @@ -1737,13 +1800,14 @@ export class AIChatManager implements ChatViewHost { return false } - const tailBudget = + const historyBudget = contextWindow * COMPACTION_TARGET_RATIO - SUMMARY_OUTPUT_RESERVE_TOKENS - this.estimateOverheadTokens() - if (tailBudget <= 0) { + if (historyBudget <= 0) { return false } + const tailBudget = historyBudget - inFlightTokens const last = this.messages.length - 1 if (last < 1) { @@ -1777,7 +1841,10 @@ export class AIChatManager implements ChatViewHost { const prefix = this.messages.slice(0, keepFrom) const tail = this.messages.slice(keepFrom) - if (prefix.length < MIN_PREFIX_MESSAGES_TO_SUMMARIZE || tail.length === 0) { + // Mid-turn, drop-oldest would cut context the running turn may rely on, so any + // prefix beyond a lone previous summary is worth the round-trip. + const minPrefix = inFlightTokens > 0 ? 2 : MIN_PREFIX_MESSAGES_TO_SUMMARIZE + if (prefix.length < minPrefix || tail.length === 0) { return false } @@ -1810,6 +1877,65 @@ export class AIChatManager implements ChatViewHost { return false } + /** + * Automatic compaction trigger, checked when a turn is sent and again before + * each tool-loop iteration, since one turn's tool results can carry the request + * past the window on their own. Rewrites the stored history (not the turn in + * flight) once `projectedTokens` reaches the trigger ratio of `model`'s window. + * Returns whether it rewrote; callers persist. An unrecognized model still gets + * the conservative assumed window rather than no limit: without one the context + * grows unbounded until the provider (or a proxy in front of it) times out. + * Guessing low only compacts earlier, which is always recoverable. + */ + private compactIfOverTrigger = async ( + projectedTokens: number, + model: ChatLoopConfig['modelProvider'] | undefined, + inFlightTokens = 0 + ): Promise<boolean> => { + const contextWindow = model + ? getEffectiveModelContextWindow( + model.provider, + model.model, + get(copilotInfo).contextWindowPerModel + ) + : undefined + if (contextWindow === undefined || projectedTokens < contextWindow * COMPACTION_TRIGGER_RATIO) { + return false + } + // Preferred path: summarize the older prefix, keep the recent tail. + const summarized = await this.summarizeAndCompact(contextWindow, inFlightTokens) + // A Stop during the in-flight summary aborts this turn's controller; + // summarizeAndCompact then returns false without touching history. Skip + // the drop-oldest fallback — it would destructively compact a conversation + // the user only meant to cancel, and the request can't run on an aborted + // controller anyway. The cancel path rolls the turn back cleanly on its own. + if (this.abortController?.signal.aborted) { + return false + } + if (!summarized) { + // Fallback when summarization isn't worthwhile or fails: drop the + // oldest messages. A report stays meaningful only debited by what + // was dropped; the estimate path needs no bookkeeping — the next + // read re-estimates the compacted history. chars/4 can + // underestimate the freed tokens, which errs toward compacting + // again — never toward overflowing. + const lengthBefore = this.messages.length + const freed = this.compactOldestMessages( + projectedTokens - contextWindow * COMPACTION_TARGET_RATIO + ) + if (this.messages.length === lengthBefore) { + return false + } + if (this.contextUsage !== undefined) { + this.contextUsage = Math.max(0, this.contextUsage - freed) + } + } + // Reconcile file registrations with the compacted transcript — the + // summary message carries the folded-away turns' files forward. + this.#syncMessageFiles() + return true + } + /** * Manual compaction (the `/compact` session command): summarize the ENTIRE * stored history into a single summary message and keep nothing verbatim, so @@ -1901,8 +2027,10 @@ export class AIChatManager implements ChatViewHost { } /** enter_plan_mode never qualifies: YOLO means "stop asking and run it", and a research - * posture inverts that. Every accept path asks here rather than carrying its own copy. */ - private autoAcceptsTool = (toolName: string | undefined) => toolName !== ENTER_PLAN_MODE_TOOL + * posture inverts that. Nor does a switch between Use and Use & build, which only the user + * picks. Every accept path asks here rather than carrying its own copy. */ + private autoAcceptsTool = (toolName: string | undefined) => + toolName !== ENTER_PLAN_MODE_TOOL && !isWorkModeSwitchTool(toolName) /** Asked before the confirmation wait is skipped, so a tool the posture will not answer * for still gets a card rather than running unasked. */ @@ -1942,7 +2070,7 @@ export class AIChatManager implements ChatViewHost { } } - private resolvePendingPlanCard = (toolName: string, confirmed: boolean) => { + private resolvePendingModeCard = (toolName: string, confirmed: boolean) => { for (const [toolId, cb] of this.confirmationCallbacks) { if (cb.toolName === toolName) { cb.resolve(confirmed) @@ -1952,24 +2080,8 @@ export class AIChatManager implements ChatViewHost { } setAutonomyMode = (mode: AIAutonomyMode) => { - const enteringPlan = mode === AIAutonomyMode.PLAN && this.autonomyMode !== AIAutonomyMode.PLAN - const leavingPlan = mode !== AIAutonomyMode.PLAN && this.autonomyMode === AIAutonomyMode.PLAN - if (enteringPlan) { - this.prePlanAutonomyMode = this.autonomyMode - this.planMode.startRound() - } else if (mode !== AIAutonomyMode.PLAN) { - this.prePlanAutonomyMode = undefined - this.planMode.resetBlocks() - } this.autonomyMode = mode persistAutonomyMode(mode) - - if (enteringPlan) { - this.resolvePendingPlanCard(ENTER_PLAN_MODE_TOOL, true) - } else if (leavingPlan) { - // Opting into YOLO means "run it"; leaving plan mode any other way is not a sign-off. - this.resolvePendingPlanCard(EXIT_PLAN_MODE_TOOL, mode === AIAutonomyMode.YOLO) - } if (this.autoAcceptToolConfirmationsActive) { this.acceptPendingToolConfirmations() } @@ -1978,6 +2090,40 @@ export class AIChatManager implements ChatViewHost { } } + setWorkMode = (mode: AIWorkMode) => { + const enteringPlan = mode === AIWorkMode.PLAN && this.workMode !== AIWorkMode.PLAN + const leavingPlan = mode !== AIWorkMode.PLAN && this.workMode === AIWorkMode.PLAN + const useChanges = (mode === AIWorkMode.USE) !== (this.workMode === AIWorkMode.USE) + if (enteringPlan) { + this.planMode.startRound() + } else if (mode !== AIWorkMode.PLAN) { + this.planMode.resetBlocks() + } + this.workMode = mode + this.onWorkModeChanged?.(mode) + + if (enteringPlan) { + this.resolvePendingModeCard(ENTER_PLAN_MODE_TOOL, true) + } else if (leavingPlan) { + // Building under Yolo means "run it"; leaving plan mode any other way is not a sign-off. + this.resolvePendingModeCard( + EXIT_PLAN_MODE_TOOL, + mode === AIWorkMode.BUILD && this.autonomyMode === AIAutonomyMode.YOLO + ) + } + // A switch card the picker answered: accepted when the picker went where the card asked. + for (const tool of [ENTER_BUILD_MODE_TOOL, ENTER_USE_MODE_TOOL] as const) { + this.resolvePendingModeCard(tool, mode === WORK_MODE_SWITCH_TARGET[tool]) + } + if (this.autoAcceptToolConfirmationsActive) { + this.acceptPendingToolConfirmations() + } + // The helpers and the system prompt are built for one access; the tool list follows alone. + if (useChanges && this.mode === AIMode.GLOBAL) { + this.configureGlobalMode() + } + } + setAutoAcceptToolConfirmations = (enabled: boolean) => { this.setAutonomyMode(enabled ? AIAutonomyMode.YOLO : AIAutonomyMode.DEFAULT) } @@ -1991,7 +2137,6 @@ export class AIChatManager implements ChatViewHost { hydrateUserScopedAutonomy = () => { migrateLegacyAutonomyKeys() this.autonomyMode = getPersistedAutonomyMode() - this.prePlanAutonomyMode = undefined this.planMode.resetRound() } @@ -2256,10 +2401,14 @@ export class AIChatManager implements ChatViewHost { ) } - setAiChatInput(aiChatInput: AIChatInput | null) { + setAiChatInput(aiChatInput: AIChatInput) { this.aiChatInput = aiChatInput } + releaseAiChatInput(aiChatInput: AIChatInput) { + if (this.aiChatInput === aiChatInput) this.aiChatInput = null + } + /** Queue the message typed while a turn is streaming. There is only ever * one queued message; pressing Enter again appends the new text as another * line so it all goes out as a single message, and its images accumulate @@ -2400,12 +2549,12 @@ export class AIChatManager implements ChatViewHost { * * Gated on `sendInFlight` as well as `loading`: `loading` only rises after a * send's attachment upkeep, so between the two a click would slip past. */ - sendOrQueue(text: string) { + sendOrQueue(text: string, context?: ContextElement[]) { if (this.loading || this.sendInFlight || this.sendPending) { - this.queueMessage(text) + this.queueMessage(text, [], context) return } - void this.sendRequest({ instructions: text }) + void this.sendRequest({ instructions: text, contextOverride: context }) } /** Remove the queued message and put it back into the input, images included. */ @@ -2620,7 +2769,7 @@ export class AIChatManager implements ChatViewHost { sessionId: this.sessionId, operatingWorkspace: this.operatingWorkspace, artifacts: this.artifacts, - access: this.sessionAccess, + access: this.#toolAccess, getChatId: () => this.historyManager.getCurrentChatId(), openArtifact: this.openArtifact } @@ -2659,11 +2808,19 @@ export class AIChatManager implements ChatViewHost { skills: this.globalSkills, folderInstructions: this.globalFolderInstructions, mcpServers: this.mcpServers, - access: this.sessionAccess, - sessionContext: this.sessionContextResolver?.(), + access: this.#toolAccess, + sessionContext: this.#sessionPromptContext(), pipelineFolders: this.#pipelineFolders() }) + #sessionPromptContext = (): SessionPromptContext | undefined => { + const ctx = this.sessionContextResolver?.() + const reason = this.#useReason + // A protected workspace needs no reason here: the prompt's own read-only line names it. + if (!ctx || !reason || reason === 'protected') return ctx + return { ...ctx, useMode: reason } + } + // Fetch the workspace's AI skills and, if GLOBAL mode is still active, rebuild // the system message so the next chat-loop iteration advertises them. Ignore // stale resolves so workspace changes cannot overwrite newer skills. @@ -3163,7 +3320,8 @@ export class AIChatManager implements ChatViewHost { callbacks, addedMessages, systemMessage: systemMessageOverride, - onWebSearchUnavailable + onWebSearchUnavailable, + onBeforeIteration }: { messages: ChatCompletionMessageParam[] abortController: AbortController @@ -3175,6 +3333,7 @@ export class AIChatManager implements ChatViewHost { addedMessages?: ChatCompletionMessageParam[] systemMessage?: ChatCompletionSystemMessageParam onWebSearchUnavailable?: () => void + onBeforeIteration?: ChatLoopConfig['onBeforeIteration'] }) => { // Fresh batch for this turn — drop any images an aborted prior turn left buffered. this.pendingToolImages.clear() @@ -3277,8 +3436,9 @@ export class AIChatManager implements ChatViewHost { console.error('Failed to record AI usage', e) } }, - onBeforeIteration: async (modelProvider) => { + onBeforeIteration: async (modelProvider, lastIterationUsage) => { this.lastIterationModel = modelProvider + await onBeforeIteration?.(modelProvider, lastIterationUsage) } }) if (this.isSessionChat && this.sessionId && result.tokenUsage.total > 0) { @@ -3661,7 +3821,10 @@ export class AIChatManager implements ChatViewHost { options.images ?? [], options.files ?? [] ) === true - if (taken) this.#restoreMentionContext(options.contextOverride, requestedMode) + if (taken) { + this.#restoreDomContext(options.contextOverride, true) + this.#restoreMentionContext(options.contextOverride, requestedMode) + } } return false } @@ -3771,7 +3934,10 @@ export class AIChatManager implements ChatViewHost { // mentions on that draft and every turn after it. const taken = this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) this.#restoreMentionContext(options.contextOverride, requestedMode) + if (taken) { + this.#restoreDomContext(options.contextOverride, true) + this.#restoreMentionContext(options.contextOverride, requestedMode) + } } sendUserToast( `Could not prepare the session before sending: ${ @@ -3821,7 +3987,10 @@ export class AIChatManager implements ChatViewHost { // text, only if the composer took it. const taken = this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) this.#restoreMentionContext(options.contextOverride, requestedMode) + if (taken) { + this.#restoreDomContext(options.contextOverride, true) + this.#restoreMentionContext(options.contextOverride, requestedMode) + } } return true } @@ -3971,10 +4140,24 @@ export class AIChatManager implements ChatViewHost { workspace: this.operatingWorkspace }) logFeatureUsage('ai_session', 'autonomy', { - key: this.autonomyMode, + // Planning keeps its own key, `plan`, so the series still tells it apart. + key: this.planModeActive ? AIWorkMode.PLAN : this.autonomyMode, entityId: this.sessionId, workspace: this.operatingWorkspace }) + if (this.workModesAvailable) { + // Keyed by the mode the message runs in, not `workMode`, which a held session keeps. + // Held Use has its own keys, so `use_chosen` counts only sessions that could build. + logFeatureUsage('ai_session', 'work_mode', { + key: this.#useReason + ? `use_${this.#useReason}` + : this.planModeActive + ? AIWorkMode.PLAN + : AIWorkMode.BUILD, + entityId: this.sessionId, + workspace: this.operatingWorkspace + }) + } } if (this.mode === AIMode.FLOW && !this.flowAiChatHelpers) { @@ -4121,61 +4304,24 @@ export class AIChatManager implements ChatViewHost { this.currentReasoningActive = false this.resetReasoningTiming() - // Compaction trigger. An unrecognized model still gets the conservative - // assumed window rather than no limit: without one the context grows - // unbounded until the provider (or a proxy in front of it) times out. - // Guessing low only compacts earlier, which is always recoverable. - const contextWindow = model - ? getEffectiveModelContextWindow( - model.provider, - model.model, - get(copilotInfo).contextWindowPerModel - ) - : undefined - if ( - contextWindow !== undefined && - projectedContextTokens >= contextWindow * COMPACTION_TRIGGER_RATIO - ) { - // Preferred path: summarize the older prefix, keep the recent tail. - const summarized = await this.summarizeAndCompact(contextWindow) - // A Stop during the in-flight summary aborts this turn's controller; - // summarizeAndCompact then returns false without touching history. Skip - // the drop-oldest fallback (and its save) — it would destructively - // compact a conversation the user only meant to cancel, and the request - // can't run on an aborted controller anyway. The cancel path below rolls - // the pushed turn back cleanly on its own. - if (!this.abortController?.signal.aborted) { - if (!summarized) { - // Fallback when summarization isn't worthwhile or fails: drop the - // oldest messages. A report stays meaningful only debited by what - // was dropped; the estimate path needs no bookkeeping — the next - // read re-estimates the compacted history. chars/4 can - // underestimate the freed tokens, which errs toward compacting - // again — never toward overflowing. - const freed = this.compactOldestMessages( - projectedContextTokens - contextWindow * COMPACTION_TARGET_RATIO - ) - if (this.contextUsage !== undefined) { - this.contextUsage = Math.max(0, this.contextUsage - freed) - } - } - // Reconcile file registrations with the compacted transcript — the - // summary message carries the folded-away turns' files forward. - this.#syncMessageFiles() - await this.historyManager.saveChat( - this.displayMessages, - this.messages, - this.contextUsage, - this.modifiedItems ? [...this.modifiedItems] : undefined - ) - } + if (await this.compactIfOverTrigger(projectedContextTokens, model)) { + await this.historyManager.saveChat( + this.displayMessages, + this.messages, + this.contextUsage, + this.modifiedItems ? [...this.modifiedItems] : undefined + ) } // Rollback anchors for restoreUnsentTurn: captured after compaction so // they index into the (possibly compacted) stored history. The summary // path shrinks displayMessages too, so the display anchor must also be // read here, not before compaction. + // Mid-turn compaction leaves these stale, but it runs only once the turn has + // tool-paired output, which keeps the turn off the restore path. const modelLenAfterUser = this.messages.length const displayLenAfterUser = this.displayMessages.length + // Set when a mid-turn compaction makes the latest provider report stale. + let usageBeforeCompaction: ChatTokenUsage | null = null const params: { messages: ChatCompletionMessageParam[] @@ -4275,6 +4421,7 @@ export class AIChatManager implements ChatViewHost { shouldAutoAcceptToolConfirmations: this.shouldAutoAcceptTool, isPlanModeActive: () => this.planModeActive, onToolBlockedByPlanMode: this.planMode.noteBlockedTool, + isToolWithdrawn: this.isToolWithdrawn, requestUserQuestion: this.requestUserQuestion, requestRunArgs: this.requestRunArgs, markRunFormStarted: this.markRunFormStarted, @@ -4303,6 +4450,46 @@ export class AIChatManager implements ChatViewHost { addedMessages: collectedMessages, onWebSearchUnavailable: () => { webSearchUnavailable = true + }, + onBeforeIteration: async (iterationModel, lastIterationUsage) => { + // The first iteration sends exactly what the send-time check measured. + if (collectedMessages.length === 0) return + // The last report's prompt covers everything before its assistant message. + // That message counts as its `completion` only on Anthropic, which replays + // its thinking verbatim (`_anthropicContent`); other providers bill reasoning + // the next request does not replay, so it is estimated. The estimate is + // the floor in case a later iteration's report never arrived. A report + // from before a compaction measured the history it replaced. + const lastAssistant = collectedMessages.findLastIndex((m) => m.role === 'assistant') + const replaysOutput = !!(collectedMessages[lastAssistant] as any)?._anthropicContent + const reported = + lastIterationUsage && lastIterationUsage !== usageBeforeCompaction + ? lastIterationUsage.prompt + + (replaysOutput ? lastIterationUsage.completion : 0) + + this.estimateMessagesTokens( + collectedMessages.slice(replaysOutput ? lastAssistant + 1 : lastAssistant) + ) + : 0 + const historyTokens = this.estimateWholeContextTokens() + // Whatever the report sees beyond the stored history is the turn's, replayed + // thinking included, so the summary leaves room for it. + const inFlightTokens = Math.max( + this.estimateMessagesTokens(collectedMessages), + reported - historyTokens + ) + const projected = Math.max(reported, historyTokens + inFlightTokens) + if (await this.compactIfOverTrigger(projected, iterationModel, inFlightTokens)) { + usageBeforeCompaction = lastIterationUsage + // The loop sends from this array, which mirrors the stored history + // plus the turn so far. + params.messages.splice( + 0, + params.messages.length, + ...this.messages, + ...collectedMessages + ) + await checkpointTurn(true) + } } }) stopCheckpoints() @@ -4324,9 +4511,10 @@ export class AIChatManager implements ChatViewHost { // stored history it was sent with (the kept partial tail is a small // undercount the trigger headroom absorbs). Without one, clear the // stale value — readers estimate via contextTokens. - this.contextUsage = result?.lastIterationUsage - ? result.lastIterationUsage.prompt + result.lastIterationUsage.completion - : undefined + this.contextUsage = + result?.lastIterationUsage && result.lastIterationUsage !== usageBeforeCompaction + ? result.lastIterationUsage.prompt + result.lastIterationUsage.completion + : undefined await this.historyManager.saveChat( this.displayMessages, this.messages, @@ -4395,9 +4583,10 @@ export class AIChatManager implements ChatViewHost { // stored — no anchoring or index bookkeeping needed. Without a // report, clear the now-stale value — readers estimate via // contextTokens. - this.contextUsage = result?.lastIterationUsage - ? result.lastIterationUsage.prompt + result.lastIterationUsage.completion - : undefined + this.contextUsage = + result?.lastIterationUsage && result.lastIterationUsage !== usageBeforeCompaction + ? result.lastIterationUsage.prompt + result.lastIterationUsage.completion + : undefined if (this.autoAcceptEditsActive) { this.acceptPendingFlowEdits() } diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index d8056e778f..582e789cf7 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -8,6 +8,7 @@ import type { ChatCompletionMessageParam } from 'openai/resources/chat/completio import type { DisplayMessage } from './shared' import type { AttachedImage } from './imageUtils' import { AIChatManager, AIMode, AIAutonomyMode } from './AIChatManager.svelte' +import { AIWorkMode, USE_MODE_WITHDRAWN } from './workMode' import { makePasteToken } from './pasteTokens' import { chatState } from './sharedChatState.svelte' import { PLAN_MODE_MESSAGES } from './planModeMessages' @@ -51,9 +52,12 @@ vi.mock('monaco-editor', () => ({ vi.mock('$lib/utils/featureUsage', () => ({ logFeatureUsage: vi.fn() })) vi.mock('$lib/gen', () => ({ - WorkspaceService: {}, + WorkspaceService: { + listProtectionRules: vi.fn(async () => []) + }, ResourceService: { - listResource: mocks.listResource + listResource: mocks.listResource, + listResourceTypeNames: vi.fn(async () => []) }, ScriptService: {}, FlowService: {}, @@ -114,7 +118,16 @@ vi.mock('$lib/stores', () => { // non-membership once this has resolved. usersWorkspaceStore: readable({ workspaces: [] as unknown[] }), NON_MEMBER_USERNAME: 'superadmin', - enterpriseLicense: readable(undefined) + enterpriseLicense: readable(undefined), + // The admin above holds every role capability. + roleCapabilities: readable({ + code: true, + flows: 'full', + apps: 'full', + manage_schedules: true, + manage_triggers: true, + visibility: {} + }) } }) @@ -977,13 +990,11 @@ describe('AIChatManager autonomy mode', () => { }) // The posture's own behaviour lives in planModeController.test.ts. What is left here is the -// wiring only the manager owns: which pending confirmation cards a change of autonomy mode -// answers, and with what. +// wiring only the manager owns: which pending confirmation cards a change of work mode or of +// autonomy mode answers, and with what. describe('AIChatManager plan mode posture', () => { beforeEach(() => { localStorage.clear() - // Plan mode is never the persisted posture, so a case starts from the one it is - // entered from and hands back to. localStorage.setItem(`ai-chat-autonomy-mode::${TEST_EMAIL}`, AIAutonomyMode.DEFAULT) vi.clearAllMocks() }) @@ -996,7 +1007,7 @@ describe('AIChatManager plan mode posture', () => { return manager } - it('enters plan mode through the tool and remembers the posture to hand back to', async () => { + it('enters plan mode through the tool and leaves the confirmations setting alone', async () => { const manager = sessionManager(AIAutonomyMode.ACCEPT_EDIT) await manager.planMode.enterTool.fn({ @@ -1008,12 +1019,12 @@ describe('AIChatManager plan mode posture', () => { }) expect(manager.planModeActive).toBe(true) - expect(manager.prePlanAutonomyMode).toBe(AIAutonomyMode.ACCEPT_EDIT) + expect(manager.autonomyMode).toBe(AIAutonomyMode.ACCEPT_EDIT) }) it('refuses to move a session chat out of GLOBAL, so the gate cannot lift under it', () => { const manager = sessionManager(AIAutonomyMode.ACCEPT_EDIT) - manager.setAutonomyMode(AIAutonomyMode.PLAN) + manager.setWorkMode(AIWorkMode.PLAN) expect(manager.planModeActive).toBe(true) // Without a configured model changeMode returns early on SCRIPT, and the case would pass // against the very guard it is meant to pin. @@ -1074,21 +1085,74 @@ describe('AIChatManager plan mode posture', () => { it('answers a pending plan card the way the picker was moved', async () => { const entering = sessionManager() const enterPending = entering.requestConfirmation('call_enter', 'enter_plan_mode') - entering.setAutonomyMode(AIAutonomyMode.PLAN) + entering.setWorkMode(AIWorkMode.PLAN) expect(await enterPending).toBe(true) // Leaving plan mode any other way is not a sign-off on the plan on the card. - const leaving = sessionManager(AIAutonomyMode.PLAN) + const leaving = sessionManager() + leaving.setWorkMode(AIWorkMode.PLAN) const exitPending = leaving.requestConfirmation('call_exit', 'exit_plan_mode') - leaving.setAutonomyMode(AIAutonomyMode.DEFAULT) + leaving.setWorkMode(AIWorkMode.BUILD) expect(await exitPending).toBe(false) - // Opting into YOLO does mean "run it". - const yolo = sessionManager(AIAutonomyMode.PLAN) + // Building under YOLO does mean "run it". + const yolo = sessionManager(AIAutonomyMode.YOLO) + yolo.setWorkMode(AIWorkMode.PLAN) const yoloPending = yolo.requestConfirmation('call_exit', 'exit_plan_mode') - yolo.setAutonomyMode(AIAutonomyMode.YOLO) + yolo.setWorkMode(AIWorkMode.BUILD) expect(await yoloPending).toBe(true) }) + + it('waits for the user on a plan card while planning under YOLO', async () => { + // YOLO is the posture an approved plan is carried out in; the approval itself is not its + // to give, or a plan no card ever showed would be run. + const manager = sessionManager() + manager.setWorkMode(AIWorkMode.PLAN) + manager.setAutonomyMode(AIAutonomyMode.YOLO) + let settled = false + void manager.requestConfirmation('call_exit', 'exit_plan_mode').then(() => (settled = true)) + await Promise.resolve() + expect(settled).toBe(false) + expect(manager.planMode.tools.map((t) => t.def.function.name)).toEqual(['exit_plan_mode']) + }) + + // The call was made with Build's tools; approving its card after the switch to Use must not + // run the write the session no longer ships. + it('does not run a write approved after the session switched to Use', async () => { + const { processToolCall } = await import('./shared') + const manager = sessionManager() + manager.configureGlobalMode() + const write = manager.availableTools.find((t) => t.def.function.name === 'write_script')! + const fn = vi.fn(async () => 'written') + let asked = false + const result = processToolCall({ + tools: [{ ...write, fn, requiresConfirmation: true }] as any, + toolCall: { + id: 'call_write', + type: 'function', + function: { name: 'write_script', arguments: '{}' } + } as any, + helpers: {}, + workspace: 'test-workspace', + toolCallbacks: { + setToolStatus: vi.fn(), + removeToolStatus: vi.fn(), + requestConfirmation: (id: string, name?: string) => { + asked = true + return manager.requestConfirmation(id, name) + }, + shouldAutoAcceptToolConfirmations: manager.shouldAutoAcceptTool, + isToolWithdrawn: manager.isToolWithdrawn + } as any + }) + await vi.waitFor(() => expect(asked).toBe(true)) + + manager.setWorkMode(AIWorkMode.USE) + manager.handleToolConfirmation('call_write', true) + + expect((await result).content).toBe(USE_MODE_WITHDRAWN.result) + expect(fn).not.toHaveBeenCalled() + }) }) describe('AIChatManager persisted autonomy default', () => { @@ -2882,6 +2946,26 @@ describe('AIChatManager queued messages', () => { expect(manager.contextManager.getSelectedContext()).toEqual([mention]) }) + // A hand-off's chip only ever lived in contextOverride, never in the selection. + it('restores a DOM chip carried only by contextOverride when the preflight is cancelled', async () => { + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + const chip = { + type: 'app_dom_selector' as const, + selector: 'h1', + appPath: 'f/app', + tagName: 'h1' + } + manager.contextManager.setSelectedContext([]) + manager.beforeSend = vi.fn().mockImplementation(async () => { + manager.cancel('user_cancelled') + }) + + await manager.sendRequest({ instructions: 'make this bigger', contextOverride: [chip] }) + + expect(manager.contextManager.getSelectedContext()).toMatchObject([{ selector: 'h1' }]) + }) + // The gate, and the reason the restore is not unconditional: an occupied // composer declines the dead draft's text, and its mentions would then ride the // draft the user is writing now and every turn after it. @@ -3394,6 +3478,186 @@ describe('AIChatManager context compaction', () => { manager.instructions = 'next question' } + it('compacts between tool iterations once tool results carry the turn over the trigger', async () => { + mocks.getCurrentModel.mockReturnValue(gpt4oModel) + mocks.tryGetCurrentModel.mockReturnValue(gpt4oModel) + mocks.getStreamedCompletionText + .mockResolvedValueOnce('<summary>SUMMARY ONE</summary>') + .mockResolvedValueOnce('<summary>SUMMARY TWO</summary>') + const step = (id: string, chars: number) => [ + { + role: 'assistant' as const, + content: '', + tool_calls: [{ id, type: 'function', function: { name: 'x', arguments: '{}' } }] + }, + { role: 'tool' as const, tool_call_id: id, content: 'r'.repeat(chars) } + ] + // ~25k estimated tokens: enough to push a ~60% history past the 0.8 * 128k trigger. + const first = step('t1', 100_000) + // ~70k more: crosses the trigger again within the same turn. + const second = step('t2', 280_000) + let secondIteration: any[] = [] + let thirdIteration: any[] = [] + mocks.runChatLoop.mockImplementation(async (config: any) => { + const push = (ms: any[]) => { + for (const m of ms) { + config.messages.push(m) + config.addedMessages.push(m) + } + } + await config.onBeforeIteration(gpt4oModel, null) + push(first) + await config.onBeforeIteration(gpt4oModel, null) + secondIteration = [...config.messages] + push(second) + await config.onBeforeIteration(gpt4oModel, null) + thirdIteration = [...config.messages] + const reply = { role: 'assistant' as const, content: 'done' } + push([reply]) + return { + addedMessages: [...first, ...second, reply], + tokenUsage: { prompt: 0, completion: 0, total: 0 }, + lastIterationUsage: null, + hitMaxIterations: false + } + }) + const manager = new AIChatManager() + // ~80k estimated tokens over ten messages: under the trigger at send time. + manager.messages = Array.from({ length: 10 }, (_, i) => ({ + role: i % 2 === 0 ? ('user' as const) : ('assistant' as const), + content: `m${i}` + 'x'.repeat(32_000) + })) + manager.displayMessages = manager.messages.map((m, i) => + m.role === 'user' + ? { role: 'user', content: `m${i}`, index: i } + : { role: 'assistant', content: `m${i}` } + ) + manager.instructions = 'next question' + + await manager.sendRequest() + + // Not at send time (under the trigger), only once the tool result landed. + expect(secondIteration[0].content).toContain('SUMMARY ONE') + expect(secondIteration.slice(-2)).toEqual(first) + // The second trigger folds the first summary into a new one instead of + // dropping it to make room for the turn. + expect(mocks.getStreamedCompletionText).toHaveBeenCalledTimes(2) + expect(mocks.getStreamedCompletionText.mock.calls[1][0][0].content).toContain('SUMMARY ONE') + expect(thirdIteration[0].content).toContain('SUMMARY TWO') + expect(thirdIteration.slice(-4)).toEqual([...first, ...second]) + expect(manager.messages[0].content).toContain('SUMMARY TWO') + expect(manager.displayMessages[0].role).toBe('summary') + }) + + it('compacts mid-turn off the provider report, then stops trusting the report it replaced', async () => { + mocks.getCurrentModel.mockReturnValue(gpt4oModel) + mocks.tryGetCurrentModel.mockReturnValue(gpt4oModel) + mocks.getStreamedCompletionText.mockResolvedValue('<summary>SUMMARY ONE</summary>') + const step = (id: string) => [ + { + role: 'assistant' as const, + content: '', + tool_calls: [{ id, type: 'function', function: { name: 'x', arguments: '{}' } }] + }, + { role: 'tool' as const, tool_call_id: id, content: 'r'.repeat(8_000) } + ] + // The provider counts far more than chars/4 sees: over the 0.8 * 128k trigger. + const report = { prompt: 101_000, completion: 1_000, total: 102_000 } + let thirdIteration: any[] = [] + mocks.runChatLoop.mockImplementation(async (config: any) => { + const push = (ms: any[]) => { + for (const m of ms) { + config.messages.push(m) + config.addedMessages.push(m) + } + } + await config.onBeforeIteration(gpt4oModel, null) + push(step('t1')) + await config.onBeforeIteration(gpt4oModel, report) + push(step('t2')) + // The iteration after the compaction reported nothing, so the loop hands the + // pre-compaction report back. + await config.onBeforeIteration(gpt4oModel, report) + thirdIteration = [...config.messages] + const reply = { role: 'assistant' as const, content: 'done' } + push([reply]) + return { + addedMessages: [...step('t1'), ...step('t2'), reply], + tokenUsage: report, + lastIterationUsage: report, + hitMaxIterations: false + } + }) + const manager = new AIChatManager() + // ~75k estimated tokens: under the trigger by the estimate alone. + manager.messages = Array.from({ length: 10 }, (_, i) => ({ + role: i % 2 === 0 ? ('user' as const) : ('assistant' as const), + content: `m${i}` + 'x'.repeat(30_000) + })) + manager.displayMessages = manager.messages.map((m, i) => + m.role === 'user' + ? { role: 'user', content: `m${i}`, index: i } + : { role: 'assistant', content: `m${i}` } + ) + manager.instructions = 'next question' + + await manager.sendRequest() + + expect(mocks.getStreamedCompletionText).toHaveBeenCalledTimes(1) + expect(thirdIteration[0].content).toContain('SUMMARY ONE') + // Nor does the stale report become the stored usage at commit. + expect(manager.contextUsage).toBeUndefined() + }) + + it('counts replayed Anthropic thinking toward the mid-turn projection', async () => { + mocks.getCurrentModel.mockReturnValue(gpt4oModel) + mocks.tryGetCurrentModel.mockReturnValue(gpt4oModel) + mocks.getStreamedCompletionText.mockResolvedValue('<summary>SUMMARY ONE</summary>') + // Under the 0.8 * 128k trigger without the thinking the next request replays. + const report = { prompt: 80_000, completion: 25_000, total: 105_000 } + let historyAfter: any[] = [] + mocks.runChatLoop.mockImplementation(async (config: any) => { + await config.onBeforeIteration(gpt4oModel, null) + const assistant = { + role: 'assistant' as const, + content: '', + tool_calls: [{ id: 't1', type: 'function', function: { name: 'x', arguments: '{}' } }], + _anthropicContent: [{ type: 'thinking', thinking: '...', signature: 'sig' }] + } + const tool = { role: 'tool' as const, tool_call_id: 't1', content: 'r'.repeat(4_000) } + for (const m of [assistant, tool]) { + config.messages.push(m) + config.addedMessages.push(m) + } + await config.onBeforeIteration(gpt4oModel, report) + historyAfter = config.messages.slice(0, -2) + return { + addedMessages: [assistant, tool], + tokenUsage: report, + lastIterationUsage: report, + hitMaxIterations: false + } + }) + const manager = new AIChatManager() + manager.messages = Array.from({ length: 10 }, (_, i) => ({ + role: i % 2 === 0 ? ('user' as const) : ('assistant' as const), + content: `m${i}` + 'x'.repeat(30_000) + })) + manager.displayMessages = manager.messages.map((m, i) => + m.role === 'user' + ? { role: 'user', content: `m${i}`, index: i } + : { role: 'assistant', content: `m${i}` } + ) + manager.instructions = 'next question' + + await manager.sendRequest() + + expect(mocks.getStreamedCompletionText).toHaveBeenCalledTimes(1) + // The kept history leaves room for the replayed thinking within the 0.5 target. + const keptTokens = historyAfter.reduce((acc, m) => acc + String(m.content).length / 4, 0) + expect(keptTokens + report.completion).toBeLessThan(128_000 * 0.5) + }) + it('summarizes the older prefix and keeps the recent tail verbatim', async () => { mocks.getCurrentModel.mockReturnValue(gpt4oModel) mocks.tryGetCurrentModel.mockReturnValue(gpt4oModel) @@ -4738,6 +5002,26 @@ describe('AIChatManager tool views', () => { expect(manager.systemMessage.content).not.toContain('write_script') }) + // Use is the user's own pick, so no profile resolves for it: the switch alone has to strip + // the writes from the tools and the prompt, and hand them back on Build. + it('ships only reads and runs in Use, and the writes again in Build', () => { + const manager = new AIChatManager() + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + manager.configureGlobalMode() + const names = () => manager.availableTools.map((t) => t.def.function.name) + expect(names()).toContain('write_script') + + manager.setWorkMode(AIWorkMode.USE) + expect(names()).toEqual(expect.arrayContaining(['list_workspace_items', 'run_script'])) + expect(names()).not.toContain('write_script') + expect(manager.systemMessage.content).not.toContain('write_script') + + manager.setWorkMode(AIWorkMode.BUILD) + expect(names()).toContain('write_script') + expect(manager.systemMessage.content).toContain('write_script') + }) + // Which transition each posture offers is planModeController.test.ts's; what this pins is // that only `tools` follows the picker. `isSessionChat` is what offers plan mode at all. it('holds availableTools steady across the autonomy picker', async () => { @@ -4754,4 +5038,56 @@ describe('AIChatManager tool views', () => { expect(names(manager.tools)).not.toContain('enter_plan_mode') expect(names(manager.availableTools)).toEqual(before) }) + + it('offers the switch out of the mode the session is in, and switches only once called', async () => { + const manager = new AIChatManager() + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + manager.configureGlobalMode() + // The posture is persisted, and the test above leaves it on Yolo. + manager.setAutonomyMode(AIAutonomyMode.DEFAULT) + const shipped = () => manager.tools.map((t) => t.def.function.name) + expect(shipped()).toContain('enter_use_mode') + expect(shipped()).not.toContain('enter_build_mode') + + // Plan leaves through its plan's approval, and Yolo would answer the card for the user. + manager.setWorkMode(AIWorkMode.PLAN) + expect(shipped()).not.toContain('enter_use_mode') + expect(shipped()).not.toContain('enter_build_mode') + manager.setWorkMode(AIWorkMode.USE) + manager.setAutonomyMode(AIAutonomyMode.YOLO) + expect(shipped()).not.toContain('enter_build_mode') + manager.setAutonomyMode(AIAutonomyMode.DEFAULT) + + const enterBuild = manager.tools.find((t) => t.def.function.name === 'enter_build_mode') + expect(manager.workMode).toBe(AIWorkMode.USE) + await enterBuild?.fn({} as any) + expect(manager.workMode).toBe(AIWorkMode.BUILD) + expect(manager.systemMessage.content).toContain('write_script') + }) + + // The card is the only consent the switch has: the picker can answer it by going where it + // asked, and turning on Yolo must not approve it. + it('resolves a pending switch card from the picker, and never from Yolo', async () => { + const manager = new AIChatManager() + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + manager.configureGlobalMode() + manager.setAutonomyMode(AIAutonomyMode.DEFAULT) + manager.setWorkMode(AIWorkMode.USE) + + const toPlan = manager.requestConfirmation('a', 'enter_build_mode') + manager.setWorkMode(AIWorkMode.PLAN) + await expect(toPlan).resolves.toBe(false) + + manager.setWorkMode(AIWorkMode.USE) + const toBuild = manager.requestConfirmation('b', 'enter_build_mode') + manager.setWorkMode(AIWorkMode.BUILD) + await expect(toBuild).resolves.toBe(true) + + manager.setWorkMode(AIWorkMode.USE) + const underYolo = manager.requestConfirmation('c', 'enter_build_mode') + manager.setAutonomyMode(AIAutonomyMode.YOLO) + await expect(underYolo).resolves.toBe(false) + }) }) diff --git a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte index d11375b89b..5f4b4a5040 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte @@ -240,6 +240,9 @@ const config = $derived<ChatModelSettingsConfig>({ label: providerModel.model, + // "claude-sonnet-4-6" → "sonnet": the family is what tells Claude models apart at a + // glance. Other providers' names have no such word, so they stay whole. + shortLabel: /^claude-([a-z]+)-/.exec(providerModel.model)?.[1], title: 'Model & reasoning settings', badge: freeTier && !freeTier.exhausted ? { text: 'Free', warn: freeRunningLow } : undefined, // Off in a session: the assistant settings modal's Instructions section owns the diff --git a/frontend/src/lib/components/copilot/chat/AssistantPermissionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantPermissionsSection.svelte index ee7b4a689c..c24b7097ee 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantPermissionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantPermissionsSection.svelte @@ -3,7 +3,7 @@ The Permissions section of the assistant settings modal: what the user's role lets them create and edit in the chat's workspace, next to what the assistant can make for them from the chat. The assistant acts with the user's own rights, but its write tools go through drafts, so for -operators the second column is narrower. +a restricted role the second column can be narrower. --> <script lang="ts"> import { Badge, Section } from '$lib/components/common' @@ -11,6 +11,7 @@ operators the second column is narrower. import { userWorkspaces } from '$lib/stores' import { useActingUser } from '$lib/actingUser.svelte' import { capitalize } from '$lib/utils/capitalize' + import { capabilitiesIn, isRestricted } from '$lib/roleCapabilities' import { OPERATOR_SETTINGS_LOCATION, permissionRows, roleName } from './assistantPermissions' let { ws }: { ws: string } = $props() @@ -18,9 +19,11 @@ operators the second column is narrower. const acting = useActingUser(() => ws) let user = $derived(acting.current) - let operatorSettings = $derived($userWorkspaces.find((w) => w.id === ws)?.operator_settings) - let role = $derived(user ? roleName(user) : undefined) - let rows = $derived(user ? permissionRows(user, operatorSettings) : []) + let entry = $derived($userWorkspaces.find((w) => w.id === ws)) + let caps = $derived(capabilitiesIn(user, entry)) + let restricted = $derived(isRestricted(caps)) + let role = $derived(user ? roleName(user, entry) : undefined) + let rows = $derived(user ? permissionRows(user, caps) : []) let chatNarrower = $derived(rows.some((r) => r.user && !r.assistant)) </script> @@ -31,7 +34,7 @@ operators the second column is narrower. > {#snippet action()} {#if role} - <Badge color={role === 'operator' ? 'yellow' : 'gray'}>{capitalize(role)}</Badge> + <Badge color={restricted ? 'yellow' : 'gray'}>{capitalize(role)}</Badge> {/if} {/snippet} @@ -76,9 +79,9 @@ operators the second column is narrower. Items in folders you can't read are hidden from you and from the assistant. Someone with access to the folder can run them. </p> - {#if role === 'operator'} + {#if restricted} <p> - A workspace admin can give operators more rights in {OPERATOR_SETTINGS_LOCATION}. + A workspace admin can give your role more rights in {OPERATOR_SETTINGS_LOCATION}. </p> {/if} </div> diff --git a/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte b/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte new file mode 100644 index 0000000000..e236e4a4c0 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte @@ -0,0 +1,110 @@ +<script lang="ts"> + import { ArrowRight, ChevronDown } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import type { Item } from '$lib/utils' + import type { AIAutonomyMode } from './AIChatManager.svelte' + import { AIWorkMode, type WorkModeLock } from './workMode' + import { + autonomyModeOption, + availableAutonomyModeOptions, + resolveAutonomyMode, + workModeOption, + workModeOptions, + type AutonomyAvailability + } from './autonomyModes' + + let { + mode, + availability, + onChange, + work = undefined + }: { + mode: AIAutonomyMode + availability: AutonomyAvailability + onChange: (mode: AIAutonomyMode) => void + /** A session chat's Use / Plan / Build, shown as the picker's first section. */ + work?: { + mode: AIWorkMode + planAvailable: boolean + /** Holds the chat in Use, and says why. */ + lock?: WorkModeLock + onChange: (mode: AIWorkMode) => void + } + } = $props() + + const effective = $derived(resolveAutonomyMode(mode, availability)) + const option = $derived(autonomyModeOption(effective)) + // Plan where the chat no longer offers it falls back to Build, as the manager does. + const workOption = $derived( + !work + ? undefined + : workModeOption( + work.lock + ? AIWorkMode.USE + : work.mode === AIWorkMode.PLAN && !work.planAvailable + ? AIWorkMode.BUILD + : work.mode + ) + ) + const postureLabel = $derived(option.shortLabel ?? option.label) + + function items(): Item[] { + const sections = !!work + const postures: Item[] = availableAutonomyModeOptions(availability).map((o, i) => ({ + displayName: o.label, + sectionTitle: sections && i === 0 ? 'Confirmations' : undefined, + separatorTop: sections && i === 0, + selected: effective === o.mode, + action: () => onChange(o.mode) + })) + const w = work + if (!w) return postures + const lockedOut = (m: AIWorkMode) => !!w.lock && m !== AIWorkMode.USE + const workItems: Item[] = workModeOptions + .filter((o) => o.mode !== AIWorkMode.PLAN || w.planAvailable || w.lock) + .map((o, i) => { + const locked = lockedOut(o.mode) + return { + displayName: o.label, + description: o.description, + icon: o.icon, + // `iconColor` takes a color value; these are text classes. A locked row's icon + // keeps the disabled color its label has. + iconProps: { class: locked ? 'shrink-0' : `shrink-0 ${o.iconColor}` }, + sectionTitle: i === 0 ? 'What the chat can do' : undefined, + selected: workOption?.mode === o.mode, + disabled: locked, + tooltip: locked ? w.lock?.reason : undefined, + action: () => w.onChange(o.mode) + } + }) + const escape = w.lock?.escape + return [ + ...workItems, + ...(escape ? [{ displayName: escape.label, icon: ArrowRight, action: escape.action }] : []), + ...postures + ] + } +</script> + +<DropdownV2 {items} placement="bottom-start" fixedHeight={false} customWidth={work ? 260 : 240}> + {#snippet buttonReplacement()} + <Button + nonCaptureEvent + unifiedSize="2xs" + variant="subtle" + title={workOption + ? (work?.lock?.reason ?? `${workOption.description} ${option.tooltip(availability)}`) + : option.tooltip(availability)} + btnClasses={workOption?.triggerClass ?? ''} + startIcon={{ + icon: (workOption ?? option).icon, + classes: (workOption ?? option).iconColor + }} + endIcon={{ icon: ChevronDown }} + > + {workOption ? `${workOption.label} · ${postureLabel}` : postureLabel} + </Button> + {/snippet} +</DropdownV2> diff --git a/frontend/src/lib/components/copilot/chat/ComposerPlaceholder.svelte b/frontend/src/lib/components/copilot/chat/ComposerPlaceholder.svelte new file mode 100644 index 0000000000..2aba3d0be4 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/ComposerPlaceholder.svelte @@ -0,0 +1,115 @@ +<script lang="ts"> + import { ArrowUp } from 'lucide-svelte' + import { twMerge } from 'tailwind-merge' + import { Button } from '$lib/components/common' + import autosize from '$lib/autosize' + import { CHAT_INPUT_PADDING } from './aiChatManagerContext' + import type { Snippet } from 'svelte' + import { + composerBoxClass, + COMPOSER_FIELD_RESET, + HERO_BOX_CLASS, + type ComposerSelection + } from './composerBox' + + /** + * The chat composer's box, drawn while the chat code loads. It must import nothing of + * AIChat's: it exists so the page can show and type into the composer before that code + * arrives. The host passes `value` and the last selection to the real composer when it mounts. + */ + let { + value = $bindable(), + placeholder, + disabled = false, + autofocus = false, + onSelectionChange, + onCompositionChange, + toolbar + }: { + value: string + placeholder?: string + disabled?: boolean + autofocus?: boolean + /** The caret while the field has focus, undefined once the user moves to another element. */ + onSelectionChange?: (selection: ComposerSelection | undefined) => void + /** Whether an IME composition is in progress: replacing the field then would lose it. */ + onCompositionChange?: (composing: boolean) => void + /** Draws the box that opens a session (AIChatInput's `hero`), its controls row in the box. */ + toolbar?: Snippet + } = $props() + + function trackSelection(e: Event & { currentTarget: HTMLTextAreaElement }) { + onSelectionChange?.({ + start: e.currentTarget.selectionStart, + end: e.currentTarget.selectionEnd + }) + } +</script> + +{#snippet sendButton(size: 'sm' | 'md')} + <Button + variant="subtle" + unifiedSize={size} + iconOnly + title="Send" + startIcon={{ icon: ArrowUp }} + disabled + /> +{/snippet} + +<div class="relative mt-1"> + <div class={twMerge(composerBoxClass(disabled), toolbar && HERO_BOX_CLASS)}> + <div class="relative w-full"> + <!-- Text metrics match ContextTextarea's `.textarea-input`, so the swap moves nothing. --> + <textarea + {@attach (node) => { + if (autofocus) node.focus() + }} + bind:value + use:autosize={toolbar ? { maxHeight: 160, minHeight: 56 } : { maxHeight: '40vh' }} + rows={1} + {placeholder} + {disabled} + class={twMerge( + 'w-full resize-none overflow-clip whitespace-pre-wrap break-words text-xs leading-[1.72] min-h-[1.9rem]', + COMPOSER_FIELD_RESET, + CHAT_INPUT_PADDING, + toolbar && '!pl-4 !pr-4 !pt-3 !pb-1' + )} + onfocus={trackSelection} + oninput={trackSelection} + onselect={trackSelection} + onkeyup={trackSelection} + onpointerup={trackSelection} + onblur={(e) => { + // Unmounting the focused field blurs it, while still connected; that is the hand-off, + // not the user leaving. The field is detached by the time a microtask runs. A window + // blur leaves the field the active element, so it is not the user leaving either. + const field = e.currentTarget + queueMicrotask(() => { + if (field.isConnected && document.activeElement !== field) { + onSelectionChange?.(undefined) + } + }) + }} + oncompositionstart={() => onCompositionChange?.(true)} + oncompositionend={() => onCompositionChange?.(false)} + onkeydown={(e) => { + // Enter sends in the real composer; here it must not add a newline to the draft. + if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) e.preventDefault() + }} + ></textarea> + {#if !toolbar} + <div class="absolute bottom-1 right-1"> + {@render sendButton('md')} + </div> + {/if} + </div> + {#if toolbar} + <div class="flex flex-row items-center gap-1.5 px-3 pb-1.5"> + <div class="flex-1 min-w-0">{@render toolbar()}</div> + {@render sendButton('sm')} + </div> + {/if} + </div> +</div> diff --git a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte index dd3a011da2..8895ad1ed0 100644 --- a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte +++ b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte @@ -1,5 +1,12 @@ <script lang="ts"> - import { composerBoxClass, COMPOSER_FIELD_RESET } from './composerBox' + import { + composerBoxClass, + COMPOSER_FIELD_RESET, + HERO_BOX_CLASS, + type ComposerSelection + } from './composerBox' + import { smoothHeight } from './starter/smoothHeight' + import { MessagesSquare } from 'lucide-svelte' import autosize from '$lib/autosize' import { tick, type Snippet } from 'svelte' import type { ContextElement } from './context' @@ -50,6 +57,14 @@ onKeyDown?: (e: KeyboardEvent) => void /** Rendered inside the input box, above the textarea (e.g. context chips). */ leading?: Snippet + /** Rendered inside the input box, below the textarea (the composer's controls). */ + trailing?: Snippet + /** The taller box that opens a session, matching Home's composer. */ + hero?: boolean + /** One row: the field and `trailing` side by side, for Home's composer at rest. */ + oneLine?: boolean + /** The assistant's chat mark before the field. */ + chatIcon?: boolean } let { @@ -66,7 +81,11 @@ onTextFiles, className = '', onKeyDown = undefined, - leading + leading, + trailing, + hero = false, + oneLine = false, + chatIcon = false }: Props = $props() const aiChatManager = getAiChatManager() @@ -761,8 +780,11 @@ prevMentionedTitles = cur }) - export function focus() { + export function focus(selection?: ComposerSelection) { textarea?.focus() + if (selection) { + textarea?.setSelectionRange(selection.start, selection.end) + } } // Wipe after dispatching a send: pre-zero `prevMentionedTitles` so the effect @@ -789,11 +811,35 @@ } </script> -<div class={composerBoxClass(disabled)}> - <!-- Context chips live inside the input box, above the textarea. The snippet +<!-- The box that opens a session grows and shrinks between its one-line and full shapes. --> +<div + class={twMerge(composerBoxClass(disabled), hero && HERO_BOX_CLASS)} + use:smoothHeight={{ enabled: hero, key: oneLine }} +> + <div class={oneLine ? 'flex flex-row items-center' : ''}> + <!-- Context chips live inside the input box, above the textarea. The snippet self-guards (renders nothing when empty) so no blank row appears. --> - {@render leading?.()} - <div class="relative w-full"> + {@render leading?.()} + {#if chatIcon} + <!-- The same mark as the "open in chat" buttons, centred on the field's first text line in + both shapes: the slot is that line (1px border + 12px padding down, 20px tall), so it + relies on the field's `!py-3`/`!pt-3` and the `leading-5` set alongside `chatIcon`. + Centring on the field box instead follows its autosized height, which varies. --> + <div class="flex items-start {oneLine ? 'flex-1 min-w-0' : ''}"> + <span class="flex items-center h-5 mt-[13px] ml-4 shrink-0"> + <MessagesSquare size={16} class="text-ai" /> + </span> + {@render field()} + </div> + {:else} + {@render field()} + {/if} + {@render trailing?.()} + </div> +</div> + +{#snippet field()} + <div class="relative w-full {oneLine ? 'flex-1 min-w-0' : ''}"> <div class={twMerge( 'textarea-input absolute inset-0 overflow-hidden pointer-events-none', @@ -811,7 +857,7 @@ bind:this={textarea} onkeydown={handleKeyDown} bind:value - use:autosize={{ maxHeight: '40vh' }} + use:autosize={hero && !oneLine ? { maxHeight: 160, minHeight: 56 } : { maxHeight: '40vh' }} rows={1} oninput={handleInput} onpaste={handlePaste} @@ -837,7 +883,9 @@ }} {placeholder} class={twMerge( - 'textarea-input resize-none caret-black dark:caret-white overflow-clip', + // `no-default-style`: the global input rule paints `surface-input` with `!important` + // and outranks `!bg-transparent`, so the field showed as a band on a hero box. + 'textarea-input no-default-style block resize-none caret-black dark:caret-white overflow-clip', COMPOSER_FIELD_RESET, CHAT_INPUT_PADDING, className @@ -846,7 +894,7 @@ {disabled} ></textarea> </div> -</div> +{/snippet} {#if showContextTooltip || showCommandTooltip} <Portal target="body"> diff --git a/frontend/src/lib/components/copilot/chat/JobsSegment.svelte b/frontend/src/lib/components/copilot/chat/JobsSegment.svelte index 31fce8fd6e..c56a3f1b05 100644 --- a/frontend/src/lib/components/copilot/chat/JobsSegment.svelte +++ b/frontend/src/lib/components/copilot/chat/JobsSegment.svelte @@ -6,7 +6,6 @@ import SessionStatusPopover from '$lib/components/sessions/SessionStatusPopover.svelte' import { zIndexes } from '$lib/zIndexes' import JobStatusIcon from '$lib/components/runs/JobStatusIcon.svelte' - import FlowStatusWaitingForEvents from '$lib/components/FlowStatusWaitingForEvents.svelte' import { ChevronUp, Hourglass, ThumbsUp, TimerOff } from 'lucide-svelte' import { slide } from 'svelte/transition' import { JobService, type Job } from '$lib/gen' @@ -244,6 +243,11 @@ let approvalOpen = $state(false) let approvalLabel = $state('') let approvalJob = $state<Job | undefined>(undefined) + // Loaded with the job, not with this segment: the approval form reaches the code editor, and + // the sessions page renders this segment on load. + let FlowStatusWaitingForEvents = $state.raw< + typeof import('$lib/components/FlowStatusWaitingForEvents.svelte').default | undefined + >(undefined) async function openApproval(job: ChatJob) { approvalLabel = job.label @@ -252,12 +256,16 @@ try { // The stored snapshot is trimmed; the approval form needs the full job // (flow_status + raw_flow), so fetch it fresh. - const full = await JobService.getJob({ - workspace: job.workspace, - id: job.jobId, - noLogs: true, - noCode: true - }) + const [full, form] = await Promise.all([ + JobService.getJob({ + workspace: job.workspace, + id: job.jobId, + noLogs: true, + noCode: true + }), + import('$lib/components/FlowStatusWaitingForEvents.svelte') + ]) + FlowStatusWaitingForEvents = form.default if (deriveChatJobStatus(full) === 'suspended') { approvalJob = full } else { @@ -383,7 +391,7 @@ bind:open={approvalOpen} minZIndex={zIndexes.monacoEditorSuggestions + 1} > - {#if approvalJob} + {#if approvalJob && FlowStatusWaitingForEvents} <FlowStatusWaitingForEvents job={approvalJob} workspaceId={approvalJob.workspace_id} diff --git a/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte b/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte index 6072b6e341..20e9b1df91 100644 --- a/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte @@ -9,6 +9,7 @@ import { sendUserToast } from '$lib/utils' import { getAiChatManager } from './aiChatManagerContext' import { PLAN_MODE_MESSAGES } from './planModeMessages' + import { USE_MODE_WITHDRAWN } from './workMode' import { scrollFades } from './scrollFades.svelte' import type { RunFormDisplay } from './shared' @@ -54,6 +55,14 @@ // off the entrypoint a `dynselect-` argument runs, which does not wait for Run. A password // field mints at mount, too early to hold off here, so `runThroughForm` gates that instead. const planMode = $derived(aiChatManager.planModeActive) + // A test run previews undeployed code, which Use withholds as plan mode withholds every run. + const refusal = $derived( + planMode + ? PLAN_MODE_MESSAGES.runFormRefused + : runForm.kind === 'test' && aiChatManager.useModeActive + ? USE_MODE_WITHDRAWN.testRunRefused + : undefined + ) onMount(() => { void tick().then(() => cardNode?.scrollIntoView({ block: 'nearest' })) @@ -79,10 +88,10 @@ return } // Ahead of processSecretArgs, which writes ephemeral variables to the workspace: the - // autonomy picker moves while a form sits pending, and the re-gate on the other side - // of the callback runs too late to unmake a write plan mode promised not to do. - if (aiChatManager.planModeActive) { - sendUserToast(PLAN_MODE_MESSAGES.runFormRefused, true) + // mode picker moves while a form sits pending, and the re-gate on the other side of the + // callback runs too late to unmake a write plan mode or Use promised not to do. + if (refusal) { + sendUserToast(refusal, true) return } if (!aiChatManager.beginRunFormSubmit(toolCallId)) return @@ -145,18 +154,19 @@ {#if hasArgs} <!-- Passing `helperScript` is what lets DynamicInput run a job before Run: it executes the `dynselect-` entrypoint on mount, carrying the other args as proposed, - and Cancel does not undo it. Withheld under plan mode, which promised no writes. + and Cancel does not undo it. Withheld under plan mode, which promised no writes, and from + a test run in Use, whose helper is undeployed code too. A test run names its draft by code: `deployed` resolves a stale version, or none. --> <SchemaForm bind:schema={draft.schema} - helperScript={planMode + helperScript={refusal ? undefined : runForm.kind === 'test' ? runForm.code && runForm.lang ? { source: 'inline', code: runForm.code, lang: runForm.lang } : undefined : { source: 'deployed', path: runForm.path, runnable_kind: runnableKind }} - disabled={planMode} + disabled={!!refusal} {workspace} prettifyHeader bind:isValid @@ -210,8 +220,8 @@ <span class="font-mono">{runForm.strippedKeys.join(', ')}</span> </p> {/if} - {#if planMode} - <p class="text-2xs text-secondary">{PLAN_MODE_MESSAGES.runFormRefused}</p> + {#if refusal} + <p class="text-2xs text-secondary">{refusal}</p> {/if} <!-- Reject then confirm at the end of the row, as ToolConfirmationFooter puts them: this @@ -232,7 +242,7 @@ variant="accent" unifiedSize="sm" startIcon={{ icon: Play }} - disabled={!isValid || submitting || planMode} + disabled={!isValid || submitting || !!refusal} onClick={run} > Run diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 2b09d75332..1b267472c8 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -21,6 +21,12 @@ PLAN_CARD_COPY, PLAN_MODE_TEXT_COLOR } from './planMode' + import { + isWorkModeSwitchTool, + WORK_MODE_SWITCH_CARD_COPY, + WORK_MODE_SWITCH_TARGET + } from './workMode' + import { workModeOption } from './autonomyModes' import { Button } from '$lib/components/common' import { markdownProse } from '$lib/components/markdownProse' import { getChatViewHost } from './chatViewHost' @@ -61,9 +67,17 @@ const mcpServer = $derived(message.mcpServer) const isPlanReview = $derived(message.toolName === EXIT_PLAN_MODE_TOOL) - const isPlanCard = $derived(isPlanCardTool(message.toolName)) + // A switch between Use and Use & build renders as enter_plan_mode's card, with its own copy + // and the icon of the mode it leads to. + const switchTool = $derived(isWorkModeSwitchTool(message.toolName) ? message.toolName : undefined) + const isPlanCard = $derived(isPlanCardTool(message.toolName) || switchTool !== undefined) const planCopy = $derived( - isPlanCardTool(message.toolName) ? PLAN_CARD_COPY[message.toolName] : undefined + isPlanCardTool(message.toolName) + ? PLAN_CARD_COPY[message.toolName] + : switchTool && WORK_MODE_SWITCH_CARD_COPY[switchTool] + ) + const CardIcon = $derived( + switchTool ? workModeOption(WORK_MODE_SWITCH_TARGET[switchTool]).icon : ClipboardList ) // exit_plan_mode carries the plan, enter_plan_mode the one-line justification. const planBody = $derived(isPlanReview ? message.parameters?.summary : message.parameters?.reason) @@ -225,13 +239,18 @@ {#if message.isLoading && !message.needsConfirmation} <Loader2 class="w-3.5 h-3.5 animate-spin text-blue-500 shrink-0" /> {:else if planState === 'settled'} - <Check class={twMerge('w-3.5 h-3.5 shrink-0', PLAN_MODE_TEXT_COLOR)} /> + <Check + class={twMerge( + 'w-3.5 h-3.5 shrink-0', + switchTool ? 'text-secondary' : PLAN_MODE_TEXT_COLOR + )} + /> {:else if planState === 'declined'} <!-- Muted and not red: declining a plan is an outcome, not a failure, and this state also covers a card resolved by leaving plan mode. --> <CircleMinus class="w-3.5 h-3.5 text-tertiary shrink-0" /> {:else} - <ClipboardList class="w-3.5 h-3.5 text-secondary shrink-0" /> + <CardIcon class="w-3.5 h-3.5 text-secondary shrink-0" /> {/if} <span class="text-primary font-medium text-2xs">{planLabel}</span> {#if planBodyText} @@ -264,7 +283,7 @@ toolCallId={message.tool_call_id} rejectLabel={planCopy?.reject} confirmLabel={planCopy?.confirm ?? ''} - confirmIcon={isPlanReview ? undefined : ClipboardList} + confirmIcon={isPlanReview ? undefined : CardIcon} class={extraClass} /> {/snippet} diff --git a/frontend/src/lib/components/copilot/chat/app/core.ts b/frontend/src/lib/components/copilot/chat/app/core.ts index 166df65a16..5a0ff5cc6d 100644 --- a/frontend/src/lib/components/copilot/chat/app/core.ts +++ b/frontend/src/lib/components/copilot/chat/app/core.ts @@ -22,7 +22,7 @@ import { appDatatableRole, sdkDatatableCall } from '$lib/components/raw_apps/dat import { RAW_APP_BASE } from '$system_prompts' // Backend runnable types -export type BackendRunnableType = 'script' | 'flow' | 'hubscript' | 'inline' +export type BackendRunnableType = 'script' | 'flow' | 'hubscript' | 'agent' | 'inline' export interface InlineScript { language: 'bun' | 'python3' @@ -311,9 +311,9 @@ const getSetBackendRunnableSchema = memo(() => ), name: z.string().describe('A short summary/description of what the runnable does'), type: z - .enum(['script', 'flow', 'hubscript', 'inline']) + .enum(['script', 'flow', 'hubscript', 'agent', 'inline']) .describe( - 'The type of runnable: "inline" for custom code, "script" for workspace script, "flow" for workspace flow, "hubscript" for hub script' + 'The type of runnable: "inline" for custom code, "script" for workspace script, "flow" for workspace flow, "hubscript" for hub script, "agent" for a saved AI agent (one chat turn)' ), staticInputs: z .record(z.string(), z.any()) @@ -328,7 +328,7 @@ const getSetBackendRunnableSchema = memo(() => .string() .optional() .describe( - 'Required when type is "script", "flow", or "hubscript". The fully qualified path to the workspace script/flow or hub script.' + 'Required when type is "script", "flow", "hubscript" or "agent". The fully qualified path to the workspace script/flow, hub script or AI agent.' ), viewerDataAccess: z .boolean() @@ -723,6 +723,11 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [ } const parsedArgs = getSetBackendRunnableSchema().parse(cleanedArgs) + if (parsedArgs.type === 'agent' && Object.keys(parsedArgs.staticInputs ?? {}).length > 0) { + const errorMsg = `An "agent" runnable takes no staticInputs: each turn's inputs come from the app.` + toolCallbacks.setToolStatus(toolId, { content: errorMsg, error: errorMsg }) + return errorMsg + } toolCallbacks.setToolStatus(toolId, { content: `Setting backend runnable '${parsedArgs.key}'...` }) @@ -1087,6 +1092,16 @@ When creating a backend runnable with \`set_backend_runnable\`: } \`\`\` +5. **For saved AI agents** (type: "agent"), one chat turn per call, taking \`user_message\` and either \`memory_id\` (the conversation id, for an agent with managed memory) or \`previous_messages\` (the history, for one whose memory is off); no staticInputs: + \`\`\` + { + key: "chat", + name: "Chat with the support agent", + type: "agent", + path: "f/support/agent" + } + \`\`\` + ## Instructions 1. Use the smallest context needed. If the target file or runnable is clear, inspect only that item with \`get_frontend_file(path)\` or \`get_backend_runnable(key)\`. diff --git a/frontend/src/lib/components/copilot/chat/assistantPermissions.ts b/frontend/src/lib/components/copilot/chat/assistantPermissions.ts index d00ac65b8e..e77864045f 100644 --- a/frontend/src/lib/components/copilot/chat/assistantPermissions.ts +++ b/frontend/src/lib/components/copilot/chat/assistantPermissions.ts @@ -1,10 +1,10 @@ -import type { OperatorSettings } from '$lib/gen' -import type { UserExt } from '$lib/stores' +import type { RoleCapabilities } from '$lib/gen' +import type { UserExt, UserWorkspace } from '$lib/stores' import { roleCanAuthor, type EditKind } from '$lib/editRights' import { capabilitiesForRole } from './global/sessionAccess' import type { SessionAccess } from './sessionCapabilities' -/** Where a workspace admin changes what operators may do. Named in the prompt and the +/** Where a workspace admin changes what a role may do. Named in the prompt and the * permissions section alike, so the two send the user to the same place. */ export const OPERATOR_SETTINGS_LOCATION = 'Workspace settings → Users → Operator settings' @@ -25,35 +25,35 @@ const ROWS: PermissionRow[] = [ { kind: 'variable', label: 'Variables', assistant: (a) => a.has('write_variable_draft') } ] -export type RoleName = 'admin' | 'developer' | 'operator' - +/** `admin`, or the member's workspace role. A server that predates roles names none, and its + * role is then `operator` or `developer` from the legacy flag. */ export function roleName( - user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'> -): RoleName { + user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'>, + workspace: Pick<UserWorkspace, 'role'> | undefined +): string { if (user.is_admin || user.is_super_admin) return 'admin' - return user.operator ? 'operator' : 'developer' + return workspace?.role ?? (user.operator ? 'operator' : 'developer') } /** * Per item kind, whether the user's role lets them create and edit it themselves, and whether * the chat can for them. Both act with the user's rights, but the user's column follows the * item handlers (`roleCanAuthor`) and the chat's the draft endpoint every write tool goes - * through (`capabilitiesForRole`), which refuses operators more than the handlers do. + * through (`capabilitiesForRole`), which refuses a restricted role more than the handlers do. */ export function permissionRows( - user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'>, - operatorSettings: OperatorSettings | null | undefined + user: Pick<UserExt, 'is_admin' | 'is_super_admin'>, + caps: RoleCapabilities ): { label: string; user: boolean; assistant: boolean }[] { const access = capabilitiesForRole({ isAdmin: !!user.is_admin || !!user.is_super_admin, - operator: !!user.operator, // Deploy rules gate deploying, not the drafts these rows are about. deployRulesPass: true, - operatorSettings + capabilities: caps }) return ROWS.map((row) => ({ label: row.label, - user: roleCanAuthor(row.kind, user, operatorSettings), + user: roleCanAuthor(row.kind, caps), assistant: row.assistant(access) })) } diff --git a/frontend/src/lib/components/copilot/chat/autonomyModes.ts b/frontend/src/lib/components/copilot/chat/autonomyModes.ts new file mode 100644 index 0000000000..b514635911 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/autonomyModes.ts @@ -0,0 +1,118 @@ +import { ChevronsRight, ClipboardList, Hammer, Hand, Play } from 'lucide-svelte' +import { AIAutonomyMode } from './AIChatManager.svelte' +import { PLAN_MODE_TEXT_COLOR, PLAN_MODE_TRIGGER_CLASS } from './planMode' +import { AIWorkMode } from './workMode' + +export type AutonomyAvailability = { + autoAcceptEditsAvailable: boolean + autoAcceptToolConfirmationsAvailable: boolean +} + +export type AutonomyModeOption = { + mode: AIAutonomyMode + label: string + shortLabel?: string + icon: typeof Hand + iconColor: string + tooltip: (a: AutonomyAvailability) => string + isAvailable: (a: AutonomyAvailability) => boolean +} + +// The one posture available everywhere, so also the fallback for a mode the +// current AI mode does not offer. +const askPermissionOption: AutonomyModeOption = { + mode: AIAutonomyMode.DEFAULT, + label: 'Ask permission', + icon: Hand, + iconColor: 'text-secondary', + tooltip: (a) => + a.autoAcceptEditsAvailable + ? 'Requires confirmation for edits and tool calls.' + : 'Requires confirmation for tool calls.', + isAvailable: () => true +} + +// One row per autonomy posture, in picker order, so adding one touches only this +// table. `isAvailable` hides the postures that would do nothing in the current AI +// mode, which is why the picker can be shorter than this list. +const autonomyModeOptions: AutonomyModeOption[] = [ + askPermissionOption, + { + mode: AIAutonomyMode.ACCEPT_EDIT, + label: 'Auto-accept edits', + icon: ChevronsRight, + iconColor: 'text-accent', + tooltip: () => + 'Automatically accepts script and flow edits. Tool calls still ask for confirmation.', + isAvailable: (a) => a.autoAcceptEditsAvailable + }, + { + mode: AIAutonomyMode.YOLO, + label: 'Yolo (bypass permissions)', + shortLabel: 'Yolo', + icon: ChevronsRight, + iconColor: 'text-red-500', + tooltip: (a) => + a.autoAcceptEditsAvailable + ? 'Automatically accepts script and flow edits plus tool confirmations.' + : 'Automatically accepts tool confirmations.', + isAvailable: (a) => a.autoAcceptToolConfirmationsAvailable + } +] + +export function autonomyModeOption(mode: AIAutonomyMode): AutonomyModeOption { + return autonomyModeOptions.find((o) => o.mode === mode) ?? askPermissionOption +} + +export function availableAutonomyModeOptions(a: AutonomyAvailability): AutonomyModeOption[] { + return autonomyModeOptions.filter((option) => option.isAvailable(a)) +} + +/** Falls back to ask-permission when `mode` isn't applicable in the current AI mode + * (e.g. auto-accept edits while in a mode without edits). */ +export function resolveAutonomyMode(mode: AIAutonomyMode, a: AutonomyAvailability) { + return availableAutonomyModeOptions(a).some((option) => option.mode === mode) + ? mode + : AIAutonomyMode.DEFAULT +} + +export type WorkModeOption = { + mode: AIWorkMode + label: string + description: string + icon: typeof Hand + iconColor: string + /** Tints the whole trigger, not just its icon. Only plan mode needs it. */ + triggerClass?: string +} + +/** A session chat's first section, above the postures: what the chat may do. */ +export const workModeOptions: WorkModeOption[] = [ + { + mode: AIWorkMode.USE, + label: 'Use', + description: 'Reads and runs. No changes.', + icon: Play, + iconColor: 'text-secondary' + }, + { + mode: AIWorkMode.PLAN, + label: 'Plan', + description: 'Proposes a plan first.', + icon: ClipboardList, + iconColor: PLAN_MODE_TEXT_COLOR, + triggerClass: PLAN_MODE_TRIGGER_CLASS + }, + { + mode: AIWorkMode.BUILD, + // Named for both halves: building does not take away running what is deployed. + label: 'Use & build', + description: 'Edits, tests and deploys.', + icon: Hammer, + iconColor: 'text-secondary' + } +] + +export function workModeOption(mode: AIWorkMode): WorkModeOption { + return workModeOptions.find((o) => o.mode === mode) ?? workModeOptions[2] +} diff --git a/frontend/src/lib/components/copilot/chat/chatLoop.ts b/frontend/src/lib/components/copilot/chat/chatLoop.ts index 343dd268e7..09232debbb 100644 --- a/frontend/src/lib/components/copilot/chat/chatLoop.ts +++ b/frontend/src/lib/components/copilot/chat/chatLoop.ts @@ -73,8 +73,13 @@ export interface ChatLoopConfig { * lets the caller recover partial output if the loop throws or is aborted. */ addedMessages?: ChatCompletionMessageParam[] - /** Called before each iteration (e.g. to record which model it is about to use). */ - onBeforeIteration?: (modelProvider: ReasoningProviderModel) => Promise<void> + /** Called before each iteration (e.g. to record which model it is about to use), with + * the last usage report that carried a prompt count, which can predate the latest + * iteration. It may rewrite `messages` in place. */ + onBeforeIteration?: ( + modelProvider: ReasoningProviderModel, + lastIterationUsage: ChatTokenUsage | null + ) => Promise<void> /** Fired for each completed provider response, before the loop continues. The * loop can fail or be aborted at any iteration, so spend has to be handed over * as it happens — a callback only at the end would discard everything the @@ -420,7 +425,7 @@ export async function runChatLoop(config: ChatLoopConfig): Promise<ChatLoopResul const webSearch = sendsWebSearch(workspace, modelProvider, config.webSearch ?? true) if (onBeforeIteration) { - await onBeforeIteration(modelProvider) + await onBeforeIteration(modelProvider, lastIterationUsage) } const tools = await Promise.all( config.tools.map(async (t) => (t.schemaFor ? { ...t, def: await t.schemaFor(helpers) } : t)) diff --git a/frontend/src/lib/components/copilot/chat/chatViewHost.ts b/frontend/src/lib/components/copilot/chat/chatViewHost.ts index 197b831e7e..5e94f39311 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -1,5 +1,6 @@ import { getContext, setContext } from 'svelte' import type { AIMode, AIAutonomyMode } from './AIChatManager.svelte' +import type { AIWorkMode } from './workMode' import { getAiChatManager } from './aiChatManagerContext' import type { DisplayMessage, Tool } from './shared' import type { ContextElement } from './context' @@ -72,7 +73,11 @@ export interface ChatViewHost { /** Resolves to whether the draft was consumed as a turn. */ sendRequest: (options?: ChatSendRequestOptions) => Promise<boolean | undefined> cancel: (reason?: string) => void - setAiChatInput: (aiChatInput: AIChatInput | null) => void + setAiChatInput: (aiChatInput: AIChatInput) => void + /** Unregisters `aiChatInput` if it is still the registered one. A host's chat can remount + * elsewhere (Home hands its session to /sessions), and the new composer may register before + * the old one's teardown runs. */ + releaseAiChatInput: (aiChatInput: AIChatInput) => void readonly queuedMessage: string queuedContext: ContextElement[] | undefined readonly queuedImages: AttachedImage[] @@ -156,6 +161,10 @@ export interface ChatViewHost { readonly tools: readonly Tool<any>[] autonomyMode: AIAutonomyMode setAutonomyMode: (mode: AIAutonomyMode) => void + /** Use, Plan or Build: offered by a session chat only. */ + readonly workModesAvailable: boolean + workMode: AIWorkMode + setWorkMode: (mode: AIWorkMode) => void readonly autoAcceptEditsActive: boolean readonly autoAcceptEditsAvailable: boolean readonly autoAcceptToolConfirmationsAvailable: boolean diff --git a/frontend/src/lib/components/copilot/chat/composerBox.ts b/frontend/src/lib/components/copilot/chat/composerBox.ts index f85783d988..3326e58274 100644 --- a/frontend/src/lib/components/copilot/chat/composerBox.ts +++ b/frontend/src/lib/components/copilot/chat/composerBox.ts @@ -22,6 +22,60 @@ export function composerBoxClass(disabled: boolean = false): string { }` } +/** Added to a usable box that opens a session (Home, an empty session). Focus shows as the + * base box's border colour alone: the brand has no focus ring. */ +export const HERO_BOX_CLASS = 'rounded-[10px]' + /** Applied to the field inside the box; without it the field draws a second border. */ export const COMPOSER_FIELD_RESET = '!border-transparent !bg-transparent !shadow-none focus:!border-transparent focus:!ring-0 disabled:cursor-not-allowed disabled:placeholder:text-disabled' + +/** The placeholder of a composer that opens a session. */ +export const STARTER_PLACEHOLDER = 'Ask about this workspace, or describe what to build…' + +/** The same, for a session held in Use, which builds nothing. */ +export const USE_STARTER_PLACEHOLDER = 'Ask about this workspace, or run what it holds…' + +/** A caret or selected range in the composer's text. */ +export type ComposerSelection = { start: number; end: number } + +const GLOBAL_PLACEHOLDER_SUGGESTIONS = [ + 'Write a hello-world flow', + 'Create a script that lists files in an S3 bucket', + 'Build a CRUD app for a customer table', + 'Schedule a daily cleanup of old runs', + 'Wrap an existing script into a flow with retries', + 'Add an HTTP trigger to an existing script', + 'Generate a report from a SQL query and email it', + 'Create a Postgres resource and a script that queries it', + 'Refactor a script to add error handling', + 'List my workspace flows and scripts' +] +// An operator authors nothing, so nothing above is theirs to ask for; one with the +// workspace's builder right can compose flows out of deployed scripts as well. +const OPERATOR_PLACEHOLDER_SUGGESTIONS = [ + 'List my workspace flows and scripts', + 'Show the runs that failed today and why', + 'Find the script that sends a report and run it', + 'Rerun the last failed run of a flow' +] +const BUILDER_PLACEHOLDER_SUGGESTIONS = [ + ...OPERATOR_PLACEHOLDER_SUGGESTIONS, + 'Compose a flow that chains two deployed scripts' +] + +/** + * The global-mode composer's placeholder: one suggestion the user may ask for. `pick` is a + * number in [0, 1) the caller draws once, so the text does not shuffle while it is read. + */ +export function globalComposerSuggestion( + pick: number, + canOpenEditor: (kind: string) => boolean +): string { + const pool = canOpenEditor('script') + ? GLOBAL_PLACEHOLDER_SUGGESTIONS + : canOpenEditor('flow') + ? BUILDER_PLACEHOLDER_SUGGESTIONS + : OPERATOR_PLACEHOLDER_SUGGESTIONS + return pool[Math.floor(pick * pool.length)] +} diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index 546459cee2..17cd4c8960 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -1370,6 +1370,40 @@ describe('global AI tools', () => { expect(localStorageSnapshot()).not.toContain('new-secret-token') }) + // The draft has no null, so a cleared expiry must deploy as an explicit one. + it('clears a variable value expiry through to the deploy body', async () => { + vi.mocked(VariableService.existsVariable).mockResolvedValueOnce(true) // write probe + vi.mocked(VariableService.existsVariable).mockResolvedValueOnce(true) // deploy probe + vi.mocked(VariableService.getVariable).mockResolvedValueOnce({ + path: 'f/secrets/api_key', + value: 'tok', + is_secret: false, + description: 'd', + value_valid_until: '2027-03-15T08:30:00Z' + } as any) + + await callGlobalTool('write_variable', { + path: 'f/secrets/api_key', + value_valid_until: null + }) + + expect( + getBackendDraft<any>('variable', 'f/secrets/api_key', { workspace: WORKSPACE }) + ?.value_valid_until + ).toBeUndefined() + + await callGlobalTool('deploy_workspace_item', { + type: 'variable', + path: 'f/secrets/api_key' + }) + + expect(VariableService.updateVariable).toHaveBeenCalledWith( + expect.objectContaining({ + requestBody: expect.objectContaining({ value_valid_until: null }) + }) + ) + }) + // '' means "no value staged", so there is nothing to create the secret with. it('does not create a secret variable draft that stages no value', async () => { seedBackendDraft( @@ -2548,6 +2582,38 @@ describe('global AI tools', () => { expect(asPath.inlineScript).toBeUndefined() }) + // A static input is pinned by the deployed policy: carried into an agent runnable, it would + // replace every viewer's message. + it('drops inherited static inputs when a runnable becomes an agent', async () => { + seedBackendDraft( + 'raw_app', + 'u/admin/agent_conv_app', + { summary: 'Converted', files: {}, runnables: {}, data: { tables: [] } }, + { workspace: WORKSPACE } + ) + await callGlobalTool('write_app_runnable', { + path: 'u/admin/agent_conv_app', + key: 'chat', + runnable: { + name: 'Run the flow', + type: 'flow', + path: 'u/admin/hello_flow', + staticInputs: { user_message: 'pinned' } + } + }) + await callGlobalTool('write_app_runnable', { + path: 'u/admin/agent_conv_app', + key: 'chat', + runnable: { name: 'Chat', type: 'agent', path: 'u/admin/assistant' } + }) + + const asAgent = getBackendDraft<any>('raw_app', 'u/admin/agent_conv_app', { + workspace: WORKSPACE + }).runnables.chat + expect(asAgent.runType).toBe('agent') + expect(asAgent.fields).toEqual({}) + }) + it("resets a path runnable's schema when it is retargeted, and keeps it when it is not", async () => { // The editor populates `schema` from the item the runnable points at, and // genWmillTs types `backend.<key>(args)` from it — so it must not outlive the target. diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 3414ef6185..c93c83eae4 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -73,13 +73,16 @@ import { import { processSecretArgs } from '$lib/components/secretArgUtils' import { parsePipelineAnnotations } from '$lib/components/assets/AssetGraph/parsePipelineAnnotations' import { PLAN_MODE_MESSAGES } from '../planModeMessages' +import { USE_MODE_WITHDRAWN } from '../workMode' import { DEFAULT_DATA as DEFAULT_RAW_APP_DATA, formatDataTableRef } from '$lib/components/raw_apps/dataTableRefUtils' import { appSourceToDraftValue } from '$lib/components/raw_apps/rawAppDraftValue' import { conformBuilderAppPolicy } from '$lib/components/raw_apps/builderAppPolicy' -import { operatorBuilderAppsIn } from '$lib/operatorWriteRights' +import { capabilitiesInWorkspace } from '$lib/operatorWriteRights' +import { capabilitiesIn, withoutBuilding } from '$lib/roleCapabilities' +import type { RoleCapabilities } from '$lib/gen' import type { RawAppDomQuery } from '$lib/components/raw_apps/rawAppDom' import { dataUrlToImagePart, normalizeImageDataUrl, type AttachedImage } from '../imageUtils' import { sanitizeAttachmentName, textLineCount, type AttachedTextFile } from '../textFileUtils' @@ -178,7 +181,7 @@ import { fileTools } from '../files/fileTools' import type { AttachedFilesStore } from '../files/attachedFiles.svelte' import { artifactTools } from '../artifacts/artifactTools' import type { SessionArtifactsStore } from '../artifacts/artifactsState.svelte' -import type { Runnable } from '$lib/components/apps/inputType' +import type { PathRunType, Runnable } from '$lib/components/apps/inputType' import { UserDraft } from '$lib/userDraft.svelte' import { emptySchema } from '$lib/utils' import type { Schema } from '$lib/common' @@ -229,6 +232,7 @@ import type { UserDraftItemKind } from '$lib/gen' import { bundleRawAppDraft } from './rawAppBundlerBridge' import { canOpenEditor, + isReadOnlyAccess, DEPLOY, NONE, RUN_FLOW_PREVIEW, @@ -327,7 +331,10 @@ const INSTRUCTION_SUBJECTS = [ // annotated scripts in a folder, so it gets authoring guidance, not a CRUD type. // `workspace_settings` is the settings document an admin reads and changes. const INSTRUCTION_SUBJECTS_EXTRA = ['datatable', 'pipeline', 'workspace_settings'] as const -const ALL_INSTRUCTION_SUBJECTS = [...INSTRUCTION_SUBJECTS, ...INSTRUCTION_SUBJECTS_EXTRA] as const +export const ALL_INSTRUCTION_SUBJECTS = [ + ...INSTRUCTION_SUBJECTS, + ...INSTRUCTION_SUBJECTS_EXTRA +] as const const MAX_LIST_LIMIT = 100 type ActiveGlobalEditorType = Extract<WorkspaceItemType, 'script' | 'flow' | 'app'> type LiveEditorDraftKind = Parameters<typeof UserDraft.getLiveEditorDraft>[0] @@ -740,6 +747,15 @@ const writeVariableSchema = variableRequestSchema.extend({ .string() .optional() .describe('The description of the variable. Omit it to keep the current description.'), + // Nullable, unlike the generated schema, so a cleared expiry differs from an omitted one. + value_valid_until: z + .string() + .datetime({ offset: true }) + .nullable() + .optional() + .describe( + "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it (1 day by default, set on the handler); never causes the variable to be deleted. Omit it to keep the current expiry, or pass null to clear one — for instance once the value has been rotated." + ), override: draftOverrideField }) @@ -1071,9 +1087,9 @@ const backendRunnableSchema = z .object({ name: z.string().describe('Short summary/description of what the runnable does.'), type: z - .enum(['inline', 'script', 'flow', 'hubscript']) + .enum(['inline', 'script', 'flow', 'hubscript', 'agent']) .describe( - 'Runnable kind: "inline" for custom code stored on the app; "script"/"flow" for a workspace runnable; "hubscript" for a hub script.' + 'Runnable kind: "inline" for custom code stored on the app; "script"/"flow" for a workspace runnable; "hubscript" for a hub script; "agent" for a saved AI agent, run as one chat turn.' ), staticInputs: z .record(z.string(), z.any()) @@ -1092,7 +1108,7 @@ const backendRunnableSchema = z .string() .optional() .describe( - 'Required when type is "script", "flow", or "hubscript". Workspace path of the runnable.' + 'Required when type is "script", "flow", "hubscript" or "agent". Workspace path of the runnable.' ), viewerDataAccess: z .boolean() @@ -1426,7 +1442,8 @@ type FolderPromptContext = { function buildFolderGuidance( username: string, ctx: FolderPromptContext | undefined, - canCreateFolder: boolean + canCreateFolder: boolean, + external = false ): string { if (!ctx) return '' const MAX = 40 @@ -1454,7 +1471,7 @@ function buildFolderGuidance( const lines: string[] = [] if (writable.length > 0) { lines.push( - `- Folders you can write to in this workspace: ${fmt(writable)}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use (askUserQuestion) rather than inventing a path.${canCreateFolder ? ' Use `create_folder` only when the user explicitly asks for a new folder.' : ''}` + `- Folders you can write to in this workspace: ${fmt(writable)}. For shared/team work, pick the one whose purpose matches the request; if none clearly fits, ask which folder to use${external ? '' : ' (askUserQuestion)'} rather than inventing a path.${canCreateFolder ? ' Use `create_folder` only when the user explicitly asks for a new folder.' : ''}` ) } else { lines.push( @@ -1482,7 +1499,10 @@ const buildGlobalSystemPrompt = ( folderCtx?: FolderPromptContext, skills: AiSkillListItem[] = [], mcpServers: McpServer[] = [], - access?: SessionAccess + access?: SessionAccess, + // The prompt as an external MCP client reads it: the same rules, minus the tools and + // surfaces only the Windmill UI has (pages, the run form, questions, the open editor). + external = false ) => { // Each `can*` mirrors the capability the matching tools declare in `requires`, so a // rule cannot outlive the tool it describes. An unresolved profile keeps every block. @@ -1493,11 +1513,13 @@ const buildGlobalSystemPrompt = ( const canDraftTriggers = !access || access.has('write_trigger_draft') const canDraftResources = !access || access.has('write_resource_draft') const canDraftVariables = !access || access.has('write_variable_draft') - // A builder operator: drafts of the kinds the workspace lets them compose, and nothing else. + const inlineFlowCode = !access || access.has('write_inline_flow_code') + const inlineAppCode = !access || access.has('write_inline_app_code') + // A role that composes a kind out of deployed runnables, with no inline code of its own. // Blocks about drafting in general follow `canWriteAnyDraft`; blocks naming scripts or the // other kinds keep `canWriteDraft`. - const buildsFlows = canWriteFlowDraft && !canWriteDraft - const buildsApps = canWriteAppDraft && !canWriteDraft + const buildsFlows = canWriteFlowDraft && !inlineFlowCode + const buildsApps = canWriteAppDraft && !inlineAppCode const canWriteAnyDraft = canWriteDraft || canWriteFlowDraft || @@ -1507,6 +1529,9 @@ const buildGlobalSystemPrompt = ( canDraftResources || canDraftVariables const canDeploy = !access || access.has('deploy') + // Holds none of the capabilities below, so every `can*` reads false; the blocks that blame + // the user's role for that check this first. + const readOnly = isReadOnlyAccess(access) // Whether deploy_workspace_item and delete_workspace_item keep any kind: only schedules and // triggers skip the deploy rules, and an admin passes them. const canDeployAnyKind = @@ -1537,6 +1562,11 @@ const buildGlobalSystemPrompt = ( (k): k is string => !!k ) const canRunPreview = !access || access.has('run_preview') + const canRunFlowPreview = !access || access.has('run_flow_preview') + // A role may code without composing flows, so the flow test tool is named only where it ships. + const testRunTools = canRunFlowPreview + ? 'test_run_script, test_run_flow, or test_run_step' + : 'test_run_script or test_run_step' const canManageSchedules = !access || access.has('manage_schedules') const canManageTriggers = !access || access.has('manage_triggers') // The deploy tools take their kind as an argument, so `deploy` gates only the folder and @@ -1546,7 +1576,7 @@ const buildGlobalSystemPrompt = ( // Each gated block carries its own leading newline, so dropping one leaves no blank // line behind and a full-access prompt is byte-for-byte the ungated text. const when = (cond: boolean, block: string) => (cond ? block : '') - const folderGuidance = buildFolderGuidance(username, folderCtx, canCreateFolder) + const folderGuidance = buildFolderGuidance(username, folderCtx, canCreateFolder, external) const folderGuidanceBlock = folderGuidance ? `\n${folderGuidance}` : '' // A grant to `g/<group>` reaches the user only through membership, which no permission // list shows. Outside the folder guidance, which a role that cannot draft never gets. @@ -1590,40 +1620,80 @@ const buildGlobalSystemPrompt = ( get(enterpriseLicense) ? 'Enterprise Edition' : 'Community Edition' }. Use that to judge whether a feature is available before promising it.` : '' + // The core rules, placed differently for an MCP client (see `coreRules`). + const draftsOnlyRule = when( + canWriteAnyDraft, + ` +- Draft tools create or update drafts only; they do not deploy or mutate deployed workspace items.` + ) + const findItemsRule = + '- Use list_workspace_items to find items and read_workspace_item before changing an existing item. For triggers, pass trigger_kind.' + const deployRule = when( + canWriteAnyDraft && canDeployAnyKind, + ` +- Use deploy_workspace_item only after the user explicitly asks to deploy. It persists a draft to the workspace.` + ) + const instructionsRule = + '- Use get_instructions before writing scripts, flows, resources, or apps. For scripts, pass the target language.' + const testDraftRule = `- After creating or editing a script${canWriteFlowDraft ? ' or flow' : ''} draft, run ${testRunTools} with representative args before reporting that it works. These tools prefer drafts, so testing does not require deployment.` + const testRunList = canRunFlowPreview + ? 'test_run_script, test_run_flow, test_run_step' + : 'test_run_script, test_run_step' + const runRule = `${when( + canRunPreview, + ` +- Default to ${testRunTools} for any run request, an existing script included; they prefer drafts and need no deployment. Use run_script or run_flow only when the user names the deployed version ("the deployed X", "in production", "for real") — a bare "run X" is not that. For those two, read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema. ${ + external + ? `${testRunList}, run_script and run_flow run with exactly the arguments you send, so fill in every argument the schema asks for. test_run_step takes the step's own inputs, not the flow's.` + : `${testRunList}, run_script and run_flow all show the user an argument form prefilled with what you sent, so fill in every argument you can infer rather than asking for it in chat. test_run_step's form is the step's own inputs, not the flow's.` + }` + )}${when( + !canRunPreview, + ` +- run_script and run_flow are how you run anything here: they run the DEPLOYED item under this user's own permissions, and show them an argument form prefilled with what you sent. Read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema, and fill in every argument you can infer rather than asking for it in chat.` + )}` - return `You are Windmill's global workspace assistant. + const intro = `${external ? 'You are working in a Windmill workspace through its MCP server.' : "You are Windmill's global workspace assistant."}${when( + external, + ` + +The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a script, flow or agent draft's url (its editor), an app draft's preview_url (the app editor with its live preview, which these instructions call "the preview"), a deployed item's url. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves, open the link in a browser they can see from this conversation if you have one, and otherwise give them the link to open.` + )} The current user's workspace username is "${username}".${instanceLine} ${ canWriteDraft ? 'Use tools to inspect workspace items and create per-user drafts (saved server-side, visible only to this user — not deployed) for scripts, flows, schedules, triggers, resources, variables, and raw apps.' - : `Use tools to inspect workspace items and the workspace's run history, and to run items that are already deployed. You cannot create or edit ${listJoin(refusedKinds, 'disjunction')} here — this user's role does not allow it — so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had. Their role is refused ${listJoin(refusedCode)} outside this chat too, so for those suggest asking a workspace admin, who grants operators more in ${OPERATOR_SETTINGS_LOCATION}, rather than creating them in the editor.${when( - canManageSchedules, - ' To make something recur, they can schedule a deployed script or flow themselves; only when none does the job is there something to ask an admin for, and it is that script.' - )} When you decline something, give the reason stated here and keep to it.${when( - buildsFlows, - '\n\nFlows are the exception: this workspace lets them compose flows out of scripts and flows that are already deployed. Write flow drafts with write_flow and patch_flow_json, using only steps that call a deployed script or flow by path. The server refuses inline code anywhere in the flow, so never add a rawscript step or inline code; when the flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.' - )}${when( - buildsApps, - `\n\nRaw apps are ${buildsFlows ? 'an exception too' : 'the exception'}: this workspace lets them build raw apps whose backend calls scripts and flows that are already deployed. Call get_instructions with subject "app" first, then write app drafts with init_app and the app file and runnable tools, making every backend runnable a path runnable to a deployed script or flow. The server refuses inline and hub runnables, so never write one; when the app needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An app this user deploys always runs sandboxed, and runs its runnables as the user who deployed it: turning the sandbox off or running them as the viewer is refused. If asked, say operators cannot, because the app's code would then run with the permissions of whoever opens it.` - )}${when( - !!draftedOperatorKinds, - `\n\nThis workspace lets them create and edit ${draftedOperatorKinds}: write them as drafts with ${listJoin( - [ - canDraftResources && 'write_resource (call search_resource_types first)', - canDraftVariables && 'write_variable', - canDraftSchedules && 'write_schedule', - canDraftTriggers && - 'write_trigger (call get_trigger_schema first: the config fields differ per kind)' - ] - )}${ - deployableKinds.length - ? `, then deploy ${deployableKinds.length === draftedKinds.length ? 'them' : listJoin(deployableKinds)} with deploy_workspace_item once the user asks` - : '' - }.` - )}` -}${when( + : readOnly + ? "Use tools to inspect workspace items, the workspace's run history and its data, and to run items that are already deployed. This session is read-only: you cannot create, edit, deploy or delete anything here, nor test-run code that is not deployed. When the user asks for such a change, say plainly that it cannot be made in this session, and tell them how to make it as the session context below says, rather than describing steps as if you had made it." + : `Use tools to inspect workspace items and the workspace's run history, and to run items that are already deployed. You cannot create or edit ${listJoin(refusedKinds, 'disjunction')} here — this user's role does not allow it — so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had. Their role is refused ${listJoin(refusedCode)} outside this chat too, so for those suggest asking a workspace admin, who can grant their role more in ${OPERATOR_SETTINGS_LOCATION}, rather than creating them in the editor.${when( + canManageSchedules, + ' To make something recur, they can schedule a deployed script or flow themselves; only when none does the job is there something to ask an admin for, and it is that script.' + )} When you decline something, give the reason stated here and keep to it.${when( + buildsFlows, + '\n\nFlows are the exception: this workspace lets them compose flows out of scripts and flows that are already deployed. Write flow drafts with write_flow and patch_flow_json, using only steps that call a deployed script or flow by path. The server refuses inline code anywhere in the flow, so never add a rawscript step or inline code; when the flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An AI agent step may link a saved agent they can read, which runs its tools as the agent defines them. Its `tool_inputs` may only fill tool inputs the agent leaves for the AI to fill: the server refuses a step that changes an input the agent sets.' + )}${when( + buildsApps, + `\n\nRaw apps are ${buildsFlows ? 'an exception too' : 'the exception'}: this workspace lets them build raw apps whose backend calls scripts and flows that are already deployed. Call get_instructions with subject "app" first, then write app drafts with init_app and the app file and runnable tools, making every backend runnable a path runnable to a deployed script or flow. The server refuses inline and hub runnables, so never write one; when the app needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An app this user deploys always runs sandboxed, and runs its runnables as the user who deployed it: turning the sandbox off or running them as the viewer is refused. If asked, say operators cannot, because the app's code would then run with the permissions of whoever opens it.` + )}${when( + !!draftedOperatorKinds, + `\n\nThis workspace lets them create and edit ${draftedOperatorKinds}: write them as drafts with ${listJoin( + [ + canDraftResources && 'write_resource (call search_resource_types first)', + canDraftVariables && 'write_variable', + canDraftSchedules && 'write_schedule', + canDraftTriggers && + 'write_trigger (call get_trigger_schema first: the config fields differ per kind)' + ] + )}${ + deployableKinds.length + ? `, then deploy ${deployableKinds.length === draftedKinds.length ? 'them' : listJoin(deployableKinds)} with deploy_workspace_item once the user asks` + : '' + }.` + )}` +}` + const paths = `${when( canWriteAnyDraft, ` @@ -1639,24 +1709,31 @@ Path conventions: )}${when( canCreateFolder && !canWriteAnyDraft, '\n- You can create a shared folder with `create_folder` when the user explicitly asks for one. You cannot create anything inside it here, so do not offer to.' - )} + )}` + // An MCP client may keep only the first 4096 characters of its instructions, so there + // these rules come before the path conventions and are left out of the later list. + const coreRules = `${draftsOnlyRule} +${findItemsRule}${deployRule}${when(canWriteDraft, `\n${instructionsRule}`)}${when( + canRunPreview && canWriteDraft, + `\n${testDraftRule}` + )}${runRule}` -Rules:${when( - canWriteAnyDraft, - ` -- Draft tools create or update drafts only; they do not deploy or mutate deployed workspace items.` - )} -- Use list_workspace_items to find items and read_workspace_item before changing an existing item. For triggers, pass trigger_kind. + return `${intro}${when(external, `\n\nRules:${coreRules}`)}${paths} + +${external ? 'More rules:' : `Rules:${draftsOnlyRule}\n${findItemsRule}`} ${groupMembershipRule}- Listings and reads return only what this user can see: items in folders they cannot read are hidden from you both. When an item the user names is missing, say it is not among what they can see and may be in a folder they cannot read, where someone with access can run it — never state that it does not exist or is not deployed. - An agent, as the Agents page lists it, is a resource of type \`ai_agent\`: read it with read_workspace_item type "resource".${when( - canDraftResources, + // An agent draft is a resource draft that the server checks under the flow builder right. + canDraftResources && canWriteFlowDraft, " You may draft a change to an agent, but never deploy or rename one here: the user reviews and deploys it from the agent's page, `/agents/edit/<path>`, so point them there." - )} -- If the user message includes an ACTIVE EDITOR section, treat it as the currently open item and use it for references like "this", "current", or "open editor".${activePreviewRule}${when( - canWriteAnyDraft && canDeployAnyKind, - ` -- Use deploy_workspace_item only after the user explicitly asks to deploy. It persists a draft to the workspace.` )}${when( + buildsFlows, + ' Its tools, like flow steps, may only reference deployed scripts and flows by path: the server refuses inline code and hub scripts.' + )}${when( + !external, + ` +- If the user message includes an ACTIVE EDITOR section, treat it as the currently open item and use it for references like "this", "current", or "open editor".` + )}${activePreviewRule}${when(!external, deployRule)}${when( canWriteAnyDraft, ` - To undo something you created or changed in this chat, use discard_local_draft: everything you write is a draft until it is explicitly deployed, so "delete it" / "never mind" / "remove that" about your own work means discarding the draft (it also clears the matching open editor draft).${when( @@ -1664,11 +1741,11 @@ ${groupMembershipRule}- Listings and reads return only what this user can see: i ' Use delete_workspace_item only to remove an item that is already deployed in the workspace; it mutates the workspace and fails if nothing is deployed at that path.' )}` )}${when( - !canWriteAnyDraft, + !canWriteAnyDraft && !readOnly, ` - Three changes are still open to you where the server allows them: discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes an item already deployed in the workspace — each only for the kinds its type lists. You cannot create or edit one.` )}${when( - !canManageSchedules || !canManageTriggers, + (!canManageSchedules || !canManageTriggers) && !readOnly, ` - This workspace does not let this user change ${ !canManageSchedules && !canManageTriggers @@ -1685,17 +1762,19 @@ ${groupMembershipRule}- Listings and reads return only what this user can see: i )}${when( canWriteDraft, ` -- Use search_resource_types before write_resource, and get_trigger_schema before write_trigger: the trigger config fields differ per kind and are not listed in the write_trigger definition. +- Use search_resource_types before write_resource${ + canDraftTriggers + ? ', and get_trigger_schema before write_trigger: the trigger config fields differ per kind and are not listed in the write_trigger definition.' + : '.' + } - When script or raw app code needs an external npm package you are not fully familiar with, use search_npm_packages to find it and get its documentation and type definitions. Link the package documentation in your answer when you rely on it. - Hub scripts are prebuilt, vetted integrations for third-party services, hosted outside the workspace under \`hub/<version>/<app>/<name>\` paths. Check search_hub_scripts before hand-writing code against a third-party API, even when the user never mentions the hub; read a result with read_workspace_item type "script" and its hub path to get its code, language, and input schema. Use what you find in whichever way fits: reference the hub path directly from a flow module or app runnable when a script already does the job, copy it into a workspace draft and adapt it when it is close (note the source hub path in a comment at the top of the code), or take it as a worked example and write your own. A script that does not do what the user asked is still worth reading when it is the only example of that integration: pass its \`integration\` back to search_hub_scripts to list that integration's other scripts with their descriptions, or use the \`suggested_integrations\` a search hands back when it finds nothing. - Before writing your own code against an integration the hub covers, call get_hub_integration with its slug: it returns the resource type to take, its auth fields and the integration's most-used scripts, which beats inferring them from script bodies. Call it for the integration you are about to write against, whichever it is. A search marks an integration \`documented\` when the hub additionally holds provider knowledge checked against the live API — pagination, enums, error codes and gotchas — so read that closely where it appears rather than trusting your own memory of the API. - If you have a web search tool and the hub does not cover a third-party API, search for the vendor's own API documentation rather than writing its endpoints and auth from memory, and link the page you relied on. Reserve it for external APIs: search_docs answers questions about Windmill itself. -${when(canCreateResourceType, '- create_resource_type creates a resource type the workspace lacks. The user confirms the schema in the call itself, so that is where you propose it rather than asking first in chat.\n')}${when(!canCreateResourceType, '- This user cannot create a resource type here, in chat or on the Resources page, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin, who can add it.\n')}${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}- Use get_instructions before writing scripts, flows, resources, or apps. For scripts, pass the target language. -${pipelineBullet}` +${when(canCreateResourceType, `- create_resource_type creates a resource type the workspace lacks. ${external ? 'Show the user the schema you propose and create it once they agree.' : 'The user confirms the schema in the call itself, so that is where you propose it rather than asking first in chat.'}\n`)}${when(!canCreateResourceType, '- This user cannot create a resource type here, in chat or on the Resources page, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin, who can add it.\n')}${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}${when(!external, `${instructionsRule}\n`)}${pipelineBullet}` )}${when( canRunPreview && canWriteDraft, - ` -- After creating or editing a script or flow draft, run test_run_script, test_run_flow, or test_run_step with representative args before reporting that it works. These tools prefer drafts, so testing does not require deployment. + `${when(!external, `\n${testDraftRule}`)} - Do the same for a raw app: run test_run_app_runnable on each backend runnable you wrote or changed before saying the app works. A bundle that compiles proves nothing about whether the runnables run. An inline runnable executes the app's draft code; a path runnable executes the DEPLOYED script/flow it names, so a path runnable aimed at something you have not deployed fails here — that failure is the point: report it and offer to deploy that one target. The app itself does not need deploying to be tested.` )}${when( buildsFlows && (!access || access.has('run_flow_preview')), @@ -1703,23 +1782,21 @@ ${pipelineBullet}` - After creating or editing a flow draft, run test_run_flow with representative args before reporting that it works. It prefers drafts, so testing does not require deployment.` )} - Use list_runs to find recent runs (optionally filtered by path, creator, label, or status), then get_run with a returned id to see what that run was called with, what it returned and what it logged — without starting a new test run. -- get_run also covers what a flow run did per step — statuses and results across the whole execution tree, subflow steps and loop iterations included — and works while the flow is still running. Pass step to read one step's result in full (capped at 12k chars). +- get_run also covers what a flow run did per step — statuses and results across the whole execution tree, subflow steps and loop iterations included — and works while the flow is still running. Pass step to read one step's result in full (capped at 12k chars).${when( + !external, + ` - Use open_page to show a workspace page with filters applied — Runs, Schedules, Variables, Resources, Assets, Audit logs, or Workspace settings on a specific tab (e.g. "open the failed runs of f/foo/bar", "open the schedule for X", "open the git sync settings"). Carry over every filter the user described — Runs takes the page's whole filter set (time window, path, user, folder, label, tag, worker, trigger kind, args/result, ...), so don't drop a criterion just because it wasn't in the request's main clause. Only the pages listed for this user in the tool are available; don't offer pages that aren't listed. Don't use it as a substitute for list_runs when you just need the data yourself. -- Whenever you ask the user to perform a manual step in the UI — fill in a resource's credentials, set a secret variable's value, adjust a schedule or setting — call open_page in the same message, targeted at that item (pass open with its path to land in its editor, or the page's filters otherwise). Never just describe where to click.${when( - canWriteDraft, +- Whenever you ask the user to perform a manual step in the UI — fill in a resource's credentials, set a secret variable's value, adjust a schedule or setting — call open_page in the same message, targeted at that item (pass open with its path to land in its editor, or the page's filters otherwise). Never just describe where to click.` + )}${when( + canWriteDraft && !external, ` - Do not offer or open the Compare & Deploy page for normal draft review. Only use open_page with page "compare" when the user explicitly asks to deploy a forked workspace's changes to its parent workspace.` - )}${when( - canRunPreview, + )}${when(!external, runRule)}${when( + !external, ` -- Default to test_run_script, test_run_flow, or test_run_step for any run request, an existing script included; they prefer drafts and need no deployment. Use run_script or run_flow only when the user names the deployed version ("the deployed X", "in production", "for real") — a bare "run X" is not that. For those two, read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema. test_run_script, test_run_flow, test_run_step, run_script and run_flow all show the user an argument form prefilled with what you sent, so fill in every argument you can infer rather than asking for it in chat. test_run_step's form is the step's own inputs, not the flow's.` - )}${when( - !canRunPreview, - ` -- run_script and run_flow are how you run anything here: they run the DEPLOYED item under this user's own permissions, and show them an argument form prefilled with what you sent. Read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema, and fill in every argument you can infer rather than asking for it in chat.` - )} - When a required decision is ambiguous, use askUserQuestion with two to ten clear proposed answer strings instead of guessing. The user can also type a custom answer when none of the proposed answers fit. Set multiSelect: true only when the answers can genuinely co-apply and the user may pick several (not mutually exclusive). -- When the user asks you to remember a lasting preference, always/never do something, or change/stop a behavior going forward, call update_user_instructions to persist it. It edits only the USER INSTRUCTIONS block (not WORKSPACE INSTRUCTIONS). Keep each instruction concise; do not use it for one-off requests scoped to the current task. +- When the user asks you to remember a lasting preference, always/never do something, or change/stop a behavior going forward, call update_user_instructions to persist it. It edits only the USER INSTRUCTIONS block (not WORKSPACE INSTRUCTIONS). Keep each instruction concise; do not use it for one-off requests scoped to the current task.` + )} - Keep context targeted.${ previewTools ? `${when( @@ -1762,7 +1839,7 @@ Documentation: Flows: - read_workspace_item returns compact flow JSON. Inline script bodies appear as "inline_script.<moduleId>". -- Use read_flow_module_code${when(canWriteDraft, ' and set_flow_module_code')} for inline script bodies.${when( +- Use read_flow_module_code${when(inlineFlowCode && canWriteFlowDraft, ' and set_flow_module_code')} for inline script bodies.${when( canWriteFlowDraft, ` - Use patch_flow_json for structural flow edits and write_flow for full flow rewrites.` @@ -1773,15 +1850,15 @@ Raw apps: - read_workspace_item returns app metadata only. Use read_app_file for file and inline runnable contents.${when( canWriteAppDraft, ` -- A draft app is reachable by nobody; deploying is what exposes its backend runnables. deploy_workspace_item says so when the deploy widens who may open the app: anonymous means anyone with the URL, without logging in; guest means anyone the instance's identity provider authenticates, member of this workspace or not. Relay that in plain words and carry on. This is disclosure, not a gate: do not stop and ask for permission, and do not refuse the deploy. You cannot change who may open an app from chat; it is set on the app's deploy settings. +- A draft app is reachable by nobody; deploying is what exposes its backend runnables. ${canDeployAnyKind ? 'deploy_workspace_item' : 'A deploy'} says so when the deploy widens who may open the app: anonymous means anyone with the URL, without logging in; guest means anyone the instance's identity provider authenticates, member of this workspace or not. Relay that in plain words and carry on. This is disclosure, not a gate: do not stop and ask for permission, and do not refuse the deploy. You cannot change who may open an app from chat; it is set on the app's deploy settings. - Use write_app_file, patch_app_file, and delete_app_file for frontend files. - Use write_app_runnable and delete_app_runnable for backend runnables. - Use init_app for a new app, with framework react19 unless the user named one or points at an app to follow: do not ask about the framework, and write the summary and pick the path (path conventions above) yourself. ${ buildsApps ? 'An app this user builds reads and stores data only through the deployed runnables it calls: do not ask about a data setup or pass init_app a data config.' - : 'When the app has to store data and the user did not say where, settle the data setup with askUserQuestion BEFORE init_app or any SQL (get_instructions subject "app" lists the questions, one askUserQuestion each), then pass the outcome as init_app\'s data.' + : `When the app has to store data and the user did not say where, settle the data setup with ${external ? 'the user' : 'askUserQuestion'} BEFORE init_app or any SQL (get_instructions subject "app" lists the questions${external ? '' : ', one askUserQuestion each'}), then pass the outcome as init_app's data.` } -- Use deploy_workspace_item after explicit user deploy intent; raw app deploy bundles JS/CSS before saving.` +${when(canDeployAnyKind, '- Use deploy_workspace_item after explicit user deploy intent; raw app deploy bundles JS/CSS before saving.')}` )} Data Tables: @@ -1951,7 +2028,7 @@ type BackendRunnableInput = z.infer<typeof backendRunnableSchema> type PersistedRunnable = { name: string type: 'inline' | 'path' | 'runnableByName' | 'runnableByPath' - runType?: 'script' | 'flow' | 'hubscript' + runType?: PathRunType path?: string inlineScript?: { language: string; content: string } fields?: Record<string, any> @@ -1984,6 +2061,7 @@ function convertPersistedToBackendRunnable( } else if (persisted.type === 'path' || persisted.type === 'runnableByPath') { if (persisted.runType === 'flow') out.type = 'flow' else if (persisted.runType === 'hubscript') out.type = 'hubscript' + else if (persisted.runType === 'agent') out.type = 'agent' else out.type = 'script' out.path = persisted.path } @@ -2005,14 +2083,19 @@ function buildPersistedRunnable( input: BackendRunnableInput, existing: PersistedRunnable | undefined ): PersistedRunnable { - const fields = input.staticInputs - ? Object.fromEntries( - Object.entries(input.staticInputs).map(([k, v]) => [ - k, - { type: 'static', value: v, fieldType: 'object' } - ]) - ) - : (existing?.fields ?? {}) + // An agent runnable takes every input from the app: a static one inherited from the kind it was + // converted from would be pinned by the deployed policy over every viewer's message. + const fields = + input.type === 'agent' + ? {} + : input.staticInputs + ? Object.fromEntries( + Object.entries(input.staticInputs).map(([k, v]) => [ + k, + { type: 'static', value: v, fieldType: 'object' } + ]) + ) + : (existing?.fields ?? {}) // Converting between kinds must drop the other kind's fields. Every consumer dispatches on // `type` (isRunnableByName / isRunnableByPath), so a leftover does not change which code @@ -2053,7 +2136,15 @@ function buildPersistedRunnable( } if (!input.path) { - throw new Error('path is required when runnable type is "script", "flow", or "hubscript".') + throw new Error( + 'path is required when runnable type is "script", "flow", "hubscript" or "agent".' + ) + } + // A static input is pinned by the deployed policy: every viewer's turn would send the same one. + if (input.type === 'agent' && Object.keys(input.staticInputs ?? {}).length > 0) { + throw new Error( + 'An "agent" runnable takes no staticInputs: each turn\'s inputs come from the app.' + ) } return { ...carried, @@ -2240,7 +2331,7 @@ async function saveAppDraft( path: string, value: AppDraftValue ): Promise<DraftPersistResult> { - if (operatorBuilderAppsIn(workspace)) { + if (capabilitiesInWorkspace(workspace).apps === 'compose') { const role = await roleForWorkspace(workspace) value.policy ??= {} conformBuilderAppPolicy(value.policy, role.kind === 'resolved' ? role.user : undefined) @@ -2686,14 +2777,15 @@ ${getScriptPrompt(selected)}` async function getFlowInstructions( workspace: string | undefined, - composeOnly: boolean + composeOnly: boolean, + external = false ): Promise<string> { - const aiAgentProviders = formatAiAgentProvidersPrompt( - await getAiAgentProviderCatalog(workspace), - { - canAskUser: true - } - ) + // An external client's catalog is rendered where no workspace is known, so it gets none. + const aiAgentProviders = external + ? '' + : formatAiAgentProvidersPrompt(await getAiAgentProviderCatalog(workspace), { + canAskUser: true + }) return `# Global draft flow instructions - Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata. @@ -2738,7 +2830,11 @@ ${composeOnly ? 'This reference is written for every author. For this user, skip type InstructionSubject = (typeof ALL_INSTRUCTION_SUBJECTS)[number] -function getAppInstructions(language: ScriptLang | undefined, composeOnly: boolean): string { +function getAppInstructions( + language: ScriptLang | undefined, + composeOnly: boolean, + external = false +): string { // getRawAppPrompt swaps in the Python SDK for python3, so the pointer has to swap with // it: telling the model to re-fetch a reference it is already holding wastes a turn, and // naming the wrong SDK contradicts the text right below the sentence. @@ -2753,7 +2849,7 @@ function getAppInstructions(language: ScriptLang | undefined, composeOnly: boole - To create a new app, use \`init_app\` with a path, optional summary, a framework (\`react19\` / \`react18\` / \`svelte5\`)${ composeOnly ? '. "Starting a new app" below decides the framework. No data setup: the app reads and stores data only through the deployed runnables it calls.' - : ' and, for an app that stores data, its `data` setup. "Starting a new app" below decides the framework and when the data setup is asked. Ask each of its questions with `askUserQuestion`, one question per call with the suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool.' + : ` 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. ${external ? 'Ask the user each of its questions, suggested answer first,' : 'Ask each of its questions with \`askUserQuestion\`, one question per call with the suggested answer first,'} before \`init_app\` and before any SQL. \`init_app\` only records \`data\`: a new schema is yours to create with the datatable SQL tool.` } \`init_app\` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing. ${ composeOnly @@ -2792,7 +2888,7 @@ function getResourceInstructions(): string { - Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata. - 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. - Reading a variable returns \`{ type: 'variable', path, summary?, isSecret, isDraft }\` — never its value, secret or not. \`isSecret\` tells you whether the value is encrypted. -- \`write_variable\` takes \`{ path, value?, is_secret?, description?, account?, is_oauth?, expires_at?, 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. +- \`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. - 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). - 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. - Use \`search_resource_types\` to discover valid \`resource_type\` names and their JSON Schemas. Match the resource value to that schema. @@ -2822,21 +2918,22 @@ function getPipelineInstructions(): string { return getPipelinePrompt() } -function getInstructions( +export function getInstructions( subject: InstructionSubject, language: ScriptLang | undefined, workspace: string | undefined, - composeOnly: boolean + composeOnly: boolean, + external = false ): string | Promise<string> { switch (subject) { case 'script': return getScriptInstructions(language) case 'flow': - return getFlowInstructions(workspace, composeOnly) + return getFlowInstructions(workspace, composeOnly, external) case 'resource': return getResourceInstructions() case 'app': - return getAppInstructions(language, composeOnly) + return getAppInstructions(language, composeOnly, external) case 'datatable': return getDatatableInstructions(language) case 'pipeline': @@ -2872,6 +2969,11 @@ export type SessionPromptContext = { forkParentUnknown?: boolean /** Pre-send intent: a staged fork of this workspace is created at first send. */ pendingForkOf?: string + /** The family's dev workspace, where a read-only session sends the user to make changes. */ + devWorkspace?: { id: string; name: string } + /** Why the session is in Use mode, where the workspace itself is not protected: the user + * picked it, or their role builds nothing there. */ + useMode?: 'chosen' | 'role' } /** Session-state guidance appended to the global system prompt so the model @@ -2898,9 +3000,17 @@ export function getSessionContextPromptSection( (!access || access.has('manage_schedules')) && 'schedules', (!access || access.has('manage_triggers')) && 'triggers' ].filter((k): k is string => !!k) + const readOnly = isReadOnlyAccess(access) + // Read-only either because the user chose Use or because the workspace forces it. + const protectedWorkspace = readOnly && !ctx.useMode // With no kind left to deploy, the deploy tool is not shipped, so the lines below cannot name it. - const deployer = canDeploy || unruledKinds.length ? 'deploy_workspace_item' : 'A deploy' - const targets = ['reads', canWriteDraft && 'drafts', canRunPreview && 'test runs', 'deploys'] + const deployer = + !readOnly && (canDeploy || unruledKinds.length) ? 'deploy_workspace_item' : 'A deploy' + const targets = ( + readOnly + ? ['reads', 'runs'] + : ['reads', canWriteDraft && 'drafts', canRunPreview && 'test runs', 'deploys'] + ) .filter(Boolean) .join(', ') const lines = [ @@ -2913,6 +3023,14 @@ export function getSessionContextPromptSection( lines.push( `- No workspace is committed yet: a staged fork of workspace "${ctx.pendingForkOf}" is created automatically when the first message is sent, and all work lands in that fork.` ) + } else if (protectedWorkspace) { + const dev = ctx.devWorkspace?.id !== ctx.workspaceId ? ctx.devWorkspace : undefined + const elsewhere = dev + ? `start a new session in the dev workspace "${dev.id}", which the "New session in ${dev.name} (dev)" entry of the composer's mode picker opens` + : 'start a new session in a fork of this workspace, or, where forking is refused too, make the change in git and open a pull request' + lines.push( + `- Operating workspace: "${ctx.workspaceId}" — a production workspace protected against direct changes, so this session is READ-ONLY whatever the user's role. To make a change, the user needs to ${elsewhere}. This session's mode picker shows Plan and Use & build greyed out and its workspace cannot change once it has started, so never suggest picking Use & build or switching this session.` + ) } else if (ctx.parentWorkspaceId && ctx.isDevWorkspace) { lines.push( `- Operating workspace: "${ctx.workspaceId}" — the user's persistent DEV WORKSPACE, forked from workspace "${ctx.parentWorkspaceId}". ${deployer} publishes into the dev workspace only; the user reviews & promotes changes into "${ctx.parentWorkspaceId}" from the session's deploy panel. Never present a change as live in "${ctx.parentWorkspaceId}".` @@ -2934,9 +3052,18 @@ export function getSessionContextPromptSection( '- No operating workspace is set yet; the user picks one (or a new staged fork) before the first message is sent.' ) } + if (readOnly && ctx.useMode === 'chosen') { + lines.push( + "- The user put this session in Use mode with the composer's mode picker, so it is READ-ONLY until they switch. To make a change, call `enter_build_mode`, which asks them to switch to Use & build, or `enter_plan_mode` to agree on the change first; without those tools, ask them to switch the picker." + ) + } else if (readOnly && ctx.useMode === 'role') { + lines.push( + `- This user's workspace role cannot create or change scripts, flows, apps, schedules or triggers, neither through you nor by hand anywhere in the workspace. That role, not this session, is why the session is held in Use mode and is READ-ONLY. When they ask for one, say that their role does not allow it, and that a workspace admin can create it for them or grant their role more in ${OPERATOR_SETTINGS_LOCATION}. Do not write its code or give steps: they can use neither. Their mode picker shows Plan and Use & build greyed out, so never suggest switching modes. Resources and variables are the exception: every role creates and edits those by hand, outside this session, on the workspace's own Resources and Variables pages.` + ) + } // The kind enum already withholds what the rules refuse; this says why, and where the user // promotes the rest instead. The rules gate deletes too, so it is owed to every such profile. - if (!canDeploy) { + if (!canDeploy && !readOnly) { lines.push( `- This workspace refuses direct deployment for this user${ unruledKinds.length === 2 @@ -2949,7 +3076,7 @@ export function getSessionContextPromptSection( } lines.push( '- Sessions are saved: the sidebar lists them under AI Sessions, and the user can reopen any of them.', - '- The composer has a permission mode picker: Ask permission, Auto-accept edits, Yolo (bypass permissions: tool confirmations are accepted without asking) and Plan (read-only). Some modes are hidden where they do not apply.', + `- The composer has a mode picker in two parts. What you may do: Use (read and run deployed items, change nothing), Plan (research, then propose a plan for approval) and Use & build (everything Use does, plus changes). How tool confirmations work: Ask permission, Auto-accept edits, or Yolo (bypass permissions: tool confirmations are accepted without asking). Some options are hidden where they do not apply${protectedWorkspace ? ', and this workspace locks the picker to Use' : ctx.useMode === 'role' ? ", and this user's role locks the picker to Use" : ''}.`, "- The sliders button next to the model picker opens Assistant settings. Its Permissions section shows what the user's role lets them change and what you can change for them; point them there when they ask what they are allowed to do." ) return lines.join('\n') @@ -3084,40 +3211,25 @@ function allowedTriggerKinds(): PageTriggerKind[] { return (Object.keys(TRIGGER_PAGES) as PageTriggerKind[]).filter((k) => ee || !TRIGGER_PAGES[k].ee) } -// Pages an operator may reach: exactly the ones enabled in the workspace's -// operator_settings, the same source the sidebar gates on. Operators are never admins, so -// workspace_settings is excluded whatever the settings say. -function operatorOpenPages(workspaceId: string | undefined): OpenPageName[] { - const settings = get(userWorkspaces).find((w) => w.id === workspaceId)?.operator_settings - return OPEN_PAGE_NAMES.filter( - (p) => - p !== 'workspace_settings' && settings?.[p as keyof NonNullable<typeof settings>] === true +// Pages a role may reach: the ones its visibility shows, the same source the sidebar gates +// on. workspace_settings is admin/superadmin only, and compare deploys code, so it follows +// `code`. +function roleOpenPages(caps: RoleCapabilities, isAdmin: boolean): OpenPageName[] { + return OPEN_PAGE_NAMES.filter((p) => + p === 'workspace_settings' ? isAdmin : p === 'compare' ? caps.code : caps.visibility[p] ) } -// workspace_settings is admin/superadmin only; the rest are open to any non-operator member. -const NON_ADMIN_OPEN_PAGES = new Set<OpenPageName>([ - 'runs', - 'assets', - 'schedules', - 'variables', - 'resources', - 'audit_logs', - 'folders', - 'groups', - 'triggers', - 'compare' -]) - -// What to advertise before the role in `workspaceId` has been resolved. -// `user_workspaces` nulls operator_settings for a workspace the user is not an operator -// in, so a non-null value narrows an operator correctly; the converse does not hold, -// which is why the real role is still fetched. +// What to advertise before the role in `workspaceId` has been resolved: the role the +// workspace list names, which is why the real role is still fetched. function restrictedOpenPages(workspaceId: string | undefined): OpenPageName[] { - if (get(userWorkspaces).find((w) => w.id === workspaceId)?.operator_settings) { - return operatorOpenPages(workspaceId) - } - return OPEN_PAGE_NAMES.filter((p) => NON_ADMIN_OPEN_PAGES.has(p)) + return roleOpenPages( + capabilitiesIn( + undefined, + get(userWorkspaces).find((w) => w.id === workspaceId) + ), + false + ) } // The role to gate `workspaceId` on. `userStore` answers only when it describes that same @@ -3196,7 +3308,9 @@ export async function resolveGlobalPromptIdentity( // for the global side-panel chat. The tool only ever advertises, and only ever acts on, // `pages`. async function allowedOpenPages( - workspaceId: string | undefined = get(workspaceStore) + workspaceId: string | undefined = get(workspaceStore), + /** A read-only session reaches what an operator reaches: never workspace settings. */ + readOnly = false ): Promise<{ pages: OpenPageName[]; roleUnverified: boolean }> { const role = await roleForWorkspace(workspaceId) // A failed lookup says nothing about the role, so guessing a page set can offer one the @@ -3209,14 +3323,14 @@ async function allowedOpenPages( return { pages: restrictedOpenPages(workspaceId), roleUnverified: false } } const u = role.user - if (u.operator) return { pages: operatorOpenPages(workspaceId), roleUnverified: false } const isAdmin = !!u.is_admin || !!u.is_super_admin || !!get(superadmin) - return { - pages: OPEN_PAGE_NAMES.filter( - (p) => NON_ADMIN_OPEN_PAGES.has(p) || (isAdmin && p === 'workspace_settings') - ), - roleUnverified: false - } + const caps = capabilitiesIn( + { ...u, is_admin: isAdmin }, + get(userWorkspaces).find((w) => w.id === workspaceId) + ) + return readOnly + ? { pages: roleOpenPages(withoutBuilding(caps), false), roleUnverified: false } + : { pages: roleOpenPages(caps, isAdmin), roleUnverified: false } } // The Runs page only offers its cross-workspace filter to a superadmin or devops user in @@ -3457,8 +3571,8 @@ function buildOpenPageDefSchema( roleUnverified = false ): z.ZodTypeAny { const full = openPageFullSchema.shape as Record<string, z.ZodTypeAny> - // z.enum() rejects an empty list, and a user with no reachable pages (e.g. an operator - // with every operator_settings flag off) yields exactly that. Fall back to a plain + // z.enum() rejects an empty list, and a user with no reachable pages (e.g. a role with + // every visibility flag off) yields exactly that. Fall back to a plain // string so schema-building can't throw; the handler still fails closed on every page. // The model reads this before it can reach the handler's message, so an unresolved role // must not be described as a denial here either. @@ -3698,7 +3812,10 @@ export const openPageTool: SessionTool<{}> = { // Re-narrow the advertised `page` enum to this user's permissions each iteration, so // the model never sees (or suggests) a page the user can't reach. schemaFor: async (helpers) => { - const access = await allowedOpenPages(operatingWorkspaceFromHelpers(helpers)) + const access = await allowedOpenPages( + operatingWorkspaceFromHelpers(helpers), + isReadOnlyAccess((helpers as GlobalToolHelpers | undefined)?.access) + ) return createToolDef( buildOpenPageDefSchema( access.pages, @@ -3719,7 +3836,10 @@ export const openPageTool: SessionTool<{}> = { // requests one outside the advertised enum. An unverified role means the lookup // failed, not that access was denied — reporting it as denied states a falsehood // about the user's permissions. - const access = await allowedOpenPages(workspaceId) + const access = await allowedOpenPages( + workspaceId, + isReadOnlyAccess((ctx.helpers as GlobalToolHelpers | undefined)?.access) + ) if (!access.pages.includes(page)) { const label = OPEN_PAGE_LABELS[page] ?? page return access.roleUnverified @@ -3816,9 +3936,17 @@ export const globalTools: SessionTool<{}>[] = [ ? `${parsed.subject} (${parsed.language})` : parsed.subject toolCallbacks.setToolStatus(toolId, { content: `Loaded ${label} instructions` }) - // Past the gate without `write_draft` means a builder: guidance for inline code would - // steer the model at writes the server refuses and tools it was not given. - const composeOnly = !!access && !access.has('write_draft') + // Guidance for inline code would steer a composing role at writes the server refuses + // and tools it was not given. + const composeOnly = + !!access && + !access.has( + parsed.subject === 'flow' + ? 'write_inline_flow_code' + : parsed.subject === 'app' + ? 'write_inline_app_code' + : 'write_draft' + ) return getInstructions(parsed.subject, parsed.language, ctx.workspace, composeOnly) } }, @@ -3903,6 +4031,8 @@ export const globalTools: SessionTool<{}>[] = [ 'update_user_instructions', 'Modify your own persistent personal instructions for the Global assistant. Use when the user asks you to remember a preference, always/never do something, or change/stop a behavior. Edits only the user-level instructions (the USER INSTRUCTIONS block, not workspace-level); changes persist in this browser and take effect on your next message.' ), + // Writes this browser's preference, not the workspace. + readOnlySafe: true, showDetails: true, fn: async ({ args, toolId, toolCallbacks, helpers }) => { const parsed = updateUserInstructionsSchema.parse(args) @@ -4353,6 +4483,7 @@ export const globalTools: SessionTool<{}>[] = [ // permissions, the one run an operator's token allows. `run_flow` likewise. requires: NONE, def: runScriptToolDef, + readOnlySafe: true, fn: async (ctx) => { const parsed = runScriptSchema.parse(ctx.args) return runDeployedScript(parsed, ctx) @@ -4385,6 +4516,7 @@ export const globalTools: SessionTool<{}>[] = [ { requires: NONE, def: runFlowToolDef, + readOnlySafe: true, fn: async (ctx) => { const parsed = runFlowSchema.parse(ctx.args) return runDeployedFlow(parsed, ctx) @@ -4522,6 +4654,8 @@ export const globalTools: SessionTool<{}>[] = [ 'cancel_job', 'Cancel a running or queued job by its id (e.g. a background test run you started that is no longer needed).' ), + // A run the session may start, it may also stop. + readOnlySafe: true, showDetails: true, fn: async ({ args, workspace, toolId, toolCallbacks }) => { const parsed = cancelJobSchema.parse(args) @@ -4594,7 +4728,7 @@ export const globalTools: SessionTool<{}>[] = [ def: createToolDef( rebaseDraftSchema, 'rebase_draft', - 'Discard a stale script, flow, or app draft and return your changes as a diff to re-apply on the latest deployed version. Use when deploy_workspace_item reports the draft was started from an older deployed version.', + 'Discard a stale script, flow, or app draft and return your changes as a diff to re-apply on the latest deployed version. Use when a deploy reports the draft was started from an older deployed version.', { strict: false } ), showDetails: true, @@ -4812,7 +4946,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: [...WRITE_FLOW_DRAFT, 'write_inline_flow_code'], def: createToolDef( setFlowModuleCodeSchema, 'set_flow_module_code', @@ -4960,6 +5094,8 @@ export const globalTools: SessionTool<{}>[] = [ { requires: NONE, def: createToolDef(openPreviewSchema, 'open_preview', OPEN_PREVIEW_DESCRIPTION), + // A read-only session holds no draft capability, so the schema below offers it viewers. + readOnlySafe: true, // Withhold the editors a session cannot save, so the model never offers the user a // panel it would not get. schemaFor: async (helpers) => { @@ -5008,6 +5144,7 @@ export const globalTools: SessionTool<{}>[] = [ 'close_page', 'Close one or more preview tabs in the side panel of this AI session. Pass `match` to close the tab(s) whose page name or item path contains that text, or `all: true` to clear the panel. Use this when the user asks to close/dismiss a tab they no longer need. Only works inside a session.' ), + readOnlySafe: true, fn: async (ctx) => { const parsed = closePageSchema.parse(ctx.args) return closeSessionPreviewTabs(parsed, sessionIdFromCtx(ctx)) @@ -5364,11 +5501,14 @@ async function canEditItemPath( if (role.kind === 'not_a_member') return 'denied' if (role.kind !== 'resolved' || !role.user) return 'unverified' const user = role.user - const settings = get(userWorkspaces).find((w) => w.id === workspace)?.operator_settings - if (!roleCanDraft(kind, user, settings)) return 'denied' + const caps = capabilitiesIn( + user, + get(userWorkspaces).find((w) => w.id === workspace) + ) + if (!roleCanDraft(kind, caps)) return 'denied' // Folder and ownership rules answer most calls without a request. An item's own // `extra_perms` can only widen them, so the item is fetched only to overturn a denial. - if (canDraftItem(kind, path, {}, user, settings)) return 'allowed' + if (canDraftItem(kind, path, {}, user, caps)) return 'allowed' try { const extraPerms = kind === 'script' @@ -5376,7 +5516,7 @@ async function canEditItemPath( : kind === 'flow' ? (await FlowService.getFlowByPath({ workspace, path })).extra_perms : (await AppService.getAppByPath({ workspace, path })).extra_perms - return canDraftItem(kind, path, extraPerms, user, settings) ? 'allowed' : 'denied' + return canDraftItem(kind, path, extraPerms, user, caps) ? 'allowed' : 'denied' } catch (e) { // Nothing deployed means no sharing to widen the folder rules with. return (e as { status?: number } | null | undefined)?.status === 404 ? 'denied' : 'unverified' @@ -5650,7 +5790,8 @@ function variableToDraftState(variable: ListableVariable): VariableDraftState { // reviews. Undefined drops out of the JSON instead. account: variable.account ?? undefined, is_oauth: variable.is_oauth ?? undefined, - expires_at: variable.expires_at ?? undefined + expires_at: variable.expires_at ?? undefined, + value_valid_until: variable.value_valid_until ?? undefined } } @@ -5720,7 +5861,11 @@ function createVariableToDraftState( wsSpecific: args.ws_specific ?? base?.wsSpecific ?? false, account: args.account ?? base?.account, is_oauth: args.is_oauth ?? base?.is_oauth, - expires_at: args.expires_at ?? base?.expires_at + expires_at: args.expires_at ?? base?.expires_at, + // `null` clears and omitted keeps the base's. The draft stores a cleared expiry as + // `undefined`, since a stored draft goes through a JSON round-trip. + value_valid_until: + args.value_valid_until === null ? undefined : (args.value_valid_until ?? base?.value_valid_until) } } @@ -5739,10 +5884,16 @@ function buildVariableCreateRequestBody(draftValue: CreateVariable): CreateVaria // endpoint, and a draft stores '' when it stages no new value — so omitting `value` in // that case is what leaves the stored one untouched. A staged value is sent as-is: the // endpoint decrypts an `$encrypted:` marker and encrypts plaintext. -function buildVariableUpdateRequestBody( - draftValue: CreateVariable -): Omit<CreateVariable, 'value'> & { value?: string } { - const { value, ...rest } = structuredClone(draftValue) +function buildVariableUpdateRequestBody(draftValue: CreateVariable): Omit< + CreateVariable, + 'value' | 'value_valid_until' +> & { + value?: string + value_valid_until?: string | null +} { + const { value, value_valid_until, ...others } = structuredClone(draftValue) + // The draft holds the full state, so an absent expiry was cleared: send `null`. + const rest = { ...others, value_valid_until: value_valid_until ?? null } // A value the draft is never allowed to carry — a secret's, and an OAuth-managed one // dropped by `variableToDraftState` — reaches here as '' whenever this edit staged // none, so sending it would blank the stored value or wipe a rotating token. @@ -6675,6 +6826,17 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st } const blockedBeforeForm = blockedByPlanMode() if (blockedBeforeForm) return blockedBeforeForm + // The form is this call's confirmation, and a session can switch to Use while it waits. + const withdrawnByUseMode = (): string | undefined => { + if (!toolCallbacks.isToolWithdrawn?.(spec.toolName)) return undefined + toolCallbacks.setToolStatus(toolId, { + content: USE_MODE_WITHDRAWN.label, + isLoading: false, + isStreamingArguments: false, + error: USE_MODE_WITHDRAWN.result + }) + return USE_MODE_WITHDRAWN.result + } const schema = spec.schema // Whether to ask is the only question decided here. What a mounted field would hold — a @@ -6769,7 +6931,7 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st const adopted = answer.kind === 'job' ? answer : undefined const submitted = answer.args - const blockedBeforeRun = adopted ? undefined : blockedByPlanMode() + const blockedBeforeRun = adopted ? undefined : (blockedByPlanMode() ?? withdrawnByUseMode()) if (blockedBeforeRun) { toolCallbacks.markRunFormEnded?.(toolId) return blockedBeforeRun @@ -7145,7 +7307,7 @@ async function initApp( }) // A builder can save no inline runnable, so they start from a static page instead of the tour. - const builder = operatorBuilderAppsIn(workspace) + const builder = capabilitiesInWorkspace(workspace).apps === 'compose' const value: AppDraftValue = { summary, files: { ...(builder ? BUILDER_FRAMEWORK_TEMPLATES : FRAMEWORK_TEMPLATES)[framework] }, @@ -9053,8 +9215,19 @@ async function deployDraft( break } case 'resource': { - const requestBody = draft.value as any + let requestBody = draft.value as any if (await ResourceService.existsResource({ workspace, path })) { + // The server resets an agent's identity to whoever deploys, unless told to keep + // it: the identity is the deployed one, never the draft's. + const deployed = await ResourceService.getResource({ workspace, path }) + const obo = (deployed.value as any)?.on_behalf_of + if (deployed.resource_type === 'ai_agent' && obo) { + requestBody = { + ...requestBody, + value: { ...requestBody.value, on_behalf_of: obo }, + preserve_on_behalf_of: true + } + } await ResourceService.updateResource({ workspace, path, requestBody }) } else { await ResourceService.createResource({ workspace, requestBody }) @@ -9357,9 +9530,16 @@ async function undeployedRunnableTargets( ? runnable?.runType : runnable?.type const path = runnable?.path - if ((type !== 'script' && type !== 'flow') || !path) continue + if ((type !== 'script' && type !== 'flow' && type !== 'agent') || !path) continue try { - if (await deployedItemExists(workspace, type, path, undefined)) continue + if (type === 'agent') { + // A saved agent is an `ai_agent` resource; another resource at the path runs nothing. + const found = await ResourceService.getResource({ workspace, path }).catch((e) => { + if ((e as { status?: number } | null | undefined)?.status === 404) return undefined + throw e + }) + if (found?.resource_type === 'ai_agent') continue + } else if (await deployedItemExists(workspace, type, path, undefined)) continue } catch { // The probe is advisory: a lookup failure must never block the write or // the deploy it annotates. @@ -9493,6 +9673,8 @@ export function prepareGlobalSystemMessage( /** Capabilities of the chat's operating workspace; undefined keeps every block. Must * match the profile the toolset was filtered with, or the prompt names withheld tools. */ access?: SessionAccess + /** Render for an external MCP client rather than the Windmill chat. */ + external?: boolean } ): ChatCompletionSystemMessageParam { const user = opts?.user ?? get(userStore) @@ -9511,7 +9693,8 @@ export function prepareGlobalSystemMessage( folderCtx, opts?.skills ?? [], opts?.mcpServers ?? [], - opts?.access + opts?.access, + opts?.external ?? false ) if (instructions?.workspace?.trim()) { content = `${content}\n\nWORKSPACE INSTRUCTIONS (configured by a workspace admin, shared by everyone in this workspace — you cannot modify these):\n${instructions.workspace.trim()}` diff --git a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts index 7c8253684d..56fa40655d 100644 --- a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts @@ -573,6 +573,20 @@ describe('fork mode', () => { expect(entry?.valueMasked).toBe(true) }) + it('sees an expiry-only variable change', async () => { + mockComparison([comparisonDiff({ kind: 'variable', path: 'f/a/plain' })]) + vi.mocked(VariableService.getVariable).mockImplementation(async ({ workspace }: any) => ({ + path: 'f/a/plain', + is_secret: false, + value: 'same', + description: 'same', + value_valid_until: workspace === FORK ? '2027-09-09T10:00:00Z' : '2027-03-01T10:00:00Z' + })) as any + const entry = await readForkDiffEntryOne(FORK, PARENT, ['variable'], 'f/a/plain') + expect(entry?.status).toBe('modified') + expect(entry?.patch).toContain('2027-09-09') + }) + it('sees flow schema-only changes the shared projection drops', async () => { mockComparison([comparisonDiff({ kind: 'flow', path: 'f/a/fl' })]) vi.mocked(FlowService.getFlowByPath).mockImplementation(async ({ workspace }: any) => ({ diff --git a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts index 472a9e6e61..9b8d04d370 100644 --- a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts +++ b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts @@ -904,6 +904,7 @@ async function fetchForkSideValue( value: { description: variable.description, is_secret: variable.is_secret, + value_valid_until: variable.value_valid_until, value: VARIABLE_VALUE_PLACEHOLDER }, valueMasked: true diff --git a/frontend/src/lib/components/copilot/chat/global/mcpSessionGen.test.ts b/frontend/src/lib/components/copilot/chat/global/mcpSessionGen.test.ts new file mode 100644 index 0000000000..3de18622a5 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/global/mcpSessionGen.test.ts @@ -0,0 +1,255 @@ +/** + * Generates what the Windmill MCP server's toolset (backend/windmill-api/src/mcp/session) + * shows a model, from the same definitions an AI session uses: tool names, descriptions and + * input schemas, the system prompt, and the `get_instructions` texts. The server implements + * the tools in Rust; everything the model reads comes from here, so the two cannot drift + * apart in wording. + * + * Run `npm run gen:mcp-session` after changing a GLOBAL tool definition, the global system + * prompt, or anything under system_prompts/. Without that env var this is the freshness check. + */ +import { describe, expect, it } from 'vitest' +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import { + ALL_INSTRUCTION_SUBJECTS, + getInstructions, + globalToolsFor, + prepareGlobalSystemMessage +} from './core' +import type { ScriptLang } from '$lib/gen' +import { FRAMEWORK_TEMPLATES, STARTER_RUNNABLES } from '$lib/components/raw_apps/templates' + +const OUT_DIR = fileURLToPath( + new URL('../../../../../../../backend/windmill-api/src/mcp/session/gen/', import.meta.url) +) + +// Sentences that describe the chat's run form, which an MCP client does not have. Each +// must still be found in the description it is listed for: a reworded description fails +// generation rather than shipping a promise of a form. +const DESCRIPTION_REWRITES: [tool: string, from: string, to: string][] = [ + [ + 'test_run_script', + ' The user gets an argument form prefilled with `args` and may edit or dismiss it before it runs, so fill in every argument you can infer.', + ' It runs with exactly the `args` you send.' + ], + [ + 'test_run_flow', + ' The user gets an argument form prefilled with `args` and may edit or dismiss it before it runs, so fill in every argument you can infer.', + ' It runs with exactly the `args` you send.' + ], + [ + 'test_run_step', + ' The user gets an argument form prefilled with `args` and may edit or dismiss it before it runs, so fill in every argument you can infer.', + ' It runs with exactly the `args` you send.' + ], + [ + 'run_script', + " Fill in every argument you can infer: the user gets an argument form prefilled with `args` and decides what runs. In an AI session the user can open that form on the script's own deployed page instead; either way this call waits for them and runs what they confirm.", + ' It runs with exactly the `args` you send.' + ], + [ + 'run_flow', + " Fill in every argument you can infer: the user gets an argument form prefilled with `args` and decides what runs. In an AI session the user can open that form on the flow's own deployed page instead; either way this call waits for them and runs what they confirm.", + ' It runs with exactly the `args` you send.' + ], + ['create_resource_type', ' once the user confirms the schema', ''], + ['set_workspace_settings', ' The user reviews the changes before they apply.', ''] +] + +// A rewrite only proves its old sentence is still there; this catches one added next to it. +const CHAT_ONLY_PROMISE = /argument form|the user (confirms|reviews|approves)/i + +function toolDefs() { + return globalToolsFor({ sessionPreview: false }).map((tool) => { + const fn = tool.def.function + let description = fn.description ?? '' + for (const [name, from, to] of DESCRIPTION_REWRITES) { + if (name !== fn.name) continue + if (!description.includes(from)) { + throw new Error(`${name}: its description no longer contains "${from}"`) + } + description = description.replace(from, to) + } + if (CHAT_ONLY_PROMISE.test(description)) { + throw new Error(`${fn.name}: its description promises a chat-only confirmation`) + } + return { + name: fn.name, + description, + parameters: fn.parameters, + // The session's own read-only marker: what plan mode lets through. + read_only: tool.planModeSafe === true + } + }) +} + +const WRITABLE = '{{writable_folders}}' +const READONLY = '{{readonly_folders}}' + +function prompt( + user: { is_admin: boolean; folders?: string[]; folders_read?: string[] }, + extra: Parameters<typeof prepareGlobalSystemMessage>[1] = {}, + instructions?: { workspace?: string } +): string { + const content = prepareGlobalSystemMessage(instructions, { + user: { username: '{{username}}', ...user } as any, + external: true, + ...extra + }).content as string + // The builder wraps each folder as `f/<name>`; the server substitutes a whole list. + return content + .replaceAll('`f/' + WRITABLE + '`', WRITABLE) + .replaceAll('`f/' + READONLY + '`', READONLY) +} + +function suffixOf(longer: string, base: string, what: string): string { + if (!longer.startsWith(base)) throw new Error(`${what} is no longer appended to the prompt`) + return longer.slice(base.length) +} + +function promptParts() { + const member = prompt({ is_admin: false, folders: [WRITABLE] }) + const skills = suffixOf( + prompt( + { is_admin: false, folders: [WRITABLE] }, + { skills: [{ path: '{{skill_path}}', name: '', description: '{{skill_description}}' }] } + ), + member, + 'the skills section' + ) + const skillLine = skills.split('\n').pop()! + // The folder guidance differs per workspace, so it is cut out of the prompt: the server + // puts it back for a single workspace, and serves it from `get_workspace_context` otherwise. + const withoutFolders = prompt({ is_admin: false }) + const variants = { + admin: prompt({ is_admin: true, folders: [WRITABLE] }), + admin_no_folders: prompt({ is_admin: true, folders: [] }), + member, + member_no_folders: prompt({ is_admin: false, folders: [] }), + member_readonly: prompt({ + is_admin: false, + folders: [WRITABLE], + folders_read: [WRITABLE, READONLY] + }), + member_no_folders_readonly: prompt({ is_admin: false, folders: [], folders_read: [READONLY] }) + } + let at: number | undefined + const folder_guidance = Object.fromEntries( + Object.entries(variants).map(([name, full]) => { + let i = 0 + while (full[i] === withoutFolders[i]) i++ + const rest = withoutFolders.slice(i) + if ((at !== undefined && at !== i) || !full.endsWith(rest)) { + throw new Error(`the folder guidance (${name}) is no longer one inserted block`) + } + at = i + return [name, full.slice(i, full.length - rest.length)] + }) + ) + return { + base: withoutFolders.slice(0, at) + '{{folder_guidance}}' + withoutFolders.slice(at), + folder_guidance, + skills_header: skills.slice(0, skills.length - skillLine.length), + skill_line: skillLine, + workspace_instructions: suffixOf( + prompt( + { is_admin: false, folders: [WRITABLE] }, + {}, + { workspace: '{{workspace_instructions}}' } + ), + member, + 'the workspace instructions' + ) + } +} + +/** What `get_trigger_schema` and `get_schedule_schema` answer: derived from the generated + * request schemas, so the tools themselves are the only faithful source. */ +async function schemas() { + const tools = globalToolsFor({ sessionPreview: false }) + const tool = (name: string) => tools.find((t) => t.def.function.name === name)! + const run = (name: string, args: unknown) => + tool(name).fn({ + args, + workspace: '', + toolId: '', + toolCallbacks: {} as any, + helpers: {} as any + }) + const kinds: string[] = (tool('get_trigger_schema').def.function.parameters as any).properties + .kind.enum + const trigger: Record<string, string> = {} + for (const kind of kinds) { + trigger[kind] = await run('get_trigger_schema', { kind }) + } + return { trigger, schedule: await run('get_schedule_schema', {}) } +} + +/** Every file to write, keyed by name. */ +async function generate(): Promise<Record<string, string>> { + const tools = toolDefs() + const files: Record<string, string> = { + 'tools.json': JSON.stringify(tools, null, '\t') + '\n', + 'prompt.json': JSON.stringify(promptParts(), null, '\t') + '\n' + } + const languages: (ScriptLang | undefined)[] = [ + undefined, + ...(tools.find((t) => t.name === 'get_instructions')!.parameters as any).properties.language + .enum + ] + // Keyed by subject then language ('' when none was given); identical texts are stored once. + const index: Record<string, Record<string, string>> = {} + const texts: Record<string, string> = {} + for (const subject of ALL_INSTRUCTION_SUBJECTS) { + index[subject] = {} + const byText = new Map<string, string>() + for (const language of languages) { + const text = await getInstructions(subject, language, undefined, false, true) + let id = byText.get(text) + if (!id) { + id = `${subject}${language ? '.' + language : ''}` + byText.set(text, id) + texts[id] = text + } + index[subject][language ?? ''] = id + } + } + // What `init_app` seeds a new raw app with. + files['app_templates.json'] = + JSON.stringify( + { templates: FRAMEWORK_TEMPLATES, starter_runnables: STARTER_RUNNABLES }, + null, + '\t' + ) + '\n' + files['schemas.json'] = JSON.stringify(await schemas(), null, '\t') + '\n' + files['instructions.json'] = JSON.stringify({ index, texts }, null, '\t') + '\n' + return files +} + +function committedFiles(dir = OUT_DIR, prefix = ''): string[] { + if (!existsSync(dir)) return [] + return readdirSync(dir, { withFileTypes: true }).flatMap((e) => + e.isDirectory() ? committedFiles(join(dir, e.name), `${prefix}${e.name}/`) : [prefix + e.name] + ) +} + +describe('MCP session server generated definitions', () => { + it('match the session tools and prompts (npm run gen:mcp-session)', async () => { + const files = await generate() + expect(Object.keys(files)).toContain('tools.json') + if (process.env.WM_GEN_MCP_SESSION) { + rmSync(OUT_DIR, { recursive: true, force: true }) + mkdirSync(OUT_DIR, { recursive: true }) + for (const [name, content] of Object.entries(files)) { + writeFileSync(join(OUT_DIR, name), content) + } + return + } + expect(committedFiles().sort()).toEqual(Object.keys(files).sort()) + for (const [name, content] of Object.entries(files)) { + expect(readFileSync(join(OUT_DIR, name), 'utf8'), name).toBe(content) + } + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts index e1da0fb624..0898837658 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts @@ -365,6 +365,8 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo ...(isRead ? { planModeSafe: true } : { + // Changes the external system, never the workspace, like a deployed run does. + readOnlySafe: true, requiresConfirmation: true, confirmAction: 'run', confirmationMessage: (args: any) => `Call ${args?.tool ?? ''} on ${args?.server ?? ''}` diff --git a/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts b/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts index 38718ed1b4..46d744fb10 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts @@ -1,15 +1,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -const { whoami, deployRules } = vi.hoisted(() => ({ +const { whoami, deployRules, protectionRules } = vi.hoisted(() => ({ whoami: vi.fn(), - deployRules: vi.fn() + deployRules: vi.fn(), + protectionRules: vi.fn() })) vi.mock('$lib/gen', () => ({ UserService: { whoami } })) vi.mock('$lib/utils_workspace_deploy', () => ({ checkDeployRules: deployRules })) +vi.mock('$lib/workspaceProtectionRules.svelte', () => ({ + readProtectionRulesForWorkspace: protectionRules, + isRuleActiveInRulesets: (rulesets: { rules: string[] }[], kind: string) => + rulesets.some((r) => r.rules.includes(kind)) +})) import { capabilitiesForRole, resolveSessionAccess } from './sessionAccess' import { clearWorkspaceRoleCache } from '$lib/user' +import { FULL_CAPABILITIES, legacyOperatorCapabilities } from '$lib/roleCapabilities' +import type { OperatorSettings, RoleCapabilities } from '$lib/gen' type WhoamiOverrides = { is_admin?: boolean; is_super_admin?: boolean; operator?: boolean } @@ -39,6 +47,7 @@ describe('resolveSessionAccess', () => { beforeEach(() => { vi.clearAllMocks() deployRules.mockResolvedValue({ ok: true }) + protectionRules.mockResolvedValue([]) // The role memo is app-wide, so without this each case answers from the previous one. clearWorkspaceRoleCache() }) @@ -52,11 +61,14 @@ describe('resolveSessionAccess', () => { 'manage_flows', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'run_flow_preview', 'run_preview', 'write_app_draft', 'write_draft', 'write_flow_draft', + 'write_inline_app_code', + 'write_inline_flow_code', 'write_resource_draft', 'write_schedule_draft', 'write_trigger_draft', @@ -72,6 +84,7 @@ describe('resolveSessionAccess', () => { 'deploy', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'write_resource_draft', 'write_schedule_draft', 'write_trigger_draft', @@ -85,6 +98,7 @@ describe('resolveSessionAccess', () => { expect([...caps].sort()).toEqual([ 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'write_resource_draft', 'write_schedule_draft', 'write_trigger_draft', @@ -92,20 +106,28 @@ describe('resolveSessionAccess', () => { ]) }) - // Both spellings of `authed.is_admin`, which the draft path honours and the handlers - // refusing `authed.is_operator` do not — the session path never clears that flag. + // Both spellings of `authed.is_admin`: `caller_capabilities` gives an admin every role + // capability, whatever role the membership row names. it.each([{ is_admin: true }, { is_super_admin: true }])( - 'lets an admin who is also an operator draft and deploy, but not preview or manage code (%o)', + 'gives an admin whose role is operator everything (%o)', async (role) => { const caps = await capabilitiesFor({ ...role, operator: true }) expect([...caps].sort()).toEqual([ 'admin', 'deploy', + 'manage_apps', + 'manage_code', + 'manage_flows', 'manage_schedules', 'manage_triggers', + 'modify_workspace', + 'run_flow_preview', + 'run_preview', 'write_app_draft', 'write_draft', 'write_flow_draft', + 'write_inline_app_code', + 'write_inline_flow_code', 'write_resource_draft', 'write_schedule_draft', 'write_trigger_draft', @@ -114,6 +136,26 @@ describe('resolveSessionAccess', () => { } ) + // A production workspace: the session reads and runs, and holds nothing that writes, even + // for an admin the rule would let through. + it('makes the session read-only in a workspace protected by DisableDirectDeployment', async () => { + protectionRules.mockResolvedValue([{ rules: ['DisableDirectDeployment'] }]) + const caps = await capabilitiesFor({ is_admin: true }) + expect([...caps]).toEqual([]) + }) + + // The server holds deploys to the rule but not drafts, so neither failure may hand a + // production session its writes. + it('stays read-only when the rules cannot be read, or the role of a protected workspace', async () => { + protectionRules.mockResolvedValue(undefined) + expect([...(await capabilitiesFor({ is_admin: true }))]).toEqual([]) + + // Another workspace: the role memo answers for the first one. + protectionRules.mockResolvedValue([{ rules: ['DisableDirectDeployment'] }]) + whoami.mockRejectedValueOnce(new Error('network')) + expect([...(await resolveSessionAccess('prod'))]).toEqual([]) + }) + it('keeps drafting when a rule refuses deploy', async () => { deployRules.mockResolvedValue({ ok: false, @@ -130,15 +172,15 @@ describe('resolveSessionAccess', () => { it("gives a builder operator the flow capabilities and nothing a script's handler refuses", () => { const caps = capabilitiesForRole({ isAdmin: false, - operator: true, deployRulesPass: true, - operatorSettings: { builder_flows: true } + capabilities: legacyOperatorCapabilities({ builder_flows: true } as OperatorSettings) }) expect([...caps].sort()).toEqual([ 'deploy', 'manage_flows', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'run_flow_preview', 'write_flow_draft', 'write_resource_draft', @@ -152,15 +194,15 @@ describe('resolveSessionAccess', () => { it('gives an app builder operator the app capabilities alone', () => { const caps = capabilitiesForRole({ isAdmin: false, - operator: true, deployRulesPass: true, - operatorSettings: { builder_apps: true } + capabilities: legacyOperatorCapabilities({ builder_apps: true } as OperatorSettings) }) expect([...caps].sort()).toEqual([ 'deploy', 'manage_apps', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'write_app_draft', 'write_resource_draft', 'write_schedule_draft', @@ -173,9 +215,8 @@ describe('resolveSessionAccess', () => { it('withholds schedule and trigger writes only where the workspace set them to false', () => { const caps = capabilitiesForRole({ isAdmin: false, - operator: true, deployRulesPass: true, - operatorSettings: { manage_schedules: false } + capabilities: legacyOperatorCapabilities({ manage_schedules: false } as OperatorSettings) }) expect(caps.has('manage_schedules')).toBe(false) expect(caps.has('write_schedule_draft')).toBe(false) @@ -183,6 +224,20 @@ describe('resolveSessionAccess', () => { expect(caps.has('write_trigger_draft')).toBe(true) }) + // A role that codes but builds no apps: scripts and flows, and nothing apps.rs refuses. + it('follows the capabilities of a custom role rather than the operator flag', () => { + const scripter: RoleCapabilities = { ...FULL_CAPABILITIES, apps: 'none' } + const caps = capabilitiesForRole({ + isAdmin: false, + deployRulesPass: true, + capabilities: scripter + }) + expect(caps.has('manage_code')).toBe(true) + expect(caps.has('manage_flows')).toBe(true) + expect(caps.has('manage_apps')).toBe(false) + expect(caps.has('write_app_draft')).toBe(false) + }) + it('grants everything when the role cannot be resolved', async () => { whoami.mockRejectedValueOnce(new Error('network')) const access = await resolveSessionAccess('ws') diff --git a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts index 86239f5b19..6c58900eab 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts @@ -1,20 +1,22 @@ import { get } from 'svelte/store' import { userWorkspaces } from '$lib/stores' -import type { OperatorSettings } from '$lib/gen' +import type { ProtectionRuleset, RoleCapabilities } from '$lib/gen' import { getWorkspaceRole } from '$lib/user' import { roleCanAuthor, roleCanDraft } from '$lib/editRights' +import { capabilitiesIn, FULL_CAPABILITIES } from '$lib/roleCapabilities' import { checkDeployRules } from '$lib/utils_workspace_deploy' -import type { SessionAccess, SessionCapability } from '../sessionCapabilities' - -type OperatorRights = Pick< - NonNullable<OperatorSettings>, - 'builder_flows' | 'builder_apps' | 'manage_schedules' | 'manage_triggers' -> +import { + isRuleActiveInRulesets, + readProtectionRulesForWorkspace +} from '$lib/workspaceProtectionRules.svelte' +import { USE_MODE_ACCESS, type SessionAccess, type SessionCapability } from '../sessionCapabilities' const ALL_CAPABILITIES: SessionCapability[] = [ 'write_draft', 'write_flow_draft', 'write_app_draft', + 'write_inline_flow_code', + 'write_inline_app_code', 'write_schedule_draft', 'write_trigger_draft', 'write_resource_draft', @@ -27,73 +29,76 @@ const ALL_CAPABILITIES: SessionCapability[] = [ 'manage_apps', 'manage_schedules', 'manage_triggers', - 'admin' + 'admin', + 'modify_workspace' ] -/** Fail open, here and at every resolution failure below: blanking a toolset on a +/** Fail open, here and at every role resolution failure below: blanking a toolset on a * transient error tells a developer mid-session that they cannot author anything, * which is worse and far less legible than the 403 they get by trying. Matches - * `checkDeployPermission`, which fails open for the same reason. */ + * `checkDeployPermission`, which fails open for the same reason. The protection rule is + * the exception (`protects`). */ export function fullSessionAccess(): SessionAccess { return new Set(ALL_CAPABILITIES) } /** Pure, so the profiles this can produce are enumerable rather than listed by hand. * `isAdmin` is one field because the server's `authed.is_admin` is - * `usr.is_admin || super_admin` (auth.rs), which `whoami` reports as two. */ + * `usr.is_admin || super_admin` (auth.rs), which `whoami` reports as two. An admin holds every + * role capability, as `caller_capabilities` gives them. */ export function capabilitiesForRole(role: { isAdmin: boolean - operator: boolean deployRulesPass: boolean - /** The workspace's `operator_settings`, null for a non-operator. */ - operatorSettings?: OperatorRights | null + capabilities: RoleCapabilities }): SessionAccess { - const capabilities = new Set<SessionCapability>() - const user = { operator: role.operator, is_admin: role.isAdmin, is_super_admin: false } - const authorsCode = roleCanAuthor('script', user, role.operatorSettings) - const authorsFlows = roleCanAuthor('flow', user, role.operatorSettings) - // Drafts take the admin precedence `roleCanDraft` encodes; previews and the item handlers - // do not — and on the session path the operator flag is never cleared for an admin. - if (roleCanDraft('script', user, role.operatorSettings)) { + const capabilities = new Set<SessionCapability>(['modify_workspace']) + const caps = role.isAdmin ? FULL_CAPABILITIES : role.capabilities + if (roleCanDraft('script', caps)) { capabilities.add('write_draft') } - if (roleCanDraft('flow', user, role.operatorSettings)) { + if (roleCanDraft('flow', caps)) { capabilities.add('write_flow_draft') } - if (roleCanDraft('raw_app', user, role.operatorSettings)) { + if (roleCanDraft('raw_app', caps)) { capabilities.add('write_app_draft') } - if (roleCanDraft('schedule', user, role.operatorSettings)) { + if (caps.flows === 'full') { + capabilities.add('write_inline_flow_code') + } + if (caps.apps === 'full') { + capabilities.add('write_inline_app_code') + } + if (roleCanDraft('schedule', caps)) { capabilities.add('write_schedule_draft') } - if (roleCanDraft('trigger', user, role.operatorSettings)) { + if (roleCanDraft('trigger', caps)) { capabilities.add('write_trigger_draft') } - if (roleCanDraft('resource', user, role.operatorSettings)) { + if (roleCanDraft('resource', caps)) { capabilities.add('write_resource_draft') } - if (roleCanDraft('variable', user, role.operatorSettings)) { + if (roleCanDraft('variable', caps)) { capabilities.add('write_variable_draft') } - if (authorsCode) { + if (roleCanAuthor('script', caps)) { capabilities.add('run_preview') capabilities.add('manage_code') } - if (authorsFlows) { + if (roleCanAuthor('flow', caps)) { capabilities.add('run_flow_preview') capabilities.add('manage_flows') } - if (roleCanAuthor('raw_app', user, role.operatorSettings)) { + if (roleCanAuthor('raw_app', caps)) { capabilities.add('manage_apps') } - if (roleCanAuthor('schedule', user, role.operatorSettings)) { + if (roleCanAuthor('schedule', caps)) { capabilities.add('manage_schedules') } - if (roleCanAuthor('trigger', user, role.operatorSettings)) { + if (roleCanAuthor('trigger', caps)) { capabilities.add('manage_triggers') } - // No operator term: the rules are their own gate, and the handlers that also refuse - // operators say so through `manage_code`. Admins bypass the rules inside the check. + // No role term: the rules are their own gate, and the handlers that also refuse a role + // say so through `manage_code`. Admins bypass the rules inside the check. if (role.deployRulesPass) { capabilities.add('deploy') } @@ -103,12 +108,53 @@ export function capabilitiesForRole(role: { return capabilities } +/** Whether `rulesets` make a session read-only. `DisableDirectDeployment` holds everyone, admins + * and bypassers included, since production changes go through its dev workspace or a fork; + * `RestrictDeployToDeployers` alone leaves its users their drafts. Unreadable rules protect too: + * the server holds deploys to the rule but not drafts. */ +function protects(rulesets: ProtectionRuleset[] | undefined): boolean { + return !rulesets || isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment') +} + +// The session UI asks this from every preview tab, the composer and the picker, and the rules +// fetch behind it is not cached, so they share one verdict per workspace for a minute. +const READ_ONLY_TTL_MS = 60_000 +const readOnlyVerdicts = new Map<string, { at: number; verdict: Promise<boolean> }>() +const settledVerdicts = new Map<string, { at: number; readOnly: boolean }>() + +/** The read-only verdict alone, for the UI around a session. Fails closed as the chat does; a + * failed read is not kept, so the next ask reads the rules again. */ +export function isReadOnlySessionWorkspace(workspace: string): Promise<boolean> { + const cached = readOnlyVerdicts.get(workspace) + if (cached && Date.now() - cached.at < READ_ONLY_TTL_MS) return cached.verdict + const at = Date.now() + const verdict = readProtectionRulesForWorkspace(workspace).then((rulesets) => { + if (!rulesets) readOnlyVerdicts.delete(workspace) + else settledVerdicts.set(workspace, { at, readOnly: protects(rulesets) }) + return protects(rulesets) + }) + readOnlyVerdicts.set(workspace, { at, verdict }) + return verdict +} + +/** The verdict read for `workspace` within the minute, without asking: what the UI stands on + * while a fresh component waits for its own ask. */ +export function settledReadOnlyVerdict(workspace: string): boolean | undefined { + const settled = settledVerdicts.get(workspace) + return settled && Date.now() - settled.at < READ_ONLY_TTL_MS ? settled.readOnly : undefined +} + export async function resolveSessionAccess(workspace: string): Promise<SessionAccess> { - // Shares the 5-minute memo with the identity the same pre-flight resolves beside this - // one, so a send costs one `whoami` rather than two, at the cost of a role changed - // elsewhere landing within that window rather than on the very next message. - // `lookup_failed` covers a rejected request AND a body too malformed to map. - const lookup = await getWorkspaceRole(workspace) + const [rulesets, lookup] = await Promise.all([ + // Not the memoized verdict above: the chat's toolset follows a rule change on the next send. + readProtectionRulesForWorkspace(workspace), + // Shares the 5-minute memo with the identity the same pre-flight resolves beside this + // one, so a send costs one `whoami` rather than two, at the cost of a role changed + // elsewhere landing within that window rather than on the very next message. + // `lookup_failed` covers a rejected request AND a body too malformed to map. + getWorkspaceRole(workspace) + ]) + if (protects(rulesets)) return USE_MODE_ACCESS if (lookup.kind !== 'resolved') { return fullSessionAccess() } @@ -116,8 +162,10 @@ export async function resolveSessionAccess(workspace: string): Promise<SessionAc return capabilitiesForRole({ isAdmin: !!me.is_admin || !!me.is_super_admin, - operator: !!me.operator, - deployRulesPass: (await checkDeployRules(workspace, me)).ok, - operatorSettings: get(userWorkspaces).find((w) => w.id === workspace)?.operator_settings + deployRulesPass: (await checkDeployRules(workspace, me, rulesets)).ok, + capabilities: capabilitiesIn( + me, + get(userWorkspaces).find((w) => w.id === workspace) + ) }) } diff --git a/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts b/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts index d3f5bfbb05..15f5e7a246 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts @@ -28,7 +28,16 @@ import { pipelineTools } from '../pipeline/core' import { assembleGlobalSystemMessage, assembleGlobalTools } from './globalAssembly' import { filterSessionTools, sessionToolAllowed } from './sessionToolset' import { capabilitiesForRole, fullSessionAccess } from './sessionAccess' -import type { SessionAccess, SessionCapability, SessionTool } from '../sessionCapabilities' +import { + canBuild, + USE_MODE_ACCESS, + type SessionAccess, + type SessionCapability, + type SessionTool +} from '../sessionCapabilities' +import { FULL_CAPABILITIES, legacyOperatorCapabilities } from '$lib/roleCapabilities' +import { buildsAnything } from '$lib/editRights' +import type { AuthorLevel, OperatorSettings, RoleCapabilities } from '$lib/gen' const ASSEMBLY_OPTS = { previewTools: true, @@ -68,40 +77,49 @@ function shippedSessionTools(access: SessionAccess) { return filterSessionTools(assembleGlobalTools(ASSEMBLY_OPTS), access) } +/** A session that can change the workspace, holding `capabilities` besides. */ function accessWith(capabilities: SessionCapability[]): SessionAccess { - return new Set(capabilities) + return new Set<SessionCapability>(['modify_workspace', ...capabilities]) } -/** The profiles a real session can hold, keyed for the test name, over every combination - * of the role facts `capabilitiesForRole` reads. */ -const REACHABLE_PROFILES = [ - ...new Map( - [false, true].flatMap((isAdmin) => - [false, true].flatMap((operator) => - // `checkDeployRules` bypasses on admin, so an admin has only the one outcome. - (isAdmin ? [true] : [false, true]).flatMap((deployRulesPass) => - // The operator rights a workspace can set: none, either builder right or both, either lock, both locks. - [ - undefined, - { builder_flows: true }, - { builder_apps: true }, - { builder_flows: true, builder_apps: true }, - { manage_schedules: false }, - { manage_triggers: false }, - { manage_schedules: false, manage_triggers: false } - ].map((operatorSettings) => { - const access = capabilitiesForRole({ - isAdmin, - operator, - deployRulesPass, - operatorSettings - }) - return [[...access].sort().join(',') || 'none', access] as const - }) +const LEVELS: AuthorLevel[] = ['none', 'compose', 'full'] + +/** Every role a workspace can define, over the capabilities `capabilitiesForRole` reads: `full` + * flows or apps require `code`, as `RoleCapabilities::validate` refuses otherwise. */ +const ROLES: RoleCapabilities[] = [false, true] + .flatMap((code) => + LEVELS.flatMap((flows) => + LEVELS.flatMap((apps) => + [false, true].flatMap((manage_schedules) => + [false, true].map((manage_triggers) => ({ + ...FULL_CAPABILITIES, + code, + flows, + apps, + manage_schedules, + manage_triggers + })) ) ) ) - ).entries() + ) + .filter((c) => c.code || (c.flows !== 'full' && c.apps !== 'full')) + +/** The profiles a real session can hold, keyed for the test name, over every combination + * of the role facts `capabilitiesForRole` reads, and the read-only one. */ +const REACHABLE_PROFILES: [string, SessionAccess][] = [ + ...new Map( + [false, true].flatMap((isAdmin) => + // `checkDeployRules` bypasses on admin, so an admin has only the one outcome. + (isAdmin ? [true] : [false, true]).flatMap((deployRulesPass) => + ROLES.map((capabilities) => { + const access = capabilitiesForRole({ isAdmin, deployRulesPass, capabilities }) + return [[...access].sort().join(',') || 'none', access] as const + }) + ) + ) + ).entries(), + ['read-only', USE_MODE_ACCESS] ] /** One per branch of getSessionContextPromptSection — each words the deploy target @@ -125,6 +143,15 @@ describe('session tool policies', () => { filtered.forEach((tool, i) => expect(tool).toBe(tools[i])) }) + // The mode picker reads the role and the toolset reads the access built from it: if they + // disagree, the picker offers Build while the chat holds only Use's tools, or the reverse. + it('agrees with the role on whether the session can build', () => { + for (const capabilities of ROLES) { + const access = capabilitiesForRole({ isAdmin: false, deployRulesPass: true, capabilities }) + expect(canBuild(access)).toBe(buildsAnything(capabilities)) + } + }) + it('withholds a tool that arrives without a policy', () => { expect(sessionToolAllowed({ def: globalTools[0].def }, fullSessionAccess())).toBe(false) }) @@ -203,6 +230,17 @@ describe('session tool policies', () => { expect((original.def.function.parameters as any).properties.type.enum).toContain('script') }) + // Keyed on the tags, so a tool added untagged stays out of a production workspace. + it('ships a read-only session the reads and the deployed runs, and nothing that writes', () => { + const shipped = shippedSessionTools(USE_MODE_ACCESS) + expect(shipped.filter((t) => !t.planModeSafe && !t.readOnlySafe)).toEqual([]) + const names = shipped.map((t) => t.def.function.name) + expect(names).toEqual(expect.arrayContaining(['read_workspace_item', 'list_runs', 'run_flow'])) + for (const write of ['write_script', 'test_run_script', 'deploy_workspace_item']) { + expect(names).not.toContain(write) + } + }) + it('offers the workspace settings tools to admins only', () => { const settingsTools = ['get_workspace_settings', 'set_workspace_settings'] for (const [, access] of REACHABLE_PROFILES) { @@ -306,14 +344,13 @@ describe('session tool policies', () => { // The operator's own rights outrun the chat's tools: what they schedule in the UI must not // be sent to an admin. it("sends an operator to the UI for what their role allows and the chat's tools do not", () => { - const prompt = (operatorSettings: { manage_schedules?: boolean }): string => + const prompt = (operatorSettings: Partial<OperatorSettings>): string => prepareGlobalSystemMessage(undefined, { user: { username: 'op' }, access: capabilitiesForRole({ isAdmin: false, - operator: true, deployRulesPass: true, - operatorSettings + capabilities: legacyOperatorCapabilities(operatorSettings as OperatorSettings) }) }).content as string diff --git a/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts b/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts index 0d8f8753a2..7a867f0c01 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts @@ -1,10 +1,12 @@ import type { ChatCompletionFunctionTool } from 'openai/resources/index.mjs' -import type { SessionAccess, SessionToolPolicy } from '../sessionCapabilities' +import { isReadOnlyAccess, type SessionAccess, type SessionToolPolicy } from '../sessionCapabilities' type FilterableTool = { def: ChatCompletionFunctionTool requires?: SessionToolPolicy kindRequires?: Readonly<Partial<Record<string, SessionToolPolicy>>> + planModeSafe?: boolean + readOnlySafe?: boolean } const satisfies = (policy: SessionToolPolicy, access: SessionAccess) => @@ -13,7 +15,15 @@ const satisfies = (policy: SessionToolPolicy, access: SessionAccess) => /** Fails closed: every array that feeds a session is typed to declare `requires`, so a tool * without one arrived some other way, and leaking it is the worse of the two answers. */ export function sessionToolAllowed(tool: FilterableTool, access: SessionAccess): boolean { - return tool.requires ? satisfies(tool.requires, access) : false + if (!tool.requires || !satisfies(tool.requires, access)) return false + return !isReadOnlyAccess(access) || readOnlyToolAllowed(tool) +} + +/** A read-only session keeps the reads `planModeSafe` already marks, plus what opts in with + * `readOnlySafe`. Keyed on the tags rather than a list of writes, so a tool added untagged + * stays out of a production workspace until someone decides it belongs there. */ +function readOnlyToolAllowed(tool: FilterableTool): boolean { + return tool.planModeSafe === true || tool.readOnlySafe === true } /** Filter an assembled toolset, and cut each kind-taking tool's `type` enum to the kinds diff --git a/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts b/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts index c53aa1b7d1..6368a27e24 100644 --- a/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts +++ b/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts @@ -239,6 +239,7 @@ function variableDraftToWorkspaceItem(path: string, draft: VariableDraftState): account: draft.account, is_oauth: draft.is_oauth, expires_at: draft.expires_at, + value_valid_until: draft.value_valid_until, labels: draft.labels, ws_specific: draft.wsSpecific }, diff --git a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts index d08fe4fd58..949a016b65 100644 --- a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts +++ b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts @@ -108,6 +108,7 @@ export type VariableDraftState = { account?: number is_oauth?: boolean expires_at?: string + value_valid_until?: string } export type WorkspaceItem = { diff --git a/frontend/src/lib/components/copilot/chat/messageDraft.svelte.ts b/frontend/src/lib/components/copilot/chat/messageDraft.svelte.ts index b64711dccf..01d815b3ef 100644 --- a/frontend/src/lib/components/copilot/chat/messageDraft.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/messageDraft.svelte.ts @@ -29,6 +29,9 @@ export interface DraftSnapshot { blobs: AttachedBlob[] } +/** Everything a draft carries besides its text. */ +export type DraftAttachments = Omit<DraftSnapshot, 'text'> + export class MessageDraft { text = $state('') pastes = $state<PasteAttachment[]>([]) diff --git a/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts b/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts index 01e5040040..c4f4ab6355 100644 --- a/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts @@ -21,8 +21,8 @@ import { normalizeChangeNote } from './artifacts/artifactLimits' import { currentVersion } from './artifacts/artifactsDB' import { type SessionArtifactsStore } from './artifacts/artifactsState.svelte' -/** What plan mode needs from the chat it runs in: it reads the autonomy state and asks for - * the two changes it can cause, rather than owning any of it. */ +/** What plan mode needs from the chat it runs in: it reads the work mode and the autonomy + * state and asks for the two changes it can cause, rather than owning any of it. */ export interface PlanModeHost { /** Offered in this chat *and* selected. */ readonly active: boolean @@ -36,8 +36,8 @@ export interface PlanModeHost { readonly artifacts: SessionArtifactsStore openArtifact(id: string, name: string, version: ArtifactVersionTarget): void enter(): void - /** Hand the posture back to whatever preceded plan mode. */ - restore(): void + /** Move to Build, where the approved plan is carried out. */ + build(): void } /** Read off the write that proposed the plan, so nothing re-reads and races a later one. */ @@ -162,7 +162,7 @@ export class PlanModeController { } // Only to the round this approval belongs to: ending a re-entered round would drop the // user out of a planning posture they just chose. - if (this.#host.active && epoch === this.#epoch) this.#host.restore() + if (this.#host.active && epoch === this.#epoch) this.#host.build() return PLAN_MODE_MESSAGES.approvedWithDoc } } diff --git a/frontend/src/lib/components/copilot/chat/planModeController.test.ts b/frontend/src/lib/components/copilot/chat/planModeController.test.ts index 4e5438b906..0b6f1e5c5e 100644 --- a/frontend/src/lib/components/copilot/chat/planModeController.test.ts +++ b/frontend/src/lib/components/copilot/chat/planModeController.test.ts @@ -26,7 +26,7 @@ describe('PlanModeController', () => { let sessionId: string let docs: Doc[] let openArtifact: ReturnType<typeof vi.fn> - let restore: ReturnType<typeof vi.fn> + let build: ReturnType<typeof vi.fn> let artifacts: any let controller: PlanModeController @@ -36,7 +36,7 @@ describe('PlanModeController', () => { sessionId = 'session-1' docs = [] openArtifact = vi.fn() - restore = vi.fn(() => { + build = vi.fn(() => { active = false }) artifacts = { @@ -89,7 +89,7 @@ describe('PlanModeController', () => { enter: () => { active = true }, - restore + build } controller = new PlanModeController(host) controller.startRound() @@ -140,7 +140,7 @@ describe('PlanModeController', () => { expect(docs[0]).toMatchObject({ version: 2, approvedVersion: 1 }) }) - it('restores posture only after proposal and approval pointer are durable', async () => { + it('moves to Build only after proposal and approval pointer are durable', async () => { await propose('# Durable\n\nBuild it.') const result = await controller.exitTool.fn({ args: { summary: '# Durable\n\nBuild it.' }, @@ -151,7 +151,7 @@ describe('PlanModeController', () => { }) expect(docs[0].approvedVersion).toBe(1) - expect(restore).toHaveBeenCalledOnce() + expect(build).toHaveBeenCalledOnce() expect(result).toBe(PLAN_MODE_MESSAGES.approvedWithDoc) }) @@ -167,7 +167,7 @@ describe('PlanModeController', () => { }) expect(active).toBe(true) - expect(restore).not.toHaveBeenCalled() + expect(build).not.toHaveBeenCalled() expect(result).toBe(PLAN_MODE_MESSAGES.persistenceFailed) }) @@ -214,7 +214,7 @@ describe('PlanModeController', () => { it('refuses a second hand-over from the batch that already ended plan mode', async () => { // One response can carry two exit_plan_mode calls, and the tool list they run against is - // snapshotted before the first one restores the posture. Under YOLO nothing asks, so the + // snapshotted before the first one moves the session to Build. Under YOLO nothing asks, so the // stale call would write its own summary and stamp the user's approval on a plan no card // ever showed them. const frozenTools = [controller.exitTool] @@ -294,6 +294,6 @@ describe('PlanModeController', () => { controller.startRound() await approval expect(active).toBe(true) - expect(restore).not.toHaveBeenCalled() + expect(build).not.toHaveBeenCalled() }) }) diff --git a/frontend/src/lib/components/copilot/chat/planModeMessages.ts b/frontend/src/lib/components/copilot/chat/planModeMessages.ts index 85710d0c54..dff3ec1c13 100644 --- a/frontend/src/lib/components/copilot/chat/planModeMessages.ts +++ b/frontend/src/lib/components/copilot/chat/planModeMessages.ts @@ -9,12 +9,9 @@ export const PLAN_MODE_MESSAGES = { blockedLabel: 'Blocked in plan mode', blockedResult: 'Blocked: plan mode is active. Put this change in your plan; call exit_plan_mode when ready for approval.', - /** Sits beside the autonomy picker while plan mode holds. The picker's tooltip carries - * the rest, so this states only the constraint. */ - modeNote: 'Read-only', /** Refuses a pending run form. Its own string because nothing is settled: the form stays * live, so this names the way out rather than telling the user their run was blocked. */ - runFormRefused: 'Plan mode is read-only — switch it off to run this script.', + runFormRefused: 'Plan mode runs nothing — switch to Use, or Use & build, to run this script.', // One pair for both artifact tools: the fact and the way forward are the same whether the // model tried to mint the plan or to rewrite it, and the generic refusal above ("put this // change in your plan") reads as nonsense for a call that writes a document. @@ -46,7 +43,7 @@ export const PLAN_MODE_MESSAGES = { `The plan is too large to save (${bytes} bytes, limit ${MAX_ARTIFACT_BYTES}) and was not shown to the user. Cut it to the decisions and the steps — name the files you will touch instead of quoting them — and call exit_plan_mode again.`, // What the version picker shows for a revision the model did not label. revisionNote: 'Revised the plan', - // States the outcome, not a decision: pressing Stop and moving the autonomy picker out of + // States the outcome, not a decision: pressing Stop and moving the mode picker out of // plan mode both land here too, and this text persists in the transcript — asserting a // rejection would open the next turn interrogating a user who never made one. exitDeclined: diff --git a/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts index 1e22903e9b..7e80854a01 100644 --- a/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts @@ -1,4 +1,5 @@ import { AIAutonomyMode } from './AIChatManager.svelte' +import { AIWorkMode } from './workMode' import type { ChatViewHost } from './chatViewHost' import type { DisplayMessage } from './shared' import { AttachedFilesStore } from './files/attachedFiles.svelte' @@ -42,6 +43,7 @@ export function readOnlyChatViewHost(options: { sendRequest: async () => false, cancel: noop, setAiChatInput: noop, + releaseAiChatInput: noop, queuedMessage: '', queuedContext: undefined, queuedImages: [], @@ -74,6 +76,9 @@ export function readOnlyChatViewHost(options: { tools: [], autonomyMode: AIAutonomyMode.DEFAULT, setAutonomyMode: noop, + workModesAvailable: false, + workMode: AIWorkMode.BUILD, + setWorkMode: noop, autoAcceptEditsActive: false, autoAcceptEditsAvailable: false, autoAcceptToolConfirmationsAvailable: false, diff --git a/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts b/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts index b06c41850e..1afe78bcfe 100644 --- a/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts +++ b/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts @@ -9,49 +9,81 @@ import type { Tool } from './shared' * what the model is offered and guarantees nothing. */ export type SessionCapability = - /** Passes drafts.rs `require_can_write_path` for a draft of any kind. A tool writing only - * schedule or trigger drafts requires the narrower capability below instead, which an - * operator can hold. */ + /** Passes drafts.rs `require_can_write_path` for a script draft: the role's `code`. A tool + * writing another kind requires that kind's capability below instead. */ | 'write_draft' - /** Passes `require_can_write_path` for a flow draft, which an operator also passes where the - * workspace grants `builder_flows`. The server then refuses a draft carrying inline code. */ + /** Passes `require_can_write_path` for a flow draft: `flows` at `compose` or above. At + * `compose` the server then refuses a draft carrying inline code. */ | 'write_flow_draft' - /** The same for a raw app draft, under `builder_apps`. */ + /** The same for a raw app draft, under `apps`. */ | 'write_app_draft' - /** Passes `require_can_write_path` for a schedule draft: everyone `write_draft` covers, and an - * operator unless the workspace set `manage_schedules` to false. */ + /** Inline code in a flow draft: `flows` at `full`. At `compose` the server validates the draft + * as a pure composition, even for a role that may write scripts. */ + | 'write_inline_flow_code' + /** Inline and hub runnables in an app draft: `apps` at `full`. */ + | 'write_inline_app_code' + /** Passes `require_can_write_path` for a schedule draft: the role's `manage_schedules`. */ | 'write_schedule_draft' /** The same for a trigger draft, read from `manage_triggers`. */ | 'write_trigger_draft' - /** Passes `require_can_write_path` for a resource draft, which every operator does. */ + /** Passes `require_can_write_path` for a resource draft, which every role does. */ | 'write_resource_draft' /** The same for a variable draft. */ | 'write_variable_draft' - /** Passes the operator refusal jobs.rs `run_preview_*` makes before starting a job. */ + /** Passes the `code` refusal jobs.rs `run_preview_*` makes before starting a job. */ | 'run_preview' - /** Passes `run_preview_flow`'s `check_operator_can_build_flows`: composed flows only, for an - * operator with `builder_flows`. */ + /** Passes `run_preview_flow`'s `check_operator_can_build`: composed flows only at `compose`. */ | 'run_flow_preview' /** Passes `check_deploy_rules`. */ | 'deploy' - /** Passes the operator refusal the script handlers make before creating or + /** Passes the `code` refusal the script handlers make before creating or * deleting one. The same condition as `run_preview` today, but another handler family's * check, so each follows its own gate if the two ever diverge. */ | 'manage_code' - /** Passes the flow handlers' `check_operator_can_build_flows`. */ + /** Passes the flow handlers' `check_operator_can_build`. */ | 'manage_flows' - /** Passes the raw app handlers' `check_operator_can_build`, read from `builder_apps`. */ + /** Passes the raw app handlers' `check_operator_can_build`, read from `apps`. */ | 'manage_apps' - /** Passes `gate_operator_writes` on the schedule router: withheld only from an operator whose - * workspace set `operator_settings.manage_schedules` to false. */ + /** Passes `gate_operator_writes` on the schedule router: the role's `manage_schedules`. */ | 'manage_schedules' /** The same gate on the trigger routers, read from `manage_triggers`. */ | 'manage_triggers' /** Passes `require_admin`. */ | 'admin' + /** Held by every role. A read-only session, in a protected workspace or in Use mode, lacks it + * and ships only the tools `readOnlyToolAllowed` admits. */ + | 'modify_workspace' export type SessionAccess = ReadonlySet<SessionCapability> +/** Whether `access` is a read-only session. `undefined` access answers false, as the toolset + * filter does. */ +export function isReadOnlyAccess(access: SessionAccess | undefined): boolean { + return !!access && !access.has('modify_workspace') +} + +/** What a session in Use mode holds whatever the user's role: nothing, as in a protected + * workspace. Fixed rather than narrowed from the resolved access, so Use ships no write while + * that check is still in flight. */ +export const USE_MODE_ACCESS: SessionAccess = new Set() + +/** `buildsAnything`, read off a session's access. `undefined` access answers true, as the + * toolset filter does. */ +export function canBuild(access: SessionAccess | undefined): boolean { + return ( + !access || + ( + [ + 'write_draft', + 'write_flow_draft', + 'write_app_draft', + 'write_schedule_draft', + 'write_trigger_draft' + ] as const + ).some((c) => access.has(c)) + ) +} + /** * The capabilities without which a tool's call cannot succeed — usually because the * backend refuses it, occasionally because only that capability produces the tool's @@ -96,4 +128,7 @@ export type SessionTool<T> = Tool<T> & { * tool is either too strict or too loose: what each kind's handler needs. A session is * offered only the kinds it can land, and the rest never appear in the schema it sees. */ kindRequires?: Readonly<Partial<Record<string, SessionToolPolicy>>> + /** Ships in a read-only session although it is not `planModeSafe`: a view tool that opens + * no editor there, or a run of a deployed item, which a production workspace is for. */ + readOnlySafe?: boolean } diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index 71ef91a0b7..13623dc73e 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -8,6 +8,7 @@ import type { UserDraftItemKind } from '$lib/gen' // The gate's two refusals, from a module that holds prose and one size limit: under the // shallow-import rule below, the rest of plan mode is not reachable from here. import { PLAN_MODE_MESSAGES } from './planModeMessages' +import { USE_MODE_WITHDRAWN } from './workMode' import { NONE, type SessionTool } from './sessionCapabilities' import { integrationDisplayName } from '$lib/components/resourceTypeDisplay' // Import-free leaf, so it satisfies the shallow-import rule below. @@ -955,6 +956,7 @@ type ToolCallStatus = | 'declined' | 'rejected' | 'blocked_plan_mode' + | 'withdrawn' | 'held_for_instructions' /** Re-reads the chat loop's current tools and helpers. A call earlier in the same @@ -1038,6 +1040,27 @@ export async function processToolCall<T>({ } } + const withdrawnBlock = (): ChatCompletionMessageParam | undefined => { + if (!tool || !toolCallbacks.isToolWithdrawn?.(tool.def.function.name)) return undefined + logToolOutcome('withdrawn') + toolCallbacks.setToolStatus(toolCall.id, { + content: USE_MODE_WITHDRAWN.label, + parameters: args, + isLoading: false, + isQueued: false, + isStreamingArguments: false, + error: USE_MODE_WITHDRAWN.result, + needsConfirmation: false, + showDetails: tool.showDetails, + autoCollapseDetails: tool.autoCollapseDetails + }) + return { + role: 'tool' as const, + tool_call_id: toolCall.id, + content: USE_MODE_WITHDRAWN.result + } + } + const preConfirmationBlock = planModeBlock() if (preConfirmationBlock) { return preConfirmationBlock @@ -1157,7 +1180,7 @@ export async function processToolCall<T>({ } } - const postConfirmationBlock = planModeBlock() + const postConfirmationBlock = planModeBlock() ?? withdrawnBlock() if (postConfirmationBlock) { return postConfirmationBlock } @@ -1456,6 +1479,10 @@ export interface ToolCallbacks { shouldAutoAcceptToolConfirmations?: (toolName?: string) => boolean isPlanModeActive?: () => boolean onToolBlockedByPlanMode?: () => void + /** Whether the session has stopped shipping this tool since the call was made, as a switch to + * Use does to every write. Asked once a confirmation or a run form has been answered, since + * the switch can land while either waits. */ + isToolWithdrawn?: (toolName: string) => boolean requestUserQuestion?: ( toolId: string, question: UserQuestionDisplay diff --git a/frontend/src/lib/components/copilot/chat/skills/skillResources.ts b/frontend/src/lib/components/copilot/chat/skills/skillResources.ts index d28a4d32e8..5fd7cfad37 100644 --- a/frontend/src/lib/components/copilot/chat/skills/skillResources.ts +++ b/frontend/src/lib/components/copilot/chat/skills/skillResources.ts @@ -1,5 +1,6 @@ import { ResourceService } from '$lib/gen' import { canEditItem } from '$lib/editRights' +import { capabilitiesIn } from '$lib/roleCapabilities' import { userWorkspaces, type UserExt } from '$lib/stores' import { get } from 'svelte/store' @@ -57,7 +58,10 @@ export type SkillListing = { skills: SkillResource[]; truncated: boolean } * the shared `canEditItem` rather than reading `extra_perms` alone. */ export async function listSkillResources(workspace: string, user?: UserExt): Promise<SkillListing> { if (!workspace) return { skills: [], truncated: false } - const operatorSettings = get(userWorkspaces).find((w) => w.id === workspace)?.operator_settings + const caps = capabilitiesIn( + user, + get(userWorkspaces).find((w) => w.id === workspace) + ) const rows: SkillResource[] = [] for (let page = 1; page <= MAX_SKILLS_PAGES; page++) { const resources = await ResourceService.listResource({ @@ -72,7 +76,7 @@ export async function listSkillResources(workspace: string, user?: UserExt): Pro name: skillNameFromPath(r.path), description: r.description ?? '', editedAt: r.edited_at, - canWrite: canEditItem('resource', r.path, r.extra_perms, user, operatorSettings) + canWrite: canEditItem('resource', r.path, r.extra_perms, user, caps) })) ) if (resources.length < SKILLS_PAGE_SIZE) return { skills: rows, truncated: false } diff --git a/frontend/src/lib/components/copilot/chat/starter/ComposerSuggestions.svelte b/frontend/src/lib/components/copilot/chat/starter/ComposerSuggestions.svelte new file mode 100644 index 0000000000..6d7dc379a4 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/ComposerSuggestions.svelte @@ -0,0 +1,37 @@ +<script lang="ts"> + import { Pencil, Play } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import type { ComposerSuggestion } from './starterPrompts.svelte' + + let { + suggestions, + onPick, + wrap = false + }: { + suggestions: ComposerSuggestion[] + onPick: (prompt: string) => void + /** Wrap onto more lines instead of one row that scrolls sideways. */ + wrap?: boolean + } = $props() +</script> + +<!-- Unwrapped, one row whatever the width: it scrolls sideways and fades out at its end, so the + page under the composer does not move with the window width. --> +<div + class="flex flex-row items-center gap-1.5 {wrap + ? 'flex-wrap' + : 'overflow-x-auto no-scrollbar [mask-image:linear-gradient(90deg,#000_calc(100%-24px),transparent)]'}" +> + {#each suggestions.slice(0, 4) as suggestion (suggestion.label)} + <Button + variant="default" + unifiedSize="sm" + btnClasses="!rounded-full !text-xs !text-secondary !font-normal shrink-0" + title={suggestion.mode === 'use' ? 'Use: look, ask or run' : 'Build: create or change'} + startIcon={{ icon: suggestion.mode === 'use' ? Play : Pencil, classes: 'text-hint' }} + onClick={() => onPick(suggestion.prompt)} + > + {suggestion.label} + </Button> + {/each} +</div> diff --git a/frontend/src/lib/components/copilot/chat/starter/SessionGreeting.svelte b/frontend/src/lib/components/copilot/chat/starter/SessionGreeting.svelte new file mode 100644 index 0000000000..8bf5a0170b --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/SessionGreeting.svelte @@ -0,0 +1,28 @@ +<script lang="ts"> + import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' + import { takeFirstVisit, timeOfDayGreeting } from './greeting' + + // `name` is the full name when the account has one; the greeting uses the first word. + const userName = $derived($userStore?.name?.trim().split(/\s+/)[0] || $userStore?.username) + const workspaceName = $derived( + $userWorkspaces.find((w) => w.id === $workspaceStore)?.name ?? $workspaceStore + ) + // Read once the membership for this workspace has loaded: `userStore` still describes the + // previous workspace for a moment after a switch. + const firstVisit = $derived( + !!$workspaceStore && + $userStore?.workspace_id === $workspaceStore && + takeFirstVisit($workspaceStore, $userStore.created_at) + ) + const greeting = timeOfDayGreeting() +</script> + +<div class="flex items-center justify-center gap-2 mb-4"> + <p class="text-center font-regular text-3xl"> + {#if firstVisit} + Welcome to {workspaceName}{userName ? `, ${userName}` : ''} + {:else} + {greeting}{userName ? `, ${userName}` : ''} + {/if} + </p> +</div> diff --git a/frontend/src/lib/components/copilot/chat/starter/composerCollapse.ts b/frontend/src/lib/components/copilot/chat/starter/composerCollapse.ts new file mode 100644 index 0000000000..d21f04f1ba --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/composerCollapse.ts @@ -0,0 +1,11 @@ +// The layers the composer's controls open render in portals under <body>, outside the +// composer's own element: DropdownV2 menus, melt popovers, and the settings modals. Not +// `[data-menu]`: DropdownV2 puts it on its trigger too, and Home has triggers everywhere. +const OVERLAY = '[data-melt-dropdown-menu], [data-melt-popover-content], [role="dialog"]' + +/** Whether a pointer-down outside the composer still leaves it open: it landed in a menu or + * dialog, or one is open, and the press is closing it rather than leaving the composer. */ +export function isComposerOverlay(target: EventTarget | null): boolean { + if (target instanceof Element && target.closest(OVERLAY)) return true + return document.querySelector(OVERLAY) !== null +} diff --git a/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.test.ts b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.test.ts new file mode 100644 index 0000000000..1c74750a43 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest' +import { composerSuggestions, type ComposerRole } from './composerSuggestions' + +const developer: ComposerRole = { operator: false, workspaceAdmin: false, instanceAdmin: false } +const operator: ComposerRole = { ...developer, operator: true } +const workspaceAdmin: ComposerRole = { ...developer, workspaceAdmin: true } + +const myDraft = { kind: 'flow', path: 'f/a/sync', name: 'Sync' } +const sharedFlow = { kind: 'flow', path: 'f/billing/charge', name: 'Charge customers' } +const favorite = { kind: 'script', path: 'f/ops/check_ssl', name: 'Check SSL expiry' } +const script = favorite +const app = { kind: 'app', path: 'f/ops/console', name: 'Ops console' } +const folderItem = sharedFlow +const database = { type: 'postgresql', path: 'f/data/main_db', name: 'main_db' } +const slack = { type: 'slack', path: 'f/team/slack', name: 'slack' } + +const labels = (...args: Parameters<typeof composerSuggestions>) => + composerSuggestions(...args).map((s) => s.label) + +describe('composerSuggestions', () => { + it('offers the build examples in an empty workspace, but not to an operator', () => { + expect(labels({ itemCount: 0 }, developer)).toEqual([ + 'Daily metrics to Slack', + 'Approve refunds in Slack', + 'Triage tickets to Slack' + ]) + expect(labels({ itemCount: 0 }, operator)).toEqual([]) + }) + + it("teaches the piece a workspace is missing first, as the reader's role allows", () => { + const fresh = { itemCount: 0, dataTables: [], database: null, channel: null } + expect(labels(fresh, workspaceAdmin)).toEqual([ + 'Set up a data table', + 'Daily metrics to Slack', + 'Approve refunds in Slack', + 'Triage tickets to Slack' + ]) + expect(labels(fresh, developer)[0]).toBe('How do I store data?') + expect(labels({ ...fresh, dataTables: ['main'] }, developer)[0]).toBe('Connect Slack') + // Past its first items a workspace may keep data and Slack where these lists don't look. + const established = { ...fresh, itemCount: 25 } + expect(labels(established, workspaceAdmin)[0]).toBe('Set up a data table') + expect(labels(established, developer)).not.toContain('How do I store data?') + expect(labels(established, developer)).not.toContain('Connect Slack') + }) + + it('builds a new workspace from its own connections, naming their paths', () => { + const s = composerSuggestions( + { itemCount: 0, dataTables: ['main'], database, channel: slack }, + developer + ) + expect(s.map((x) => [x.mode, x.label])).toEqual([ + ['build', 'Daily main_db summary to Slack'], + ['use', "What's in the main data table?"], + ['build', 'Build an app on the main data table'], + ['use', 'Post a Slack message from a script'] + ]) + expect(s[0].prompt).toContain('f/data/main_db') + expect(s[0].prompt).toContain('f/team/slack') + }) + + it("ranks the reader's own work first, then what the workspace holds, once per concept", () => { + const established = { + itemCount: 25, + sharedFlow, + favorite, + script, + app, + folderItem, + database, + channel: slack, + dataTables: ['main'] + } + expect(labels({ ...established, myDraft }, workspaceAdmin)).toEqual([ + 'Finish my draft: Sync', + "What's in the main data table?", + 'Walk me through Charge customers', + 'Run Check SSL expiry' + ]) + expect(labels(established, developer)).toEqual([ + "What's in the main data table?", + 'Walk me through Charge customers', + 'Run Check SSL expiry', + 'Add a page to Ops console' + ]) + }) + + it('keeps an operator to running and reading', () => { + expect( + labels( + { itemCount: 25, myDraft, sharedFlow, favorite, folderItem, dataTables: [], channel: null }, + operator + ) + ).toEqual([ + 'Run Check SSL expiry', + 'Walk me through Charge customers', + 'What can I run here?', + 'Who can see Charge customers?' + ]) + }) + + it('fills with the checks for the role', () => { + expect(labels({ itemCount: 10 }, workspaceAdmin)).toEqual([ + 'Check the schedules', + 'Check recent runs', + 'Check the run queue', + 'Use my scripts from Claude' + ]) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts new file mode 100644 index 0000000000..a6a6a00c90 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts @@ -0,0 +1,387 @@ +import type { StarterPrompt } from '$lib/onboardingProfile' + +/** A prompt offered under the composer: `label` is the pill, `prompt` what it puts in the + * box. `use` looks at, asks about or runs what exists; `build` creates or changes things. */ +export type ComposerSuggestion = StarterPrompt & { mode: 'use' | 'build' } + +/** What the reader may do where the session acts. An instance admin is not assumed to be an + * admin of the workspace. */ +export type ComposerRole = { operator: boolean; workspaceAdmin: boolean; instanceAdmin: boolean } + +export type ComposerItem = { kind: string; path: string; name: string } + +/** A connection the workspace holds; `type` is its resource type. */ +export type ComposerResource = { type: string; path: string; name: string } + +/** Below this many items the workspace is new enough that building leads. */ +export const FEW_ITEMS = 10 + +/** The databases whose tables the chat can read (`get_db_schema`), by resource type. */ +export const DATABASE_TYPES: Record<string, string> = { + postgresql: 'Postgres', + mysql: 'MySQL', + ms_sql_server: 'SQL Server', + snowflake: 'Snowflake', + bigquery: 'BigQuery' +} + +/** Where a job can send a message, by resource type, most preferred first. */ +export const CHANNEL_TYPES: Record< + string, + { name: string; to: string; send: string; message: string } +> = { + slack: { + name: 'Slack', + to: 'to Slack', + send: 'post it to Slack', + message: 'post a Slack message' + }, + ms_teams_webhook: { + name: 'Microsoft Teams', + to: 'to Teams', + send: 'post it to Microsoft Teams', + message: 'post a Teams message' + }, + discord_webhook: { + name: 'Discord', + to: 'to Discord', + send: 'post it to Discord', + message: 'post a Discord message' + }, + telegram: { + name: 'Telegram', + to: 'to Telegram', + send: 'send it on Telegram', + message: 'send a Telegram message' + }, + gmail: { name: 'Gmail', to: 'by email', send: 'email it', message: 'send an email' }, + smtp: { name: 'email', to: 'by email', send: 'email it', message: 'send an email' } +} + +/** What the workspace looks like now: read from the composer's item, resource and data table + * lists. An absent field fires no rule. A `null` channel and an + * empty `dataTables` mean the list answered and holds none, which fires the pills that teach + * the missing piece. */ +export type ComposerSignals = { + /** Capped at the page the list call reads. */ + itemCount?: number + /** The reader's draft among the items the list call reads, the most recently updated. */ + myDraft?: ComposerItem + /** Among the same items, the most recently updated flow outside the reader's user folder. */ + sharedFlow?: ComposerItem + /** Among the same items, the most recently updated deployed script with a main function. */ + script?: ComposerItem + /** Among the same items the reader may edit, the most recently updated full-code app. */ + app?: ComposerItem + /** Among the same items, the most recently updated AI agent. */ + agent?: ComposerItem + /** Among the same items, the most recently updated one in a folder. */ + folderItem?: ComposerItem + /** Among the same items, a script or flow the reader starred. The sidebar's favorites are + * not used: they name no workspace, so after a switch they can still be the last one's. */ + favorite?: ComposerItem + /** Among the connections the resource list reads (one page, ordered by path), the most + * recently edited database. */ + database?: ComposerResource + /** Among the same connections, the one a job would send a message through, the most + * preferred type first. */ + channel?: ComposerResource | null + /** The workspace's data tables, `main` first. */ + dataTables?: string[] +} + +/** Each example shows a different piece of Windmill: a schedule, an approval step, a webhook. */ +const BUILD_EXAMPLES: ComposerSuggestion[] = [ + { + mode: 'build', + label: 'Daily metrics to Slack', + prompt: + "Every weekday at 9am, query postgres for yesterday's signups and revenue and post a summary to the #metrics Slack channel" + }, + { + mode: 'build', + label: 'Approve refunds in Slack', + prompt: + 'Build a flow that asks for approval in Slack before issuing a refund in Stripe, and only refunds if someone approves' + }, + { + mode: 'build', + label: 'Triage tickets to Slack', + prompt: + 'When a support ticket arrives by webhook, classify its urgency with an LLM and post the urgent ones to the #support Slack channel' + } +] + +const MAX_SUGGESTIONS = 4 +const MAX_NAME = 32 + +/** Up to four suggestions that each teach one Windmill concept on the reader's own workspace, + * most pressing first: their unfinished work, the next piece the workspace is missing, then + * what it already holds, the build examples while it is empty, and checks for the role. A + * concept is offered once. A prompt names the exact item or connection path: the chat cannot + * list resources by type, so "our database" would leave it guessing. A pill reads what the + * workspace holds, never how its runs went: one that names a failure would announce it and + * offer the fix at once. The checks claim nothing, so they read the same whether or not + * anything is wrong. */ +export function composerSuggestions( + signals: ComposerSignals, + role: ComposerRole +): ComposerSuggestion[] { + const out: ComposerSuggestion[] = [] + const taught = new Set<string>() + const add = ( + concept: string, + mode: ComposerSuggestion['mode'], + label: string, + prompt: string + ) => { + if (taught.has(concept)) return + taught.add(concept) + out.push({ mode, label, prompt }) + } + const empty = signals.itemCount === 0 + const few = signals.itemCount !== undefined && signals.itemCount < FEW_ITEMS + const { database, channel, dataTables, script, sharedFlow } = signals + const dataTable = dataTables?.[0] + // Operators run what others built and author nothing. + const builder = !role.operator + + if (builder) { + const draft = signals.myDraft + if (draft) + add( + 'draft', + 'build', + `Finish my draft: ${shortName(draft.name)}`, + `Help me finish my draft of the ${draft.kind} ${draft.path}` + ) + + // The next piece the workspace is missing, one at a time: where data lives, then a + // channel to send messages through. Past its first items a workspace may keep its data + // in its own database and reach Slack through workspace settings, neither of which these + // lists see, so only the admin's data table setup is offered there. + if (dataTables?.length === 0) { + // Only an admin can set up a data table. + if (role.workspaceAdmin) + add( + 'next', + 'build', + 'Set up a data table', + 'This workspace has no data table yet. Walk me through setting one up in the workspace settings, then show me how a script writes to it.' + ) + else if (few) + add( + 'next', + 'use', + 'How do I store data?', + 'How should my scripts store data in Windmill? Explain data tables and show me how a script reads and writes one.' + ) + } + if (channel === null && few) + add( + 'next', + 'build', + 'Connect Slack', + 'Help me connect Slack to this workspace so my scripts can post messages.' + ) + } + + const send = channel ? CHANNEL_TYPES[channel.type] : undefined + const summary = () => { + if (!few || !builder || !database || !channel || !send) return + add( + 'summary', + 'build', + `Daily ${shortName(database.name)} summary ${send.to}`, + `Every weekday at 9am, summarize yesterday's activity in the ${DATABASE_TYPES[database.type]} database ${database.path} and ${send.send} with the resource ${channel.path}` + ) + } + const exploreTable = () => { + if (!dataTable) return + add( + 'datatable', + 'use', + `What's in the ${shortName(dataTable)} data table?`, + `List the tables in the data table ${dataTable} and tell me what each one holds.` + ) + } + const walkThrough = () => { + const flow = sharedFlow + if (flow) + add( + 'walk', + 'use', + `Walk me through ${shortName(flow.name)}`, + `Walk me through what the flow ${flow.path} does, step by step.` + ) + const agent = signals.agent + if (agent) + add( + 'walk', + 'use', + `Walk me through ${shortName(agent.name)}`, + `Walk me through what the AI agent ${agent.path} does and which tools it can use.` + ) + } + const run = () => { + const favorite = signals.favorite + if (favorite) + add( + 'run', + 'use', + `Run ${shortName(favorite.name)}`, + `Run the ${favorite.kind} ${favorite.path} for me.` + ) + } + const access = () => { + const item = signals.folderItem + if (item) + add( + 'access', + 'use', + `Who can see ${shortName(item.name)}?`, + `Who can see and edit the ${item.kind} ${item.path}, and why?` + ) + } + + if (role.operator) { + run() + walkThrough() + exploreTable() + if (!empty) + add( + 'operator', + 'use', + 'What can I run here?', + 'Which scripts and flows can I run in this workspace, and what does each one do?' + ) + access() + } else { + summary() + exploreTable() + walkThrough() + run() + const app = signals.app + if (app) + add( + 'app', + 'build', + `Add a page to ${shortName(app.name)}`, + `Add a page to the app ${app.path}, and ask me what it should show.` + ) + else if (dataTable) + add( + 'app', + 'build', + `Build an app on the ${shortName(dataTable)} data table`, + `Build a full-code app to browse and edit the rows of a table in the data table ${dataTable}.` + ) + if (channel && send) + add( + 'channel', + 'use', + `${capitalize(send.message)} from a script`, + `Show me how a script uses the resource ${channel.path} to ${send.message}, with a short example.` + ) + if (database?.type === 'postgresql') + add( + 'postgres', + 'build', + `React to new rows in ${shortName(database.name)}`, + `Run a script whenever a row is inserted into a table of the Postgres database ${database.path}, and explain how Postgres triggers work.` + ) + if (script) { + add( + 'endpoint', + 'build', + `Make ${shortName(script.name)} an API endpoint`, + `Expose the script ${script.path} as an HTTP API endpoint that requires a Windmill token, and show me how to call it.` + ) + if (few) + add( + 'schedule', + 'build', + `Run ${shortName(script.name)} every morning`, + `Run the script ${script.path} every weekday at 9am. Ask me for any input it needs, and explain how schedules work.` + ) + } + if (sharedFlow) + add( + 'webhook', + 'use', + `Call ${shortName(sharedFlow.name)} by webhook`, + `How do I start the flow ${sharedFlow.path} from another app with its webhook? Show me the URL and an example request.` + ) + access() + // While the workspace is new; an empty one needs its build examples more. + if (few && !empty) + add( + 'secret', + 'build', + 'Store an API key as a secret', + 'I have an API key my scripts need. Store it as a secret and show me how a script reads it with wmill.getVariable.' + ) + if (channel && send) + add( + 'hub', + 'use', + `Find Hub scripts for ${send.name}`, + `Find scripts on the Windmill Hub for ${send.name} that I could use with the resource ${channel.path}.` + ) + } + + if (empty && builder) { + const [dailyMetrics, ...others] = BUILD_EXAMPLES + out.push(...(taught.has('summary') ? others : [dailyMetrics, ...others])) + } + + // A workspace with nothing in it has nothing to check yet. Keep these to what the chat's + // tools can answer: its run listing has no date filter and stops at 100 runs, so a prompt + // naming a period ("today", "this week") gets a guess. + if (!empty) { + if (role.instanceAdmin) + add( + 'workers', + 'use', + 'Check worker health', + 'Are the workers healthy and keeping up with the queue? Compare how long jobs wait before they start with how busy each worker group is.' + ) + if (role.workspaceAdmin) + add( + 'schedules', + 'use', + 'Check the schedules', + 'Do any schedules in this workspace keep failing? If so, which ones and why?' + ) + add( + 'runs', + 'use', + 'Check recent runs', + 'Look at the recent runs in this workspace: did any fail, and why? Is anything getting slower?' + ) + add( + 'queue', + 'use', + 'Check the run queue', + "Is anything stuck in this workspace's queue? Which jobs are waiting or suspended, and why?" + ) + } + + if (builder && !empty) + add( + 'mcp', + 'use', + 'Use my scripts from Claude', + 'How do I connect Claude to this workspace with MCP so it can run my scripts and flows?' + ) + + return out.slice(0, MAX_SUGGESTIONS) +} + +function shortName(name: string): string { + return name.length > MAX_NAME ? `${name.slice(0, MAX_NAME - 1)}…` : name +} + +function capitalize(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1) +} diff --git a/frontend/src/lib/components/copilot/chat/starter/greeting.test.ts b/frontend/src/lib/components/copilot/chat/starter/greeting.test.ts new file mode 100644 index 0000000000..835896cfb8 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/greeting.test.ts @@ -0,0 +1,41 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const scoped = vi.hoisted(() => ({ key: 'welcomed::ada@example.com' as string | undefined })) +vi.mock('$lib/userScopedStorage', () => ({ scopedKey: () => scoped.key })) + +import { takeFirstVisit } from './greeting' + +const DAY = 24 * 60 * 60 * 1000 +const daysAgo = (n: number) => new Date(Date.now() - n * DAY).toISOString() + +const store = new Map<string, string>() +vi.stubGlobal('localStorage', { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => void store.set(k, v) +}) + +beforeEach(() => { + store.clear() + scoped.key = 'welcomed::ada@example.com' +}) + +describe('takeFirstVisit', () => { + it('welcomes a new member once per workspace, for the whole page load', () => { + expect(takeFirstVisit('acme', daysAgo(2))).toBe(true) + // Back on Home or the empty session in the same load: still the welcome. + expect(takeFirstVisit('acme', daysAgo(2))).toBe(true) + expect(JSON.parse(store.get('welcomed::ada@example.com')!)).toEqual(['acme']) + }) + + it('greets by time of day for an older member, or a workspace already welcomed', () => { + expect(takeFirstVisit('old-team', daysAgo(45))).toBe(false) + store.set('welcomed::ada@example.com', JSON.stringify(['seen-before'])) + expect(takeFirstVisit('seen-before', daysAgo(1))).toBe(false) + }) + + it('records nothing before the user is known', () => { + scoped.key = undefined + expect(takeFirstVisit('fresh', daysAgo(1))).toBe(false) + expect(store.size).toBe(0) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/starter/greeting.ts b/frontend/src/lib/components/copilot/chat/starter/greeting.ts new file mode 100644 index 0000000000..8e63dc3d5a --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/greeting.ts @@ -0,0 +1,37 @@ +import { scopedKey } from '$lib/userScopedStorage' + +const WELCOMED_KEY = 'session-block-welcomed-workspaces' +/** A membership older than this is not a first visit, whatever this browser remembers: without + * it, everyone already in a workspace would be welcomed to it once on their next visit. */ +const NEW_MEMBER_MS = 30 * 24 * 60 * 60 * 1000 + +// Workspaces welcomed during this page load: the welcome holds for the whole visit (Home, the +// empty session, back), and only a later load greets by time of day. +const welcomedThisLoad = new Set<string>() + +/** Whether this is the user's first visit to `workspace`: a recent member this browser has not + * welcomed there yet. Answering yes records the welcome. */ +export function takeFirstVisit(workspace: string, memberSince: string | undefined): boolean { + if (welcomedThisLoad.has(workspace)) return true + const key = scopedKey(WELCOMED_KEY) + if (!key) return false + let welcomed: string[] = [] + try { + welcomed = JSON.parse(localStorage.getItem(key) ?? '[]') + } catch {} + if (welcomed.includes(workspace)) return false + const joined = memberSince ? Date.parse(memberSince) : NaN + if (!(Date.now() - joined < NEW_MEMBER_MS)) return false + welcomedThisLoad.add(workspace) + try { + localStorage.setItem(key, JSON.stringify([...welcomed, workspace])) + } catch {} + return true +} + +export function timeOfDayGreeting(now = new Date()): string { + const hour = now.getHours() + if (hour >= 5 && hour < 12) return 'Good morning' + if (hour >= 12 && hour < 18) return 'Good afternoon' + return 'Good evening' +} diff --git a/frontend/src/lib/components/copilot/chat/starter/smoothHeight.ts b/frontend/src/lib/components/copilot/chat/starter/smoothHeight.ts new file mode 100644 index 0000000000..57336ef9b8 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/smoothHeight.ts @@ -0,0 +1,63 @@ +type SmoothHeightParams = { + /** Off: the element takes its natural height and nothing is animated. */ + enabled: boolean + /** The state whose change should animate. Height changes at any other time follow the + * content at once: animating every line the user types would clip the caret's line. */ + key: unknown +} + +const DURATION_MS = 200 +const EASING = 'cubic-bezier(0.2, 0.8, 0.2, 1)' + +/** + * Sizes `node` to its first child and animates that height when `key` changes, so a block + * that changes shape grows and shrinks instead of jumping. The child is measured, not the + * node: the node's own height is the one being set. `node` clips while it animates, so a + * focus ring belongs on `node` itself (box-shadow is not clipped by its own overflow). + */ +export function smoothHeight(node: HTMLElement, params: SmoothHeightParams) { + let { enabled, key } = params + let animateUntil = 0 + const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)') + + const apply = () => { + const inner = node.firstElementChild as HTMLElement | null + if (!enabled || !inner) { + node.style.height = '' + node.style.overflow = '' + node.style.transition = '' + return + } + const borders = node.offsetHeight - node.clientHeight + const animate = performance.now() < animateUntil && !reducedMotion.matches + node.style.overflow = 'hidden' + node.style.transition = animate ? `height ${DURATION_MS}ms ${EASING}` : 'none' + node.style.height = `${inner.offsetHeight + borders}px` + } + + // Created on first use: most chats mount this disabled and never turn it on. + let ro: ResizeObserver | undefined + const observe = () => { + ro?.disconnect() + const inner = node.firstElementChild + if (!enabled || !inner) return + ro ??= new ResizeObserver(apply) + ro.observe(inner) + } + // No measuring at mount: the content's height is not settled yet (a newly mounted session + // composer reads ~60px too tall), and a view transition captures the box at that height. + // The observer's first callback comes after layout and sets the right one. + observe() + + return { + update(next: SmoothHeightParams) { + if (next.key !== key) animateUntil = performance.now() + DURATION_MS + ;({ enabled, key } = next) + observe() + apply() + }, + destroy() { + ro?.disconnect() + } + } +} diff --git a/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts new file mode 100644 index 0000000000..11ce754710 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts @@ -0,0 +1,280 @@ +import { onboardingProfile, type StarterPrompt } from '$lib/onboardingProfile' +import { roleCapabilities, userStore } from '$lib/stores' +import { canEditItem } from '$lib/editRights' +import { scopedKey } from '$lib/userScopedStorage' +import { fromStore, get } from 'svelte/store' +import { resource } from 'runed' +import { + ResourceService, + ScriptService, + WorkspaceService, + type ListableResource, + type RunnableItem +} from '$lib/gen' +import { + CHANNEL_TYPES, + composerSuggestions, + DATABASE_TYPES, + FEW_ITEMS, + type ComposerItem, + type ComposerResource, + type ComposerRole, + type ComposerSignals, + type ComposerSuggestion +} from './composerSuggestions' + +export type { ComposerSuggestion } + +/** The newest items read: enough to find a shared flow beside the reader's own work. */ +const ITEMS_READ = 25 +/** The connections read. A full page may have cut the channel off, so only a page shorter + * than this proves the workspace has none. */ +const RESOURCES_READ = 20 + +/** The suggestions for the reader's role and the workspace the session acts on, and whether + * that workspace is still small. An invite that wrote prompts for this person replaces the + * suggestions outright: a prompt written for someone's own stack next to "Approve refunds in + * Slack" reads as the generic one. */ +export class StarterPrompts { + #invite = $state<StarterPrompt[]>() + #user = fromStore(userStore) + #capabilities = fromStore(roleCapabilities) + #workspace: () => string | undefined + #builds: () => boolean + #signals: { readonly current: Tagged<ComposerSignals> | undefined } + + /** `workspace`: where the session acts. `builds`: false while the session is held in Use. */ + constructor(workspace: () => string | undefined, builds: () => boolean = () => true) { + this.#workspace = workspace + this.#builds = builds + void onboardingProfile().then((p) => { + if (p?.starter_prompts?.length) this.#invite = p.starter_prompts + }) + // runed keeps whichever fetch settles last, so after a workspace or account switch an + // earlier fetch can land on top of the current one: each answer carries what it is for. + this.#signals = resource( + () => this.#tag, + async (tag) => { + const ws = this.#workspace() + return ws ? { tag, value: await readComposerSignals(ws) } : undefined + } + ) + } + + get #tag(): string { + return `${this.#workspace()}\0${this.#user.current?.email}` + } + + /** Undefined until the user is known. The user is read for Home's workspace, so a session + * acting on another one (a fork) keeps only what is instance-wide. */ + get #role(): ComposerRole | undefined { + const user = this.#user.current + if (!user) return undefined + const own = user.workspace_id === this.#workspace() + return { + operator: own && !this.#capabilities.current.code, + workspaceAdmin: own && user.is_admin, + instanceAdmin: user.is_super_admin + } + } + + /** Signals already read this page load stand in while they are asked again, so a remount + * does not wait on them. */ + get #currentSignals(): ComposerSignals | undefined { + const current = this.#signals.current + if (current?.tag === this.#tag) return current.value + const ws = this.#workspace() + const key = ws && signalsKey(ws) + return key ? settled.get(key) : undefined + } + + readonly suggestions: ComposerSuggestion[] = $derived.by(() => { + const builds = this.#builds() + // Not while held in Use: the invite's prompts are written to be built. + if (this.#invite && builds) return this.#invite.map((p) => ({ ...p, mode: 'build' as const })) + const signals = this.#currentSignals + const role = this.#role + if (!signals || !role) return [] + // A session held in Use authors nothing, so it gets an operator's suggestions. + return composerSuggestions(signals, builds ? role : { ...role, operator: true }) + }) + + /** Whether the workspace holds fewer than `FEW_ITEMS`, below which Home's composer rests + * open as the page's main way in; undefined until known. */ + get fewItems(): boolean | undefined { + const count = this.#currentSignals?.itemCount + return count === undefined ? undefined : count < FEW_ITEMS + } +} + +type Tagged<T> = { tag: string; value: T } + +/** Per account: the signals name the reader's private draft. A key is taken when a request + * starts, so one that settles after an account switch cannot answer for the next account; with + * no account known yet, nothing is cached. */ +const signalsKey = (workspace: string) => scopedKey(`composerSignals:${workspace}`) + +const settled = new Map<string, ComposerSignals>() +const requests = new Map<string, { at: number; request: Promise<ComposerSignals> }>() +/** How long an answer is reused before a mount asks again: long enough to cover the prefetch + * that preceded the mount, short enough that returning to Home sees what changed. */ +const REUSE_MS = 30_000 + +/** Starts the reads for a page about to mount the starter; the starter then takes these + * requests rather than sending its own. */ +export function prefetchComposerSignals(workspace: string): void { + void readComposerSignals(workspace) +} + +/** What the starter reads for `workspace`: one set of requests, shared by every caller and + * reused for `REUSE_MS`; a failure is not kept. */ +export async function readComposerSignals(workspace: string): Promise<ComposerSignals> { + const key = signalsKey(workspace) + try { + let request: Promise<ComposerSignals> + const kept = key && requests.get(key) + if (kept && Date.now() - kept.at < REUSE_MS) request = kept.request + else { + request = fetchSignals(workspace) + if (key) { + requests.set(key, { at: Date.now(), request }) + request.catch(() => { + if (requests.get(key)?.request === request) requests.delete(key) + }) + } + } + const signals = await request + if (!key) return signals + // A request that outlived the reuse window can settle after the one that replaced it. + if (requests.get(key)?.request === request) settled.set(key, signals) + return settled.get(key) ?? signals + } catch (e) { + // Unknown reads as a full workspace: a collapsed composer is the quieter mistake. + console.error(`Could not list the items of workspace ${workspace}:`, e) + return { itemCount: FEW_ITEMS } + } +} + +async function fetchSignals(workspace: string): Promise<ComposerSignals> { + // Read before the requests: a workspace switch while they are pending moves the user store + // to the next workspace's membership. + const member = get(userStore) + const user = member?.workspace_id === workspace ? member : undefined + const capabilities = get(roleCapabilities) + const [res, resources, dataTables] = await Promise.all([ + // What Home's list counts: library scripts and the user's own drafts included. + ScriptService.listRunnables({ + workspace, + includeWithoutMain: true, + includeDraftOnly: true, + orderBy: 'updated', + orderDesc: true, + perPage: ITEMS_READ + }), + readConnections(workspace), + readDataTables(workspace) + ]) + const items = res.items ?? [] + const deployed = items.filter((i) => !i.draft_only) + const username = user?.username + const draft = items.find( + (i) => + i.is_draft || + i.draft_only || + (username && i.draft_users?.some((u) => u['username'] === username)) + ) + const editable = (i: RunnableItem) => + canEditItem( + i.type === 'app' && i.raw_app ? 'raw_app' : i.type, + i.path, + i.extra_perms, + user, + capabilities + ) + const shared = deployed.find( + (i) => i.type === 'flow' && !(username && i.path.startsWith(`u/${username}/`)) + ) + // Only plain scripts run on their own: a library has no main function, a pipeline script + // runs as its pipeline, and test and preprocessor scripts serve another runnable. + const script = deployed.find( + (i) => + i.type === 'script' && (!i.auto_kind || i.auto_kind === 'script' || i.auto_kind === 'wac') + ) + const starred = deployed.find((i) => i.starred && (i.type === 'script' || i.type === 'flow')) + const pick = (item: RunnableItem | undefined) => item && composerItem(item) + const complete = resources !== undefined && resources.length < RESOURCES_READ + return { + itemCount: items.length, + myDraft: draft && composerItem(draft, draft.draft_path), + sharedFlow: pick(shared), + script: pick(script), + app: pick(deployed.find((i) => i.type === 'app' && i.raw_app && editable(i))), + agent: pick(deployed.find((i) => i.type === 'agent')), + folderItem: pick(deployed.find((i) => i.path.startsWith('f/'))), + favorite: pick(starred), + database: + resources && newest(resources.filter((r) => Object.hasOwn(DATABASE_TYPES, r.resource_type))), + channel: resources && (preferredChannel(resources) ?? (complete ? null : undefined)), + dataTables + } +} + +/** The workspace's databases and channels; unknown when the list fails, which fires none of + * the pills that read them. */ +async function readConnections(workspace: string): Promise<ListableResource[] | undefined> { + try { + return await ResourceService.listResource({ + workspace, + resourceType: [...Object.keys(DATABASE_TYPES), ...Object.keys(CHANNEL_TYPES)].join(','), + perPage: RESOURCES_READ + }) + } catch (e) { + console.error(`Could not list the connections of workspace ${workspace}:`, e) + return undefined + } +} + +/** The workspace's data table names, `main` (the one scripts use by default) first; unknown + * when the list fails. */ +async function readDataTables(workspace: string): Promise<string[] | undefined> { + try { + const names = (await WorkspaceService.listDataTables({ workspace })).map((d) => d.name) + return names.includes('main') ? ['main', ...names.filter((n) => n !== 'main')] : names + } catch (e) { + console.error(`Could not list the data tables of workspace ${workspace}:`, e) + return undefined + } +} + +function preferredChannel(resources: ListableResource[]): ComposerResource | undefined { + for (const type of Object.keys(CHANNEL_TYPES)) { + const channel = newest(resources.filter((r) => r.resource_type === type)) + if (channel) return channel + } + return undefined +} + +function newest(resources: ListableResource[]): ComposerResource | undefined { + const r = resources.reduce<ListableResource | undefined>( + (a, b) => (!a || (b.edited_at ?? '') > (a.edited_at ?? '') ? b : a), + undefined + ) + return r?.path && r.resource_type + ? { type: r.resource_type, path: r.path, name: r.path.split('/').pop() || r.path } + : undefined +} + +function composerItem(item: RunnableItem, path = item.path): ComposerItem { + return { + kind: item.type, + path, + name: item.summary || path.split('/').pop() || path + } +} + +/** What turns an empty chat into the block that starts a session. */ +export type ChatStarter = { suggestions: ComposerSuggestion[] } & ( + | /** An empty session centres the block in the pane under a greeting. */ + { where: 'session' } /** Home shows it alone, collapsed to one line at rest unless `fewItems`. */ + | { where: 'home'; fewItems: boolean } +) diff --git a/frontend/src/lib/components/copilot/chat/starter/starterPrompts.test.ts b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.test.ts new file mode 100644 index 0000000000..62713dccd9 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const account = vi.hoisted(() => ({ email: 'ada@example.com' as string | undefined })) +const listRunnables = vi.hoisted(() => vi.fn()) +const listResource = vi.hoisted(() => vi.fn()) +const listDataTables = vi.hoisted(() => vi.fn()) + +vi.mock('$lib/userScopedStorage', () => ({ + scopedKey: (base: string) => (account.email ? `${base}::${account.email}` : undefined) +})) +vi.mock('$lib/onboardingProfile', () => ({ onboardingProfile: async () => undefined })) +vi.mock('$lib/gen', () => ({ + ScriptService: { listRunnables }, + ResourceService: { listResource }, + WorkspaceService: { listDataTables } +})) + +import { readComposerSignals } from './starterPrompts.svelte' + +const draftOf = (owner: string) => ({ + items: [{ type: 'flow', path: `u/${owner}/secret_plan`, summary: '', is_draft: true }] +}) + +beforeEach(() => { + listRunnables.mockReset() + listResource.mockReset() + listResource.mockResolvedValue([]) + listDataTables.mockReset() + listDataTables.mockResolvedValue([]) +}) + +describe('readComposerSignals', () => { + it("never answers one account's signals for another", async () => { + listRunnables.mockResolvedValueOnce(draftOf('ada')) + expect((await readComposerSignals('acme')).myDraft?.path).toBe('u/ada/secret_plan') + + // Another account in the same browser, well inside the reuse window. + account.email = 'bob@example.com' + listRunnables.mockResolvedValueOnce({ items: [] }) + expect((await readComposerSignals('acme')).myDraft).toBeUndefined() + expect(listRunnables).toHaveBeenCalledTimes(2) + }) + + it('picks the newest database and the preferred channel', async () => { + listRunnables.mockResolvedValueOnce({ items: [] }) + listResource.mockResolvedValueOnce([ + { path: 'f/mail/smtp', resource_type: 'smtp', edited_at: '2026-10-03' }, + { path: 'f/data/old_db', resource_type: 'postgresql', edited_at: '2026-01-01' }, + { path: 'f/team/slack', resource_type: 'slack', edited_at: '2026-02-01' }, + { path: 'f/data/main_db', resource_type: 'mysql', edited_at: '2026-09-01' } + ]) + listDataTables.mockResolvedValueOnce([{ name: 'analytics' }, { name: 'main' }]) + const signals = await readComposerSignals('globex') + expect(signals.database).toEqual({ type: 'mysql', path: 'f/data/main_db', name: 'main_db' }) + expect(signals.channel?.path).toBe('f/team/slack') + expect(signals.dataTables).toEqual(['main', 'analytics']) + }) + + it('tells a list that holds nothing from one that failed or was cut off', async () => { + listRunnables.mockResolvedValueOnce({ items: [] }) + listDataTables.mockRejectedValueOnce(new Error('offline')) + const signals = await readComposerSignals('initech') + expect(signals.channel).toBeNull() + expect(signals.dataTables).toBeUndefined() + + // A full page of databases may have pushed the channel past it. + listRunnables.mockResolvedValueOnce({ items: [] }) + listResource.mockResolvedValueOnce( + Array.from({ length: 20 }, (_, i) => ({ path: `u/ada/db_${i}`, resource_type: 'postgresql' })) + ) + expect((await readComposerSignals('hooli')).channel).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/toolGroups.test.ts b/frontend/src/lib/components/copilot/chat/toolGroups.test.ts index 4dd3b376fe..d0f14e1f52 100644 --- a/frontend/src/lib/components/copilot/chat/toolGroups.test.ts +++ b/frontend/src/lib/components/copilot/chat/toolGroups.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from 'vitest' import type { DisplayMessage } from './shared' -import { groupHeader, groupToolRuns, type GroupState, type ToolGroup } from './toolGroups' +import { + createChatItemGrouper, + groupHeader, + groupToolRuns, + type GroupState, + type ToolGroup +} from './toolGroups' let nextId = 0 function tool( @@ -274,3 +280,37 @@ describe('groupToolRuns', () => { expect(header([mcp('list_issues'), other])).toBe('List issues, get issue') }) }) + +describe('createChatItemGrouper', () => { + it('keeps the history rows while only the live answer changes', () => { + const group = createChatItemGrouper() + const history = [ + assistant('done'), + tool('read_workspace_item'), + tool('list_runs'), + assistant('more') + ] + const first = group([...history, assistant('a', { streaming: true })]) + const second = group([...history, assistant('ab', { streaming: true })]) + expect(second).toHaveLength(first.length) + second.slice(0, -1).forEach((item, i) => expect(item).toBe(first[i])) + expect(second.at(-1)).toMatchObject({ kind: 'message', index: 4, message: { content: 'ab' } }) + expect(shape([...history, assistant('ab', { streaming: true })])).toEqual( + second.map((item) => + item.kind === 'group' ? { [item.groupKind]: item.entries.map((e) => e.index) } : item.index + ) + ) + }) + + it('keeps every row but the one a tool status change replaced', () => { + const group = createChatItemGrouper() + const history = [assistant('done'), tool('run_script'), assistant('more')] + const first = group(history) + const updated = [history[0], { ...history[1], isLoading: false }, history[2]] + const second = group(updated) + expect(second[0]).toBe(first[0]) + expect(second[1]).not.toBe(first[1]) + expect(second[1]).toMatchObject({ message: updated[1] }) + expect(second[2]).toBe(first[2]) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/toolGroups.ts b/frontend/src/lib/components/copilot/chat/toolGroups.ts index f3e3ad0aa9..5c0a8c2e1e 100644 --- a/frontend/src/lib/components/copilot/chat/toolGroups.ts +++ b/frontend/src/lib/components/copilot/chat/toolGroups.ts @@ -295,6 +295,49 @@ export function groupToolRuns(messages: DisplayMessage[]): ChatItem[] { return items } +function sameChatItem(a: ChatItem, b: ChatItem): boolean { + if (a.kind === 'message') { + return b.kind === 'message' && a.message === b.message && a.index === b.index + } + return ( + b.kind === 'group' && + a.groupKind === b.groupKind && + a.key === b.key && + a.target === b.target && + a.entries.length === b.entries.length && + a.entries.every((e, i) => e.message === b.entries[i].message && e.index === b.entries[i].index) + ) +} + +/** `groupToolRuns` for a transcript that is re-sent whole on every streamed chunk and on every + * tool status change: a row whose messages did not change keeps its previous item object. A + * fresh item per row re-renders the whole history each time (every answer re-parsing its + * markdown, every tool row its result), which freezes the tab on long sessions. + * + * A changed message is told apart by identity alone, so a row must be replaced, never mutated + * in place, for its grouping to update. */ +export function createChatItemGrouper(): (messages: DisplayMessage[]) => ChatItem[] { + let settled: DisplayMessage[] = [] + let settledItems: ChatItem[] = [] + return (messages) => { + // The live answer only ever comes last, and it can neither join nor end a group + // differently than the end of the transcript does, so it is grouped on its own and the + // rows before it are not regrouped while it streams. + const last = messages.at(-1) + const live = last?.role === 'assistant' && last.streaming ? last : undefined + const n = live ? messages.length - 1 : messages.length + if (n !== settled.length || settled.some((m, i) => m !== messages[i])) { + const previous = new Map(settledItems.map((item) => [chatItemKey(item), item])) + settled = messages.slice(0, n) + settledItems = groupToolRuns(settled).map((item) => { + const before = previous.get(chatItemKey(item)) + return before && sameChatItem(before, item) ? before : item + }) + } + return live ? [...settledItems, { kind: 'message', message: live, index: n }] : settledItems + } +} + // The server's full resource path: two servers can share a last segment (u/alice/github, // f/team/github), so only the display shortens it. function mcpServerPath(call: ToolDisplayMessage): string | undefined { diff --git a/frontend/src/lib/components/copilot/chat/workMode.ts b/frontend/src/lib/components/copilot/chat/workMode.ts new file mode 100644 index 0000000000..ffedf912b5 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/workMode.ts @@ -0,0 +1,63 @@ +// A leaf: the chat hosts and the session UI around them read these without loading the manager. + +/** What a session chat may do, picked in the composer beside the confirmations posture. */ +export enum AIWorkMode { + /** Reads and runs deployed items, and changes nothing. Locks the session's preview too. */ + USE = 'use', + /** Researches, then proposes a plan for the user's approval. Runs nothing. */ + PLAN = 'plan', + /** Shown as "Use & build": everything Use does, plus edits, tests and deploys. */ + BUILD = 'build' +} + +/** Why a session cannot leave Use, and where the user can build instead. */ +export type WorkModeLock = { + reason: string + escape?: { label: string; action: () => void } +} + +/** The answer to a call approved after its session switched to Use: the card or form it + * waited on was approved, but the mode the session is in now withholds the tool. */ +export const USE_MODE_WITHDRAWN = { + label: 'Not run: the session is in Use', + result: + 'Not run: the user switched this session to Use mode, which changes nothing, while this call waited for them. Do not retry it; it can run once they switch back to Use & build.', + /** On a test-run form left open across the switch. */ + testRunRefused: 'Use mode does not run undeployed code. Switch to Use & build to run this test.' +} + +/** The chat's tools that ask the user to move the session between Use and Use & build, each + * with the mode its card leads to. Named here because the card renderer and the picker resolve + * them by name. */ +export const ENTER_BUILD_MODE_TOOL = 'enter_build_mode' +export const ENTER_USE_MODE_TOOL = 'enter_use_mode' +export const WORK_MODE_SWITCH_TARGET = { + [ENTER_BUILD_MODE_TOOL]: AIWorkMode.BUILD, + [ENTER_USE_MODE_TOOL]: AIWorkMode.USE +} as const + +export type WorkModeSwitchTool = keyof typeof WORK_MODE_SWITCH_TARGET + +export function isWorkModeSwitchTool(name: string | undefined): name is WorkModeSwitchTool { + // hasOwn, not `in`: the name comes from the model, and `in` would accept `toString`. + return name !== undefined && Object.hasOwn(WORK_MODE_SWITCH_TARGET, name) +} + +/** In the shape of plan mode's card copy, whose card these render as. `declined` names the + * outcome: picking another mode in the picker resolves the card too. */ +export const WORK_MODE_SWITCH_CARD_COPY = { + [ENTER_BUILD_MODE_TOOL]: { + pending: 'Switch to Use & build?', + confirm: 'Switch to Use & build', + reject: 'Stay in Use', + settled: 'Switched to Use & build', + declined: 'Not switched to Use & build' + }, + [ENTER_USE_MODE_TOOL]: { + pending: 'Switch to Use?', + confirm: 'Switch to Use', + reject: 'Stay in Use & build', + settled: 'Switched to Use', + declined: 'Not switched to Use' + } +} as const diff --git a/frontend/src/lib/components/copilot/chat/workModeSwitch.ts b/frontend/src/lib/components/copilot/chat/workModeSwitch.ts new file mode 100644 index 0000000000..1752ee4cdf --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/workModeSwitch.ts @@ -0,0 +1,84 @@ +import { z } from 'zod' +import { createToolDef } from './shared' +import { NONE, type SessionTool } from './sessionCapabilities' +import { + ENTER_BUILD_MODE_TOOL, + ENTER_USE_MODE_TOOL, + WORK_MODE_SWITCH_CARD_COPY, + WORK_MODE_SWITCH_TARGET, + type AIWorkMode, + type WorkModeSwitchTool +} from './workMode' + +const switchArgs = z.object({ + reason: z + .string() + .describe('One concise sentence on why, shown to the user on the card that asks them.') +}) + +const DESCRIPTIONS: Record<WorkModeSwitchTool, string> = { + [ENTER_BUILD_MODE_TOOL]: + 'Asks the user to switch this session from Use to Use & build, the mode that also edits, tests and deploys. Call it when they ask for a change, which Use cannot make: the switch, and the tools that change the workspace, come only if they accept. Not for questions or for running deployed items, which Use already does.', + [ENTER_USE_MODE_TOOL]: + 'Asks the user to switch this session to Use, which reads and runs deployed items and changes nothing. Call it only when they ask you to stop changing the workspace in this session, never for a single question. The switch happens only if they accept.' +} + +// `declined` names the switch, not a mode: picking another mode in the picker declines the card too. +const RESULTS: Record<WorkModeSwitchTool, { switched: string; declined: string }> = { + [ENTER_BUILD_MODE_TOOL]: { + switched: + 'The user switched this session to Use & build. The tools that change the workspace are available from your next step: go on with the change they asked for.', + declined: + 'The user did not switch this session to Use & build. Do not make the change: carry on in the mode the session is in now, and say they can pick Use & build in the mode picker whenever they want it.' + }, + [ENTER_USE_MODE_TOOL]: { + switched: + 'The user switched this session to Use: from your next step you read and run deployed items, and change nothing.', + declined: + 'The user did not switch this session to Use. Carry on in the mode the session is in now.' + } +} + +const NO_LONGER_APPLIES = { + label: 'Switch no longer applies', + result: + 'Not run: the session changed mode before the user saw this switch. Carry on in the mode it is in now.' +} + +/** What a switch needs from the chat it runs in. */ +export interface WorkModeSwitchHost { + /** Whether the chat offers this switch now, from the mode the session is in. */ + offers(tool: WorkModeSwitchTool): boolean + setWorkMode(mode: AIWorkMode): void +} + +export function workModeSwitchTools( + host: WorkModeSwitchHost +): Record<WorkModeSwitchTool, SessionTool<any>> { + return { + [ENTER_BUILD_MODE_TOOL]: workModeSwitchTool(ENTER_BUILD_MODE_TOOL, host), + [ENTER_USE_MODE_TOOL]: workModeSwitchTool(ENTER_USE_MODE_TOOL, host) + } +} + +/** The switch happens in `fn`, so only once the user accepted the card: the chat stops offering + * the switches while confirmations are auto-accepted, and that posture never answers one. */ +function workModeSwitchTool(tool: WorkModeSwitchTool, host: WorkModeSwitchHost): SessionTool<any> { + return { + requires: NONE, + def: createToolDef(switchArgs, tool, DESCRIPTIONS[tool]), + // It changes no workspace item, only this session's mode. Not planModeSafe: a call left + // over from Use must not take a session out of Plan past its plan's approval. + readOnlySafe: true, + requiresConfirmation: true, + // A card queued behind another call can come up after the picker moved on. + validateBeforeConfirmation: () => (host.offers(tool) ? undefined : NO_LONGER_APPLIES), + confirmationMessage: WORK_MODE_SWITCH_CARD_COPY[tool].pending, + cancellationMessage: RESULTS[tool].declined, + showDetails: true, + fn: async () => { + host.setWorkMode(WORK_MODE_SWITCH_TARGET[tool]) + return RESULTS[tool].switched + } + } +} diff --git a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts index c6b03cee68..c4acf87ffb 100644 --- a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts +++ b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts @@ -488,9 +488,10 @@ export const variableRequestSchema = z.object({ "value": z.string().describe("The value of the variable"), "is_secret": z.boolean().describe("Whether the variable is a secret"), "description": z.string().describe("The description of the variable"), - "account": z.number().int().describe("The account identifier").optional(), + "account": z.number().int().describe("Ignored. A variable is linked to an OAuth account only when `createAccount` creates both.").optional(), "is_oauth": z.boolean().describe("Whether the variable is an OAuth variable").optional(), - "expires_at": z.string().datetime({ offset: true }).describe("The expiration date of the variable").optional(), + "expires_at": z.string().datetime({ offset: true }).describe("When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry \u2014 see value_valid_until.\n").optional(), + "value_valid_until": z.string().datetime({ offset: true }).describe("When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it, by the handler's `notify_before_secs` (1 day by default); never causes the variable to be deleted.\n").optional(), "labels": z.array(z.string()).optional(), "ws_specific": z.boolean().optional() }) diff --git a/frontend/src/lib/components/copilot/chatModelSettings.ts b/frontend/src/lib/components/copilot/chatModelSettings.ts index 3fce0270d1..e65a0b5141 100644 --- a/frontend/src/lib/components/copilot/chatModelSettings.ts +++ b/frontend/src/lib/components/copilot/chatModelSettings.ts @@ -41,6 +41,8 @@ export type ChoiceSection = { export type ChatModelSettingsConfig = { /** The trigger's main text: the chosen model, or an invitation to choose one. */ label: string + /** Shown instead of `label` on windows narrower than 1280px. */ + shortLabel?: string title?: string /** Trailing pill on the trigger, e.g. the free-tier grant this chat is spending. */ badge?: { text: string; warn?: boolean } diff --git a/frontend/src/lib/components/copilot/workspaceAiHidden.svelte.ts b/frontend/src/lib/components/copilot/workspaceAiHidden.svelte.ts new file mode 100644 index 0000000000..99d0cca9f0 --- /dev/null +++ b/frontend/src/lib/components/copilot/workspaceAiHidden.svelte.ts @@ -0,0 +1,44 @@ +import { resource } from 'runed' +import { fromStore } from 'svelte/store' +import { WorkspaceService } from '$lib/gen' +import { copilotInfo, copilotWorkspace } from '$lib/aiStore' + +/** + * Whether a workspace hid the AI assistant (`ai_config.copilot_disabled`), read for that workspace + * directly: `copilotInfo` holds whichever workspace loaded last, so it answers only when it was + * loaded for this very workspace. `hidden` is `undefined` until a verdict for the workspace asked + * about lands; runed keeps the previous `current` while a new source loads, so each verdict is + * tagged with its workspace. A failed read counts as not hidden, as an unloaded config does + * everywhere else. + */ +export function useWorkspaceAiHidden(workspace: () => string | undefined) { + const loadedInfo = fromStore(copilotInfo) + const loadedWorkspace = fromStore(copilotWorkspace) + const verdict = resource(workspace, async (ws, _prev, { signal }) => { + if (!ws) return { workspace: ws, hidden: false } + let hidden = false + try { + hidden = (await WorkspaceService.getCopilotInfo({ workspace: ws })).copilot_disabled === true + } catch (e) { + console.error(`Failed to read the AI config of workspace ${ws}:`, e) + } + // The generated client can't take an abort signal, so drop a superseded response here. + if (signal.aborted) throw new DOMException('superseded', 'AbortError') + return { workspace: ws, hidden } + }) + const hidden = $derived.by(() => { + const ws = workspace() + const current = verdict.current + if (current && current.workspace === ws) return current.hidden + return ws && loadedWorkspace.current === ws ? loadedInfo.current.workspaceDisabled : undefined + }) + return { + get hidden(): boolean | undefined { + return hidden + }, + /** Whether any verdict has landed yet, for any workspace. */ + get settledOnce(): boolean { + return verdict.current !== undefined + } + } +} diff --git a/frontend/src/lib/components/details/DetailPageHeader.svelte b/frontend/src/lib/components/details/DetailPageHeader.svelte index 30b0d5dab7..c8f7ffc0d7 100644 --- a/frontend/src/lib/components/details/DetailPageHeader.svelte +++ b/frontend/src/lib/components/details/DetailPageHeader.svelte @@ -11,7 +11,13 @@ import type { Item } from '$lib/utils' import { Bell, BellOff, Calendar } from 'lucide-svelte' import { toggleWorkspaceErrorHandler } from './errorHandlerToggle' - import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { + operatingWorkspaceContextEntry, + useOperatingWorkspace + } from '$lib/components/operatingWorkspace.svelte' + import OpenInSessionButton, { + type OpenInSessionSource + } from '$lib/components/sessions/OpenInSessionButton.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -42,7 +48,10 @@ const triggerContext = getContext<TriggerContext | undefined>('TriggerContext') const { triggersCount, triggersState } = $state(triggerContext ?? ({} as Partial<TriggerContext>)) // The buttons below render in the page header, away from this page's tree. - const headerContexts = new Map<any, any>([['TriggerContext', triggerContext]]) + const headerContexts = new Map<any, any>([ + ['TriggerContext', triggerContext], + operatingWorkspaceContextEntry() + ]) interface Props { mainButtons?: MainButton[] @@ -104,6 +113,17 @@ // no error handler and says so itself. const renameKind = $derived(itemKind ?? errorHandlerKind) + // The session's preview opens on this same deployed page (`/get/`), not the item's editor: + // someone here came to run the item, not to change it. + const sessionSource: OpenInSessionSource | undefined = $derived( + errorHandlerKind && path + ? { + page: () => `/${errorHandlerKind}s/get/${path}`, + workspaceId: $operatingWorkspace ?? undefined + } + : undefined + ) + // The band folds the buttons once its breadcrumb has given all it can (`actionFolds` below): // first the secondary ones go to their `placement`, then every bar button but the last, which // is what the page is for (Edit), then that one too. Outside the band — a session's preview @@ -277,8 +297,15 @@ unifiedSize={size} /> {/if} - {#each barButtons as btn (btn.label)} + <!-- The session button goes right before the last bar button, the one the page is for (Edit). --> + {#if ownsPageHeader && barButtons.length === 0} + <OpenInSessionButton source={sessionSource} /> + {/if} + {#each barButtons as btn, i (btn.label)} {@const dropdownItems = dropdownItemsOf(btn)} + {#if ownsPageHeader && i === barButtons.length - 1} + <OpenInSessionButton source={sessionSource} /> + {/if} <Button {...btn.buttonProps} startIcon={{ icon: btn.buttonProps.startIcon }} @@ -313,6 +340,7 @@ pathTrigger: onSaved ? pathTrigger : undefined }} {actions} + {sessionSource} actionFolds={3} earlyActionFolds={1} contexts={headerContexts} diff --git a/frontend/src/lib/components/details/FlowDetail.svelte b/frontend/src/lib/components/details/FlowDetail.svelte index a9648b183d..862435fb57 100644 --- a/frontend/src/lib/components/details/FlowDetail.svelte +++ b/frontend/src/lib/components/details/FlowDetail.svelte @@ -79,6 +79,7 @@ import { setOperatingWorkspace, useOperatingUser, + useReadOnlyWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' import FlowChat from '$lib/components/flows/conversations/FlowChat.svelte' @@ -95,6 +96,7 @@ openEditInFork } from '$lib/utils/editInFork' import { isCloudHosted } from '$lib/cloud' + import { recentItems } from '$lib/components/home/recentItems.svelte' let { path: routePath, @@ -138,13 +140,16 @@ const operatingHref = useOperatingWorkspaceHref() const actingUser = $derived(operatingUser.current) const editRights = useEditRights() + const readOnly = useReadOnlyWorkspace() let flow: Flow | undefined = $state() // Derived, not assigned during the load: in a fork the acting user is looked up // asynchronously, and a value read after `getFlowByPath` resolves can land before that // lookup does. Assigned once, that leaves the page permanently read-only — `canWrite` // refuses an unknown user — with nothing to recompute it. - const can_write = $derived(!!flow && canWrite(flow.path, flow.extra_perms!, actingUser)) + const can_write = $derived( + !!flow && !readOnly(workspace) && canWrite(flow.path, flow.extra_perms!, actingUser) + ) const promptForAi = $derived((flow?.schema?.prompt_for_ai as string | undefined) ?? '') let shareModal: ShareModal | undefined = $state() @@ -263,6 +268,15 @@ if (!flow.path.startsWith(`u/${actingUser?.username}`) && flow.path.split('/').length > 2) { invisible_to_owner = flow.visible_to_runner_only } + // Opened from a session's preview tab, it was the session's doing, not a visit. + if (!embedded) { + recentItems.record(workspace!, { + kind: 'flow', + path: flow.path, + summary: flow.summary, + via: 'view' + }) + } intervalId && clearInterval(intervalId) deploymentInProgress = flow.lock_error_logs == '' if (deploymentInProgress) { @@ -374,6 +388,7 @@ if (pendingRun) args = { ...untrack(() => pendingRun.proposedArgs) } let canAuthorFlow = $derived(editRights.roleCanAuthor('flow')) + const caps = $derived(editRights.capabilities) let moveDrawer: MoveDrawer | undefined = $state() let deploymentDrawer: DeployWorkspaceDrawer | undefined = $state() @@ -410,12 +425,7 @@ }) } - if ( - flow && - !actingUser?.operator && - !isCloudHosted() && - editInForkAllowed(workspace, $userWorkspaces) - ) { + if (flow && caps.code && !isCloudHosted() && editInForkAllowed(workspace, $userWorkspaces)) { buttons.push({ label: editInForkLabel(workspace, $userWorkspaces), description: editInForkDescription('flow', workspace, $userWorkspaces), @@ -460,8 +470,8 @@ return buttons } - // Build app makes a low-code app, which no builder right covers. - if (!actingUser?.operator) { + // Build app starts from the full template, not the builder one a compose-only role deploys. + if (caps.apps === 'full') { buttons.push({ label: 'Build app', placement: 'menu', @@ -530,11 +540,8 @@ }) } - // The builder right opens this menu to operators; audit logs stay behind their own setting. - if ( - !actingUser?.operator || - $userWorkspaces.find((w) => w.id === workspace)?.operator_settings?.audit_logs - ) { + // A flow-composing role opens this menu; audit logs stay behind their own visibility flag. + if (caps.visibility.audit_logs) { menuItems.push({ label: 'Audit logs', Icon: Eye, @@ -544,7 +551,7 @@ }) } - if (isDeployable('flow', flow?.path ?? '', deployUiSettings) && !actingUser?.operator) { + if (isDeployable('flow', flow?.path ?? '', deployUiSettings) && caps.flows === 'full') { menuItems.push({ label: 'Deploy to staging/prod', onclick: () => deploymentDrawer?.openDrawer(flow?.path ?? '', 'flow'), @@ -670,7 +677,7 @@ <DetailPageLayout bind:this={detailLayout} bind:selected={rightPaneSelected} - isOperator={actingUser?.operator} + isOperator={!caps.code} forceSmallScreen={chatInputEnabled} isChatMode={chatInputEnabled} flow_json={{ @@ -696,7 +703,8 @@ } } scriptOrFlowPath={flow?.path ?? ''} - errorHandlerKind="flow" + itemKind="flow" + errorHandlerKind={readOnly(workspace) ? undefined : 'flow'} tag={flow?.tag ?? ''} labels={flow?.labels} inheritedLabels={flow?.inherited_labels} diff --git a/frontend/src/lib/components/details/ScriptDetail.svelte b/frontend/src/lib/components/details/ScriptDetail.svelte index 1d6bde0c82..160a8f49b8 100644 --- a/frontend/src/lib/components/details/ScriptDetail.svelte +++ b/frontend/src/lib/components/details/ScriptDetail.svelte @@ -103,6 +103,7 @@ import { setOperatingWorkspace, useOperatingUser, + useReadOnlyWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' import { useEditRights } from '$lib/operatorWriteRights' @@ -119,6 +120,7 @@ import WacDiagram from '$lib/components/graph/WacDiagram.svelte' import { twMerge } from 'tailwind-merge' import CiTestResults from '$lib/components/CiTestResults.svelte' + import { recentItems } from '$lib/components/home/recentItems.svelte' let { hash: routeHash, @@ -172,14 +174,17 @@ // lookup does. Assigned once, that leaves the page permanently read-only — `canWrite` // refuses an unknown user — with nothing to recompute it. A hub script is never writable. const promptForAi = $derived((script?.schema?.prompt_for_ai as string | undefined) ?? '') + const readOnly = useReadOnlyWorkspace() const can_write = $derived( !isHubScript && !!script && script.workspace_id == workspace && + !readOnly(workspace) && canWrite(script.path, script.extra_perms!, actingUser) ) const editRights = useEditRights() - // The edit actions also need a role that authors scripts, which no operator has. + const caps = $derived(editRights.capabilities) + // The edit actions also need a role that authors scripts. const canEdit = $derived(can_write && editRights.roleCanAuthor('script')) let deploymentInProgress = $state(false) let expandedModuleLocks: Record<string, boolean> = $state({}) @@ -369,6 +374,16 @@ if (!script.path.startsWith(`u/${actingUser?.username}`) && script.path.split('/').length > 2) { invisible_to_owner = script.visible_to_runner_only } + // Opened from a session's preview tab, it was the session's doing, not a visit. An + // archived script has no page for Home's card to open. + if (!embedded && !script.archived) { + recentItems.record(workspace!, { + kind: 'script', + path: script.path, + summary: script.summary, + via: 'view' + }) + } onLoadState?.('loaded') } @@ -545,7 +560,7 @@ ) { const buttons: any = [] - if (!topHash && script && !actingUser?.operator && !script.codebase) { + if (!topHash && script && caps.code && !script.codebase) { buttons.push({ label: 'Fork', description: `Start a new script from a copy of this one`, @@ -561,12 +576,7 @@ }) } - if ( - script && - !actingUser?.operator && - !isCloudHosted() && - editInForkAllowed(workspace, $userWorkspaces) - ) { + if (script && caps.code && !isCloudHosted() && editInForkAllowed(workspace, $userWorkspaces)) { buttons.push({ label: editInForkLabel(workspace, $userWorkspaces), description: editInForkDescription('script', workspace, $userWorkspaces), @@ -616,24 +626,26 @@ }) } - if (!actingUser?.operator) { - buttons.push({ - label: 'Build app', - placement: 'menu', - alwaysPlaced: true, - buttonProps: { - onClick: async () => { - const app = createRawAppFromScript(script.path, script.summary, script.schema) - // The raw app editor reads the payload from sessionStorage on mount. - sessionStorage.setItem('rawAppImport', JSON.stringify(app)) - await onNavigate('/apps_raw/add') - }, - disabled: !showEditButtons, - unifiedSize: 'md', - variant: 'subtle', - startIcon: LayoutDashboard - } - }) + if (caps.code) { + // It starts from the full template, not the builder one a compose-only role deploys. + if (caps.apps === 'full') + buttons.push({ + label: 'Build app', + placement: 'menu', + alwaysPlaced: true, + buttonProps: { + onClick: async () => { + const app = createRawAppFromScript(script.path, script.summary, script.schema) + // The raw app editor reads the payload from sessionStorage on mount. + sessionStorage.setItem('rawAppImport', JSON.stringify(app)) + await onNavigate('/apps_raw/add') + }, + disabled: !showEditButtons, + unifiedSize: 'md', + variant: 'subtle', + startIcon: LayoutDashboard + } + }) if (script?.restart_unless_cancelled ?? false) { buttons.push({ @@ -688,7 +700,7 @@ script: Script | undefined, deployUiSettings: WorkspaceDeployUISettings | undefined ) { - if (!script || actingUser?.operator) return [] + if (!script || !caps.code) return [] const menuItems: any = [] @@ -855,7 +867,7 @@ </DrawerContent> </Drawer> {#key script?.hash} - <DetailPageLayout bind:selected={rightPaneSelected} isOperator={actingUser?.operator}> + <DetailPageLayout bind:selected={rightPaneSelected} isOperator={!caps.code}> {#snippet header({ wide }: { wide: boolean })} <DetailPageHeader {wide} @@ -868,7 +880,8 @@ if (script !== undefined) script.ws_error_handler_muted = v } } - errorHandlerKind="script" + itemKind="script" + errorHandlerKind={readOnly(workspace) ? undefined : 'script'} scriptOrFlowPath={script?.path ?? ''} tag={script?.tag ?? ''} labels={script?.labels} diff --git a/frontend/src/lib/components/filterSearchbarMatch.test.ts b/frontend/src/lib/components/filterSearchbarMatch.test.ts new file mode 100644 index 0000000000..7bc0a5eefa --- /dev/null +++ b/frontend/src/lib/components/filterSearchbarMatch.test.ts @@ -0,0 +1,19 @@ +import { describe, it, expect } from 'vitest' +import { filterMatchesQuery } from './FilterSearchbar.svelte' + +describe('filterMatchesQuery', () => { + const archived = { type: 'boolean' as const, label: 'Only archived' } + + it('matches each word anywhere in the label or key', () => { + expect(filterMatchesQuery('archived', archived, 'archive')).toBe(true) + expect(filterMatchesQuery('archived', archived, 'archived only')).toBe(true) + expect(filterMatchesQuery('archived', archived, 'archived scripts')).toBe(false) + expect( + filterMatchesQuery('include_library', { type: 'boolean', label: 'Library' }, 'include lib') + ).toBe(true) + }) + + it('reads an escaped space as a word break', () => { + expect(filterMatchesQuery('archived', archived, 'archived\\ only')).toBe(true) + }) +}) diff --git a/frontend/src/lib/components/flow_builder.ts b/frontend/src/lib/components/flow_builder.ts index 1a4b7e5c26..8f2f634643 100644 --- a/frontend/src/lib/components/flow_builder.ts +++ b/frontend/src/lib/components/flow_builder.ts @@ -10,9 +10,9 @@ import type { WorkspaceItem } from './workspacePicker' export type FlowBuilderProps = { initialPath?: string - /** The draft row's own path (the URL path). `initialPath` is re-seeded from the - * draft's `draft_path` so the topbar shows the pending name, so it can't be used - * to resolve what is actually deployed. */ + /** The draft row's own path (the URL path). For a draft-only flow `initialPath` is + * re-seeded from the draft's `draft_path` so the topbar shows the pending name, so + * it can't be used to resolve what is actually deployed. */ userDraftPath?: string /** Moves the draft's base to the head and keeps its content; offered in the diff * drawer while the draft is behind, and called with the version the drawer shows diff --git a/frontend/src/lib/components/flows/FlowEditor.svelte b/frontend/src/lib/components/flows/FlowEditor.svelte index a9c3a40e8a..f735d1579b 100644 --- a/frontend/src/lib/components/flows/FlowEditor.svelte +++ b/frontend/src/lib/components/flows/FlowEditor.svelte @@ -40,14 +40,11 @@ import FlowPanelPlacementPicker from './common/FlowPanelPlacementPicker.svelte' import { prefersSessionHandoff } from '../copilot/chat/global/gate' import { openSourceInSession } from '$lib/components/sessions/sessionSwitch.svelte' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) + const roleCaps = useRoleCapabilities() const { flowStore, selectionManager, pathStore, opWorkspace } = getContext<FlowEditorContext>('FlowEditorContext') // Flow paths repeat across workspaces, and a session keeps every tab it has visited alive, so two @@ -408,11 +405,7 @@ // contain. Hand it to a session opened on that step rather than the // docked chat, which sessions leave unmounted. Sent on arrival: the // user already said what they wanted in the description field. - if ( - !sessionScopedManager && - sessionOpen && - prefersSessionHandoff(actingUser?.operator) - ) { + if (!sessionScopedManager && sessionOpen && prefersSessionHandoff(!$roleCaps.code)) { void openSourceInSession(sessionOpen, { previewParams: { selected: detail.moduleId }, seedPrompt: stepInstructionsPrompt(detail.moduleId, detail.instructions), diff --git a/frontend/src/lib/components/flows/agentActions.ts b/frontend/src/lib/components/flows/agentActions.ts index da31a3665f..b99229d4d3 100644 --- a/frontend/src/lib/components/flows/agentActions.ts +++ b/frontend/src/lib/components/flows/agentActions.ts @@ -25,8 +25,8 @@ export function agentMenuItems(agent: { /** Never deployed: no resource yet to hold permissions or to deploy onward. */ draftOnly?: boolean wsSpecific?: boolean - /** Hides what an operator has no page for, as on a flow's menu. */ - operator?: boolean + /** Hides what a role that cannot code has no page or right for, as on a flow's menu. */ + noCode?: boolean /** Undefined until loaded, when nothing is offered for deploy. */ deployUiSettings: WorkspaceDeployUISettings | undefined onPermissions: () => void @@ -35,6 +35,7 @@ export function agentMenuItems(agent: { onDelete: (event?: MouseEvent) => void }): Item[] { const deployable = + !agent.noCode && !agent.wsSpecific && !agent.draftOnly && isDeployable('resource', agent.path, agent.deployUiSettings) @@ -50,7 +51,7 @@ export function agentMenuItems(agent: { icon: List, action: () => goto(`/runs/${agent.path}?job_kinds=previews`) }, - ...(agent.operator + ...(agent.noCode ? [] : [ { @@ -70,7 +71,7 @@ export function agentMenuItems(agent: { ...(deployable ? [{ displayName: 'Deploy to prod/staging', icon: FileUp, action: agent.onDeploy }] : []), - ...(agent.draftOnly || agent.operator + ...(agent.draftOnly || agent.noCode ? [] : [{ displayName: 'Version history', icon: History, action: agent.onHistory }]), { diff --git a/frontend/src/lib/components/flows/agentDraft.svelte.ts b/frontend/src/lib/components/flows/agentDraft.svelte.ts index c0b2ba8bc4..aef204784d 100644 --- a/frontend/src/lib/components/flows/agentDraft.svelte.ts +++ b/frontend/src/lib/components/flows/agentDraft.svelte.ts @@ -4,6 +4,7 @@ import { deepEqual } from 'fast-equals' import { ResourceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' import { canEditItem, roleCanAuthor } from '$lib/editRights' +import { capabilitiesIn } from '$lib/roleCapabilities' import { userStore, userWorkspaces } from '$lib/stores' import { getUserExt } from '$lib/user' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' @@ -359,12 +360,16 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { // Same rule the generic resource editor applies. The backend refuses the write // either way, but without this the editor would invite edits it cannot save and // autosave a draft on every keystroke against a resource the reader cannot deploy. + const writer = user ?? get(userStore) ?? undefined canWriteResource = canEditItem( 'agent', r.path, r.extra_perms, - user ?? get(userStore) ?? undefined, - get(userWorkspaces).find((w) => w.id === ws)?.operator_settings + writer, + capabilitiesIn( + user, + get(userWorkspaces).find((w) => w.id === ws) + ) ) // An agent that exists only as a draft has no deployed value to compare against or // fall back to, and the response's is a synthetic echo of the draft. Leaving the @@ -406,8 +411,11 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { deployed = undefined canWriteResource = roleCanAuthor( 'agent', - get(userStore) ?? undefined, - get(userWorkspaces).find((w) => w.id === ws)?.operator_settings + // Only superadmin carries over: the nav user's admin flag belongs to another workspace. + capabilitiesIn( + { is_super_admin: get(userStore)?.is_super_admin }, + get(userWorkspaces).find((w) => w.id === ws) + ) ) state = { path: name, diff --git a/frontend/src/lib/components/flows/common/FlowCardHeader.svelte b/frontend/src/lib/components/flows/common/FlowCardHeader.svelte index e50fde2cb2..80aea48e4a 100644 --- a/frontend/src/lib/components/flows/common/FlowCardHeader.svelte +++ b/frontend/src/lib/components/flows/common/FlowCardHeader.svelte @@ -20,7 +20,7 @@ import type { FlowBuilderWhitelabelCustomUi } from '$lib/components/custom_ui' import DropdownV2 from '$lib/components/DropdownV2.svelte' import { hubBaseUrlStore } from '$lib/stores' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { DEFAULT_HUB_BASE_URL, PRIVATE_HUB_MIN_VERSION } from '$lib/hub' import { getLatestHashForScript } from '$lib/scripts' import { sendUserToast, type Item } from '$lib/utils' @@ -31,7 +31,8 @@ import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderFlows = useOperatorBuilderFlows() + const roleCaps = useRoleCapabilities() + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') interface Props { flowModuleValue?: FlowModuleValue | undefined @@ -104,7 +105,7 @@ const scriptItems: Item[] = $derived.by(() => { if (flowModuleValue?.type !== 'script') return [] const items: Item[] = [] - if (!isHub && customUi?.scriptEdit != false && !$operatorBuilderFlows) { + if (!isHub && customUi?.scriptEdit != false && !composeOnlyFlows) { items.push({ displayName: "Edit the script's code", icon: Pen, @@ -148,7 +149,7 @@ }) } } - if (customUi?.scriptFork != false && !$operatorBuilderFlows) { + if (customUi?.scriptFork != false && !composeOnlyFlows) { items.push({ displayName: 'Fork into an inline script', icon: GitFork, diff --git a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte index b902b69bfa..cdec419e5a 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte @@ -47,7 +47,8 @@ AGENT_EDITOR_RUN_INPUTS, AGENT_TOOLS_ROW, DEFAULT_AGENT_MEMORY, - keepsManagedMemory + keepsManagedMemory, + agentMemoryMode } from '../agentFormFields' import { toolDisplayName, type AgentTool } from '../agentToolUtils' import { useAgentDraft, type AgentRunAs } from '../agentDraft.svelte' @@ -243,6 +244,23 @@ // apart from the echo of their own write. let lastArgs = $state<string | undefined>(undefined) + // With memory off a run keeps no history of its own, so the form also takes the one to answer + // from; managed memory and an older setting would ignore one. + let formSchema = $derived( + agentMemoryMode((agentValue?.input_transforms?.memory as any)?.value) !== 'off' + ? AGENT_CHAT_SCHEMA + : { + ...AGENT_CHAT_SCHEMA, + properties: { + ...AGENT_CHAT_SCHEMA.properties, + previous_messages: { + type: 'array', + items: { type: 'object' }, + description: 'The conversation so far, as chat messages, for the agent to answer from' + } + } + } + ) // Picked on the first load, after which it is the reader's: following the memory setting live // would pull them out of a chat for switching memory off in the form. let testMode = $state<'form' | 'chat' | undefined>(undefined) @@ -603,7 +621,7 @@ <div class="flex-1 min-h-0 overflow-auto p-4 {testMode === 'chat' ? 'hidden' : ''}"> <div class="max-w-3xl mx-auto"> {@render viewForm?.({ - schema: AGENT_CHAT_SCHEMA, + schema: formSchema, run: runOnce, loading: runLoading, actions: onOpenConfig ? configurationButton : undefined diff --git a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte index f3ee578050..7fde7a56f4 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte @@ -35,6 +35,7 @@ import PathEditPopover from '$lib/components/PathEditPopover.svelte' import { emptyString } from '$lib/utils' import Tooltip from '$lib/components/Tooltip.svelte' + import { useEditRights } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() @@ -134,9 +135,17 @@ let draftOnly = $derived(draft?.noDeployed ?? false) // Evals run against the deployed agent, and a draft-only one has none: the backend's // `require_agent` would reject every run. Evaluating is authoring, so it is for those who can - // edit the agent. Unknown until the load answers, and warming the pane loads it. + // edit the agent, except a role without `code`: eval datasets are refused to it + // (`check_role_can_code`) whatever its flows right. Unknown until the load answers, and warming + // the pane loads it. + const editRights = useEditRights(() => ws) let canEvaluate = $derived( - draft != undefined && !draft.loading && !draftOnly && !readOnly && !refused + draft != undefined && + !draft.loading && + !draftOnly && + !readOnly && + !refused && + editRights.capabilities.code ) // The draft's path, so a rename shows where it is typed — including a never-deployed agent, // stored at a minted `draft_<uuid>` path and named by the path its first deploy will create, diff --git a/frontend/src/lib/components/flows/content/AgentResourceBar.svelte b/frontend/src/lib/components/flows/content/AgentResourceBar.svelte index 6aa5a902e8..6d116cb79d 100644 --- a/frontend/src/lib/components/flows/content/AgentResourceBar.svelte +++ b/frontend/src/lib/components/flows/content/AgentResourceBar.svelte @@ -8,8 +8,9 @@ import ResourcePathHint from '$lib/components/ResourcePathHint.svelte' import { ResourceService, type InputTransform, type Resource } from '$lib/gen' import { sendUserToast } from '$lib/toast' - import { userStore, userWorkspaces } from '$lib/stores' + import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' import { canEditItem } from '$lib/editRights' + import { capabilitiesIn } from '$lib/roleCapabilities' import { Bot, ChevronDown, ChevronUp, Save, Unlink, Pencil } from 'lucide-svelte' import { AGENT_BRAIN_KEYS, @@ -244,7 +245,10 @@ agent, linkedInfo?.extraPerms, $userStore ?? undefined, - $userWorkspaces.find((w) => w.id === ws)?.operator_settings + capabilitiesIn( + ws === $workspaceStore ? $userStore : undefined, + $userWorkspaces.find((w) => w.id === ws) + ) ) ) // The hint flips on the first keystroke in the agent editor, so the badge does not wait for the diff --git a/frontend/src/lib/components/flows/content/AgentSettings.svelte b/frontend/src/lib/components/flows/content/AgentSettings.svelte index 9d02183812..5ed0799df3 100644 --- a/frontend/src/lib/components/flows/content/AgentSettings.svelte +++ b/frontend/src/lib/components/flows/content/AgentSettings.svelte @@ -11,6 +11,7 @@ import AgentSlackSettings from './AgentSlackSettings.svelte' import { WorkspaceService } from '$lib/gen' import { userStore } from '$lib/stores' + import { useActingUser } from '$lib/actingUser.svelte' import type { AgentDraftHandle, AgentRunAs } from '../agentDraft.svelte' /** An agent's own settings, laid out as the top of the resource editor: what it is saved as @@ -27,6 +28,7 @@ } let { draft, path, workspace, error = $bindable(), onRunAsChange = undefined }: Props = $props() + const acting = useActingUser(() => workspace) let readOnly = $derived(!draft.canWrite) // As the deploy resolves it: the deployer, unless one who may keep another picked them. @@ -130,8 +132,11 @@ {/if} </div> </Section> - <Section label="Slack"> - <AgentSlackSettings {draft} {path} {workspace} {nextRunAs} /> - </Section> + <!-- Operators cannot share agents in Slack, builder rights or not (slack_agents.rs). --> + {#if acting.current?.operator === false} + <Section label="Slack"> + <AgentSlackSettings {draft} {path} {workspace} {nextRunAs} /> + </Section> + {/if} </div> {/if} diff --git a/frontend/src/lib/components/flows/content/AgentToolBindings.svelte b/frontend/src/lib/components/flows/content/AgentToolBindings.svelte index dc3fad1ea7..b3c956b7fc 100644 --- a/frontend/src/lib/components/flows/content/AgentToolBindings.svelte +++ b/frontend/src/lib/components/flows/content/AgentToolBindings.svelte @@ -4,6 +4,7 @@ import type { InputTransform, ScriptLang } from '$lib/gen' import InputTransformSchemaForm from '$lib/components/InputTransformSchemaForm.svelte' import HighlightCode from '$lib/components/HighlightCode.svelte' + import InputTransformsViewer from '$lib/components/InputTransformsViewer.svelte' import { Button } from '$lib/components/common' import { ChevronDown, ChevronRight, Wrench } from 'lucide-svelte' import type { PickableProperties } from '../previousResults' @@ -16,6 +17,7 @@ } from '../agentToolUtils' import { flowLocalAgentSchema, toolInputOverrides } from '../agentResourceUtils' import { loadSchemaFromModule } from '../flowInfers' + import { useRoleCapabilities } from '$lib/operatorWriteRights' let { tools, @@ -35,6 +37,42 @@ } = $props() let flowTools = $derived(tools.filter(isFlowModuleTool)) + const roleCaps = useRoleCapabilities() + // The server checks bindings only below `full` (`check_operator_can_build`). + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') + + /** Mirrors the backend's `InputTransform::is_completed`: an input the agent fills is hidden from + * the model, and the server refuses a builder's binding of it. */ + function isSetByAgent(transform: InputTransform | undefined): boolean { + if (transform?.type === 'static') { + return transform.value !== undefined && transform.value !== null + } + return transform?.type === 'javascript' && !!transform.expr?.trim() + } + + /** A builder binds only the inputs the agent leaves to the model. */ + function shownSchema(tool: FlowModuleTool): any { + const schema = schemas[tool.id] + if (!composeOnlyFlows || !schema?.properties) return schema + const base = baseInputs(tool) + const keep = Object.keys(schema.properties).filter((k) => !isSetByAgent(base[k])) + return { + ...schema, + properties: Object.fromEntries(keep.map((k) => [k, schema.properties[k]])), + required: (schema.required ?? []).filter((k: string) => keep.includes(k)) + } + } + + /** The inputs `shownSchema` hides, shown read-only so the tool code reads in context. */ + function agentSetInputs(tool: FlowModuleTool): Record<string, InputTransform> { + if (!composeOnlyFlows) return {} + const base = baseInputs(tool) + return Object.fromEntries( + Object.keys(schemas[tool.id]?.properties ?? {}) + .filter((k) => isSetByAgent(base[k])) + .map((k) => [k, base[k]]) + ) + } function baseInputs(tool: FlowModuleTool): Record<string, InputTransform> { return ((tool.value as { input_transforms?: Record<string, InputTransform> }) @@ -182,7 +220,7 @@ {:else if schemas[tool.id] !== undefined && localArgs[tool.id] !== undefined} <InputTransformSchemaForm class="px-3 pt-1" - schema={schemas[tool.id]} + schema={shownSchema(tool)} {pickableProperties} {extraLib} {workspace} @@ -197,6 +235,13 @@ } } /> + {@const setInputs = agentSetInputs(tool)} + {#if Object.keys(setInputs).length > 0} + <div class="flex flex-col gap-1 px-3 pb-2"> + <span class="text-xs font-semibold text-emphasis">Static inputs</span> + <InputTransformsViewer inputTransforms={setInputs} /> + </div> + {/if} {:else} <div class="px-3 py-2 text-2xs text-tertiary">Loading inputs...</div> {/if} diff --git a/frontend/src/lib/components/flows/content/AgentUsePanel.svelte b/frontend/src/lib/components/flows/content/AgentUsePanel.svelte index 3f2c473937..ee5f761b69 100644 --- a/frontend/src/lib/components/flows/content/AgentUsePanel.svelte +++ b/frontend/src/lib/components/flows/content/AgentUsePanel.svelte @@ -41,7 +41,8 @@ runsAs, anyone, canShare, - channels + channels, + section }: { agentPath: string workspace: string @@ -65,10 +66,12 @@ /** Whether the user can change its Slack settings: anyone who can edit it. */ canShare: boolean channels: SlackAgentChannel[] + /** Shows only this section, without the panel's own tabs: the page offers them as its tabs. */ + section?: 'api' | 'slack' } = $props() let pickedTab = $state('api') - let tab = $derived(chat ? pickedTab : 'api') + let tab = $derived(section ?? (chat ? pickedTab : 'api')) let handle = $derived(`+${agentPath.split('/').pop()}`) let userSettings: UserSettings | undefined = $state(undefined) @@ -100,7 +103,11 @@ /> <div class="flex flex-col h-full"> - <Tabs bind:selected={() => tab, (t) => (pickedTab = t)} wrapperClass="flex-none w-full"> + <Tabs + bind:selected={() => tab, (t) => (pickedTab = t)} + hideTabs={section !== undefined} + wrapperClass="flex-none w-full" + > <Tab value="api" label="API" /> {#if chat} <Tab value="slack" label="Slack" /> @@ -132,9 +139,13 @@ {:else} {#if !signingSecretSet} <Alert type="warning" title="Agents can't answer in Slack yet" size="xs"> - The server needs the Slack app's signing secret, so Windmill can tell who sent a - message. An instance admin sets it as the <code>SLACK_SIGNING_SECRET</code> environment - variable. + Windmill needs the Slack app's signing secret to tell who sent a message. + {#if isAdmin} + A workspace's own Slack app takes it in the workspace settings, the instance's app + in the instance settings. + {:else} + A workspace or instance admin can set it. + {/if} </Alert> {/if} {#if !botName} diff --git a/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte b/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte index ecb3187c5c..8b77a29896 100644 --- a/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte +++ b/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte @@ -8,7 +8,7 @@ import FlowScriptPickerQuick from '../pickers/FlowScriptPickerQuick.svelte' import { defaultScriptLanguages, processInlineLangs } from '$lib/scripts' import { defaultScripts, enterpriseLicense, hubBaseUrlStore } from '$lib/stores' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import type { SupportedLanguage } from '$lib/common' import { createEventDispatcher, getContext, untrack } from 'svelte' import type { FlowBuilderWhitelabelCustomUi } from '$lib/components/custom_ui' @@ -35,7 +35,8 @@ } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderFlows = useOperatorBuilderFlows() + const roleCaps = useRoleCapabilities() + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) @@ -158,7 +159,7 @@ selectedKind: 'script' | 'flow' | 'approval' | 'trigger' | 'preprocessor' | 'failure' ) { if ( - !$operatorBuilderFlows && + !composeOnlyFlows && ['script', 'trigger', 'failure', 'approval', 'preprocessor'].includes(selectedKind) ) { if (!selected && preFilter == 'all') { @@ -258,7 +259,7 @@ let showAiRows = $derived( !disableAi && !$copilotInfo.workspaceDisabled && - !$operatorBuilderFlows && + !composeOnlyFlows && funcDesc?.length > 0 && kind != 'failure' && kind != 'preprocessor' && @@ -291,14 +292,14 @@ preFilter === 'all' && !selected && customUi?.aiSandbox != false && - !$operatorBuilderFlows + !composeOnlyFlows ? matchingAiSandboxes : [] ) // Hub runnables carry code the workspace never reviewed, and the backend refuses them in a // flow a builder authors, so the hub browser and its integration filters are not offered. - let showHub = $derived(!$operatorBuilderFlows) + let showHub = $derived(!composeOnlyFlows) // Every result row lives in one keyboard index space, and hovering a row moves that index, so // mouse and keyboard can never highlight two different rows. Offsets follow the render order. diff --git a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte index 5694965663..fa64fad44d 100644 --- a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte +++ b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte @@ -40,7 +40,7 @@ import type { ButtonProp } from '$lib/components/diffEditorTypes' import { loadSchemaFromModule } from '../flowInfers' import { type Job } from '$lib/gen' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { checkIfParentLoop } from '../utils.svelte' import { useWorkspaceScriptSettings } from '../useWorkspaceScriptSettings.svelte' import ScriptSettingsBadges from '$lib/components/ScriptSettingsBadges.svelte' @@ -76,7 +76,8 @@ import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderFlows = useOperatorBuilderFlows() + const roleCaps = useRoleCapabilities() + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') const { selectionManager, @@ -244,11 +245,11 @@ !flowModule.value.path?.startsWith('hub/') && flowModule.value.hash == undefined && customUi?.scriptEdit != false && - !$operatorBuilderFlows && + !composeOnlyFlows && $workspaceScriptSettingsDrawer != undefined ) // Same rule as the graph node's Run button (FlowModuleSchemaItem). - let builderCannotTestStep = $derived($operatorBuilderFlows && flowModule.value.type === 'script') + let builderCannotTestStep = $derived(composeOnlyFlows && flowModule.value.type === 'script') let workspaceScriptNoEditReason = $derived( flowModule.value.type !== 'script' || canEditWorkspaceScriptSettings ? undefined diff --git a/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte b/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte index 9d7f39ed2c..52098d33ee 100644 --- a/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte +++ b/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte @@ -8,7 +8,7 @@ import SchemaForm from '$lib/components/SchemaForm.svelte' import GfmMarkdown from '$lib/components/GfmMarkdown.svelte' import { emptyString, DynamicInput } from '$lib/utils' - import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { tick, untrack } from 'svelte' import type { Chat } from 'windmill-chat' import { saveFlowChatInputs } from './flowChatProps' @@ -80,14 +80,14 @@ extraSettings = undefined }: Props = $props() - const operatingUser = useOperatingUser() + const roleCaps = useRoleCapabilities() // Derive helperScript for dynamic inputs from schema const dynamicInputHelperScript = $derived( DynamicInput.flowHelperScript( additionalInputsSchema?.['x-windmill-dyn-select-code'], additionalInputsSchema?.['x-windmill-dyn-select-lang'], path, - operatingUser.current?.operator + !$roleCaps.code ) ) diff --git a/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts b/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts index d8dee9dcaa..6009d73ccd 100644 --- a/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts +++ b/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts @@ -20,6 +20,7 @@ import type { } from '$lib/components/copilot/chat/chatViewHost' import type { DisplayMessage, WebSearchResult } from '$lib/components/copilot/chat/shared' import type { AIAutonomyMode } from '$lib/components/copilot/chat/AIChatManager.svelte' +import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import { isPlanCardTool } from '$lib/components/copilot/chat/planMode' import { AttachedFilesStore } from '$lib/components/copilot/chat/files/attachedFiles.svelte' import { SessionArtifactsStore } from '$lib/components/copilot/chat/artifacts/artifactsState.svelte' @@ -570,7 +571,7 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender<ComposerAttac } // Typed off the interface: a Svelte component's own type resolves differently // across import specifiers, and the two would then not be assignable. - #aiChatInput: Parameters<ChatViewHost['setAiChatInput']>[0] = null + #aiChatInput: Parameters<ChatViewHost['setAiChatInput']>[0] | null = null setAiChatInput: ChatViewHost['setAiChatInput'] = (aiChatInput) => // Called from the composer's mount effect, and taking what a turn handed back reads the // draft it writes: tracked, that would rerun the effect and hand it back again. @@ -578,6 +579,9 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender<ComposerAttac this.#aiChatInput = aiChatInput this.#takeReturned() }) + releaseAiChatInput: ChatViewHost['releaseAiChatInput'] = (aiChatInput) => { + if (this.#aiChatInput === aiChatInput) this.#aiChatInput = null + } /** Whether a composer showing this conversation holds something not sent — text, an * attachment, a file still being read. Its panel stays mounted for as long as one does: @@ -734,6 +738,9 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender<ComposerAttac // runtime: its unit test would otherwise load the manager and the editor it pulls in. autonomyMode = 'default' as AIAutonomyMode.DEFAULT setAutonomyMode = () => {} + workModesAvailable = false + workMode = AIWorkMode.BUILD + setWorkMode = () => {} autoAcceptEditsActive = false autoAcceptEditsAvailable = false autoAcceptToolConfirmationsAvailable = false diff --git a/frontend/src/lib/components/flows/linkedAgentDrafts.ts b/frontend/src/lib/components/flows/linkedAgentDrafts.ts index 9367b21b12..1a5b7ac7f1 100644 --- a/frontend/src/lib/components/flows/linkedAgentDrafts.ts +++ b/frontend/src/lib/components/flows/linkedAgentDrafts.ts @@ -3,7 +3,7 @@ import { type FlowModule, type FlowValue, type InputTransform, - type OperatorSettings, + type RoleCapabilities, type Resource } from '$lib/gen' import { UserDraft } from '$lib/userDraft.svelte' @@ -123,15 +123,15 @@ export interface LinkedAgentDraft { extraPerms: Record<string, boolean> } -/** Whether `user` may write this agent's resource, in a workspace with these `operator_settings`. +/** Whether `user`, holding a role with `caps`, may write this agent's resource. * Split from the load so that resolving the drafts of a whole flow costs no `whoami` — only the * deploy dialog needs the answer, and it looks the user up once for every agent it lists. */ export function agentDraftCanWrite( draft: LinkedAgentDraft, user: UserExt | undefined, - operatorSettings: OperatorSettings | undefined + caps: RoleCapabilities ): boolean { - return canEditItem('agent', draft.path, draft.extraPerms, user, operatorSettings) + return canEditItem('agent', draft.path, draft.extraPerms, user, caps) } /** A link that cannot resolve for the user rather than because something went wrong: the agent was diff --git a/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte b/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte index 06c01dd75c..00b9172479 100644 --- a/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte +++ b/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte @@ -35,9 +35,9 @@ import DiffActionBar from './DiffActionBar.svelte' import { getGraphContext } from '$lib/components/graph/graphContext' import MoveHandleButton from '$lib/components/graph/MoveHandleButton.svelte' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' - const operatorBuilderFlows = useOperatorBuilderFlows() + const roleCaps = useRoleCapabilities() interface Props { selected?: boolean @@ -136,7 +136,9 @@ ) // A script step is tested as a script preview, which operators are refused: running the // deployed runnable is left to "Test flow". - let builderCannotTestStep = $derived($operatorBuilderFlows && mod?.value.type === 'script') + let builderCannotTestStep = $derived( + $roleCaps.flows === 'compose' && mod?.value.type === 'script' + ) let moduleTest: ModuleTest | undefined = $state(undefined) let testIsLoading = $state(false) let hover = $state(false) diff --git a/frontend/src/lib/components/flows/map/FlowStickyNode.svelte b/frontend/src/lib/components/flows/map/FlowStickyNode.svelte index 9a33bd2ce5..1d5c1d2fe1 100644 --- a/frontend/src/lib/components/flows/map/FlowStickyNode.svelte +++ b/frontend/src/lib/components/flows/map/FlowStickyNode.svelte @@ -101,7 +101,7 @@ </Popover> {/if} {#if showFlowAiButton} - <OpenInSessionButton source={sessionOpen}> + <OpenInSessionButton source={sessionOpen} deferToHeader> {#snippet fallback()} <AIButton label="Open AI chat" diff --git a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte index 62ec111b6c..b4228ea0a3 100644 --- a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte +++ b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte @@ -12,14 +12,15 @@ import RefreshButton from '$lib/components/common/button/RefreshButton.svelte' import Button from '$lib/components/common/button/Button.svelte' import { ResourceService } from '$lib/gen' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import type { FlowEditorContext } from '../types' import { logReusableAgentUsage } from '../agentTelemetry' import { BotIcon, Loader2, Plus } from 'lucide-svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderFlows = useOperatorBuilderFlows() + const roleCaps = useRoleCapabilities() + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') const dispatch = createEventDispatcher() interface Props { @@ -61,7 +62,7 @@ // Builders compose what the workspace already deployed: hub scripts bring in code nobody here // reviewed, and the backend refuses them, so never open on the hub for them. let preFilter: 'all' | 'workspace' | 'hub' = $state( - untrack(() => $operatorBuilderFlows) ? 'workspace' : 'all' + untrack(() => composeOnlyFlows) ? 'workspace' : 'all' ) let loading = $state(false) let small = $derived(smallProp ?? (kind === 'preprocessor' || kind === 'failure')) @@ -83,19 +84,20 @@ let savedAgentsLoading = $state(false) let savedAgentsWs: string | undefined = undefined async function loadSavedAgents() { - // The backend refuses a linked agent in a builder's flow. - if (!ws || savedAgentsWs === ws || $operatorBuilderFlows) { + const requested = ws + if (!requested || savedAgentsWs === requested) { return } savedAgentsLoading = true try { const rs = await ResourceService.listResource({ - workspace: ws, + workspace: requested, resourceType: 'ai_agent', perPage: 1000 }) + if (requested !== ws) return savedAgents = rs.map((r) => ({ path: r.path, description: r.description })) - savedAgentsWs = ws + savedAgentsWs = requested } catch { savedAgents = [] } finally { @@ -200,13 +202,13 @@ <StepGenQuick bind:this={stepGen} on:escape={() => dispatch('close')} - disableAi={disableAi || $operatorBuilderFlows} + disableAi={disableAi || composeOnlyFlows} on:insert bind:funcDesc {preFilter} {loading} /> - {#if selectedKind != 'preprocessor' && selectedKind != 'flow' && !$operatorBuilderFlows} + {#if selectedKind != 'preprocessor' && selectedKind != 'flow' && !composeOnlyFlows} <ToggleHubWorkspaceQuick bind:selected={preFilter} /> {/if} <RefreshButton @@ -349,7 +351,7 @@ }} /> {/if} - {#if customUi?.aiSandbox != false && !$operatorBuilderFlows} + {#if customUi?.aiSandbox != false && !composeOnlyFlows} <TopLevelNode label="AI Sandbox" selected={selectedKind === 'aisandbox'} @@ -385,9 +387,7 @@ <kbd class="!text-xs">↵</kbd> {/if} </Button> - {#if $operatorBuilderFlows} - <!-- Linked agents are refused to builders, see `loadSavedAgents`. --> - {:else if savedAgentsLoading} + {#if savedAgentsLoading} <div class="flex items-center gap-2 p-2 text-xs text-tertiary"> <Loader2 size={13} class="animate-spin" /> Loading saved agents </div> diff --git a/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte b/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte index 8c07ad1506..ff926c0c5d 100644 --- a/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte +++ b/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte @@ -60,7 +60,7 @@ {@render children?.()} <TextInput inputProps={{ - placeholder: 'Search Hub Flows' + placeholder: 'Search Hub flows' }} bind:value={filter} {size} diff --git a/frontend/src/lib/components/flows/pickers/PickHubScript.svelte b/frontend/src/lib/components/flows/pickers/PickHubScript.svelte index 5d3de9150b..5311339c3a 100644 --- a/frontend/src/lib/components/flows/pickers/PickHubScript.svelte +++ b/frontend/src/lib/components/flows/pickers/PickHubScript.svelte @@ -174,7 +174,7 @@ <div class="relative w-full"> <TextInput inputProps={{ - placeholder: 'Search Hub Scripts' + placeholder: 'Search Hub scripts' }} bind:value={filter} class="grow !pr-9" diff --git a/frontend/src/lib/components/graph/renderers/nodes/AssetNode.svelte b/frontend/src/lib/components/graph/renderers/nodes/AssetNode.svelte index cf2a7339c6..17a5e635dd 100644 --- a/frontend/src/lib/components/graph/renderers/nodes/AssetNode.svelte +++ b/frontend/src/lib/components/graph/renderers/nodes/AssetNode.svelte @@ -210,10 +210,9 @@ import { deepEqual } from 'fast-equals' import { slide } from 'svelte/transition' import AssetColumnBadges from '$lib/components/assets/AssetColumnBadges.svelte' - import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) + const roleCaps = useRoleCapabilities() interface Props { data: AssetN['data'] @@ -282,7 +281,7 @@ Could not find resource {/snippet} </Tooltip> - {:else if isSelected && assetCanBeExplored(data.asset, cachedResourceMetadata) && !actingUser?.operator} + {:else if isSelected && assetCanBeExplored(data.asset, cachedResourceMetadata) && $roleCaps.code} <div transition:slide={{ axis: 'x', duration: 100 }}> <ExploreAssetButton btnClasses="rounded-none" diff --git a/frontend/src/lib/components/handlerDraft.svelte.ts b/frontend/src/lib/components/handlerDraft.svelte.ts index a1422e42ed..ac73fc1d6a 100644 --- a/frontend/src/lib/components/handlerDraft.svelte.ts +++ b/frontend/src/lib/components/handlerDraft.svelte.ts @@ -2,7 +2,7 @@ import type { ErrorHandler } from '$lib/gen' import { WORKSPACE_SLACK_BOT_TOKEN_PATH } from '$lib/consts' import hubPaths from '$lib/hubPaths.json' -export type HandlerMode = 'error' | 'recovery' | 'success' +export type HandlerMode = 'error' | 'recovery' | 'success' | 'variableExpiration' type BuiltinDestination = 'slack' | 'teams' | 'email' export type HandlerSlot = { path?: string; args: Record<string, any> } @@ -32,6 +32,10 @@ const BUILTIN_SUFFIXES: Record<HandlerMode, Record<'slack' | 'teams', string>> = success: { slack: '/schedule-success-handler-slack', teams: '/schedule-success-handler-teams' + }, + variableExpiration: { + slack: '/variable-expiration-handler-slack', + teams: '/variable-expiration-handler-teams' } } diff --git a/frontend/src/lib/components/home/BulkActionsBar.svelte b/frontend/src/lib/components/home/BulkActionsBar.svelte index fffd18a3c0..1874008fc2 100644 --- a/frontend/src/lib/components/home/BulkActionsBar.svelte +++ b/frontend/src/lib/components/home/BulkActionsBar.svelte @@ -12,7 +12,19 @@ import { sendUserToast } from '$lib/toast' import { useReducedMotion } from '$lib/svelte5Utils.svelte' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' - import { Archive, ArchiveRestore, FolderInput, MoreHorizontal, Trash, X } from 'lucide-svelte' + import { + Archive, + ArchiveRestore, + FolderInput, + MoreHorizontal, + Trash, + WandSparkles, + X + } from 'lucide-svelte' + import { + homeComposerContext, + itemContextElement + } from '$lib/components/sessions/homeComposerContext.svelte' import { fly } from 'svelte/transition' import { blockedReason, @@ -25,6 +37,7 @@ type BulkOutcome } from './bulkActions' import type { BulkItem, HomeSelection } from './homeSelection.svelte' + import { roleCapabilities } from '$lib/stores' interface Props { selection: HomeSelection @@ -38,7 +51,7 @@ let { selection, workspace, isAdmin, moveTargets, onDone }: Props = $props() - let ctx: BulkContext = $derived({ workspace, isAdmin }) + let ctx: BulkContext = $derived({ workspace, isAdmin, caps: $roleCapabilities }) // The bar is still on screen while it flies out, and unticking the last row is // what starts that — by then the live selection is empty. Rendering the last // non-empty one keeps the count and the action states from blinking on the way @@ -49,6 +62,17 @@ }) let items = $derived(selection.items.length > 0 ? selection.items : lastNonEmpty) + // What of the selection the composer can take as context; the rest has no context element. + let askAiElements = $derived( + items.flatMap((i) => itemContextElement({ ...i, summary: i.summary || undefined }) ?? []) + ) + // The selection was the way to gather them; once they are in the composer it is done. + async function askAi() { + const elements = askAiElements + selection.exit() + for (const element of elements) await homeComposerContext.attach(element) + } + let reducedMotion = useReducedMotion() const plural = (n: number) => (n === 1 ? '' : 's') @@ -184,6 +208,20 @@ {items.length} selected </span> <div class="h-4 border-l"></div> + {#if homeComposerContext.available && askAiElements.length > 0} + <Button + variant="subtle" + unifiedSize="sm" + btnClasses="!text-ai" + startIcon={{ icon: WandSparkles }} + title={askAiElements.length < items.length + ? `Add the ${askAiElements.length} scripts, flows and code apps of the selection to the chat above` + : 'Add the selection to the chat above'} + on:click={askAi} + > + Ask AI{askAiElements.length < items.length ? ` (${askAiElements.length})` : ''} + </Button> + {/if} <Button variant="subtle" unifiedSize="sm" diff --git a/frontend/src/lib/components/home/CreateActionsMenu.svelte b/frontend/src/lib/components/home/CreateActionsMenu.svelte index 2e22b0765c..9b8db55066 100644 --- a/frontend/src/lib/components/home/CreateActionsMenu.svelte +++ b/frontend/src/lib/components/home/CreateActionsMenu.svelte @@ -16,8 +16,10 @@ Workflow, Import, Store, - PanelLeftClose + PanelLeftClose, + Folder } from 'lucide-svelte' + import MenuItem from '$lib/components/meltComponents/MenuItem.svelte' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import DbtIcon from '$lib/components/icons/DbtIcon.svelte' import { PythonIcon, TypeScriptIcon } from '$lib/components/common/languageIcons' @@ -27,6 +29,7 @@ import { importStore } from '$lib/components/apps/store' import { conditionalMelt, getLocalSetting, storeLocalSetting } from '$lib/utils' import { useEditRights } from '$lib/operatorWriteRights' + import type { EditKind } from '$lib/editRights' import { createDropdownMenu, melt } from '@melt-ui/svelte' import YAML from 'yaml' import type { Snippet } from 'svelte' @@ -47,9 +50,17 @@ * serve both this menu and the empty state's own link. */ onImportHubProject?: () => void + /** Opens the host's folder drawer. The entry is offered only when this is set. */ + onCreateFolder?: () => void } - let { trigger, triggerElement, source = 'toolbar', onImportHubProject }: Props = $props() + let { + trigger, + triggerElement, + source = 'toolbar', + onImportHubProject, + onCreateFolder + }: Props = $props() type Variant = { label: string @@ -313,11 +324,15 @@ } } - // Only the kinds this user's role authors: a builder operator gets the kinds its rights grant. + // The edit kind of an option whose key is not one: a low-code app needs `full` apps, a + // full-code one `compose`. Every other key is itself a kind (`wac` falls to `code`). + const EDIT_KIND: Record<string, EditKind> = { 'app-fullcode': 'raw_app', 'app-lowcode': 'app' } + + // Only the kinds this user's role authors. // Derived, not computed once: switching workspace only sets `workspaceStore`, it does not // remount this component, so a snapshot would keep the previous workspace's kinds. const options: Option[] = $derived( - allOptions.filter((o) => editRights.roleCanAuthor(o.key === 'app-fullcode' ? 'raw_app' : o.key)) + allOptions.filter((o) => editRights.roleCanAuthor(EDIT_KIND[o.key] ?? o.key)) ) // the doc panel only shows while an option is hovered or focused, so the menu opens compact @@ -708,8 +723,26 @@ {/if} {/each} - <!-- bottom import section: one entry whose submenu imports any artifact --> + <!-- bottom section: a folder, then one entry whose submenu imports any artifact --> <div class="mx-1 my-1 border-t border-gray-200 dark:border-gray-700"></div> + {#if onCreateFolder} + <!-- Focus also arrives on hover: melt focuses the highlighted item. --> + <MenuItem + {item} + class="w-full flex flex-row items-center gap-2.5 rounded-md px-2 py-1.5 text-left cursor-pointer transition-colors focus:outline-none data-[highlighted]:bg-surface-hover hover:bg-surface-hover" + onFocusIn={() => highlightOption(undefined)} + onClick={() => onCreateFolder()} + > + <div + class="w-6 h-6 rounded-md flex items-center justify-center shrink-0 bg-gray-100 dark:bg-gray-700" + > + <Folder size={14} class="text-gray-600 dark:text-gray-300" /> + </div> + <span class="text-xs font-medium text-primary flex-1 min-w-0 whitespace-nowrap"> + Folder + </span> + </MenuItem> + {/if} <button use:melt={$importSubTrigger} class="w-full flex flex-row items-center gap-2.5 rounded-md px-2 py-1.5 text-left cursor-pointer transition-colors focus:outline-none data-[highlighted]:bg-surface-hover hover:bg-surface-hover" diff --git a/frontend/src/lib/components/home/HomeAIChat.svelte b/frontend/src/lib/components/home/HomeAIChat.svelte index fdc76a1a00..3816a18898 100644 --- a/frontend/src/lib/components/home/HomeAIChat.svelte +++ b/frontend/src/lib/components/home/HomeAIChat.svelte @@ -1,73 +1,39 @@ <script lang="ts" module> - /** Example prompts: the short `label` is shown as a clickable tag under the chat, - * the `prompt` is what rotates through the placeholder / gets dropped into the input. */ - export const homeAIExamples: { label: string; prompt: string }[] = [ - { - label: 'Sync Salesforce', - prompt: 'Sync new Salesforce leads into a postgres table every hour' - }, - { - label: 'Ban Discord users', - prompt: - 'Build a workflow that triggers on a Discord message, checks for offensive language using an LLM, and possibly block them' - }, - { - label: 'Weekly Slack report', - prompt: 'Generate a weekly sales report from postgres and post it to Slack every Monday' - } - ] + import type HomeSessionStarterComponent from '../sessions/HomeSessionStarter.svelte' - /** An operator's session can run what is deployed, read runs and call MCP servers, but - * cannot author scripts or apps. It composes flows only where the workspace grants - * `operator_settings.builder_flows`, so none of these asks it to build anything. */ - export const homeAIOperatorExamples: { label: string; prompt: string }[] = [ - { - label: 'Run a flow', - prompt: 'Find the flow that onboards a new employee and run it for Jane Doe, starting Monday' - }, - { - label: 'Rerun failed jobs', - prompt: 'List the jobs that failed today, tell me why, and rerun the ones that timed out' - }, - { - label: 'Summarize GitHub issues', - prompt: "Read this week's open GitHub issues and summarize the ones that mention billing" - } - ] + // The starter is a full AIChat, which reaches monaco, and the build refuses monaco in Home's + // static imports. Kept once loaded, so a return to Home renders it in its first frame: the + // AI Sessions → Home view transition snapshots that frame. + let loadedStarter: typeof HomeSessionStarterComponent | undefined + function loadStarter() { + return import('../sessions/HomeSessionStarter.svelte').then((m) => (loadedStarter = m.default)) + } </script> <script lang="ts"> - import TextInput from '$lib/components/text_input/TextInput.svelte' - import { - ArrowUp, - ExternalLink, - Globe2, - KeyRound, - PlugZap, - Settings, - WandSparkles - } from 'lucide-svelte' + import { ExternalLink, Globe2, PinOff, PlugZap } from 'lucide-svelte' import Button from '../common/button/Button.svelte' - import { Badge } from '../common' import CloseButton from '../common/CloseButton.svelte' import { logFeatureUsage } from '$lib/utils/featureUsage' - import { startSessionWithPrompt } from '../sessions/sessionSwitch.svelte' - import { copilotInfo, copilotWorkspace } from '$lib/aiStore' - import { loadCopilot } from '$lib/components/copilot/loadCopilot' - import { aiUserDisabled, hubBaseUrlStore, userStore, workspaceStore } from '$lib/stores' + import { hubBaseUrlStore, roleCapabilities, workspaceStore } from '$lib/stores' + import { sessionState } from '../sessions/sessionState.svelte' + import { currentWorkspaceRootId } from '../sessions/sessionScope.svelte' import { HOME_SHOW_HUB } from '$lib/consts' import { getLocalSetting, storeLocalSetting } from '$lib/utils' - import { isRuleActive } from '$lib/workspaceProtectionRules.svelte' import { useReducedMotion } from '$lib/svelte5Utils.svelte' import { BROWSER } from 'esm-env' - import AIChatModelSettings from '../copilot/chat/AIChatModelSettings.svelte' import HomeConnectDrawer from './HomeConnectDrawer.svelte' - import { USER_SETTINGS_HASH } from '../sidebar/settings' + import HomeComposerSkeleton, { + composerHeight, + rememberComposerHeight + } from './HomeComposerSkeleton.svelte' import { prefersSessionHandoff } from '../copilot/chat/global/gate' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' - import { onboardingProfile } from '$lib/onboardingProfile' + import { prefetchComposerSignals } from '../copilot/chat/starter/starterPrompts.svelte' + import { useWorkspaceAiHidden } from '../copilot/workspaceAiHidden.svelte' + import { homeQuickAccessSettings } from './homeQuickAccessSettings.svelte' const COLLAPSED_SETTING = 'home-ai-composer-collapsed' @@ -76,291 +42,99 @@ * labelled buttons without the trail starting to truncate. Below it they fold back. */ const BAR_FITS_SIDE_TRIPS = 1024 const sideTripsInBar = $derived(pageHeader.barWidth >= BAR_FITS_SIDE_TRIPS) - const hubOffered = $derived(!$userStore?.operator && HOME_SHOW_HUB) + const hubOffered = $derived($roleCapabilities.code && HOME_SHOW_HUB) - let value = $state('') - // The stock examples for the reader's role, unless the invite that brought this person here wrote prompts for - // them — those replace the set outright rather than joining it, since a prompt written - // for someone's own stack next to "Ban Discord users" reads as the generic one. - let invitePrompts: { label: string; prompt: string }[] | undefined = $state(undefined) - void onboardingProfile().then((p) => { - if (!p?.starter_prompts?.length) return - invitePrompts = p.starter_prompts - promptIndex = 0 - }) - let examples = $derived( - invitePrompts ?? ($userStore?.operator ? homeAIOperatorExamples : homeAIExamples) - ) - let placeholderVisible = $state(true) let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined) - // How much of the home page this reader wants the composer to take, so it lives per browser - // rather than per workspace or account. - let collapsed = $state(BROWSER && getLocalSetting(COLLAPSED_SETTING) === 'true') - function setCollapsed(next: boolean) { - collapsed = next + // Whether this reader wants the composer on the home page at all, so it lives per browser + // rather than per workspace or account. It has nothing to do with the composer's one-line + // state despite the key's name; renaming the key would reset every reader's choice. + let removed = $state(BROWSER && getLocalSetting(COLLAPSED_SETTING) === 'true') + function setRemoved(next: boolean) { + removed = next storeLocalSetting(COLLAPSED_SETTING, next ? 'true' : undefined) } // Removing puts the composer away rather than throwing it out, and the way back is one item in // the band's menu — so the ellipsis flashes as it appears, in a corner nobody is watching while - // the hero collapses in the middle of the page. + // the composer leaves the page. // - // A keyframe animation, not a transition: this mounts in the same flush that collapses the - // hero, so the frame that would paint it at rest is the frame it is already told to leave, and + // A keyframe animation, not a transition: this mounts in the same flush that removes the + // composer, so the frame that would paint it at rest is the frame it is already told to leave, and // one `requestAnimationFrame` is not reliably past that paint. The flash then goes straight to // invisible without ever being drawn. Mounted only while pulsing, so each removal replays it. const PULSE_MS = 1000 + const reducedMotion = useReducedMotion() let pulsing = $state(false) let pulseEndTimer: ReturnType<typeof setTimeout> | undefined - // `no_ai` is the overlay's button, shown only while AI is unusable here. - function removeComposer(source: 'close' | 'no_ai') { - logFeatureUsage('home', 'ai_hero_remove', { key: source }) - setCollapsed(true) + function removeComposer() { + // The `close` key keeps these events in the series they have always been counted in. + logFeatureUsage('home', 'ai_hero_remove', { key: 'close' }) + setRemoved(true) if (reducedMotion.val) return clearTimeout(pulseEndTimer) pulsing = true pulseEndTimer = setTimeout(() => (pulsing = false), PULSE_MS) } - // In global-AI mode the layout's chat panel is disabled and never loads the copilot - // config, so the home chat loads it for the current workspace itself. - $effect(() => { - if ($workspaceStore) { - loadCopilot($workspaceStore) - } - }) + let HomeSessionStarter = $state(loadedStarter) + if (!loadedStarter) void loadStarter().then((c) => (HomeSessionStarter = c)) + // The starter waits on the workspace's item count before it mounts, and its suggestions on + // the other signals; asked alongside its code rather than once the code has loaded, they + // are no extra wait. + if ($workspaceStore) prefetchComposerSignals($workspaceStore) - // Whether the copilot config has actually loaded for the current workspace. - let configLoaded = $derived($copilotWorkspace === $workspaceStore) - // No usable model (no provider configured, or AI disabled): the input is blurred and an overlay - // explains why and links to the fix. Gate on `configLoaded` so the initial (unloaded) state - // doesn't flash the overlay while a provider is in fact configured. - let disabled = $derived(configLoaded && !$copilotInfo.enabled) - // Submission is stricter than the overlay: block it until the config is loaded AND - // enabled. Submitting during the unknown-config window hands the prompt to a session - // that only sends once `copilotInfo.enabled` flips true — on an unconfigured/disabled - // workspace that never happens and the prompt is silently lost. - let canSend = $derived(configLoaded && $copilotInfo.enabled) + // Whether Home's own workspace hides the assistant, read for that workspace: once the block + // shows, the shared copilot config is the draft's, so a draft acting on a workspace that hides + // AI would otherwise take the whole block, and the picker that could undo it, off Home. + const homeAiHidden = useWorkspaceAiHidden(() => $workspaceStore ?? undefined) - // The input alone: what the overlay covers and the one part a missing provider makes unusable. - let blurClass = $derived(disabled ? 'blur-sm pointer-events-none select-none' : '') - - // Disabled because the user spent their free Windmill AI grant, not because AI was never - // set up — the two look identical otherwise, and the "configure AI" copy would be a lie. - let freeTierExhausted = $derived($copilotInfo.freeTier?.exhausted === true) - - // A workspace locked against direct deployment is run, not authored in, so its home page drops - // the composer and the button to reopen it. This is about the workspace, not the caller: - // `createSession` would steer a prompt into the paired dev workspace and an admin bypasses the - // lock outright, yet neither makes prod the place to start one. Unresolved rules read as - // unlocked, so the far commoner unlocked workspace never pops the composer in mid-load. - let runOnlyWorkspace = $derived(isRuleActive('DisableDirectDeployment')) - - // The composer hands off to /sessions, which refuses operators and users opted out of the - // sessions beta — so hide it from them (the prompt would be silently dropped) while the + // The composer hands off to /sessions, which refuses roles that cannot code and users opted out + // of the sessions beta — so hide it from them (the prompt would be silently dropped) while the // AI-independent CLI/MCP row below stays. let showComposer = $derived( - prefersSessionHandoff($userStore?.operator) && - !runOnlyWorkspace && - !$copilotInfo.workspaceDisabled + prefersSessionHandoff(!$roleCapabilities.code) && !homeAiHidden.hidden ) - // The hero's margins and centered column are for the full block. The lone button row left - // by a collapsed, opted-out, run-only or hidden-assistant view is a hint line and should - // cost the page almost nothing: no top margin, and the content column's full width so it - // hugs the right edge instead of floating centered in empty space. - let hero = $derived(showComposer && !collapsed) - let outerSpacing = $derived(hero ? 'mt-20 mb-16' : 'mt-0 mb-1') - - let starting = $state(false) - async function start() { - if (!canSend || starting || !value.trim()) return - starting = true - try { - await startSessionWithPrompt(value, { autoSend: true }) - } finally { - starting = false - } - } - - // Enter starts the session; Shift+Enter keeps inserting a newline. - function onKeydown(e: KeyboardEvent) { - if (e.key === 'Enter' && !e.shiftKey) { - e.preventDefault() - start() - } - } - - let prompts = $derived(examples.map((e) => e.prompt)) - - const CYCLE_MS = 7_000 - // Must match the `duration-*` class on the placeholder overlay: the swap happens once the - // fade-out has finished, and Tailwind only emits classes it finds written out in full. - const FADE_MS = 600 - - // Rotate the example prompt every CYCLE_MS: fade the placeholder out, swap it, fade it back in. - // Only while the composer is shown — otherwise it would loop forever driving an - // unrendered input — and not under reduced motion, where the first prompt simply stays put. - // The index lives outside the effect so re-showing the composer resumes the rotation from the - // prompt currently displayed rather than restarting it. - const reducedMotion = useReducedMotion() - let promptIndex = $state(0) - let placeholder = $derived(prompts[promptIndex % prompts.length]) - $effect(() => { - if (!showComposer || collapsed || reducedMotion.val) return - let timer: ReturnType<typeof setTimeout> - - function next() { - placeholderVisible = false - timer = setTimeout(() => { - promptIndex = (promptIndex + 1) % prompts.length - placeholderVisible = true - timer = setTimeout(next, CYCLE_MS) - }, FADE_MS) - } - - timer = setTimeout(next, CYCLE_MS) - return () => { - clearTimeout(timer) - // Torn down mid-fade, the input would otherwise remount with an invisible placeholder. - placeholderVisible = true - } - }) + let hero = $derived(showComposer && !removed) </script> -<div class="w-full flex justify-center {outerSpacing}"> - <div class="{hero ? 'max-w-[40rem]' : ''} grow relative group"> - {#if showComposer && !collapsed} - {#if !disabled} - <!-- The one dismiss control while the composer is usable; the overlay below carries its - own once it takes over, so the two never show at the same time. --> - <div class="absolute right-0 top-0 z-20"> - <CloseButton - small - noBg - title="Remove session chat" - onClick={() => removeComposer('close')} +<div class="w-full {hero ? 'mt-2' : 'mb-1'}"> + <div class="relative group/composer"> + {#if hero} + <!-- In the page's side padding, clear of the composer's own controls at its right end, + and centred on the composer's first row: the one-line box's middle, and where that + row stays once the box opens downward. Shown on hover; the container starts at the + composer's edge so the pointer reaches the unpin button without leaving the hovered + zone. Below `sm` there is no side padding to hold it, so unpinning is in the band's + menu instead. --> + <div + class="hidden sm:block absolute top-4 left-full pl-1 z-20 transition-opacity opacity-0 group-hover/composer:opacity-100 focus-within:opacity-100" + > + <CloseButton small noBg Icon={PinOff} title="Unpin from Home" onClick={removeComposer} /> + </div> + <!-- The block is a session's chat, so it waits for the sessions it might reuse. Keyed on + the workspace family, not the workspace: another family needs its own draft, but a + fork shares its parent's, and remounting for it only flashes the block. --> + {#if HomeSessionStarter && sessionState.hydrated} + {#key $currentWorkspaceRootId} + <HomeSessionStarter + {placeholder} + onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)} /> - </div> + {/key} + {:else} + {@render placeholder()} {/if} - <div class="flex items-center justify-center gap-2 mb-4"> - <p class="text-center font-regular text-3xl"> - {$userStore?.operator ? 'Run with AI' : 'Build with AI'} - </p> - <Badge color="blue" small>Beta</Badge> - </div> - <!-- Anchors the send button / model settings to the input, not to the whole block — the row - below would otherwise push them down. The inner wrapper stays `relative` in both - states: `blur-sm` is a filter, which makes an element the containing block for its - absolutely positioned children, so those two would shift when the blur turns on. --> - <div class="relative"> - <div class="relative {blurClass}" inert={disabled}> - <TextInput - bind:value - class="resize-none px-4 py-3 pb-9 shadow-sm border-accent" - underlyingInputEl="textarea" - inputProps={{ - rows: 4, - 'aria-label': $userStore?.operator - ? 'Describe what you want to do' - : 'Describe what you want to build', - onkeydown: onKeydown - }} - /> - {#if !value} - <!-- Drawn over the textarea instead of set as its `placeholder`: WebKit and Gecko do - not run transitions on `::placeholder`, so the fade would be a hard cut there. - The 1px margin is the textarea's border, so the text sits where typing starts. --> - <span - aria-hidden="true" - class="pointer-events-none absolute inset-x-4 top-3 m-px text-xs text-hint transition-opacity duration-[600ms] ease-in-out {placeholderVisible - ? 'opacity-100' - : 'opacity-0'}" - > - {placeholder} - </span> - {/if} - <Button - endIcon={starting ? {} : { icon: ArrowUp }} - wrapperClasses="absolute right-2 bottom-3.5" - variant={value.trim() ? 'accent' : 'subtle'} - iconOnly - loading={starting} - disabled={!value.trim() || starting || !canSend} - onclick={start} - ></Button> - <div class="absolute left-3 bottom-4 flex items-center gap-1.5 px-0.5"> - <AIChatModelSettings /> - </div> - </div> - {#if disabled} - <!-- Covers the input alone: the title, the example prompts and the CLI/MCP row are all - still legible and usable without a provider. Static, not hover-gated, so keyboard - and touch users see it too. --> - <div - class="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 rounded-md bg-surface/70" - > - <p class="text-sm text-secondary"> - {#if $aiUserDisabled} - Windmill AI is disabled in your account settings - {:else if freeTierExhausted} - You have used all of your free Windmill AI tokens - {:else} - No AI provider is configured - {/if} - </p> - <div class="flex items-center gap-2"> - {#if $aiUserDisabled} - <!-- The fix lives in account settings (a hash-opened drawer, not a route), so link - the hash the sidebar's Account menu uses rather than the workspace AI settings. --> - <Button - unifiedSize="sm" - variant="accent" - startIcon={{ icon: Settings }} - href={USER_SETTINGS_HASH} - > - Open account settings - </Button> - {:else} - <Button - unifiedSize="sm" - variant="accent" - startIcon={{ icon: freeTierExhausted ? KeyRound : Settings }} - href="/workspace_settings?tab=ai" - > - {freeTierExhausted ? 'Add your own API key' : 'Configure AI'} - </Button> - {/if} - <Button unifiedSize="sm" variant="default" onClick={() => removeComposer('no_ai')} - >Remove</Button - > - </div> - </div> - {/if} - </div> {/if} - - <div class="flex items-center justify-between gap-2 pt-2"> - {#if showComposer && !collapsed} - <div class="flex flex-row flex-wrap items-center gap-1.5"> - {#each examples as example (example.label)} - <Button - variant="default" - unifiedSize="xs" - btnClasses="!rounded-full !text-2xs !text-hint" - onClick={() => (value = example.prompt)} - > - {example.label} - </Button> - {/each} - </div> - {/if} - </div> </div> </div> +{#snippet placeholder()} + <HomeComposerSkeleton height={composerHeight($workspaceStore ?? undefined)} /> +{/snippet} + <HomeConnectDrawer bind:this={homeConnectDrawer} /> <!-- Everything the hero offered beside the composer lives in the band's menu: the connect helper, @@ -406,9 +180,9 @@ <!-- Nothing left to hold once the side trips stand in the bar and the composer is on the page: an ellipsis that opens an empty menu is a button that does nothing. --> <!-- No menu while the hero is on the page and its side trips are in the bar: the hero's own - cross removes it, so an ellipsis holding a second way to do that is a button whose only + unpin button removes it, so an ellipsis holding a second way to do that is a button whose only item is a duplicate. --> - {#if !sideTripsInBar || (showComposer && collapsed)} + {#if !sideTripsInBar || (showComposer && removed) || homeQuickAccessSettings.hidden} <!-- The flash rides the ellipsis itself, not the row: with the side trips beside it the row is three controls wide, and marking all three names none of them. --> <span class="relative inline-flex"> @@ -421,35 +195,54 @@ class="pointer-events-none absolute -inset-1 rounded-lg bg-blue-500/30 opacity-0 animate-fade-out" ></span> {/if} + <!-- The same flash for hiding the favorites & recent section. It rests at opacity 0, so + it can stay mounted; the key replays it on each hide. --> + {#if homeQuickAccessSettings.hideCount > 0 && !reducedMotion.val} + {#key homeQuickAccessSettings.hideCount} + <span + aria-hidden="true" + class="pointer-events-none absolute -inset-1 rounded-lg bg-blue-500/30 opacity-0 animate-fade-out" + ></span> + {/key} + {/if} <DropdownV2 placement="bottom-end" size="sm" + customWidth={240} items={[ - ...(showComposer && collapsed + // Every phone gets the menu, and there the composer has no room for its own unpin + // button. The menu can also hold the section's pin, so the label names the session. + ...(hero ? [{ displayName: 'Unpin session from Home', action: removeComposer }] : []), + ...(showComposer && removed ? [ { displayName: 'Pin session hero to homepage', - icon: WandSparkles, action: () => { logFeatureUsage('home', 'ai_hero_pin') - setCollapsed(false) + setRemoved(false) } } ] : []), + ...(homeQuickAccessSettings.hidden + ? [ + { + displayName: 'Pin favorites & recent to homepage', + action: () => homeQuickAccessSettings.setHidden(false) + } + ] + : []), ...(sideTripsInBar ? [] : [ { displayName: 'CLI / MCP', - icon: PlugZap, action: () => homeConnectDrawer?.openDrawer?.() }, ...(hubOffered ? [ { displayName: 'Hub', - icon: Globe2, href: $hubBaseUrlStore, hrefTarget: '_blank' as const } diff --git a/frontend/src/lib/components/home/HomeComposerSkeleton.svelte b/frontend/src/lib/components/home/HomeComposerSkeleton.svelte new file mode 100644 index 0000000000..cd81077342 --- /dev/null +++ b/frontend/src/lib/components/home/HomeComposerSkeleton.svelte @@ -0,0 +1,108 @@ +<script lang="ts" module> + import { getLocalSetting, storeLocalSetting } from '$lib/utils' + + const HEIGHT_SETTING = 'home-composer-height:' + // The box's 4px top margin and the 8px under the block. + const BLOCK_MARGINS = 12 + // The suggestion chips' row under an open box. A disabled composer has none, and its box, + // the shortest open one, is 78px. + const SUGGESTIONS_ROW = 36 + const OPEN_BOX_MIN = 78 + // The one-line box is 48px in Chromium but taller in Firefox, so the shape is told apart by + // the shortest open block: anything below it is one line, whatever the browser. + const OPEN_MIN_HEIGHT = OPEN_BOX_MIN + BLOCK_MARGINS + + /** The height Home's composer took when it last appeared in this workspace. */ + export function composerHeight(workspace: string | undefined): number | undefined { + const stored = workspace ? Number(getLocalSetting(HEIGHT_SETTING + workspace)) : NaN + return Number.isFinite(stored) && stored > 0 ? stored : undefined + } + + export function rememberComposerHeight(workspace: string | undefined, height: number) { + if (workspace && height > 0) storeLocalSetting(HEIGHT_SETTING + workspace, String(height)) + } +</script> + +<script lang="ts"> + import { ArrowUp, MessagesSquare } from 'lucide-svelte' + import { twMerge } from 'tailwind-merge' + import Button from '../common/button/Button.svelte' + import { + composerBoxClass, + HERO_BOX_CLASS, + STARTER_PLACEHOLDER + } from '../copilot/chat/composerBox' + + // Stands in for the composer while its code and config load, drawn as the composer it + // replaces: the same box, mark and placeholder, in the shape it last took in this workspace. + // Without a remembered height it is the one-line shape, which is what a workspace past a + // handful of items rests in. + let { height }: { height?: number } = $props() + + const open = $derived(height !== undefined && height >= OPEN_MIN_HEIGHT) + const suggestions = $derived(open && height! - BLOCK_MARGINS - SUGGESTIONS_ROW >= OPEN_BOX_MIN) + const boxClass = twMerge(composerBoxClass(), HERO_BOX_CLASS) +</script> + +{#snippet bar(width: string)} + <span class="animate-skeleton dark:bg-frost-900/50 rounded h-3 {width}"></span> +{/snippet} + +{#snippet sendButton()} + <Button variant="subtle" unifiedSize="sm" iconOnly disabled startIcon={{ icon: ArrowUp }} /> +{/snippet} + +<div + class="w-full pb-2 flex flex-col" + style:height={height !== undefined ? `${height}px` : undefined} + aria-busy="true" + aria-label="Loading the AI composer" +> + <!-- The placeholder's `-px` offsets stand for the real field's transparent 1px border. --> + {#if open} + <div class="mt-1 flex-1 min-h-0 flex flex-col {boxClass}"> + <div class="flex items-start"> + <span class="flex items-center h-5 mt-[13px] ml-4 shrink-0"> + <MessagesSquare size={16} class="text-ai" /> + </span> + <span class="mt-px ml-px pl-2 pr-4 pt-3 text-xs leading-5 text-gray-500 truncate"> + {STARTER_PLACEHOLDER} + </span> + </div> + <div class="mt-auto flex flex-row items-center gap-1.5 px-3 pb-1.5"> + <div class="flex-1 min-w-0 flex flex-row items-center gap-3"> + {@render bar('w-24')} + {@render bar('w-20')} + </div> + {@render bar('w-12')} + {@render sendButton()} + </div> + </div> + {#if suggestions} + <div class="pt-2 flex flex-row items-center gap-1.5 shrink-0"> + {#each ['w-20', 'w-24', 'w-24'] as width, i (i)} + <span class="h-7 px-3 flex items-center rounded-full border border-border-light"> + {@render bar(width)} + </span> + {/each} + </div> + {/if} + {:else} + <div + class="mt-1 {height !== undefined + ? 'flex-1 min-h-0' + : 'h-12'} flex flex-row items-center {boxClass}" + > + <span class="flex items-center ml-4 shrink-0"> + <MessagesSquare size={16} class="text-ai" /> + </span> + <span class="flex-1 min-w-0 ml-px pl-2 pr-2 text-xs leading-5 text-gray-500 truncate"> + {STARTER_PLACEHOLDER} + </span> + <div class="flex flex-row items-center gap-1 pr-3 shrink-0"> + {@render bar('w-12')} + {@render sendButton()} + </div> + </div> + {/if} +</div> diff --git a/frontend/src/lib/components/home/HomeConnectDrawer.svelte b/frontend/src/lib/components/home/HomeConnectDrawer.svelte index 2b86025549..ff451b1da4 100644 --- a/frontend/src/lib/components/home/HomeConnectDrawer.svelte +++ b/frontend/src/lib/components/home/HomeConnectDrawer.svelte @@ -5,13 +5,11 @@ import CopyableCodeBlock from '$lib/components/details/CopyableCodeBlock.svelte' import { Bot, ExternalLink, Terminal } from 'lucide-svelte' import { shell } from 'svelte-highlight/languages' - import { mcpTokenUrlDisabled } from '$lib/mcpAuth' import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' type ConnectTab = 'cli' | 'mcp' let drawer: Drawer | undefined = $state() - let tokenUrlDisabled = $state(false) let selectedTab: ConnectTab = $state('cli') let openVersion = $state(0) @@ -27,10 +25,6 @@ wmill sync pull`) export function openDrawer(tab: ConnectTab = 'cli') { selectedTab = tab openVersion += 1 - // Falls back like CreateToken below, which shows the bare URL when the read fails. - void mcpTokenUrlDisabled() - .then((v) => (tokenUrlDisabled = v)) - .catch(() => (tokenUrlDisabled = true)) drawer?.openDrawer() } @@ -105,15 +99,12 @@ wmill sync pull`) <div class="flex flex-col gap-4"> <div class="flex items-start justify-between gap-3 flex-wrap"> <div class="flex flex-col gap-1"> - <h3 class="text-sm font-semibold text-emphasis">MCP URL</h3> + <h3 class="text-sm font-semibold text-emphasis" + >Build and run from your AI client</h3 + > <p class="text-xs text-secondary max-w-xl"> - {#if tokenUrlDisabled} - The MCP server URL for the current workspace. Your client signs in to - Windmill to use it. - {:else} - Generate an MCP server URL for the current workspace and choose which - scripts, flows, and endpoints the client can access. - {/if} + Connect Claude, ChatGPT or Cursor to Windmill: build scripts, flows and + apps, run your automations and check their runs, from your chat. </p> </div> diff --git a/frontend/src/lib/components/home/HomeQuickAccess.svelte b/frontend/src/lib/components/home/HomeQuickAccess.svelte new file mode 100644 index 0000000000..b81f848838 --- /dev/null +++ b/frontend/src/lib/components/home/HomeQuickAccess.svelte @@ -0,0 +1,481 @@ +<script lang="ts"> + import { + AtSign, + Check, + ChevronLeft, + ChevronRight, + Copy, + Eye, + EyeOff, + GitFork, + LayoutGrid, + List, + Pen, + Star as StarIcon, + StarOff, + X + } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import { useEditRights } from '$lib/operatorWriteRights' + import { roleCapabilities } from '$lib/stores' + import { AppService } from '$lib/gen' + import { copyToClipboard, type Item } from '$lib/utils' + import RowIcon from '$lib/components/common/table/RowIcon.svelte' + import Star from '$lib/components/Star.svelte' + import TimeAgo from '$lib/components/TimeAgo.svelte' + import { + favoriteManager, + getFavoriteHref, + type FavoriteKind + } from '$lib/components/sidebar/FavoriteMenu.svelte' + import { MAX_AGE_DAYS, recentItems, type RecentKind, type RecentVia } from './recentItems.svelte' + import { useReducedMotion } from '$lib/svelte5Utils.svelte' + import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate' + import { + homeComposerContext, + itemContextElement + } from '$lib/components/sessions/homeComposerContext.svelte' + import HomeSectionLabel from './HomeSectionLabel.svelte' + import HomeSectionCount from './HomeSectionCount.svelte' + import { QUICK_ACCESS_ROWS, homeQuickAccessSettings } from './homeQuickAccessSettings.svelte' + + interface Props { + workspace: string + /** Cleared where direct-deploy protection hides the rows' edit actions. */ + showEditButtons?: boolean + /** For the items card's heading, which shows only under this section: alone on the + * page, a heading has nothing to tell apart. */ + itemCount?: number + } + + let { workspace, showEditButtons = true, itemCount }: Props = $props() + + type Entry = { + kind: RecentKind + /** The kind its favorite is stored under: every app, raw ones included, stars as `app` + * (AppRow, and the app listing's starred join), so a raw app's must not be `raw_app`. */ + starKind: FavoriteKind + path: string + title: string + at?: number + via?: RecentVia + } + + function asStarKind(kind: RecentKind): FavoriteKind { + return kind === 'raw_app' ? 'app' : kind + } + + const RECENT_COUNT = 6 + + // The way back from Hide from Home is in the header menu HomeAIChat adds, which Home mounts + // only with the AI sessions beta on. Without it the section can't be hidden, and one hidden + // earlier shows again. + const restoreMenuOnPage = isGlobalAiEnabled() + let hidden = $derived(restoreMenuOnPage && homeQuickAccessSettings.hidden) + + // Turning off the last list shown would leave an empty section; Hide from Home does that. + const sectionMenu = (): Item[] => [ + { + displayName: 'Show favorites', + description: 'Items you starred', + toggle: homeQuickAccessSettings.showFavorites, + disabled: homeQuickAccessSettings.showFavorites && !homeQuickAccessSettings.showRecent, + action: () => homeQuickAccessSettings.setShowFavorites(!homeQuickAccessSettings.showFavorites) + }, + { + displayName: 'Show recent', + description: `Scripts, flows and apps you opened or edited in the last ${MAX_AGE_DAYS} days, in this browser`, + toggle: homeQuickAccessSettings.showRecent, + disabled: homeQuickAccessSettings.showRecent && !homeQuickAccessSettings.showFavorites, + action: () => homeQuickAccessSettings.setShowRecent(!homeQuickAccessSettings.showRecent) + }, + { + displayName: 'Grid size', + separatorTop: true, + icon: LayoutGrid, + submenuItems: QUICK_ACCESS_ROWS.map((rows) => ({ + displayName: rows === 1 ? '1 row' : `${rows} rows`, + icon: homeQuickAccessSettings.rows === rows ? Check : undefined, + action: () => homeQuickAccessSettings.setRows(rows) + })) + }, + { + displayName: 'Hide from Home', + icon: EyeOff, + hide: !restoreMenuOnPage, + action: () => homeQuickAccessSettings.setHidden(true) + } + ] + + // Only the role is checked: the cards don't carry the item's own permissions, and an + // editor opened without write access says so itself. + const editRights = useEditRights() + + // A favorite app arrives as plain `app` (the layout lists apps without their subtype), and + // `/apps/edit` mounts the low-code editor whatever it opens, so the editor routes ask which + // one it is, once, when its menu opens. + async function editorKind(item: Entry): Promise<RecentKind> { + if (item.kind !== 'app') return item.kind + try { + const app: any = await AppService.getAppLiteByPath({ workspace, path: item.path }) + return app?.raw_app ? 'raw_app' : 'app' + } catch { + return 'app' + } + } + + // The row menus' actions that need nothing but the kind and path. Moving, deleting, + // deploying and sharing need the full item and the row's own drawers, so they stay there. + async function menuItems(item: Entry, favorite: boolean): Promise<Item[]> { + const kind = await editorKind(item) + const base = kind === 'raw_app' ? 'apps_raw' : `${kind}s` + const contextElement = itemContextElement({ + kind: kind === 'raw_app' ? 'app' : kind, + rawApp: kind === 'raw_app', + path: item.path, + summary: item.title === item.path ? undefined : item.title + }) + return [ + { + displayName: 'Add to AI session context', + icon: AtSign, + type: 'ai', + action: () => contextElement && homeComposerContext.attach(contextElement), + hide: !contextElement || !homeComposerContext.available + }, + { + displayName: 'Edit', + icon: Pen, + href: `/${base}/edit/${item.path}`, + hide: !showEditButtons || !editRights.roleCanAuthor(kind) + }, + { + displayName: 'Duplicate/Fork', + icon: GitFork, + href: `/${base}/add?template=${item.path}`, + hide: !showEditButtons || !$roleCapabilities.code || kind === 'agent' + }, + { + displayName: 'View runs', + icon: List, + // An agent run is a flow preview, which the runs page hides by default. + href: `/runs/${item.path}${item.kind === 'agent' ? '?job_kinds=previews' : ''}`, + hide: item.kind === 'app' || item.kind === 'raw_app' + }, + { + displayName: 'Audit logs', + icon: Eye, + href: `/audit_logs?resource=${item.path}`, + hide: !$roleCapabilities.code || !$roleCapabilities.visibility.audit_logs + }, + { displayName: 'Copy path', icon: Copy, action: () => copyToClipboard(item.path) }, + { + displayName: favorite ? 'Remove from favorites' : 'Add to favorites', + icon: favorite ? StarOff : StarIcon, + separatorTop: true, + action: () => + favorite + ? favoriteManager.unstar(item.path, item.starKind, workspace) + : favoriteManager.star(item.path, item.starKind, workspace, item.title) + }, + { + displayName: 'Remove from recent', + icon: X, + action: () => recentItems.forget(workspace, item.kind, item.path), + hide: favorite + } + ] + } + + // Assets are favorites too, but they open in the database manager rather than at a page, + // so they stay in the sidebar's menu. + let favorites: Entry[] = $derived( + favoriteManager.current.flatMap((f) => + f.kind === 'asset' ? [] : [{ kind: f.kind, starKind: f.kind, path: f.path, title: f.label }] + ) + ) + // Favorites first, then what was opened lately; a starred item is listed once, as a favorite. + // With the favorites turned off, a starred item opened lately shows among the recent ones. + let recentAll: Entry[] = $derived.by(() => { + const { showFavorites, showRecent } = homeQuickAccessSettings + const starred = new Set( + showFavorites ? favorites.map((f) => `${asStarKind(f.kind)}/${f.path}`) : [] + ) + return (showRecent ? recentItems.list(workspace) : []) + .filter((r) => !starred.has(`${asStarKind(r.kind)}/${r.path}`)) + .map((r) => ({ + kind: r.kind, + starKind: asStarKind(r.kind), + path: r.path, + title: r.summary || r.path, + at: r.at, + via: r.via + })) + }) + // Grows by a page from the "Load next" card; back to one page on the next visit. + let recentLimit = $state(RECENT_COUNT) + let recentMore = $derived(Math.max(0, recentAll.length - recentLimit)) + let entries: { item: Entry; favorite: boolean }[] = $derived([ + ...(homeQuickAccessSettings.showFavorites ? favorites : []).map((item) => ({ + item, + favorite: true + })), + ...recentAll.slice(0, recentLimit).map((item) => ({ item, favorite: false })) + ]) + + // The list turned off has items, the one left on has none. The section stays, or its menu + // (the only way to turn the list back on) would leave with it. + let emptiedBySettings = $derived( + entries.length === 0 && + ((!homeQuickAccessSettings.showFavorites && favorites.length > 0) || + (!homeQuickAccessSettings.showRecent && recentItems.list(workspace).length > 0)) + ) + + // Read when the pointer reaches the time, so the tooltip is current however long the + // page has been open. + let now = $state(Date.now()) + + function recentTooltip(at: number, via: RecentVia | undefined): string { + const mins = Math.max(0, Math.floor((now - at) / 60_000)) + const unit = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'} ago` + const ago = + mins < 1 + ? 'just now' + : mins < 60 + ? unit(mins, 'minute') + : mins < 1440 + ? unit(Math.floor(mins / 60), 'hour') + : unit(Math.floor(mins / 1440), 'day') + return `${via === 'view' ? 'Opened' : 'Edited'} by you ${ago}` + } + + // Everything the lists hold, the recent ones not loaded yet included. + let favoriteCount = $derived(homeQuickAccessSettings.showFavorites ? favorites.length : 0) + let recentCount = $derived(recentAll.length) + + // The cards fill one screen at a time, row by row, and the next screen scrolls in from the + // right. Placed by hand: the grid's own flow fills either whole rows across every screen or + // whole columns. The column counts follow the `auto-cols` breakpoints below. + let innerWidth = $state(1280) + let cols = $derived(innerWidth >= 1024 ? 3 : innerWidth >= 640 ? 2 : 1) + let cellCount = $derived(entries.length + (recentMore > 0 ? 1 : 0)) + // Fewer rows when there aren't enough cards to fill a screen. + let rows = $derived(Math.min(homeQuickAccessSettings.rows, Math.ceil(cellCount / cols))) + + function cellPosition(index: number): { row: number; column: number } { + const perScreen = cols * rows + const screen = Math.floor(index / perScreen) + const within = index % perScreen + return { row: Math.floor(within / cols) + 1, column: screen * cols + (within % cols) + 1 } + } + + let scroller: HTMLDivElement | undefined = $state(undefined) + let canBack = $state(false) + let canForward = $state(false) + + function measure() { + if (!scroller) return + canBack = scroller.scrollLeft > 1 + canForward = scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 1 + } + + // No scroll snap: when the favorites load in front of the recent cards, a snapped scroller + // follows the card it had snapped to and opens scrolled to the end. One page (the width + // inside the scroller's 1px padding) plus the grid's 8px gap lands on a column edge by itself. + // Animated by hand: `behavior: 'smooth'` runs at the browser's own pace, which is slow for a + // page this wide. A click during the animation moves on from where the last one was going. + const PAGE_MS = 200 + const reducedMotion = useReducedMotion() + let scrollTarget: number | undefined + let scrollFrame: number | undefined + + function page(direction: 1 | -1) { + const el = scroller + if (!el) return + const max = el.scrollWidth - el.clientWidth + const from = el.scrollLeft + const to = Math.max( + 0, + Math.min(max, (scrollTarget ?? from) + direction * (el.clientWidth - 2 + 8)) + ) + if (scrollFrame != undefined) cancelAnimationFrame(scrollFrame) + if (reducedMotion.val) { + el.scrollLeft = to + return + } + scrollTarget = to + const start = performance.now() + const step = (now: number) => { + const t = Math.min(1, (now - start) / PAGE_MS) + el.scrollLeft = from + (to - from) * (1 - Math.pow(1 - t, 3)) + if (t < 1) { + scrollFrame = requestAnimationFrame(step) + } else { + scrollFrame = undefined + scrollTarget = undefined + } + } + scrollFrame = requestAnimationFrame(step) + } + + // A resize changes what fits, and so does a change of cards or rows, which can leave the + // scroller's own box the same size. + function watchOverflow(node: HTMLElement) { + void cellCount + void rows + measure() + const observer = new ResizeObserver(measure) + observer.observe(node) + return () => observer.disconnect() + } +</script> + +<svelte:window bind:innerWidth /> + +{#snippet card(item: Entry, favorite: boolean)} + <div + class="group flex items-center gap-1 rounded-md border border-light bg-surface-tertiary hover:bg-surface-hover transition-colors min-w-0" + > + <a + href={getFavoriteHref(item.path, item.kind)} + class="flex items-center gap-2 min-w-0 pl-2.5 py-2" + title={item.title === item.path ? item.path : `${item.title}\n${item.path}`} + > + <span class="shrink-0"><RowIcon kind={item.kind} size={14} /></span> + <span class="text-2xs font-normal text-primary truncate">{item.title}</span> + </a> + <!-- The star sits after the title, as on the tree's rows: a set one stays, an unset one + shows on hover or focus. --> + <Star + kind={item.starKind} + path={item.path} + workspaceId={workspace} + summary={item.title} + size={13} + class="inline-flex shrink-0 p-px text-yellow-500 opacity-0 data-[starred]:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100" + /> + <!-- A button can't sit inside the link, so the rest of the card is a second, untabbable + link to the same page. --> + <a + href={getFavoriteHref(item.path, item.kind)} + class="flex-1 self-stretch" + tabindex="-1" + aria-hidden="true" + ></a> + {#if !favorite && item.at} + <span + class="shrink-0 text-2xs text-secondary" + title={recentTooltip(item.at, item.via)} + onmouseenter={() => (now = Date.now())} + role="note" + > + <TimeAgo date={new Date(item.at).toISOString()} compact noSeconds /> + </span> + {/if} + <div class="shrink-0 pr-1 text-secondary"> + <DropdownV2 items={() => menuItems(item, favorite)} size="xs" fixedHeight={false} /> + </div> + </div> +{/snippet} + +{#snippet arrow(direction: 1 | -1)} + <!-- In the page's side padding, beside the cards rather than over them, so the cards keep + the items card's width. A touch screen swipes instead. --> + <div + class="absolute inset-y-0 hidden sm:block [@media(hover:none)]:hidden {direction === -1 + ? 'right-full mr-1' + : 'left-full ml-1'}" + > + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + wrapperClasses="h-full" + btnClasses="!h-full !w-6 !px-0" + startIcon={{ icon: direction === -1 ? ChevronLeft : ChevronRight }} + title={direction === -1 ? 'Scroll left' : 'Scroll right'} + aria-label={direction === -1 ? 'Scroll left' : 'Scroll right'} + onClick={() => page(direction)} + /> + </div> +{/snippet} + +<!-- Held back until the favorites are in: the recent cards are ready first, and the favorites + landing in front of them would push every card over. --> +{#if favoriteManager.loadedFor === workspace && (entries.length > 0 || emptiedBySettings) && !hidden} + <!-- 30px under the cards: the gap from the composer down to this section's heading text. --> + <section class="flex flex-col gap-2 px-4 sm:px-0 pb-[30px]"> + <div class="flex items-center gap-1 -my-1"> + <HomeSectionLabel> + {#if favoriteCount > 0} + Favorites <HomeSectionCount count={favoriteCount} /> + {/if} + {#if favoriteCount > 0 && recentCount > 0} + <span class="text-hint">·</span> + {/if} + {#if recentCount > 0} + Recent <HomeSectionCount count={recentCount} /> + {/if} + </HomeSectionLabel> + <div class="text-secondary"> + <DropdownV2 items={sectionMenu} size="xs" fixedHeight={false} /> + </div> + </div> + {#if entries.length === 0} + <p class="text-2xs text-hint"> + {homeQuickAccessSettings.showFavorites + ? 'No favorites yet. Star a script, flow or app to keep it here.' + : 'Nothing opened lately in this browser.'} + </p> + {/if} + <div class="relative"> + <!-- The scrollbar is hidden, so a trackpad, shift-wheel or a swipe scrolls it and the + arrows stand in for the bar. The 1px padding, taken back by the margin, keeps the + cards' borders off the clip edge: a third of the width is rarely a whole pixel, and + the edge then cuts the outer border. --> + <div + bind:this={scroller} + {@attach watchOverflow} + onscroll={measure} + class="grid gap-2 overflow-x-auto no-scrollbar px-px -mx-px auto-cols-[85%] sm:auto-cols-[calc((100%_-_0.5rem)/2)] lg:auto-cols-[calc((100%_-_1rem)/3)]" + style:grid-template-rows="repeat({rows}, auto)" + > + {#each entries as { item, favorite }, i (item.kind + '/' + item.path)} + {@const at = cellPosition(i)} + <div class="min-w-0" style:grid-row={at.row} style:grid-column={at.column}> + {@render card(item, favorite)} + </div> + {/each} + {#if recentMore > 0} + {@const next = Math.min(recentMore, RECENT_COUNT)} + {@const at = cellPosition(entries.length)} + <div class="min-w-0" style:grid-row={at.row} style:grid-column={at.column}> + <Button + variant="subtle" + unifiedSize="sm" + wrapperClasses="h-full min-w-0" + btnClasses="!h-full rounded-md border border-dashed border-border-light !text-2xs text-secondary font-normal" + onClick={() => (recentLimit += RECENT_COUNT)} + > + Load next {next} + {next === 1 ? 'item' : 'items'} + </Button> + </div> + {/if} + </div> + {#if canBack} + {@render arrow(-1)} + {/if} + {#if canForward} + {@render arrow(1)} + {/if} + </div> + </section> + <HomeSectionLabel class="px-4 sm:px-0 pb-1"> + Workspace items + {#if itemCount != undefined} + <HomeSectionCount count={itemCount} /> + {/if} + </HomeSectionLabel> +{/if} diff --git a/frontend/src/lib/components/home/HomeSectionCount.svelte b/frontend/src/lib/components/home/HomeSectionCount.svelte new file mode 100644 index 0000000000..043be77dae --- /dev/null +++ b/frontend/src/lib/components/home/HomeSectionCount.svelte @@ -0,0 +1,5 @@ +<script lang="ts"> + let { count }: { count: number } = $props() +</script> + +<span class="text-hint tabular-nums">({count})</span> diff --git a/frontend/src/lib/components/home/HomeSectionLabel.svelte b/frontend/src/lib/components/home/HomeSectionLabel.svelte new file mode 100644 index 0000000000..54deb6067a --- /dev/null +++ b/frontend/src/lib/components/home/HomeSectionLabel.svelte @@ -0,0 +1,15 @@ +<script lang="ts"> + import type { Snippet } from 'svelte' + + interface Props { + children: Snippet + class?: string + } + + let { children, class: className = '' }: Props = $props() +</script> + +<!-- Names a section of Home without competing with what it labels. --> +<h2 class="flex items-center gap-1 text-xs font-normal text-secondary {className}"> + {@render children()} +</h2> diff --git a/frontend/src/lib/components/home/ItemsList.svelte b/frontend/src/lib/components/home/ItemsList.svelte index 7e71cd5a02..36099ac1b9 100644 --- a/frontend/src/lib/components/home/ItemsList.svelte +++ b/frontend/src/lib/components/home/ItemsList.svelte @@ -2,7 +2,6 @@ import CenteredPage from '$lib/components/CenteredPage.svelte' import { PIPELINE_DRAFT_KIND, pipelineFolderFromBundlePath } from '$lib/pipelinePaths' import { Button, Skeleton } from '$lib/components/common' - import Toggle from '$lib/components/Toggle.svelte' import { AssetService, FolderService, @@ -17,24 +16,26 @@ } from '$lib/gen' import { resource } from 'runed' import { getDraftItems } from '$lib/workspaceDrafts.svelte' - import { disableHubStore, userStore, workspaceStore } from '$lib/stores' + import { disableHubStore, roleCapabilities, userStore, workspaceStore } from '$lib/stores' import { useEditRights } from '$lib/operatorWriteRights' import type uFuzzy from '@leeoniya/ufuzzy' import { - ArrowDownUp, Bot, + ChevronDown, ChevronsDownUp, ChevronsUpDown, Code2, LayoutDashboard, + MoreHorizontal, + Settings, Tag } from 'lucide-svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import CreateActionsMenu from './CreateActionsMenu.svelte' import ContentSearchInner from '$lib/components/ContentSearchInner.svelte' - import type { Item as MenuItem } from '$lib/utils' + import type { IconType, Item as MenuItem } from '$lib/utils' - import { HOME_SEARCH_SHOW_FLOW, HOME_SEARCH_PLACEHOLDER } from '$lib/consts' + import { HOME_COLUMN_WIDTH, HOME_SEARCH_SHOW_FLOW, HOME_SEARCH_PLACEHOLDER } from '$lib/consts' import SearchItems from '../SearchItems.svelte' import FilterSearchbar, { @@ -46,22 +47,27 @@ import HubProjectPickerModal from './HubProjectPickerModal.svelte' import type { HubProjectPick } from '$lib/hubProject' import ListFilters from './ListFilters.svelte' - import ToggleButtonGroup from '../common/toggleButton-v2/ToggleButtonGroup.svelte' - import ToggleButton from '../common/toggleButton-v2/ToggleButton.svelte' - import FlowIcon from './FlowIcon.svelte' + import LabelBadge from '../common/badge/LabelBadge.svelte' + import { clampRows } from './clampRows' + import { setUnruledList } from '../common/table/unruledList' + import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import { getLocalSetting, isOwner, storeLocalSetting } from '$lib/utils' import { sendUserToast } from '$lib/toast' import Drawer from '../common/drawer/Drawer.svelte' import HighlightCode from '../HighlightCode.svelte' import DrawerContent from '../common/drawer/DrawerContent.svelte' - import Item from './Item.svelte' import TreeViewRoot from './TreeViewRoot.svelte' + import FolderEditorDrawer from '../FolderEditorDrawer.svelte' + import { isDemoWorkspaceRestricted } from '$lib/cloud' + import Item from './Item.svelte' + import PipelineRow from '../common/table/PipelineRow.svelte' + import { TreeOpenMemory } from './treeViewState.svelte' import { effectivePath, type ItemType } from './treeViewUtils' import { tick, untrack } from 'svelte' import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte' - import PipelineRow from '../common/table/PipelineRow.svelte' import BulkActionsBar from './BulkActionsBar.svelte' import { HomeSelection, setHomeSelection, toBulkItem } from './homeSelection.svelte' + import HomeQuickAccess from './HomeQuickAccess.svelte' const editRights = useEditRights() @@ -72,6 +78,8 @@ let { subtab = $bindable('script'), showEditButtons = true }: Props = $props() + setUnruledList() + // Which user-folder scoping toggle (if any) this role gets. Declared before the // FilterSearchbar schema and the derived filters that both read it. let filterUserFoldersType: 'only f/*' | 'u/username and f/*' | undefined = $derived( @@ -119,7 +127,7 @@ label: 'Include library scripts', // On by default, so selecting it means "turn it off" — keep the picker. default: true, - hidden: !($userStore && !$userStore.operator) + hidden: !($userStore && $roleCapabilities.code) }, only_user_folders: { type: 'boolean' as const, @@ -165,7 +173,17 @@ } // Single URL-synced source of truth for the searchbar-driven filters. - let filterValues = useUrlSyncedFilterInstance(untrack(() => searchFilterSchema)) + // The library and user-folder choices outlive the URL: a link that sets one still wins, + // but a bare visit restores the last one made in this browser. + const HIDE_LIBRARY_SETTING_NAME = 'homeHideLibrary' + const ONLY_USER_FOLDERS_SETTING_NAME = 'homeOnlyUserFolders' + let filterValues = useUrlSyncedFilterInstance( + untrack(() => searchFilterSchema), + { + include_library: getLocalSetting(HIDE_LIBRARY_SETTING_NAME) == 'true' ? false : undefined, + only_user_folders: getLocalSetting(ONLY_USER_FOLDERS_SETTING_NAME) == 'true' || undefined + } + ) // Derived views the rest of the data layer reads. The merged-endpoint reload effect // depends on these (search, kind, archived, library, user-folder scope), so changing a @@ -177,13 +195,24 @@ let runnableKinds = $derived(itemKind === 'all' ? undefined : itemKind) let archived = $derived(!!filterValues.val.archived) let includeWithoutMain = $derived((filterValues.val.include_library ?? true) as boolean) - let filterUserFolders = $derived(!!filterValues.val.only_user_folders) + // Gated on the role so a choice remembered from an admin session can't hide other users' + // spaces for a role that is never offered the toggle. + let filterUserFolders = $derived(!!filterValues.val.only_user_folders && !!filterUserFoldersType) + $effect(() => { + storeLocalSetting(HIDE_LIBRARY_SETTING_NAME, includeWithoutMain ? undefined : 'true') + }) + $effect(() => { + storeLocalSetting( + ONLY_USER_FOLDERS_SETTING_NAME, + filterValues.val.only_user_folders ? 'true' : undefined + ) + }) // Content search is a distinct mode: its results come from ContentSearchInner // (which carries only path + content), so the row-list filters can't // apply to it. When it's active we restrict the searchbar to just the content filter, // clear any other filters so they don't linger as ignored chips, and hide the row-list - // controls (kind toggle, tree view) that no longer drive anything. + // controls (kind filter, tree view) that no longer drive anything. let contentActive = $derived(!!filterValues.val.content) let searchbarSchema = $derived( contentActive ? { content: searchFilterSchema.content } : searchFilterSchema @@ -216,7 +245,7 @@ starred?: boolean hash?: string // Fetch ordinal: the position this row arrived in from the server (which already - // applied the chosen order + starred-first). Sorting by it reproduces the server's + // applied its order + starred-first). Sorting by it reproduces the server's // global order EXACTLY — no client re-derivation that could disagree on collation // or sub-millisecond ties and make a later page jump above shown rows. ord?: number @@ -320,6 +349,7 @@ let loading = $state(true) + // Rows the flat list shows of the loaded window. let nbDisplayed = $state(15) // Keyset cursor for the next browse page; null once the stream is exhausted. @@ -328,21 +358,6 @@ // Guards against out-of-order responses: only the latest request applies. let loadGen = 0 - // Sort selector value -> merged-endpoint order params. - function sortToParams(o: SortOrder): { orderBy: 'updated' | 'name'; orderDesc: boolean } { - switch (o) { - case 'updated_asc': - return { orderBy: 'updated', orderDesc: false } - case 'name_asc': - return { orderBy: 'name', orderDesc: false } - case 'name_desc': - return { orderBy: 'name', orderDesc: true } - case 'updated_desc': - default: - return { orderBy: 'updated', orderDesc: true } - } - } - function mapRunnable(it: RunnableItem): TableScript | TableFlow | TableApp | TableAgent { const base = { ...it, @@ -363,15 +378,15 @@ } // The merged, server-ordered, keyset-paginated source. `reset` reloads from - // the first page (order/filter change or workspace switch); otherwise it + // the first page (filter change or workspace switch); otherwise it // appends the next page. Every kind arrives interleaved and are split into // the existing per-kind arrays so the downstream pipeline is unchanged. async function loadRunnables(reset: boolean): Promise<void> { const ws = $workspaceStore if (!ws || !$userStore) return - // Only the very first load shows the skeleton; reorder/filter reloads keep - // the toolbar and current items visible (they're replaced on arrival) so the - // sort control itself doesn't flicker out when you use it. + // Only the very first load shows the skeleton; filter reloads keep the toolbar + // and current items visible (they're replaced on arrival) so the filter control + // itself doesn't flicker out when you use it. // An append (load-more) needs a live cursor. If there isn't one — the stream // is exhausted, or a reset just cleared it and its page-1 response hasn't // landed — bail so a load-more can't append a fresh page-1 onto the old @@ -381,13 +396,12 @@ if (reset) { serverCursor = undefined hasMoreServer = false - // Note: this resets only the global/flat stream. The lazy tree's own store + // Note: this resets only the global stream. The lazy tree's own store // (treeOwnerItems/ownerLoad/openOwners) is managed separately — a mode change - // clears it (see the treeKey effect), while an in-place sort/filter change + // clears it (see the treeKey effect), while an in-place filter change // replaces each open owner's rows atomically as they re-load (see - // loadOwnerItems), so expanded folders don't blank out mid-reorder. + // loadOwnerItems), so expanded folders don't blank out mid-reload. } - const { orderBy, orderDesc } = sortToParams(sortOrder) const gen = ++loadGen // Snapshot the cursor now: a later request must not consume a cursor minted // by an order/filter that has since changed. @@ -396,8 +410,7 @@ try { res = await ScriptService.listRunnables({ workspace: ws, - orderBy, - orderDesc, + ...sortToParams(sortOrder), showArchived: archived ? true : undefined, includeWithoutMain: includeWithoutMain ? true : undefined, kinds: runnableKinds, @@ -480,7 +493,7 @@ } if (have.has(itemKey(it))) continue // Appended after the browse window; a higher ord keeps them after it (search - // itself ranks by relevance, so this ordinal only matters if sort resumes). + // itself ranks by relevance, so this ordinal only matters once it is cleared). const mapped = { ...mapRunnable(it), ord: fetchOrd++ } if (it.type === 'script') s.push(mapped as TableScript) else if (it.type === 'flow') f.push(mapped as TableFlow) @@ -504,9 +517,9 @@ // // Rows for every prefix live in ONE store (`treeOwnerItems`), never in the global // browse arrays: those advance by a single `serverCursor`, so out-of-window rows there - // would make the flat stream non-contiguous and duplicate once pagination reached them. + // would make the global stream non-contiguous and duplicate once pagination reached them. // - // `treeGen` ties every request to the active scope (order/archived/library/kind/ + // `treeGen` ties every request to the active scope (archived/library/kind/ // workspace); a reset bumps it so an in-flight response from a stale scope is dropped. type OwnerLoadState = { cursor?: string @@ -515,7 +528,7 @@ loaded: boolean gen: number } - // Rows per request when loading a prefix in the tree. Larger than the flat list's + // Rows per request when loading a prefix in the tree. Larger than the global stream's // page because a tree row is a single line and a folder is opened to see what it // holds — most folders come in whole on the first click. const OWNER_PAGE_SIZE = 300 @@ -546,7 +559,7 @@ // `owner` is the full prefix a node covers: `f/<folder>`, `u/<username>`, or any // folder under one. `force` re-fetches its first page even if already loaded (a - // re-sort / re-filter reload uses it to refresh the loaded rows in place); `all` + // re-filter reload uses it to refresh the loaded rows in place); `all` // keeps paging until the prefix's stream is exhausted instead of stopping at a page. async function loadOwnerItems( owner: string, @@ -562,7 +575,7 @@ openOwners.add(owner) const st = ownerLoad[owner] // Only a load for the CURRENT generation blocks a new one. A load left in flight - // by a superseded generation (treeGen bumped on a sort/filter reload) has already + // by a superseded generation (treeGen bumped on a filter reload) has already // been invalidated, so it must not wedge the owner as permanently loading. if (st?.loading && st.gen === treeGen) return if (!force && (more ? !st?.hasMore : st?.loaded)) return @@ -574,9 +587,8 @@ loaded: st?.loaded ?? false, gen } - const { orderBy, orderDesc } = sortToParams(sortOrder) const prefix = `${owner}/` - // Only a forced refresh replaces this prefix's rows, so a re-sort swaps them without + // Only a forced refresh replaces this prefix's rows, so a reload swaps them without // blanking the tree. Everything else merges: a nested prefix inherits rows from an // ancestor's pages, and one page of its own can cover fewer of them than are shown — // replacing would delete rows on the click meant to add them. @@ -618,8 +630,7 @@ try { res = await ScriptService.listRunnables({ workspace: ws, - orderBy, - orderDesc, + ...sortToParams(sortOrder), showArchived: archived ? true : undefined, includeWithoutMain: includeWithoutMain ? true : undefined, kinds: runnableKinds, @@ -646,7 +657,7 @@ sendUserToast(`Failed to load ${owner}: ${e?.body ?? e?.message ?? e}`, true) return } - // The scope moved on while this was in flight (order/archive/library/kind/ + // The scope moved on while this was in flight (archive/library/kind/ // workspace changed and reset the tree); drop the response so stale rows from // another scope can't appear under the current one. if (gen !== treeGen) return @@ -678,13 +689,13 @@ } // Reload the merged list once and re-fetch the owners that are currently expanded so // they don't go blank. Used both for row mutations (create/edit/archive/move/share) - // and for in-place scope changes (sort/archive/library/kind): those keep the tree in + // and for in-place scope changes (archive/library/kind): those keep the tree in // lazy mode (treeKey unchanged, so folders stay open like a file explorer), and the - // re-fetch reloads each open owner's items in the new order/filter. When a mode + // re-fetch reloads each open owner's items under the new filter. When a mode // change (owner/search) has switched the tree out of lazy mode, there's nothing to // re-fetch — the tree remounts and groups the global stream instead. async function reloadItems(): Promise<void> { - // Invalidate any in-flight owner loads from the previous sort/filter so their + // Invalidate any in-flight owner loads from the previous filter so their // late responses can't overwrite the fresh ones. treeGen++ const toReload = treeLazyMode ? [...openOwners] : [] @@ -720,7 +731,7 @@ } // For row mutations (create/delete/move/archive), which also change how many - // runnables an owner holds. A scope change (sort/archive/kind/…) doesn't go + // runnables an owner holds. A scope change (archive/kind/…) doesn't go // through here: the counts resource keys on those itself. async function reloadItemsAndCounts(): Promise<void> { // The answer can change with the rows: archiving the last item leaves the listing empty @@ -769,45 +780,131 @@ const cmp = new Intl.Collator('en').compare - // The selected order maps to the endpoint's order_by/order_desc (see - // sortToParams) so it is applied server-side and stays correct across the - // whole workspace, not just loaded pages. Starred items are pinned on top of - // the first page. + // The order is applied server-side so it holds across the whole workspace, not just the + // loaded pages. Starred items are pinned on top of the first page. type SortOrder = 'updated_desc' | 'updated_asc' | 'name_asc' | 'name_desc' const SORT_SETTING_NAME = 'homeSort' - // `short` labels the trigger button next to the sort icon (the button is icon-only - // only while searching, when sorting is disabled — see below). - const sortOptions: { value: SortOrder; label: string; short: string }[] = [ - { value: 'updated_desc', label: 'Recently updated', short: 'Recent' }, - { value: 'updated_asc', label: 'Oldest updated', short: 'Oldest' }, - { value: 'name_asc', label: 'Name (A-Z)', short: 'A-Z' }, - { value: 'name_desc', label: 'Name (Z-A)', short: 'Z-A' } + const sortOptions: { value: SortOrder; label: string }[] = [ + { value: 'updated_desc', label: 'Recently updated' }, + { value: 'updated_asc', label: 'Oldest updated' }, + { value: 'name_asc', label: 'Name (A-Z)' }, + { value: 'name_desc', label: 'Name (Z-A)' } ] let sortOrder = $state<SortOrder>( sortOptions.find((o) => o.value === getLocalSetting(SORT_SETTING_NAME))?.value ?? 'updated_desc' ) - $effect(() => { - storeLocalSetting(SORT_SETTING_NAME, sortOrder === 'updated_desc' ? undefined : sortOrder) - }) - let sortItems: MenuItem[] = $derived( - sortOptions.map((o) => ({ + function setSortOrder(o: SortOrder) { + sortOrder = o + storeLocalSetting(SORT_SETTING_NAME, o === 'updated_desc' ? undefined : o) + } + function sortToParams(o: SortOrder): { orderBy: 'updated' | 'name'; orderDesc: boolean } { + return { + orderBy: o.startsWith('name') ? 'name' : 'updated', + orderDesc: o.endsWith('desc') + } + } + + // Preserve the endpoint's exact order rather than re-deriving it on the client: each row + // carries its server fetch ordinal (`ord`), which already reflects the chosen order, the + // (path, kind) tiebreaks, full-precision timestamps and the database collation. Sorting by + // it can never disagree with the server, so a later page never jumps above shown rows on + // "load more". + function compareItems(a: { ord?: number }, b: { ord?: number }): number { + return (a.ord ?? 0) - (b.ord ?? 0) + } + + const FLAT_LIST_SETTING_NAME = 'homeFlatList' + let flatList = $state(getLocalSetting(FLAT_LIST_SETTING_NAME) == 'true') + function setFlatList(v: boolean) { + flatList = v + storeLocalSetting(FLAT_LIST_SETTING_NAME, v ? 'true' : undefined) + } + + // Unfiltered, the tree lists every folder, empty ones too, so a workspace holding only + // folders is not empty: its first folder is created from here and managed from its row. + // A role without the Folders page gets no folder menu, so empty rows would be noise. + let keepEmptyFolders = $derived(itemKind === 'all' && $roleCapabilities.visibility.folders) + // Only drops rows inside the tree. Whether the tree shows at all, rather than the "no items" + // or empty-workspace state, must not depend on it: either state can take down the settings + // menu, or replace owners whose items sit past the loaded window. + const HIDE_EMPTY_FOLDERS_SETTING_NAME = 'homeHideEmptyFolders' + let hideEmptyFolders = $state(getLocalSetting(HIDE_EMPTY_FOLDERS_SETTING_NAME) == 'true') + function setHideEmptyFolders(v: boolean) { + hideEmptyFolders = v + storeLocalSetting(HIDE_EMPTY_FOLDERS_SETTING_NAME, v ? 'true' : undefined) + } + // A folder created here starts empty; hiding it would read as a failed create. It stays + // listed until the page reloads. + let createdFolders = $state<{ workspace: string; name: string }[]>([]) + let keptFolders = $derived( + createdFolders.filter((f) => f.workspace === $workspaceStore).map((f) => f.name) + ) + + // Reload from the server whenever an input the endpoint resolves changes: order, + // archived/library scope, kind, the selected owner/folder, or entering/leaving + // search (see the reload effect below). Only the label filter and fuzzy ranking + // stay client-side over the loaded pages, so they don't reload here. + let searching = $derived(filter !== '') + // Lazy owner tree is active only in the tree when browsing all (no owner selected, no + // search, no label filter): every folder AND user shows as a top-level node and paginates + // on expand, its items coming from the separate `treeOwnerItems` store. In the flat list, + // or with a selected owner / active search / label filter, the lazy store is unused + // (reloadItems must not touch it), so this is false and the view reads the global loaded + // window instead. + let treeLazyMode = $derived( + !flatList && !searching && ownerFilter == undefined && labelFilter == undefined + ) + + let listSettingsItems: MenuItem[] = $derived([ + { + displayName: 'Flat list', + description: 'List items without grouping them by folder', + toggle: flatList, + action: () => setFlatList(!flatList) + }, + { + displayName: 'Hide empty folders', + description: + 'Folders with no scripts, flows, apps, agents or data pipelines. They may still hold resources, variables or schedules.', + toggle: hideEmptyFolders, + // Only the unfiltered tree lists folders it holds no rows of. + hide: !treeLazyMode || archived || !keepEmptyFolders, + action: () => setHideEmptyFolders(!hideEmptyFolders) + }, + { + displayName: 'Show library scripts', + description: 'Scripts without a main function', + toggle: includeWithoutMain, + hide: !($userStore && $roleCapabilities.code), + action: () => { + // On by default, so showing them again clears the key rather than leaving a chip. + if (includeWithoutMain) filterValues.val.include_library = false + else delete filterValues.val.include_library + } + }, + { + displayName: + filterUserFoldersType === 'only f/*' ? 'Hide user folders' : "Hide other users' folders", + description: + filterUserFoldersType === 'only f/*' + ? 'Only f/*' + : `Only u/${$userStore?.username} and f/*`, + toggle: filterUserFolders, + hide: !filterUserFoldersType, + action: () => { + if (filterUserFolders) delete filterValues.val.only_user_folders + else filterValues.val.only_user_folders = true + } + }, + ...sortOptions.map((o, i) => ({ displayName: o.label, selected: o.value === sortOrder, - action: () => (sortOrder = o.value) + separatorTop: i === 0, + disabled: filter !== '', + tooltip: filter !== '' ? 'Search results are ranked by relevance' : undefined, + action: () => setSortOrder(o.value) })) - ) - // Preserve the endpoint's exact order rather than re-deriving it on the client: - // each row carries its server fetch ordinal (`ord`), which already reflects the - // chosen order, the (path, kind) tiebreaks, full-precision timestamps, the database - // collation, and starred-first pinning. Sorting by it can never disagree with the - // server, so a later page never jumps above shown rows on "load more". Depends on - // `sortOrder` only so its identity changes when the order does (re-grouping the tree, - // whose leaves also sort by ord); the actual reordering comes from the reload that - // restamps ord. - let compareItems = $derived.by(() => { - sortOrder - return (a: { ord?: number }, b: { ord?: number }): number => (a.ord ?? 0) - (b.ord ?? 0) - }) + ]) const opts: uFuzzy.Options = { sort: (info, haystack, needle) => { @@ -860,8 +957,8 @@ } } - const TREE_VIEW_SETTING_NAME = 'treeView' - let treeView = $state(getLocalSetting(TREE_VIEW_SETTING_NAME) == 'true') + let toolbarHeight = $state(0) + let chipsExpanded = $state(false) // Pipeline entries are rendered independently of the item list, so apply the // same gates the items get — otherwise a pipeline would still show under the @@ -882,6 +979,7 @@ ) }) let viewCodeDrawer: Drawer | undefined = $state() + let folderEditorDrawer: FolderEditorDrawer | undefined = $state() let viewCodeTitle: string | undefined = $state() let script: Script | undefined = $state() async function showCode(path: string, summary: string) { @@ -898,6 +996,12 @@ } let collapseAll = $state(true) + let treeOpenMemory = $derived(new TreeOpenMemory(`homeTreeOpen:${$workspaceStore}`)) + function toggleCollapseAll() { + // Collapsing all is also how to forget the folders reopened on every visit. + if (!collapseAll) treeOpenMemory.clear() + collapseAll = !collapseAll + } // Human-readable list of the filters currently narrowing the list. Empty means no // filter is active, so an empty result then means the workspace itself has no items // (NoItemFound shows the welcome message); otherwise the filters are just too narrow @@ -977,19 +1081,8 @@ }) ) }) - // Reload from the server whenever an input the endpoint resolves changes: order, - // archived/library scope, kind, the selected owner/folder, or entering/leaving - // search (see the reload effect below). Only the label filter and fuzzy ranking - // stay client-side over the loaded pages, so they don't reload here. - let searching = $derived(filter !== '') - // Lazy owner tree is active only in the tree view when browsing all (no owner - // selected, no search, no label filter): every folder AND user shows as a top-level - // node and paginates on expand, its items coming from the separate `treeOwnerItems` - // store. In the flat view, or a selected owner / active search / label filter, the - // lazy store is unused (the flat list and reloadItems must not touch it), so this is - // false and those views group the global loaded window instead. - let treeLazyMode = $derived( - treeView && !searching && ownerFilter == undefined && labelFilter == undefined + let treeShowsFolders = $derived( + treeLazyMode && !archived && keepEmptyFolders && (folderNamesRes.current?.length ?? 0) > 0 ) // How many runnables each owner (`f/<folder>` / `u/<user>`) holds for this user, // in one request. It labels every tree node up front — a lazy owner's own count is @@ -1018,6 +1111,53 @@ } ) let ownerCounts = $derived(ownerCountsRes.current) + // Every path sits under a folder or a user, so the owners' counts add up to the workspace. + let workspaceItemCount = $derived( + ownerCounts == undefined ? undefined : Object.values(ownerCounts).reduce((sum, n) => sum + n, 0) + ) + + type KindOption = { + value: 'all' | 'script' | 'flow' | 'app' | 'agent' + label: string + icon?: IconType + /** The kind's colour in the rows (`RowIcon`). */ + iconClass?: string + } + const kindOptions: KindOption[] = [ + { value: 'all', label: 'All kinds' }, + { value: 'script', label: 'Scripts', icon: Code2, iconClass: 'text-blue-500' }, + ...(HOME_SEARCH_SHOW_FLOW + ? [ + { + value: 'flow', + label: 'Flows', + icon: BarsStaggered, + iconClass: 'text-teal-500' + } satisfies KindOption + ] + : []), + { value: 'app', label: 'Apps', icon: LayoutDashboard, iconClass: 'text-orange-500' }, + { value: 'agent', label: 'Agents', icon: Bot, iconClass: 'text-violet-500' } + ] + function setItemKind(v: KindOption['value']) { + // itemKind is derived from the shared filter object (which URL-syncs itself); `all` + // clears the kind filter (delete, not null, so it doesn't linger as a `kind: null` chip). + if (v === 'all') { + delete filterValues.val.kind + } else { + filterValues.val.kind = v + subtab = v + } + } + let kindItems = $derived( + kindOptions.map((o) => ({ + displayName: o.label, + icon: o.icon, + iconProps: o.iconClass ? { class: `shrink-0 ${o.iconClass}` } : undefined, + selected: itemKind === o.value, + action: () => setItemKind(o.value) + })) + ) // The counts decide which owners the tree renders, so drawing it before they land // would show every workspace folder and then prune it away. Hold the skeleton // until the first response instead — it is fetched in parallel with the listing, @@ -1027,16 +1167,8 @@ treeLazyMode && ownerCountsRes.current == undefined && ownerCountsRes.loading ) - // An import just landed, so the rows about to replace the empty state are all new: they - // fade in one after another rather than appearing as a finished list. Cleared on a timer - // because nothing else marks the end — the reload resolves before the rows animate. - let justImported = $state(false) - let justImportedTimer: ReturnType<typeof setTimeout> | undefined function onImported() { reloadItemsAndCounts() - justImported = true - clearTimeout(justImportedTimer) - justImportedTimer = setTimeout(() => (justImported = false), 2500) } // The hub import, owned here rather than by either entry point: the empty state's link and @@ -1103,6 +1235,11 @@ let canCreateHere = $derived( (editRights.roleCanAuthor('flow') || editRights.roleCanAuthor('raw_app')) && showEditButtons ) + // The Folders page's own rule for its "New folder" button. + let canCreateFolder = $derived( + $roleCapabilities.visibility.folders && + !isDemoWorkspaceRestricted($workspaceStore, $userStore?.is_admin, $userStore?.is_super_admin) + ) // The workspace itself holds nothing — no filter is narrowing the list away. It stays // false until the first load resolves: a skeleton already means "loading", and the @@ -1116,6 +1253,7 @@ filteredItems != undefined && filteredItems.length === 0 && visiblePipelineFolders.size === 0 && + !treeShowsFolders && !hasMoreServer ) /** @@ -1133,6 +1271,8 @@ * tell leaves it live as the fallback. */ let toolbarInert = $derived(placeholderTakesOver && !archivedUnknown) + // Expand/collapse: nothing to group on an empty workspace. + let listControls = $derived(!loading && !workspaceEmpty) // Owners the counts found the user has something in, split by kind. They cover // what the folder/username lists miss: an item shared individually out of a @@ -1152,7 +1292,7 @@ const s = new Set<string>() // Always inject your own personal space (u/<you>): list_usernames can be empty // (you may not be a listed workspace member) yet u/<you> still holds runnables, - // and it must not vanish under a name sort whose first page is all folders. + // and it must not vanish when the first page holds none of its rows. if ($userStore?.username) s.add($userStore.username) // Other users only when no user-folder restriction is active. if (!filterUserFolders) { @@ -1163,18 +1303,17 @@ }) // The bottom "load more" only pages the *global* stream, which in lazy mode holds // folder rows the tree ignores (folders come from the store and are all injected - // already) — so surfacing it there is confusing. Restrict it to scoped mode, where - // it pages within the selected owner. In lazy mode the footer instead reveals more - // root nodes purely client-side (nbDisplayed) when there are more than are shown, - // and each folder paginates within itself; users past the window are reached via - // their owner chip. - let treeGlobalHasMore = $derived(ownerFilter != undefined && !searching ? hasMoreServer : false) + // already) — so surfacing it there is confusing. Offer it wherever the tree groups that + // stream instead: a selected owner pages within it, and a label filter with no owner + // matches against it, so later pages hold matches the first one lacks. In lazy mode each + // folder paginates within itself; users past the window are reached via their owner chip. + let treeGlobalHasMore = $derived(!treeLazyMode && !searching ? hasMoreServer : false) $effect(() => { if ($userStore && $workspaceStore) { ;[archived, includeWithoutMain, sortOrder, searching, ownerFilter, itemKind] // reloadItems (not a bare loadRunnables) so an in-place change — sort, archive, - // library, kind — reloads the global stream AND re-fetches the currently-open - // owners in the new order/filter, keeping folders expanded (file-explorer style) + // library, kind — reloads the global stream AND re-fetches the currently-open owners + // under the new filter, keeping folders expanded (file-explorer style) // rather than collapsing them. Mode changes (owner/search) flip treeLazyMode, so // reloadItems skips the re-fetch and the {#key} remount handles the reset. untrack(() => { @@ -1281,7 +1420,7 @@ return mergeRunnables(res.items ?? []) searchCursor = res.next_cursor - // Reveal the freshly fetched matches instead of leaving them behind the display cap. + // Reveal the freshly fetched matches instead of leaving them behind the flat list's cap. nbDisplayed += 30 } @@ -1382,16 +1521,20 @@ ) // Remount identity: only a *mode* change (workspace, selected owner, entering/leaving // search, label filter) restructures the tree, so only those key the {#key} remount. - // A sort/archive/library/kind change keeps the same lazy tree and is applied in place + // An archive/library/kind change keeps the same lazy tree and is applied in place // by reloadItems re-fetching the open owners — so expanded folders don't collapse when - // you re-sort (searching is a boolean so per-keystroke query changes don't remount). + // you change it (searching is a boolean so per-keystroke query changes don't remount). let treeKey = $derived( - `${treeView}|${$workspaceStore}|${ownerFilter}|${searching}|${labelFilter}` + `${flatList}|${$workspaceStore}|${ownerFilter}|${searching}|${labelFilter}` ) // A mode change restructures the tree (it remounts on treeKey), so the lazy owner // store is stale — clear it here (the global reset no longer does). An in-place - // sort/filter change leaves treeKey unchanged, so the store survives and its owners + // filter change leaves treeKey unchanged, so the store survives and its owners // are refreshed in place instead of blanking. + // A selected owner or label narrows the tree to what matches, so its folders open on + // the way in and close again on the way out; in between, expand/collapse stays the + // user's. Closed again because "expand all" in the lazy tree loads every owner it opens. + let wasScoped = false $effect(() => { treeKey untrack(() => { @@ -1399,6 +1542,10 @@ ownerLoad = {} treeOwnerItems = [] openOwners = new Set() + nbDisplayed = 15 + const scoped = ownerFilter != undefined || labelFilter != undefined + if (scoped !== wasScoped) collapseAll = !scoped + wasScoped = scoped }) }) let displayedItems = $derived((items ?? []).slice(0, nbDisplayed)) @@ -1407,14 +1554,14 @@ }) let selectedIndex: number = $state(-1) - // More to show: either loaded items not yet sliced in, or the server has further - // browse pages (not while searching — the browse cursor is paused then; further + // More to show in the flat list: either loaded items not yet sliced in, or the server has + // further browse pages (not while searching — the browse cursor is paused then; further // search matches load on demand via searchCursor / "Load more results"). let hasMore = $derived( items != undefined && (items.length > nbDisplayed || (hasMoreServer && !searching)) ) let loadMoreIndex = $derived(displayedItems.length) - let loadMoreEl: HTMLButtonElement | undefined = $state() + let loadMoreEl: HTMLElement | undefined = $state() let pendingAutoSelect = $state(true) let firstWorkspaceRun = true $effect(() => { @@ -1427,7 +1574,7 @@ // On workspace switch, melt-ui restores focus to the workspace-picker trigger // button asynchronously after the menu closes. Without overriding it, pressing // an arrow key would re-open / re-highlight the workspace picker instead of - // moving the items-list selection. Run several times to win the focus race. + // moving the flat list's selection. Run several times to win the focus race. const focusSearch = () => { const el = document.getElementById('home-search-input') as HTMLInputElement | null el?.focus() @@ -1486,9 +1633,9 @@ nbDisplayed += 30 } - // Fetch the next server page directly (tree view and the empty-state control - // use this — their "all shown" threshold is on a different scale than the flat - // list's, so they must not route through loadMore's item-count check). + // Fetch the next server page directly (the tree's scoped footer and the empty-state + // control): their "all shown" threshold is on a different scale than the flat list's, + // so they must not route through loadMore's item-count check. async function fetchMoreServer() { if (hasMoreServer && !searching) { await loadRunnables(false) @@ -1507,8 +1654,7 @@ // open (free-text mode passes them through to the list); track that so nav stands down then. let searchbarDropdownOpen = $state(false) - // Caret position inside the searchbar's contenteditable, via the Selection API — the equivalent - // of an <input>'s selectionStart/End the list navigation used before the searchbar swap. + // Caret position inside the searchbar's contenteditable, via the Selection API. function searchCaret(el: HTMLElement): { atStart: boolean; atEnd: boolean; empty: boolean } { const text = el.textContent ?? '' const sel = window.getSelection() @@ -1523,7 +1669,7 @@ } // Elements that own the keyboard themselves (menus, dialogs, comboboxes): the - // list's own shortcuts stand down while one of them has focus. + // flat list's own shortcuts stand down while one of them has focus. const SKIP_SELECTOR = '[role="menu"], [role="menuitem"], [role="dialog"], [role="listbox"], [role="combobox"], [aria-expanded="true"], [data-menu], [data-chat-keyboard-scope]' @@ -1555,7 +1701,7 @@ return } } - if (treeView) return + if (!flatList || contentActive) return // When focus is inside a row's action buttons, handle arrow keys ourselves: // - Left/Right cycle between buttons (Left from the first returns to search). @@ -1635,7 +1781,6 @@ return } - const skipSelector = SKIP_SELECTOR if (target) { const tag = target.tagName const isEditable = @@ -1644,10 +1789,10 @@ if (isEditable && !isOurSearch) return // While the searchbar's suggestion dropdown is open it owns the arrows/Enter itself. if (isOurSearch && searchbarDropdownOpen) return - if (target.closest(skipSelector)) return + if (target.closest(SKIP_SELECTOR)) return } const active = document.activeElement as HTMLElement | null - if (active?.closest(skipSelector)) return + if (active?.closest(SKIP_SELECTOR)) return // ArrowRight from search input / body → focus first action button of selected row. // Guard: if cursor is in the middle of typed search text, let the cursor move. @@ -1664,14 +1809,7 @@ } return } - // ArrowLeft from search input with cursor at start: no-op (let default handle). - if (e.key === 'ArrowLeft') { - if (target?.id === 'home-search-input') { - const c = searchCaret(target) - if (!c.empty && !c.atStart) return - } - return - } + if (e.key === 'ArrowLeft') return if (e.key === 'ArrowDown') { if (displayedItems.length === 0) return @@ -1737,15 +1875,12 @@ } } } - $effect(() => { - storeLocalSetting(TREE_VIEW_SETTING_NAME, treeView ? 'true' : undefined) - }) // Multi-selection + bulk actions. Published through context so the tree's // nested levels don't have to carry it; `Item` is the only reader. const homeSelection = new HomeSelection() setHomeSelection(homeSelection) $effect(() => { - homeSelection.available = showEditButtons && !!$userStore && !$userStore.operator + homeSelection.available = showEditButtons && !!$userStore && $roleCapabilities.code }) // A selected path means nothing in another workspace. Narrowing the view // within one (kind, owner, label, search) keeps the selection instead, so @@ -1777,6 +1912,22 @@ {opts} /> +<!-- Permission changes can hide or reveal rows for this user, so a save reloads them. --> +<FolderEditorDrawer + bind:this={folderEditorDrawer} + onSaved={async (name, created) => { + if (created) { + // Folder pickers and the tree's folder menu derive write access from these, which + // the server only resends on the next whoami. The creator is the folder's owner. + $userStore?.folders.push(name) + $userStore?.folders_owners.push(name) + if ($workspaceStore) createdFolders.push({ workspace: $workspaceStore, name }) + await folderNamesRes.refetch() + } + await reloadItemsAndCounts() + }} +/> + <Drawer bind:this={viewCodeDrawer} on:close={() => { @@ -1795,273 +1946,285 @@ </DrawerContent> </Drawer> -<CenteredPage wrapperClasses="w-full" handleOverflow={false}> - <div - class="flex flex-wrap gap-2 items-center justify-between w-full" - use:triggerableByAI={{ - id: 'home-items-list', - description: 'Lists of scripts, flows, and apps' - }} - > - {#if !contentActive} - <!-- Kept mounted, not hidden, so the toolbar doesn't reflow the moment the first item - lands; `inert` takes it out of the tab order and off the pointer meanwhile. A - workspace with nothing but archived items reaches them from its own placeholder, - so these controls are not the way there — but only where that placeholder - renders, which is what `placeholderTakesOver` tracks. --> - <div class="flex justify-start" class:opacity-40={placeholderTakesOver} inert={toolbarInert}> - <ToggleButtonGroup - selected={itemKind} - onSelected={(v) => { - // itemKind is derived from the shared filter object (which URL-syncs itself); - // `all` clears the kind filter (delete, not null, so it doesn't linger as a - // `kind: null` chip). - if (v === 'all') { - delete filterValues.val.kind - } else { - filterValues.val.kind = v - subtab = v - } - }} +<CenteredPage + wrapperClasses="w-full pb-6" + class="{HOME_COLUMN_WIDTH} sm:px-8" + handleOverflow={false} +> + <!-- The shortcuts are the user's own, not a view of the list, so the list's filters leave + them be. A search is a question about the whole workspace: they step aside for its + answer rather than sit above its results (or above its empty state). --> + {#if !searching && !contentActive && !workspaceEmpty && $workspaceStore} + <HomeQuickAccess workspace={$workspaceStore} {showEditButtons} itemCount={workspaceItemCount} /> + {/if} + <!-- The items section, one card: its controls, its filters and its rows. No `overflow-hidden` + on it: the page scrolls, and that would stop the controls sticking. --> + <div class="flex flex-col bg-surface-tertiary border border-border-light rounded-lg"> + <div + bind:clientHeight={toolbarHeight} + class="sticky top-0 z-10 bg-surface-tertiary rounded-t-lg flex flex-wrap gap-2 items-center justify-between px-5 py-3 shrink-0" + use:triggerableByAI={{ + id: 'home-items-list', + description: 'Lists of scripts, flows, and apps' + }} + > + <!-- The search takes the row; on a phone it takes a row of its own above the kind + filter and New. --> + <div class="flex flex-wrap grow items-center gap-2 min-w-0"> + <div + class="relative text-primary w-full basis-full sm:basis-0 sm:grow sm:min-w-[200px]" + class:opacity-40={placeholderTakesOver} + inert={toolbarInert} > - {#snippet children({ item })} - <ToggleButton value="all" label="All" size="md" {item} /> - <ToggleButton value="script" icon={Code2} label="Scripts" size="md" {item} /> - {#if HOME_SEARCH_SHOW_FLOW} - <ToggleButton - value="flow" - label="Flows" - icon={FlowIcon} - selectedColor="#14b8a6" - size="md" - {item} - /> - {/if} - <ToggleButton - value="app" - label="Apps" - icon={LayoutDashboard} - selectedColor="#fb923c" - size="md" - {item} - /> - <ToggleButton - value="agent" - label="Agents" - icon={Bot} - selectedColor="#8b5cf6" - size="md" - {item} - /> - {/snippet} - </ToggleButtonGroup> - </div> - {/if} - - {#if !loading && !contentActive && !workspaceEmpty} - <!-- List controls, between the kind toggle and the searchbar: tree view, - expand/collapse (tree only), sort. Nothing to group or order on an empty - workspace, so the whole row goes. --> - <div class="flex items-center gap-2"> - <Toggle size="xs" bind:checked={treeView} options={{ right: 'Tree view' }} /> - {#if treeView} - <Button - unifiedSize="sm" - variant="subtle" - on:click={() => (collapseAll = !collapseAll)} - startIcon={{ icon: collapseAll ? ChevronsUpDown : ChevronsDownUp }} - > - {#if collapseAll} - Expand all - {:else} - Collapse all - {/if} - </Button> + <FilterSearchbar + schema={searchbarSchema} + bind:value={filterValues.val} + placeholder={HOME_SEARCH_PLACEHOLDER} + presets={contentActive ? [] : searchPresets} + autofocus + hideDropdownOnFreeText + inputId="home-search-input" + onDropdownVisibleChange={(v) => (searchbarDropdownOpen = v)} + /> + </div> + {#if !contentActive} + <!-- Kept mounted, not hidden, so the toolbar doesn't reflow the moment the first + item lands; `inert` takes it out of the tab order and off the pointer meanwhile. + A workspace with nothing but archived items reaches them from its own + placeholder, so this is not the way there — but only where that placeholder + renders, which is what `placeholderTakesOver` tracks. --> + <div class="shrink-0" class:opacity-40={placeholderTakesOver} inert={toolbarInert}> + <DropdownV2 items={kindItems} placement="bottom-end" fixedHeight={false}> + {#snippet buttonReplacement()} + {@const active = kindOptions.find((o) => o.value === itemKind)} + <Button + nonCaptureEvent + unifiedSize="md" + variant="default" + title="Filter by kind" + startIcon={active?.icon + ? { icon: active.icon, classes: active.iconClass } + : undefined} + endIcon={{ icon: ChevronDown }} + > + {active?.label ?? 'All kinds'} + </Button> + {/snippet} + </DropdownV2> + </div> {/if} - <DropdownV2 - items={sortItems} - disabled={filter !== ''} - placement="bottom-end" - fixedHeight={false} - > - {#snippet buttonReplacement()} - {@const active = sortOptions.find((o) => o.value === sortOrder)} - {@const short = filter !== '' ? '' : (active?.short ?? '')} + {#if !contentActive && listControls} + {#if !flatList} <Button - nonCaptureEvent - disabled={filter !== ''} - iconOnly={short === ''} - unifiedSize="xs" + unifiedSize="md" variant="default" - startIcon={{ icon: ArrowDownUp }} - title={filter !== '' - ? 'Sorting is disabled while searching (results are ranked by relevance)' - : `Sort: ${active?.label ?? ''}`} - > - {#if short !== ''}{short}{/if} - </Button> - {/snippet} - </DropdownV2> - </div> - {/if} - - <div class="flex grow items-center justify-end gap-2 min-w-0"> - <div - class="relative text-primary w-full min-w-[200px] max-w-[26rem]" - class:opacity-40={placeholderTakesOver} - inert={toolbarInert} - > - <FilterSearchbar - schema={searchbarSchema} - bind:value={filterValues.val} - placeholder={HOME_SEARCH_PLACEHOLDER} - presets={contentActive ? [] : searchPresets} - autofocus - hideDropdownOnFreeText - inputId="home-search-input" - onDropdownVisibleChange={(v) => (searchbarDropdownOpen = v)} - /> - </div> - <!-- Same gate the old create actions used: hidden from operators and in workspaces + iconOnly + title={collapseAll ? 'Expand all' : 'Collapse all'} + on:click={toggleCollapseAll} + startIcon={{ icon: collapseAll ? ChevronsUpDown : ChevronsDownUp }} + /> + {/if} + <DropdownV2 items={listSettingsItems} placement="bottom-end" fixedHeight={false}> + {#snippet buttonReplacement()} + <Button + nonCaptureEvent + unifiedSize="md" + variant="default" + iconOnly + title="List settings" + startIcon={{ icon: Settings }} + /> + {/snippet} + </DropdownV2> + {/if} + <!-- Same gate the old create actions used: hidden from operators and in workspaces whose direct-deploy protection cleared showEditButtons (NoDirectDeployAlert), since the menu itself does no permission check. --> - {#if canCreateHere} - <!-- No hub entry where the instance has the hub turned off: the same setting the + {#if canCreateHere} + <!-- No hub entry where the instance has the hub turned off: the same setting the script and flow hub pickers observe. Nor for a builder: a hub project brings scripts and apps along. --> - <CreateActionsMenu - onImportHubProject={$disableHubStore || !editRights.roleCanAuthor('script') - ? undefined - : () => (hubPickerOpen = true)} - /> - {/if} + <CreateActionsMenu + onImportHubProject={$disableHubStore || !editRights.roleCanAuthor('script') + ? undefined + : () => (hubPickerOpen = true)} + onCreateFolder={canCreateFolder ? () => folderEditorDrawer?.initNew() : undefined} + /> + {/if} + </div> </div> - </div> - {#if !contentActive && hasChips} - <!-- Owner and label chips on one line. Each function binding routes the chip's + <!-- The chips scroll away with the rows; only the controls above stay. --> + {#if !contentActive && hasChips} + <!-- Owner and label chips on one line. Each function binding routes the chip's selection into the searchbar key of the same name, and `queryName` points ListFilters' own mount-time URL read at the param the filter instance syncs, so the two writers agree. No `syncQuery`: the filter instance owns the URL. --> - <div class="gap-2 w-full flex flex-wrap mt-3"> - <ListFilters - inline - bind:selectedFilter={() => ownerFilter, setOwnerFilter} - filters={owners} - queryName="owner" - maxDisplayed={10} - /> - <ListFilters - inline - bind:selectedFilter={() => labelFilter, setLabelFilter} - filters={allLabels} - queryName="label" - maxDisplayed={10} - color="blue" - icon={Tag} - /> - </div> - {/if} - {#if filteredItems?.length == 0 && !workspaceEmpty} - <div class="mt-10"></div> - {/if} - <div class="mt-3"> - {#if filterValues.val.content} - <!-- Content filter: swap the normal list/tree for the content-match view (the same one + <div + class="gap-x-2 gap-y-0.5 w-full flex flex-wrap px-5 pb-3" + use:clampRows={{ rows: 2, expanded: chipsExpanded }} + > + <ListFilters + inline + bind:selectedFilter={() => ownerFilter, setOwnerFilter} + filters={owners} + color="subtle" + queryName="owner" + /> + <ListFilters + inline + bind:selectedFilter={() => labelFilter, setLabelFilter} + filters={allLabels} + queryName="label" + color="subtle" + icon={Tag} + /> + <div data-clamp-toggle hidden> + <LabelBadge + icon={chipsExpanded ? undefined : MoreHorizontal} + title={chipsExpanded ? 'Show fewer filters' : 'Show all filters'} + onclick={() => (chipsExpanded = !chipsExpanded)} + > + {#if chipsExpanded}Show less{/if} + </LabelBadge> + </div> + </div> + <!-- Its own element, not the chips' border: it stays under the controls once the chips + have scrolled away. --> + <div class="sticky z-10 border-b mx-5" style:top="{toolbarHeight}px"></div> + {/if} + {#if filteredItems?.length == 0 && !workspaceEmpty && !treeShowsFolders} + <div class="mt-10"></div> + {/if} + <!-- Inset so a row's hover fill clears the card's border; the controls above take the same + extra 4px, so they line up with the rows' content. --> + <div class="px-1"> + {#if filterValues.val.content} + <!-- Content filter: swap the normal list/tree for the content-match view (the same one used by the Ctrl-K "Content" modal). It loads the workspace's scripts/flows/apps/ resources and matches their contents client-side — usable on any instance. Keyed by workspace so a switch remounts a fresh instance and late in-flight responses from the previous workspace can't land in it. --> - <!-- -mx-2 cancels ContentSearchInner's own px-2 so its rows line up flush with the - runnable list instead of sitting slightly inset. --> - <div class="-mx-2"> - {#key $workspaceStore} - <ContentSearchInner bind:this={contentSearchEl} search={filterValues.val.content} /> - {/key} - </div> - {:else if filteredItems == undefined || treeCountsPending} - <div class="mt-4"></div> - <Skeleton layout={[[2], 1]} /> - {#each new Array(6) as _} - <Skeleton layout={[[4], 0.5]} /> - {/each} - {:else if filteredItems.length === 0 && (filter !== '' || visiblePipelineFolders.size === 0)} - <!-- Pipelines aren't part of the text filter, so only fall through to show + <!-- px-1 plus ContentSearchInner's own px-2 lines its rows up with the controls + above. --> + <div class="px-1 pb-2"> + {#key $workspaceStore} + <ContentSearchInner bind:this={contentSearchEl} search={filterValues.val.content} /> + {/key} + </div> + {:else if filteredItems == undefined || treeCountsPending} + <div class="px-4 pb-3"> + <div class="mt-4"></div> + <Skeleton layout={[[2], 1]} /> + {#each new Array(6) as _} + <Skeleton layout={[[4], 0.5]} /> + {/each} + </div> + {:else if filteredItems.length === 0 && (filter !== '' || visiblePipelineFolders.size === 0) && !treeShowsFolders} + <div class="px-4 pb-3"> + <!-- Pipelines aren't part of the text filter, so only fall through to show them (list rows / injected tree folders) when not actively searching; a no-match search still reads as empty. --> - {#if workspaceEmpty} - <!-- Held until the archived probe answers rather than drawn and swapped: the two + {#if workspaceEmpty} + <!-- Held until the archived probe answers rather than drawn and swapped: the two placeholders say different things, and showing the wrong one first says the workspace is empty when it is not. --> - {#if emptyStateAnswered} - {#if archivedProbe?.hasArchived || canCreateHere} - <!-- Shown to whoever has something to do here: the archived notice to + {#if emptyStateAnswered} + {#if archivedProbe?.hasArchived || canCreateHere} + <!-- Shown to whoever has something to do here: the archived notice to everyone, since reading archived items is not a write, and the create actions only to a user who may take them. --> - <WorkspaceEmptyState - archivedOnly={archivedProbe?.hasArchived === true} - canCreate={canCreateHere} - onPick={(project) => (hubPick = project)} - onShowArchived={() => (filterValues.val = { ...filterValues.val, archived: true })} - /> + <WorkspaceEmptyState + archivedOnly={archivedProbe?.hasArchived === true} + canCreate={canCreateHere} + onCreateFolder={canCreateFolder ? () => folderEditorDrawer?.initNew() : undefined} + onPick={(project) => (hubPick = project)} + onShowArchived={() => + (filterValues.val = { ...filterValues.val, archived: true })} + /> + {:else} + <NoItemFound {activeFilters} /> + {/if} + {/if} {:else} <NoItemFound {activeFilters} /> {/if} - {/if} - {:else} - <NoItemFound {activeFilters} /> - {/if} - {#if hasMoreServer && !searching} - <!-- The active filter matched nothing on the loaded pages, but the server + {#if hasMoreServer && !searching} + <!-- The active filter matched nothing on the loaded pages, but the server has more: keep paging reachable so matches on later pages aren't lost. --> - <div class="text-center text-xs text-secondary mt-2"> - <button class="text-primary hover:text-emphasis underline" onclick={fetchMoreServer} - >Load more to search further</button - > + <div class="text-center text-xs text-secondary mt-2"> + <button class="text-primary hover:text-emphasis underline" onclick={fetchMoreServer} + >Load more to search further</button + > + </div> + {/if} </div> - {/if} - {:else if treeView} - <!-- Remount the tree on a MODE change only (treeKey = view/owner/search/label): + {:else if flatList} + <!-- Every row draws its own border-b; pulling the content 1px down hides the last + one under the clip, as the tree does. --> + <div class="overflow-hidden"> + <div class="-mb-px"> + {#if filter === ''} + {#each [...visiblePipelineFolders].sort() as folder (folder)} + <PipelineRow {folder} onDeleted={reloadItemsAndCounts} /> + {/each} + {/if} + {#each displayedItems as item, i (item.type + '/' + item.path + (item.hash ? '/' + item.hash : ''))} + <Item + {item} + on:scriptChanged={reloadItemsAndCounts} + on:flowChanged={reloadItemsAndCounts} + on:appChanged={reloadItemsAndCounts} + on:rawAppChanged={reloadItemsAndCounts} + on:reload={reloadItemsAndCounts} + {showCode} + showEditButton={showEditButtons} + keyboardSelected={selectedIndex === i} + /> + {/each} + {#if items && hasMore} + <div + bind:this={loadMoreEl} + class="px-4 py-3 flex flex-row items-center justify-between gap-4 {selectedIndex === + loadMoreIndex + ? 'bg-surface-hover' + : 'bg-surface-secondary'}" + > + <span class="text-xs text-secondary"> + Showing {Math.min(nbDisplayed, items.length)}{(hasMoreServer && !searching) || + (searching && searchCursor) + ? '' + : ` of ${items.length}`} items + </span> + <Button unifiedSize="sm" variant="subtle" on:click={loadMore}>Load more</Button> + </div> + {/if} + </div> + </div> + {:else} + <!-- Remount the tree on a MODE change only (treeKey = view/owner/search/label): expanded folders (their `opened` state is local to each TreeView) collapse - and re-load fresh for the new mode. An in-place order/archive/library/kind + and re-load fresh for the new mode. An in-place archive/library/kind change keeps treeKey stable, so folders stay open and refresh via reloadItems instead (see loadOwnerItems). --> - {#key treeKey} - <TreeViewRoot - items={treeSource} - {collapseAll} - sortCompare={compareItems} - groupDesc={sortOrder === 'name_desc'} - hasMoreServer={treeGlobalHasMore} - onLoadMore={fetchMoreServer} - pipelineFolders={visiblePipelineFolders} - allFolders={treeInjectFolders} - allUsers={treeInjectUsers} - ownerCounts={!searching && labelFilter == undefined ? ownerCounts : undefined} - selfUsername={$userStore?.username} - groupOtherUsers={treeLazyMode} - ownerLoad={treeLazyMode ? ownerLoad : undefined} - onExpandOwner={treeLazyMode ? loadOwnerItems : undefined} - onCollapseOwner={treeLazyMode ? collapseOwner : undefined} - isSearching={filter !== ''} - on:scriptChanged={reloadItemsAndCounts} - on:flowChanged={reloadItemsAndCounts} - on:appChanged={reloadItemsAndCounts} - on:rawAppChanged={reloadItemsAndCounts} - on:reload={reloadItemsAndCounts} - {showCode} - showEditButton={showEditButtons} - /> - {/key} - {:else} - <div class="border rounded-md bg-surface-tertiary" class:wm-imported={justImported}> - {#if filter === ''} - {#each [...visiblePipelineFolders].sort() as folder (folder)} - <PipelineRow {folder} onDeleted={reloadItemsAndCounts} /> - {/each} - {/if} - {#each displayedItems as item, i (item.type + '/' + item.path + (item.hash ? '/' + item.hash : ''))} - <Item - {item} + {#key treeKey} + <TreeViewRoot + items={treeSource} + {collapseAll} + sortCompare={compareItems} + groupDesc={sortOrder === 'name_desc'} + openMemory={treeOpenMemory} + hasMoreServer={treeGlobalHasMore} + onLoadMore={fetchMoreServer} + pipelineFolders={visiblePipelineFolders} + allFolders={treeInjectFolders} + allUsers={treeInjectUsers} + ownerCounts={!searching && labelFilter == undefined ? ownerCounts : undefined} + selfUsername={$userStore?.username} + groupOtherUsers={treeLazyMode} + ownerLoad={treeLazyMode ? ownerLoad : undefined} + onExpandOwner={treeLazyMode ? loadOwnerItems : undefined} + onCollapseOwner={treeLazyMode ? collapseOwner : undefined} + isSearching={filter !== ''} on:scriptChanged={reloadItemsAndCounts} on:flowChanged={reloadItemsAndCounts} on:appChanged={reloadItemsAndCounts} @@ -2069,45 +2232,36 @@ on:reload={reloadItemsAndCounts} {showCode} showEditButton={showEditButtons} - keyboardSelected={selectedIndex === i} + framed={false} + onManageFolder={$roleCapabilities.visibility.folders + ? (name) => folderEditorDrawer?.initEdit(name) + : undefined} + keepEmptyFolders={keepEmptyFolders && !hideEmptyFolders} + {keptFolders} /> - {/each} - </div> - {#if items && hasMore} - <span class="text-xs font-normal text-secondary" - >{Math.min(nbDisplayed, items.length)} items{hasMoreServer && !searching - ? '' - : ` out of ${items.length}`} - <button - bind:this={loadMoreEl} - class="ml-4 text-xs font-normal text-primary hover:text-emphasis rounded px-1 {selectedIndex === - loadMoreIndex - ? 'bg-gray-200 dark:bg-gray-700 underline' - : ''}" - onclick={loadMore}>load 30 more</button - ></span - > + {/key} {/if} - {/if} - {#if searching && searchCursor} - <!-- The server has further search matches beyond the page already merged in; + {#if searching && searchCursor} + <!-- The server has further search matches beyond the page already merged in; fetch them one page at a time on demand rather than auto-downloading a broad query's entire result set. --> - <div class="text-center text-xs text-secondary mt-2"> - {#if searchLoadingMore} - Loading more results… - {:else} - <button class="text-primary hover:text-emphasis underline" onclick={loadMoreSearchResults} - >Load more results</button - > - {/if} - </div> - {/if} - {#if homeSelection.active} - <!-- The bar floats over the page bottom; without this the last rows sit - under it with no way to scroll them clear. --> - <div class="h-20"></div> - {/if} + <div class="text-center text-xs text-secondary py-2 border-t"> + {#if searchLoadingMore} + Loading more results… + {:else} + <button + class="text-primary hover:text-emphasis underline" + onclick={loadMoreSearchResults}>Load more results</button + > + {/if} + </div> + {/if} + {#if homeSelection.active} + <!-- The bar floats over the list's bottom; without this the last rows sit + under it with no way to scroll them clear. --> + <div class="h-20"></div> + {/if} + </div> </div> </CenteredPage> @@ -2136,59 +2290,3 @@ <ImportProjectModal.default pick={hubPick} onClose={() => (hubPick = undefined)} {onImported} /> {/await} {/if} - -<style> - /* Rows arriving after an import, one after another. The animation is declared on the - container's children rather than on each row: a wrapper element around a row would make - every row `first-of-type` and `last-of-type`, which is how Row draws its corners and - separators. The delay steps for the first rows only — past those the stagger is longer - than anyone waits, so they share the last one. */ - @keyframes wm-row-in { - from { - opacity: 0; - transform: translateY(4px); - } - to { - opacity: 1; - transform: none; - } - } - - /* `backwards`, not `both`: the fill hides rows until their staggered start, but a forwards - fill would keep `transform` animated afterwards and confine the row's remove confirmation - (`position: fixed`) to the row. The `to` keyframe equals the row's resting style. */ - .wm-imported > :global(*) { - animation: wm-row-in 260ms ease-out backwards; - animation-delay: 320ms; - } - .wm-imported > :global(*:nth-child(1)) { - animation-delay: 0ms; - } - .wm-imported > :global(*:nth-child(2)) { - animation-delay: 40ms; - } - .wm-imported > :global(*:nth-child(3)) { - animation-delay: 80ms; - } - .wm-imported > :global(*:nth-child(4)) { - animation-delay: 120ms; - } - .wm-imported > :global(*:nth-child(5)) { - animation-delay: 160ms; - } - .wm-imported > :global(*:nth-child(6)) { - animation-delay: 200ms; - } - .wm-imported > :global(*:nth-child(7)) { - animation-delay: 240ms; - } - .wm-imported > :global(*:nth-child(8)) { - animation-delay: 280ms; - } - - @media (prefers-reduced-motion: reduce) { - .wm-imported > :global(*) { - animation: none; - } - } -</style> diff --git a/frontend/src/lib/components/home/ListFilters.svelte b/frontend/src/lib/components/home/ListFilters.svelte index 5482c59c42..9714b18aa4 100644 --- a/frontend/src/lib/components/home/ListFilters.svelte +++ b/frontend/src/lib/components/home/ListFilters.svelte @@ -1,6 +1,6 @@ <script lang="ts"> import { Folder, User } from 'lucide-svelte' - import { Badge } from '../common' + import LabelBadge from '../common/badge/LabelBadge.svelte' import type { BadgeColor, BadgeIconProps } from '../common/badge/model' import { appIconComponent } from '../icons/appIcon.svelte' import { integrationDisplayName } from '../resourceTypeDisplay' @@ -14,9 +14,6 @@ queryName?: string syncQuery?: boolean bottomMargin?: boolean - // Keep only the first N filters visible, the rest behind a "…" toggle. Unset - // shows every one. - maxDisplayed?: number // Chip look. `icon` is drawn before every chip; unset, the icon follows the value // (user/folder prefix, or the app icon under `resourceType`). color?: BadgeColor @@ -34,7 +31,6 @@ queryName = 'filter', syncQuery = false, bottomMargin = true, - maxDisplayed, color = 'transparent', icon, inline = false @@ -76,71 +72,39 @@ : [selectedFilter, ...filters] : filters ) - - let expanded = $state(false) - let truncated = $derived.by(() => { - if (maxDisplayed == undefined || filtersAndSelected.length <= maxDisplayed) - return filtersAndSelected - const shown = filtersAndSelected.slice(0, maxDisplayed) - // Clicking the selected chip is how the filter is cleared, so it is never truncated - // away, however far down the order it sits. - if (selectedFilter && !shown.includes(selectedFilter)) shown.push(selectedFilter) - return shown - }) - // Derived from what is actually withheld, so the selected chip kept above never counts - // as hidden — otherwise the toggle offers to reveal a chip that is already on screen. - let hiddenCount = $derived(filtersAndSelected.length - truncated.length) - let displayedFilters = $derived(expanded ? filtersAndSelected : truncated) </script> {#if Array.isArray(filtersAndSelected) && filtersAndSelected.length > 0} <div class={inline ? 'contents' : `gap-2 w-full flex flex-wrap ${bottomMargin ? 'my-4' : 'mt-4'}`} > - {#each displayedFilters as filter (filter)} - <div> - <Badge - class="inline-flex items-center gap-1 align-middle" + {#each filtersAndSelected as filter (filter)} + <div data-chip data-selected={filter === selectedFilter ? '' : undefined}> + <LabelBadge + {color} + icon={icon ?? + (resourceType + ? undefined + : filter.startsWith('u/') + ? User + : filter.startsWith('f/') + ? Folder + : undefined)} + selected={filter === selectedFilter} onclick={() => { selectedFilter = selectedFilter == filter ? undefined : filter writeQuery(selectedFilter) }} - {color} - clickable - selected={filter === selectedFilter} > - <span style="height: 12px" class="-mt-0.5"> - {#if icon} - {@const Icon = icon} - <Icon class="mr-0.5" size={12} /> - {:else if resourceType} - {@const SvelteComponent = appIconComponent(filter)} - {#if SvelteComponent} - <SvelteComponent height="14px" width="14px" /> - {/if} - {:else if filter.startsWith('u/')} - <User class="mr-0.5" size={14} /> - {:else if filter.startsWith('f/')} - <Folder class="mr-0.5" size={14} /> + {#if !icon && resourceType} + {@const AppIcon = appIconComponent(filter)} + {#if AppIcon} + <AppIcon height="12px" width="12px" /> {/if} - </span> + {/if} {resourceType ? integrationDisplayName(filter) : filter} - {#if filter === selectedFilter}✗{/if} - </Badge> + </LabelBadge> </div> {/each} - {#if hiddenCount > 0} - <div> - <Badge - class="inline-flex items-center gap-1 align-middle" - {color} - clickable - title={expanded ? 'Show fewer' : `Show ${hiddenCount} more`} - onclick={() => (expanded = !expanded)} - > - {expanded ? 'Show less' : '…'} - </Badge> - </div> - {/if} </div> {/if} diff --git a/frontend/src/lib/components/home/TreeOwnerRow.svelte b/frontend/src/lib/components/home/TreeOwnerRow.svelte new file mode 100644 index 0000000000..29a055fa59 --- /dev/null +++ b/frontend/src/lib/components/home/TreeOwnerRow.svelte @@ -0,0 +1,84 @@ +<script lang="ts"> + import { ChevronDown, ChevronUp } from 'lucide-svelte' + import type { Snippet } from 'svelte' + import { inUnruledList, rowRule } from '../common/table/unruledList' + + const unruled = inUnruledList() + + /** A row of the tree that groups others under it (a folder, a user, "Other users"): clicking + * anywhere on it opens or closes what it groups. */ + interface Props { + icon: typeof import('lucide-svelte').Folder + name: string + opened: boolean + onToggle: () => void + /** Extra left padding in px, for a nested folder. */ + indent?: number + /** The toggle's accessible name; the row's name when unset. */ + toggleLabel?: string + /** The line under the name, usually its item count. */ + detail: Snippet + /** Controls rendered next to the name. Clicks on them do not toggle the row. */ + actions?: Snippet + } + + let { + icon: Icon, + name, + opened, + onToggle, + indent = 0, + toggleLabel, + detail, + actions + }: Props = $props() +</script> + +<!-- svelte-ignore a11y_click_events_have_key_events --> +<!-- svelte-ignore a11y_no_static_element_interactions --> +<div + onclick={onToggle} + class="px-4 py-2 {rowRule( + unruled + )} group/row w-full flex flex-row items-center justify-between cursor-pointer hover:bg-surface-hover" +> + <div + class="flex flex-row items-center gap-4" + style={indent > 0 ? `padding-left: ${indent}px;` : ''} + > + <Icon size={16} class="text-secondary shrink-0" /> + <div> + <div class="flex flex-row items-center gap-1"> + <span class="whitespace-nowrap text-xs text-emphasis font-semibold">{name}</span> + {#if actions} + <!-- Shown for the hovered row, a tabbed-into one, or one whose menu is open. + `-my-0.5` keeps the 20px trigger from making this line taller than the + name alone, so rows with and without actions line up. --> + <!-- svelte-ignore a11y_click_events_have_key_events --> + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="-my-0.5 opacity-0 transition-opacity duration-100 group-hover/row:opacity-100 group-has-[:focus-visible]/row:opacity-100 has-[[aria-expanded=true]]:opacity-100" + onclick={(e) => e.stopPropagation()} + > + {@render actions()} + </div> + {/if} + </div> + <div class="text-2xs font-normal text-secondary whitespace-nowrap"> + {@render detail()} + </div> + </div> + </div> + <!-- Keyboard access only: its click bubbles to the row, which does the toggling. --> + <button + class="w-full flex flex-row-reverse" + aria-expanded={opened} + aria-label={toggleLabel ?? name} + > + {#if opened} + <ChevronUp size={16} /> + {:else} + <ChevronDown size={16} /> + {/if} + </button> +</div> diff --git a/frontend/src/lib/components/home/TreeView.svelte b/frontend/src/lib/components/home/TreeView.svelte index 806787cb76..f7b99ae5d7 100644 --- a/frontend/src/lib/components/home/TreeView.svelte +++ b/frontend/src/lib/components/home/TreeView.svelte @@ -3,13 +3,17 @@ import { createEventDispatcher, onDestroy, untrack, type Snippet } from 'svelte' import ResizeTransitionWrapper from '$lib/components/common/ResizeTransitionWrapper.svelte' - import { ChevronDown, ChevronUp, Folder, FolderTree, User } from 'lucide-svelte' + import { Eye, Folder, FolderTree, Pen, User } from 'lucide-svelte' + import { userStore } from '$lib/stores' + import Dropdown from '$lib/components/DropdownV2.svelte' + import TreeOwnerRow from './TreeOwnerRow.svelte' import PipelineRow from '../common/table/PipelineRow.svelte' import Item from './Item.svelte' import { countLeaves, type FolderItem, type ItemType, type UserItem } from './treeViewUtils' - import { twMerge } from 'tailwind-merge' import { pluralize } from '$lib/utils' import { Button } from '$lib/components/common' + import { inUnruledList, rowRule } from '../common/table/unruledList' + import type { TreeOpenMemory } from './treeViewState.svelte' interface Props { item: ItemType | FolderItem | UserItem @@ -51,6 +55,12 @@ // Renders a leaf in place of the home page's `<Item>`, for lists whose rows are not // scripts/flows/apps. Receives the leaf and its visual depth. leaf?: Snippet<[ItemType, number]> + // Remembers which nodes the user opened by hand, so they reopen on the next visit + // while expand/collapse-all is in its collapsed state. + openMemory?: TreeOpenMemory + // Adds a "Manage folder" menu ("View folder" for a non-owner) to top-level folder rows. + // Subfolders are path segments, not folders with permissions of their own, so get none. + onManageFolder?: (folderName: string) => void } let { @@ -69,9 +79,13 @@ parentPrefix, ancestorHasMore = false, indent = 0, - leaf + leaf, + openMemory, + onManageFolder }: Props = $props() + const unruled = inUnruledList() + let visualDepth = $derived(depth + indent) const dispatch = createEventDispatcher<{ reload: void }>() @@ -205,7 +219,8 @@ ownerKey != undefined && ownerLoad != undefined && rootIndex >= EXPAND_ALL_LOAD_LIMIT - const shouldOpen = expandAll && !cappedOwner + const remembered = !expandAll && nodePrefix != undefined && !!openMemory?.isOpen(nodePrefix) + const shouldOpen = (expandAll && !cappedOwner) || remembered opened = shouldOpen if (ownerKey == undefined) return if (shouldOpen) { @@ -241,6 +256,7 @@ if (now - lastToggle < 300) return lastToggle = now opened = !opened + if (nodePrefix != undefined) openMemory?.setOpen(nodePrefix, opened) if (opened) { // A top-level owner loads on expand. A subfolder's rows come from an ancestor's // pages, so opening one must not fire a request per subfolder — its own "Load @@ -260,58 +276,56 @@ } </script> +{#snippet manageFolderMenu()} + {#if isFolder(item)} + {@const folderName = item.folderName} + <!-- The Folders page's write rule. A non-owner's drawer opens read-only. --> + {@const canWrite = + $userStore?.is_admin || + $userStore?.is_super_admin || + $userStore?.folders_owners.includes(folderName)} + <Dropdown + size="xs" + fixedHeight={false} + placement="bottom-start" + items={[ + { + displayName: canWrite ? 'Manage folder' : 'View folder', + icon: canWrite ? Pen : Eye, + action: () => onManageFolder?.(folderName) + } + ]} + /> + {/if} +{/snippet} + {#if isFolder(item) || isUser(item)} <div> - <!-- svelte-ignore a11y_click_events_have_key_events --> - <!-- svelte-ignore a11y_no_static_element_interactions --> - <div - onclick={toggleOwner} - class="px-4 py-2 border-b w-full flex flex-row items-center justify-between cursor-pointer" + <TreeOwnerRow + icon={isUser(item) ? User : depth === 0 ? Folder : FolderTree} + name={isUser(item) ? `u/${item.username}` : `${depth === 0 ? 'f/' : ''}${item.folderName}`} + {opened} + onToggle={toggleOwner} + indent={visualDepth * 16} + actions={onManageFolder && depth === 0 && isFolder(item) ? manageFolderMenu : undefined} > - <div - class={twMerge('flex flex-row items-center gap-4 text-sm font-semibold')} - style={visualDepth > 0 ? `padding-left: ${visualDepth * 16}px;` : ''} - > - <div class="flex justify-center items-center"> - {#if isUser(item)} - <User size={16} class="text-secondary" /> - {:else if depth === 0} - <Folder size={16} class="text-secondary" /> - {:else} - <FolderTree size={16} class="text-secondary" /> - {/if} - </div> - - <div> - <span class="whitespace-nowrap text-xs text-emphasis font-semibold"> - {#if isUser(item)}u/{item.username}{:else}{#if depth === 0}f/{/if}{item.folderName}{/if} - </span> - <div class="text-2xs font-normal text-secondary whitespace-nowrap"> - {#if ownerCount != undefined} - ({pluralize(ownerCount, ' item')}) - {:else if isLazyOwner && !ownerState?.loaded} - <!-- Lazy owner not expanded yet and no count for it: its true item count - is unknown until loaded, so showing "(0 items)" would be misleading. --> -   - {:else if nodeHasMore} - <!-- Partial: this node still has pages to load (its own once it has been - loaded directly, otherwise its ancestor's), so what is grouped under - it is only what has arrived so far. --> - ({loadedHere}+ items) - {:else} - ({pluralize(loadedHere, ' item')}) - {/if} - </div> - </div> - </div> - <button class="w-full flex flex-row-reverse"> - {#if opened} - <ChevronUp size={16} /> + {#snippet detail()} + {#if ownerCount != undefined} + ({pluralize(ownerCount, ' item')}) + {:else if isLazyOwner && !ownerState?.loaded} + <!-- Lazy owner not expanded yet and no count for it: its true item count + is unknown until loaded, so showing "(0 items)" would be misleading. --> +   + {:else if nodeHasMore} + <!-- Partial: this node still has pages to load (its own once it has been + loaded directly, otherwise its ancestor's), so what is grouped under + it is only what has arrived so far. --> + ({loadedHere}+ items) {:else} - <ChevronDown size={16} /> + ({pluralize(loadedHere, ' item')}) {/if} - </button> - </div> + {/snippet} + </TreeOwnerRow> <!-- ResizeObserver, not a slide: a freshly-opened owner fetches its rows, so its height changes twice (open-empty, then rows land) and a slide would only animate the first. --> <ResizeTransitionWrapper vertical innerClass="w-full"> @@ -336,6 +350,7 @@ {onCollapseOwner} parentPrefix={nodePrefix} ancestorHasMore={nodeHasMore} + {openMemory} on:scriptChanged on:flowChanged on:appChanged @@ -346,11 +361,14 @@ depth={depth + 1} {indent} {leaf} + {onManageFolder} /> {/each} {#if effectiveMax < item.items.length} <div - class="px-4 py-2 border-b flex flex-row items-center justify-between gap-4 bg-surface-secondary" + class="px-4 py-2 {rowRule( + unruled + )} flex flex-row items-center justify-between gap-4 bg-surface-secondary" style="padding-left: {(visualDepth + 1) * 16}px;" > <!-- Rows, not items: this slices the node's own entries, where a subfolder @@ -387,7 +405,9 @@ is the point: without them this reads as an optional extra rather than as rows still missing. --> <div - class="px-4 py-2 border-b flex flex-row items-center justify-between gap-4 bg-surface-secondary" + class="px-4 py-2 {rowRule( + unruled + )} flex flex-row items-center justify-between gap-4 bg-surface-secondary" style="padding-left: {(visualDepth + 1) * 16}px;" > <span class="text-xs text-secondary"> diff --git a/frontend/src/lib/components/home/TreeViewRoot.svelte b/frontend/src/lib/components/home/TreeViewRoot.svelte index 753feb6a8b..935157d152 100644 --- a/frontend/src/lib/components/home/TreeViewRoot.svelte +++ b/frontend/src/lib/components/home/TreeViewRoot.svelte @@ -3,8 +3,11 @@ import TreeView from './TreeView.svelte' import { countLeaves, groupItems, type ItemType, type UserItem } from './treeViewUtils' import { Button } from '$lib/components/common' - import { ChevronDown, ChevronUp, Users } from 'lucide-svelte' + import { Users } from 'lucide-svelte' + import TreeOwnerRow from './TreeOwnerRow.svelte' + import { inUnruledList, rowRule } from '../common/table/unruledList' import { getLocalSetting, pluralize, storeLocalSetting } from '$lib/utils' + import type { TreeOpenMemory } from './treeViewState.svelte' interface Props { collapseAll: boolean @@ -40,12 +43,23 @@ onExpandOwner?: (owner: string, more?: boolean, opts?: { all?: boolean }) => void onCollapseOwner?: (owner: string) => void showEditButton?: boolean + /** Off where the tree is part of its host's list rather than a box of its own (Home). */ + framed?: boolean // Tuck every user space but `selfUsername`'s into one collapsible "Other users" row // under it. Only for browsing: a search or filter must not hide its matches behind // a closed row. groupOtherUsers?: boolean // See TreeView's `leaf`. leaf?: Snippet<[ItemType, number]> + // See TreeView's `openMemory`. + openMemory?: TreeOpenMemory + // See TreeView's `onManageFolder`. + onManageFolder?: (folderName: string) => void + // Inject folders `ownerCounts` calls empty, as "0 items". Off under a kind filter, + // where those counts are per kind and every folder lacking that kind would show. + keepEmptyFolders?: boolean + // Folders injected even when empty and `keepEmptyFolders` is off. + keptFolders?: string[] } let { @@ -66,10 +80,17 @@ onExpandOwner, onCollapseOwner, showEditButton = true, + framed = true, groupOtherUsers = false, - leaf + leaf, + openMemory, + onManageFolder, + keepEmptyFolders = false, + keptFolders }: Props = $props() + const unruled = inUnruledList() + // How many root nodes render at once. A root node is a collapsed owner row that // fetches nothing until expanded, so a large slice costs a row each and no request // — and an owner sliced off the end is indistinguishable from one that doesn't @@ -92,6 +113,8 @@ allUsers ownerCounts selfUsername + keepEmptyFolders + keptFolders untrack(() => { // While searching, `items` is already relevance-ranked and the sort // selector is disabled, so keep that order: a no-op leaf comparator @@ -116,15 +139,21 @@ .filter((g) => 'folderName' in g) .map((g) => (g as { folderName: string }).folderName) ) - // Once counts are in, an owner holding nothing the user can see is dropped - // rather than injected — a workspace's folder list is mostly noise in the - // tree otherwise. Pipeline folders are exempt: their entry is the pipeline - // itself, whose member scripts are folded out of the runnable count. + // Once counts are in, a user space holding nothing the user can see is dropped + // rather than injected — the member list is mostly noise in the tree otherwise. + // Empty folders are dropped too unless `keepEmptyFolders` or `keptFolders`. Pipeline folders are + // exempt: their entry is the pipeline, whose scripts the count folds out. const isEmptyOwner = (prefix: string) => ownerCounts != undefined && !ownerCounts[prefix] const missingFolders: { folderName: string; items: [] }[] = [] for (const folderName of [...(pipelineFolders ?? []), ...allFolders]) { if (presentFolders.has(folderName)) continue - if (!pipelineFolders?.has(folderName) && isEmptyOwner(`f/${folderName}`)) continue + if ( + !keepEmptyFolders && + !pipelineFolders?.has(folderName) && + !keptFolders?.includes(folderName) && + isEmptyOwner(`f/${folderName}`) + ) + continue presentFolders.add(folderName) missingFolders.push({ folderName, items: [] }) } @@ -264,6 +293,8 @@ {showCode} {showEditButton} {leaf} + {openMemory} + {onManageFolder} /> {/snippet} @@ -280,42 +311,25 @@ <!-- Every row draws its own border-b, so the last one would double the frame's bottom border. Pulling the content 1px down puts that border under the frame, where overflow-hidden clips it, whichever row (collapsed owner, leaf, expanded subtree) ends the list. --> - <div class="border rounded-md bg-surface-tertiary overflow-hidden"> + <div class="{framed ? 'border rounded-md bg-surface-tertiary' : ''} overflow-hidden"> <div class="-mb-px"> {#each rows.slice(0, nbDisplayed) as row (row.kind === 'otherUsers' ? 'other_users' : 'folderName' in row.node ? `f__${row.node.folderName}` : 'username' in row.node ? `u__${row.node.username}` : `i__${row.node.type}__${row.node.path}`)} {#if row.kind === 'otherUsers'} <!-- Same shape as an owner row, so it reads as part of the tree. It only reveals the user rows under it: each still loads its own items when opened. --> - <!-- svelte-ignore a11y_click_events_have_key_events --> - <!-- svelte-ignore a11y_no_static_element_interactions --> - <div - onclick={toggleOtherUsers} - class="px-4 py-2 border-b w-full flex flex-row items-center justify-between cursor-pointer" + <TreeOwnerRow + icon={Users} + name="Other users" + opened={otherUsersOpen} + onToggle={toggleOtherUsers} + toggleLabel={otherUsersOpen ? 'Hide other users' : 'Show other users'} > - <div class="flex flex-row items-center gap-4"> - <Users size={16} class="text-secondary" /> - <div> - <span class="whitespace-nowrap text-xs text-emphasis font-semibold" - >Other users</span - > - <div class="text-2xs font-normal text-secondary whitespace-nowrap"> - ({pluralize(otherUsers.length, 'user')}{otherUsersItemCount != undefined - ? ` · ${pluralize(otherUsersItemCount, 'item')}` - : ''}) - </div> - </div> - </div> - <Button - iconOnly - unifiedSize="xs" - variant="subtle" - startIcon={{ icon: otherUsersOpen ? ChevronUp : ChevronDown }} - title={otherUsersOpen ? 'Hide other users' : 'Show other users'} - aria-label="Other users" - aria-expanded={otherUsersOpen} - onClick={toggleOtherUsers} - /> - </div> + {#snippet detail()} + ({pluralize(otherUsers.length, 'user')}{otherUsersItemCount != undefined + ? ` · ${pluralize(otherUsersItemCount, 'item')}` + : ''}) + {/snippet} + </TreeOwnerRow> {#if otherUsersOpen} <!-- Ranked after every root owner, so opening this row can't push folders out of what "expand all" auto-loads. --> @@ -324,7 +338,9 @@ {/each} {#if nbOtherUsersDisplayed < otherUsers.length} <div - class="pl-8 pr-4 py-2 border-b flex flex-row items-center justify-between gap-4 bg-surface-secondary" + class="pl-8 pr-4 py-2 {rowRule( + unruled + )} flex flex-row items-center justify-between gap-4 bg-surface-secondary" > <span class="text-xs text-secondary"> Showing {nbOtherUsersDisplayed} of {otherUsers.length} users diff --git a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte index 6e828eee34..5014e2842b 100644 --- a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte +++ b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte @@ -4,11 +4,11 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import type { HubProjectPick } from '$lib/hubProject' import { disableHubStore } from '$lib/stores' - import { useOperatorBuilderRights } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import CreateActionsMenu from './CreateActionsMenu.svelte' import HubTemplatePicker from './HubTemplatePicker.svelte' - const operatorBuilderRights = useOperatorBuilderRights() + const roleCaps = useRoleCapabilities() interface Props { /** A project was chosen here. The list owns the import dialog, and opens it on this. */ @@ -26,9 +26,17 @@ * take — the archived link stays, since reading archived items is not a write. */ canCreate?: boolean + /** See CreateActionsMenu's `onCreateFolder`. */ + onCreateFolder?: () => void } - let { onPick, archivedOnly = false, onShowArchived, canCreate = true }: Props = $props() + let { + onPick, + archivedOnly = false, + onShowArchived, + canCreate = true, + onCreateFolder + }: Props = $props() // Row opacities: the list fading out of existence. Static on purpose — motion is what // makes a skeleton mean "loading", and this state means "empty". @@ -38,8 +46,8 @@ // `border-light`; only the container outline steps up, so nothing outweighs its frame. const rowOpacities = [1, 0.7, 0.4] - // A builder gets no hub template: a hub project brings scripts and apps along. - const showHub = $derived(!$disableHubStore && !$operatorBuilderRights) + // A hub project brings scripts and apps along, which only a role with code may deploy. + const showHub = $derived(!$disableHubStore && $roleCaps.code) // The inline "create a new one" link is the anchor for the very same New menu the // toolbar button opens, so the menu pops next to the words that promised it. @@ -57,7 +65,7 @@ </script> <div - class="rounded-md border-[1.5px] border-dashed border-border-normal/60 bg-surface" + class="rounded-md border-[1.5px] border-dashed border-border-normal/60" role="status" aria-label={archivedOnly ? 'Everything here is archived' : 'Your workspace is empty'} > @@ -136,7 +144,7 @@ </Popover> or {/if} - <CreateActionsMenu source="empty_state" triggerElement={newLinkEl}> + <CreateActionsMenu source="empty_state" triggerElement={newLinkEl} {onCreateFolder}> {#snippet trigger()} <!-- The full stop rides inside the snippet: across a component boundary Svelte keeps the markup whitespace, which would leave a gap before it. --> diff --git a/frontend/src/lib/components/home/bulkActions.test.ts b/frontend/src/lib/components/home/bulkActions.test.ts index e00d5f5da5..f0edc5ffad 100644 --- a/frontend/src/lib/components/home/bulkActions.test.ts +++ b/frontend/src/lib/components/home/bulkActions.test.ts @@ -1,3 +1,4 @@ +import { FULL_CAPABILITIES } from '$lib/roleCapabilities' import { describe, it, expect } from 'vitest' import { blockedReason, movedPath, type BulkContext } from './bulkActions' import type { BulkItem } from './homeSelection.svelte' @@ -21,8 +22,8 @@ function item(over: Partial<BulkItem> = {}): BulkItem { } } -const admin: BulkContext = { workspace: 'w', isAdmin: true } -const member: BulkContext = { workspace: 'w', isAdmin: false } +const admin: BulkContext = { workspace: 'w', isAdmin: true, caps: FULL_CAPABILITIES } +const member: BulkContext = { workspace: 'w', isAdmin: false, caps: FULL_CAPABILITIES } // Each action's gate has to keep matching what the equivalent per-row menu entry // allows (common/table/{Script,Flow,App}Row.svelte, MoveDrawer.svelte) — a bulk @@ -45,6 +46,17 @@ describe('blockedReason', () => { expect(blockedReason('delete', item({ kind: 'app', canWrite: false }), member)).toBeDefined() }) + // The selection opens for any role with `code`, which may still lack apps. + it("refuses the kinds the member's role cannot author", () => { + const scripter = { ...member, caps: { ...FULL_CAPABILITIES, apps: 'none' as const } } + expect(blockedReason('delete', item({ kind: 'app' }), scripter)).toBeDefined() + expect(blockedReason('move', item({ kind: 'app', rawApp: true }), scripter)).toBeDefined() + expect(blockedReason('move', item({ kind: 'flow' }), scripter)).toBeUndefined() + const ownDraft = item({ kind: 'app', draftOnly: true }) + expect(blockedReason('discard', ownDraft, scripter)).toBeUndefined() + expect(blockedReason('discard', { ...ownDraft, legacyDraft: true }, scripter)).toBeDefined() + }) + it('requires ownership to move, and refuses archived rows', () => { expect(blockedReason('move', item({ owner: false }), admin)).toBeDefined() expect(blockedReason('move', item({ canWrite: false }), admin)).toBeDefined() diff --git a/frontend/src/lib/components/home/bulkActions.ts b/frontend/src/lib/components/home/bulkActions.ts index 20a65ec596..2cc5cf1f94 100644 --- a/frontend/src/lib/components/home/bulkActions.ts +++ b/frontend/src/lib/components/home/bulkActions.ts @@ -9,7 +9,8 @@ * there is nothing deployed at its path. */ import { AppService, DraftService, FlowService, ResourceService, ScriptService } from '$lib/gen' -import type { UserDraftItemKind } from '$lib/gen' +import type { RoleCapabilities, UserDraftItemKind } from '$lib/gen' +import { roleCanAuthor, roleCanDraft } from '$lib/editRights' import { updateItemPathAndSummary } from '$lib/components/moveRenameManager' import { discardDraft } from '$lib/utils_draft_deploy' import type { BulkItem } from './homeSelection.svelte' @@ -30,6 +31,8 @@ export type BulkContext = { workspace: string /** Deleting a script is admin-only, mirroring the row menu. */ isAdmin: boolean + /** The role's capabilities: a role that codes may still lack the flows or apps it selects. */ + caps: RoleCapabilities } /** Why `action` cannot be applied to `item`; `undefined` means it can. The @@ -41,6 +44,12 @@ export function blockedReason( ctx: BulkContext ): string | undefined { const notOwner = 'you are not an owner of this path' + const kind = draftKind(item) + // Discarding one's own draft needs no authoring right server-side, so a member who lost it + // can still clean up; a legacy (owner-less) draft does. + const roleGated = action !== 'discard' || item.legacyDraft + if (roleGated && !(action === 'discard' ? roleCanDraft : roleCanAuthor)(kind, ctx.caps)) + return 'your role cannot author this kind of item' switch (action) { case 'move': if (item.archived) return 'archived items cannot be moved' diff --git a/frontend/src/lib/components/home/clampRows.ts b/frontend/src/lib/components/home/clampRows.ts new file mode 100644 index 0000000000..b62b45dcf5 --- /dev/null +++ b/frontend/src/lib/components/home/clampRows.ts @@ -0,0 +1,65 @@ +import type { Action } from 'svelte/action' + +export type ClampRowsOptions = { rows: number; expanded: boolean } + +/** + * Keeps a wrapping row of `[data-chip]` items to `rows` lines, measured rather than counted, so + * how many fit follows the width. The `[data-clamp-toggle]` child shows only on overflow, and + * while collapsed it takes the end of the last line: items are hidden from there back until it + * fits. A `[data-selected]` item is never hidden, since clicking it is how its filter clears. + */ +export const clampRows: Action<HTMLElement, ClampRowsOptions> = (node, initial) => { + let options = initial + let frame = 0 + let width = -1 + + function run() { + frame = 0 + const toggle = node.querySelector<HTMLElement>('[data-clamp-toggle]') + const items = Array.from(node.querySelectorAll<HTMLElement>('[data-chip]')) + for (const item of items) item.hidden = false + if (toggle) toggle.hidden = true + + // Every position is read before any item is hidden: reading one after a write forces a + // layout per item, quadratic in the number of chips. + const tops = items.map((item) => item.offsetTop) + const lines = [...new Set(tops)].sort((a, b) => a - b) + if (lines.length <= options.rows || !toggle) return + toggle.hidden = false + if (options.expanded) return + + const lastLine = lines[options.rows - 1] + items.forEach((item, i) => { + if (tops[i] > lastLine && !item.hasAttribute('data-selected')) item.hidden = true + }) + const hideable = items.filter((item) => !item.hidden && !item.hasAttribute('data-selected')) + while (toggle.offsetTop > lastLine && hideable.length) hideable.pop()!.hidden = true + } + + function schedule() { + if (!frame) frame = requestAnimationFrame(run) + } + + // Width only: hiding items changes the height, which must not measure again. + const resize = new ResizeObserver(([entry]) => { + if (entry.contentRect.width === width) return + width = entry.contentRect.width + schedule() + }) + resize.observe(node) + // The items themselves changing; the `hidden` flips above are attributes, not seen here. + const mutations = new MutationObserver(schedule) + mutations.observe(node, { childList: true, subtree: true, characterData: true }) + + return { + update(next) { + options = next + schedule() + }, + destroy() { + cancelAnimationFrame(frame) + resize.disconnect() + mutations.disconnect() + } + } +} diff --git a/frontend/src/lib/components/home/deploy_ui.ts b/frontend/src/lib/components/home/deploy_ui.ts index 1134789e76..ea51129347 100644 --- a/frontend/src/lib/components/home/deploy_ui.ts +++ b/frontend/src/lib/components/home/deploy_ui.ts @@ -4,14 +4,55 @@ import { ALL_DEPLOYABLE } from '$lib/utils_deployable' import { get, writable } from 'svelte/store' const deployUiStore = writable<Record<string, WorkspaceDeployUISettings>>({}) +let pending: Record<string, Promise<WorkspaceDeployUISettings>> = {} +let generation = 0 + +// Until the license loads, a load reads as CE and resolves to ALL_DEPLOYABLE. Rows warm the cache +// on mount, often before then, so a license arriving drops whatever was loaded without it. +enterpriseLicense.subscribe((license) => { + if (!license) return + const hadSettings = Object.keys(get(deployUiStore)).length > 0 || Object.keys(pending).length > 0 + generation++ + pending = {} + deployUiStore.set({}) + if (hadSettings) warmDeployUiSettings() +}) + export async function getDeployUiSettings(): Promise<WorkspaceDeployUISettings> { - let deployUiSettings = get(deployUiStore) - let workspace = get(workspaceStore) - if (!deployUiSettings[workspace!]) { - deployUiSettings[workspace!] = await getDeployUiSettingsInner() - deployUiStore.set(deployUiSettings) + const workspace = get(workspaceStore)! + const cached = get(deployUiStore)[workspace] + if (cached) return cached + const gen = generation + const load = (pending[workspace] ??= getDeployUiSettingsInner()) + let settings: WorkspaceDeployUISettings + try { + settings = await load + } finally { + if (pending[workspace] === load) delete pending[workspace] } - return deployUiSettings[workspace!] + if (gen !== generation) return getDeployUiSettings() + deployUiStore.update((s) => ({ ...s, [workspace]: settings })) + return settings +} + +/** + * Starts loading the settings without waiting for them. Every row on a page calls this, so a + * failed fetch must not reject: the root layout toasts each unhandled rejection, once per row. + */ +export function warmDeployUiSettings(): void { + getDeployUiSettings().catch(() => {}) +} + +/** + * The current workspace's settings if a load has already resolved. Row menus read this so they + * can build their items synchronously: a menu whose items arrive after it opens is positioned for + * its loading spinner and then flips once the real list is taller. A miss starts a new load, so a + * fetch that failed is retried on the next open. + */ +export function cachedDeployUiSettings(): WorkspaceDeployUISettings | undefined { + const settings = get(deployUiStore)[get(workspaceStore)!] + if (!settings) warmDeployUiSettings() + return settings } async function getDeployUiSettingsInner(): Promise<WorkspaceDeployUISettings> { diff --git a/frontend/src/lib/components/home/homeQuickAccessSettings.svelte.ts b/frontend/src/lib/components/home/homeQuickAccessSettings.svelte.ts new file mode 100644 index 0000000000..af88da656a --- /dev/null +++ b/frontend/src/lib/components/home/homeQuickAccessSettings.svelte.ts @@ -0,0 +1,56 @@ +import { BROWSER } from 'esm-env' +import { getLocalSetting, storeLocalSetting } from '$lib/utils' + +// Per browser, like the composer's own pin: how a reader likes their Home laid out. +const HIDDEN_SETTING = 'home-quick-access-hidden' +const ROWS_SETTING = 'home-quick-access-rows' +const NO_FAVORITES_SETTING = 'home-quick-access-no-favorites' +const NO_RECENT_SETTING = 'home-quick-access-no-recent' + +export const QUICK_ACCESS_ROWS = [1, 2, 3, 4] as const +export type QuickAccessRows = (typeof QUICK_ACCESS_ROWS)[number] +const DEFAULT_ROWS: QuickAccessRows = 2 + +// Blocked storage (some private windows) throws on write; the setting then lasts the visit. +function save(name: string, value: string | undefined) { + try { + storeLocalSetting(name, value) + } catch {} +} + +function readRows(): QuickAccessRows { + const raw = getLocalSetting(ROWS_SETTING) + return QUICK_ACCESS_ROWS.find((r) => String(r) === raw) ?? DEFAULT_ROWS +} + +class HomeQuickAccessSettings { + hidden = $state(BROWSER && getLocalSetting(HIDDEN_SETTING) === 'true') + rows = $state<QuickAccessRows>(BROWSER ? readRows() : DEFAULT_ROWS) + showFavorites = $state(!(BROWSER && getLocalSetting(NO_FAVORITES_SETTING) === 'true')) + showRecent = $state(!(BROWSER && getLocalSetting(NO_RECENT_SETTING) === 'true')) + /** Bumped on each hide, so the header menu that holds the way back can flash. */ + hideCount = $state(0) + + setHidden(next: boolean) { + this.hidden = next + if (next) this.hideCount++ + save(HIDDEN_SETTING, next ? 'true' : undefined) + } + + setShowFavorites(next: boolean) { + this.showFavorites = next + save(NO_FAVORITES_SETTING, next ? undefined : 'true') + } + + setShowRecent(next: boolean) { + this.showRecent = next + save(NO_RECENT_SETTING, next ? undefined : 'true') + } + + setRows(next: QuickAccessRows) { + this.rows = next + save(ROWS_SETTING, next === DEFAULT_ROWS ? undefined : String(next)) + } +} + +export const homeQuickAccessSettings = new HomeQuickAccessSettings() diff --git a/frontend/src/lib/components/home/recentItems.svelte.ts b/frontend/src/lib/components/home/recentItems.svelte.ts new file mode 100644 index 0000000000..29057df0f3 --- /dev/null +++ b/frontend/src/lib/components/home/recentItems.svelte.ts @@ -0,0 +1,112 @@ +import { untrack } from 'svelte' +import { onUserChange, scopedKey } from '$lib/userScopedStorage' + +export type RecentKind = 'script' | 'flow' | 'app' | 'raw_app' | 'agent' + +export type RecentItem = { + kind: RecentKind + path: string + summary?: string + /** Epoch ms of the last time the item was opened, in its editor or on its own page. */ + at: number + /** How it was last opened: in its editor, or on its page to run or use it. Items stored + * before views were recorded have none, and were all edits. */ + via?: RecentVia +} + +export type RecentVia = 'edit' | 'view' + +type RecordedItem = Omit<RecentItem, 'at' | 'via'> & { via: RecentVia } + +const MAX_ITEMS = 30 +export const MAX_AGE_DAYS = 7 +const MAX_AGE_MS = MAX_AGE_DAYS * 24 * 60 * 60 * 1000 + +function fresh(items: RecentItem[]): RecentItem[] { + const cutoff = Date.now() - MAX_AGE_MS + return items.filter((x) => typeof x.at === 'number' && x.at >= cutoff) +} + +// Per user (scopedKey) and per workspace: what one person opened in one workspace says nothing +// about another, and a shared browser must not show the previous user's items. +function storageKey(workspace: string): string | undefined { + return scopedKey(`homeRecentItems:${workspace}`) +} + +function read(workspace: string): RecentItem[] { + const key = storageKey(workspace) + if (!key) return [] + try { + const parsed = JSON.parse(localStorage.getItem(key) ?? '[]') + return Array.isArray(parsed) + ? parsed.filter((x) => x && typeof x.path === 'string' && typeof x.kind === 'string') + : [] + } catch { + return [] + } +} + +function write(workspace: string, items: RecentItem[]): void { + const key = storageKey(workspace) + if (!key) return + try { + localStorage.setItem(key, JSON.stringify(items)) + } catch {} +} + +class RecentItems { + // Bumped on every write and on the user resolving, so readers re-read storage. + #version = $state(0) + // `++` reads the counter too: bumped from an effect (a page recording its visit), the effect + // would depend on it and re-run on its own write, forever. + #bump() { + untrack(() => this.#version++) + } + // A page opened by a cold load can finish loading before the user's email resolves, and the + // storage key needs it; those visits wait here instead of being dropped. + #pending: { workspace: string; item: RecordedItem }[] = [] + + constructor() { + onUserChange((email) => { + if (email) { + const pending = this.#pending + this.#pending = [] + for (const p of pending) this.record(p.workspace, p.item) + } + this.#bump() + }) + } + + list(workspace: string): RecentItem[] { + this.#version + return fresh(read(workspace)) + } + + /** Records an item as just opened. A missing summary keeps the one already stored. */ + record(workspace: string, item: RecordedItem): void { + if (!workspace || !item.path) return + if (!storageKey(workspace)) { + this.#pending.push({ workspace, item }) + return + } + const previous = fresh(read(workspace)) + const existing = previous.find((x) => x.kind === item.kind && x.path === item.path) + const next: RecentItem = { + ...item, + summary: item.summary || existing?.summary, + at: Date.now() + } + write(workspace, [next, ...previous.filter((x) => x !== existing)].slice(0, MAX_ITEMS)) + this.#bump() + } + + forget(workspace: string, kind: RecentKind, path: string): void { + write( + workspace, + read(workspace).filter((x) => !(x.kind === kind && x.path === path)) + ) + this.#bump() + } +} + +export const recentItems = new RecentItems() diff --git a/frontend/src/lib/components/home/treeViewState.svelte.ts b/frontend/src/lib/components/home/treeViewState.svelte.ts index b12597f51d..b8f23a7bcf 100644 --- a/frontend/src/lib/components/home/treeViewState.svelte.ts +++ b/frontend/src/lib/components/home/treeViewState.svelte.ts @@ -20,3 +20,39 @@ export class TreeViewState { storeLocalSetting(this.#settingName, value ? 'true' : undefined) } } + +/** The tree nodes a user opened by hand, by full path prefix, persisted under `settingName`. */ +export class TreeOpenMemory { + // Bounds what a long-lived browser accumulates; the oldest openings drop first. + static readonly MAX = 200 + #settingName: string + #open: string[] + + constructor(settingName: string) { + this.#settingName = settingName + let stored: unknown + try { + stored = JSON.parse(getLocalSetting(settingName) ?? '[]') + } catch {} + this.#open = Array.isArray(stored) ? stored.filter((k) => typeof k === 'string') : [] + } + + isOpen(prefix: string): boolean { + return this.#open.includes(prefix) + } + + setOpen(prefix: string, open: boolean) { + this.#open = this.#open.filter((k) => k !== prefix) + if (open) this.#open = [...this.#open, prefix].slice(-TreeOpenMemory.MAX) + this.#save() + } + + clear() { + this.#open = [] + this.#save() + } + + #save() { + storeLocalSetting(this.#settingName, this.#open.length ? JSON.stringify(this.#open) : undefined) + } +} diff --git a/frontend/src/lib/components/instanceSettings.ts b/frontend/src/lib/components/instanceSettings.ts index 9c55834caa..54c59f3362 100644 --- a/frontend/src/lib/components/instanceSettings.ts +++ b/frontend/src/lib/components/instanceSettings.ts @@ -6,6 +6,7 @@ import { ACCENT_COLOR_SETTING, parseAccentColor } from '$lib/accentColor' import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration' import { writable } from 'svelte/store' import { OidcService } from '$lib/gen' +import { workspaceRolesErrors } from '$lib/workspaceRoles' /** * Bumped after instance settings are successfully saved. Settings whose display @@ -78,6 +79,7 @@ export interface Setting { | 'instance_banner' | 'accent_color' | 'agent_workload_identity_issuers' + | 'workspace_roles' storage: SettingStorage advancedToggle?: { label: string @@ -635,6 +637,16 @@ export const settings: Record<string, Setting[]> = { (Number.isInteger(Number(v)) && Number(v) >= 0 && Number(v) <= 3650) } ], + 'Workspace roles': [ + { + label: 'Workspace roles', + key: 'workspace_roles', + fieldType: 'workspace_roles', + storage: 'setting', + ee_only: 'Custom workspace roles are only available in the EE version', + validate: workspaceRolesErrors + } + ], 'Managed Postgres': [ { label: 'External instance', @@ -1325,6 +1337,13 @@ export const instanceSettingsNavigationGroups = [ label: 'Jobs', aiId: 'instance-settings-jobs', aiDescription: 'Instance jobs settings' + }, + { + id: 'workspace_roles', + label: 'Workspace roles', + aiId: 'instance-settings-workspace-roles', + aiDescription: 'Roles workspace members can hold and their capabilities', + isEE: true } ] }, @@ -1516,6 +1535,7 @@ export const tabToCategoryMap: Record<string, string> = { object_storage: 'Object Storage', managed_postgres: 'Managed Postgres', jobs: 'Jobs', + workspace_roles: 'Workspace roles', private_hub: 'Private Hub', github_enterprise_app: 'GitHub App', websocket: 'WebSocket', @@ -1579,6 +1599,7 @@ export const categoryToTabMap: Record<string, string> = { 'Object Storage': 'object_storage', 'Managed Postgres': 'managed_postgres', Jobs: 'jobs', + 'Workspace roles': 'workspace_roles', 'Private Hub': 'private_hub', 'GitHub App': 'github_enterprise_app', WebSocket: 'websocket', diff --git a/frontend/src/lib/components/instanceSettings/WorkspaceRolesSetting.svelte b/frontend/src/lib/components/instanceSettings/WorkspaceRolesSetting.svelte new file mode 100644 index 0000000000..404f27e638 --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/WorkspaceRolesSetting.svelte @@ -0,0 +1,253 @@ +<script lang="ts"> + import type { Writable } from 'svelte/store' + import { untrack } from 'svelte' + import { Alert, Badge, Button } from '../common' + import TextInput from '../text_input/TextInput.svelte' + import RoleCapabilitiesEditor from '../settings/RoleCapabilitiesEditor.svelte' + import type { RoleCapabilities, RoleCapabilitiesPatch, RoleDefinition } from '$lib/gen' + import { + applyCapabilitiesPatch, + authorLevelLabel, + baseCapabilitiesFor, + DEFAULT_INSTANCE_ROLES, + DEVELOPER_ROLE, + isDefaultInstanceRoles, + isEmptyPatch, + workspaceRolesErrors + } from '$lib/workspaceRoles' + import { dragHandle, dragHandleZone } from '@windmill-labs/svelte-dnd-action' + import { ChevronDown, ChevronRight, GripVertical, Plus, RotateCcw, Trash2 } from 'lucide-svelte' + + interface Props { + values: Writable<Record<string, any>> + loading?: boolean + /** Without a valid license the stored list keeps applying but can only be reset. */ + unlicensed?: boolean + } + + let { values, loading = false, unlicensed = false }: Props = $props() + + const disabled = $derived(loading || unlicensed) + + const KEY = 'workspace_roles' + + type Row = { + id: number + name: string + label: string + capabilities: RoleCapabilitiesPatch + open: boolean + } + + let nextId = 0 + let rows = $state<Row[]>([]) + // The JSON last read from or written to `$values[KEY]`, to tell our own writes from external + // ones (the async load, Save, Discard) and re-hydrate only on the latter. + let lastSynced: string | undefined = undefined + + function toRows(v: unknown): Row[] { + const list = Array.isArray(v) && v.length > 0 ? (v as RoleDefinition[]) : DEFAULT_INSTANCE_ROLES + return list.map((r) => ({ + id: nextId++, + name: r.name ?? '', + label: r.label ?? '', + capabilities: structuredClone(r.capabilities ?? {}), + open: false + })) + } + + function serialize(rs: Row[]): RoleDefinition[] | undefined { + const list: RoleDefinition[] = rs.map((r) => ({ + name: r.name.trim(), + ...(r.label.trim() ? { label: r.label.trim() } : {}), + ...(isEmptyPatch(r.capabilities) ? {} : { capabilities: r.capabilities }) + })) + return isDefaultInstanceRoles(list) ? undefined : list + } + + $effect(() => { + const cur = JSON.stringify($values[KEY] ?? null) + if (cur === lastSynced) return + lastSynced = cur + const open = new Set(rows.filter((r) => r.open).map((r) => r.name)) + rows = toRows($values[KEY]).map((r) => ({ + ...r, + open: open.has(r.name) + })) + }) + + $effect(() => { + const next = serialize($state.snapshot(rows) as Row[]) + if (lastSynced === undefined || disabled) return + const nextStr = JSON.stringify(next ?? null) + // Compared with the stored value in serialized form, so one spelled differently (the + // defaults written out, an empty `capabilities`, another key order) is not rewritten + // and the category not marked unsaved before anything is edited. + const stored = untrack(() => $values[KEY]) + if (nextStr === JSON.stringify(serialize(toRows(stored)) ?? null)) return + lastSynced = nextStr + $values[KEY] = next + }) + + const errors = $derived(workspaceRolesErrors(serialize(rows) ?? DEFAULT_INSTANCE_ROLES)) + + const flipDurationMs = 200 + + function addRole() { + rows = [...rows, { id: nextId++, name: '', label: '', capabilities: {}, open: true }] + } + + function summary(caps: RoleCapabilities): string { + return [ + caps.code ? 'Code' : 'No code', + `Flows: ${authorLevelLabel(caps.flows).toLowerCase()}`, + `Apps: ${authorLevelLabel(caps.apps).toLowerCase()}` + ].join(' · ') + } +</script> + +<div class="flex flex-col gap-3"> + {#if unlicensed} + <Alert + type="info" + size="xs" + title="Changing workspace roles requires a valid Windmill Enterprise Edition license" + > + The roles below keep applying as they are. A workspace admin can still override what they + allow in that workspace's settings. + {#if serialize(rows) !== undefined} + <div class="mt-2"> + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: RotateCcw }} + disabled={loading} + onclick={() => ($values[KEY] = undefined)} + > + Reset to the default roles + </Button> + </div> + {/if} + </Alert> + {/if} + <span class="text-xs text-secondary"> + Roles members can hold in every workspace, in order: when several instance groups map a member + to different roles, the role listed first wins. A capability left unset uses the default: + everything for a role named <code>developer</code>, the operator rights for any other name. + Workspace admins can override a role in their workspace. A role still held by a member, invite, + auto-invite or instance group mapping cannot be removed. + </span> + + <section + class="flex flex-col gap-3" + use:dragHandleZone={{ + items: rows, + flipDurationMs, + dragDisabled: disabled, + // The handle zone is drag-disabled between drags, which would otherwise mark every + // input in it aria-disabled. + autoAriaDisabled: true, + dropTargetStyle: {} + }} + onconsider={(e) => (rows = e.detail.items)} + onfinalize={(e) => (rows = e.detail.items)} + > + {#each rows as row, i (row.id)} + {@const base = baseCapabilitiesFor(row.name)} + {@const caps = applyCapabilitiesPatch(base, row.capabilities)} + <div class="flex flex-col rounded-md border bg-surface-tertiary"> + <div class="flex items-center gap-2 p-2"> + <div + class="shrink-0 flex items-center {disabled + ? 'text-disabled cursor-not-allowed' + : 'text-secondary cursor-move'}" + use:dragHandle + aria-label="Reorder role {row.name || i + 1}" + > + <GripVertical size={16} /> + </div> + <div class="flex flex-col gap-0.5 w-40 shrink-0"> + <TextInput + size="sm" + bind:value={row.name} + error={errors[`${i}.name`]} + inputProps={{ placeholder: 'name', disabled, 'aria-label': 'Role name' }} + /> + </div> + <span class="text-2xs text-secondary truncate grow"> + {#if row.label.trim()} + <span class="text-primary">{row.label.trim()}</span> · + {/if} + {summary(caps)} + </span> + {#if i === 0} + <Badge color="gray" verySmall>Highest</Badge> + {/if} + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: row.open ? ChevronDown : ChevronRight }} + onclick={() => (row.open = !row.open)} + > + Capabilities + </Button> + <Button + variant="subtle" + unifiedSize="sm" + destructive + iconOnly + startIcon={{ icon: Trash2 }} + aria-label="Remove role" + title={rows.length === 1 ? 'Keep at least one role' : 'Remove role'} + disabled={disabled || rows.length === 1} + onclick={() => (rows = rows.filter((r) => r.id !== row.id))} + /> + </div> + {#if errors[`${i}.name`]} + <span class="text-2xs text-red-600 dark:text-red-400 px-2 pb-2 -mt-1"> + {errors[`${i}.name`]} + </span> + {/if} + {#if row.open} + <div class="border-t p-3 flex flex-col gap-3"> + <div class="flex items-center gap-2"> + <span class="text-xs font-semibold text-emphasis w-24">Label</span> + <div class="w-60"> + <TextInput + size="sm" + bind:value={row.label} + inputProps={{ + placeholder: row.name || 'label', + disabled, + 'aria-label': 'Role label' + }} + /> + </div> + </div> + <RoleCapabilitiesEditor + {base} + patch={row.capabilities} + baseName={row.name === DEVELOPER_ROLE ? 'developer default' : 'operator default'} + setText="Set" + inheritedText="Default" + {disabled} + onchange={(p) => (row.capabilities = p)} + /> + </div> + {:else if errors[`${i}.capabilities`]} + <span class="text-2xs text-red-600 dark:text-red-400 px-2 pb-2"> + {errors[`${i}.capabilities`]} + </span> + {/if} + </div> + {/each} + </section> + + {#if !disabled} + <div> + <Button variant="default" unifiedSize="sm" startIcon={{ icon: Plus }} onclick={addRole}> + Add role + </Button> + </div> + {/if} +</div> diff --git a/frontend/src/lib/components/mcp/McpAccessPicker.svelte b/frontend/src/lib/components/mcp/McpAccessPicker.svelte new file mode 100644 index 0000000000..6466bb8761 --- /dev/null +++ b/frontend/src/lib/components/mcp/McpAccessPicker.svelte @@ -0,0 +1,150 @@ +<script lang="ts" module> + export type McpAccess = 'read' | 'read_run' | 'full' | 'selected' + + /** Marks a selection, so the per-workspace URLs add no API endpoint tools to it. */ + export const RUNNABLES_AS_TOOLS = 'mcp:runnables_as_tools' + + /** Added by the server to an `mcp:all` sign-in so the tools server's URLs serve it the AI + * session's tools. Grants nothing, so it is never shown. */ + export const MCP_SESSION = 'mcp:session' + + const ACCESS_SCOPES: Record<Exclude<McpAccess, 'selected'>, string[]> = { + read: ['mcp:all', 'mcp:read_only'], + read_run: ['mcp:all', 'mcp:read_run'], + full: ['mcp:all'] + } + + /** The access a token's MCP scopes give: `mcp:all` and how it is narrowed, or else a + * selection of scripts, flows and endpoints. */ + export function mcpAccessOf(scopes: string[]): McpAccess { + scopes = scopes.filter((s) => s !== RUNNABLES_AS_TOOLS && s !== MCP_SESSION) + if (!scopes.includes('mcp:all')) return scopes.length > 0 ? 'selected' : 'full' + if (scopes.includes('mcp:read_only')) return 'read' + if (scopes.includes('mcp:read_run')) return 'read_run' + return 'full' + } +</script> + +<script lang="ts"> + import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' + import McpScopeSelector from './McpScopeSelector.svelte' + import Popover from '$lib/components/Popover.svelte' + import { Badge } from '$lib/components/common' + import Section from '$lib/components/Section.svelte' + import { SvelteMap } from 'svelte/reactivity' + + interface Props { + /** The workspace the selection picker browses. */ + workspaceId: string + /** The token's MCP scopes, the workspace list aside. */ + scopes?: string[] + access?: McpAccess + initialScopes?: string[] + } + + let { + workspaceId, + scopes = $bindable(), + access = $bindable(), + initialScopes = [] + }: Props = $props() + + const initialAccess = mcpAccessOf(initialScopes) + access = initialAccess + const initialSelection = + initialAccess === 'selected' + ? initialScopes.filter((s) => s !== RUNNABLES_AS_TOOLS && s !== MCP_SESSION).join(' ') + : undefined + let selection = $state(initialSelection ?? 'mcp:favorites') + + $effect(() => { + scopes = + access === 'selected' || access === undefined + ? [ + ...selection.split(' ').filter((s) => s.length > 0 && s !== RUNNABLES_AS_TOOLS), + RUNNABLES_AS_TOOLS + ] + : ACCESS_SCOPES[access] + }) + + // The tools each access level gives, as the server lists them. + type ToolsetEntry = { name: string; description: string } + let toolsCollapsed = $state(true) + const toolsets = new SvelteMap<string, ToolsetEntry[]>() + const toolsetAccess = $derived(access === 'selected' ? undefined : access) + $effect(() => { + const level = toolsetAccess + if (toolsCollapsed || !level || toolsets.has(level)) return + fetch(`/api/mcp/toolset?access=${level}`) + .then((r) => (r.ok ? r.json() : [])) + .then((tools: ToolsetEntry[]) => toolsets.set(level, tools)) + .catch(() => toolsets.set(level, [])) + }) + const tools = $derived(toolsetAccess ? toolsets.get(toolsetAccess) : undefined) +</script> + +<div class="flex flex-col gap-4"> + <div> + <span class="block mb-1 text-emphasis text-xs font-semibold">Access</span> + <ToggleButtonGroup bind:selected={access} allowEmpty={false}> + {#snippet children({ item })} + <ToggleButton + {item} + value="full" + label="Build and run" + tooltip="Everything you can do yourself: explore, write, test and deploy drafts, and run." + /> + <ToggleButton + {item} + value="read_run" + label="Read and run" + tooltip="Explore, and run deployed scripts and flows. The client changes nothing itself; the scripts and flows it runs can." + /> + <ToggleButton + {item} + value="read" + label="Read only" + tooltip="Explore and read. Nothing is run or changed." + /> + <ToggleButton + {item} + value="selected" + label="Scripts and flows as tools" + tooltip="The scripts and flows you pick, each as its own tool, and nothing else. To share a few automations." + /> + {/snippet} + </ToggleButtonGroup> + </div> + {#if toolsetAccess} + <Section label="Tools the client gets" small collapsable bind:collapsed={toolsCollapsed}> + <div class="flex flex-col gap-1 -mt-2"> + <span class="text-2xs text-secondary"> + {tools ? `${tools.length} tools. Hover one for what it does.` : 'Loading tools…'} + </span> + <div class="flex flex-wrap gap-1"> + {#each tools ?? [] as tool (tool.name)} + <Popover notClickable> + {#snippet text()} + <div class="text-xs max-w-md">{tool.description}</div> + {/snippet} + <Badge rounded small color="gray">{tool.name}</Badge> + </Popover> + {/each} + </div> + </div> + </Section> + {/if} + {#if access === 'selected'} + <p class="text-2xs text-secondary -mt-2"> + The client can run these scripts and flows and nothing else: it cannot explore the workspace, + read runs, build, or run anything outside the selection. + </p> + <McpScopeSelector + {workspaceId} + bind:scope={selection} + initialScope={initialSelection} + runnablesOnly + /> + {/if} +</div> diff --git a/frontend/src/lib/components/mcp/McpConnect.svelte b/frontend/src/lib/components/mcp/McpConnect.svelte index a8808aa052..5cf286be80 100644 --- a/frontend/src/lib/components/mcp/McpConnect.svelte +++ b/frontend/src/lib/components/mcp/McpConnect.svelte @@ -278,27 +278,21 @@ if (!t) return const { workspace, path } = t try { - let account: number | undefined = undefined - if (res?.expires_in != undefined) { - account = Number( - await OauthService.createAccount({ - workspace, - requestBody: { - refresh_token: res.refresh_token ?? '', - expires_in: res.expires_in, - client: t.client, - scopes: t.scopes - } - }) - ) - } await upsertSecretVariable({ workspace, path, value: res.access_token, resourcePath: path, isOauth: true, - account + account: + res?.expires_in != undefined + ? { + refresh_token: res.refresh_token ?? '', + expires_in: res.expires_in, + client: t.client, + scopes: t.scopes + } + : undefined }) await createMcpResource(t, `$var:${path}`) sendUserToast(`Connected ${t.label}`) diff --git a/frontend/src/lib/components/mcp/McpScopeSelector.svelte b/frontend/src/lib/components/mcp/McpScopeSelector.svelte index 46274d10d0..35b815fcff 100644 --- a/frontend/src/lib/components/mcp/McpScopeSelector.svelte +++ b/frontend/src/lib/components/mcp/McpScopeSelector.svelte @@ -25,9 +25,19 @@ scope: string initialScope?: string readOnly?: boolean + /** Scripts and flows alone, for `/api/mcp`: a selection gets no endpoint tools there, so + * endpoints are left out, and since `mcp:all` is the full toolset, "All scripts/flows" + * is written as `mcp:scripts:* mcp:flows:*`. */ + runnablesOnly?: boolean } - let { workspaceId, scope = $bindable(), initialScope, readOnly = false }: Props = $props() + let { + workspaceId, + scope = $bindable(), + initialScope, + readOnly = false, + runnablesOnly = false + }: Props = $props() // Mirrors ITEMS_FETCH_MAX_LIMIT in backend/windmill-api/src/mcp/utils.rs: the // server exposes at most this many scripts and this many flows (per type) as @@ -147,8 +157,15 @@ scriptFolders.length === flowFolders.length && scriptFolders.every((f, i) => f === flowFolders[i]) const endpointsIsAll = byKind.endpoints?.length === 1 && byKind.endpoints[0] === '*' + // Without endpoints, scopes say "folder" or "all" with the scripts and flows alone. + const endpointsAsExpected = runnablesOnly ? !byKind.endpoints : endpointsIsAll + const isWildcard = (patterns?: string[]) => patterns?.length === 1 && patterns[0] === '*' - if (mode !== 'favorites' && mode !== 'all' && sameFolders && endpointsIsAll) { + if (runnablesOnly && isWildcard(byKind.scripts) && isWildcard(byKind.flows)) { + return { ...empty, mode: 'all', hubApps } + } + + if (mode !== 'favorites' && mode !== 'all' && sameFolders && endpointsAsExpected) { return { mode: 'folder', folders: scriptFolders.filter((f): f is string => !!f), @@ -205,14 +222,21 @@ scopeParts.push(`mcp:flows:${flowPaths.join(',')}`) } - if (selectedEndpoints.length > 0) { + if (!runnablesOnly && selectedEndpoints.length > 0) { scopeParts.push(`mcp:endpoints:${selectedEndpoints.join(',')}`) } } else if (selectedMode === 'folder') { const folderPaths = selectedFolders.map((f) => `f/${f}/*`).join(',') if (selectedFolders.length > 0) { - scopeParts = [`mcp:scripts:${folderPaths}`, `mcp:flows:${folderPaths}`, `mcp:endpoints:*`] + scopeParts = [`mcp:scripts:${folderPaths}`, `mcp:flows:${folderPaths}`] + if (!runnablesOnly) { + scopeParts.push(`mcp:endpoints:*`) + } } + } else if (selectedMode === 'all' && runnablesOnly) { + // `mcp:all` is the full toolset on `/api/mcp`: every script and flow as its own + // tool is said with wildcards instead. + scopeParts = ['mcp:scripts:*', 'mcp:flows:*'] } else { scopeParts = [`mcp:${selectedMode}`] } @@ -656,16 +680,18 @@ {/if} </div> - <div class="flex flex-col gap-2 mt-2"> - {@render sectionHeader('API Endpoints', selectAllEndpoints, clearAllEndpoints)} - <MultiSelect - items={safeSelectItems(selectableEndpointTools.map((e) => e.name))} - placeholder="Select endpoints" - bind:value={selectedEndpoints} - /> - </div> + {#if !runnablesOnly} + <div class="flex flex-col gap-2 mt-2"> + {@render sectionHeader('API Endpoints', selectAllEndpoints, clearAllEndpoints)} + <MultiSelect + items={safeSelectItems(selectableEndpointTools.map((e) => e.name))} + placeholder="Select endpoints" + bind:value={selectedEndpoints} + /> + </div> + {/if} - {#if withheldEndpoints.length > 0} + {#if !runnablesOnly && withheldEndpoints.length > 0} <Alert type="warning" size="xs" title="Some selected endpoints will not be exposed"> <span class="text-xs"> Endpoints that cannot be limited to specific script paths are withheld from a token @@ -675,7 +701,7 @@ </Alert> {/if} - {#if runByPathTools.length > 0} + {#if !runnablesOnly && runByPathTools.length > 0} <div class="flex flex-col gap-2 mt-2"> <span class="block text-xs font-semibold">Run tools</span> <p class="text-xs text-tertiary"> @@ -701,8 +727,9 @@ {/if} <div class="text-xs text-primary mt-2"> - Selected: {selectedScripts.length} scripts, {selectedFlows.length} flows, {selectedEndpoints.length} - endpoints + Selected: {selectedScripts.length} scripts, {selectedFlows.length} flows{#if !runnablesOnly}, + {selectedEndpoints.length} + endpoints{/if} </div> <!-- Wildcard Patterns Section --> @@ -785,23 +812,25 @@ </p> {/if} - <span class="block text-xs mt-2">API endpoint tools that will be available via MCP</span> - <div class="flex flex-wrap gap-1"> - {#each exposedEndpointTools as endpoint (endpoint.name)} - <Popover notClickable> - {#snippet text()} - <div class="flex flex-col gap-1"> - <div class="text-xs">{endpoint.description}</div> - <div class="text-xs"> - {endpoint.method} - {endpoint.path} + {#if !runnablesOnly} + <span class="block text-xs mt-2">API endpoint tools that will be available via MCP</span> + <div class="flex flex-wrap gap-1"> + {#each exposedEndpointTools as endpoint (endpoint.name)} + <Popover notClickable> + {#snippet text()} + <div class="flex flex-col gap-1"> + <div class="text-xs">{endpoint.description}</div> + <div class="text-xs"> + {endpoint.method} + {endpoint.path} + </div> </div> - </div> - {/snippet} - <Badge rounded small color="green">{endpoint.name}</Badge> - </Popover> - {/each} - </div> + {/snippet} + <Badge rounded small color="green">{endpoint.name}</Badge> + </Popover> + {/each} + </div> + {/if} </div> {/if} {/if} diff --git a/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte b/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte index bafbf4b7b4..3d721d6882 100644 --- a/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte +++ b/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte @@ -1,10 +1,5 @@ <script lang="ts"> - import { - McpOauthService, - OauthService, - ResourceService, - type DiscoverMcpOauthResponse - } from '$lib/gen' + import { McpOauthService, ResourceService, type DiscoverMcpOauthResponse } from '$lib/gen' import { Button } from '$lib/components/common' import Label from '$lib/components/Label.svelte' import { sendUserToast } from '$lib/toast' @@ -136,27 +131,21 @@ if (!target) return const { workspace, path } = target try { - let accountId: number | undefined - if (data.expires_in && data.refresh_token) { - const accountIdStr = await OauthService.createAccount({ - workspace, - requestBody: { - refresh_token: data.refresh_token, - expires_in: data.expires_in, - client: 'mcp', - mcp_server_url: data.mcp_server_url - } - }) - accountId = Number(accountIdStr) - } - await upsertSecretVariable({ workspace, path, value: data.access_token, resourcePath: path, isOauth: true, - account: accountId + account: + data.expires_in && data.refresh_token + ? { + refresh_token: data.refresh_token, + expires_in: data.expires_in, + client: 'mcp', + mcp_server_url: data.mcp_server_url + } + : undefined }) await ResourceService.createResource({ diff --git a/frontend/src/lib/components/mcp/secretVariable.test.ts b/frontend/src/lib/components/mcp/secretVariable.test.ts index ced0f8e611..60e01ba7b8 100644 --- a/frontend/src/lib/components/mcp/secretVariable.test.ts +++ b/frontend/src/lib/components/mcp/secretVariable.test.ts @@ -71,7 +71,7 @@ describe('upsertSecretVariable', () => { existsVariable.mockResolvedValue(true) getVariable.mockResolvedValue({ description: OURS }) - await upsertSecretVariable({ ...ARGS, isOauth: true, account: 7 }) + await upsertSecretVariable({ ...ARGS, isOauth: true }) expect(deleteVariable).toHaveBeenCalled() expect(createVariable).toHaveBeenCalledWith({ @@ -81,7 +81,6 @@ describe('upsertSecretVariable', () => { value: 'token', is_secret: true, is_oauth: true, - account: 7, description: OURS } }) diff --git a/frontend/src/lib/components/mcp/secretVariable.ts b/frontend/src/lib/components/mcp/secretVariable.ts index e84a5ac641..4240983afc 100644 --- a/frontend/src/lib/components/mcp/secretVariable.ts +++ b/frontend/src/lib/components/mcp/secretVariable.ts @@ -1,4 +1,4 @@ -import { ResourceService, VariableService } from '$lib/gen' +import { OauthService, ResourceService, VariableService } from '$lib/gen' /** * What this connection writes in its token variable's description, and the only @@ -33,7 +33,14 @@ export async function upsertSecretVariable(args: { /** The MCP resource this token belongs to; stamped into the description. */ resourcePath: string isOauth?: boolean - account?: number + /** The account an expiring token refreshes through, created with the variable and linked to it. */ + account?: { + refresh_token: string + expires_in: number + client: string + scopes?: string[] + mcp_server_url?: string + } }): Promise<void> { const { workspace, path, value, resourcePath, isOauth, account } = args const description = mcpTokenDescription(resourcePath) @@ -64,8 +71,10 @@ export async function upsertSecretVariable(args: { await VariableService.deleteVariable({ workspace, path }) } - await VariableService.createVariable({ - workspace, - requestBody: { path, value, is_secret: true, is_oauth: isOauth, account, description } - }) + const variable = { path, value, is_secret: true, is_oauth: isOauth, description } + if (account) { + await OauthService.createAccount({ workspace, requestBody: { ...account, variable } }) + } else { + await VariableService.createVariable({ workspace, requestBody: variable }) + } } diff --git a/frontend/src/lib/components/operatingWorkspace.svelte.ts b/frontend/src/lib/components/operatingWorkspace.svelte.ts index 70f1c63c1c..f25fa1415a 100644 --- a/frontend/src/lib/components/operatingWorkspace.svelte.ts +++ b/frontend/src/lib/components/operatingWorkspace.svelte.ts @@ -22,6 +22,24 @@ export function setOperatingWorkspace(resolve: () => string | undefined): void { setContext(KEY, outer ? () => resolve() ?? outer() : resolve) } +const READ_ONLY_KEY = Symbol('readOnlyWorkspace') + +/** Declare which workspaces this subtree may not change: a session in Use mode. `useEditRights` + * refuses every check there, so each control gated on it, the operator gates included, follows. + * Reads context: call during component initialisation. */ +export function setReadOnlyWorkspace(isReadOnly: (workspace: string | undefined) => boolean): void { + setContext(READ_ONLY_KEY, isReadOnly) +} + +/** Whether this subtree may not change `workspace`. Reads context: call during component + * initialisation. */ +export function useReadOnlyWorkspace(): (workspace: string | undefined) => boolean { + return ( + getContext<((workspace: string | undefined) => boolean) | undefined>(READ_ONLY_KEY) ?? + (() => false) + ) +} + /** This subtree's operating workspace as an entry for a `ContextBridge` contexts map. A snippet * handed to the page header's band renders outside the subtree that declared the workspace, so * without this it would quietly act on the navigation workspace instead. Reads context: call diff --git a/frontend/src/lib/components/pageHeaderRegistry.svelte.ts b/frontend/src/lib/components/pageHeaderRegistry.svelte.ts index 91f092e88d..4fc47ef101 100644 --- a/frontend/src/lib/components/pageHeaderRegistry.svelte.ts +++ b/frontend/src/lib/components/pageHeaderRegistry.svelte.ts @@ -1,5 +1,6 @@ import type { Snippet } from 'svelte' import type { WorkspaceItemKind } from './workspacePicker' +import type { OpenInSessionSource } from './sessions/OpenInSessionButton.svelte' /** An item the page is working on: the breadcrumb walks its path and ends with its summary. */ export type PageHeaderItem = { @@ -41,6 +42,10 @@ export type PageHeaderContent = { section?: PageHeaderSection /** Rendered at the right end of the bar — the page's own buttons. */ actions?: Snippet + /** What the "Open in AI session" button in `actions` takes this page to. The page draws that + * button itself, right before its main action (Deploy, Edit), since only the page knows which + * that is; naming it here lets in-page buttons to the same destination stand down. */ + sessionSource?: OpenInSessionSource /** Orders these buttons among the other registrations', ascending; registration order breaks a * tie. For a menu that must stay at the far end however many pages register before it. */ actionsOrder?: number @@ -199,6 +204,14 @@ export const pageHeader = { }) .sort((a, b) => a.order - b.order || a.i - b.i) }, + /** The innermost registration's session source: the hand-off the header offers. */ + get sessionSource(): OpenInSessionSource | undefined { + for (let i = entries.length - 1; i >= 0; i--) { + const c = read(entries[i]) + if (c?.sessionSource) return c.sessionSource + } + return undefined + }, /** Width of the bar in px, or 0 before it has been measured. */ get barWidth(): number { return barWidth diff --git a/frontend/src/lib/components/pageHeaderRegistry.test.ts b/frontend/src/lib/components/pageHeaderRegistry.test.ts index 035eabb60e..74cbb27d5d 100644 --- a/frontend/src/lib/components/pageHeaderRegistry.test.ts +++ b/frontend/src/lib/components/pageHeaderRegistry.test.ts @@ -52,4 +52,20 @@ describe('pageHeader', () => { register({ actions: snippet('nested') }) expect(pageHeader.actions.map((a) => a.contexts)).toEqual([pageContexts, undefined]) }) + + // In-page buttons stand down when the header offers the same hand-off, so which registration + // is read decides which of them disappear; a nested registration that names no source must not + // hide the page's. + it('takes the session source of the innermost registration that has one', () => { + const route = { page: () => '/runs' } + const editor = { target: { kind: 'script' as const, path: 'u/admin/s' } } + register({ sessionSource: route }) + register({ sessionSource: editor }) + register({ section: { label: 'Nested' } }) + expect(pageHeader.sessionSource).toBe(editor) + pageHeader.release(ids.splice(1, 1)[0]) + expect(pageHeader.sessionSource).toBe(route) + pageHeader.release(ids.shift()!) + expect(pageHeader.sessionSource).toBeUndefined() + }) }) diff --git a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte b/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte index 33a6617ace..721b3b4bfe 100644 --- a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte +++ b/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte @@ -7,6 +7,7 @@ x, y, label, + inNewSession = false, onSend, onClose }: { @@ -15,11 +16,15 @@ y: number /** Short element label shown as the placeholder hint (e.g. "button.btn"). */ label: string - onSend: (prompt: string) => void + /** Sending leaves this page for a new AI session, so the hint says so. */ + inNewSession?: boolean + /** Resolving to `false` keeps the box open with its text. */ + onSend: (prompt: string) => void | Promise<boolean | void> onClose: () => void } = $props() let value = $state('') + let sending = $state(false) let textarea = $state<HTMLTextAreaElement | undefined>(undefined) // Focus when the anchor first appears (the element was just selected). @@ -27,16 +32,20 @@ textarea?.focus() }) - function submit() { + async function submit() { const v = value.trim() - if (!v) return - onSend(v) - value = '' + if (!v || sending) return + sending = true + try { + if ((await onSend(v)) !== false) value = '' + } finally { + sending = false + } } </script> <!-- Floating mini-composer anchored to the selected element in the preview. Sends - the prompt to the session chat with that element as context. --> + the prompt to the session chat (or a new session) with that element as context. --> <!-- The whole pill is the field: the border/focus-ring lives on this box and the send arrow sits inside it, centered against a single-line input. --> <div @@ -50,7 +59,7 @@ bind:value use:autosize={{ maxHeight: '120px', minHeight: 20 }} rows={1} - placeholder={`Ask about ${label}…`} + placeholder={inNewSession ? 'Ask in a new AI session…' : `Ask about ${label}…`} class="min-w-0 flex-1 resize-none !border-0 !bg-transparent !shadow-none px-1.5 !pt-[5px] !pb-[3px] text-xs leading-tight !ring-0 focus:!border-0 focus:!ring-0 focus:outline-none" onkeydown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { @@ -67,7 +76,7 @@ variant="accent" iconOnly startIcon={{ icon: ArrowUp }} - disabled={value.trim().length === 0} + disabled={sending || value.trim().length === 0} on:click={submit} title="Send" /> diff --git a/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte b/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte index 487da15f1f..19281fc9e8 100644 --- a/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import { onDestroy } from 'svelte' import { executeRunnable } from '../apps/components/helpers/executeRunnable' import { userStore } from '$lib/stores' import { waitJob } from '../waitJob' @@ -54,6 +55,9 @@ // Job ids launched by this app instance — see `gateJobIds`. const launchedJobs = new Set<string>() + // A stream resumed on every server timeout would otherwise outlive the app it answers. + let destroyed = false + onDestroy(() => (destroyed = true)) /** For a host that loads this component after the bundle may already have sent requests. */ export function handleMessage(event: MessageEvent) { @@ -124,48 +128,64 @@ args[key] = `$ctx:${field.ctx}` } } - const uuid = await executeRunnable( - runnable, - workspace, - undefined, - $userStore?.username, - path, - runnable_id, - { - component: runnable_id, - args, - force_viewer_allow_user_resources: editor - ? undefinedIfEmpty( - Object.keys(runnable?.fields ?? {}).filter( - (k) => - runnable?.fields?.[k]?.type == 'user' && - runnable?.fields?.[k]?.allowUserResources + let uuid: string + try { + uuid = await executeRunnable( + runnable, + workspace, + undefined, + $userStore?.username, + path, + runnable_id, + { + component: runnable_id, + args, + force_viewer_allow_user_resources: editor + ? undefinedIfEmpty( + Object.keys(runnable?.fields ?? {}).filter( + (k) => + runnable?.fields?.[k]?.type == 'user' && + runnable?.fields?.[k]?.allowUserResources + ) ) - ) - : undefined, - force_viewer_one_of_fields: undefined, - force_viewer_static_fields: editor - ? Object.fromEntries( - Object.entries(runnable?.fields ?? {}) - .filter(([k, v]) => v.type == 'static') - .map(([k, v]) => [k, v?.['value']]) - ) - : undefined, - force_viewer_sensitive_inputs: editor - ? undefinedIfEmpty( - Object.keys(runnable?.fields ?? {}).filter( - (k) => runnable?.fields?.[k]?.type == 'user' && runnable?.fields?.[k]?.sensitive + : undefined, + force_viewer_one_of_fields: undefined, + force_viewer_static_fields: editor + ? Object.fromEntries( + Object.entries(runnable?.fields ?? {}) + .filter(([k, v]) => v.type == 'static') + .map(([k, v]) => [k, v?.['value']]) ) - ) - : undefined, - force_viewer_delete_after_secs: editor ? runnable?.delete_after_secs : undefined, - on_behalf_of: editor ? previewOnBehalfOf : undefined, - viewer_data_access: editor ? runnable?.viewer_data_access || undefined : undefined - }, - undefined, - undefined, - editor ? rawAppPreviewModules(runnables, runnable_id) : undefined - ) + : undefined, + force_viewer_sensitive_inputs: editor + ? undefinedIfEmpty( + Object.keys(runnable?.fields ?? {}).filter( + (k) => + runnable?.fields?.[k]?.type == 'user' && runnable?.fields?.[k]?.sensitive + ) + ) + : undefined, + force_viewer_delete_after_secs: editor ? runnable?.delete_after_secs : undefined, + on_behalf_of: editor ? previewOnBehalfOf : undefined, + viewer_data_access: editor ? runnable?.viewer_data_access || undefined : undefined + }, + undefined, + undefined, + editor ? rawAppPreviewModules(runnables, runnable_id) : undefined + ) + } catch (e) { + // A run refused before it started still answers the app, which would otherwise + // wait for ever; the refusal's body says why (a 409 names the turn still running). + const body = (e as { body?: unknown })?.body + const message = + typeof body === 'string' + ? body + : body + ? JSON.stringify(body) + : String((e as Error)?.message ?? e) + respond({ result: { message }, error: true }) + return + } launchedJobs.add(uuid) let job: JobById = { component: runnable_id, created_at: Date.now(), job: uuid } if (data.type == 'backendAsync') { @@ -209,97 +229,105 @@ ) return } - const params = new URLSearchParams() - params.set('fast', 'true') - params.set('only_result', 'true') + let lastOffset: number | undefined + const connect = (streamOffset?: number) => { + const params = new URLSearchParams() + params.set('fast', 'true') + params.set('only_result', 'true') + if (streamOffset !== undefined) params.set('stream_offset', String(streamOffset)) - const sseUrl = `/api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?${params.toString()}` - const eventSource = new EventSource(sseUrl) + const sseUrl = `/api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?${params.toString()}` + const eventSource = new EventSource(sseUrl) - eventSource.onmessage = (sseEvent) => { - try { - const update = JSON.parse(sseEvent.data) - const type = update.type + eventSource.onmessage = (sseEvent) => { + try { + const update = JSON.parse(sseEvent.data) + const type = update.type - if (type === 'ping' || type === 'timeout') { - if (type === 'timeout') { - eventSource.close() + if (type === 'ping' || type === 'timeout') { + if (type === 'timeout') { + // The server ends every stream after a while; the job goes on, so it is resumed. + eventSource.close() + if (!destroyed) connect(lastOffset) + } + return } - return - } - if (type === 'error') { - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: true, - result: { message: update.error || 'SSE error' } - }, - '*' - ) - return - } + if (type === 'error') { + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: true, + result: { message: update.error || 'SSE error' } + }, + '*' + ) + return + } - if (type === 'not_found') { - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: true, - result: { message: 'Job not found' } - }, - '*' - ) - return - } + if (type === 'not_found') { + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: true, + result: { message: 'Job not found' } + }, + '*' + ) + return + } - // Send stream update if there's new stream data - if (update.new_result_stream !== undefined) { - sourceWindow?.postMessage( - { - type: 'streamJobUpdate', - reqId, - new_result_stream: update.new_result_stream, - stream_offset: update.stream_offset - }, - '*' - ) - } + // Send stream update if there's new stream data + if (update.stream_offset !== undefined) lastOffset = update.stream_offset + if (update.new_result_stream !== undefined) { + sourceWindow?.postMessage( + { + type: 'streamJobUpdate', + reqId, + new_result_stream: update.new_result_stream, + stream_offset: update.stream_offset + }, + '*' + ) + } - // Check if job is completed - if (update.completed) { - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: false, - result: update.only_result - }, - '*' - ) + // Check if job is completed + if (update.completed) { + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: false, + result: update.only_result + }, + '*' + ) + } + } catch (parseErr) { + console.warn('Failed to parse SSE data:', parseErr) } - } catch (parseErr) { - console.warn('Failed to parse SSE data:', parseErr) + } + + eventSource.onerror = (error) => { + console.warn('SSE stream error:', error) + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: true, + result: { message: 'SSE connection error' } + }, + '*' + ) } } - - eventSource.onerror = (error) => { - console.warn('SSE stream error:', error) - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: true, - result: { message: 'SSE connection error' } - }, - '*' - ) - } + connect() } } </script> diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 2006aef442..55b211ecdd 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -40,7 +40,7 @@ import { getAppliedDarkModeVariant, type DarkModeVariant } from '$lib/darkModeVariant' import RawAppSidebar from './RawAppSidebar.svelte' import type { Modules } from './RawAppModules.svelte' - import { isRunnableByName, isRunnableByPath } from '../apps/inputType' + import { isRunnableByName, isRunnableByPath, type PathRunType } from '../apps/inputType' import { aiChatManager, AIMode } from '../copilot/chat/AIChatManager.svelte' import { onMount, onDestroy, untrack } from 'svelte' import type { @@ -48,10 +48,15 @@ LintResult, InspectorElementInfo } from '../copilot/chat/app/core' - import { createAppSelectedContext, type AppCodeSelectionElement } from '../copilot/chat/context' + import { + createAppDomSelectorElement, + createAppSelectedContext, + type AppCodeSelectionElement + } from '../copilot/chat/context' import { captureScale, MAX_IMAGE_EDGE } from '../copilot/chat/imageUtils' import { rawAppLintStore } from './lintStore' import { dbSchemas, userStore } from '$lib/stores' + import { copilotInfo } from '$lib/aiStore' import { useActingUser } from '$lib/actingUser.svelte' import { appPreviewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' import RawAppSdkConsent from './RawAppSdkConsent.svelte' @@ -77,6 +82,8 @@ import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { UserDraft } from '$lib/userDraft.svelte' import { setOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext' + import { prefersSessionHandoff } from '$lib/components/copilot/chat/global/gate' + import { openSourceInSession } from '$lib/components/sessions/sessionSwitch.svelte' import { buildDataTableWhitelist, parseDataTableRef, @@ -90,11 +97,11 @@ import { randomSecret, randomUUID } from '$lib/utils/uuid' import { editorFontSize } from '$lib/editorFontSize.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { conformBuilderAppPolicy } from './builderAppPolicy' const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderApps = useOperatorBuilderApps() + const roleCaps = useRoleCapabilities() interface Props { files?: Record<string, string> @@ -156,12 +163,18 @@ * still toggle the mode after mount; this prop only seeds the * initial state. */ defaultSplitWithPreview?: boolean + /** Open on the preview alone, with the file sidebar and the build logs retracted, + * whatever the width, as a narrow container does. The saved sidebar preference is + * left as it is. */ + compact?: boolean /** User-typed path when it differs from `savedApp.path`. The route injects * it as `draft_path` so the home row shows the friendly name, not `draft_{uuid}`. */ pendingDraftPath?: string | undefined // Threaded to the AutosaveIndicator's "Reset to deployed" button. /** `Exit & see details`: see RawAppEditorHeader. */ onDetails?: (e: { path: string }) => void + /** See RawAppEditorHeader. */ + onOpenFork?: (path: string) => void onResetToDeployed?: () => void | Promise<void> /** The app_version the draft forked from, for the deploy-time "new version * deployed" guard: deploying is refused with a confirmation while it is not @@ -230,8 +243,10 @@ autosaveWorkspace = undefined, autosavePath = undefined, defaultSplitWithPreview = true, + compact = false, pendingDraftPath = $bindable(undefined), onDetails, + onOpenFork, onResetToDeployed, loadedFromDraft = false, othersDraftsCount = 0, @@ -423,7 +438,7 @@ // The deploy panel cannot switch Viewer mode off, nor drop the identity an app another user // deployed carries, so the editor conforms the policy as soon as it opens. $effect(() => { - if ($operatorBuilderApps && policy) conformBuilderAppPolicy(policy, $userStore) + if ($roleCaps.apps === 'compose' && policy) conformBuilderAppPolicy(policy, $userStore) }) // An app with sandbox isolation previews the way it runs once deployed: in the // served, opaque-origin shell, framed with the deployed wrapper's flags. The nonce @@ -473,6 +488,12 @@ addEventListener('message', function (e) { } let previewIframe: HTMLIFrameElement | undefined = $state(undefined) let previewIframeLoaded = $state(false) + // The shell answers every build with `inspectorClear`, and the UI Builder + // rebuilds unchanged code (twice on load). Only a changed build can move what a + // chip points at, so the clears of the others are skipped: they would drop a + // chip handed in from the editor before it is sent. + let previewShellBuild: { css: string; js: string } | undefined = undefined + let previewClearsToSkip = 0 // Sandboxed only: the handshake's port, the one channel to the preview that // can't reach a document app code navigated the frame to. let previewPort: MessagePort | undefined = undefined @@ -538,7 +559,9 @@ addEventListener('message', function (e) { call: "createRoot(document.getElementById('root')!).render(<App />)" } }) - let logsCollapsed = $state(false) + // Folded when the editor opens on the preview alone, where the log matters only on a + // failed build (the Preview tab turns red then); shown beside the code in split view. + let logsCollapsed = $state(untrack(() => !defaultSplitWithPreview || compact)) let logsDiv: HTMLDivElement | undefined = $state(undefined) $effect(() => { if (logsDiv && logs && !logsCollapsed) { @@ -566,7 +589,7 @@ addEventListener('message', function (e) { let activeTabId: string = $state(PREVIEW_TAB_ID) // Seed from the prop, then own the state locally so the user's toggle // after mount sticks even if the prop reference changes. - let splitWithPreview: boolean = $state(untrack(() => defaultSplitWithPreview)) + let splitWithPreview: boolean = $state(untrack(() => defaultSplitWithPreview && !compact)) const activeTabKind = $derived<'file' | 'runnable' | 'preview'>( activeTabId === PREVIEW_TAB_ID ? 'preview' @@ -840,7 +863,7 @@ addEventListener('message', function (e) { const w = rootWidth if (appliedNarrowDefault || w <= 0) return appliedNarrowDefault = true - if (w < NARROW_PX) { + if (compact || w < NARROW_PX) { splitWithPreview = false sidebarCollapsed.setWithoutPersist(true) } @@ -910,6 +933,8 @@ addEventListener('message', function (e) { backendRunnable.type = 'flow' } else if (runnable.runType === 'hubscript') { backendRunnable.type = 'hubscript' + } else if (runnable.runType === 'agent') { + backendRunnable.type = 'agent' } else { backendRunnable.type = 'script' } @@ -1223,7 +1248,7 @@ addEventListener('message', function (e) { runnables[key] = { name: runnable.name, type: 'path', - runType: runnable.type as 'script' | 'flow' | 'hubscript', + runType: runnable.type as PathRunType, path: runnable.path, fields: runnable.staticInputs ? Object.fromEntries( @@ -1535,7 +1560,7 @@ addEventListener('message', function (e) { // Escape inside the preview exits inspect mode, and also dismisses a lingering // green "selected" overlay after a pick (which auto-disables hover). if (fromPreview && e.data.type === 'previewEscape') { - if (inspectorEnabled || inspectorElement || selectedDomSelectors.length > 0) { + if (inspectorEnabled || inspectorElement || previewSelectors.length > 0) { disableInspector() } return @@ -1572,15 +1597,28 @@ addEventListener('message', function (e) { // picking (the chip list, not the harness, holds the selection). Shift // held → add to the selection; a plain click replaces it. if (onInspectorSelect) onInspectorSelect(inspectorElement, !!e.data.additive) - else inspectorEnabled = false + else { + inspectorEnabled = false + // The preview keeps picking until told to stop. + postToPreview({ type: 'inspectorDisable' }) + } return } if (fromPreview && e.data.type === 'inspectorDeselect') { // User clicked × on a selected overlay in the preview — drop that chip. if (typeof e.data.selector === 'string') onInspectorDeselect?.(e.data.selector) + if (!onInspectorSelect && e.data.selector === inspectorElement?.path) { + inspectorElement = undefined + } return } if (fromPreview && e.data.type === 'inspectorClear') { + if (previewClearsToSkip > 0) { + previewClearsToSkip-- + // The shell dropped its outlines along with the old DOM. + postToPreview({ type: 'inspectorSetSelection', selectors: [...previewSelectors] }) + return + } inspectorElement = undefined // A rebuild invalidates the selection — clear all session chips. onInspectorClearAll?.() @@ -1842,6 +1880,13 @@ addEventListener('message', function (e) { if (previewSdkPending || previewUserPending || !previewIframeLoaded) return runtimeError = undefined emptyRender = false + if ( + !previewShellBuild || + (previewShellBuild.css === build.css && previewShellBuild.js === build.js) + ) { + previewClearsToSkip++ + } + previewShellBuild = build postToPreview({ type: 'preview', css: build.css, @@ -1854,7 +1899,7 @@ addEventListener('message', function (e) { // The deployed app's `window.ctx`: the viewer's membership in the app's workspace. function previewCtx() { - return $state.snapshot({ ctx: operatingUser.current, workspace: opWorkspace }) + return $state.snapshot({ ctx: operatingUser.current, workspace: opWorkspace, path }) } // A build fed before the viewer is known keeps that viewer until the next one. Outside @@ -2097,19 +2142,56 @@ addEventListener('message', function (e) { return { text } } - // ---- Inline "prompt this element" mini-composer (session preview only) ---- + // What the preview outlines as selected: the session's chips when a session + // drives the inspector, else this editor's single pick. + const previewSelectors = $derived.by(() => + onInspectorSelect ? selectedDomSelectors : inspectorElement ? [inspectorElement.path] : [] + ) + + // ---- Inline "prompt this element" mini-composer ---- // Anchored over the most-recently selected element in the live preview. It's a // host overlay (position: fixed in the top document) computed from the element's // rect inside the preview iframe, repositioned as the preview scrolls. let inlinePromptDismissed = $state(false) let inlinePromptPos = $state<{ x: number; y: number } | undefined>(undefined) let inlinePromptLabel = $state('') + // Outside a session, with sessions on, there is no docked chat to take the pick: + // the prompt opens a new session instead, carrying the element as its chip. + const inlinePrompt: ((selector: string, prompt: string) => void | Promise<boolean>) | undefined = + $derived( + onInlinePrompt ?? + (!onInspectorSelect && sessionOpen && prefersSessionHandoff(!$roleCaps.code) + ? sendPickToNewSession + : undefined) + ) const inlinePromptSelector = $derived( - onInlinePrompt && selectedDomSelectors.length > 0 - ? selectedDomSelectors[selectedDomSelectors.length - 1] + inlinePrompt && previewSelectors.length > 0 + ? previewSelectors[previewSelectors.length - 1] : undefined ) + async function sendPickToNewSession(selector: string, prompt: string) { + const el = inspectorElement + if (!sessionOpen || !el) return false + try { + await openSourceInSession(sessionOpen, { + seedPrompt: prompt, + autoSend: true, + seedDomElement: createAppDomSelectorElement({ + selector, + appPath: sessionOpen.target.path, + tagName: el.tagName, + id: el.id, + className: el.className + }) + }) + return true + } catch (e) { + sendUserToast(e instanceof Error ? e.message : String(e), true) + return false + } + } + function shortElementLabel(el: { tagName: string; id: string; className: string }): string { const tag = el.tagName.toLowerCase() const id = el.id ? `#${el.id}` : '' @@ -2172,7 +2254,7 @@ addEventListener('message', function (e) { // overlay pinned as the host scrolls/resizes. The preview's own scrolls arrive // as `previewScroll` messages. inlinePromptSelector - selectedDomSelectors + previewSelectors previewIframeLoaded inlinePromptDismissed updateInlinePromptPos() @@ -2290,6 +2372,8 @@ addEventListener('message', function (e) { }) function onPreviewShellReady() { previewIframeLoaded = true + previewShellBuild = undefined + previewClearsToSkip = 0 // Replay the last build so the preview repopulates without // waiting for the user to trigger another bundle. if (lastBuild) { @@ -2333,7 +2417,7 @@ addEventListener('message', function (e) { // Push the chat's DOM-selector chips into the preview (source of truth): // the harness renders one highlight per selector. Re-posts on every // selection change and on preview (re)load. - const selectors = selectedDomSelectors + const selectors = previewSelectors if (previewIframeLoaded) { postToPreview({ type: 'inspectorSetSelection', selectors: [...selectors] }) } @@ -2482,7 +2566,7 @@ addEventListener('message', function (e) { // selection (highlights + the inline prompt), so a chip-only selection // (picking already toggled off) must still be dismissable. Bail only // when there is genuinely nothing to dismiss. - if (!inspectorEnabled && !inspectorElement && selectedDomSelectors.length === 0) return + if (!inspectorEnabled && !inspectorElement && previewSelectors.length === 0) return inspectorEnabled = false // `inspectorDisable` only stops hover/click; the green "selected" // overlay from a prior pick persists until we explicitly clear it. @@ -2505,7 +2589,7 @@ addEventListener('message', function (e) { const onEscapeCapture = (e: KeyboardEvent) => { if ( e.key === 'Escape' && - (inspectorEnabled || inspectorElement || selectedDomSelectors.length > 0) + (inspectorEnabled || inspectorElement || previewSelectors.length > 0) ) { disableInspector() e.stopImmediatePropagation() @@ -2645,6 +2729,7 @@ addEventListener('message', function (e) { {onNavigate} {onDeploy} {onDetails} + {onOpenFork} {onResetToDeployed} {loadedFromDraft} {othersDraftsCount} @@ -2864,28 +2949,30 @@ addEventListener('message', function (e) { {bundlerType} </Button> {/if} - <Button - variant="subtle" - unifiedSize="sm" - iconOnly - startIcon={{ icon: MousePointerSquareDashed }} - selected={inspectorEnabled} - title={inspectorEnabled - ? 'Click to disable element inspector' - : 'Click to enable element inspector'} - aria-label="Toggle element inspector" - aria-pressed={inspectorEnabled} - onClick={() => { - if (inspectorEnabled) { - // Turning off is a full exit: stop picking and clear the - // selection + inline prompt (mirrors Escape). - disableInspector() - } else { - inspectorEnabled = true - postToPreview({ type: 'inspectorEnable' }) - } - }} - /> + {#if !$copilotInfo.workspaceDisabled} + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + startIcon={{ icon: MousePointerSquareDashed }} + selected={inspectorEnabled} + title={inspectorEnabled + ? 'Click to disable element inspector' + : 'Click to enable element inspector'} + aria-label="Toggle element inspector" + aria-pressed={inspectorEnabled} + onClick={() => { + if (inspectorEnabled) { + // Turning off is a full exit: stop picking and clear the + // selection + inline prompt (mirrors Escape). + disableInspector() + } else { + inspectorEnabled = true + postToPreview({ type: 'inspectorEnable' }) + } + }} + /> + {/if} <Button variant="subtle" unifiedSize="sm" @@ -3045,7 +3132,7 @@ addEventListener('message', function (e) { </div> </div> -{#if inlinePromptPos && inlinePromptSelector && onInlinePrompt} +{#if inlinePromptPos && inlinePromptSelector && inlinePrompt} <!-- Key on the selector so selecting a different element remounts the input (fresh value + autofocus); repositioning on scroll keeps the same key so it never steals focus mid-scroll. --> @@ -3054,8 +3141,9 @@ addEventListener('message', function (e) { x={inlinePromptPos.x} y={inlinePromptPos.y} label={inlinePromptLabel} - onSend={(prompt) => { - onInlinePrompt?.(inlinePromptSelector!, prompt) + inNewSession={!onInlinePrompt} + onSend={async (prompt) => { + if ((await inlinePrompt?.(inlinePromptSelector!, prompt)) === false) return false inlinePromptDismissed = true }} onClose={() => (inlinePromptDismissed = true)} diff --git a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte index b7ce8d7684..a03d5512ca 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte @@ -51,6 +51,7 @@ import AppEditorHeaderDeploy from '../apps/editor/AppEditorHeaderDeploy.svelte' import type { Runnable } from './RawAppInlineScriptRunnable.svelte' import { updateRawAppPolicy } from './rawAppPolicy' + import { saveRawAppFork } from './forkRawApp.svelte' import { aiChatManager } from '../copilot/chat/AIChatManager.svelte' import { getContext } from 'svelte' @@ -188,6 +189,9 @@ /** `Exit & see details`: leaves the editor for the app's deployed page. A session hosts that * page itself, so it flips the tab there rather than navigating out of the session. */ onDetails?: (e: { path: string }) => void + /** Opens the draft `Fork` saved. Without it, the fork opens in a new browser tab; a + * session opens it as one of its own tabs instead. */ + onOpenFork?: (path: string) => void onResetToDeployed?: () => void | Promise<void> // See ScriptBuilderProps — same semantics for the raw-app editor's // indicator. @@ -239,6 +243,7 @@ onDeploy = undefined, pendingDraftPath = $bindable(undefined), onDetails, + onOpenFork, onResetToDeployed, loadedFromDraft = false, othersDraftsCount = 0, @@ -257,6 +262,21 @@ const opWorkspace = $derived(autosaveWorkspace ?? $operatingWorkspace) const indicatorPath = $derived(autosavePath ?? liveEditorDraftStoragePath) + async function forkApp() { + if (!opWorkspace || !files) return + const workspace = opWorkspace + // Opened before the save: a tab opened after an await is no longer tied to the + // click, and browsers block it as a popup. + const tab = onOpenFork ? undefined : window.open('', '_blank') + const forkPath = await saveRawAppFork(workspace, { files, runnables, data, policy }) + if (!forkPath) { + tab?.close() + return + } + if (onOpenFork) onOpenFork(forkPath) + else if (tab) tab.location.href = `/apps_raw/edit/${forkPath}?workspace=${workspace}` + } + $effect(() => { const typed = newEditedPath const baseline = savedApp?.path ?? '' @@ -323,10 +343,19 @@ const compactTopbar = $derived( ownsPageHeader ? pageHeader.actionFold >= 1 : topbarWidth > 0 && topbarWidth < 720 ) - // The second fold keeps the trail, the file sidebar's toggle, Diff and Deploy. AI stands down — - // the sidebar's own Ask AI is the way in at that width — while Jobs and the export are already - // in the menu, Jobs from `compactTopbar` (true at the second fold too) and the export always. + // In the page header no fold drops a button's label: what does not fit goes into the menu. + // The second fold keeps the trail, the file sidebar's toggle and Deploy; Diff joins the menu. + // The docked-chat AI toggle stands down — the sidebar's own Ask AI is the way in at that + // width — while Jobs and the + // export are already in the menu, Jobs from `compactTopbar` (true at the second fold too) and + // the export always. const phoneTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 2) + // The third fold leaves the autosave indicator as its icon, so the AI session button still fits + // right before Deploy on a phone. + const narrowTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 3) + // The last fold, for the narrowest phones: the file sidebar's toggle joins the menu, which is + // then the way back to a collapsed sidebar. + const sidebarToggleInMenu = $derived(ownsPageHeader && pageHeader.actionFold >= 4) // Top-bar button size + bar height. Condensed (session preview) uses the // smallest well-supported unified size (`sm`) so the bar is thinner. @@ -450,8 +479,7 @@ async function syncWithDeployed(opening?: number) { const deployedApp = await AppService.getAppByPath({ workspace: opWorkspace!, - path: appPath!, - withStarredInfo: true + path: appPath! }) // A superseded opening must not write these: the current one would then render @@ -704,6 +732,26 @@ const mod = isMac() ? '⌘' : 'Ctrl+' let moreItems = $derived([ + ...(sidebarToggleInMenu && onToggleSidebar + ? [ + { + displayName: `${sidebarCollapsed ? 'Expand' : 'Collapse'} file sidebar`, + icon: sidebarCollapsed ? PanelLeft : PanelLeftClose, + action: () => onToggleSidebar?.(), + shortcut: `${mod}B` + } + ] + : []), + ...(phoneTopbar + ? [ + { + displayName: 'Diff', + icon: DiffIcon, + action: () => openDiffDrawer(), + disabled: !savedApp || newApp || savedApp?.no_deployed === true + } + ] + : []), ...(compactTopbar ? [ { @@ -956,7 +1004,8 @@ pathTrigger: rawAppPathTrigger }} actions={rawAppHeaderActions} - actionFolds={2} + sessionSource={sessionOpen} + actionFolds={4} contexts={headerContexts} separator="none" /> @@ -996,7 +1045,7 @@ {/if} {#snippet sidebarToggle()} - {#if onToggleSidebar} + {#if onToggleSidebar && !sidebarToggleInMenu} <Button unifiedSize="sm" variant="subtle" @@ -1019,6 +1068,7 @@ {loadedFromDraft} {othersDraftsCount} {onOpenOthersDrafts} + compact={narrowTopbar} /> {/if} {/snippet} @@ -1075,7 +1125,8 @@ {#snippet rawAppHeaderActions()} <!-- The bar's own order kept: the file sidebar, how the draft is doing, who else is here, then what to do with the app. The sidebar's toggle is the only way back once it is folded — the - collapsed sidebar renders nothing of its own — so it stays on the bar at every width. --> + collapsed sidebar renders nothing of its own — so it stays on the bar until the last fold, + which moves it into the ⋮ menu rather than dropping it. --> {@render sidebarToggle()} {@render autosaveIndicator()} {@render awarenessMark()} @@ -1102,9 +1153,11 @@ title={newApp || savedApp?.no_deployed === true ? 'Deploy this app once to compare against the deployed version' : 'Diff'} - class={!savedApp || newApp || savedApp?.no_deployed === true - ? 'flex cursor-not-allowed' - : 'flex'} + class={phoneTopbar + ? 'hidden' + : !savedApp || newApp || savedApp?.no_deployed === true + ? 'flex cursor-not-allowed' + : 'flex'} > <Button variant="default" @@ -1114,7 +1167,7 @@ btnClasses={!savedApp || newApp || savedApp?.no_deployed === true ? 'pointer-events-none' : undefined} - iconOnly={compactTopbar} + iconOnly={compactTopbar && !ownsPageHeader} title={newApp || savedApp?.no_deployed === true ? 'Deploy this app once to compare against the deployed version' : 'Diff'} @@ -1145,9 +1198,11 @@ <!-- Draws nothing in the bar: it is the export drawer, opened from the menu's Export entry through this instance. --> <AppExportButton bind:this={appExport} /> - {#if !phoneTopbar} - <OpenInSessionButton source={sessionOpen}> - {#snippet fallback()} + <!-- Right before Deploy at every fold; only the opted-out docked-chat toggle gives way on a + phone. --> + <OpenInSessionButton source={sessionOpen}> + {#snippet fallback()} + {#if !phoneTopbar} <Button unifiedSize={headerBtnSize} variant="default" @@ -1158,9 +1213,9 @@ > AI </Button> - {/snippet} - </OpenInSessionButton> - {/if} + {/if} + {/snippet} + </OpenInSessionButton> <Button loading={loading.save} startIcon={{ icon: Save }} @@ -1181,9 +1236,7 @@ ]), { label: 'Fork', - onClick: () => { - window.open(`/apps/add?template=${appPath}`) - } + onClick: forkApp }, ...(!isCloudHosted() && editInForkAllowed(opWorkspace, $userWorkspaces) ? [ diff --git a/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte b/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte index 86b2ea57ed..71a3dae951 100644 --- a/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte @@ -21,7 +21,7 @@ import SchemaForm from '../SchemaForm.svelte' import RunnableJobPanelInner from '../apps/editor/RunnableJobPanelInner.svelte' import JobLoader from '../JobLoader.svelte' - import { FlowService, type Job, type OpenFlow, type ScriptLang } from '$lib/gen' + import { FlowService, JobService, type Job, type OpenFlow, type ScriptLang } from '$lib/gen' import { getScriptByPath } from '$lib/scripts' import { slide } from 'svelte/transition' import { DebugToolbar, DebugPanel, debugState } from '$lib/components/debug' @@ -224,6 +224,22 @@ } else { await jobLoader.runFlowByPath(runnable.path, args) } + } else if (runnable.runType == 'agent') { + // A turn of the agent as it is deployed, as the editor: the direct run has no way + // to ask for the app's identity. + const path = runnable.path + const { user_message, memory_id, user_attachments, previous_messages } = args as Record< + string, + any + > + await jobLoader.abstractRun(() => + JobService.runAgent({ + workspace: opWs!, + path, + memoryId: memory_id || undefined, + requestBody: { user_message, user_attachments, previous_messages } + }) + ) } else if (runnable.runType == 'script' || runnable.runType == 'hubscript') { if (previewOnBehalfOf) { const script = await getScriptByPath(runnable.path, opWs) diff --git a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte index 36c3fb360c..1c82cdcd33 100644 --- a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte @@ -134,7 +134,7 @@ const html = unsandboxedRawAppHtml( workspace, secret, - { ctx: u, workspace }, + { ctx: u, workspace, path }, window.location.origin, pageHash() ) @@ -207,7 +207,7 @@ // Same shape as the unsandboxed wrapper: always the object, so // `window.ctx.workspace` works for anonymous viewers too. Snapshotted: a // caller's `$state` user is a proxy, which postMessage cannot clone. - ctx: { ctx: $state.snapshot(user), workspace }, + ctx: { ctx: $state.snapshot(user), workspace, path }, initialHash, storage: { local: bundleStorage ?? {}, session: {} }, // The wrapper turns this into `window.process.env` before it injects the diff --git a/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte b/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte index e56ef4bff6..e5e25a5ff1 100644 --- a/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte @@ -46,7 +46,7 @@ import RawAppDataTableDrawer from './RawAppDataTableDrawer.svelte' import FileEditorIcon from './FileEditorIcon.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { prefersSessionHandoff } from '$lib/components/copilot/chat/global/gate' export type RawAppTemplatePickerResult = { @@ -68,7 +68,7 @@ } = $props() const templates = $derived.by(() => { - const files = $operatorBuilderApps ? BUILDER_FRAMEWORK_TEMPLATES : FRAMEWORK_TEMPLATES + const files = composeOnlyApps ? BUILDER_FRAMEWORK_TEMPLATES : FRAMEWORK_TEMPLATES return [ { name: 'React 19', icon: 'tsx', files: files.react19, recommended: true }, { name: 'React 18', icon: 'tsx', files: files.react18 }, @@ -87,7 +87,8 @@ let dataTableDrawer: RawAppDataTableDrawer | undefined = $state() const operatingWorkspace = useOperatingWorkspace() - const operatorBuilderApps = useOperatorBuilderApps() + const roleCaps = useRoleCapabilities() + const composeOnlyApps = $derived($roleCaps.apps === 'compose') let opWs = $derived($operatingWorkspace) const datatables = createDatatablesResource(() => opWs) @@ -284,8 +285,7 @@ // With AI turned off for the workspace there is nothing to choose between. A builder is // offered AI only through a session: the docked app mode writes inline code they cannot save. const aiOffered = $derived( - !$copilotInfo.workspaceDisabled && - (!$operatorBuilderApps || prefersSessionHandoff($userStore?.operator)) + !$copilotInfo.workspaceDisabled && (!composeOnlyApps || prefersSessionHandoff(!$roleCaps.code)) ) const canStart = $derived( @@ -301,7 +301,7 @@ execution_mode: 'publisher', sandbox: true } - if ($operatorBuilderApps) conformBuilderAppPolicy(policy, $userStore) + if (composeOnlyApps) conformBuilderAppPolicy(policy, $userStore) return policy } diff --git a/frontend/src/lib/components/raw_apps/agentRunnable.ts b/frontend/src/lib/components/raw_apps/agentRunnable.ts new file mode 100644 index 0000000000..cca1964197 --- /dev/null +++ b/frontend/src/lib/components/raw_apps/agentRunnable.ts @@ -0,0 +1,43 @@ +import type { Schema, SchemaProperty } from '$lib/common' +import { agentMemoryMode, keepsManagedMemory } from '$lib/components/flows/agentFormFields' + +/** + * The inputs of a raw app's agent runnable, after the agent's memory as its own page reads it: a + * chat (`memory_id`, the conversation and memory key) when it keeps managed memory, single runs + * answered from the history the app passes (`previous_messages`) when it is off, and neither for an + * older `manual` setting (`memory_id` is the run's, which an older `auto` one keeps memory under). + * The server accepts both either way (see `execute_component`), so a schema gone stale only + * mistypes the inputs. + */ +export function agentRunnableSchema(memory: unknown): Schema { + const history: Record<string, SchemaProperty> = {} + if (keepsManagedMemory(memory)) { + history.memory_id = { + type: 'string', + description: + 'The conversation the message belongs to: reuse it to continue one, or omit it for a single run' + } + } + if (agentMemoryMode(memory) === 'off') { + history.previous_messages = { + type: 'array', + description: 'The history to answer from, as chat messages: this agent keeps no memory', + items: { type: 'object' } + } + } + return { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties: { + user_message: { type: 'string', description: 'The message to answer' }, + ...history, + user_attachments: { + type: 'array', + description: 'Files the message carries, as object storage references', + items: { type: 'object', resourceType: 's3object' } + } + }, + required: ['user_message'], + order: ['user_message', ...Object.keys(history), 'user_attachments'] + } +} diff --git a/frontend/src/lib/components/raw_apps/forkRawApp.svelte.ts b/frontend/src/lib/components/raw_apps/forkRawApp.svelte.ts new file mode 100644 index 0000000000..ffeab765da --- /dev/null +++ b/frontend/src/lib/components/raw_apps/forkRawApp.svelte.ts @@ -0,0 +1,55 @@ +import { get } from 'svelte/store' +import type { Policy } from '$lib/gen' +import { userStore } from '$lib/stores' +import { sendUserToast } from '$lib/toast' +import { UserDraft } from '$lib/userDraft.svelte' +import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' +import { mintDraftPath } from '$lib/mintDraftPath' +import { userPathPrefix } from '$lib/utils' +import { random_adj } from '$lib/components/random_positive_adjetive' +import type { RawAppDraft } from '$lib/components/sessions/appDraftCodec' +import type { RawAppData } from './dataTableRefUtils' + +/** + * Saves what the editor holds as a new raw-app draft under a fresh path and returns that + * path, or `undefined` when the save failed. The copy is taken from the editor rather than + * reloaded from the server, which would miss edits autosave has not written (or never will, + * with auto-save off). + */ +export async function saveRawAppFork( + workspace: string, + source: { + files: Record<string, string> + runnables: Record<string, any> + data: RawAppData + policy: Policy | undefined + } +): Promise<string | undefined> { + const user = get(userStore) + const forkPath = mintDraftPath() + const draft: RawAppDraft = { + summary: '', + files: $state.snapshot(source.files), + runnables: $state.snapshot(source.runnables), + data: $state.snapshot(source.data), + // The forker's identity, since the source's would publish as its owner, but the + // source's sandbox and SDK scopes: the copied code's SDK calls depend on them. + policy: { + on_behalf_of: user?.username.includes('@') ? user.username : `u/${user?.username}`, + on_behalf_of_email: user?.email, + execution_mode: 'publisher', + sandbox: source.policy?.sandbox ?? false, + frontend_sdk_scopes: $state.snapshot(source.policy?.frontend_sdk_scopes) + }, + // Without it the fork would deploy under its `draft_<uuid>` storage path. + draft_path: `${userPathPrefix(user?.username)}${random_adj()}_app` + } + UserDraft.save('raw_app', forkPath, draft, { workspace }) + await UserDraft.forcePersist('raw_app', forkPath, { workspace }) + const saved = UserDraftDbSyncer.getState({ workspace, itemKind: 'raw_app', path: forkPath }) + if (saved.state === 'failed') { + sendUserToast(`Could not save the fork: ${saved.failureMessage ?? 'unknown error'}`, true) + return undefined + } + return forkPath +} diff --git a/frontend/src/lib/components/resources/ResourcesList.svelte b/frontend/src/lib/components/resources/ResourcesList.svelte index 2b0cc5eb1e..b592d0b86c 100644 --- a/frontend/src/lib/components/resources/ResourcesList.svelte +++ b/frontend/src/lib/components/resources/ResourcesList.svelte @@ -42,7 +42,7 @@ import Tooltip from '$lib/components/Tooltip.svelte' import type { ResourceType, WorkspaceDeployUISettings } from '$lib/gen' import { OauthService, ResourceService, WorkspaceService, type ListableResource } from '$lib/gen' - import { enterpriseLicense, userWorkspaces } from '$lib/stores' + import { enterpriseLicense } from '$lib/stores' import { sendUserToast } from '$lib/toast' import { useEditRights } from '$lib/operatorWriteRights' import { @@ -1027,10 +1027,10 @@ </DrawerContent> </Drawer> -{#if operatingUser.current?.operator && $operatingWorkspace && !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.resources} +{#if $operatingWorkspace && !editRights.capabilities.visibility.resources} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage> @@ -1358,7 +1358,7 @@ </Cell> <Cell last actions> <div class="flex justify-end items-center gap-2"> - {#if path && assetCanBeExplored({ kind: 'resource', path }, { resource_type }) && !operatingUser.current?.operator} + {#if path && assetCanBeExplored({ kind: 'resource', path }, { resource_type }) && editRights.capabilities.code} <ExploreAssetButton asset={{ kind: 'resource', path }} _resourceMetadata={{ resource_type }} diff --git a/frontend/src/lib/components/runs/JobDetailHeader.svelte b/frontend/src/lib/components/runs/JobDetailHeader.svelte index 5783deaf53..1caf43fbfb 100644 --- a/frontend/src/lib/components/runs/JobDetailHeader.svelte +++ b/frontend/src/lib/components/runs/JobDetailHeader.svelte @@ -30,14 +30,11 @@ import { flowPathToHref } from '$lib/scripts' import { slide } from 'svelte/transition' import { twMerge } from 'tailwind-merge' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) + const roleCaps = useRoleCapabilities() interface Props { job: Job @@ -503,7 +500,7 @@ <div class="flex items-baseline flex-wrap gap-x-2 gap-y-1"> <JobStatus {job} /> - {#if isJobResolvable(job) && !actingUser?.operator} + {#if isJobResolvable(job) && $roleCaps.code} <!-- No startIcon on these: the row is baseline-aligned, and a Button is itself a flex container whose baseline comes from its icon rather than its label, which sits the text ~3px above the badges. Text diff --git a/frontend/src/lib/components/runs/RunDetail.svelte b/frontend/src/lib/components/runs/RunDetail.svelte index d372d5d540..7ab0c13d06 100644 --- a/frontend/src/lib/components/runs/RunDetail.svelte +++ b/frontend/src/lib/components/runs/RunDetail.svelte @@ -90,7 +90,9 @@ import ExecutionDuration from '$lib/components/ExecutionDuration.svelte' import { isWindmillTooBigObject } from '$lib/components/job_args' import ScheduleEditor from '$lib/components/triggers/schedules/ScheduleEditor.svelte' - import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte' + import OpenInSessionButton, { + type OpenInSessionSource + } from '$lib/components/sessions/OpenInSessionButton.svelte' import { onDestroy, setContext, untrack } from 'svelte' import { getJobStatusKind, resetFavicon, setStatusFavicon } from '$lib/favicon' @@ -609,7 +611,7 @@ // Offer to resolve this failure once the re-run succeeds. Captured here because the // new job carries no back-pointer to the run it supersedes. An already-resolved // failure needs no offer, and its note must not be restated as a supersession. - if (job && isJobResolvable(job) && !job.resolved && !actingUser?.operator) { + if (job && isJobResolvable(job) && !job.resolved && editRights.capabilities.code) { rememberRerunOrigin({ originalId: job.id, rerunId: id, workspace: workspaceId! }) } await onNavigate('/run/' + id + '?workspace=' + workspaceId) @@ -715,11 +717,10 @@ onDestroy(resetFavicon) } - // The bar folds these (`actionFolds` below) once its breadcrumb has given all it can: first the - // buttons drop their labels, then the plain actions go into one menu. Embedded, the buttons - // have a row of their own that wraps. - const compactBar = $derived(!embedded && pageHeader.actionFold >= 1) - const actionsInMenu = $derived(!embedded && pageHeader.actionFold >= 2) + // The bar folds these (`actionFolds` below) once its breadcrumb has given all it can: the plain + // actions go into one menu rather than losing their labels. Embedded, the buttons have a row + // of their own that wraps. + const actionsInMenu = $derived(!embedded && pageHeader.actionFold >= 1) const isScriptJob = $derived(job?.job_kind === 'script') const isRunnableJob = $derived( @@ -755,12 +756,22 @@ ) const canEdit = $derived( (job?.job_kind === 'script' || job?.job_kind === 'flow') && - !actingUser?.operator && editRights.canEditItem(isScriptJob ? 'script' : 'flow', job?.script_path ?? '', {}) ) + // Opens the deployed runnable at this job's path, like Edit — unlike "View script", which pins + // the hash this run executed. Not gated on edit rights: a session also reads and explains, and + // the server still refuses a deploy the user has no right to. + const sessionOpen: OpenInSessionSource | undefined = $derived( + (job?.job_kind === 'script' || job?.job_kind === 'flow') && job?.script_path + ? { + target: { kind: isScriptJob ? 'script' : 'flow', path: job?.script_path ?? '' }, + workspaceId: workspaceId ?? undefined + } + : undefined + ) const canEditInFork = $derived( (job?.job_kind === 'script' || job?.job_kind === 'flow') && - !actingUser?.operator && + editRights.capabilities.code && !showEditButton && !isCloudHosted() && editInForkAllowed(workspaceId, $userWorkspaces) @@ -1081,7 +1092,8 @@ <PageHeaderContent section={{ label: `run/${runId}` }} actions={runActions} - actionFolds={2} + sessionSource={sessionOpen} + actionFolds={1} {actionsVersion} /> {/if} @@ -1091,15 +1103,6 @@ {#if restartStep !== undefined && canRestart(restart)} {@render flowRestartButton(restart, restartStep, 'button')} {/if} - {#if canEdit && showEditButton} - <OpenInSessionButton - source={{ - target: { kind: isScriptJob ? 'script' : 'flow', path: job?.script_path ?? '' }, - workspaceId: workspaceId ?? undefined - }} - btnProps={{ unifiedSize: 'sm' }} - /> - {/if} <Dropdown items={menuItems} customWidth={260}> {#snippet buttonReplacement()} <Button @@ -1112,6 +1115,7 @@ /> {/snippet} </Dropdown> + <OpenInSessionButton source={sessionOpen} /> {:else} {@render runActionsRow()} {/if} @@ -1139,7 +1143,6 @@ href={runsHref} variant="default" unifiedSize="sm" - iconOnly={compactBar} title="View runs" startIcon={{ icon: List }} > @@ -1174,7 +1177,6 @@ nonCaptureEvent variant="default" unifiedSize="sm" - iconOnly={compactBar} title="Share" startIcon={{ icon: Share2 }} > @@ -1210,7 +1212,6 @@ <Button unifiedSize="sm" variant="default" - iconOnly={compactBar} title={isHubFlowPreview ? 'Fork flow into workspace' : `Fork ${isFlowPreview(job?.job_kind) ? 'flow' : 'code'} preview`} @@ -1226,7 +1227,6 @@ <Button unifiedSize="sm" variant="default" - iconOnly={compactBar} title="Current runs" startIcon={{ icon: Activity }} on:click={() => { @@ -1303,7 +1303,6 @@ on:click={runAgain} unifiedSize="sm" variant="default" - iconOnly={compactBar} title="Run again" startIcon={{ icon: RefreshCw }} loading={runImmediatelyLoading} @@ -1323,7 +1322,7 @@ </Button> {/if} {#if job?.job_kind === 'script' || job?.job_kind === 'flow'} - {#if !actingUser?.operator} + {#if canEdit || canEditInFork} {#if editRights.canEditItem(isScriptJob ? 'script' : 'flow', job?.script_path ?? '', {})} <Button href={`${stem}/edit/${job?.script_path}?workspace=${workspaceId}`} @@ -1333,24 +1332,11 @@ unifiedSize="sm" variant="default" disabled={!showEditButton} - iconOnly={compactBar} title="Edit" startIcon={{ icon: Pen }}>Edit</Button > - {#if showEditButton} - <!-- Opens the deployed runnable at this job's path, like Edit — unlike - "View script", which pins the hash this run executed. Same gate as - Edit: where direct deployment is off, the way in is "Edit in fork". --> - <OpenInSessionButton - source={{ - target: { kind: isScriptJob ? 'script' : 'flow', path: job?.script_path ?? '' }, - workspaceId: workspaceId ?? undefined - }} - btnProps={{ unifiedSize: 'sm' }} - /> - {/if} {/if} - {#if !showEditButton && !isCloudHosted() && editInForkAllowed(workspaceId, $userWorkspaces)} + {#if canEditInFork} <Button href={buildForkEditUrl( isScriptJob ? 'script' : 'flow', @@ -1360,19 +1346,21 @@ onClick={(e) => editInFork(e, isScriptJob ? 'script' : 'flow', job?.script_path ?? '')} unifiedSize="sm" variant="default" - iconOnly={compactBar} title={editInForkLabel(workspaceId, $userWorkspaces)} startIcon={{ icon: Pen }}>{editInForkLabel(workspaceId, $userWorkspaces)}</Button > {/if} {/if} {/if} + <OpenInSessionButton + source={sessionOpen} + btnProps={embedded ? { unifiedSize: 'sm' } : undefined} + /> {#if job?.job_kind === 'script' || job?.job_kind === 'script_hub' || job?.job_kind === 'flow'} <Button href={viewHref} unifiedSize="sm" variant="accent" - iconOnly={compactBar} title="View {job?.job_kind === 'script_hub' ? 'script' : job?.job_kind}" startIcon={{ icon: diff --git a/frontend/src/lib/components/runs/RunsTable.svelte b/frontend/src/lib/components/runs/RunsTable.svelte index be997f1096..2bf333b1c7 100644 --- a/frontend/src/lib/components/runs/RunsTable.svelte +++ b/frontend/src/lib/components/runs/RunsTable.svelte @@ -21,7 +21,8 @@ import { clickOutside, isJobCancelable, isJobReRunnable, isJobResolvable } from '$lib/utils' import { goto } from '$lib/navigation' import { useHostedPage } from '../hostedPage' - import { useOperatingUser, useOperatingWorkspace } from '../operatingWorkspace.svelte' + import { useOperatingWorkspace } from '../operatingWorkspace.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { withWorkspaceParam } from '../sessions/sessionMode.svelte' import BarsStaggered from '../icons/BarsStaggered.svelte' @@ -205,7 +206,7 @@ const dispatch = createEventDispatcher() const hosted = useHostedPage() const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() + const roleCaps = useRoleCapabilities() // Under a host the link opens where it decides, in the workspace the run belongs to: the // document's own router would leave the host for the navigation workspace. @@ -331,8 +332,8 @@ onClick: () => onCancelJobs?.(selectedIdsPossibleActions.cancellableJobIds), onHover: (hover) => (hoveredDropdownAction = hover ? 'cancel' : null) }) - // Operators are rejected by the endpoint, so offering the action would only 403. - const canResolve = !operatingUser.current?.operator + // A role without `code` is rejected by the endpoint, so offering the action would only 403. + const canResolve = $roleCaps.code const resolvable = canResolve ? selectedIdsPossibleActions.resolvableJobIds.length : 0 const unresolvable = canResolve ? selectedIdsPossibleActions.unresolvableJobIds.length : 0 if (resolvable) diff --git a/frontend/src/lib/components/schedules/SchedulesList.svelte b/frontend/src/lib/components/schedules/SchedulesList.svelte index 3d8732e088..53a4ebf256 100644 --- a/frontend/src/lib/components/schedules/SchedulesList.svelte +++ b/frontend/src/lib/components/schedules/SchedulesList.svelte @@ -21,7 +21,7 @@ import InheritedLabels from '$lib/components/InheritedLabels.svelte' import ShareModal from '$lib/components/ShareModal.svelte' import Toggle from '$lib/components/Toggle.svelte' - import { userWorkspaces, enterpriseLicense } from '$lib/stores' + import { enterpriseLicense } from '$lib/stores' import { Calendar, Circle, @@ -714,10 +714,10 @@ <DeployWorkspaceDrawer bind:this={deploymentDrawer} /> <ScheduleEditor onUpdate={loadSchedules} bind:this={scheduleEditor} /> -{#if operatingUser.current?.operator && $operatingWorkspace && !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.schedules} +{#if $operatingWorkspace && !editRights.capabilities.visibility.schedules} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage> diff --git a/frontend/src/lib/components/search/GlobalSearchModal.svelte b/frontend/src/lib/components/search/GlobalSearchModal.svelte index c2c4a15bd8..0feb82db1d 100644 --- a/frontend/src/lib/components/search/GlobalSearchModal.svelte +++ b/frontend/src/lib/components/search/GlobalSearchModal.svelte @@ -39,7 +39,7 @@ import ContentSearchInner from '../ContentSearchInner.svelte' import { goto } from '$app/navigation' import QuickMenuItem from '../search/QuickMenuItem.svelte' - import { devopsRole, enterpriseLicense, userStore, workspaceStore } from '$lib/stores' + import { devopsRole, enterpriseLicense, roleCapabilities, workspaceStore } from '$lib/stores' import uFuzzy from '@leeoniya/ufuzzy' import BarsStaggered from '../icons/BarsStaggered.svelte' import { Alert } from '../common' @@ -106,77 +106,77 @@ label: 'Go to HTTP routes', action: (newtab: boolean = false) => gotoPage('/routes', newtab), icon: Route, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:web_sockets', label: 'Go to WebSockets', action: (newtab: boolean = false) => gotoPage('/websocket_triggers', newtab), icon: Unplug, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:postgres_triggers', label: 'Go to Postgres triggers', action: (newtab: boolean = false) => gotoPage('/postgres_triggers', newtab), icon: Database, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:kafka_triggers', label: 'Go to Kafka triggers' + (!$enterpriseLicense ? '' : ' (EE)'), action: (newtab: boolean = false) => gotoPage('/kafka_triggers', newtab), icon: KafkaIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:nats_triggers', label: 'Go to NATS triggers' + (!$enterpriseLicense ? '' : ' (EE)'), action: (newtab: boolean = false) => gotoPage('/nats_triggers', newtab), icon: NatsIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:sqs_triggers', label: 'Go to SQS triggers' + (!$enterpriseLicense ? '' : ' (EE)'), action: (newtab: boolean = false) => gotoPage('/sqs_triggers', newtab), icon: AwsIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:gcp_pub_sub', label: 'Go to GCP Pub/Sub' + (!$enterpriseLicense ? '' : ' (EE)'), action: (newtab: boolean = false) => gotoPage('/gcp_triggers', newtab), icon: GoogleCloudIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:azure_event_grid', label: 'Go to Azure Event Grid' + (!$enterpriseLicense ? '' : ' (EE)'), action: (newtab: boolean = false) => gotoPage('/azure_triggers', newtab), icon: AzureIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:mqtt_triggers', label: 'Go to MQTT triggers', action: (newtab: boolean = false) => gotoPage('/mqtt_triggers', newtab), icon: MqttIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:amqp_triggers', label: 'Go to AMQP triggers', action: (newtab: boolean = false) => gotoPage('/amqp_triggers', newtab), icon: AmqpIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers }, { search_id: 'nav:email_triggers', label: 'Go to Email triggers', action: (newtab: boolean = false) => gotoPage('/email_triggers', newtab), icon: MailIcon, - disabled: $userStore?.operator + disabled: !$roleCapabilities.visibility.triggers } ] diff --git a/frontend/src/lib/components/sessions/FlowEditorView.svelte b/frontend/src/lib/components/sessions/FlowEditorView.svelte index 9e34b1f7a4..ae5e25097d 100644 --- a/frontend/src/lib/components/sessions/FlowEditorView.svelte +++ b/frontend/src/lib/components/sessions/FlowEditorView.svelte @@ -131,10 +131,10 @@ onDetails={onSeeDetails} condensedHeader={true} customUi={{ topBar: { aiBuilder: false } }} - onDeploy={() => { + onDeploy={(e) => { // FlowBuilder has no deploy toast and the session stays put, so toast here. sendUserToast('Deployed') - runtime.itemDeployed(workspaceId, 'flow', path) + runtime.itemDeployed(workspaceId, 'flow', path, e.path) }} /> {/snippet} diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte new file mode 100644 index 0000000000..942025c21c --- /dev/null +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -0,0 +1,159 @@ +<script lang="ts"> + import { onMount, setContext, type Snippet } from 'svelte' + import AIChat from '$lib/components/copilot/chat/AIChat.svelte' + import type { DraftAttachments } from '$lib/components/copilot/chat/messageDraft.svelte' + import type { AIChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte' + import { StarterPrompts } from '$lib/components/copilot/chat/starter/starterPrompts.svelte' + import { goto } from '$lib/navigation' + import { getOrCreateRuntime } from './sessionRuntime.svelte' + import { workspaceStore } from '$lib/stores' + import { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot' + import { copilotWorkspace } from '$lib/aiStore' + import { + getEffectiveWorkspaceId, + getSessionDraftAttachments, + getSessionDraftPrompt, + homeStarterSession, + setSessionDraftAttachments, + selectSession, + sessionInCurrentFamily, + sessionPageHref, + sessionState, + setNewSessionWorkspace, + setSessionDraftPrompt + } from './sessionState.svelte' + import SessionWorkspaceBar from './SessionWorkspaceBar.svelte' + import { useWorkModeLock } from './workModeLock.svelte' + import { AIWorkMode } from '$lib/components/copilot/chat/workMode' + import { composerSentFromHome, takeComposerFocus } from './homeSessionsTransition.svelte' + import { homeComposerContext } from './homeComposerContext.svelte' + + // Home's block is the empty session's own chat, run by that session's manager: the + // composer, its controls and what a send does are the session's, not a copy of them. + // Picked once; the parent remounts this on a workspace switch, which changes the family. + // `placeholder` stands in while the chat waits on its config; `onSettled` reports the height + // the chat first took, for the next placeholder to take. + let { + onShown, + placeholder, + onSettled + }: { onShown?: () => void; placeholder?: Snippet; onSettled?: (height: number) => void } = + $props() + + const initialSession = homeStarterSession() + const sessionId = initialSession.id + const runtime = getOrCreateRuntime(initialSession) + setContext<AIChatManager>('aiChatManager', runtime.manager) + + const session = $derived(sessionState.sessions.find((s) => s.id === sessionId)) + // Switches the page along with the session, as the workspace bar below does. + const workModeLock = useWorkModeLock(() => session, true) + const actingWorkspaceId = $derived( + (session ? getEffectiveWorkspaceId(session) : undefined) ?? $workspaceStore ?? undefined + ) + const starterPrompts = new StarterPrompts( + () => actingWorkspaceId, + () => !workModeLock.current && runtime.manager.workMode !== AIWorkMode.USE + ) + + // The AI config (models, whether AI is hidden) of the workspace the draft acts on, as the + // session page loads it, so a fork picked here shows its own models and the session page + // can judge it at once on arrival instead of covering it while it asks. The layout also + // loads Home's own workspace into the same shared config, and the last request wins, so + // this asks again whenever a later request named another workspace. + $effect(() => { + if (actingWorkspaceId && $copilotWorkspaceRequested !== actingWorkspaceId) + loadCopilot(actingWorkspaceId) + }) + + // The turn is already running on the session's manager; the page it belongs to takes over. + function onSent() { + composerSentFromHome() + selectSession(sessionId) + void goto(sessionPageHref(sessionId)) + } + + function onDraftChange(text: string) { + setSessionDraftPrompt(sessionId, text) + // A prompt typed here is what the AI Sessions switch should open; an empty box leaves + // the switch resuming whatever session the user was last in. + if (text.trim()) selectSession(sessionId) + } + + function onAttachmentsChange(attachments: DraftAttachments) { + setSessionDraftAttachments(sessionId, attachments) + if (Object.values(attachments).some((lane) => lane.length > 0)) selectSession(sessionId) + } + + let aiChat: AIChat | undefined = $state(undefined) + let chatWrapper: HTMLDivElement | undefined = $state(undefined) + // A seeded draft holds the composer open, which is not the shape it rests in once the + // draft is sent, so only a mount with an empty draft is measured. + const initialAttachments = getSessionDraftAttachments(sessionId) + let settled = + !!getSessionDraftPrompt(sessionId)?.trim() || + (!!initialAttachments && Object.values(initialAttachments).some((lane) => lane.length > 0)) + $effect(() => { + if (!aiChat || !chatWrapper || settled) return + settled = true + const wrapper = chatWrapper + requestAnimationFrame(() => onSettled?.(wrapper.offsetHeight)) + }) + // The draft acts on the workspace Home shows, whichever picker switched it: a switch within + // the family keeps this mount, so the draft's pick has to follow. A switch to another family + // remounts with that family's draft, so this one is left where it was. A staged fork of the + // shown workspace stays. On mount, a draft that differs is one that follows Home, moved off it + // by a switch made elsewhere (homeStarterSession). + onMount(() => + workspaceStore.subscribe((ws) => { + const s = sessionState.sessions.find((x) => x.id === sessionId) + if (!ws || !s || s.workspace_id || s.pending_workspace_id === ws) return + if (sessionInCurrentFamily(s)) setNewSessionWorkspace(sessionId, ws) + }) + ) + onMount(() => { + onShown?.() + if (takeComposerFocus()) setTimeout(() => aiChat?.focusInput(), 0) + // The rows' "Ask AI" lands here. Before the chat has mounted (its config still + // loading) there is nowhere to put the item, and the attach does nothing. + return homeComposerContext.register(async (element) => { + await aiChat?.attachContext(element) + }) + }) +</script> + +{#snippet actingOn()} + {#if session} + <SessionWorkspaceBar {session} switchesWorkspace /> + {/if} +{/snippet} + +<!-- Until a config has loaded the chat reads "AI not configured" and would flash its disabled + state. Any loaded config will do, so a fork switch does not hide it while the fork's loads. + The item count decides whether the composer rests collapsed, so it waits for that too + rather than open and fold up a moment later. --> +{#if session && $copilotWorkspace !== undefined && starterPrompts.fewItems !== undefined} + <div bind:this={chatWrapper}> + <AIChat + bind:this={aiChat} + hideHeader + hideModeSelector + wideLayout + initialInstructions={getSessionDraftPrompt(sessionId)} + {onDraftChange} + initialAttachments={getSessionDraftAttachments(sessionId)} + {onAttachmentsChange} + starter={{ + where: 'home', + suggestions: starterPrompts.suggestions, + fewItems: starterPrompts.fewItems + }} + viewTransitionNames + {onSent} + {actingOn} + workModeLock={workModeLock.current} + /> + </div> +{:else} + {@render placeholder?.()} +{/if} diff --git a/frontend/src/lib/components/sessions/ItemViewerView.svelte b/frontend/src/lib/components/sessions/ItemViewerView.svelte index e9fa9b7768..d1adaa952f 100644 --- a/frontend/src/lib/components/sessions/ItemViewerView.svelte +++ b/frontend/src/lib/components/sessions/ItemViewerView.svelte @@ -64,7 +64,10 @@ untrack(() => runtime.manager) ) - const permissions = useSessionPermissions(() => workspaceId) + const permissions = useSessionPermissions( + () => workspaceId, + () => runtime.manager + ) const canEdit = $derived(permissions.canOpenEditor(kind)) // This reads the deployed version over the API rather than from the editor cell the diff --git a/frontend/src/lib/components/sessions/OpenInSessionButton.svelte b/frontend/src/lib/components/sessions/OpenInSessionButton.svelte index 00b784138f..2ea4bdbf61 100644 --- a/frontend/src/lib/components/sessions/OpenInSessionButton.svelte +++ b/frontend/src/lib/components/sessions/OpenInSessionButton.svelte @@ -32,6 +32,13 @@ * only `window.location` read at that moment matches what the user sees. */ | { page: () => string | undefined; target?: never } ) + + function sameDestination(a: OpenInSessionSource | undefined, b: OpenInSessionSource | undefined) { + if (!a || !b) return false + if (a.target && b.target) + return a.target.kind === b.target.kind && a.target.path === b.target.path + return !!a.page && !!b.page && a.page() === b.page() + } </script> <script lang="ts"> @@ -43,10 +50,10 @@ import { copilotInfo } from '$lib/aiStore' import { sendUserToast } from '$lib/toast' import { openSourceInSession } from './sessionSwitch.svelte' - import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' + import { useRoleCapabilities } from '$lib/operatorWriteRights' - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) + const roleCaps = useRoleCapabilities() let { source, @@ -54,7 +61,8 @@ btnProps, label, tooltip, - fallback + fallback, + deferToHeader = false }: { /** Undefined (e.g. an item without a path yet) renders the fallback. */ source?: OpenInSessionSource @@ -72,6 +80,11 @@ * opted-out user (typically the editor's inline-chat * toggle). Never rendered inside the session panel. */ fallback?: Snippet + /** For a button inside a page whose header can carry the same hand-off: while the header + * does, this renders nothing, so the hand-off has one place on screen. The fallback still + * renders for a user who opted out of sessions, since the header then offers nothing. An + * editor in a drawer opened on another item keeps its own button. */ + deferToHeader?: boolean } = $props() // Inside the session panel the chat is already on screen — a second entry @@ -80,13 +93,16 @@ // SessionEditorTarget / the session wrapper); iframe preview tabs are not // the top window. const inSessionPanel = !!getContext('aiChatManager') || (BROWSER && window.self !== window.top) - // prefersSessionHandoff carries the operator clause: the sessions page refuses - // them, so an entry point on a page they can reach (Runs, the trigger lists) + // prefersSessionHandoff carries the role clause: the sessions page refuses a role + // that cannot code, so an entry point on a page they can reach (Runs, the trigger lists) // would only route them into that refusal. - const show = $derived( + const handoff = $derived( !inSessionPanel && !!(source?.target || source?.page) && - prefersSessionHandoff(actingUser?.operator) + prefersSessionHandoff(!$roleCaps.code) + ) + const show = $derived( + handoff && !(deferToHeader && sameDestination(pageHeader.sessionSource, source)) ) // Not $state: only read inside open() as a re-entrancy latch, never rendered. @@ -119,6 +135,6 @@ {label} {tooltip} /> -{:else if !inSessionPanel} +{:else if !inSessionPanel && !handoff} {@render fallback?.()} {/if} diff --git a/frontend/src/lib/components/sessions/PageItemEditorView.svelte b/frontend/src/lib/components/sessions/PageItemEditorView.svelte index 73efd892d4..a77550a3ef 100644 --- a/frontend/src/lib/components/sessions/PageItemEditorView.svelte +++ b/frontend/src/lib/components/sessions/PageItemEditorView.svelte @@ -10,12 +10,15 @@ import { setOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { pageItemKindLabel, + pageItemPageHref, pageItemUrl, TRIGGER_PAGES, type PageItemRef, type TriggerKind } from './previewPaths' import type { SessionRuntime } from './sessionRuntime.svelte' + import { useSessionPermissions } from './sessionPermissions.svelte' + import { withWorkspaceParam } from './sessionMode.svelte' let { runtime, @@ -103,6 +106,13 @@ ) ) + // These editors save on click, and a schedule or trigger save passes a production + // workspace's deploy rules, so a read-only session mounts none of them. + const permissions = useSessionPermissions( + () => workspaceId, + () => runtime.manager + ) + function closeTab() { const tab = runtime.previewTabs.tabs.find((t) => t.url === pageItemUrl(item)) if (tab) runtime.previewTabs.close(tab.id) @@ -135,6 +145,21 @@ </p> <Button variant="default" unifiedSize="sm" onClick={closeTab}>Close tab</Button> </div> + {:else if permissions.readOnly} + <div class="flex flex-col items-start gap-3 p-4 text-sm text-secondary"> + <p> + {pageItemKindLabel(item)} <span class="font-mono">{item.path}</span> can't be edited while the + session is in Use mode. + </p> + <Button + variant="default" + unifiedSize="sm" + href={withWorkspaceParam(pageItemPageHref(item), workspaceId)} + target="_blank" + > + Open in workspace + </Button> + </div> {:else} {#key `${item.kind}:${triggerKey}:${item.path}:${workspaceId}:${reloadNonce}:${savedNonce}`} {#if item.kind === 'variable'} diff --git a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte index bc03272712..8fa6b465cc 100644 --- a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte +++ b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte @@ -50,6 +50,7 @@ section or the flat layout. type PreviewTarget } from './previewRouter' import { useSessionPermissions } from './sessionPermissions.svelte' + import type { AIWorkMode } from '$lib/components/copilot/chat/workMode' type Kind = WorkspaceItemKind type DrillPickerHandle = { @@ -75,6 +76,9 @@ section or the flat layout. // Session artifacts to surface as an "Artifacts" branch; omitted or empty // hides the branch (non-session consumers, sessions without artifacts). artifacts?: PersistedArtifact[] + /** The session chat, whose Use mode opens items in their viewer. Read from the + * `aiChatManager` context when omitted. */ + chat?: { readonly workMode: AIWorkMode } } let { @@ -86,12 +90,16 @@ section or the flat layout. autoFocus = true, flush = false, workspaceId, - artifacts + artifacts, + chat }: Props = $props() const kinds: Kind[] = ['flow', 'script', 'app'] const effectiveWorkspace = $derived(workspaceId ?? $workspaceStore) - const permissions = useSessionPermissions(() => effectiveWorkspace) + const permissions = useSessionPermissions( + () => effectiveWorkspace, + () => chat + ) const canEdit = (item: WorkspaceItem) => permissions.canEditItem(item) let inner = $state<DrillPickerHandle | undefined>(undefined) diff --git a/frontend/src/lib/components/sessions/PreviewTabHost.svelte b/frontend/src/lib/components/sessions/PreviewTabHost.svelte index c2adaf7688..33470fa261 100644 --- a/frontend/src/lib/components/sessions/PreviewTabHost.svelte +++ b/frontend/src/lib/components/sessions/PreviewTabHost.svelte @@ -22,6 +22,7 @@ import ArtifactViewer from '../copilot/chat/artifacts/ArtifactViewer.svelte' import RunFormPreviewSlot from './RunFormPreviewSlot.svelte' import { setOverlayHost } from '../common/overlayHost.svelte' + import { setReadOnlyWorkspace } from '../operatingWorkspace.svelte' let { tab, @@ -80,7 +81,11 @@ const workspaceId = $derived( session ? (getEffectiveWorkspaceId(session) ?? $workspaceStore ?? '') : '' ) - const permissions = useSessionPermissions(() => workspaceId || undefined) + const permissions = useSessionPermissions( + () => workspaceId || undefined, + () => runtime?.manager + ) + setReadOnlyWorkspace((ws) => !!ws && ws === workspaceId && permissions.readOnly) // Every route into an editor ends here, the breadcrumb and the chat's openers included, so // this is where an editor the user cannot save is turned into the deployed page. const mode = $derived( @@ -419,7 +424,9 @@ {:else} <!-- A pipeline has no deployed page, only its editor. --> <div class="flex-1 flex items-center justify-center p-8 text-center text-sm text-secondary"> - The pipeline editor saves drafts, which your role cannot do in this workspace. + {permissions.readOnly + ? 'The pipeline editor saves drafts, which a session in Use mode cannot do.' + : 'The pipeline editor saves drafts, which your role cannot do in this workspace.'} </div> {/if} </div> diff --git a/frontend/src/lib/components/sessions/RawAppEditorView.svelte b/frontend/src/lib/components/sessions/RawAppEditorView.svelte index b944612f91..50ea1e054a 100644 --- a/frontend/src/lib/components/sessions/RawAppEditorView.svelte +++ b/frontend/src/lib/components/sessions/RawAppEditorView.svelte @@ -23,7 +23,7 @@ import SessionEditorTarget from './SessionEditorTarget.svelte' import { runResetToDeployed } from '$lib/userDraftToast' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' - import { operatorBuilderAppsIn } from '$lib/operatorWriteRights' + import { capabilitiesInWorkspace } from '$lib/operatorWriteRights' import type { RawAppRuntimeLogRequester, RawAppRunsProvider, @@ -100,7 +100,9 @@ files: { ...result.files }, runnables: { ...result.runnables, - ...(operatorBuilderAppsIn(workspaceId) ? {} : structuredClone(STARTER_RUNNABLES)) + ...(capabilitiesInWorkspace(workspaceId).apps === 'compose' + ? {} + : structuredClone(STARTER_RUNNABLES)) }, data: result.data, policy: result.policy @@ -148,12 +150,27 @@ if (dp !== undefined) { surfacedDraftPath = true if (val.draft_path !== dp) val.draft_path = dp - } else if (surfacedDraftPath && val.draft_path !== undefined) { + } else if ( + surfacedDraftPath && + val.draft_path !== undefined && + // Equal to the saved path, it is not stale: a deploy just moved the app + // there. Clearing it would schedule a save of this cell at the old path + // that lands after the deploy discarded it, and the moved draft row + // would come back on the new path. + val.draft_path !== cell.saved.val?.path + ) { val.draft_path = undefined } }) }) + function openFork(forkPath: string) { + runtime.previewTabs.open({ + type: 'item', + item: { kind: 'app', raw_app: true, path: forkPath, summary: '' } + }) + } + async function reloadDeployed() { await runtime.loadRawApp(workspaceId, path, true, true) } @@ -372,6 +389,7 @@ {diffDrawer} {onNavigate} onDetails={onSeeDetails} + onOpenFork={openFork} condensedHeader={true} onResetToDeployed={reloadDeployed} onDeploy={(e) => runtime.itemDeployed(workspaceId, 'raw_app', path, e.path)} diff --git a/frontend/src/lib/components/sessions/ScriptEditorView.svelte b/frontend/src/lib/components/sessions/ScriptEditorView.svelte index ab1bac52c9..5248f14164 100644 --- a/frontend/src/lib/components/sessions/ScriptEditorView.svelte +++ b/frontend/src/lib/components/sessions/ScriptEditorView.svelte @@ -124,7 +124,7 @@ // Fires on every deploy (primary, "Deploy & Stay here", and lib — we // ignore e.stay since the session always stays). sendUserToast('Deployed') - runtime.itemDeployed(workspaceId, 'script', e.path) + runtime.itemDeployed(workspaceId, 'script', path, e.path) }} /> {/if} diff --git a/frontend/src/lib/components/sessions/SessionChangesBar.svelte b/frontend/src/lib/components/sessions/SessionChangesBar.svelte index 3929b78ca9..b7ee23034c 100644 --- a/frontend/src/lib/components/sessions/SessionChangesBar.svelte +++ b/frontend/src/lib/components/sessions/SessionChangesBar.svelte @@ -11,11 +11,18 @@ import Badge from '$lib/components/common/badge/Badge.svelte' import SessionStatusPopover from './SessionStatusPopover.svelte' import WorkspaceFamilyPicker from './WorkspaceFamilyPicker.svelte' - import { maybePremium, userStore, userWorkspaces, workspaceStore } from '$lib/stores' + import { + maybePremium, + roleCapabilities, + userStore, + userWorkspaces, + workspaceStore + } from '$lib/stores' import { canCreateFork } from '$lib/utils/editInFork' import { isCloudHosted } from '$lib/cloud' import { sessionState, type Session } from './sessionState.svelte' import { getRuntime } from './sessionRuntime.svelte' + import { useSessionPermissions } from './sessionPermissions.svelte' import SessionDiffDrawer from './SessionDiffDrawer.svelte' import { TOKEN_TRIGGER_CLASS } from './SessionStatusToken.svelte' import { useWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' @@ -63,10 +70,17 @@ // Same gate as the sidebar WorkspaceMenu / SessionWorkspaceBar. On cloud, // forking is a premium-only feature (backend caps it per paid seat). const forksAllowed = $derived( - (!isCloudHosted() || $maybePremium) && canCreateFork($userStore) && $workspaceStore !== 'admins' + (!isCloudHosted() || $maybePremium) && + canCreateFork($userStore, $roleCapabilities) && + $workspaceStore !== 'admins' ) const runtime = $derived(getRuntime(session.id)) + // A session in Use deploys and discards nothing, as its chat does not. + const permissions = useSessionPermissions( + () => committedId, + () => runtime?.manager + ) // The chat's modified-items mask (`${UserDraftItemKind}:${storagePath}`). // undefined = legacy/untracked chat → fall back to showing every draft. @@ -381,8 +395,10 @@ onItemDiscarded={(item) => { void runtime?.manager.removeModifiedItem(item.draftKind, item.path) const folder = pipelineFolderFromBundlePath(item.path) - if (item.draftKind === PIPELINE_DRAFT_KIND && folder) void runtime?.forgetPipelineDrafts(folder) + if (item.draftKind === PIPELINE_DRAFT_KIND && folder) + void runtime?.forgetPipelineDrafts(folder) }} deployPipeline={runtime?.deployPipeline} + readOnly={permissions.readOnly} /> {/if} diff --git a/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte b/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte index d921e435b0..76d7f7e7ab 100644 --- a/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte +++ b/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte @@ -20,7 +20,8 @@ onDataChanged, onItemDeployed, onItemDiscarded, - deployPipeline + deployPipeline, + readOnly = false }: { workspaceId: string parentWorkspaceId?: string @@ -39,6 +40,8 @@ onItemDiscarded?: (item: DeployItem) => void /** Forwarded to the deploy model: deploys a pipeline folder's draft bundle. */ deployPipeline?: (folder: string) => Promise<DeployResult> + /** Forwarded to the deploy model: the session is in Use. */ + readOnly?: boolean } = $props() const isFork = $derived(!!parentWorkspaceId) @@ -55,7 +58,8 @@ onDataChanged, onItemDeployed, onItemDiscarded, - deployPipeline + deployPipeline, + readOnly })) // Editor URL for a row (every item lives in the session workspace). @@ -99,7 +103,11 @@ {ws?.name ?? workspaceId} </span> {#if ws?.is_dev_workspace} - <DevWorkspaceBadge label={ws.dev_workspace_label} color={ws.color} fallbackColor="indigo" /> + <DevWorkspaceBadge + label={ws.dev_workspace_label} + color={ws.color} + fallbackColor="indigo" + /> {/if} <ArrowRight class="w-3 h-3 shrink-0 text-tertiary" /> <span class="font-medium truncate" title={parentWs?.name ?? parentWorkspaceId}> diff --git a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte index 1a992b818b..768064576a 100644 --- a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte +++ b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte @@ -1,35 +1,68 @@ -<script lang="ts"> +<script lang="ts" module> + import { get } from 'svelte/store' import { workspaceStore } from '$lib/stores' + import { setSessionPendingWorkspace, stopFollowingHome } from './sessionState.svelte' + import { switchWorkspace } from '$lib/storeUtils' + import { workspaceAIClients } from '$lib/components/copilot/lib' + import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl' + + function followPick(id: string, switchesWorkspace: boolean) { + if (!switchesWorkspace || get(workspaceStore) === id) return + workspaceAIClients.init(id) + switchWorkspace(id) + void fixupUrlAfterWorkspaceSwitch(id) + } + + // Before the pick, which stores the session: Home would otherwise move a draft picked off + // Home back to the workspace it shows. + function releaseFromHome(sessionId: string, switchesWorkspace: boolean) { + if (!switchesWorkspace) stopFollowingHome(sessionId) + } + + /** Point a session that has not sent yet at workspace `id`, as a pick in this bar does. */ + export function pickSessionWorkspace(sessionId: string, id: string, switchesWorkspace: boolean) { + releaseFromHome(sessionId, switchesWorkspace) + // Pre-send only: writes the pending pick. workspace_id stays undefined until + // the user sends their first message. The chat targets this pending workspace + // via the manager's workspace resolver, not the global workspaceStore. + setSessionPendingWorkspace(sessionId, id) + followPick(id, switchesWorkspace) + } +</script> + +<script lang="ts"> import { getEffectiveWorkspaceId, setSessionPendingFork, - setSessionPendingWorkspace, type Session } from './sessionState.svelte' import WorkspaceFamilyPicker from './WorkspaceFamilyPicker.svelte' import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte' - let { session }: { session: Session } = $props() + // `switchesWorkspace`: a pick also moves the navigation workspace. For a host whose page + // shows the navigation workspace around the composer (Home), where a pick that left it + // behind would read as ignored; the session page follows the session's own workspace instead. + let { session, switchesWorkspace = false }: { session: Session; switchesWorkspace?: boolean } = + $props() // Effective workspace for display: committed → pending pick → active store. const effectiveId = $derived(getEffectiveWorkspaceId(session) ?? $workspaceStore ?? undefined) const pendingFork = $derived(session.pending_fork) function pick(id: string) { - // Pre-send only: writes the pending pick. workspace_id stays undefined until - // the user sends their first message. The global workspaceStore is left - // untouched — the chat targets this pending workspace via the manager's - // workspace resolver, so picking here must not switch the active workspace. - setSessionPendingWorkspace(session.id, id) + pickSessionWorkspace(session.id, id, switchesWorkspace) } function stageFork(req: { parent_workspace_id: string; id: string; name: string }) { + releaseFromHome(session.id, switchesWorkspace) setSessionPendingFork(session.id, req) + followPick(req.parent_workspace_id, switchesWorkspace) } </script> -<div class="flex flex-row items-center gap-1 py-0.5 px-1 text-2xs text-secondary"> - <span class="shrink-0">Acting on</span> +<!-- A control of the composer's toolbar; on a narrow window it gives up its label first. --> +<div class="flex flex-row items-center gap-1 min-w-0 text-2xs text-secondary"> + <span class="shrink-0 hidden lg:inline">Acting on</span> <WorkspaceFamilyPicker selectedId={effectiveId} {pendingFork} diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index 05a0cdda41..fc128584ba 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -1,7 +1,29 @@ +<script module lang="ts"> + import { preloadComponent } from '$lib/utils/preloadComponent.svelte' + + // AIChat's code is most of this page's: loaded beside it rather than as part of it, so the + // page and its ComposerPlaceholder show without waiting on it. + const aiChatComponent = preloadComponent( + () => import('$lib/components/copilot/chat/AIChat.svelte') + ) +</script> + <script lang="ts"> import { onDestroy, setContext, untrack } from 'svelte' import { Pane, Splitpanes } from 'svelte-splitpanes' - import AIChat from '$lib/components/copilot/chat/AIChat.svelte' + import type AIChat from '$lib/components/copilot/chat/AIChat.svelte' + import ComposerPlaceholder from '$lib/components/copilot/chat/ComposerPlaceholder.svelte' + import SessionGreeting from '$lib/components/copilot/chat/starter/SessionGreeting.svelte' + import ComposerSuggestions from '$lib/components/copilot/chat/starter/ComposerSuggestions.svelte' + import { + globalComposerSuggestion, + STARTER_PLACEHOLDER, + USE_STARTER_PLACEHOLDER, + type ComposerSelection + } from '$lib/components/copilot/chat/composerBox' + import { useSessionPermissions } from './sessionPermissions.svelte' + import { useWorkModeLock } from './workModeLock.svelte' + import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import EditableInput from '$lib/components/common/EditableInput.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import { Button } from '$lib/components/common' @@ -13,7 +35,7 @@ import { WorkspaceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' import Toggle from '$lib/components/Toggle.svelte' - import { copilotInfo } from '$lib/aiStore' + import { copilotInfo, copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' import { Archive, @@ -21,10 +43,12 @@ EllipsisVertical, MessageSquareDashed, Pencil, + Plus, Trash2, X } from 'lucide-svelte' import SessionWorkspaceBar from './SessionWorkspaceBar.svelte' + import { arrivingFromHomeSend } from './homeSessionsTransition.svelte' import SessionChangesBar from './SessionChangesBar.svelte' import SessionShareButton from './SessionShareButton.svelte' import { clearSessionRecovered, isSessionRecovered } from './sessionRecoveryNotice.svelte' @@ -37,7 +61,10 @@ moveSessionToWorkspace, getSessionDraftPrompt, setSessionDraftPrompt, + getSessionDraftAttachments, + setSessionDraftAttachments, peekSessionAutoSend, + getSessionAutoSendDomElement, takeSessionAutoSend, reconcileAfterWorkspaceChange, renameSession, @@ -51,14 +78,24 @@ import { getOrCreateRuntime, removeSession } from './sessionRuntime.svelte' import { goto } from '$lib/navigation' import { splitterPointerCapture } from '$lib/utils/splitterPointerCapture' + import { StarterPrompts } from '$lib/components/copilot/chat/starter/starterPrompts.svelte' + import { resolvePreviewTab } from './previewRouter' + import { whereIs } from './sessionPreviewTabs.svelte' + import type { SessionPreviewTab } from './sessionState.svelte' let { sessionId, - headerInPage = false + headerInPage = false, + covered = false, + previewTabName }: { sessionId: string /** True for the session the page is showing: its header rides the page header bar. */ headerInPage?: boolean + /** True while the page holds this wrapper inert under an overlay, where nothing takes focus. */ + covered?: boolean + /** The name the preview's tab strip shows for a tab, without its side marker. */ + previewTabName: (tab: SessionPreviewTab) => string } = $props() // Parent keys by sessionId; this wrapper only mounts when the session exists. @@ -73,6 +110,41 @@ // Reactive session reference (mutations to summary/target propagate via the $state proxy) const session = $derived(sessionState.sessions.find((s) => s.id === sessionId)) + // Only a session that has never sent opens as the starter block. Read off the record, not + // the transcript: a cold session's history is still loading from storage when it mounts, + // and an empty transcript would show the greeting and then glide the composer away. + // The first send commits the workspace, so this flips only after the transcript has. + const opensSession = $derived(!session?.workspace_id) + const permissions = useSessionPermissions( + () => runtime?.manager.operatingWorkspace, + () => runtime?.manager + ) + const workModeLock = useWorkModeLock(() => session) + // Whether the first message goes out in Use. Not `permissions.readOnly`: before that send a + // staged fork's session reads the workspace it forks, while the message builds in the fork. + const heldInUse = $derived(!!workModeLock.current || runtime?.manager.workMode === AIWorkMode.USE) + // The item an unsent session opened on ("Open in AI session", or a tab opened before the + // first send): the chat reads the displayed tab with each message, so the empty chat asks + // about that item instead of greeting. What is on screen only: a collapsed panel hides it. + // Named as its tab is, so a deployed item in View mode gets its summary from the listing. + const previewedItem = $derived.by(() => { + if (!opensSession) return undefined + const tab = runtime?.previewTabs.displayedTab + if (!tab) return undefined + const slot = resolvePreviewTab(whereIs(tab)) + if (slot.kind !== 'editor' && slot.kind !== 'viewer') return undefined + const kind = slot.kind === 'editor' ? slot.editorKind : slot.viewerKind + return { + kind: kind === 'raw_app' ? 'app' : kind, + name: previewTabName(tab) + } + }) + const greets = $derived(opensSession && !previewedItem) + const starterPrompts = new StarterPrompts( + () => (greets ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined), + () => !heldInUse + ) + // Seed the composer with the unsent prompt a reload preserved on the session // record (script-init: AIChatInput reads it once at mount). const restoredDraftPrompt = getSessionDraftPrompt(sessionId) @@ -85,6 +157,30 @@ // mount-time empty draft would otherwise erase the prompt from the record. const armedAtInit = sessionState.currentSessionId === sessionId && peekSessionAutoSend(sessionId) + // The composer's text before AIChat mounts, typed into the placeholder, and then the real + // composer's initial draft. + let draftText = $state(armedAtInit ? '' : (restoredDraftPrompt ?? '')) + // What the first focus after the swap does: put the caret where the placeholder had it, or, + // when null, leave focus where the user moved it while the chat loaded. Undefined when the + // placeholder never had focus. + let handoff: ComposerSelection | null | undefined = undefined + // The swap waits for an IME composition to end: the new field would not carry it over. + let placeholderComposing = $state(false) + // The placeholder's text counts as unsent input, like the real composer's draft, so the page + // does not evict this session's chat (and the text with it) while it waits for the chat code. + const PLACEHOLDER_DRAFT_KEY = 'composer-placeholder' + function setPlaceholderText(text: string) { + draftText = text + setSessionDraftPrompt(sessionId, text) + runtime?.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, text.trim() !== '') + } + + // Drawn once, and shared by the placeholder and the real composer so the text survives the swap. + const suggestionPick = Math.random() + const composerPlaceholder = $derived( + globalComposerSuggestion(suggestionPick, permissions.canOpenEditor) + ) + // A hand-off whose click already stated the intent asks for its prompt to be // sent, not parked. Reactive rather than mount-time: `createSession` reuses an // untouched blank session and the sessions page keys wrappers by id, so a @@ -97,13 +193,14 @@ if (!session?.autoSendDraftAt || !runtime) return untrack(() => { const prompt = getSessionDraftPrompt(sessionId) + const domElement = getSessionAutoSendDomElement(sessionId) // takeSessionAutoSend clears the intent whether or not it is still // fresh, so this cannot re-enter on the next dependency change. if (!takeSessionAutoSend(sessionId) || !prompt) return // sendOrQueue, not sendRequest: a reused session may already be mid-turn. // The runtime's beforeSend awaits loadCopilot for the committed // workspace, so this cannot race the model config on a cold session. - runtime.manager.sendOrQueue(prompt) + runtime.manager.sendOrQueue(prompt, domElement ? [domElement] : undefined) }) }) @@ -258,17 +355,43 @@ // warm-session switch via the picker, and the moment copilot finishes // loading. let aiChat: AIChat | undefined = $state(undefined) + let seenFocusNonce = untrack(() => composerFocusRequest.nonce) $effect(() => { // Focus the composer when this session becomes active, or on an explicit // focus request — the latter covers `+` reusing the untouched draft you're // already viewing, where currentSessionId doesn't change so activation alone // wouldn't re-run this. - void composerFocusRequest.nonce - if (sessionState.currentSessionId !== sessionId) return + const focusNonce = composerFocusRequest.nonce + if (focusNonce !== seenFocusNonce) { + // An explicit request overrides the user having left the placeholder before it. + seenFocusNonce = focusNonce + handoff = undefined + } + if (sessionState.currentSessionId !== sessionId) { + // The user left for another session: coming back is an activation, which focuses. + handoff = undefined + return + } if (!aiChat) return if (!$copilotInfo.enabled) return const chat = aiChat - setTimeout(() => chat.focusInput(), 0) + const selection = handoff + handoff = undefined + if (selection === null) return + setTimeout(() => chat.focusInput(selection), 0) + }) + + // The real composer is disabled until the copilot config of the workspace it acts on is in, + // so the active session keeps the placeholder, which takes typing, until then. Latched: a + // later config reload must not swap a mounted chat, and its transcript, back out. + let chatShown = false + const showChat = $derived.by(() => { + chatShown ||= + !!aiChatComponent.current && + !placeholderComposing && + (sessionState.currentSessionId !== sessionId || + $copilotWorkspace === (actingWorkspaceId ?? $workspaceStore)) + return chatShown }) // True when the session committed to a workspace that's no longer in @@ -302,11 +425,27 @@ // utilities on one element resolve by stylesheet order, not attribute order. const bannerClass = 'flex flex-row items-center justify-between gap-2 py-2 px-3 text-xs border rounded-md' + + const previewedItemPlaceholder = $derived( + previewedItem && + (heldInUse + ? `Ask about the ${previewedItem.kind} ${previewedItem.name}, or run it…` + : `Ask about the ${previewedItem.kind} ${previewedItem.name}, or describe a change…`) + ) </script> {#if !session || !runtime} <div class="p-8 text-secondary text-sm">Session not found</div> {:else} + <!-- A sent session whose transcript is still loading (or came back empty) shows nothing + rather than the docked copilot's keyboard-shortcut hint, which means nothing here. --> + {#snippet sessionEmptyHint()} + {#if previewedItem} + <!-- Holds the composer at the bottom, as in a session under way. --> + <div class="flex-1 min-h-0"></div> + {/if} + {/snippet} + {#snippet inputPreface()} {#if showRecoveryNotice} <!-- mb-6, not the banner column's mb-1: at that gap it reads as one more @@ -334,9 +473,6 @@ /> </div> {/if} - {#if !hasFirstUserMessage} - <SessionWorkspaceBar {session} /> - {/if} <!-- gap-1 (4px) spaces the archived banner and the changes bar when both are visible. Each renders a single in-flow root (or nothing); the diff drawer is position:fixed, so it doesn't count as a flex item — no stray @@ -373,9 +509,17 @@ </div> {/snippet} - <!-- Override the chat's default keyboard-shortcut hint with nothing — - sessions have their own empty-state affordances above. --> - {#snippet sessionEmptyHint()}{/snippet} + {#snippet actingOn()} + <SessionWorkspaceBar {session} /> + {/snippet} + + <!-- The left of AIChatDisplay's controls row: the rest arrives with the chat. --> + {#snippet placeholderToolbar()} + <div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap"> + <Button unifiedSize="2xs" variant="subtle" iconOnly startIcon={{ icon: Plus }} disabled /> + {@render actingOn()} + </div> + {/snippet} {#snippet sessionHeader()} <EditableInput @@ -463,23 +607,85 @@ <div class="flex-1 min-h-0 flex flex-col" use:splitterPointerCapture> <Splitpanes horizontal={false} class="flex-1 min-h-0 splitter-hidden"> <Pane minSize={25} class="flex flex-col min-h-0 pb-2"> - <div class="flex-1 min-h-0 w-full flex flex-col {hasFirstUserMessage ? '' : 'pt-8'}"> - <AIChat - bind:this={aiChat} - hideHeader - hideModeSelector - wideLayout - initialInstructions={armedAtInit ? undefined : restoredDraftPrompt} - onDraftChange={(text) => setSessionDraftPrompt(sessionId, text)} - forceDisabled={isUnavailable || !!session.archived} - forceDisabledMessage={isUnavailable - ? 'This session is linked to a workspace that no longer exists. Move it or discard it from the banner above to keep working.' - : session.archived - ? 'This session is archived. Unarchive it from the banner above to keep working.' - : ''} - emptyHint={sessionEmptyHint} - {inputPreface} - /> + <div class="flex-1 min-h-0 w-full flex flex-col"> + {#if showChat && aiChatComponent.current} + <aiChatComponent.current + bind:this={aiChat} + hideHeader + hideModeSelector + wideLayout + initialInstructions={draftText} + onDraftChange={(text) => setSessionDraftPrompt(sessionId, text)} + initialAttachments={armedAtInit ? undefined : getSessionDraftAttachments(sessionId)} + onAttachmentsChange={(a) => setSessionDraftAttachments(sessionId, a)} + placeholder={previewedItemPlaceholder ?? composerPlaceholder} + forceDisabled={isUnavailable || !!session.archived} + forceDisabledMessage={isUnavailable + ? 'This session is linked to a workspace that no longer exists. Move it or discard it from the banner above to keep working.' + : session.archived + ? 'This session is archived. Unarchive it from the banner above to keep working.' + : ''} + starter={greets + ? { where: 'session', suggestions: starterPrompts.suggestions } + : undefined} + viewTransitionNames={headerInPage && (opensSession || arrivingFromHomeSend())} + emptyHint={sessionEmptyHint} + {inputPreface} + actingOn={hasFirstUserMessage ? undefined : actingOn} + workModeLock={workModeLock.current} + /> + {:else} + <!-- AIChatDisplay's layout, so the composer stays put when the chat replaces it: + its transcript area, its column, and its footer row's height; for a session + that has never sent, the greeting above the centred composer. --> + <div + class="flex flex-col h-full {greets ? 'justify-center' : ''}" + {@attach () => () => + runtime.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, false)} + > + {#if greets} + <div class="flex-1 min-h-0 flex flex-col justify-end"> + <div class="w-full max-w-3xl mx-auto px-7"> + <SessionGreeting /> + </div> + </div> + {:else if previewedItem || runtime.manager.displayMessages.length > 0} + <div class="flex-1 min-h-0"></div> + {/if} + <div class="w-full max-w-3xl mx-auto px-7 pb-2"> + {@render inputPreface()} + <ComposerPlaceholder + bind:value={() => draftText, setPlaceholderText} + toolbar={greets ? placeholderToolbar : undefined} + placeholder={greets + ? heldInUse + ? USE_STARTER_PLACEHOLDER + : STARTER_PLACEHOLDER + : runtime.manager.displayMessages.length > 0 + ? 'Ask followup' + : (previewedItemPlaceholder ?? composerPlaceholder)} + disabled={isUnavailable || !!session.archived} + autofocus={sessionState.currentSessionId === sessionId && !covered} + onSelectionChange={(selection) => (handoff = selection ?? null)} + onCompositionChange={(composing) => (placeholderComposing = composing)} + /> + {#if !greets} + <div class="mt-1 h-5"></div> + {:else if !isUnavailable && !session.archived && starterPrompts.suggestions.length > 0} + <div class="pt-2"> + <ComposerSuggestions + suggestions={starterPrompts.suggestions} + wrap + onPick={setPlaceholderText} + /> + </div> + {/if} + </div> + {#if greets} + <div class="flex-1 min-h-0"></div> + {/if} + </div> + {/if} </div> </Pane> </Splitpanes> diff --git a/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte b/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte index c35ee5a2fc..11f3219155 100644 --- a/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte +++ b/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte @@ -1059,7 +1059,10 @@ variant="subtle" unifiedSize="sm" destructive - disabled={model.deploying || !!staged[d.key]} + disabled={model.deploying || !!staged[d.key] || model.readOnly} + title={model.readOnly + ? 'A session in Use mode discards nothing. Switch it to Use & build to discard.' + : undefined} onclick={() => confirmDiscard(d)} > {action.secondary[0].label} diff --git a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte index 09fed8bba6..1edd4f9376 100644 --- a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte +++ b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte @@ -3,6 +3,7 @@ import { enterpriseLicense, maybePremium, + roleCapabilities, superadmin, userStore, userWorkspaces, @@ -19,14 +20,8 @@ import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte' import { canCreateFork } from '$lib/utils/editInFork' import { forkAccentStyle } from '$lib/utils/forkColor' - import { getUserExt } from '$lib/user' import { WorkspaceService } from '$lib/gen' - import { - fetchProtectionRulesForWorkspace, - isRuleActiveInRulesets, - canUserBypassRuleKindInRulesets - } from '$lib/workspaceProtectionRules.svelte' - import { resource } from 'runed' + import { useSessionReadOnly } from './sessionPermissions.svelte' import { isCloudHosted } from '$lib/cloud' import { random_adj } from '$lib/components/random_positive_adjetive' import DropdownV2 from '$lib/components/DropdownV2.svelte' @@ -141,35 +136,9 @@ return depth > 0 ? `padding-left: ${12 + depth * 16}px` : undefined } - // Judge the prod root off its OWN protection rules (fetched), not the active - // workspace's — so it reads correctly from a dev/fork too, the same way - // ParentWorkspaceProtectionAlert checks the parent. It's selectable when you - // can deploy to it, and "Fork from prod" shows when you can fork it. - const rootRulesetsResource = resource( - () => root?.id, - async (id) => (id ? await fetchProtectionRulesForWorkspace(id) : []) - ) - const rootRulesets = $derived(rootRulesetsResource.current ?? []) - // Bypass must be judged with the user's identity IN THE ROOT (is_admin/groups are per-workspace), - // not the active workspace's `$userStore` — otherwise an admin of the dev/active workspace who is a - // non-admin of the root would get a false bypass. `getUserExt` returns undefined for a non-member, - // which `canUserBypassRuleKindInRulesets` treats as no bypass. - const rootUserInfoResource = resource( - () => root?.id, - async (id) => (id ? await getUserExt(id) : undefined) - ) - const rootUserInfo = $derived(rootUserInfoResource.current) - const canDeployRoot = $derived( - !isRuleActiveInRulesets(rootRulesets, 'DisableDirectDeployment') || - canUserBypassRuleKindInRulesets(rootRulesets, 'DisableDirectDeployment', rootUserInfo) - ) - // A genuinely deploy-locked root (you can't deploy and can't bypass) is disabled regardless of - // whether a dev workspace exists to steer to — being deploy-locked is the gate, not dev presence. - // Roots with no rules resolve `canDeployRoot` to true, so ordinary families aren't affected. Kept - // disabled while either fetch is in flight (both default to the conservative locked state). - const rootDisabled = $derived( - rootRulesetsResource.loading || rootUserInfoResource.loading || !canDeployRoot - ) + // Judged off the root's OWN rules, so it reads correctly from a dev workspace or a fork too. + // A locked root stays selectable: its session is read-only. + const rootReadOnly = useSessionReadOnly(() => root?.id) // Structural gate: hidden in the admins workspace, or when the user can't fork; on cloud, forking // is premium-only (backend caps it per paid seat). DisableWorkspaceForking on the active workspace @@ -178,7 +147,7 @@ const forksGateOpen = $derived( (!isCloudHosted() || $maybePremium) && $workspaceStore !== 'admins' && - (canCreateFork($userStore) || !!devOfRoot) + (canCreateFork($userStore, $roleCapabilities) || !!devOfRoot) ) // A fork is a new workspace, so it's subject to the community-edition cap on // the number of non-'admins' workspaces (backend _check_nb_of_workspaces, @@ -234,7 +203,7 @@ if (row.kind === 'create') { requestCreateFork() } else if (row.kind === 'root') { - if (!rootDisabled) void pick(row.id) + void pick(row.id) } else if (row.kind === 'fork') { void pick(row.id) } @@ -404,20 +373,19 @@ <div class="relative group shrink-0"> <button type="button" - disabled={rootDisabled} - title={rootDisabled - ? devOfRoot - ? `${root.name} is locked. Run in its ${devLabelNoun(devOfRoot.dev_workspace_label)} instead.` - : `${root.name} is locked for direct deploys.` + title={rootReadOnly.known + ? `Sessions in ${root.name} can read and run deployed items, but not edit. Pick ${ + devOfRoot ? `its ${devLabelNoun(devOfRoot.dev_workspace_label)}` : 'a fork' + } to make changes.` : undefined} - class={`${rowBase} pr-8 ${rootDisabled ? 'opacity-50 cursor-not-allowed' : ''} ${isSelected(root.id) && !pendingFork ? 'bg-surface-selected' : ''} ${!rootDisabled && keyArrowPos === rootIdx ? 'bg-surface-hover' : !rootDisabled ? 'hover:bg-surface-hover' : ''}`} - onmouseenter={() => !rootDisabled && (keyArrowPos = rootIdx)} - onclick={() => !rootDisabled && void pick(root.id)} + class={`${rowBase} pr-8 ${isSelected(root.id) && !pendingFork ? 'bg-surface-selected' : ''} ${keyArrowPos === rootIdx ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`} + onmouseenter={() => (keyArrowPos = rootIdx)} + onclick={() => void pick(root.id)} > <Building size={14} class="shrink-0 text-tertiary" /> <span class="truncate">{root.name}</span> <span class="text-2xs text-tertiary shrink-0 ml-auto" - >{rootDisabled ? 'locked' : 'root'}</span + >{rootReadOnly.known ? 'read-only' : 'root'}</span > {#if isSelected(root.id) && !pendingFork} <Check size={14} class="shrink-0 text-accent" /> diff --git a/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts new file mode 100644 index 0000000000..3a923c0cbc --- /dev/null +++ b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts @@ -0,0 +1,50 @@ +import type { ContextElement } from '$lib/components/copilot/chat/context' +import type { BulkKind } from '$lib/components/home/homeSelection.svelte' + +/** Resolves once the element is in the draft, so several attach in the order given. */ +type Attach = (element: ContextElement) => Promise<void> + +/** What the composer can take as context from a workspace item: a script, a flow or a code + * app, as "+" → Mention file builds it. A visual-builder app or an agent has no context + * element, so it gets none. */ +export function itemContextElement(item: { + kind: BulkKind + path: string + summary?: string + rawApp?: boolean +}): ContextElement | undefined { + const type = + item.kind === 'script' + ? 'workspace_script' + : item.kind === 'flow' + ? 'workspace_flow' + : item.kind === 'app' && item.rawApp + ? 'workspace_app' + : undefined + if (!type) return undefined + return { type, path: item.path, title: item.path, summary: item.summary, deletable: true } +} + +let attach = $state<Attach | undefined>(undefined) + +/** + * The way from anywhere on Home into Home's composer: a row's "Ask AI" hands its item over + * here, and the composer takes it as context. Only a mounted composer registers, so a page + * whose composer is removed, hidden or not Home offers no button that would go nowhere. + */ +export const homeComposerContext = { + get available(): boolean { + return attach !== undefined + }, + async attach(element: ContextElement): Promise<void> { + await attach?.(element) + }, + /** Returns the unregister, which only clears its own registration: a remount registers + * the new composer before the old one is destroyed. */ + register(fn: Attach): () => void { + attach = fn + return () => { + if (attach === fn) attach = undefined + } + } +} diff --git a/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts b/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts new file mode 100644 index 0000000000..74a72ec0ce --- /dev/null +++ b/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts @@ -0,0 +1,96 @@ +import type { OnNavigate } from '@sveltejs/kit' +import { sessionState } from './sessionState.svelte' + +// Moving between Home and AI Sessions keeps the composer in sight: the browser +// snapshots the page before and after the navigation and glides the element that +// carries the `composer` view-transition-name on both sides (AIChatDisplay names it); +// the rest of the page cross-fades. The timing lives in app.css, keyed on the +// `data-home-sessions-transition` attribute set here for the length of the move. + +const HOME = '/' +const SESSIONS = '/sessions' + +/** Whether the composer had focus when the user left AI Sessions for Home. */ +let composerFocused = false + +/** The focus flag to keep after a navigation from `from` to `to`. Only the return to Home + * hands focus on — the sessions page focuses its composer on its own — and every other + * navigation clears the flag, so a later arrival on Home never acts on a stale one. */ +export function composerFocusAfter( + from: string | undefined, + to: string | undefined, + composerHadFocus: boolean +): boolean { + return from === SESSIONS && to === HOME && composerHadFocus +} + +/** Whether Home should give its composer the focus the sessions page's had. Read once: + * a later visit starts unfocused. */ +export function takeComposerFocus(): boolean { + const focused = composerFocused + composerFocused = false + return focused +} + +// A session that has sent its first message has a composer of its own, not Home's draft, so +// a move between it and Home is not one composer moving: its page names no composer. The one +// exception is the send from Home itself, which lands on that session already under way. +let sentFromHome = $state(false) + +/** Called by Home's composer as its send hands over to the session page. */ +export function composerSentFromHome(): void { + sentFromHome = true +} + +/** Whether the session page arriving now came from a send on Home, so its composer is the + * one Home just sent from. */ +export function arrivingFromHomeSend(): boolean { + return sentFromHome +} + +/** For SvelteKit's `onNavigate`: runs a move between Home and AI Sessions as a view + * transition. Any other navigation, or a browser without the API, is left alone. */ +export function homeSessionsTransition(navigation: OnNavigate): Promise<void> | undefined { + const from = navigation.from?.url.pathname + const to = navigation.to?.url.pathname + composerFocused = composerFocusAfter( + from, + to, + document.activeElement?.closest('[data-session-composer]') != null + ) + const direction = + from === HOME && to === SESSIONS + ? 'enter' + : from === SESSIONS && to === HOME + ? 'leave' + : undefined + // Good for the navigation the send started, and only that one. + if (direction !== 'enter') sentFromHome = false + if (!direction || navigation.willUnload || !document.startViewTransition) return + if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return + const root = document.documentElement + // To or from a session under way there is no composer to carry over: Home's would only + // fade out or in on its own, so the move drops every name and the page cross-fades as + // one. Leaving, the page says so; arriving, the session's record does (it has sent once + // it has a workspace), short of the send from Home that just started it. + const composerOnScreen = Array.from(document.querySelectorAll('[data-session-composer]')).some( + (el) => getComputedStyle(el).viewTransitionName === 'composer' + ) + const arrivingId = navigation.to?.url.searchParams.get('session') ?? sessionState.currentSessionId + const arrivingUnderWay = + !sentFromHome && !!sessionState.sessions.find((s) => s.id === arrivingId)?.workspace_id + const plain = direction === 'leave' ? !composerOnScreen : arrivingUnderWay + root.dataset.homeSessionsTransition = plain ? 'fade' : direction + return new Promise((resolve) => { + const transition = document.startViewTransition(async () => { + resolve() + await navigation.complete + }) + // Rejects when the navigation is cancelled or fails; the attribute goes either way. + const done = () => { + delete root.dataset.homeSessionsTransition + sentFromHome = false + } + void transition.finished.then(done, done) + }) +} diff --git a/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts b/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts new file mode 100644 index 0000000000..4be3f18fce --- /dev/null +++ b/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { composerFocusAfter } from './homeSessionsTransition.svelte' + +describe('composerFocusAfter', () => { + it('hands focus on only for the return from AI Sessions to Home', () => { + expect(composerFocusAfter('/sessions', '/', true)).toBe(true) + expect(composerFocusAfter('/sessions', '/', false)).toBe(false) + // Going to AI Sessions: that page focuses its own composer, so nothing is kept for Home. + expect(composerFocusAfter('/', '/sessions', true)).toBe(false) + // Any other navigation clears it, so a later arrival on Home never reads a stale flag. + expect(composerFocusAfter('/sessions', '/runs', true)).toBe(false) + expect(composerFocusAfter('/runs', '/', true)).toBe(false) + }) +}) diff --git a/frontend/src/lib/components/sessions/previewRouter.ts b/frontend/src/lib/components/sessions/previewRouter.ts index 6417903f94..9f50621de0 100644 --- a/frontend/src/lib/components/sessions/previewRouter.ts +++ b/frontend/src/lib/components/sessions/previewRouter.ts @@ -28,8 +28,8 @@ import { type PreviewItemRoute, type TriggerKind } from './previewPaths' -import type { UserExt, UserWorkspace } from '$lib/stores' -import { sidebarPageAllowed, type OperatorPageKey } from '../sidebar/operatorRoutes' +import type { UserWorkspace } from '$lib/stores' +import { capabilitiesIn, type CapabilitiesUser, type VisibilityKey } from '$lib/roleCapabilities' // Re-exported so the preview code that already reads locations through this module keeps // one import, while a caller needing only a path can reach for the leaf instead. export { @@ -122,20 +122,20 @@ export type PreviewPage = { label: string path: string icon: DrillIcon - /** The `operator_settings` key that admits an operator, as the sidebar reads it. */ - operatorKey?: OperatorPageKey + /** The role visibility flag that shows the page, as the sidebar reads it. */ + visibilityKey?: VisibilityKey adminOnly?: boolean } /** Whether `page` loads for `user` rather than showing its "not available" state. An unknown - * user is let through to every page but the admin-only ones. */ + * user is held to the workspace entry's role, and kept off the admin-only pages. */ export function previewPageAllowed( page: PreviewPage, - user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'> | undefined, + user: CapabilitiesUser | undefined, workspace: UserWorkspace | undefined ): boolean { - if (page.adminOnly) return !!user && (user.is_admin || user.is_super_admin) - return !page.operatorKey || sidebarPageAllowed(user?.operator, workspace, page.operatorKey) + if (page.adminOnly) return !!user && (!!user.is_admin || !!user.is_super_admin) + return !page.visibilityKey || capabilitiesIn(user, workspace).visibility[page.visibilityKey] } // Core workspace-level destinations the preview can route to. Intentionally @@ -143,15 +143,15 @@ export function previewPageAllowed( // EE/feature gating in SidebarContent and aren't worth duplicating here). export const PREVIEW_PAGES: PreviewPage[] = [ { label: 'Home', path: '/', icon: Home }, - { label: 'Runs', path: RUNS_PATH, icon: Play, operatorKey: 'runs' }, - { label: 'Variables', path: VARIABLES_PATH, icon: DollarSign, operatorKey: 'variables' }, - { label: 'Resources', path: RESOURCES_PATH, icon: Boxes, operatorKey: 'resources' }, - { label: 'Schedules', path: SCHEDULES_PATH, icon: Calendar, operatorKey: 'schedules' }, - { label: 'Assets', path: ASSETS_PATH, icon: Database, operatorKey: 'assets' }, - { label: 'Folders', path: FOLDERS_PATH, icon: FolderOpen, operatorKey: 'folders' }, - { label: 'Groups', path: GROUPS_PATH, icon: Users, operatorKey: 'groups' }, + { label: 'Runs', path: RUNS_PATH, icon: Play, visibilityKey: 'runs' }, + { label: 'Variables', path: VARIABLES_PATH, icon: DollarSign, visibilityKey: 'variables' }, + { label: 'Resources', path: RESOURCES_PATH, icon: Boxes, visibilityKey: 'resources' }, + { label: 'Schedules', path: SCHEDULES_PATH, icon: Calendar, visibilityKey: 'schedules' }, + { label: 'Assets', path: ASSETS_PATH, icon: Database, visibilityKey: 'assets' }, + { label: 'Folders', path: FOLDERS_PATH, icon: FolderOpen, visibilityKey: 'folders' }, + { label: 'Groups', path: GROUPS_PATH, icon: Users, visibilityKey: 'groups' }, { label: 'Workspace settings', path: WORKSPACE_SETTINGS_PATH, icon: Settings, adminOnly: true }, - { label: 'Audit logs', path: AUDIT_LOGS_PATH, icon: ScrollText, operatorKey: 'audit_logs' } + { label: 'Audit logs', path: AUDIT_LOGS_PATH, icon: ScrollText, visibilityKey: 'audit_logs' } ] // The Compare & Deploy review page. Kept out of PREVIEW_PAGES (it's not a picker diff --git a/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts b/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts index 4ade5552bf..487f80aaf8 100644 --- a/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts @@ -1,7 +1,6 @@ import { getDraftItems, type DraftItem } from '$lib/workspaceDrafts.svelte' -import { get } from 'svelte/store' -import { userWorkspaces } from '$lib/stores' import { roleCanAuthor } from '$lib/editRights' +import { capabilitiesInWorkspace } from '$lib/operatorWriteRights' import { checkDeployPermission, checkDeployRules, @@ -61,6 +60,13 @@ export interface SessionDeployModelArgs { /** Deploys a pipeline folder's draft bundle, which no per-item deploy can: it * expands into the folder's scripts and triggers. */ deployPipeline?: (folder: string) => Promise<DeployResult> + /** The session is in Use: its edits still show, but nothing deploys or discards. */ + readOnly?: boolean +} + +const USE_MODE_REFUSAL: DeployPermission = { + ok: false, + reason: 'A session in Use mode deploys nothing. Switch it to Use & build to deploy.' } export interface DiffValues { @@ -232,8 +238,8 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { // button disables with a reason instead of failing on click. `ok` defaults // true while resolving (fail-open). let deployPerm = $state<DeployPermission>({ ok: true }) - // `checkDeployPermission` refuses every operator, but flows.rs and apps.rs let one with the - // workspace's matching builder right deploy that kind, under the rules alone. + // `checkDeployPermission` refuses every role that cannot code, but flows.rs and apps.rs let one + // that composes that kind deploy it, under the rules alone. let builder = $state<{ perm: DeployPermission; kinds: Kind[] } | undefined>(undefined) let deployPermFetchedFor = '' $effect(() => { @@ -248,10 +254,8 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { void checkDeployPermission(ws).then(async (perm) => { if (deployPermFetchedFor !== ws) return deployPerm = perm - const settings = get(userWorkspaces).find((w) => w.id === ws)?.operator_settings - const kinds = (['flow', 'raw_app'] as const).filter((k) => - roleCanAuthor(k, { operator: true }, settings) - ) + const caps = capabilitiesInWorkspace(ws) + const kinds = (['flow', 'raw_app'] as const).filter((k) => roleCanAuthor(k, caps)) if (perm.refusedBy === 'operator' && kinds.length) { const rules = await checkDeployRules(ws) if (deployPermFetchedFor === ws) builder = { perm: rules, kinds } @@ -261,8 +265,10 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { }) function permissionFor(kind: Kind): DeployPermission { - if (builder?.kinds.includes(kind)) return deployPermissionForKind(builder.perm, kind) - return deployPermissionForKind(deployPerm, kind) + if (getArgs().readOnly) return USE_MODE_REFUSAL + const caps = capabilitiesInWorkspace(getArgs().workspaceId) + if (builder?.kinds.includes(kind)) return deployPermissionForKind(builder.perm, kind, caps) + return deployPermissionForKind(deployPerm, kind, caps) } // ── Deploy execution ───────────────────────────────────────────────────── @@ -307,7 +313,7 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { /** Deploy (or discard) a single item; returns whether it succeeded. */ async function deployOne(item: DeployItem, discard = false): Promise<boolean> { const plan = discard ? discardPlanFor(item) : deployPlanFor(item) - if (!plan) return false + if (!plan || getArgs().readOnly) return false // Snapshot before the await: the user may switch sessions while the // deploy runs, and the event belongs to the initiating session. const initiatingSessionId = sessionState.currentSessionId @@ -412,6 +418,10 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { deployPermissionForKind(kind: Kind): DeployPermission { return permissionFor(kind) }, + /** The session is in Use, so discarding is refused as deploying is. */ + get readOnly() { + return !!getArgs().readOnly + }, deployRow, discardRow } diff --git a/frontend/src/lib/components/sessions/sessionMirrorPlan.ts b/frontend/src/lib/components/sessions/sessionMirrorPlan.ts index 5d40c35e3b..1aa970aa47 100644 --- a/frontend/src/lib/components/sessions/sessionMirrorPlan.ts +++ b/frontend/src/lib/components/sessions/sessionMirrorPlan.ts @@ -79,8 +79,8 @@ export function isFallbackStorage(name: string): boolean { /** * The part of a session record the backup keeps. Left out on purpose: `name` (a * per-browser legacy label), the unsent-draft fields (`pending_*`, `draftPrompt`, - * `autoSendDraftAt`), `workspace_root_id` (derived on import), `transient`, `restoredAt` - * (this browser's clock), and the two fields reading a session bumps (`lastSeenCount`, + * `autoSendDraftAt`, `autoSendDomElement`), `workspace_root_id` (derived on import), + * `transient`, `restoredAt` (this browser's clock), and the two fields reading a session bumps (`lastSeenCount`, * `lastActivityAt`) — so opening a session and reading its new messages never costs a push. */ export type SessionHead = Pick< diff --git a/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts b/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts index caceb2e623..0db9ac09e7 100644 --- a/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts @@ -1,31 +1,89 @@ +import { getContext } from 'svelte' import { fromStore } from 'svelte/store' +import { resource } from 'runed' import { userWorkspaces } from '$lib/stores' import { useActingUser } from '$lib/actingUser.svelte' import { useEditRights } from '$lib/operatorWriteRights' +import { buildsAnything } from '$lib/editRights' +import { + isReadOnlySessionWorkspace, + settledReadOnlyVerdict +} from '$lib/components/copilot/chat/global/sessionAccess' +import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import type { WorkspaceItem } from '$lib/components/workspacePicker' import { previewPageAllowed, type PreviewPage } from './previewRouter' +/** Whether a session in `workspace` is read-only because the workspace is protected: the verdict + * `resolveSessionAccess` gives the chat, so the UI and the toolset agree. */ +export function useSessionReadOnly(workspace: () => string | undefined) { + const verdict = resource(workspace, async (ws) => + ws ? { workspace: ws, readOnly: await isReadOnlySessionWorkspace(ws) } : undefined + ) + // `resource` keeps the previous workspace's verdict while it asks about the next one. + const verdictFor = (ws: string): boolean | undefined => { + const landed = verdict.current + return landed?.workspace === ws ? landed.readOnly : settledReadOnlyVerdict(ws) + } + return { + /** Read-only, and also while the rules have not been read yet: the preview's writes wait + * for the lookup rather than race it. */ + get current() { + const ws = workspace() + return !!ws && (verdictFor(ws) ?? true) + }, + /** Read-only as far as is known, so false while the rules are read. For what only shows the + * verdict, the picker's lock or a label, which would otherwise flash a reason that is not + * true. */ + get known() { + const ws = workspace() + return !!ws && (verdictFor(ws) ?? false) + } + } +} + +/** The session chat whose work mode the session UI follows. */ +type WorkModeHost = { readonly workMode: AIWorkMode } + /** * What the session UI may offer in `workspace`. Its editors save drafts, so it reads * `roleCanDraft` / `canDraftItem` — the rule the chat's draft tools and `open_preview` follow — so * a control and the tool behind it never disagree. An unknown user reads as able to draft, as the toolset does before access * resolves: hiding every editor from a developer while `whoami` is in flight is the worse - * mistake, and the server refuses an operator anyway. Reads context and registers an effect: - * call during component initialisation. + * mistake, and the server refuses an operator anyway. A session held in Use opens no editor: one + * in a protected workspace, one whose role builds nothing there, or one whose chat is in Use + * mode — the chat `chat` returns, else the `aiChatManager` context's. + * Reads context and registers an effect: call during component initialisation. */ -export function useSessionPermissions(workspace: () => string | undefined) { +export function useSessionPermissions( + workspace: () => string | undefined, + chat?: () => WorkModeHost | undefined +) { + const contextChat = getContext<WorkModeHost | undefined>('aiChatManager') const rights = useEditRights(workspace) const user = useActingUser(workspace) + const protectedWorkspace = useSessionReadOnly(workspace) + const readOnly = $derived( + protectedWorkspace.current || + !buildsAnything(rights.capabilities) || + (chat?.() ?? contextChat)?.workMode === AIWorkMode.USE + ) const workspaces = fromStore(userWorkspaces) const entry = $derived(workspaces.current.find((w) => w.id === workspace())) return { + /** The session is read-only in this workspace. */ + get readOnly() { + return readOnly + }, /** Whether this user can save the drafts the `kind` editor writes. */ - canOpenEditor: (kind: string) => rights.roleCanDraft(kind), + canOpenEditor: (kind: string) => !readOnly && rights.roleCanDraft(kind), /** The same, and this item's own permissions let them write it. */ canEditItem: (item: Pick<WorkspaceItem, 'kind' | 'raw_app' | 'path' | 'extraPerms'>) => + !readOnly && rights.canDraftItem(item.raw_app ? 'raw_app' : item.kind, item.path, item.extraPerms), /** Whether the page loads for this user rather than refusing them. */ - pageAllowed: (page: PreviewPage) => previewPageAllowed(page, user.current, entry) + pageAllowed: (page: PreviewPage) => + // A read-only session reaches what an operator reaches: no admin page. + !(readOnly && page.adminOnly) && previewPageAllowed(page, user.current, entry) } } diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index f40882b95b..8be0b2836e 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -4,6 +4,7 @@ import { get } from 'svelte/store' import { invalidate as invalidateWorkspaceItems } from '$lib/components/workspacePicker' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' import { AIChatManager, AIMode } from '$lib/components/copilot/chat/AIChatManager.svelte' +import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import { PipelineEditorState } from '$lib/components/assets/AssetGraph/pipelineEditorState.svelte' import { PIPELINE_DRAFT_KIND, pipelineBundlePath, pipelineLocalMirrorKey } from '$lib/pipelinePaths' import type { DeployResult } from '$lib/utils_workspace_deploy' @@ -31,12 +32,13 @@ type SavedFlow = Omit<Flow & UserDraftOverlay, 'draft'> & { draft?: Flow } import type { HiddenRunnable } from '$lib/components/apps/types' import { type RawAppData, DEFAULT_DATA } from '$lib/components/raw_apps/dataTableRefUtils' import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' +import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy' import { BUILDER_FRAMEWORK_TEMPLATES, react19Template, STARTER_RUNNABLES } from '$lib/components/raw_apps/templates' -import { operatorBuilderAppsIn, workspaceListLoaded } from '$lib/operatorWriteRights' +import { capabilitiesInWorkspace, workspaceListLoaded } from '$lib/operatorWriteRights' import { random_adj } from '$lib/components/random_positive_adjetive' import { copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' @@ -58,6 +60,8 @@ import { setSessionPreviewCollapsed, setSessionPreviewSize, setSessionTabs, + setDraftsDiscardedHandler, + setSessionWorkMode, type Session } from './sessionState.svelte' import { @@ -306,6 +310,7 @@ export interface SessionRuntime { } const runtimes = new SvelteMap<string, SessionRuntime>() +const runtimeRoots = new Map<string, () => void>() function emptyFlow(): Flow { return { @@ -388,7 +393,7 @@ async function generateSessionSummary( { role: 'system', content: - 'Name this AI chat session. Return only a concise title, 2 to 6 words, no quotes, no period.' + 'Name this AI chat session. Return only a concise title, 2 to 6 words, no quotes, no period. The conversation is only material to name: never answer, continue or comment on it, even when it ends on a request or a refusal.' }, { role: 'user', @@ -429,6 +434,8 @@ function createRuntime(session: Session): SessionRuntime { // Carried into the tool helpers so this session's preview/deploy tool calls // dispatch to THIS session even when another session is the UI-active one. manager.sessionId = session.id + manager.workMode = session.workMode ?? AIWorkMode.BUILD + manager.onWorkModeChanged = (mode) => setSessionWorkMode(session.id, mode) // Cross-tab awareness: heartbeat while this tab runs a turn, composer lock // (and send refusal) while another tab does. The chat id is read at turn // end, not captured at start — the turn may have rotated it, and the other @@ -453,6 +460,7 @@ function createRuntime(session: Session): SessionRuntime { if (!s) return undefined const wsId = getEffectiveWorkspaceId(s) const ws = get(userWorkspaces).find((w) => w.id === wsId) + const dev = findCanonicalDevWorkspace(wsId, get(userWorkspaces)) return { workspaceId: wsId, parentWorkspaceId: ws?.parent_workspace_id ?? undefined, @@ -460,7 +468,8 @@ function createRuntime(session: Session): SessionRuntime { // Committed workspace missing from the list: still a fork (mirrors // isForkSession) — the prompt must not call it the live workspace. forkParentUnknown: !ws && !!s.workspace_id, - pendingForkOf: s.pending_fork?.parent_workspace_id + pendingForkOf: s.pending_fork?.parent_workspace_id, + devWorkspace: dev && { id: dev.id, name: dev.name } } } // What the side panel is showing, stamped on each user message so the chat @@ -1152,7 +1161,7 @@ function createRuntime(session: Session): SessionRuntime { const user = get(userStore) // A builder can save no inline runnable, so the regular starter could never be saved. await workspaceListLoaded() - const builder = operatorBuilderAppsIn(workspace) + const builder = capabilitiesInWorkspace(workspace).apps === 'compose' saved.val = undefined store.val = { files: { ...(builder ? BUILDER_FRAMEWORK_TEMPLATES.react19 : react19Template) }, @@ -1330,7 +1339,18 @@ async function initRuntime(runtime: SessionRuntime, session: Session) { export function getOrCreateRuntime(session: Session): SessionRuntime { let runtime = runtimes.get(session.id) if (!runtime) { - runtime = createRuntime(session) + // The manager's `$derived` fields belong to whatever effect is running when they are + // built. A runtime outlives the component that first asked for it (Home hands its + // session to /sessions and unmounts), so give it a root of its own; built inside the + // component, its deriveds turn inert once that component is gone. + let created: SessionRuntime | undefined + runtimeRoots.set( + session.id, + $effect.root(() => { + created = createRuntime(session) + }) + ) + runtime = created! runtimes.set(session.id, runtime) // The gate opens even when the restore fails: a session that cannot read its // history is still usable, and a send that waits forever is not. @@ -1347,6 +1367,8 @@ export function disposeRuntime(sessionId: string) { runtime.manager.cancel('runtime disposed') runtime.manager.historyManager.close() runtimes.delete(sessionId) + runtimeRoots.get(sessionId)?.() + runtimeRoots.delete(sessionId) // The sidebar reads the stored chat again rather than trust a read that // predates everything this runtime saw. peeks.delete(sessionId) @@ -1475,6 +1497,8 @@ export function removeSession(sessionId: string): void { deleteSessionState(sessionId) } +setDraftsDiscardedHandler((ids) => ids.forEach(disposeRuntime)) + // The chat calls a new item by its chosen name while its draft is stored at // `draft_<uuid>`; resolve the name the way the chat's write tools do. function draftStoragePath( diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index f032385d31..9f6bb07dd4 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -5,21 +5,16 @@ import { random_adj } from '$lib/components/random_positive_adjetive' import { enterpriseLicense, superadmin, - userStore, userWorkspaces, usersWorkspaceStore, workspaceStore, type UserWorkspace } from '$lib/stores' import { switchWorkspace } from '$lib/storeUtils' -import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy' -import { - isRuleActive, - canUserBypassRuleKind, - protectionRulesState -} from '$lib/workspaceProtectionRules.svelte' import { getLocalSetting, storeLocalSetting } from '$lib/utils' import { logFeatureUsage } from '$lib/utils/featureUsage' +import { isReadOnlySessionWorkspace } from '../copilot/chat/global/sessionAccess' +import { AIWorkMode } from '../copilot/chat/workMode' import { workspaceRootId } from './sessionScope.svelte' import { clearSessionRecovered } from './sessionRecoveryNotice.svelte' import { type DBSchema, type IDBPDatabase } from 'idb' @@ -28,6 +23,8 @@ import { emailOfScopedKey, scopedKeyFor } from '$lib/userScopedStorage' import { deleteItemsForSession } from '../copilot/chat/files/attachedFilesDB' import { deleteArtifactsForSession } from '../copilot/chat/artifacts/artifactsDB' import { deleteSessionChats } from '../copilot/chat/HistoryManager.svelte' +import type { DraftAttachments } from '../copilot/chat/messageDraft.svelte' +import type { AppDomSelectorElement } from '../copilot/chat/context' import { markSessionDirty, markSessionRemoved, @@ -101,6 +98,10 @@ export type Session = { // deferred to first send (via commitSessionWorkspace) so cancelling // the draft doesn't leave an orphan fork behind. pending_fork?: PendingFork + // Home's draft: it acts on whatever workspace Home shows, so a switch made on another page + // moves it on Home's next mount. Cleared by a pick made on the session page, whose picker + // leaves the navigation workspace where it is. + followsHome?: boolean // Stable root workspace id used only for sidebar grouping. Lifecycle follows // workspace_id, not this field. Root sessions store the same id in both fields. workspace_root_id?: string @@ -157,6 +158,8 @@ export type Session = { // Preview split size (preview pane %, 0-100) the user dragged for this session. // Per-session so each session restores its own layout. previewSize?: number + // Use or Build, as the chat's mode picker last left it. Absent reads as Build. + workMode?: AIWorkMode.USE | AIWorkMode.BUILD // Unsent composer text for a pending (uncommitted) session, persisted with // the record so each parallel draft restores its own typed-but-unsent prompt. // Only tracked while unsent; cleared once the workspace commits at first send. @@ -169,6 +172,10 @@ export type Session = { // would otherwise leave a session armed forever and fire on some later visit. // Consumed exactly once, by takeSessionAutoSend. autoSendDraftAt?: number + // The element a preview pick hands over with the auto-sent prompt, sent as its + // chip. Lives and dies with `autoSendDraftAt`: a prompt like "make this bigger" + // must never go out without the element it names. + autoSendDomElement?: AppDomSelectorElement } // One preview tab: `url` is the URL we command the iframe to load, `loc` the @@ -387,6 +394,32 @@ export function getSessionDraftPrompt(sessionId: string): string | undefined { return s.draftPrompt } +// The rest of an unsent draft (collapsed pastes, images, files), so a composer mounted again +// for the same session, on Home or the session page, gets the draft whole: a collapsed paste +// is a token in `draftPrompt` whose content lives here. In memory only, like the attachments +// themselves before a send, so a reload drops them as it always has. +const draftAttachments = new Map<string, DraftAttachments>() + +export function setSessionDraftAttachments(sessionId: string, attachments: DraftAttachments): void { + const empty = Object.values(attachments).every((lane) => lane.length === 0) + if (empty) { + draftAttachments.delete(sessionId) + return + } + const s = sessionState.sessions.find((x) => x.id === sessionId) + if (!s || s.workspace_id) return + draftAttachments.set(sessionId, attachments) + // Attaching is a touch, as typing is: a draft holding only an image would otherwise still + // read as a blank, be reused by the next hand-off with the image in it, or be dropped. + if (s.transient) persistTouched(s) +} + +export function getSessionDraftAttachments(sessionId: string): DraftAttachments | undefined { + const s = sessionState.sessions.find((x) => x.id === sessionId) + if (!s || s.workspace_id) return undefined + return draftAttachments.get(sessionId) +} + // A hand-off arrives within a navigation; anything older than this is the debris // of one that never landed, and must not fire at whatever the user does next. const AUTO_SEND_TTL_MS = 5 * 60_000 @@ -394,13 +427,19 @@ const AUTO_SEND_TTL_MS = 5 * 60_000 // Mark this session's draft prompt for sending on arrival. Written straight to // the record (not via setSessionDraftPrompt's debounce) because the navigation // that follows must not outrun it. -export function setSessionAutoSend(sessionId: string): void { +export function setSessionAutoSend(sessionId: string, domElement?: AppDomSelectorElement): void { const s = sessionState.sessions.find((x) => x.id === sessionId) if (!s) return s.autoSendDraftAt = Date.now() + s.autoSendDomElement = domElement persistTouched(s) } +// The element armed with the auto-send intent; read before takeSessionAutoSend clears both. +export function getSessionAutoSendDomElement(sessionId: string): AppDomSelectorElement | undefined { + return sessionState.sessions.find((x) => x.id === sessionId)?.autoSendDomElement +} + function autoSendIsFresh(s: Session | undefined): boolean { return !!s?.autoSendDraftAt && Date.now() - s.autoSendDraftAt < AUTO_SEND_TTL_MS } @@ -421,6 +460,7 @@ export function takeSessionAutoSend(sessionId: string): boolean { if (!s?.autoSendDraftAt) return false const fresh = autoSendIsFresh(s) delete s.autoSendDraftAt + delete s.autoSendDomElement persistTouched(s) return fresh } @@ -1060,6 +1100,9 @@ export function createSession(): Session { (s) => isDiscardableDraft(s) && sessionInCurrentFamily(s) ) if (reusable) { + // It may be Home's draft; asked for here, it is the session page's now, and callers + // park it on a workspace of their own that Home must not move it off. + delete reusable.followsHome sessionState.currentSessionId = reusable.id // The blank recovery just landed on is exactly what this reuses, so `+` // would otherwise hand back a session still carrying the recovery notice: @@ -1070,25 +1113,27 @@ export function createSession(): Session { requestComposerFocus() return reusable } + const session = newTransientSession() + sessionState.currentSessionId = session.id + return session +} + +// Told which never-touched drafts were dropped, so their runtimes go with them. Set by +// sessionRuntime, which imports this module and so cannot be imported back. Home builds a +// runtime for its draft on every mount, so a dropped draft would otherwise leave its +// manager and its history database handle open. +let onDraftsDiscarded: ((ids: string[]) => void) | undefined +export function setDraftsDiscardedHandler(handler: (ids: string[]) => void): void { + onDraftsDiscarded = handler +} + +function newTransientSession(): Session { + const discarded = sessionState.sessions.filter(isDiscardableDraft).map((s) => s.id) sessionState.sessions = sessionState.sessions.filter((s) => !isDiscardableDraft(s)) - // Start in the workspace you're in. The one exception: a root you can't - // deploy to (locked, no bypass) steers to its dev, since a session there - // couldn't edit anything. The picker lets you switch. - const currentWs = get(workspaceStore) - const devOfCurrent = currentWs - ? findCanonicalDevWorkspace(currentWs, get(userWorkspaces))?.id - : undefined - // Only trust the deploy check once the active workspace's rules have actually loaded: until then - // `isRuleActive` reads an empty ruleset and fails open, which would default a new session onto a - // locked prod. Treat "not yet loaded for currentWs" as not-deployable so we steer to the dev (always - // editable) when one exists; the picker still lets the user switch back once rules resolve. - const rulesLoadedForCurrent = - protectionRulesState.rulesets !== undefined && protectionRulesState.workspace === currentWs - const canDeployHere = - rulesLoadedForCurrent && - (!isRuleActive('DisableDirectDeployment') || - canUserBypassRuleKind('DisableDirectDeployment', get(userStore))) - const pending = devOfCurrent && !canDeployHere ? devOfCurrent : currentWs + if (discarded.length > 0) onDraftsDiscarded?.(discarded) + // Start in the workspace you're in, a locked production root included: the session is then + // read-only, and points the user to a new session in the dev workspace for changes. + const pending = get(workspaceStore) // Friendly default summary so the header reads like "Zippy session" // rather than "Untitled session" — assigned at create time, the user // can still rename it (or it gets overwritten by an editor target). @@ -1103,12 +1148,41 @@ export function createSession(): Session { transient: true } sessionState.sessions = [session, ...sessionState.sessions] - sessionState.currentSessionId = session.id // Transient until first touch: no DB record yet. Persisting is deferred to the // first user edit (the mutation helpers below route through persistTouched). return session } +/** The unsent session Home's composer writes into, so a prompt half-typed on Home is the + * one the empty session page shows, and the reverse. Never selects it: merely opening Home + * must not change which session the AI Sessions switch resumes. A session opened on an + * item (it carries preview tabs) is about that item, and one the session page picked onto + * another workspace of the family is about that workspace: Home acts on the workspace it + * shows, so it starts its own instead of moving either. */ +export function homeStarterSession(): Session { + const homeWs = get(workspaceStore) + const homes = (s: Session) => + (s.followsHome || s.pending_workspace_id === homeWs) && sessionInCurrentFamily(s) + const unsent = (s: Session) => + !s.archived && !s.workspace_id && !s.previewTabs?.length && homes(s) + const current = sessionState.sessions.find((s) => s.id === sessionState.currentSessionId) + // Stored but never sent: a draft the user touched, by typing or by picking where it acts. + // Either is theirs to come back to, and leaving it would strand it in the sidebar. + const touched = sessionState.sessions + .filter((s) => unsent(s) && !s.transient) + .sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))[0] + const draft = + (current && unsent(current) ? current : undefined) ?? + touched ?? + sessionState.sessions.find((s) => isDiscardableDraft(s) && homes(s)) ?? + newTransientSession() + if (!draft.followsHome) { + draft.followsHome = true + if (!draft.transient) void putSession(draft) + } + return draft +} + // Promote an in-memory transient session to a persisted IndexedDB record. // No-op when the session isn't transient (already persisted by a prior touch). // Called on the first genuine user touch (via persistTouched) and, idempotently, @@ -1130,6 +1204,13 @@ export function setSessionPendingWorkspace(id: string, workspace_id: string) { if (changed) persistTouched(s) } +export function stopFollowingHome(id: string) { + const s = sessionState.sessions.find((x) => x.id === id) + if (!s?.followsHome) return + delete s.followsHome + if (!s.transient) void putSession(s) +} + // Park a just-created session on a workspace. Deliberately does not persist a // still-transient draft: picking where it will live is part of creating it, not a // user touch, so an unused draft still vanishes on reload (see `transient`). @@ -1219,12 +1300,16 @@ export async function commitSessionWorkspace( // The draft prompt has been consumed as the first message. delete s.draftPrompt await putSession(s) - // A picked workspace can itself be an existing fork — classify by root. - logFeatureUsage('ai_session', 'created', { - key: ws === s.workspace_root_id ? 'root' : 'fork', - entityId: s.id, - workspace: ws - }) + // A picked workspace can itself be an existing fork — classify by root. A read-only root is + // counted apart, to see whether production sessions are used. + const sessionId = s.id + void isReadOnlySessionWorkspace(ws).then((readOnly) => + logFeatureUsage('ai_session', 'created', { + key: readOnly ? 'read_only' : ws === s.workspace_root_id ? 'root' : 'fork', + entityId: sessionId, + workspace: ws + }) + ) // The global workspaceStore is intentionally left untouched (see the fork // branch above): the session chat reads its committed workspace through the // manager's workspace resolver, not the active workspaceStore. @@ -1263,6 +1348,16 @@ export function setSessionPreviewSize(id: string, size: number): void { persistTouched(s) } +// Persist the session's Use or Build choice (a touch). Plan is left out: a reload ends the +// planning round, and the session reopens in the mode it was entered from. +export function setSessionWorkMode(id: string, mode: AIWorkMode): void { + if (mode === AIWorkMode.PLAN) return + const s = sessionState.sessions.find((x) => x.id === id) + if (!s || (s.workMode ?? AIWorkMode.BUILD) === mode) return + s.workMode = mode + persistTouched(s) +} + export function selectSession(id: string) { sessionState.currentSessionId = id } @@ -1457,6 +1552,7 @@ export function deleteSession(id: string) { // a draft deleted inside the debounce window. clearTimeout(draftPromptFlushHandles.get(id)) draftPromptFlushHandles.delete(id) + draftAttachments.delete(id) sessionState.sessions = sessionState.sessions.filter((x) => x.id !== id) if (sessionState.currentSessionId === id) { sessionState.currentSessionId = sessionState.sessions[0]?.id diff --git a/frontend/src/lib/components/sessions/sessionState.test.ts b/frontend/src/lib/components/sessions/sessionState.test.ts index 710028413e..5dd3570c6b 100644 --- a/frontend/src/lib/components/sessions/sessionState.test.ts +++ b/frontend/src/lib/components/sessions/sessionState.test.ts @@ -3,13 +3,18 @@ import { get } from 'svelte/store' import { commitSessionWorkspace, createSession, + setNewSessionWorkspace, decideSessionLifecycle, findEmptyLandingSession, + getSessionDraftAttachments, + homeStarterSession, isForkSession, isTearingDownOpenSession, renameSession, + setDraftsDiscardedHandler, sessionInCurrentFamily, setGeneratedSessionSummary, + setSessionDraftAttachments, setSessionDraftPrompt, sessionState, withOpenSessionTeardown, @@ -27,6 +32,10 @@ import { type UserWorkspace } from '$lib/stores' import { WorkspaceService } from '$lib/gen' +import type { DraftAttachments } from '$lib/components/copilot/chat/messageDraft.svelte' +import type { PasteAttachment } from '$lib/components/copilot/chat/pasteTokens' + +const NO_ATTACHMENTS: DraftAttachments = { pastes: [], images: [], files: [], blobs: [] } // Force createWorkspaceFork to fail so we can pin commitSessionWorkspace's // failure contract (the invariant the beforeSend abort fix relies on). @@ -451,6 +460,35 @@ describe('createSession — reuses an untouched draft, family-scoped', () => { } }) + it('does not reuse a draft that holds only an attachment', () => { + const restore = withTwoFamilies('rootA') + const prevCurrent = sessionState.currentSessionId + const attached = session({ + id: 'attachment-only', + name: 'session-904', + pending_workspace_id: 'forkA', + transient: true + }) + sessionState.sessions.push(attached) + let createdId: string | undefined + try { + setSessionDraftAttachments('attachment-only', { + ...NO_ATTACHMENTS, + pastes: [{} as PasteAttachment] + }) + createdId = createSession().id + expect(createdId).not.toBe('attachment-only') + expect(getSessionDraftAttachments('attachment-only')).toBeDefined() + } finally { + setSessionDraftAttachments('attachment-only', NO_ATTACHMENTS) + sessionState.sessions = sessionState.sessions.filter( + (s) => s.id !== 'attachment-only' && s.id !== createdId + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + it('clears the recovery notice off the draft it reuses, so `+` is not answered with "not found"', () => { const restore = withTwoFamilies('rootA') const prevCurrent = sessionState.currentSessionId @@ -674,3 +712,120 @@ describe('withOpenSessionTeardown — the gate that holds recovery off during a expect(isTearingDownOpenSession()).toBe(false) }) }) + +describe('homeStarterSession', () => { + it("shows the family's stored draft, not the conversation in view, and selects nothing", () => { + const restore = withTwoFamilies('forkA') + const prevCurrent = sessionState.currentSessionId + const conversation = session({ id: 'conversation', workspace_id: 'rootA' }) + // Touched only by picking where it acts: no text, but stored, so it is the user's draft. + const picked = session({ id: 'picked-draft', pending_workspace_id: 'forkA', lastActivityAt: 2 }) + const otherFamily = session({ + id: 'other-family-draft', + pending_workspace_id: 'rootB', + draftPrompt: 'elsewhere', + lastActivityAt: 3 + }) + sessionState.sessions.push(conversation, picked, otherFamily) + sessionState.currentSessionId = 'conversation' + try { + expect(homeStarterSession().id).toBe('picked-draft') + // Opening Home must leave the AI Sessions switch resuming the conversation. + expect(sessionState.currentSessionId).toBe('conversation') + } finally { + sessionState.sessions = sessionState.sessions.filter( + (s) => !['conversation', 'picked-draft', 'other-family-draft'].includes(s.id) + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + + it('leaves a draft picked onto another workspace of the family to that workspace', () => { + const restore = withTwoFamilies('rootA') + const prevCurrent = sessionState.currentSessionId + const picked = session({ id: 'picked-fork-draft', pending_workspace_id: 'forkA' }) + sessionState.sessions.push(picked) + sessionState.currentSessionId = 'picked-fork-draft' + let createdId: string | undefined + try { + createdId = homeStarterSession().id + expect(createdId).not.toBe('picked-fork-draft') + expect(picked.pending_workspace_id).toBe('forkA') + } finally { + sessionState.sessions = sessionState.sessions.filter( + (s) => !['picked-fork-draft', createdId].includes(s.id) + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + + it('keeps its own draft when the workspace was switched on another page', () => { + const restore = withTwoFamilies('forkA') + const typed = session({ + id: 'home-draft', + pending_workspace_id: 'rootA', + draftPrompt: 'typed on Home', + followsHome: true + }) + sessionState.sessions.push(typed) + try { + expect(homeStarterSession().id).toBe('home-draft') + } finally { + sessionState.sessions = sessionState.sessions.filter((s) => s.id !== 'home-draft') + restore() + } + }) + + it('lets go of its draft once the session page reuses it for a new session', () => { + const restore = withTwoFamilies('forkA') + const prevCurrent = sessionState.currentSessionId + const ids: string[] = [] + try { + ids.push(homeStarterSession().id) + const reused = createSession() + expect(reused.id).toBe(ids[0]) + setNewSessionWorkspace(reused.id, 'rootA') + ids.push(homeStarterSession().id) + expect(ids[1]).not.toBe(ids[0]) + expect(reused.pending_workspace_id).toBe('rootA') + } finally { + sessionState.sessions = sessionState.sessions.filter((s) => !ids.includes(s.id)) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + + it('reports the never-touched drafts it drops, so their runtimes can be disposed', () => { + const restore = withTwoFamilies('rootB') + const prevCurrent = sessionState.currentSessionId + const blank = session({ + id: 'blank-other-family', + pending_workspace_id: 'forkA', + transient: true + }) + const typed = session({ + id: 'typed-other-family', + pending_workspace_id: 'rootA', + draftPrompt: 'kept' + }) + sessionState.sessions.push(blank, typed) + const discarded: string[][] = [] + setDraftsDiscardedHandler((ids) => discarded.push(ids)) + let createdId: string | undefined + try { + // No draft of family B exists, so Home starts one, dropping family A's blank draft. + createdId = homeStarterSession().id + expect(discarded).toEqual([['blank-other-family']]) + expect(sessionState.sessions.some((s) => s.id === 'typed-other-family')).toBe(true) + } finally { + setDraftsDiscardedHandler(() => {}) + sessionState.sessions = sessionState.sessions.filter( + (s) => !['blank-other-family', 'typed-other-family', createdId].includes(s.id) + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) +}) diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index 30b7792487..2ef63bacfc 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -20,6 +20,10 @@ import { findMountedOpenInSessionSource } from './openInSessionContext' // Type-only: erased at compile time, so the component graph stays out of this // navigation seam (see the dynamic import in openEditorInSession). import type { OpenInSessionSource } from './OpenInSessionButton.svelte' +import type { AppDomSelectorElement } from '../copilot/chat/context' + +// `seedDomElement` rides only with `autoSend`: it is the chip of the prompt being sent. +type SeedOpts = { seedPrompt?: string; autoSend?: boolean; seedDomElement?: AppDomSelectorElement } // The session/navigation switch turns the global rail into either the workspace // navigation (navigation mode) or the sessions sidebar (session mode). Session @@ -171,7 +175,7 @@ export async function openEditorInSession( target: SessionTarget, workspaceId?: string, previewParams?: Record<string, string>, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise<void> { await openInSession( withPreviewParams(sessionTargetHref(target), previewParams), @@ -186,7 +190,7 @@ export async function openEditorInSession( export async function openPageInSession( href: string, workspaceId?: string, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise<void> { await openInSession(href, workspaceId, opts) } @@ -194,7 +198,7 @@ export async function openPageInSession( async function openInSession( url: string | undefined, workspaceId?: string, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise<void> { await goto(await sessionHrefFor(url, workspaceId, opts)) } @@ -212,7 +216,7 @@ export function editorSessionHref( async function sessionHrefFor( url: string | undefined, workspaceId?: string, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise<string> { // Seed the fresh session's preview with a single tab on `url` so it opens // straight onto what the caller wants (resetSessionPreviewTabs also writes @@ -221,7 +225,7 @@ async function sessionHrefFor( if (workspaceId) setSessionPendingWorkspace(session.id, workspaceId) if (opts?.seedPrompt) { setSessionDraftPrompt(session.id, opts.seedPrompt) - if (opts.autoSend) setSessionAutoSend(session.id) + if (opts.autoSend) setSessionAutoSend(session.id, opts.seedDomElement) } if (url) { // Dynamic import: a static one would drag the runtime's heavy graph @@ -243,12 +247,13 @@ async function sessionHrefFor( // step; `OpenInSessionButton` is the declarative equivalent. export async function openSourceInSession( source: OpenInSessionSource, - overrides?: { previewParams?: Record<string, string>; seedPrompt?: string; autoSend?: boolean } + overrides?: { previewParams?: Record<string, string> } & SeedOpts ): Promise<void> { await source.beforeOpen?.() const opts = { seedPrompt: overrides?.seedPrompt ?? source.seedPrompt, - autoSend: overrides?.autoSend ?? source.autoSend + autoSend: overrides?.autoSend ?? source.autoSend, + seedDomElement: overrides?.seedDomElement } if (source.target) { await openEditorInSession( @@ -267,15 +272,14 @@ export async function openSourceInSession( // composer. For entry points that carry a question rather than a target (the // global search's "Ask AI"). Always a new session rather than the most recent // one (`enterSessionMode`), so the seed cannot overwrite a prompt the user has -// already typed into a session they are mid-way through. +// already typed into a session they are mid-way through. `workspace` is the way +// out of a read-only session, whose workspace is fixed once it has started. export async function startSessionWithPrompt( prompt: string, - opts?: { autoSend?: boolean } + opts?: { autoSend?: boolean; workspace?: string } ): Promise<void> { - // No setSessionPendingWorkspace: createSession already picked the workspace, - // steering off a root the user cannot deploy to onto its dev. Overwriting it - // with the raw current workspace would land the session where it cannot edit. const session = createSession() + if (opts?.workspace) setSessionPendingWorkspace(session.id, opts.workspace) setSessionDraftPrompt(session.id, prompt) // An empty prompt has nothing to send; leave the composer focused instead. if (opts?.autoSend && prompt.trim()) setSessionAutoSend(session.id) diff --git a/frontend/src/lib/components/sessions/sessionSwitch.test.ts b/frontend/src/lib/components/sessions/sessionSwitch.test.ts index 497e3cbad9..3ee386a9ac 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.test.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.test.ts @@ -9,12 +9,14 @@ import { takeNewSessionSeed } from './sessionSwitch.svelte' import { + getSessionAutoSendDomElement, peekSessionAutoSend, sessionState, takeSessionAutoSend, type Session } from './sessionState.svelte' import { usersWorkspaceStore, workspaceStore, type UserWorkspace } from '$lib/stores' +import { createAppDomSelectorElement } from '../copilot/chat/context' vi.mock('$lib/navigation', () => ({ goto: vi.fn().mockResolvedValue(undefined) })) import { goto } from '$lib/navigation' @@ -176,6 +178,31 @@ describe('auto-send intent', () => { } }) + // A picked element names what the prompt is about ("make this bigger"): it must + // arrive with the prompt and be consumed with it, never outlive the intent. + it('carries a picked element with the prompt and clears it on claim', async () => { + const prevCurrent = sessionState.currentSessionId + let createdId: string | undefined + const el = createAppDomSelectorElement({ + selector: 'main > h1', + appPath: 'u/me/app', + tagName: 'H1' + }) + try { + await openSourceInSession( + { target: { kind: 'raw_app', path: 'u/me/app' } }, + { seedPrompt: 'make this bigger', autoSend: true, seedDomElement: el } + ) + createdId = sessionState.currentSessionId! + expect(getSessionAutoSendDomElement(createdId)).toEqual(el) + expect(takeSessionAutoSend(createdId)).toBe(true) + expect(getSessionAutoSendDomElement(createdId)).toBeUndefined() + } finally { + sessionState.sessions = sessionState.sessions.filter((s) => s.id !== createdId) + sessionState.currentSessionId = prevCurrent + } + }) + // `goto` resolves even when a beforeNavigate cancels it, so an abandoned // hand-off leaves the session armed. The claim must go stale rather than fire // a turn at whatever the user is doing whenever that session next opens. @@ -226,10 +253,9 @@ describe('startSessionWithPrompt', () => { vi.mocked(goto).mockClear() }) - // The hand-off must not re-pick the workspace: createSession already steers off - // a root the user cannot deploy to onto its dev, and overwriting that with the - // raw current workspace lands the session somewhere it cannot edit. - it('seeds the composer and keeps createSession’s workspace choice', async () => { + // A question asked on prod is answered against prod, in a read-only session, even + // when a dev workspace exists to make changes in. + it('seeds the composer and starts in the current workspace', async () => { const prevUsers = get(usersWorkspaceStore) const prevWs = get(workspaceStore) const prevCurrent = sessionState.currentSessionId @@ -244,7 +270,7 @@ describe('startSessionWithPrompt', () => { createdId = sessionState.currentSessionId const created = sessionState.sessions.find((s) => s.id === createdId) expect(created?.draftPrompt).toBe('list my flows') - expect(created?.pending_workspace_id).toBe('prod-dev') + expect(created?.pending_workspace_id).toBe('prod') } finally { sessionState.sessions = sessionState.sessions.filter((s) => s.id !== createdId) sessionState.currentSessionId = prevCurrent diff --git a/frontend/src/lib/components/sessions/workModeLock.svelte.ts b/frontend/src/lib/components/sessions/workModeLock.svelte.ts new file mode 100644 index 0000000000..e32645625b --- /dev/null +++ b/frontend/src/lib/components/sessions/workModeLock.svelte.ts @@ -0,0 +1,64 @@ +import { fromStore } from 'svelte/store' +import { userWorkspaces } from '$lib/stores' +import { useEditRights } from '$lib/operatorWriteRights' +import { buildsAnything } from '$lib/editRights' +import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy' +import type { WorkModeLock } from '../copilot/chat/workMode' +import { pickSessionWorkspace } from './SessionWorkspaceBar.svelte' +import { useSessionReadOnly } from './sessionPermissions.svelte' +import { getEffectiveWorkspaceId, type Session } from './sessionState.svelte' +import { startSessionWithPrompt } from './sessionSwitch.svelte' + +/** + * What holds a session's chat in Use, for its mode picker: a protected workspace, whose way + * out is its dev workspace, or a role that builds nothing there. `switchesWorkspace` is the + * session's workspace bar's: on Home, moving the session to the dev workspace moves the page + * too. Reads context and registers an effect: call during component initialisation. + */ +export function useWorkModeLock(session: () => Session | undefined, switchesWorkspace = false) { + const workspace = () => { + const s = session() + return s ? getEffectiveWorkspaceId(s) : undefined + } + const protectedWorkspace = useSessionReadOnly(workspace) + const rights = useEditRights(workspace) + const workspaces = fromStore(userWorkspaces) + const lock = $derived.by((): WorkModeLock | undefined => { + const s = session() + const ws = workspace() + // A staged fork is created at the first send and the session builds there, so nothing + // about the workspace it forks holds the session in Use. + if (!s || !ws || s.pending_fork) return undefined + if (protectedWorkspace.known) { + const dev = findCanonicalDevWorkspace(ws, workspaces.current) + if (!dev) + return { reason: 'This workspace is protected against direct changes. Build in a fork.' } + const label = `${dev.name} (dev)` + return { + reason: `This workspace is protected against direct changes. Build in ${label}.`, + // Until its first message a session can still change workspace; after it, only a new + // one can act elsewhere. + escape: s.workspace_id + ? { + label: `New session in ${label}`, + action: () => void startSessionWithPrompt('', { workspace: dev.id }) + } + : { + label: `Switch to ${label}`, + action: () => pickSessionWorkspace(s.id, dev.id, switchesWorkspace) + } + } + } + if (!buildsAnything(rights.capabilities)) { + return { + reason: "Your role can't build in this workspace. A workspace admin can change that." + } + } + return undefined + }) + return { + get current() { + return lock + } + } +} diff --git a/frontend/src/lib/components/settings/CreateToken.svelte b/frontend/src/lib/components/settings/CreateToken.svelte index 56952eb584..b8d512b799 100644 --- a/frontend/src/lib/components/settings/CreateToken.svelte +++ b/frontend/src/lib/components/settings/CreateToken.svelte @@ -1,19 +1,21 @@ <script lang="ts"> import { onMount, untrack } from 'svelte' import { userWorkspaces, usersWorkspaceStore, type UserWorkspace } from '$lib/stores' - import { Alert, Button, Skeleton } from '../common' + import { Button, Skeleton } from '../common' import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte' import Toggle from '../Toggle.svelte' import { SettingService, UserService, type NewToken } from '$lib/gen' import { mcpTokenUrlDisabled } from '$lib/mcpAuth' import TokenDisplay from './TokenDisplay.svelte' import ScopesPicker from './ScopesPicker.svelte' - import CopyableCodeBlock from '../details/CopyableCodeBlock.svelte' - import { shell } from 'svelte-highlight/languages' import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration' import TextInput from '../text_input/TextInput.svelte' import Select from '../select/Select.svelte' + import Section from '../Section.svelte' + import ClipboardPanel from '../details/ClipboardPanel.svelte' + import McpAccessPicker, { type McpAccess } from '../mcp/McpAccessPicker.svelte' + import MultiSelect from '../select/MultiSelect.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -44,16 +46,20 @@ displayCreateToken = true }: Props = $props() - // Sentinel workspace value meaning "all workspaces the user can access". - // Produces a workspace-less MCP token served through the /api/mcp/gateway - // endpoint, where tools take an explicit workspace_id argument. - const ALL_WORKSPACES = '*' - let newToken = $state<string | undefined>(undefined) let newMcpToken = $state<string | undefined>(undefined) + let newMcpTokenUrl = $state('') + // What an MCP token may do, as the access picker sets it. + let mcpAccess = $state<McpAccess>('full') + let mcpScopes = $state<string[]>(['mcp:all']) // What the user picked; `newTokenExpiration` is that pick held within the ceiling. let pickedExpiration = $state<number | undefined>(undefined) let newTokenWorkspace = $state<string | undefined>(untrack(() => defaultNewTokenWorkspace)) + // The workspaces an MCP token reaches. One binds the token to it; several leave it unbound + // and are listed in its scopes; all of them leaves it unbound with no list, so it also + // reaches the workspaces its owner joins later. + let mcpWorkspaces = $state<string[]>([]) + let mcpAllWorkspaces = $state(false) let mcpCreationMode = $state(false) let lastRequestedMcpMode = $state<boolean | undefined>(undefined) let mcpLabelAutofilled = $state(false) @@ -136,10 +142,11 @@ mcpCreationMode = true void loadMcpUrlPolicy() resetExpirationOnModeChange() - newTokenWorkspace = defaultNewTokenWorkspace ?? $operatingWorkspace + const current = defaultNewTokenWorkspace ?? $operatingWorkspace + mcpWorkspaces = current ? [current] : [] + mcpAllWorkspaces = false newToken = undefined newMcpToken = undefined - readOnly = false if (!newTokenLabel) { newTokenLabel = 'MCP token' mcpLabelAutofilled = true @@ -167,7 +174,9 @@ date = new Date(new Date().getTime() + newTokenExpiration * 1000) } - const tokenScopes = scopes ?? pickedScopes ?? undefined + const pickedOrFixed = scopes ?? (mcpMode ? mcpScopes : pickedScopes) ?? undefined + const tokenScopes = + pickedOrFixed && workspacesScope ? [...pickedOrFixed, workspacesScope] : pickedOrFixed const createdToken = await UserService.createToken({ requestBody: { @@ -175,13 +184,14 @@ expiration: date?.toISOString(), scopes: tokenScopes, workspace_id: tokenWorkspaceId, - read_only: readOnly + read_only: mcpMode ? false : readOnly } as NewToken }) if (mcpMode) { newToken = undefined newMcpToken = `${createdToken}` + newMcpTokenUrl = `${mcpUrl}?token=${createdToken}` } else { newMcpToken = undefined newToken = `${createdToken}` @@ -197,13 +207,15 @@ } const workspaces = $derived(ensureCurrentWorkspaceIncluded($userWorkspaces, $operatingWorkspace)) - const isAllWorkspaces = $derived(newTokenWorkspace === ALL_WORKSPACES) - const tokenWorkspaceId = $derived( - isAllWorkspaces - ? undefined - : mcpCreationMode - ? newTokenWorkspace || $operatingWorkspace - : newTokenWorkspace + const mcpBoundWorkspace = $derived( + !mcpAllWorkspaces && mcpWorkspaces.length === 1 ? mcpWorkspaces[0] : undefined + ) + const mcpReachesWorkspaces = $derived(mcpAllWorkspaces || mcpWorkspaces.length > 0) + const tokenWorkspaceId = $derived(mcpCreationMode ? mcpBoundWorkspace : newTokenWorkspace) + const workspacesScope = $derived( + mcpCreationMode && !mcpAllWorkspaces && mcpWorkspaces.length > 1 + ? `mcp:workspaces:${mcpWorkspaces.join(',')}` + : undefined ) // Mirrors the server's exemption for tokens owned by a service account: one in the workspace @@ -236,25 +248,21 @@ ? maxExpirationSecs : pickedExpiration ) - // The workspace used to browse scripts/flows/endpoints in the scope picker. - // For an all-workspaces token there is no single workspace, so fall back to - // the current one just for populating the endpoint list. + // The workspace used to browse scripts/flows/endpoints in the scope picker: the first + // picked one, or the current one for a token reaching all of them. const scopeWorkspaceId = $derived( - isAllWorkspaces ? $operatingWorkspace || '' : newTokenWorkspace || $operatingWorkspace || '' + (mcpCreationMode && !mcpAllWorkspaces ? mcpWorkspaces[0] : newTokenWorkspace) || + $operatingWorkspace || + '' ) - // Undefined wherever the workspace is: `/api/mcp/w/undefined/mcp` reads like a real URL - // and is copyable, so the OAuth panel withholds it rather than showing a broken one. The - // token branch guards the same case by disabling its generate button. // On the browsing origin, not the API base url: the OAuth metadata the server // publishes for this URL is built from `base_url`, and a client rejects a mismatch. - const mcpUrl = $derived( - isAllWorkspaces - ? `${window.location.origin}/api/mcp/gateway` - : newTokenWorkspace - ? `${window.location.origin}/api/mcp/w/${newTokenWorkspace}/mcp` - : undefined + // One URL whatever the access: the token's scopes decide which tools it gets. + const mcpUrl = `${window.location.origin}/api/mcp` + // Selected scripts and flows are listed per workspace: across several, a path could be two. + const selectionNeedsOneWorkspace = $derived( + mcpAccess === 'selected' && (mcpAllWorkspaces || mcpWorkspaces.length !== 1) ) - const mcpBaseUrl = $derived(`${mcpUrl ?? ''}?token=`) $effect(() => { const requestedMcpMode = mcpOnly || openWithMcpMode @@ -278,13 +286,87 @@ }) </script> +{#snippet mcpTokenForm()} + <div class="flex flex-col gap-3"> + <McpAccessPicker + workspaceId={scopeWorkspaceId} + bind:scopes={mcpScopes} + bind:access={mcpAccess} + /> + {#if !lockWorkspace} + {@render mcpWorkspacePicker()} + {#if selectionNeedsOneWorkspace} + <p class="text-2xs text-secondary"> + Selected scripts and flows come from one workspace: pick one. + </p> + {/if} + {/if} + {#if !mcpOnly} + <div> + <span class="block mb-1 text-emphasis text-xs font-semibold" + >Label <span class="text-xs text-primary">(optional)</span></span + > + <TextInput inputProps={{ type: 'text' }} bind:value={newTokenLabel} class="w-full" /> + </div> + {/if} + {#if maxExpirationSecs != undefined} + <div> + <span class="block mb-1 text-xs text-emphasis font-semibold">Expires In</span> + <Select + bind:value={() => newTokenExpiration, (v) => (pickedExpiration = v)} + placeholder="Pick an expiration" + inputClass="w-full" + items={expirationItems} + /> + <p class="mt-1 text-xs text-tertiary" + >This instance limits tokens to {maxExpirationLabel}.</p + > + </div> + {/if} + <div class="flex"> + <Button + onclick={() => createToken(true)} + disabled={!mcpReachesWorkspaces || selectionNeedsOneWorkspace || mcpScopes.length === 0} + variant="default" + unifiedSize="sm" + > + Generate URL with token + </Button> + </div> + </div> +{/snippet} + +{#snippet mcpWorkspacePicker()} + <div class="flex flex-col gap-1"> + <span class="block text-emphasis text-xs font-semibold">Workspaces</span> + <Toggle + bind:checked={mcpAllWorkspaces} + options={{ right: 'All my workspaces, including ones I join later' }} + size="xs" + /> + {#if !mcpAllWorkspaces} + <MultiSelect + bind:value={mcpWorkspaces} + items={workspaces.map((w) => ({ label: w.name, value: w.id }))} + placeholder="Pick workspaces" + reorderable={false} + /> + {/if} + {#if mcpAllWorkspaces || mcpWorkspaces.length > 1} + <p class="text-xs text-tertiary"> + Tools take a <code>workspace_id</code> argument naming the workspace they act in. + </p> + {/if} + </div> +{/snippet} + <div> <!-- Stays bounded by the panel width: a content-driven width (min-w-min) would let a long scope chip stretch this card and push the rest of the form out of view. --> - <div class="p-4 rounded-md mb-6 bg-surface-tertiary"> - <h3 class="pb-2 font-semibold text-emphasis text-sm"> - {mcpCreationMode && mcpUrlPolicy !== 'token' ? 'MCP URL' : title} - </h3> + <div class="p-4 rounded-md bg-surface-tertiary {!mcpOnly || newMcpToken ? 'mb-6' : ''}"> + {#if !mcpOnly} + <h3 class="pb-2 font-semibold text-emphasis text-sm">{title}</h3> + {/if} {#if showMcpMode && !mcpOnly} <div @@ -316,37 +398,30 @@ {#if mcpCreationMode && mcpUrlPolicy === 'loading'} <Skeleton layout={[[2], 0.5, [1]]} /> - {:else if mcpCreationMode && mcpUrlPolicy === 'oauth'} - {#if !lockWorkspace} - <div class="mb-4 max-w-md"> - <span class="block mb-1 text-emphasis text-xs font-semibold">Workspace</span> - <!-- No all-workspaces entry: the gateway's consent screen binds the token it issues - to the one workspace picked there, so OAuth has no multi-workspace grant to offer. --> - <Select - bind:value={newTokenWorkspace} - items={workspaces.map((w) => ({ label: w.name, value: w.id, subtitle: w.id }))} - /> + {:else if mcpCreationMode} + <div class="flex flex-col gap-6"> + <div class="flex flex-col gap-1"> + <span class="text-xs font-semibold text-emphasis">MCP URL</span> + <ClipboardPanel content={mcpUrl} size="sm" /> + <p class="text-2xs text-secondary"> + Add it to your client as a remote MCP server. It opens a Windmill page where you sign in + and choose the workspaces and what the client may do: build and run, read and run, read + only, or only the scripts and flows you pick. + </p> </div> - {/if} - {#if mcpUrl} - <CopyableCodeBlock code={mcpUrl} language={shell} wrap /> + {#if mcpUrlPolicy === 'token'} + <Section label="Use a token instead of signing in" small collapsable collapsed> + {@render mcpTokenForm()} + </Section> + {/if} - <div class="mt-2"> - <Alert type="info" title="This instance requires MCP clients to sign in" size="xs"> - Paste this URL into your client. It opens a Windmill page where you approve the access - it asks for, and no token needs to be copied around. - </Alert> - </div> - {:else} - <p class="text-xs text-tertiary">Pick a workspace to get its MCP URL.</p> - {/if} - - {#if !mcpOnly} - <div class="mt-4 flex justify-end gap-2 flex-row"> - <Button onClick={exitMcpMode} variant="default">Cancel</Button> - </div> - {/if} + {#if !mcpOnly} + <div class="flex justify-end"> + <Button onClick={exitMcpMode} variant="default">Cancel</Button> + </div> + {/if} + </div> {:else} {#if scopes != undefined} <div class="mb-4"> @@ -370,7 +445,7 @@ {#if !scopes || scopes.length === 0} <ScopesPicker - mode={mcpCreationMode ? 'mcp' : 'standard'} + mode="standard" workspaceId={scopeWorkspaceId} bind:value={pickedScopes} bind:readOnly @@ -378,31 +453,6 @@ {/if} <div class="mt-2 grid grid-cols-1 md:grid-cols-2 gap-4"> - {#if mcpCreationMode} - {#if !lockWorkspace} - <div> - <span class="block mb-1 text-emphasis text-xs font-semibold">Workspace</span> - <Select - bind:value={newTokenWorkspace} - items={[ - { - label: 'All workspaces', - value: ALL_WORKSPACES, - subtitle: 'Multi-workspace' - }, - ...workspaces.map((w) => ({ label: w.name, value: w.id, subtitle: w.id })) - ]} - /> - {#if isAllWorkspaces} - <p class="mt-1 text-xs text-tertiary"> - This token works across every workspace you can access. Tools take a - <code>workspace_id</code> argument; call <code>list_workspaces</code> to discover them. - </p> - {/if} - </div> - {/if} - {/if} - {#if !mcpOnly} <div> <span class="block mb-1 text-emphasis text-xs font-semibold" @@ -412,27 +462,25 @@ </div> {/if} - {#if !mcpCreationMode || maxExpirationSecs != undefined} - <div> - <span class="block mb-1 text-xs text-emphasis font-semibold"> - Expires In - {#if maxExpirationSecs == undefined} - <span class="text-xs text-primary">(optional)</span> - {/if} - </span> - <Select - bind:value={() => newTokenExpiration, (v) => (pickedExpiration = v)} - placeholder={maxExpirationSecs == undefined ? 'No expiration' : 'Pick an expiration'} - inputClass="w-full" - items={expirationItems} - /> - {#if maxExpirationSecs != undefined} - <p class="mt-1 text-xs text-tertiary"> - This instance limits tokens to {maxExpirationLabel}. - </p> + <div> + <span class="block mb-1 text-xs text-emphasis font-semibold"> + Expires In + {#if maxExpirationSecs == undefined} + <span class="text-xs text-primary">(optional)</span> {/if} - </div> - {/if} + </span> + <Select + bind:value={() => newTokenExpiration, (v) => (pickedExpiration = v)} + placeholder={maxExpirationSecs == undefined ? 'No expiration' : 'Pick an expiration'} + inputClass="w-full" + items={expirationItems} + /> + {#if maxExpirationSecs != undefined} + <p class="mt-1 text-xs text-tertiary"> + This instance limits tokens to {maxExpirationLabel}. + </p> + {/if} + </div> </div> <div class="mt-4 flex justify-end gap-2 flex-row"> @@ -446,13 +494,7 @@ Cancel </Button> {/if} - <Button - on:click={() => createToken(mcpCreationMode)} - disabled={mcpCreationMode && (newTokenWorkspace == undefined || !pickedScopes)} - variant="accent" - > - {mcpCreationMode ? 'Generate MCP URL' : 'New token'} - </Button> + <Button on:click={() => createToken()} variant="accent">New token</Button> </div> {/if} </div> @@ -462,6 +504,6 @@ {/if} {#if newMcpToken && displayCreateToken} - <TokenDisplay token={newMcpToken} mcpUrl={`${mcpBaseUrl}${newMcpToken}`} /> + <TokenDisplay token={newMcpToken} mcpUrl={newMcpTokenUrl} /> {/if} </div> diff --git a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte index 44a44a7937..46ad5b4720 100644 --- a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte +++ b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte @@ -6,6 +6,7 @@ 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 { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -41,8 +42,29 @@ let labelValue = $state('') let pickedScopes = $state<string[] | null>(null) + let mcpScopes = $state<string[]>([]) let saving = $state(false) + // The access picker re-derives a token's scopes from what it can show, which drops what it + // does not model (an old token's endpoint list, say). So they are rewritten only once the + // user has used the picker; until then the token keeps exactly the scopes it had. + let mcpTouched = $state(false) + // 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. + const isWorkspaceList = (s: string) => s.startsWith('mcp:workspaces:') + const keptAside = (s: string) => + isWorkspaceList(s) || + s === MCP_SESSION || + (mcpAccessOf(mcpScopes) !== 'selected' && s.startsWith('mcp:hub:')) + const scopesToSave = $derived( + isMcp + ? mcpTouched + ? [...mcpScopes, ...(initialScopes ?? []).filter(keptAside)] + : (initialScopes ?? []) + : pickedScopes + ) + // Seed the label field from the token whenever the modal opens or the token // identity changes (untracked read so typing doesn't reset it). ScopesPicker // seeds itself via the `{#key tokenPrefix}` remount below. @@ -51,6 +73,7 @@ if (open) { untrack(() => { labelValue = initialLabel ?? '' + mcpTouched = false }) } }) @@ -69,7 +92,7 @@ try { const trimmed = labelValue.trim() const labelChanged = labelEditable && trimmed !== (initialLabel ?? '') - const scopesChanged = !scopesEqual(pickedScopes, initialScopes ?? null) + const scopesChanged = !scopesEqual(scopesToSave, initialScopes ?? null) if (labelChanged) { await UserService.updateTokenLabel({ @@ -80,7 +103,7 @@ if (scopesChanged) { await UserService.updateTokenScopes({ tokenPrefix, - requestBody: { scopes: pickedScopes } + requestBody: { scopes: scopesToSave } }) } if (labelChanged || scopesChanged) { @@ -95,7 +118,7 @@ } } - const saveDisabled = $derived(saving || !tokenPrefix || (isMcp && !pickedScopes)) + const saveDisabled = $derived(saving || !tokenPrefix || (isMcp && mcpScopes.length === 0)) </script> <Modal bind:open title="Edit token" class="!max-w-3xl"> @@ -117,14 +140,30 @@ </div> <div class="flex flex-col gap-1"> - <span class="text-xs font-semibold text-emphasis">Scopes</span> + {#if !isMcp} + <span class="text-xs font-semibold text-emphasis">Scopes</span> + {/if} {#key tokenPrefix} - <ScopesPicker - mode={isMcp ? 'mcp' : 'standard'} - workspaceId={mcpWorkspaceId} - {initialScopes} - bind:value={pickedScopes} - /> + {#if isMcp} + <div + role="group" + onpointerdown={() => (mcpTouched = true)} + onkeydown={() => (mcpTouched = true)} + > + <McpAccessPicker + workspaceId={mcpWorkspaceId} + initialScopes={(initialScopes ?? []).filter((s) => !isWorkspaceList(s))} + bind:scopes={mcpScopes} + /> + </div> + {:else} + <ScopesPicker + mode="standard" + workspaceId={mcpWorkspaceId} + {initialScopes} + bind:value={pickedScopes} + /> + {/if} {/key} </div> </div> diff --git a/frontend/src/lib/components/settings/ForkMemberSettings.svelte b/frontend/src/lib/components/settings/ForkMemberSettings.svelte index 69d911dffc..8603980bb5 100644 --- a/frontend/src/lib/components/settings/ForkMemberSettings.svelte +++ b/frontend/src/lib/components/settings/ForkMemberSettings.svelte @@ -7,7 +7,8 @@ import Cell from '$lib/components/table/Cell.svelte' import Popover from '$lib/components/meltComponents/Popover.svelte' import Select from '$lib/components/select/Select.svelte' - import type { User } from '$lib/gen' + import type { EffectiveRole, User } from '$lib/gen' + import { loadWorkspaceRoles, pickerValue, roleLabel } from '$lib/workspaceRoles' import { UserService, WorkspaceService } from '$lib/gen' import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' @@ -32,10 +33,16 @@ .map((c) => ({ value: c.email, label: `${c.username} (${c.email})` })) ) + let roles: EffectiveRole[] | undefined = $state(undefined) + async function loadMembers(workspace: string): Promise<void> { - const loaded = await UserService.listUsers({ workspace }) + const [loaded, workspaceRoles] = await Promise.all([ + UserService.listUsers({ workspace }), + loadWorkspaceRoles(workspace).catch(() => undefined) + ]) if (workspace !== $workspaceStore) return members = loaded + roles = workspaceRoles?.roles } async function loadCandidates(workspace: string, parent: string): Promise<void> { @@ -167,7 +174,7 @@ <tbody> {#if members} {#each members as member (member.email)} - {@const { email, username, is_admin, operator } = member} + {@const { email, username, is_admin } = member} <tr class="bg-surface"> <Cell first> {#if member.is_service_account} @@ -184,7 +191,7 @@ </Cell> <Cell> <Badge color="blue"> - {is_admin ? 'Admin' : operator ? 'Operator' : 'Developer'} + {roleLabel(roles, pickerValue(member))} </Badge> </Cell> <Cell last actions> diff --git a/frontend/src/lib/components/settings/RoleCapabilitiesEditor.svelte b/frontend/src/lib/components/settings/RoleCapabilitiesEditor.svelte new file mode 100644 index 0000000000..a9fc0e9911 --- /dev/null +++ b/frontend/src/lib/components/settings/RoleCapabilitiesEditor.svelte @@ -0,0 +1,227 @@ +<script lang="ts"> + import { Badge, Button } from '$lib/components/common' + import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' + import Toggle from '$lib/components/Toggle.svelte' + import type { + AuthorLevel, + RoleCapabilities, + RoleCapabilitiesPatch, + RoleVisibility + } from '$lib/gen' + import { + applyCapabilitiesPatch, + capabilitiesError, + isEmptyPatch, + VISIBILITY_KEYS + } from '$lib/workspaceRoles' + import { RotateCcw } from 'lucide-svelte' + + interface Props { + /** The layer an unset field falls through to. */ + base: RoleCapabilities + /** Fields whose `base` value is not known here, as `code` or `visibility.runs`. */ + unknownBase?: string[] + patch: RoleCapabilitiesPatch + /** What the layer below is called: "default" on the instance, "instance" in a workspace. */ + baseName: string + /** Marks a field this layer sets, and one it leaves to `base`. */ + setText: string + inheritedText: string + disabled?: boolean + onchange?: (patch: RoleCapabilitiesPatch) => void + } + + let { + base, + unknownBase = [], + patch, + baseName, + setText, + inheritedText, + disabled = false, + onchange + }: Props = $props() + + const effective = $derived(applyCapabilitiesPatch(base, patch)) + const error = $derived(capabilitiesError(effective)) + + type BoolKey = 'code' | 'manage_schedules' | 'manage_triggers' + type LevelKey = 'flows' | 'apps' + + function boolValue(path: string): boolean { + if (path.startsWith('visibility.')) { + return effective.visibility[path.slice('visibility.'.length) as keyof RoleVisibility] + } + return effective[path as BoolKey] + } + + function isSet(path: string): boolean { + if (path.startsWith('visibility.')) { + return patch.visibility?.[path.slice('visibility.'.length)] != null + } + return patch[path as keyof RoleCapabilitiesPatch] != null + } + + function update(path: string, value: boolean | AuthorLevel | undefined) { + const next: RoleCapabilitiesPatch = structuredClone($state.snapshot(patch)) + if (path.startsWith('visibility.')) { + const vis = { ...(next.visibility ?? {}) } + const k = path.slice('visibility.'.length) + if (value === undefined) delete vis[k] + else vis[k] = value as boolean + next.visibility = Object.keys(vis).length > 0 ? vis : undefined + if (next.visibility === undefined) delete next.visibility + } else if (value === undefined) { + delete next[path as keyof RoleCapabilitiesPatch] + } else { + ;(next as Record<string, unknown>)[path] = value + } + onchange?.(next) + } + + function resetAll() { + onchange?.({}) + } + + const authoring: { key: BoolKey | LevelKey; label: string; description: string }[] = [ + { + key: 'code', + label: 'Write code', + description: + 'Author scripts and run code of their own: previews, dependency jobs, dynamic selects. Required for full flow or app authoring.' + }, + { + key: 'flows', + label: 'Flows and AI agents', + description: + 'Compose builds flows and AI agents out of deployed scripts and flows, without code of their own.' + }, + { + key: 'apps', + label: 'Apps', + description: + 'Compose builds full-code apps out of deployed runnables, always sandboxed. Low-code apps need full.' + } + ] + + const management: { key: BoolKey; label: string; description: string }[] = [ + { + key: 'manage_schedules', + label: 'Manage schedules', + description: 'Create, edit and delete schedules where folder permissions allow.' + }, + { + key: 'manage_triggers', + label: 'Manage triggers', + description: 'Create, edit and delete triggers where folder permissions allow.' + } + ] +</script> + +{#snippet status(path: string)} + <div class="flex items-center justify-end gap-1 w-32 shrink-0"> + {#if isSet(path)} + <Badge color="blue" verySmall>{setText}</Badge> + <Button + variant="subtle" + unifiedSize="xs" + iconOnly + startIcon={{ icon: RotateCcw }} + title="Reset to the {baseName} value" + aria-label="Reset to the {baseName} value" + {disabled} + onclick={() => update(path, undefined)} + /> + {:else if unknownBase.includes(path)} + <span class="text-2xs text-hint text-right">{inheritedText}, shown after saving</span> + {:else} + <span class="text-2xs text-hint">{inheritedText}</span> + {/if} + </div> +{/snippet} + +{#snippet row(label: string, description: string | undefined, path: string)} + <div class="flex items-center gap-4 py-1.5"> + <div class="flex flex-col grow min-w-0"> + <span class="text-xs font-semibold text-emphasis">{label}</span> + {#if description} + <span class="text-2xs text-secondary">{description}</span> + {/if} + </div> + <div class="flex justify-end w-60 shrink-0"> + {#if path === 'flows' || path === 'apps'} + {@const key = path as LevelKey} + <ToggleButtonGroup + {disabled} + selected={effective[key]} + onSelected={(v) => update(key, v as AuthorLevel)} + > + {#snippet children({ item })} + <ToggleButton value="none" label="None" small {item} /> + <ToggleButton value="compose" label="Compose" small {item} /> + <ToggleButton + value="full" + label="Full" + small + disabled={!effective.code} + tooltip={effective.code ? undefined : 'Requires the code capability'} + {item} + /> + {/snippet} + </ToggleButtonGroup> + {:else} + <Toggle + size="xs" + {disabled} + checked={boolValue(path)} + on:change={(e) => update(path, e.detail)} + /> + {/if} + </div> + {@render status(path)} + </div> +{/snippet} + +<div class="flex flex-col gap-4"> + <div class="flex flex-col divide-y"> + <span class="text-xs font-semibold text-secondary pb-1">Authoring</span> + {#each authoring as f (f.key)} + {@render row(f.label, f.description, f.key)} + {/each} + </div> + {#if error} + <span class="text-xs text-red-600 dark:text-red-400">{error}</span> + {/if} + + <div class="flex flex-col divide-y"> + <span class="text-xs font-semibold text-secondary pb-1">Management</span> + {#each management as f (f.key)} + {@render row(f.label, f.description, f.key)} + {/each} + </div> + + <div class="flex flex-col divide-y"> + <span class="text-xs font-semibold text-secondary pb-1"> + Pages in their menu + <span class="font-normal">(hides a page, does not block the API)</span> + </span> + {#each VISIBILITY_KEYS as v (v.key)} + {@render row(v.label, undefined, `visibility.${v.key}`)} + {/each} + </div> + + {#if !isEmptyPatch(patch)} + <div> + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: RotateCcw }} + {disabled} + onclick={resetAll} + > + Reset all to the {baseName} values + </Button> + </div> + {/if} +</div> diff --git a/frontend/src/lib/components/settings/RolePicker.svelte b/frontend/src/lib/components/settings/RolePicker.svelte new file mode 100644 index 0000000000..f8bb3d444a --- /dev/null +++ b/frontend/src/lib/components/settings/RolePicker.svelte @@ -0,0 +1,79 @@ +<script lang="ts"> + import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' + import Select from '$lib/components/select/Select.svelte' + import type { EffectiveRole } from '$lib/gen' + import { roleItems } from '$lib/workspaceRoles' + + interface Props { + /** The workspace's roles; undefined while loading. */ + roles: EffectiveRole[] | undefined + /** A role name, or `admin`. */ + value: string | undefined + /** May return a promise; the picker shows `value` again once it settles. */ + onchange: (value: string) => unknown + /** Whether Admin is offered next to the roles. */ + admin?: boolean + disabled?: boolean + disablePortal?: boolean + } + + let { + roles, + value, + onchange, + admin = true, + disabled = false, + disablePortal = false + }: Props = $props() + + const known = $derived(roleItems(roles, { admin })) + // A role the workspace no longer defines grants nothing; it stays visible rather than showing + // nothing selected. + const missing = $derived(value && !known.some((i) => i.value === value) ? value : undefined) + const undefinedValue = $derived(roles ? missing : undefined) + const items = $derived( + missing + ? [...known, { label: undefinedValue ? `${missing} (inactive)` : missing, value: missing }] + : known + ) + + let picks = $state(0) + + async function pick(v: string) { + if (v === value) return + try { + await onchange(v) + } finally { + picks++ + } + } + + const TOOLTIPS: Record<string, string> = { + admin: + 'Full control over the workspace: members, settings, every item. Holds everything whatever the role.' + } +</script> + +{#if items.length <= 4 && !undefinedValue} + <!-- The group keeps its own selection, so it is remounted after each pick: a pick the parent + refuses then shows `value` again instead of the refused one. --> + {#key picks} + <ToggleButtonGroup selected={value} {disabled} onSelected={pick}> + {#snippet children({ item })} + {#each items as i (i.value)} + <ToggleButton value={i.value} label={i.label} tooltip={TOOLTIPS[i.value]} small {item} /> + {/each} + {/snippet} + </ToggleButtonGroup> + {/key} +{:else} + <Select + {items} + {disabled} + {disablePortal} + size="sm" + class="min-w-36" + bind:value={() => value, (v) => v && pick(v)} + /> +{/if} diff --git a/frontend/src/lib/components/settings/TokenDisplay.svelte b/frontend/src/lib/components/settings/TokenDisplay.svelte index 5697b55b1b..238e7faa00 100644 --- a/frontend/src/lib/components/settings/TokenDisplay.svelte +++ b/frontend/src/lib/components/settings/TokenDisplay.svelte @@ -74,8 +74,8 @@ <!-- Additional info using alert info styling --> <div class="mt-1 {alertStyles.bgClass} rounded-md p-2"> <p class="text-xs {alertStyles.descriptionClass}"> - <strong>Next steps:</strong> Use this URL in your MCP-compatible client (like Claude Desktop) - to access your Windmill scripts and flows as tools. + <strong>Next steps:</strong> Add this URL to your MCP-compatible client (like Claude Desktop) + as a remote MCP server. </p> </div> {/if} diff --git a/frontend/src/lib/components/settings/TokensTable.svelte b/frontend/src/lib/components/settings/TokensTable.svelte index 1024aefa72..3cd83e7d89 100644 --- a/frontend/src/lib/components/settings/TokensTable.svelte +++ b/frontend/src/lib/components/settings/TokensTable.svelte @@ -10,6 +10,7 @@ import Badge from '../common/badge/Badge.svelte' import Alert from '../common/alert/Alert.svelte' import { Pen, Trash } from 'lucide-svelte' + import { MCP_SESSION } from '../mcp/McpAccessPicker.svelte' // --- Props --- interface Props { @@ -114,6 +115,10 @@ listTokens() } + function shownScopes(scopes: string[] | null | undefined): string { + return (scopes ?? []).filter((s) => s !== MCP_SESSION).join(', ') + } + function handleEditClick( tokenPrefix: string, tokenLabel: string | undefined, @@ -129,7 +134,7 @@ editModalOpen = true } - async function listTokens(): Promise<void> { + export async function listTokens(): Promise<void> { tokens = await UserService.listTokens({ excludeEphemeral: true, page: tokenPage, @@ -199,13 +204,13 @@ </td> <td class="min-w-0 max-w-48 truncate text-xs text-secondary" - title={scopes?.join(', ') ?? ''} + title={shownScopes(scopes)} > <div class="flex items-center gap-1.5 truncate"> {#if read_only} <Badge color="blue" small>Read-only</Badge> {/if} - <span class="truncate">{scopes?.join(', ') ?? ''}</span> + <span class="truncate">{shownScopes(scopes)}</span> </div> </td> <td class="w-24 text-center"> diff --git a/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte b/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte deleted file mode 100644 index b9ad80f63e..0000000000 --- a/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte +++ /dev/null @@ -1,295 +0,0 @@ -<script lang="ts"> - import { Button } from '$lib/components/common' - import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' - import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' - import DataTable from '$lib/components/table/DataTable.svelte' - import Section from '$lib/components/Section.svelte' - import Head from '$lib/components/table/Head.svelte' - import Cell from '$lib/components/table/Cell.svelte' - import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' - import Toggle from '$lib/components/Toggle.svelte' - import { WorkspaceService } from '$lib/gen' - import { workspaceStore } from '$lib/stores' - import { sendUserToast } from '$lib/toast' - import { SaveIcon, EyeIcon, EyeOffIcon } from 'lucide-svelte' - import { untrack } from 'svelte' - - const defaultVisibility = { - runs: true, - schedules: true, - resources: true, - variables: true, - assets: true, - triggers: true, - audit_logs: true, - groups: true, - folders: true, - workers: true - } - let operatorWorkspaceSettings = $state({ ...defaultVisibility }) - - // Kept out of `operatorWorkspaceSettings` so the visibility table's "Enable all" never flips a - // write right, and so these rows stay out of that table. - let builderFlows = $state(false) - let builderApps = $state(false) - // Withdrawable rather than granted: operators hold these until an admin turns them off. - let manageSchedules = $state(true) - let manageTriggers = $state(true) - - let originalSettings = $state({ - ...untrack(() => operatorWorkspaceSettings), - builder_flows: false, - builder_apps: false, - manage_schedules: true, - manage_triggers: true - }) - let isChanged = $state(false) - let currentWorkspace: string | null = $state(null) - let confirmBuilderOpen = $state(false) - // Saving sends every key, so saving before the load, or over a late response for another - // workspace, would write defaults over the rights stored there. - let loadedWorkspace: string | null = $state(null) - - const settingsPayload = $derived({ - ...operatorWorkspaceSettings, - builder_flows: builderFlows, - builder_apps: builderApps, - manage_schedules: manageSchedules, - manage_triggers: manageTriggers - }) - - // The seat cost lands on the first right granted, so confirm only when going from neither to - // either. Adding the second one later is already paid for. - const grantsFirstBuilderRight = $derived( - (builderFlows || builderApps) && - !(originalSettings.builder_flows || originalSettings.builder_apps) - ) - - const grantedBuilderKinds = $derived( - [builderFlows && 'flows', builderApps && 'full-code apps'].filter(Boolean).join(' and ') - ) - - function onSaveClicked() { - if (grantsFirstBuilderRight) { - confirmBuilderOpen = true - } else { - saveSettings() - } - } - - async function saveSettings() { - try { - await WorkspaceService.updateOperatorSettings({ - workspace: $workspaceStore!, - requestBody: settingsPayload - }) - originalSettings = { ...settingsPayload } - isChanged = false - sendUserToast('Operator settings saved successfully!', false) - } catch (error) { - console.error('Error updating operator settings:', error) - sendUserToast(`Failed to save operator settings: ${error?.body ?? error}`, true) - } - } - - const descriptions = { - runs: { title: 'Runs', description: 'View runs' }, - schedules: { title: 'Schedules', description: 'View schedules' }, - resources: { title: 'Resources', description: 'View resources' }, - variables: { title: 'Variables', description: 'View variables' }, - assets: { title: 'Assets', description: 'View assets' }, - triggers: { title: 'Triggers', description: 'View all triggers (HTTP, Websocket, Kafka)' }, - audit_logs: { title: 'Audit Logs', description: 'View audit logs' }, - groups: { title: 'Groups', description: 'View groups and group members' }, - folders: { title: 'Folders', description: 'View folders' }, - workers: { title: 'Workers', description: 'View workers and worker groups' } - } - - $effect(() => { - if ($workspaceStore && $workspaceStore !== currentWorkspace) { - ;(async () => { - const ws = $workspaceStore - currentWorkspace = ws - const settings = await WorkspaceService.getSettings({ workspace: ws }) - if (ws !== currentWorkspace) return - // Every value is reset, null settings included: one kept from the previous workspace - // would be saved here with the next unrelated change, builder rights among them. - const { - builder_flows: remoteFlows, - builder_apps: remoteApps, - manage_schedules: remoteSchedules, - manage_triggers: remoteTriggers, - ...remoteVisibility - } = settings.operator_settings ?? {} - operatorWorkspaceSettings = { ...defaultVisibility, ...remoteVisibility } - builderFlows = remoteFlows ?? false - builderApps = remoteApps ?? false - manageSchedules = remoteSchedules ?? true - manageTriggers = remoteTriggers ?? true - originalSettings = { - ...operatorWorkspaceSettings, - builder_flows: builderFlows, - builder_apps: builderApps, - manage_schedules: manageSchedules, - manage_triggers: manageTriggers - } - loadedWorkspace = ws - })() - } - }) - - $effect(() => { - isChanged = JSON.stringify(settingsPayload) !== JSON.stringify(originalSettings) - }) - - const allDisabled = $derived( - Object.values(operatorWorkspaceSettings).every((value) => value === false) - ) - const allEnabled = $derived( - Object.values(operatorWorkspaceSettings).every((value) => value === true) - ) -</script> - -<Section - label="Operator settings" - collapsable={true} - tooltip="Operators run what is shared with them. Choose what else they can change and see in this workspace." - description="Operators run what is shared with them. Choose what else they can change and see in this workspace." -> - {#snippet action()} - <Button - on:click={onSaveClicked} - startIcon={{ icon: SaveIcon }} - disabled={!isChanged || loadedWorkspace !== $workspaceStore} - variant="accent" - > - Save operator settings - </Button> - {/snippet} - - <Section - small - label="Build flows and apps" - description="Let operators build flows out of deployed scripts and flows, and full-code apps whose frontend code they write. Apps always run sandboxed, and operators still cannot write backend scripts. Granting either right makes each operator consume a full seat instead of half a seat." - wrapperClass="mb-6" - class="flex flex-col gap-y-1" - > - <Toggle - bind:checked={builderFlows} - options={{ right: 'Operators can build flows' }} - size="xs" - /> - <Toggle - bind:checked={builderApps} - options={{ right: 'Operators can build full-code apps' }} - size="xs" - /> - </Section> - - <Section - small - label="Change schedules and triggers" - description="Operators can create, edit and delete schedules and triggers wherever their folder permissions let them write. When turned off, the server refuses these changes, including through the API and the CLI." - wrapperClass="mb-6" - class="flex flex-col gap-y-1" - > - <Toggle - bind:checked={manageSchedules} - options={{ right: 'Operators can manage schedules' }} - size="xs" - /> - <Toggle - bind:checked={manageTriggers} - options={{ right: 'Operators can manage triggers' }} - size="xs" - /> - </Section> - - <Section - small - label="Pages in their menu" - description="Hides pages from an operator's menu. It does not block access through the API: use folder and item permissions to restrict what they can read." - > - <DataTable tableFixed={true} size="xs"> - <Head> - <tr> - <Cell head first>Section</Cell> - <Cell head>Description</Cell> - <Cell head last> - <ToggleButtonGroup - bind:selected={ - () => (allDisabled ? 'false' : allEnabled ? 'true' : ''), - (v) => { - Object.keys(operatorWorkspaceSettings).forEach((key) => { - if (v === 'true') operatorWorkspaceSettings[key] = true - if (v === 'false') operatorWorkspaceSettings[key] = false - }) - } - } - > - {#snippet children({ item })} - <ToggleButton - icon={EyeIcon} - small={true} - value={'true'} - label="Enable All" - {item} - /> - <ToggleButton - icon={EyeOffIcon} - small={true} - value={'false'} - label="Disable All" - {item} - /> - {/snippet} - </ToggleButtonGroup> - </Cell> - </tr> - </Head> - <tbody class="divide-y bg-surface"> - {#each Object.entries(descriptions) as [key, { title, description }]} - <tr> - <Cell first>{title}</Cell> - <Cell>{description}</Cell> - <Cell last class="pl-8"> - <ToggleButtonGroup - selected={operatorWorkspaceSettings[key] ? 'on' : 'off'} - on:selected={({ detail }) => (operatorWorkspaceSettings[key] = detail === 'on')} - > - {#snippet children({ item })} - <ToggleButton icon={EyeIcon} small={true} value={'on'} label="On" {item} /> - <ToggleButton icon={EyeOffIcon} small={true} value={'off'} label="Off" {item} /> - {/snippet} - </ToggleButtonGroup> - </Cell> - </tr> - {/each} - </tbody> - </DataTable> - </Section> -</Section> - -<ConfirmationModal - open={confirmBuilderOpen} - title="Give operators builder rights" - type="info" - confirmationText="Enable builder rights" - onCanceled={() => (confirmBuilderOpen = false)} - onConfirmed={async () => { - confirmBuilderOpen = false - await saveSettings() - }} -> - <div class="flex flex-col gap-2 text-sm"> - <span>This applies to every operator of this workspace, not to a chosen few.</span> - <span> - Each of them then consumes a full seat instead of half a seat, which changes what this - instance is billed. - </span> - <span> - They can create, edit and delete {grantedBuilderKinds} wherever their folder permissions already - let them write. Review those permissions before enabling. - </span> - </div> -</ConfirmationModal> diff --git a/frontend/src/lib/components/settings/WorkspaceRoleOverrides.svelte b/frontend/src/lib/components/settings/WorkspaceRoleOverrides.svelte new file mode 100644 index 0000000000..12e1b3e68e --- /dev/null +++ b/frontend/src/lib/components/settings/WorkspaceRoleOverrides.svelte @@ -0,0 +1,393 @@ +<script lang="ts"> + import { Alert, Badge, Button, Section } from '$lib/components/common' + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import TextInput from '$lib/components/text_input/TextInput.svelte' + import RoleCapabilitiesEditor from './RoleCapabilitiesEditor.svelte' + import { + WorkspaceService, + type EffectiveRole, + type RoleCapabilities, + type RoleOverride, + type RoleOverrides, + type WorkspaceRoles + } from '$lib/gen' + import { sendUserToast } from '$lib/toast' + import { + applyCapabilitiesPatch, + authorLevelLabel, + baseCapabilitiesFor, + capabilitiesError, + isEmptyPatch, + roleNameError, + VISIBILITY_KEYS + } from '$lib/workspaceRoles' + import { ChevronDown, ChevronRight, Plus, RotateCcw, SaveIcon, Trash2 } from 'lucide-svelte' + import { SvelteMap } from 'svelte/reactivity' + + interface Props { + workspace: string + /** The workspace's roles as last read; undefined while loading. */ + data: WorkspaceRoles | undefined + onSaved: () => void + } + + let { workspace, data, onSaved }: Props = $props() + + // Maps, not objects: a role name is any slug, `constructor` and `__proto__` included. + const draft = new SvelteMap<string, RoleOverride>() + let loadedFrom: WorkspaceRoles | undefined = undefined + const open = new SvelteMap<string, boolean>() + let newRoleName = $state('') + let confirmSeatOpen = $state(false) + let saving = $state(false) + + $effect(() => { + if (data && data !== loadedFrom) { + loadedFrom = data + draft.clear() + for (const [name, o] of Object.entries(data.overrides ?? {})) { + draft.set(name, structuredClone($state.snapshot(o))) + } + } + }) + + const instanceRoles = $derived((data?.roles ?? []).filter((r) => r.source === 'instance')) + const workspaceOnlyNames = $derived( + [...draft.keys()].filter((n) => !instanceRoles.some((r) => r.name === n)).sort() + ) + + function overriddenKeys(o: RoleOverride | undefined): string[] { + const c = o?.capabilities ?? {} + const keys = ['code', 'flows', 'apps', 'manage_schedules', 'manage_triggers'].filter( + (k) => c[k] != null + ) + for (const { key } of VISIBILITY_KEYS) { + if (c.visibility?.[key] != null) keys.push(`visibility.${key}`) + } + return keys + } + + /** + * The instance layer of a role. The listing gives only capabilities with the stored override + * applied, so a field that override sets has no known instance value: `unknown` lists them. + */ + function baseFor(name: string): { base: RoleCapabilities; unknown: string[] } { + const role = instanceRoles.find((r) => r.name === name) + if (!role) return { base: baseCapabilitiesFor(name), unknown: [] } + const stored = data && Object.hasOwn(data.overrides, name) ? data.overrides[name] : undefined + return { base: role.capabilities, unknown: overriddenKeys(stored) } + } + + function effectiveFor(name: string): RoleCapabilities { + return applyCapabilitiesPatch(baseFor(name).base, draft.get(name)?.capabilities) + } + + const AUTHORING_KEYS = ['code', 'flows', 'apps'] + + /** Whether saving makes an authoring field of `name` fall back to an unknown instance value. */ + function authoringUnknown(name: string): boolean { + const set = overriddenKeys(draft.get(name)) + return baseFor(name).unknown.some((k) => AUTHORING_KEYS.includes(k) && !set.includes(k)) + } + + function isAuthor(c: RoleCapabilities): boolean { + return c.code || c.flows !== 'none' || c.apps !== 'none' + } + + function summary(c: RoleCapabilities): string { + return [ + c.code ? 'Code' : 'No code', + `Flows: ${authorLevelLabel(c.flows).toLowerCase()}`, + `Apps: ${authorLevelLabel(c.apps).toLowerCase()}` + ].join(' · ') + } + + /** The overrides to store: instance roles left as the instance has them are dropped. */ + function cleaned(entries: Iterable<[string, RoleOverride]>): RoleOverrides { + const out: [string, RoleOverride][] = [] + for (const [name, v] of entries) { + const label = v.label?.trim() || undefined + const isInstance = instanceRoles.some((r) => r.name === name) + if (isInstance && !label && isEmptyPatch(v.capabilities)) continue + out.push([ + name, + { + ...(label ? { label } : {}), + capabilities: isEmptyPatch(v.capabilities) ? {} : v.capabilities + } + ]) + } + return Object.fromEntries(out) + } + + const cleanedDraft = $derived(cleaned(draft)) + + const dirty = $derived( + data != undefined && + JSON.stringify(cleanedDraft) !== JSON.stringify(cleaned(Object.entries(data.overrides))) + ) + + const errors = $derived.by(() => { + const e: Record<string, string> = Object.create(null) + for (const name of [...instanceRoles.map((r) => r.name), ...workspaceOnlyNames]) { + // Left to the server, which knows the instance value. + if (authoringUnknown(name)) continue + const err = capabilitiesError(effectiveFor(name)) + if (err) e[name] = err + } + return e + }) + + // A role that starts authoring moves each member from half a seat to a full one. One that + // falls back to an unknown instance value may, so it is confirmed too. + const newAuthorRoles = $derived( + [ + ...instanceRoles.map((r) => r.name), + ...(data?.custom_roles_enabled ? workspaceOnlyNames : []) + ].filter((name) => { + const before = data?.roles.find((r) => r.name === name)?.capabilities + if (before && isAuthor(before)) return false + return isAuthor(effectiveFor(name)) || authoringUnknown(name) + }) + ) + + function setPatch(name: string, capabilities: RoleOverride['capabilities']) { + draft.set(name, { ...(draft.get(name) ?? {}), capabilities }) + } + + function setLabel(name: string, label: string) { + draft.set(name, { ...(draft.get(name) ?? {}), label }) + } + + function resetRole(name: string) { + draft.delete(name) + } + + const newRoleError = $derived.by(() => { + const name = newRoleName.trim() + if (!name) return undefined + if (instanceRoles.some((r) => r.name === name) || draft.has(name)) { + return 'This role already exists' + } + return roleNameError(name) + }) + + function addRole() { + const name = newRoleName.trim() + if (!name || newRoleError) return + draft.set(name, { capabilities: {} }) + open.set(name, true) + newRoleName = '' + } + + function onSaveClicked() { + if (newAuthorRoles.length > 0) confirmSeatOpen = true + else save() + } + + async function save() { + saving = true + try { + await WorkspaceService.updateWorkspaceRoleOverrides({ + workspace, + requestBody: cleanedDraft + }) + sendUserToast('Workspace roles saved') + onSaved() + } catch (e) { + sendUserToast(`Failed to save workspace roles: ${e?.body ?? e}`, true) + } finally { + saving = false + } + } +</script> + +{#snippet roleCard(name: string, role: EffectiveRole | undefined)} + {@const { base, unknown } = baseFor(name)} + {@const caps = applyCapabilitiesPatch(base, draft.get(name)?.capabilities)} + {@const overridden = Object.hasOwn(cleanedDraft, name)} + {@const frozen = !role && !data?.custom_roles_enabled} + <div class="flex flex-col rounded-md border bg-surface-tertiary"> + <div class="flex items-center gap-2 p-2"> + <div class="flex flex-col w-40 shrink-0 min-w-0"> + <span class="text-xs font-semibold text-emphasis truncate"> + {draft.get(name)?.label?.trim() || role?.label || name} + </span> + <span class="text-2xs text-secondary font-mono truncate">{name}</span> + </div> + {#if role} + <Badge color="gray" verySmall>Instance</Badge> + {#if overridden} + <Badge color="blue" verySmall>Overridden here</Badge> + {/if} + {:else if frozen} + <Badge color="orange" verySmall>Read-only without a license</Badge> + {:else} + <Badge color="indigo" verySmall>This workspace only</Badge> + {/if} + <span class="text-2xs text-secondary truncate grow"> + {summary(caps)} + </span> + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: open.get(name) ? ChevronDown : ChevronRight }} + onclick={() => open.set(name, !open.get(name))} + > + Capabilities + </Button> + {#if role} + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: RotateCcw }} + disabled={!overridden} + title="Use the instance definition of this role" + onclick={() => resetRole(name)} + > + Reset role + </Button> + {:else} + <Button + variant="subtle" + unifiedSize="sm" + destructive + iconOnly + startIcon={{ icon: Trash2 }} + aria-label="Remove role" + title="Remove role" + onclick={() => resetRole(name)} + /> + {/if} + </div> + {#if errors[name] && !open.get(name)} + <span class="text-2xs text-red-600 dark:text-red-400 px-2 pb-2">{errors[name]}</span> + {/if} + {#if open.get(name)} + <div class="border-t p-3 flex flex-col gap-3"> + <div class="flex items-center gap-2"> + <span class="text-xs font-semibold text-emphasis w-24">Label</span> + <div class="w-60"> + <TextInput + size="sm" + value={draft.get(name)?.label ?? ''} + inputProps={{ + placeholder: role?.label ?? name, + disabled: frozen, + 'aria-label': 'Label in this workspace', + oninput: (e) => setLabel(name, e.currentTarget.value) + }} + /> + </div> + </div> + <RoleCapabilitiesEditor + {base} + unknownBase={unknown} + patch={draft.get(name)?.capabilities ?? {}} + baseName={role ? 'instance' : 'default'} + setText={role ? 'Overridden' : 'Set'} + inheritedText={role ? 'From instance' : 'Default'} + disabled={frozen} + onchange={(p) => setPatch(name, p)} + /> + </div> + {/if} + </div> +{/snippet} + +<Section + label="Workspace roles" + collapsable={true} + description="The roles members of this workspace can hold, as the instance defines them. Override what a role allows in this workspace; a field you do not override keeps following the instance. Workspace admins hold everything regardless of their role." +> + {#snippet action()} + <Button + onclick={onSaveClicked} + startIcon={{ icon: SaveIcon }} + disabled={!dirty || saving || Object.keys(errors).length > 0} + variant="accent" + > + Save workspace roles + </Button> + {/snippet} + + {#if !data} + <span class="text-xs text-secondary">Loading roles...</span> + {:else} + <div class="flex flex-col gap-3"> + {#each instanceRoles as role (role.name)} + {@render roleCard(role.name, role)} + {/each} + {#each workspaceOnlyNames as name (name)} + {@render roleCard(name, undefined)} + {/each} + + {#if data.custom_roles_enabled} + <div class="flex items-start gap-2"> + <div class="flex flex-col gap-0.5 w-60"> + <TextInput + size="sm" + bind:value={newRoleName} + error={newRoleError} + inputProps={{ + placeholder: 'new role name', + 'aria-label': 'New role name', + onkeydown: (e) => e.key === 'Enter' && addRole() + }} + /> + {#if newRoleError} + <span class="text-2xs text-red-600 dark:text-red-400">{newRoleError}</span> + {/if} + </div> + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: Plus }} + disabled={!newRoleName.trim() || !!newRoleError} + onclick={addRole} + > + Add workspace role + </Button> + </div> + <span class="text-2xs text-secondary"> + A workspace role exists only here. Its unset capabilities default to the operator rights. + One still held by a member, invite, auto-invite or instance group mapping cannot be + removed. + </span> + {:else} + <Alert + type="info" + size="xs" + title="Adding roles requires a valid Windmill Enterprise Edition license" + > + This workspace can still override what the instance roles allow. Roles added here earlier + keep applying but are read-only; they can still be removed. + </Alert> + {/if} + </div> + {/if} +</Section> + +<ConfirmationModal + open={confirmSeatOpen} + title="Roles that now author consume a full seat" + type="info" + confirmationText="Save" + onCanceled={() => (confirmSeatOpen = false)} + onConfirmed={async () => { + confirmSeatOpen = false + await save() + }} +> + <div class="flex flex-col gap-2 text-sm"> + <span> + With this change, members holding + <b>{newAuthorRoles.join(', ')}</b> can write code or build flows or apps in this workspace, or + may again if the instance definition allows it. + </span> + <span> + Each of them then consumes a full seat instead of half a seat, which changes what this + instance is billed. They can author wherever their folder permissions already let them write. + </span> + </div> +</ConfirmationModal> diff --git a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte index 8f5db5f2d9..19ca67a5f7 100644 --- a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte +++ b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte @@ -4,7 +4,17 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' - import WorkspaceOperatorSettings from '$lib/components/settings/WorkspaceOperatorSettings.svelte' + import WorkspaceRoleOverrides from '$lib/components/settings/WorkspaceRoleOverrides.svelte' + import RolePicker from '$lib/components/settings/RolePicker.svelte' + import { + defaultRoleName, + loadWorkspaceRoles, + OPERATOR_ROLE, + pickerValue, + roleLabel, + roleRequestFields, + validRoleOr + } from '$lib/workspaceRoles' import InviteUser from '$lib/components/InviteUser.svelte' import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte' @@ -12,7 +22,7 @@ import Head from '$lib/components/table/Head.svelte' import Toggle from '$lib/components/Toggle.svelte' import Tooltip from '$lib/components/Tooltip.svelte' - import type { CancelablePromise, User, UserUsage } from '$lib/gen' + import type { CancelablePromise, User, UserUsage, WorkspaceRoles } from '$lib/gen' import { UserService, WorkspaceService, GroupService, type WorkspaceInvite } from '$lib/gen' import { userStore, @@ -39,12 +49,28 @@ let offboardingUser: string | undefined = $state(undefined) let offboardingReassignOnly = $state(false) - let users: User[] | undefined = $state(undefined) + // `role` is the member's workspace role, which `listUsers` returns but the spec's `User` omits. + type Member = User & { role?: string } + + let users: Member[] | undefined = $state(undefined) let invites: WorkspaceInvite[] = $state([]) - let filteredUsers: User[] | undefined = $state(undefined) + let filteredUsers: Member[] | undefined = $state(undefined) let userFilter = $state('') let auto_invite_domain: string | undefined = $state() - let operatorOnly: boolean | undefined = $state(undefined) + // Unset until picked or stored; the pickers and payloads fall back to the default role. + let autoInviteRole: string | undefined = $state(undefined) + let workspaceRoles = $state<WorkspaceRoles | undefined>(undefined) + const roles = $derived(workspaceRoles?.roles) + + async function loadRoles(): Promise<void> { + const workspace = $workspaceStore! + try { + const r = await loadWorkspaceRoles(workspace) + if (workspace === $workspaceStore) workspaceRoles = r + } catch (e) { + sendUserToast(`Failed to load the workspace roles: ${e?.body ?? e}`, true) + } + } let autoAdd: boolean | undefined = $state(false) let addAdminsAndDevelopersToForks = $state(false) let nbDisplayed = $state(30) @@ -56,7 +82,7 @@ // Add new instance group form state let selectedNewInstanceGroup: string | undefined = $state(undefined) - let selectedNewRole: string | undefined = $state('developer') + let selectedNewRole: string | undefined = $state(undefined) // Service account creation @@ -113,13 +139,14 @@ enabled?: boolean domain?: string operator?: boolean + role?: string mode?: string instance_groups?: string[] instance_groups_roles?: Record<string, string> } | undefined auto_invite_domain = autoInvite?.enabled ? (autoInvite?.domain ?? '*') : undefined - operatorOnly = autoInvite?.operator ?? false + autoInviteRole = autoInvite?.role ?? (autoInvite?.operator ? OPERATOR_ROLE : undefined) autoAdd = autoInvite?.mode === 'add' autoAddInstanceGroups = autoInvite?.instance_groups || [] autoAddInstanceGroupsRoles = autoInvite?.instance_groups_roles || {} @@ -190,11 +217,11 @@ let lastSeen: { workspace: string; signature: string; seq: number } | undefined = undefined let usersIssued = 0 - // Every field a paid seat count depends on — the developer/operator split, and the - // two categories billing excludes. - function membershipSignature(list: User[] | undefined): string { + // Every field a paid seat count depends on — the role, and the two categories billing + // excludes. + function membershipSignature(list: Member[] | undefined): string { return (list ?? []) - .map((u) => `${u.email}:${u.operator}:${u.disabled}:${u.is_service_account}`) + .map((u) => `${u.email}:${u.operator}:${u.role}:${u.disabled}:${u.is_service_account}`) .sort() .join(',') } @@ -218,29 +245,25 @@ } } + // Throws, so each caller rolls back its optimistic change. async function saveInstanceGroupSettings(): Promise<void> { - try { - await WorkspaceService.editInstanceGroups({ - workspace: $workspaceStore ?? '', - requestBody: { - groups: autoAddInstanceGroups, - roles: autoAddInstanceGroupsRoles - } - }) - sendUserToast('Instance group settings saved') - // Refresh user list to show newly auto-added users - listUsers() - } catch (e) { - console.error('Failed to save instance group settings:', e) - sendUserToast('Failed to save settings', true) - } + await WorkspaceService.editInstanceGroups({ + workspace: $workspaceStore ?? '', + requestBody: { + groups: autoAddInstanceGroups, + roles: autoAddInstanceGroupsRoles + } + }) + sendUserToast('Instance group settings saved') + // Refresh user list to show newly auto-added users + listUsers() } async function addInstanceGroup(): Promise<void> { - if (!selectedNewInstanceGroup || !selectedNewRole) return + if (!selectedNewInstanceGroup) return const groupToAdd = selectedNewInstanceGroup - const roleToAdd = selectedNewRole + const roleToAdd = validRoleOr(roles, selectedNewRole) try { autoAddInstanceGroups = [...autoAddInstanceGroups, groupToAdd] @@ -248,14 +271,14 @@ // Reset form selectedNewInstanceGroup = undefined - selectedNewRole = 'developer' + selectedNewRole = undefined await saveInstanceGroupSettings() } catch (e) { // Rollback on error autoAddInstanceGroups = autoAddInstanceGroups.filter((g) => g !== groupToAdd) delete autoAddInstanceGroupsRoles[groupToAdd] - sendUserToast('Failed to add instance group', true) + sendUserToast(`Failed to add instance group: ${e?.body ?? e}`, true) } } @@ -273,7 +296,7 @@ if (previousRole) { autoAddInstanceGroupsRoles[groupName] = previousRole } - sendUserToast('Failed to remove instance group', true) + sendUserToast(`Failed to remove instance group: ${e?.body ?? e}`, true) } } @@ -286,7 +309,7 @@ } catch (e) { // Rollback on error autoAddInstanceGroupsRoles[groupName] = previousRole - sendUserToast('Failed to update role', true) + sendUserToast(`Failed to update role: ${e?.body ?? e}`, true) } } @@ -315,6 +338,8 @@ listInvites() loadSettings() loadInstanceGroups() + workspaceRoles = undefined + loadRoles() }) } }) @@ -356,20 +381,16 @@ let nbInviteDisplayed = $state(50) - async function inviteUser(email: string, selected: 'operator' | 'developer' | 'admin') { + async function inviteUser(email: string, selected: string) { try { await WorkspaceService.inviteUser({ workspace: $workspaceStore!, - requestBody: { - email, - is_admin: selected == 'admin', - operator: selected == 'operator' - } + requestBody: { email, ...roleRequestFields(selected) } }) sendUserToast(`Invited ${email}`) } catch (e) { console.error('Failed to invite user:', e) - sendUserToast('Failed to invite user', true) + sendUserToast(`Failed to invite user: ${e?.body ?? e}`, true) } if (!(await UserService.existsEmail({ email }))) { @@ -412,7 +433,7 @@ workspace: $workspaceStore ?? '', requestBody: enable ? { - operator: operatorOnly ?? false, + ...roleRequestFields(validRoleOr(roles, autoInviteRole)), invite_all: !isCloudHosted(), auto_add: autoAdd } @@ -430,7 +451,7 @@ sendUserToast(message) } catch (e) { console.error('Failed to update auto invite:', e) - sendUserToast('Failed to update auto invite', true) + sendUserToast(`Failed to update auto invite: ${e?.body ?? e}`, true) } loadSettings() listInvites() @@ -548,32 +569,18 @@ {/if} <span class="text-xs mb-1">Role <Tooltip>Role of the auto-added users</Tooltip></span> - <ToggleButtonGroup - selected={operatorOnly ? 'operator' : 'developer'} - on:selected={async (e) => { - operatorOnly = e.detail === 'operator' + <RolePicker + {roles} + admin={false} + disablePortal + value={validRoleOr(roles, autoInviteRole)} + onchange={async (v) => { + autoInviteRole = v if (auto_invite_domain != undefined) { await updateAutoInvite(true) } }} - > - {#snippet children({ item })} - <ToggleButton - value="operator" - small - label="Operator" - tooltip="An operator can only execute and view scripts/flows/apps from your workspace, and only those that he has visibility on." - {item} - /> - <ToggleButton - value="developer" - small - label="Developer" - tooltip="A Developer can execute and view scripts/flows/apps, but they can also create new ones and edit those they are allowed to by their path (either u/ or Writer or Admin of their folder found at /f)." - {item} - /> - {/snippet} - </ToggleButtonGroup> + /> <div class="mt-6"> <Toggle @@ -660,36 +667,12 @@ <div class="flex flex-col gap-1"> <span class="text-xs text-primary">Role</span> - <ToggleButtonGroup - selected={selectedNewRole} - on:selected={(e) => { - selectedNewRole = e.detail - }} - > - {#snippet children({ item })} - <ToggleButton - value="operator" - small - label="Operator" - tooltip="An operator can only execute and view scripts/flows/apps from your workspace, and only those that he has visibility on." - {item} - /> - <ToggleButton - value="developer" - small - label="Developer" - tooltip="A Developer can execute and view scripts/flows/apps, but they can also create new ones and edit those they are allowed to by their path (either u/ or Writer or Admin of their folder found at /f)." - {item} - /> - <ToggleButton - value="admin" - small - label="Admin" - tooltip="An admin has full control over a specific Windmill workspace, including the ability to manage users, edit entities, and control permissions within the workspace." - {item} - /> - {/snippet} - </ToggleButtonGroup> + <RolePicker + {roles} + disablePortal + value={validRoleOr(roles, selectedNewRole)} + onchange={(v) => (selectedNewRole = v)} + /> </div> </div> @@ -697,7 +680,7 @@ color="blue" size="xs" startIcon={{ icon: Plus }} - disabled={!selectedNewInstanceGroup || !selectedNewRole} + disabled={!selectedNewInstanceGroup} onclick={addInstanceGroup} > Add @@ -730,38 +713,15 @@ </td> <td class="py-2"> <div> - <ToggleButtonGroup - selected={autoAddInstanceGroupsRoles[groupName] || - 'developer'} - on:selected={async (e) => { - autoAddInstanceGroupsRoles[groupName] = e.detail - await updateGroupRole(groupName, e.detail) + <RolePicker + {roles} + disablePortal + value={autoAddInstanceGroupsRoles[groupName] || + defaultRoleName(roles)} + onchange={async (v) => { + await updateGroupRole(groupName, v) }} - > - {#snippet children({ item })} - <ToggleButton - value="operator" - small - label="Operator" - tooltip="An operator can only execute and view scripts/flows/apps from your workspace, and only those that he has visibility on." - {item} - /> - <ToggleButton - value="developer" - small - label="Developer" - tooltip="A Developer can execute and view scripts/flows/apps, but they can also create new ones and edit those they are allowed to by their path (either u/ or Writer or Admin of their folder found at /f)." - {item} - /> - <ToggleButton - value="admin" - small - label="Admin" - tooltip="An admin has full control over a specific Windmill workspace, including the ability to manage users, edit entities, and control permissions within the workspace." - {item} - /> - {/snippet} - </ToggleButtonGroup> + /> </div> </td> <td class="py-2"> @@ -800,10 +760,11 @@ {/if} {#if showAutoInviteToggle} - <InviteUser {inviteUser} /> + <InviteUser {inviteUser} {roles} /> {/if} <AddUser + {roles} on:new={() => { listUsers() listInvites() @@ -851,7 +812,7 @@ <tbody> {#if filteredUsers} {#each sortedUsers().slice(0, nbDisplayed) as user, index (user.email)} - {@const { email, username, is_admin, operator, disabled, added_via } = user} + {@const { email, username, is_admin, disabled, added_via } = user} <!-- Add separator between manual users and instance group users --> {#if hasNonManualUsers && index > 0 && sortedUsers()[index - 1]?.added_via?.source !== 'instance_group' && added_via?.source === 'instance_group'} <tr class="bg-surface-secondary"> @@ -901,63 +862,35 @@ {#if added_via?.source === 'instance_group'} <div class="flex items-center gap-1"> <span class="rounded-md text-xs px-2 py-1 bg-surface shadow-md font-bold"> - {is_admin ? 'Admin' : operator ? 'Operator' : 'Developer'} + {roleLabel(roles, pickerValue(user))} </span> <Tooltip>Role is managed through instance group configuration above.</Tooltip> </div> {:else} - <ToggleButtonGroup - selected={is_admin ? 'admin' : operator ? 'operator' : 'developer'} - on:selected={async (e) => { - if (is_admin && email == $userStore?.email && e.detail != 'admin') { + <RolePicker + {roles} + value={pickerValue(user)} + onchange={async (v) => { + if (is_admin && email == $userStore?.email && v != 'admin') { sendUserToast( 'Admins cannot be demoted by themselves, ask another admin to demote you', true ) - e.preventDefault() listUsers() return } - const body = - e.detail == 'admin' - ? { is_admin: true, operator: false } - : e.detail == 'operator' - ? { is_admin: false, operator: true } - : { is_admin: false, operator: false } - await UserService.updateUser({ - workspace: $workspaceStore ?? '', - username, - requestBody: body - }) - listUsers() + try { + await UserService.updateUser({ + workspace: $workspaceStore ?? '', + username, + requestBody: roleRequestFields(v) + }) + } catch (e) { + sendUserToast(`Failed to change role: ${e?.body ?? e}`, true) + } + await listUsers() }} - > - {#snippet children({ item })} - <ToggleButton - value="operator" - small - label="Operator" - tooltip="An operator can only execute and view scripts/flows/apps from your workspace, and only those that he has visibility on." - {item} - /> - - <ToggleButton - value="developer" - small - label="Developer" - tooltip="A Developer can execute and view scripts/flows/apps, but they can also create new ones and edit those they are allowed to by their path (either u/ or Writer or Admin of their folder found at /f)." - {item} - /> - - <ToggleButton - value="admin" - small - label="Admin" - tooltip="An admin has full control over a specific Windmill workspace, including the ability to manage users, edit entities, and control permissions within the workspace." - {item} - /> - {/snippet} - </ToggleButtonGroup> + /> {/if} </div> </Cell> @@ -1083,7 +1016,9 @@ <div class="pt-12"></div> -<WorkspaceOperatorSettings /> +{#if $workspaceStore} + <WorkspaceRoleOverrides workspace={$workspaceStore} data={workspaceRoles} onSaved={loadRoles} /> +{/if} <div class="pt-12"></div> @@ -1118,7 +1053,7 @@ {#snippet action()} {#if showAutoInviteToggle && !isAdminsWorkspaceWithoutEE} <div class="flex gap-2 items-center"> - <InviteUser {inviteUser} /> + <InviteUser {inviteUser} {roles} /> </div> {/if} {/snippet} @@ -1132,56 +1067,27 @@ </Head> <tbody class="divide-y bg-surface"> {#if invites?.length > 0} - {#each invites.slice(0, nbInviteDisplayed) as { email, is_admin, operator }} + {#each invites.slice(0, nbInviteDisplayed) as invite} + {@const { email, is_admin, operator } = invite} <Row> <Cell first>{email}</Cell> <Cell> <div> - <ToggleButtonGroup - selected={is_admin ? 'admin' : operator ? 'operator' : 'developer'} - on:selected={async (e) => { - const body = - e.detail == 'admin' - ? { is_admin: true, operator: false } - : e.detail == 'operator' - ? { is_admin: false, operator: true } - : { is_admin: false, operator: false } - await WorkspaceService.inviteUser({ - workspace: $workspaceStore ?? '', - requestBody: { - email, - ...body - } - }) - listUsers() + <RolePicker + {roles} + value={pickerValue(invite)} + onchange={async (v) => { + try { + await WorkspaceService.inviteUser({ + workspace: $workspaceStore ?? '', + requestBody: { email, ...roleRequestFields(v) } + }) + } catch (e) { + sendUserToast(`Failed to change role: ${e?.body ?? e}`, true) + } + await listInvites() }} - > - {#snippet children({ item })} - <ToggleButton - value="operator" - small - label="Operator" - tooltip="An operator can only execute and view scripts/flows/apps from your workspace, and only those that he has visibility on." - {item} - /> - - <ToggleButton - value="developer" - small - label="Developer" - tooltip="A Developer can execute and view scripts/flows/apps, but they can also create new ones and edit those they are allowed to by their path (either u/ or Writer or Admin of their folder found at /f)." - {item} - /> - - <ToggleButton - value="admin" - small - label="Admin" - tooltip="An admin has full control over a specific Windmill workspace, including the ability to manage users, edit entities, and control permissions within the workspace." - {item} - /> - {/snippet} - </ToggleButtonGroup> + /> </div> </Cell> <Cell last actions> diff --git a/frontend/src/lib/components/sidebar/FavoriteMenu.svelte b/frontend/src/lib/components/sidebar/FavoriteMenu.svelte index c3d14d4c4d..448d7644bc 100644 --- a/frontend/src/lib/components/sidebar/FavoriteMenu.svelte +++ b/frontend/src/lib/components/sidebar/FavoriteMenu.svelte @@ -30,6 +30,9 @@ href: string kind: FavoriteKind }[] = $state([]) + /** The workspace `current` was last loaded for, so a reader can tell "none yet" from + * "none". */ + loadedFor: string | undefined = $state(undefined) async unstar(path: string, favorite_kind: FavoriteKind, workspaceId?: string) { this.current = this.current.filter( diff --git a/frontend/src/lib/components/sidebar/SettingsMenu.svelte b/frontend/src/lib/components/sidebar/SettingsMenu.svelte index 95dc03992c..13f38840d4 100644 --- a/frontend/src/lib/components/sidebar/SettingsMenu.svelte +++ b/frontend/src/lib/components/sidebar/SettingsMenu.svelte @@ -38,7 +38,6 @@ import { USER_SETTINGS_HASH, SUPERADMIN_SETTINGS_HASH } from './settings' import { accountSetup } from './accountSetup.svelte' import { EXECUTIONS_HINT } from './executionsHint' - import { sidebarPageAllowed } from './operatorRoutes' import { TOUR_PARAM, TOUR_PARAM_VALUE } from '$lib/components/tutorials/operatorTour' import { userWorkspaces, @@ -49,7 +48,8 @@ enterpriseLicense, isCriticalAlertsUIOpen, usageStore, - isPremiumStore + isPremiumStore, + roleCapabilities } from '$lib/stores' let { @@ -250,7 +250,7 @@ icon: Settings, action: () => goto(USER_SETTINGS_HASH) }, - ...($userStore?.operator + ...(!$roleCapabilities.code ? [ { displayName: 'Take the tour', @@ -318,7 +318,7 @@ label="Workers" href="/workers" icon={ServerCog} - disabled={!sidebarPageAllowed($userStore?.operator, currentWs, 'workers')} + disabled={!$roleCapabilities.visibility.workers} {isCollapsed} aiId="sidebar-menu-link-workers" aiDescription="Button to navigate to workers" @@ -364,7 +364,7 @@ label="Audit logs" href="/audit_logs" icon={Eye} - disabled={!sidebarPageAllowed($userStore?.operator, currentWs, 'audit_logs')} + disabled={!$roleCapabilities.visibility.audit_logs} {isCollapsed} aiId="sidebar-menu-link-audit-logs" aiDescription="Button to navigate to audit logs" diff --git a/frontend/src/lib/components/sidebar/SidebarContent.svelte b/frontend/src/lib/components/sidebar/SidebarContent.svelte index 7187709d2c..f08446d4ed 100644 --- a/frontend/src/lib/components/sidebar/SidebarContent.svelte +++ b/frontend/src/lib/components/sidebar/SidebarContent.svelte @@ -8,7 +8,8 @@ workspaceStore, isCriticalAlertsUIOpen, enterpriseLicense, - devopsRole + devopsRole, + roleCapabilities } from '$lib/stores' import { isForkOwner } from '$lib/utils/workspaceHierarchy' import { SIDEBAR_SHOW_SCHEDULES } from '$lib/consts' @@ -65,7 +66,7 @@ import GoogleCloudIcon from '../icons/triggers/GoogleCloudIcon.svelte' import AzureIcon from '../icons/triggers/AzureIcon.svelte' import { leaveCurrentWorkspace } from './leaveWorkspace' - import { sidebarPageAllowed, type OperatorPageKey } from './operatorRoutes' + import type { VisibilityKey } from '$lib/roleCapabilities' import { markChangelogsOpened, readRecentChangelogs } from './changelogs' const { recent: recentChangelogs, hasNew } = readRecentChangelogs() @@ -183,8 +184,8 @@ } const currentWs = $derived($userWorkspaces?.find((w) => w.id === $workspaceStore)) - function allows(key: OperatorPageKey) { - return sidebarPageAllowed($userStore?.operator, currentWs, key) + function allows(key: VisibilityKey) { + return $roleCapabilities.visibility[key] } const itemClass = twMerge( @@ -228,7 +229,7 @@ label: p.label, href: p.path === '/' ? `/` : `${p.path}`, icon: p.icon, - disabled: p.operatorKey ? !allows(p.operatorKey) : false, + disabled: p.visibilityKey ? !allows(p.visibilityKey) : false, ...MAIN_MENU_EXTRAS[p.label] })) .filter((l) => !excludeMainLabels.includes(l.label)) @@ -436,7 +437,7 @@ ] : []) ], - disabled: $userStore?.operator + disabled: !$roleCapabilities.code }, { label: 'Workers', diff --git a/frontend/src/lib/components/sidebar/UserMenu.svelte b/frontend/src/lib/components/sidebar/UserMenu.svelte index ff302d3c5e..40c64d5621 100644 --- a/frontend/src/lib/components/sidebar/UserMenu.svelte +++ b/frontend/src/lib/components/sidebar/UserMenu.svelte @@ -6,8 +6,11 @@ usageStore, workspaceUsageStore, isPremiumStore, - workspaceStore + workspaceStore, + userWorkspaces, + roleCapabilities } from '$lib/stores' + import { isRestricted } from '$lib/roleCapabilities' import { USER_SETTINGS_HASH } from './settings' import { isCloudHosted } from '$lib/cloud' import { twMerge } from 'tailwind-merge' @@ -32,6 +35,12 @@ // An account entered through an invite link that still has no credentials of its own. let pendingSetup = $derived(accountSetup.pending) + // A server that predates roles sends no role name, and its only restricted role is operator. + const roleName = $derived( + $userWorkspaces.find((w) => w.id === $workspaceStore)?.role ?? 'operator' + ) + const roleLabel = $derived(roleName.charAt(0).toUpperCase() + roleName.slice(1)) + const itemClass = twMerge( 'text-secondary text-left font-normal text-xs ', 'flex flex-row items-center gap-2 px-4 py-3 w-full', @@ -62,8 +71,8 @@ Superadmin, not a member of this workspace <Crown size={14} /> {:else if $userStore?.is_admin} Admin of this workspace <Crown size={14} /> - {:else if $userStore?.operator} - Operator in this workspace <ServerCog size={14} /> + {:else if isRestricted($roleCapabilities)} + {roleLabel} in this workspace <ServerCog size={14} /> {/if} </span> {#if $userStore?.non_member} diff --git a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte index c70fef70a4..97385c7e9d 100644 --- a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte +++ b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte @@ -2,8 +2,10 @@ import { tick, untrack } from 'svelte' import type { MenubarMenuElements } from '@melt-ui/svelte' import { workspaceMenuHref } from './workspaceMenuHref' - import { isOperatorInWorkspace } from './operatorRoutes' + import { capabilitiesIn, hidesPages, isRestricted } from '$lib/roleCapabilities' + import type { RoleCapabilities } from '$lib/gen' import { + roleCapabilities, isPremiumStore, maybePremium, superadmin, @@ -85,16 +87,15 @@ await fixupUrlAfterWorkspaceSwitch(id, { landOnHome }) } - // Operator page access is granted per workspace, so a switch lands on home rather than - // on a page either side may refuse. Both signals are positive: `userStore.operator` is - // an explicit flag for the workspace being left, and `isOperatorInWorkspace` only ever - // confirms the target (its NULL is ambiguous, so a `false` from it is never taken as - // proof of a developer on its own). Leaving one developer workspace for another keeps - // the page, as it always has. + // What a role may see and do is per workspace, so a switch that leaves or enters a restricted + // role lands on home rather than on a page either side may refuse. Leaving one unrestricted + // workspace for another keeps the page. function landsOnHome(id: string): boolean { if (keepPageOnSwitch) return false - if ($userStore?.operator) return true - return isOperatorInWorkspace(($userWorkspaces ?? []).find((w) => w.id === id)) + const gated = (caps: RoleCapabilities) => isRestricted(caps) || hidesPages(caps) + if (gated($roleCapabilities)) return true + const target = ($userWorkspaces ?? []).find((w) => w.id === id) + return gated(capabilitiesIn({ is_super_admin: $userStore?.is_super_admin }, target)) } // Href for the item's navigation (including modifier/middle clicks opening a @@ -160,7 +161,7 @@ // modal carries its own base-workspace picker). Hidden on non-premium cloud, // in the admins workspace, or when forking is disabled. const canForkHere = $derived( - (!isCloudHosted() || $maybePremium) && $workspaceStore !== 'admins' && canCreateFork($userStore) + (!isCloudHosted() || $maybePremium) && $workspaceStore !== 'admins' && canCreateFork($userStore, $roleCapabilities) ) // The row mechanics below — which family to expand, which collapsed row carries the tick — key on // a depth-0 row of the list, which `buildWorkspaceHierarchy` puts at the highest workspace the diff --git a/frontend/src/lib/components/sidebar/navDetached.svelte.ts b/frontend/src/lib/components/sidebar/navDetached.svelte.ts index 19568eaddc..e53f4e7cbb 100644 --- a/frontend/src/lib/components/sidebar/navDetached.svelte.ts +++ b/frontend/src/lib/components/sidebar/navDetached.svelte.ts @@ -1,5 +1,5 @@ import { fromStore } from 'svelte/store' -import { userStore } from '$lib/stores' +import { roleCapabilities } from '$lib/stores' import { useLocalStorageValue } from '$lib/svelte5Utils.svelte' // One preference per role rather than one per account. The same person is both — an operator in @@ -8,21 +8,21 @@ import { useLocalStorageValue } from '$lib/svelte5Utils.svelte' // Empty until that role presses detach or attach once. const operatorPref = useLocalStorageValue<string>('nav_detached_operator', '', 'string') const devPref = useLocalStorageValue<string>('nav_detached_dev', '', 'string') -const user = fromStore(userStore) +const caps = fromStore(roleCapabilities) /** Whether the sidebar is detached: hidden behind a floating button that slides it in over the page. */ export const navDetached = { get val(): boolean { // Unasked, operators start detached: many of them navigate through a workspace's own app, // and a docked sidebar would take its width. - const operator = !!user.current?.operator + const operator = !caps.current.code const pref = operator ? operatorPref : devPref if (pref.val === 'true') return true if (pref.val === 'false') return false return operator }, set val(detached: boolean) { - const pref = user.current?.operator ? operatorPref : devPref + const pref = caps.current.code ? devPref : operatorPref pref.val = String(detached) } } diff --git a/frontend/src/lib/components/sidebar/navPages.ts b/frontend/src/lib/components/sidebar/navPages.ts index 385b93abcc..2461ba6e1a 100644 --- a/frontend/src/lib/components/sidebar/navPages.ts +++ b/frontend/src/lib/components/sidebar/navPages.ts @@ -11,7 +11,7 @@ import { Unplug, Users } from 'lucide-svelte' -import type { OperatorPageKey } from './operatorRoutes' +import type { VisibilityKey } from '$lib/roleCapabilities' /** * The names the page header's breadcrumb gives the workspace's own pages, and the rows the @@ -20,7 +20,7 @@ import type { OperatorPageKey } from './operatorRoutes' * Every entry names a page for the breadcrumb, and its `icon` goes there too. Only the entries * `SidebarContent`'s `MAIN_MENU_EXTRAS` also lists become sidebar links from here — Schedules, * HTTP routes, Workers and Audit logs are grouped differently there and carry their own row, so - * for those four the `operatorKey` below goes unread. Keep the labels in step with those rows by + * for those four the `visibilityKey` below goes unread. Keep the labels in step with those rows by * hand. */ export type NavPage = { @@ -28,23 +28,23 @@ export type NavPage = { /** Path under `base`, matched against the current route by longest prefix. */ path: string icon: any - /** The `operator_settings` key that admits an operator, when the page has one. */ - operatorKey?: OperatorPageKey + /** The role visibility flag that shows the page, when the page has one. */ + visibilityKey?: VisibilityKey } export const NAV_PAGES: NavPage[] = [ { label: 'Home', path: '/', icon: Home }, - { label: 'Runs', path: '/runs', icon: Play, operatorKey: 'runs' }, - { label: 'Variables', path: '/variables', icon: DollarSign, operatorKey: 'variables' }, - { label: 'Resources', path: '/resources', icon: Boxes, operatorKey: 'resources' }, - { label: 'Assets', path: '/assets', icon: Pyramid, operatorKey: 'assets' }, - { label: 'Folders', path: '/folders', icon: FolderOpen, operatorKey: 'folders' }, - { label: 'Groups', path: '/groups', icon: Users, operatorKey: 'groups' }, - { label: 'Schedules', path: '/schedules', icon: Calendar, operatorKey: 'schedules' }, + { label: 'Runs', path: '/runs', icon: Play, visibilityKey: 'runs' }, + { label: 'Variables', path: '/variables', icon: DollarSign, visibilityKey: 'variables' }, + { label: 'Resources', path: '/resources', icon: Boxes, visibilityKey: 'resources' }, + { label: 'Assets', path: '/assets', icon: Pyramid, visibilityKey: 'assets' }, + { label: 'Folders', path: '/folders', icon: FolderOpen, visibilityKey: 'folders' }, + { label: 'Groups', path: '/groups', icon: Users, visibilityKey: 'groups' }, + { label: 'Schedules', path: '/schedules', icon: Calendar, visibilityKey: 'schedules' }, // "Triggers" is the group the sidebar files this under, not the page: the row there reads HTTP. - { label: 'HTTP routes', path: '/routes', icon: Unplug, operatorKey: 'triggers' }, - { label: 'Workers', path: '/workers', icon: HardHat, operatorKey: 'workers' }, - { label: 'Audit logs', path: '/audit_logs', icon: Eye, operatorKey: 'audit_logs' } + { label: 'HTTP routes', path: '/routes', icon: Unplug, visibilityKey: 'triggers' }, + { label: 'Workers', path: '/workers', icon: HardHat, visibilityKey: 'workers' }, + { label: 'Audit logs', path: '/audit_logs', icon: Eye, visibilityKey: 'audit_logs' } ] /** diff --git a/frontend/src/lib/components/sidebar/operatorRoutes.test.ts b/frontend/src/lib/components/sidebar/operatorRoutes.test.ts deleted file mode 100644 index bf14926d00..0000000000 --- a/frontend/src/lib/components/sidebar/operatorRoutes.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { sidebarPageAllowed } from './operatorRoutes' -import type { UserWorkspace } from '$lib/stores' - -const ws = (operator_settings: any): UserWorkspace => - ({ id: 'w', name: 'w', username: 'u', operator_settings }) as UserWorkspace - -describe('sidebarPageAllowed', () => { - it('shows every page to anyone who is not an operator', () => { - expect(sidebarPageAllowed(false, ws(null), 'runs')).toBe(true) - expect(sidebarPageAllowed(undefined, undefined, 'runs')).toBe(true) - }) - - it('admits an operator only where the workspace turned the page on', () => { - expect(sidebarPageAllowed(true, ws({ runs: true }), 'runs')).toBe(true) - expect(sidebarPageAllowed(true, ws({ runs: false }), 'runs')).toBe(false) - }) - - it('withholds a page the settings do not mention', () => { - // `=== true`, not truthiness: a right absent from the jsonb, or settings that were never - // written, must not read as granted. - expect(sidebarPageAllowed(true, ws({ variables: true }), 'runs')).toBe(false) - expect(sidebarPageAllowed(true, ws(null), 'runs')).toBe(false) - expect(sidebarPageAllowed(true, undefined, 'runs')).toBe(false) - }) -}) diff --git a/frontend/src/lib/components/sidebar/operatorRoutes.ts b/frontend/src/lib/components/sidebar/operatorRoutes.ts deleted file mode 100644 index 6824c36c62..0000000000 --- a/frontend/src/lib/components/sidebar/operatorRoutes.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type { OperatorSettings } from '$lib/gen' -import type { UserWorkspace } from '$lib/stores' - -/** - * An `operator_settings` key that admits an operator to one page (`triggers` to all of them). - * - * Only the visibility flags: the same object also carries the write rights `builder_flows`, - * `manage_schedules` and `manage_triggers`, which the `=== true` rule below answers wrongly. A - * write right is granted unless withdrawn, so its absence means "never configured" rather than - * "no" — see `docs/operator-write-rights.md`. - */ -export type OperatorPageKey = Extract< - keyof NonNullable<OperatorSettings>, - | 'runs' - | 'schedules' - | 'resources' - | 'variables' - | 'assets' - | 'audit_logs' - | 'triggers' - | 'groups' - | 'folders' - | 'workers' -> - -/** - * Whether the sidebar shows the page behind `key`. Everyone but an operator sees every page - * (other gates, such as admin-only entries, still apply); an operator sees only the pages the - * workspace's `operator_settings` turn on. - */ -export function sidebarPageAllowed( - isOperator: boolean | undefined, - workspace: UserWorkspace | undefined, - key: OperatorPageKey -): boolean { - return !isOperator || workspace?.operator_settings?.[key] === true -} - -/** - * Whether the user is an operator in `workspace`. The server nulls - * `operator_settings` for a non-operator, so a non-null value narrows an operator - * correctly; the converse does not hold — the column is itself nullable, so a - * genuine operator whose workspace never had settings written also reads as NULL. - * Only rely on `true`, never on `false` meaning "not an operator". - */ -export function isOperatorInWorkspace(workspace: UserWorkspace | undefined): boolean { - return workspace?.operator_settings != null -} diff --git a/frontend/src/lib/components/triggers/TriggerList.svelte b/frontend/src/lib/components/triggers/TriggerList.svelte index 1ccbd21d0e..3931d9660c 100644 --- a/frontend/src/lib/components/triggers/TriggerList.svelte +++ b/frontend/src/lib/components/triggers/TriggerList.svelte @@ -22,7 +22,7 @@ } from '$lib/utils' import { withForkConflictRetry } from '$lib/utils/forkConflict' import { getLocalDraftHint } from '$lib/localDraftHints.svelte' - import { enterpriseLicense, usedTriggerKinds, userWorkspaces, workspaceStore } from '$lib/stores' + import { enterpriseLicense, usedTriggerKinds, workspaceStore } from '$lib/stores' import { goto, setQuery } from '$lib/navigation' import { isCloudHosted } from '$lib/cloud' import { ALL_DEPLOYABLE, isDeployable } from '$lib/utils_deployable' @@ -519,10 +519,7 @@ } const operatorBlocked = $derived( - config.operatorGate && - !!operatingUser.current?.operator && - !!$operatingWorkspace && - !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.triggers + config.operatorGate && !!$operatingWorkspace && !editRights.capabilities.visibility.triggers ) const canCreate = $derived(!config.adminOnly || isAdmin) </script> @@ -883,7 +880,7 @@ {#if operatorBlocked} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage> diff --git a/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte b/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte index c6b0986226..9a954b211e 100644 --- a/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte +++ b/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte @@ -15,7 +15,8 @@ scriptPath: string initialScriptPath: string canWrite: boolean - isOperator: boolean + /** Whether to link to the picked runnable's editor: the role must author its kind. */ + allowEdit: boolean promptText?: string promptClass?: string workspace?: string @@ -30,7 +31,7 @@ scriptPath = $bindable(), initialScriptPath, canWrite, - isOperator, + allowEdit, promptText = 'Pick a script or flow to be triggered', promptClass = 'text-xs mb-1 text-primary', workspace = undefined, @@ -53,7 +54,7 @@ bind:itemKind bind:scriptPath allowRefresh={canWrite} - allowEdit={!isOperator} + {allowEdit} {workspace} clearable /> diff --git a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte index 7295ca0c35..c0f4803339 100644 --- a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte @@ -91,7 +91,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const wsId = $derived($operatingWorkspace) let amqp_resource_path: string = $state('') @@ -586,7 +585,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} /> </Section> {/if} diff --git a/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte index e0c2008be8..6b52a05428 100644 --- a/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte @@ -54,7 +54,6 @@ let mode = $state<TriggerMode>('enabled') let dirtyPath = $state(false) const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) let permsPath = $state<string | undefined>(undefined) let permsForWrite = $state<Record<string, boolean> | undefined>(undefined) // The acting user in the operating workspace arrives asynchronously, and an unknown user @@ -526,7 +525,7 @@ bind:itemKind bind:scriptPath={script_path} allowRefresh={can_write} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte index 38a8243855..9de47ba600 100644 --- a/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte @@ -455,7 +455,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptClass="text-xs mt-3 mb-1 text-primary" > {#snippet createButton()} diff --git a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte index 486711bd6c..04052a54d6 100644 --- a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte @@ -63,7 +63,6 @@ let mode = $state<TriggerMode>('enabled') let dirtyPath = $state(false) const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) let permsPath = $state<string | undefined>(undefined) let permsForWrite = $state<Record<string, boolean> | undefined>(undefined) // The acting user in the operating workspace arrives asynchronously, and an unknown user @@ -599,7 +598,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptText="Pick a script or flow to be triggered " > {#snippet createButton()} diff --git a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte index 786137eab4..fe94787167 100644 --- a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte +++ b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte @@ -778,7 +778,7 @@ bind:itemKind bind:scriptPath={script_path} allowRefresh={can_write} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> diff --git a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte index 17a17f98e8..80be6049d3 100644 --- a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte @@ -88,7 +88,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -609,7 +608,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} > {#snippet createButton()} {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte index 5c1fb4aaf0..d58abebe3b 100644 --- a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte @@ -96,7 +96,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -582,7 +581,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} > {#snippet createButton()} {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/native/NativeConnectionPicker.svelte b/frontend/src/lib/components/triggers/native/NativeConnectionPicker.svelte new file mode 100644 index 0000000000..ad7d0badb2 --- /dev/null +++ b/frontend/src/lib/components/triggers/native/NativeConnectionPicker.svelte @@ -0,0 +1,245 @@ +<script lang="ts"> + import { WorkspaceIntegrationService } from '$lib/gen' + import type { NativeServiceName, NativeTriggerConnection } from '$lib/gen/types.gen' + import { Button } from '$lib/components/common' + import Alert from '$lib/components/common/alert/Alert.svelte' + import Select from '$lib/components/select/Select.svelte' + import AppConnectDrawer from '$lib/components/AppConnectDrawer.svelte' + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import { createAsyncConfirmationModal } from '$lib/components/common/confirmationModal/asyncConfirmationModal.svelte' + import { sendUserToast } from '$lib/toast' + import { Plus, RefreshCw, Unplug } from 'lucide-svelte' + import { userStore } from '$lib/stores' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { connectNativeAccount, getServiceConfig } from './utils' + + interface Props { + service: NativeServiceName + value: string | undefined + /** An existing trigger keeps the connection its webhook was registered under. */ + locked?: boolean + disabled?: boolean + /** Select the first connection when none is chosen yet. */ + autoSelect?: boolean + clearable?: boolean + /** Suffix the workspace connection's label, where it sits among personal ones. */ + labelWorkspace?: boolean + placeholder?: string + /** Called instead of setting `value` directly when the user picks or clears a connection. */ + onSelect?: (path: string | undefined) => void + /** Called after an account is connected or disconnected from the picker. */ + onConnectionsChange?: () => void + } + + let { + service, + value = $bindable(), + locked = false, + disabled = false, + autoSelect = true, + clearable = false, + labelWorkspace = true, + placeholder, + onSelect, + onConnectionsChange + }: Props = $props() + + const operatingWorkspace = useOperatingWorkspace() + const displayName = $derived(getServiceConfig(service)?.serviceDisplayName ?? service) + const confirmationModal = createAsyncConfirmationModal() + + let connections = $state<NativeTriggerConnection[] | undefined>(undefined) + let connecting = $state(false) + let connectDrawer: AppConnectDrawer | undefined = $state(undefined) + + async function load() { + try { + connections = await WorkspaceIntegrationService.listNativeTriggerConnections({ + workspace: $operatingWorkspace!, + serviceName: service + }) + } catch (err: any) { + connections = [] + sendUserToast(`Failed to load ${displayName} connections: ${err.body ?? err.message}`, true) + } + if (autoSelect && !locked && value === undefined && connections.length > 0) { + select(connections[0].path) + } + } + + $effect(() => { + service + $operatingWorkspace + load() + }) + + function select(path: string | undefined) { + if (onSelect) onSelect(path) + else value = path + } + + async function connect(path: string) { + connecting = true + try { + path = await connectNativeAccount($operatingWorkspace!, service, path) + await load() + sendUserToast(`${displayName} account connected`) + onConnectionsChange?.() + select(path) + } catch (err: any) { + sendUserToast(`Could not connect ${displayName}: ${err.body ?? err.message}`, true) + throw err + } finally { + connecting = false + } + } + + async function reconnect(c: NativeTriggerConnection) { + if (c.owner && c.owner !== $userStore?.username) { + const confirmed = await confirmationModal.ask({ + title: `Reconnect ${c.path} with your account?`, + confirmationText: 'Reconnect', + children: `${c.path} will act as the ${displayName} account you sign in with, instead of ${c.owner}'s. Every trigger using it will act as you.` + }) + if (!confirmed) return + } + await connect(c.path).catch(() => {}) + } + + async function disconnect(path: string) { + const confirmed = await confirmationModal.ask({ + title: `Disconnect ${path}?`, + confirmationText: 'Disconnect', + children: `This deletes every ${displayName} trigger that uses this account, including ones other members created. This action cannot be undone.` + }) + if (!confirmed) return + try { + await WorkspaceIntegrationService.deleteNativeTriggerConnection({ + workspace: $operatingWorkspace!, + serviceName: service, + path + }) + sendUserToast(`${path} disconnected`) + if (value === path) select(undefined) + await load() + onConnectionsChange?.() + } catch (err: any) { + sendUserToast(`Failed to disconnect ${path}: ${err.body ?? err.message}`, true) + } + } + + // Members cannot write the workspace connection; the server refuses anyone else it does not own. + function canDisconnect(c: NativeTriggerConnection): boolean { + if ($userStore?.is_admin) return true + return !c.workspace && !!c.owner && c.owner === $userStore?.username + } + + // The server lets only the connection's owner or an admin replace it. + function canReconnect(c: NativeTriggerConnection): boolean { + return !!$userStore?.is_admin || (!!c.owner && c.owner === $userStore?.username) + } + + const items = $derived.by(() => { + const list = (connections ?? []).map((c) => ({ + label: c.workspace && labelWorkspace ? `${c.path} (shared account)` : c.path, + value: c.path + })) + if (value && !list.some((i) => i.value === value)) { + list.push({ label: value, value }) + } + return list + }) + const unusable = $derived( + connections !== undefined && !!value && !connections.some((c) => c.path === value) + ) +</script> + +<div class="flex flex-col gap-2"> + <Select + {items} + bind:value={() => value, (v) => select(v)} + onClear={() => select(undefined)} + {clearable} + disabled={disabled || locked} + loading={connections === undefined || connecting} + placeholder={placeholder ?? `Connect a ${displayName} account to create this trigger`} + noItemsMsg="No {displayName} account connected yet" + > + {#snippet endSnippet({ item, close })} + {@const connection = connections?.find((c) => c.path === item.value)} + {#if connection && canReconnect(connection)} + <Button + unifiedSize="xs" + variant="subtle" + startIcon={{ icon: RefreshCw }} + disabled={connecting} + onclick={() => (close(), reconnect(connection))} + > + Reconnect + </Button> + {/if} + {#if connection && canDisconnect(connection)} + <Button + unifiedSize="xs" + variant="subtle" + destructive + startIcon={{ icon: Unplug }} + onclick={() => (close(), disconnect(connection.path))} + > + Disconnect + </Button> + {/if} + {/snippet} + {#snippet bottomSnippet({ close })} + <div class="flex bg-surface border-t"> + <Button + unifiedSize="md" + variant="subtle" + wrapperClasses="flex-1" + btnClasses="rounded-none" + startIcon={{ icon: Plus }} + disabled={disabled || connecting} + onclick={() => (close(), connectDrawer?.open(getServiceConfig(service)?.resourceType))} + > + Connect a {displayName} account + </Button> + </div> + {/snippet} + </Select> + {#if locked} + {@const current = connections?.find((c) => c.path === value)} + <div class="flex items-center justify-between gap-2"> + <p class="text-2xs text-secondary"> + The webhook is registered under this account. To use another one, create a new trigger. + </p> + {#if current && canReconnect(current)} + <Button + unifiedSize="xs" + variant="subtle" + startIcon={{ icon: RefreshCw }} + disabled={connecting} + onclick={() => reconnect(current)} + > + Reconnect + </Button> + {/if} + </div> + {/if} + {#if unusable} + <Alert type="warning" title="You cannot use this connection" size="xs"> + Saving acts as the account at {value}. Ask its owner for read access to it, or create a new + trigger with your own account. + </Alert> + {/if} +</div> + +<AppConnectDrawer + bind:this={connectDrawer} + native={{ + title: `Connect a ${displayName} account`, + defaultName: `native_${service}`, + connect + }} +/> + +<ConfirmationModal {...confirmationModal.props} /> diff --git a/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte b/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte new file mode 100644 index 0000000000..18c9428d76 --- /dev/null +++ b/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte @@ -0,0 +1,69 @@ +<script lang="ts"> + import { onMount } from 'svelte' + import { page } from '$app/state' + import { WorkspaceIntegrationService } from '$lib/gen' + import type { NativeServiceName } from '$lib/gen/types.gen' + import Alert from '$lib/components/common/alert/Alert.svelte' + import { Loader2 } from 'lucide-svelte' + import { postNativeOAuthResult } from './utils' + + interface Props { + /** The exact redirect URI the authorization request was made with. */ + redirectUri: string + } + + let { redirectUri }: Props = $props() + + let outcome = $state<{ ok: true; path: string } | { ok: false; error: string } | undefined>() + + // The signed state carries the workspace and service it was issued for, so this page works + // whatever workspace is selected and wherever the provider sends the user back. + function decodeState(state: string): { workspace: string; service: NativeServiceName } { + const payload = atob(state.split(':')[0].replace(/-/g, '+').replace(/_/g, '/')) + const [workspace, service] = payload.split(':') + return { workspace, service: service as NativeServiceName } + } + + async function finish(): Promise<{ ok: true; path: string } | { ok: false; error: string }> { + const error = page.url.searchParams.get('error') + const code = page.url.searchParams.get('code') + const state = page.url.searchParams.get('state') + if (error || !code || !state) { + return { ok: false, error: error ?? 'The provider returned no authorization code' } + } + try { + const { workspace, service } = decodeState(state) + const path = await WorkspaceIntegrationService.nativeTriggerServiceCallback({ + workspace, + serviceName: service, + requestBody: { code, state, redirect_uri: redirectUri } + }) + return { ok: true, path } + } catch (err: any) { + return { ok: false, error: err.body ?? err.message ?? String(err) } + } + } + + onMount(async () => { + outcome = await finish() + postNativeOAuthResult(outcome) + if (window.opener) { + window.close() + } + }) +</script> + +<div class="max-w-lg mx-auto mt-16 px-4"> + {#if outcome === undefined} + <div class="flex items-center gap-2 text-sm text-secondary"> + <Loader2 class="animate-spin" size={16} /> + Finishing the connection... + </div> + {:else if outcome.ok} + <Alert type="success" title="Account connected"> + Saved as {outcome.path}. You can close this window. + </Alert> + {:else} + <Alert type="error" title="Could not connect the account">{outcome.error}</Alert> + {/if} +</div> diff --git a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte index 9e8dc592e9..bf8fe0f7d1 100644 --- a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte @@ -6,8 +6,10 @@ validateCommonFields, getServiceConfig, getTemplatePath, - saveNativeTriggerFromCfg + saveNativeTriggerFromCfg, + setNativeConnectionContext } from './utils' + import NativeConnectionPicker from './NativeConnectionPicker.svelte' import { usedTriggerKinds } from '$lib/stores' import { emptyString, sendUserToast } from '$lib/utils' import { useEditRights, useTriggerLock } from '$lib/operatorWriteRights' @@ -28,15 +30,10 @@ import { deepEqual } from 'fast-equals' import type { Snippet } from 'svelte' import Alert from '$lib/components/common/alert/Alert.svelte' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const triggerLock = useTriggerLock() const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const editRights = useEditRights() interface Props { @@ -130,6 +127,8 @@ let externalError = $state<string | undefined>(undefined) let retryEdit = $state<(() => void) | undefined>(undefined) let enabled = $state(true) + let connectionPath = $state<string | undefined>(undefined) + setNativeConnectionContext(() => connectionPath) export function openNew( nis_flow?: boolean, @@ -161,6 +160,7 @@ externalError = undefined retryEdit = undefined enabled = true + connectionPath = undefined } export function openRecreate(nativeTrigger: ExtendedNativeTrigger) { @@ -190,6 +190,7 @@ externalError = undefined retryEdit = undefined enabled = nativeTrigger.enabled + connectionPath = nativeTrigger.connection_path ?? undefined } export async function openEdit( @@ -224,6 +225,7 @@ initialScriptPath = '' summary = '' enabled = true + connectionPath = undefined try { const fullTrigger = await NativeTriggerService.getNativeTrigger({ @@ -241,6 +243,7 @@ externalData = fullTrigger.external_data externalError = fullTrigger.external_error ?? undefined enabled = fullTrigger.enabled + connectionPath = fullTrigger.connection_path ?? undefined // Apply default values if provided (for draft triggers) if (defaultValues) { @@ -268,7 +271,8 @@ script_path: scriptPath, is_flow: isFlow, service_config: serviceConfig, - summary: summary !== '' ? summary : undefined + summary: summary !== '' ? summary : undefined, + connection_path: connectionPath } } @@ -313,7 +317,8 @@ loadingForm || !can_write || !hasChanged || - loadError !== undefined + loadError !== undefined || + (isNew && !connectionPath) ) const saveCfg = $derived.by(getSaveCfg) @@ -540,7 +545,7 @@ bind:itemKind kinds={['script']} allowFlow={true} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> {#if emptyString(scriptPath)} @@ -562,6 +567,17 @@ </Section> {/if} + {#if !loadingConfig} + <Section label="{serviceInfo?.serviceDisplayName} account"> + <NativeConnectionPicker + {service} + bind:value={connectionPath} + locked={!isNew} + disabled={loading || !can_write} + /> + </Section> + {/if} + {#if loadingConfig} <Section label="{serviceInfo?.serviceDisplayName} configuration"> <div class="flex items-center gap-2 text-secondary text-xs"> @@ -569,34 +585,39 @@ Loading configuration from {serviceInfo?.serviceDisplayName}... </div> </Section> + {:else if isNew && !connectionPath} + <!-- The pickers browse the service as the chosen account, so there is nothing to + configure until one is chosen. --> {:else if ServiceFormComponent} - <ServiceFormComponent - bind:loading={loadingForm} - bind:this={serviceFormRef} - bind:serviceConfig - bind:errors - {externalData} - disabled={loading || loadingConfig || !can_write} - path={scriptPath} - {isFlow} - token="" - triggerTokens={undefined} - scopes={[]} - /> + {#key connectionPath} + <ServiceFormComponent + bind:loading={loadingForm} + bind:this={serviceFormRef} + bind:serviceConfig + bind:errors + {externalData} + disabled={loading || loadingConfig || !can_write} + path={scriptPath} + {isFlow} + token="" + triggerTokens={undefined} + scopes={[]} + /> + {/key} {:else} <Section label="{serviceInfo?.serviceDisplayName} configuration"> <div class="text-red-500 text-xs space-y-2"> <div>Failed to load service configuration component for {service}.</div> <div class="text-secondary"> - Ensure your workspace has a connected {serviceInfo?.serviceDisplayName} integration. + Check that {serviceInfo?.serviceDisplayName} is configured in the native trigger settings. </div> <Button unifiedSize="xs" variant="default" - href="/workspace_settings?tab=integrations" + href="/workspace_settings?tab=native_triggers" target="_blank" > - Manage integrations + Native trigger settings </Button> </div> </Section> diff --git a/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte b/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte index 27add7f797..c058a41560 100644 --- a/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte +++ b/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte @@ -7,8 +7,10 @@ import { sendUserToast } from '$lib/toast' import { Loader2 } from 'lucide-svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useNativeConnection } from '../../utils' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { serviceConfig: Record<string, any> @@ -66,7 +68,8 @@ loading = true try { repos = await NativeTriggerService.listGithubRepos({ - workspace: $operatingWorkspace + workspace: $operatingWorkspace, + connectionPath: connectionPath() }) } catch (err: any) { console.error('Failed to load GitHub repositories:', err) diff --git a/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte b/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte index f4c6d9894b..3252d7c6aa 100644 --- a/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte +++ b/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte @@ -6,8 +6,10 @@ import { Loader2, X, RefreshCw } from 'lucide-svelte' import GoogleCalendarIcon from '$lib/components/icons/GoogleCalendarIcon.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useNativeConnection } from '../../utils' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { calendarId: string @@ -26,7 +28,8 @@ loading = true try { calendars = await NativeTriggerService.listGoogleCalendars({ - workspace: $operatingWorkspace + workspace: $operatingWorkspace, + connectionPath: connectionPath() }) if (calendarId && !calendarName) { const found = calendars.find((c) => c.id === calendarId) diff --git a/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte b/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte index 597eb7d514..26e82dbdde 100644 --- a/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte +++ b/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte @@ -9,8 +9,10 @@ import { Debounced, watch } from 'runed' import { untrack } from 'svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useNativeConnection } from '../../utils' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { resourceId: string @@ -53,6 +55,7 @@ try { const params: Parameters<typeof NativeTriggerService.listGoogleDriveFiles>[0] = { workspace: $operatingWorkspace, + connectionPath: connectionPath(), pageToken } @@ -98,7 +101,8 @@ try { sharedDrives = await NativeTriggerService.listGoogleSharedDrives({ - workspace: $operatingWorkspace + workspace: $operatingWorkspace, + connectionPath: connectionPath() }) } catch (err: any) { sendUserToast(`Failed to load shared drives: ${err.body || err.message}`, true) diff --git a/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte b/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte index 780ccde9e8..d4f01478ef 100644 --- a/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte +++ b/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte @@ -6,10 +6,11 @@ import SchemaForm from '$lib/components/SchemaForm.svelte' import Section from '$lib/components/Section.svelte' import { Loader2 } from 'lucide-svelte' - import { getNextcloudSchema } from '../../utils' + import { getNextcloudSchema, useNativeConnection } from '../../utils' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { serviceConfig: Record<string, any> @@ -49,7 +50,8 @@ eventsError = undefined try { const events = await NativeTriggerService.listNextCloudEvents({ - workspace: $operatingWorkspace! + workspace: $operatingWorkspace!, + connectionPath: connectionPath() }) availableEvents = events serviceSchema = getNextcloudSchema(events) @@ -116,16 +118,14 @@ {#if eventsError} <div class="break-words">Could not load the available events: {eventsError}</div> {:else} - <div - >No events available. Please ensure your workspace has a connected Nextcloud integration.</div - > + <div>No events available. Check that the selected Nextcloud account can reach the server.</div> {/if} <div class="flex gap-2"> <Button variant="default" on:click={loadAvailableEvents} {disabled}> Retry loading events </Button> - <Button variant="subtle" href="/workspace_settings?tab=integrations" target="_blank"> - Manage integrations + <Button variant="subtle" href="/workspace_settings?tab=native_triggers" target="_blank"> + Native trigger settings </Button> </div> </div> @@ -140,8 +140,7 @@ /> {:else} <div class="text-secondary text-xs"> - Please ensure Nextcloud workspace integration is connected to load available configuration - options. + Select a Nextcloud account to load the available configuration options. </div> {/if} </Section> diff --git a/frontend/src/lib/components/triggers/native/utils.ts b/frontend/src/lib/components/triggers/native/utils.ts index b411429d74..5d0a7f0fca 100644 --- a/frontend/src/lib/components/triggers/native/utils.ts +++ b/frontend/src/lib/components/triggers/native/utils.ts @@ -2,11 +2,97 @@ import type { NativeServiceName, NativeTrigger, NativeTriggerData } from '$lib/g import { isCloudHosted } from '$lib/cloud' import { NativeTriggerService, WorkspaceIntegrationService } from '$lib/gen' import { get, type Writable } from 'svelte/store' +import { getContext, setContext } from 'svelte' import { sendUserToast } from '$lib/toast' +const CONNECTION_CONTEXT = Symbol('nativeTriggerConnection') + +/** Makes the connection a trigger editor acts through available to the pickers of its form. */ +export function setNativeConnectionContext(connectionPath: () => string | undefined) { + setContext(CONNECTION_CONTEXT, connectionPath) +} + +/** The connection the service pickers browse through; undefined lets the server pick. */ +export function useNativeConnection(): () => string | undefined { + return getContext<(() => string | undefined) | undefined>(CONNECTION_CONTEXT) ?? (() => undefined) +} + +const CONNECT_MESSAGE = 'native_trigger_oauth' + +/** Turns the resource connect drawer into the connect step of a native trigger account. */ +export type NativeConnect = { + title: string + defaultName: string + /** Rejects when the connection was not saved; the drawer then stays open on the path. */ + connect: (path: string) => Promise<void> +} + +export type NativeOAuthMessage = + | { type: typeof CONNECT_MESSAGE; ok: true; path: string } + | { type: typeof CONNECT_MESSAGE; ok: false; error: string } + +/** The page the provider redirects to, as registered on the workspace's OAuth apps. */ +export function nativeOAuthRedirectUri(service: NativeServiceName): string { + return `${window.location.origin}/workspace_settings?tab=native_triggers&service=${service}` +} + +/** Hands the outcome of a connect popup back to the page that opened it. */ +export function postNativeOAuthResult( + result: { ok: true; path: string } | { ok: false; error: string } +) { + const message = { type: CONNECT_MESSAGE, ...result } as NativeOAuthMessage + window.opener?.postMessage(message, window.location.origin) +} + +/** + * Connect an account in a popup and resolve with the path of the saved connection. The + * connection is saved at `resourcePath`, or at the caller's default path when omitted. + */ +export async function connectNativeAccount( + workspace: string, + service: NativeServiceName, + resourcePath?: string +): Promise<string> { + const authUrl = await WorkspaceIntegrationService.generateNativeTriggerServiceConnectUrl({ + workspace, + serviceName: service, + requestBody: { redirect_uri: nativeOAuthRedirectUri(service), resource_path: resourcePath } + }) + const popup = window.open(authUrl, '_blank', 'popup,width=600,height=750') + if (!popup) { + throw new Error('The connection window was blocked. Allow popups for this site and retry.') + } + return new Promise((resolve, reject) => { + const onMessage = (event: MessageEvent<NativeOAuthMessage>) => { + if (event.origin !== window.location.origin || event.data?.type !== CONNECT_MESSAGE) return + cleanup() + if (event.data.ok) resolve(event.data.path) + else reject(new Error(event.data.error)) + } + // The callback page posts its result and then closes itself, so a closed window may still + // have a message in flight: give it a moment before treating the close as a cancel. + const closedPoll = setInterval(() => { + if (popup.closed) { + clearInterval(closedPoll) + setTimeout(() => { + cleanup() + reject(new Error('The connection window was closed before finishing')) + }, 1000) + } + }, 500) + function cleanup() { + window.removeEventListener('message', onMessage) + clearInterval(closedPoll) + } + window.addEventListener('message', onMessage) + }) +} + export interface NativeTriggerConfig { readonly serviceDisplayName: string readonly serviceKey: NativeServiceName + /** The type of the resource a connection is saved as. */ + readonly resourceType: string readonly supportsSync: boolean readonly isCloudCompatible: boolean readonly templates?: { @@ -19,6 +105,7 @@ export const NATIVE_TRIGGER_SERVICES: Record<NativeServiceName, NativeTriggerCon nextcloud: { serviceDisplayName: 'Nextcloud', serviceKey: 'nextcloud', + resourceType: 'nextcloud', supportsSync: true, isCloudCompatible: true, templates: { @@ -30,6 +117,7 @@ export const NATIVE_TRIGGER_SERVICES: Record<NativeServiceName, NativeTriggerCon google: { serviceDisplayName: 'Google', serviceKey: 'google', + resourceType: 'gworkspace', supportsSync: true, isCloudCompatible: true, templates: { @@ -40,6 +128,7 @@ export const NATIVE_TRIGGER_SERVICES: Record<NativeServiceName, NativeTriggerCon github: { serviceDisplayName: 'GitHub', serviceKey: 'github', + resourceType: 'github', supportsSync: true, isCloudCompatible: true, templates: { @@ -216,8 +305,13 @@ export async function saveNativeTriggerFromCfg( service_config: triggerCfg.service_config, summary: triggerCfg.summary } - // Only a create can set it: an update ignores the field, and `setenabled` owns it thereafter. - const createBody: NativeTriggerData = { ...requestBody, enabled: triggerCfg.enabled ?? true } + // Only a create can set these: an update ignores both, `setenabled` owns `enabled` thereafter, + // and the connection stays the one the webhook was registered under. + const createBody: NativeTriggerData = { + ...requestBody, + enabled: triggerCfg.enabled ?? true, + connection_path: triggerCfg.connection_path + } const serviceName = NATIVE_TRIGGER_SERVICES[service].serviceDisplayName diff --git a/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte index e0ba992e12..db95d73e7f 100644 --- a/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte @@ -84,7 +84,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -578,7 +577,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} > {#snippet createButton()} {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte index 68ee8816b7..402cca53fb 100644 --- a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte @@ -103,7 +103,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -760,7 +759,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptText="Pick a script or flow to be triggered " promptClass="text-xs text-primary" > diff --git a/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte b/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte index 48227dea44..5e167a4337 100644 --- a/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte +++ b/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte @@ -141,9 +141,9 @@ ? editRights.roleCanAuthor('schedule') : editRights.canEditItem('schedule', permsPath, extraPerms) ) - // Editing the runnable is closed to operators, and an unresolved acting user is no - // evidence that this one isn't. - const canEditRunnable = $derived(actingUser !== undefined && !actingUser.operator) + // Editing the runnable needs a role that authors its kind; an unresolved acting user is no + // evidence of that role. + const canEditRunnable = $derived(actingUser !== undefined && editRights.roleCanAuthor(itemKind)) const saveDisabled = $derived( !allowSchedule || pathError != '' || diff --git a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte index 5593dd121f..77f9478026 100644 --- a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte @@ -88,7 +88,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -561,7 +560,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptText="Pick a script or flow to be triggered " > {#snippet createButton()} diff --git a/frontend/src/lib/components/triggers/triggers.svelte.ts b/frontend/src/lib/components/triggers/triggers.svelte.ts index 7fe40d111d..8ee12aaaea 100644 --- a/frontend/src/lib/components/triggers/triggers.svelte.ts +++ b/frontend/src/lib/components/triggers/triggers.svelte.ts @@ -32,6 +32,7 @@ import type { UserExt } from '$lib/stores' import type { ScheduleTrigger } from '../triggers' import { formatCron, generateRandomString } from '$lib/utils' import { canEditItem } from '$lib/editRights' +import { capabilitiesIn } from '$lib/roleCapabilities' export class Triggers { #triggers = $state<Trigger[]>([]) @@ -135,9 +136,10 @@ export class Triggers { user: UserExt | undefined = undefined ): number { const currentTriggers = this.#triggers - const operatorSettings = get(userWorkspaces).find( - (w) => w.id === workspaceId - )?.operator_settings + const caps = capabilitiesIn( + user, + get(userWorkspaces).find((w) => w.id === workspaceId) + ) const kind = type === 'schedule' ? 'schedule' : 'trigger' // Identify triggers with draftConfig to preserve const configuredTriggers = currentTriggers.filter( @@ -157,7 +159,7 @@ export class Triggers { path: trigger.path, isPrimary: type === 'schedule' && trigger.path === trigger.script_path, isDraft: false, - canWrite: canEditItem(kind, trigger.path, trigger.extra_perms, user, operatorSettings), + canWrite: canEditItem(kind, trigger.path, trigger.extra_perms, user, caps), draftConfig: draftConfig, lightConfig: getLightConfig(type, trigger) } diff --git a/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte index b011d6fee1..5d19535b01 100644 --- a/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte @@ -105,7 +105,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -637,7 +636,7 @@ bind:itemKind bind:scriptPath={script_path} allowRefresh={can_write} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/variables/VariablesList.svelte b/frontend/src/lib/components/variables/VariablesList.svelte index 3805b51bbb..c01eb5dbd4 100644 --- a/frontend/src/lib/components/variables/VariablesList.svelte +++ b/frontend/src/lib/components/variables/VariablesList.svelte @@ -36,7 +36,7 @@ import Tooltip from '$lib/components/Tooltip.svelte' import VariableEditor from '$lib/components/VariableEditor.svelte' import type { ContextualVariable, ListableVariable, WorkspaceDeployUISettings } from '$lib/gen' - import { enterpriseLicense, userWorkspaces } from '$lib/stores' + import { enterpriseLicense } from '$lib/stores' import { sendUserToast } from '$lib/toast' import { isOwner, truncate } from '$lib/utils' import { useEditRights } from '$lib/operatorWriteRights' @@ -50,6 +50,7 @@ Shield, Trash, Building, + CalendarClock, DollarSign, EyeOff, Circle, @@ -60,11 +61,13 @@ import { useHostedPage } from '$lib/components/hostedPage' import { useOperatingWorkspace, - useOperatingUser + useOperatingUser, + useReadOnlyWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const readOnly = useReadOnlyWorkspace() const editRights = useEditRights() const hosted = useHostedPage() @@ -317,10 +320,10 @@ <DeployWorkspaceDrawer bind:this={deploymentDrawer} /> -{#if operatingUser.current?.operator && $operatingWorkspace && !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.variables} +{#if $operatingWorkspace && !editRights.capabilities.visibility.variables} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage> @@ -439,7 +442,7 @@ </tr> </Head> <tbody class="divide-y"> - {#each filteredItems as { path, value, is_secret, description, extra_perms, canWrite, account, is_refreshed, is_expired, refresh_error, is_linked, labels, inherited_labels, ws_specific, draft_only, is_draft }} + {#each filteredItems as { path, value, is_secret, description, extra_perms, canWrite, account, is_refreshed, is_expired, refresh_error, is_linked, labels, inherited_labels, ws_specific, draft_only, is_draft, value_valid_until }} {@const hasDraft = getLocalDraftHint($operatingWorkspace, 'variable', path) ?? is_draft} <Row> @@ -520,6 +523,21 @@ {/snippet} </Popover> {/if} + {#if value_valid_until} + {@const expired = new Date(value_valid_until).getTime() <= Date.now()} + <Popover notClickable> + <CalendarClock + size={16} + class={expired ? 'text-red-600' : 'text-secondary'} + /> + {#snippet text()} + <div> + The value {expired ? 'expired' : 'expires'} on + {new Date(value_valid_until).toLocaleString()}. + </div> + {/snippet} + </Popover> + {/if} {#if account} <Popover notClickable> <RefreshCw size={16} /> @@ -694,8 +712,8 @@ headers={['Name', 'Value']} data={contextualVariables.filter((x) => x.is_custom)} keys={['name', 'value']} - getRowActions={operatingUser.current?.is_admin || - operatingUser.current?.is_super_admin + getRowActions={!readOnly($operatingWorkspace) && + (operatingUser.current?.is_admin || operatingUser.current?.is_super_admin) ? (row) => { return [ { diff --git a/frontend/src/lib/components/workspaceSettings/AISettings.svelte b/frontend/src/lib/components/workspaceSettings/AISettings.svelte index 05159e3057..79d7be2214 100644 --- a/frontend/src/lib/components/workspaceSettings/AISettings.svelte +++ b/frontend/src/lib/components/workspaceSettings/AISettings.svelte @@ -520,6 +520,9 @@ resourceType={provider === 'openai' && usingOpenaiClientCredentialsOauth ? 'openai_client_credentials_oauth' : provider} + additionalResourceTypes={provider === 'anthropic' + ? ['anthropic_federated'] + : []} initialValue={aiProviders[provider].resource_path} bind:value={ () => aiProviders[provider].resource_path || undefined, diff --git a/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte b/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte index 2afcbce3c8..d6a43364f0 100644 --- a/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte +++ b/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte @@ -34,7 +34,7 @@ devWorkspacesInChainAbove } from '$lib/utils/workspaceHierarchy' import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte' - import { isOperatorInWorkspace } from '$lib/components/sidebar/operatorRoutes' + import { capabilitiesIn, isRestricted } from '$lib/roleCapabilities' import { canUserBypassRuleKindInRulesets, fetchProtectionRulesForWorkspace, @@ -138,14 +138,14 @@ let forkableWorkspaces = $derived(forkable.current) // Base candidates are the current workspace's family: its root first, then every fork/dev under it. - // Never one the user is an operator in: a fork does not carry the role, so forking such a base + // Never one the user holds a restricted role in: a fork does not carry the role, so forking such a base // would hand them a full-rights copy of it. let familyRoot = $derived(findWorkspaceRoot($workspaceStore, forkableWorkspaces)) let baseCandidates = $derived( (familyRoot ? [familyRoot, ...findWorkspaceDescendants(familyRoot.id, forkableWorkspaces)] : [] - ).filter((w) => !isOperatorInWorkspace(w)) + ).filter((w) => !isRestricted(capabilitiesIn(undefined, w))) ) let baseItems = $derived( baseCandidates.map((w) => ({ @@ -1112,7 +1112,7 @@ <span class="text-2xs text-secondary">(optional but recommended)</span> </label> - <ToggleButtonGroup bind:selected> + <ToggleButtonGroup bind:selected wrap> {#snippet children({ item })} <ToggleButton value="openai" label="OpenAI" {item} /> <ToggleButton value="anthropic" label="Anthropic" {item} /> @@ -1123,6 +1123,7 @@ <div class="flex flex-row gap-1"> <input id="ai-key" + class="flex-1 min-w-0" type="password" autocomplete="new-password" bind:value={aiKey} diff --git a/frontend/src/lib/components/workspaceSettings/OAuthClientConfig.svelte b/frontend/src/lib/components/workspaceSettings/OAuthClientConfig.svelte index 1a6f15345f..86d224160c 100644 --- a/frontend/src/lib/components/workspaceSettings/OAuthClientConfig.svelte +++ b/frontend/src/lib/components/workspaceSettings/OAuthClientConfig.svelte @@ -1,11 +1,14 @@ <script lang="ts"> + import type { Snippet } from 'svelte' import { sendUserToast } from '$lib/utils' import { Button, Alert } from '$lib/components/common' - import Label from '$lib/components/Label.svelte' + import Modal from '$lib/components/common/modal/Modal.svelte' + import TextInput from '$lib/components/text_input/TextInput.svelte' import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte' - import { Save, ExternalLink } from 'lucide-svelte' + import { ExternalLink } from 'lucide-svelte' interface Props { + open: boolean serviceName: string serviceDisplayName: string existingConfig?: { @@ -16,178 +19,147 @@ redirectUri: string onConfigSaved: (oauthData: any) => Promise<void> requiresBaseUrl?: boolean - baseUrlLabel?: string baseUrlPlaceholder?: string baseUrlSettingsPath?: string clientIdPlaceholder?: string clientSecretPlaceholder?: string setupInstructions?: string[] + /** Shown above the form, for what the service needs before it can be connected. */ + requirements?: Snippet } let { + open = $bindable(), serviceName, serviceDisplayName, existingConfig, onConfigSaved, redirectUri, requiresBaseUrl = true, - baseUrlLabel = `${serviceDisplayName} base URL`, baseUrlPlaceholder = `https://your-${serviceName}.example.com`, baseUrlSettingsPath = '/settings/admin/security', clientIdPlaceholder = `Generated by ${serviceDisplayName} OAuth app`, clientSecretPlaceholder = `Generated by ${serviceDisplayName} OAuth app`, - setupInstructions + setupInstructions, + requirements }: Props = $props() let saving = $state(false) let clientId = $state('') let clientSecret = $state('') let baseUrl = $state('') + $effect(() => { - if (existingConfig) { - clientId = existingConfig.client_id - clientSecret = existingConfig.client_secret - baseUrl = existingConfig.base_url + if (open) { + clientId = existingConfig?.client_id ?? '' + clientSecret = existingConfig?.client_secret ?? '' + baseUrl = existingConfig?.base_url ?? '' } }) - let canSave = $derived( - !saving && - !!clientId.trim() && - !!clientSecret.trim() && - (!requiresBaseUrl || !!baseUrl.trim()) + const baseUrlValid = $derived.by(() => { + try { + return ['http:', 'https:'].includes(new URL(baseUrl.trim()).protocol) + } catch { + return false + } + }) + + const canSave = $derived( + !saving && !!clientId.trim() && !!clientSecret.trim() && (!requiresBaseUrl || baseUrlValid) ) - async function saveConfig() { - if (!canSave) { - sendUserToast('Please fill in all required fields', true) - return - } - + async function save() { + if (!canSave) return saving = true try { - const oauthData: Record<string, string> = { + await onConfigSaved({ client_id: clientId.trim(), client_secret: clientSecret.trim(), base_url: requiresBaseUrl ? baseUrl.trim().replace(/\/+$/, '') : '', redirect_uri: redirectUri.trim() - } - - await onConfigSaved(oauthData) - resetForm() + }) } catch (err: any) { - sendUserToast(`Failed to configure OAuth client: ${err.message}`, true) + sendUserToast(`Failed to save the OAuth app: ${err.message}`, true) } finally { saving = false } } - - function resetForm() { - clientId = '' - clientSecret = '' - } - - </script> -<div class="space-y-4"> - <div class="flex justify-between items-center"> - <h4 class="text-md font-medium text-primary">{serviceDisplayName} OAuth Client Configuration</h4 - > - </div> +<Modal + bind:open + title="{serviceDisplayName} OAuth app" + description="Members connect their {serviceDisplayName} accounts through this app." + cancelText="Cancel" +> + <div class="flex flex-col gap-6"> + {@render requirements?.()} - {#if !existingConfig} - <Alert type="warning" title="OAuth client required"> - <p class="text-sm mb-2"> - Before you can connect to {serviceDisplayName}, you need to configure an OAuth client. - </p> - {#if setupInstructions} - <ol class="list-decimal list-inside space-y-1 text-sm"> + {#if !existingConfig && setupInstructions} + <Alert type="info" title="Create an OAuth app in {serviceDisplayName}"> + <ol class="list-decimal list-inside flex flex-col gap-1"> {#each setupInstructions as instruction} <li>{@html instruction}</li> {/each} </ol> - {/if} - </Alert> - {/if} + </Alert> + {/if} - <div class="space-y-4"> - <div class="space-y-4"> - {#if requiresBaseUrl} - <div class="flex flex-col gap-1"> - <Label label={baseUrlLabel} /> - <p class="text-xs font-normal text-secondary" - >The base URL of your {serviceDisplayName} instance (without trailing slash)</p - > - <input - type="url" - bind:value={baseUrl} - placeholder={baseUrlPlaceholder} - class="windmill-input" - disabled={saving} - /> - {#if baseUrl && baseUrlSettingsPath} + {#if requiresBaseUrl} + <div class="flex flex-col gap-1"> + <div class="text-xs font-semibold text-emphasis">{serviceDisplayName} URL</div> + <div class="text-xs text-secondary">The address of your {serviceDisplayName} server</div> + <TextInput + bind:value={baseUrl} + error={!!baseUrl.trim() && !baseUrlValid} + inputProps={{ type: 'url', placeholder: baseUrlPlaceholder, disabled: saving }} + /> + {#if baseUrl.trim() && !baseUrlValid} + <div class="text-2xs text-red-500">Enter a full address, starting with https://</div> + {/if} + {#if baseUrlValid && baseUrlSettingsPath} + <div class="flex"> <Button - wrapperClasses="self-start" - href={`${baseUrl}${baseUrlSettingsPath}`} + unifiedSize="sm" + variant="subtle" + href={`${baseUrl.replace(/\/+$/, '')}${baseUrlSettingsPath}`} target="_blank" startIcon={{ icon: ExternalLink }} > - {serviceDisplayName} OAuth Settings + Open the {serviceDisplayName} OAuth settings </Button> - {/if} - </div> - {/if} - - <div class="flex flex-col gap-1"> - <Label label="Redirect URI" /> - <p class="text-xs font-normal text-secondary" - >Use this URL when creating the OAuth app in {serviceDisplayName}</p - > - <ClipboardPanel content={redirectUri} size="sm" /> + </div> + {/if} </div> + {/if} - <div class="flex flex-col gap-1"> - <Label label="Client ID" /> - <input - type="text" - bind:value={clientId} - placeholder={clientIdPlaceholder} - class="windmill-input" - disabled={saving} - /> + <div class="flex flex-col gap-1"> + <div class="text-xs font-semibold text-emphasis">Redirect URI</div> + <div class="text-xs text-secondary"> + Register this URL when creating the OAuth app in {serviceDisplayName} </div> + <ClipboardPanel content={redirectUri} size="sm" /> + </div> - <div class="flex flex-col gap-1"> - <Label label="Client secret" /> - <input - type="password" - bind:value={clientSecret} - placeholder={clientSecretPlaceholder} - class="windmill-input" - disabled={saving} - /> - </div> + <div class="flex flex-col gap-1"> + <div class="text-xs font-semibold text-emphasis">Client ID</div> + <TextInput + bind:value={clientId} + inputProps={{ placeholder: clientIdPlaceholder, disabled: saving }} + /> + </div> - <div class="flex gap-2"> - <Button - color="blue" - onclick={saveConfig} - disabled={!canSave} - startIcon={{ icon: Save }} - > - {saving ? 'Saving...' : 'Save configuration'} - </Button> - </div> + <div class="flex flex-col gap-1"> + <div class="text-xs font-semibold text-emphasis">Client secret</div> + <TextInput + bind:value={clientSecret} + inputProps={{ type: 'password', placeholder: clientSecretPlaceholder, disabled: saving }} + /> </div> </div> - {#if existingConfig} - <Alert type="success" title="OAuth client configured"> - <p class="text-sm"> - OAuth client is configured for {serviceDisplayName}. You can now connect this workspace to - {serviceDisplayName}. - </p> - </Alert> - {/if} -</div> + {#snippet actions()} + <Button variant="accent" disabled={!canSave} loading={saving} onclick={save}>Save</Button> + {/snippet} +</Modal> diff --git a/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte b/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte index 622a9620a4..e1b8672e03 100644 --- a/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte +++ b/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte @@ -4,22 +4,25 @@ import { Button, Alert } from '$lib/components/common' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte' - import { Check, X, ExternalLink, Cog, Plug } from 'lucide-svelte' + import { Check, ExternalLink, KeyRound, Pencil, Trash2 } from 'lucide-svelte' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import type { Item } from '$lib/utils' import NextcloudIcon from '$lib/components/icons/NextcloudIcon.svelte' import GithubIcon from '$lib/components/icons/GithubIcon.svelte' import GoogleIcon from '$lib/components/icons/GoogleIcon.svelte' - import { WorkspaceIntegrationService, type NativeServiceName } from '$lib/gen' - import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte' + import { + WorkspaceIntegrationService, + type NativeServiceName, + type NativeTriggerConnection + } from '$lib/gen' import OAuthClientConfig from './OAuthClientConfig.svelte' import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte' import { createAsyncConfirmationModal } from '../common/confirmationModal/asyncConfirmationModal.svelte' - import Path from '$lib/components/Path.svelte' - import { page } from '$app/state' - import { goto } from '$app/navigation' + import NativeConnectionPicker from '$lib/components/triggers/native/NativeConnectionPicker.svelte' + import { nativeOAuthRedirectUri } from '$lib/components/triggers/native/utils' interface WorkspaceIntegration { service_name: string - resource_path?: string oauth_data: { client_id: string client_secret: string @@ -44,7 +47,7 @@ nextcloud: { name: 'nextcloud', displayName: 'Nextcloud', - description: 'Connect to Nextcloud for file operations and webhook triggers', + description: 'File events', icon: NextcloudIcon, docsUrl: 'https://www.windmill.dev/docs/integrations/nextcloud', setupInstructions: [ @@ -56,7 +59,7 @@ google: { name: 'google', displayName: 'Google', - description: 'Connect to Google for Drive and Calendar triggers', + description: 'Drive and Calendar changes', icon: GoogleIcon, docsUrl: 'https://www.windmill.dev/docs/core_concepts/native_triggers#google-triggers', requiresBaseUrl: false, @@ -73,7 +76,7 @@ github: { name: 'github', displayName: 'GitHub', - description: 'Connect to GitHub for repository webhook triggers', + description: 'Repository events', icon: GithubIcon, docsUrl: 'https://www.windmill.dev/docs/core_concepts/native_triggers#github-triggers', requiresBaseUrl: false, @@ -89,18 +92,13 @@ } let integrations = $state<WorkspaceIntegration[]>([]) + let connections = $state<Record<string, NativeTriggerConnection[]>>({}) let loading = $state(false) - let connecting = $state<string | null>(null) - let showingConfig = $state<string | null>(null) + // The service whose OAuth app dialog is open. + let configOpen = $state<Record<string, boolean>>( + Object.fromEntries(Object.keys(supportedServices).map((s) => [s, false])) + ) let instanceSharingAvailable = $state<Record<string, boolean>>({}) - let pendingCallback = $state<{ - serviceName: NativeServiceName - code: string - state: string - workspace: string - } | null>(null) - let resourcePath = $state<string | undefined>(undefined) - let pathError = $state<string | undefined>(undefined) let confirmationModal = createAsyncConfirmationModal() async function loadIntegrations() { @@ -113,9 +111,9 @@ }) integrations = response.map((item) => ({ service_name: item.service_name, - resource_path: item.resource_path ?? undefined, oauth_data: item.oauth_data || null })) + await Promise.all(Object.keys(supportedServices).map(loadConnections)) } catch (err: any) { console.error('Failed to load workspace integrations:', err) sendUserToast(`Failed to load integrations: ${err.message}`, true) @@ -124,59 +122,132 @@ } } + async function loadConnections(serviceName: string) { + if (!$workspaceStore) return + try { + connections[serviceName] = await WorkspaceIntegrationService.listNativeTriggerConnections({ + workspace: $workspaceStore, + serviceName: serviceName as NativeServiceName + }) + } catch { + connections[serviceName] = [] + } + } + async function deleteIntegration(serviceName: string) { if (!$workspaceStore) return const displayName = supportedServices[serviceName]?.displayName ?? serviceName const confirmed = await confirmationModal.ask({ - title: `Disconnect ${displayName}?`, - confirmationText: 'Disconnect', - children: `This will delete all ${displayName} triggers associated with this integration. This action cannot be undone.` + title: `Remove the ${displayName} configuration?`, + confirmationText: 'Remove', + children: `This deletes the workspace's ${displayName} OAuth app, every ${displayName} account connected through it and all ${displayName} triggers, which stop receiving events. This action cannot be undone.` }) if (!confirmed) return try { await WorkspaceIntegrationService.deleteNativeTriggerService({ workspace: $workspaceStore, - serviceName: serviceName as any + serviceName: serviceName as NativeServiceName }) - sendUserToast(`${displayName} disconnected successfully`) + sendUserToast(`${displayName} integration removed`) loadIntegrations() } catch (err: any) { - sendUserToast(`Failed to disconnect ${displayName}: ${err.message}`, true) + sendUserToast(`Failed to remove ${displayName}: ${err.body ?? err.message}`, true) } } - async function connectService(serviceName: string, redirectUri: string) { - if (!$workspaceStore) return + async function setWorkspaceConnection( + serviceName: string, + path: string | undefined + ): Promise<boolean> { + if (!$workspaceStore) return false - connecting = serviceName - try { - const auth_url = await WorkspaceIntegrationService.generateNativeTriggerServiceConnectUrl({ - workspace: $workspaceStore, - serviceName: serviceName as any, - requestBody: { redirect_uri: redirectUri } + const displayName = supportedServices[serviceName]?.displayName ?? serviceName + if (path) { + const owner = connections[serviceName]?.find((c) => c.path === path)?.owner + const account = owner ? `this account, connected by ${owner}` : 'this account' + const browsable: string | undefined = ( + { google: 'its Drive files and calendars', github: 'its repositories' } as Record< + string, + string + > + )[serviceName] + const browse = browsable ? `, and browse ${browsable} in the trigger editor` : '' + const confirmed = await confirmationModal.ask({ + title: `Share ${path} with the workspace?`, + confirmationText: 'Share', + children: `Every member will be able to create and edit ${displayName} triggers that act as ${account}${browse}. They will not see its token. It replaces any connection shared before.` }) - - if (auth_url) { - window.location.href = auth_url - } - } catch (err: any) { - sendUserToast( - `Failed to connect ${supportedServices[serviceName]?.displayName}: ${err.message}`, - true - ) - connecting = null + if (!confirmed) return false + } else { + const confirmed = await confirmationModal.ask({ + title: 'Stop sharing this account?', + confirmationText: 'Stop sharing', + children: `Members will no longer be able to create or edit ${displayName} triggers through it, unless they can read it. Its triggers keep running.` + }) + if (!confirmed) return false } + + try { + await WorkspaceIntegrationService.setNativeTriggerWorkspaceConnection({ + workspace: $workspaceStore, + serviceName: serviceName as NativeServiceName, + requestBody: { path: path ?? null } + }) + sendUserToast(path ? `${path} is now the shared account` : 'Stopped sharing') + await loadConnections(serviceName) + return true + } catch (err: any) { + sendUserToast(`Failed to update the shared account: ${err.body ?? err.message}`, true) + return false + } + } + + function docsItem(config: ServiceConfig): Item[] { + return config.docsUrl + ? [{ displayName: 'Docs', icon: ExternalLink, href: config.docsUrl, hrefTarget: '_blank' }] + : [] + } + + async function openConfig(serviceName: string, leavingInstanceApp: boolean) { + const displayName = supportedServices[serviceName]?.displayName ?? serviceName + // A refresh token only works with the OAuth app that issued it. + if (leavingInstanceApp && (connections[serviceName]?.length ?? 0) > 0) { + const confirmed = await confirmationModal.ask({ + title: `Use your own ${displayName} OAuth app?`, + confirmationText: 'Continue', + children: `Accounts connected with the instance app will have to be connected again, at the same path, before their triggers work again.` + }) + if (!confirmed) return + } + configOpen[serviceName] = true } async function createOrUpdateIntegration(serviceName: string, oauthData: any) { if (!$workspaceStore) return + const displayName = supportedServices[serviceName]?.displayName ?? serviceName + const current = getIntegrationByService(serviceName)?.oauth_data + // Leaving the instance app is confirmed when the form opens; this covers editing our own app. + const clientChanges = + !!current?.client_id && + !current.instance_shared && + current.client_id !== (oauthData.client_id ?? '') + // A refresh token only works with the OAuth app that issued it. + if (clientChanges && (connections[serviceName]?.length ?? 0) > 0) { + const confirmed = await confirmationModal.ask({ + title: `Change the ${displayName} OAuth app?`, + confirmationText: 'Change', + children: `Accounts connected with the current app must be connected again, at the same path, before their triggers work again.` + }) + if (!confirmed) return + } + try { await WorkspaceIntegrationService.createNativeTriggerService({ workspace: $workspaceStore, - serviceName: serviceName as any, + serviceName: serviceName as NativeServiceName, requestBody: oauthData }) sendUserToast( @@ -207,33 +278,9 @@ } } - async function connectWithInstanceCredentials(serviceName: string) { - if (!$workspaceStore) return - - connecting = serviceName - try { - const redirectUri = getRedirectUri(serviceName) - const auth_url = await WorkspaceIntegrationService.generateInstanceConnectUrl({ - workspace: $workspaceStore, - serviceName: serviceName as NativeServiceName, - requestBody: { redirect_uri: redirectUri } - }) - - if (auth_url) { - window.location.href = auth_url - } - } catch (err: any) { - sendUserToast( - `Failed to connect ${supportedServices[serviceName]?.displayName}: ${err.message}`, - true - ) - connecting = null - } - } - - function isConfigured(integration: WorkspaceIntegration): boolean { - if (integration.oauth_data === null) return false - if (integration.oauth_data.instance_shared) return true + /** Whether the workspace has its own OAuth app for the service. */ + function hasWorkspaceApp(integration: WorkspaceIntegration | null): boolean { + if (!integration?.oauth_data || integration.oauth_data.instance_shared) return false const serviceConfig = supportedServices[integration.service_name] const needsBaseUrl = serviceConfig?.requiresBaseUrl !== false return ( @@ -243,82 +290,10 @@ ) } - function isConnected(integration: WorkspaceIntegration): boolean { - if (integration.oauth_data?.instance_shared) { - return !!integration.resource_path - } - return isConfigured(integration) && !!integration.resource_path - } - function getIntegrationByService(serviceName: string): WorkspaceIntegration | null { return integrations.find((integration) => integration.service_name === serviceName) || null } - function handleOAuthCallback( - workspace: string, - serviceName: NativeServiceName, - code: string, - state: string - ) { - // Phase 1: store callback params and clean URL — don't call backend yet - pendingCallback = { serviceName, code, state, workspace } - - // Pre-populate resource path from existing integration (for reconnect) - const integration = getIntegrationByService(serviceName) - resourcePath = integration?.resource_path ?? undefined - - const url = new URL(page.url) - url.searchParams.delete('code') - url.searchParams.delete('state') - url.searchParams.delete('service') - goto(url.toString(), { replaceState: true, noScroll: true, keepFocus: true }) - } - - async function finalizePendingCallback() { - if (!pendingCallback) return - - const { serviceName, code, state, workspace } = pendingCallback - try { - const redirectUri = getRedirectUri(serviceName) - await WorkspaceIntegrationService.nativeTriggerServiceCallback({ - serviceName, - workspace, - requestBody: { - code, - state, - redirect_uri: redirectUri, - resource_path: resourcePath - } - }) - sendUserToast(`${supportedServices[serviceName]?.displayName} connected successfully!`) - await loadIntegrations() - } catch (err: any) { - sendUserToast(`Failed to complete OAuth connection: ${err.message}`, true) - } finally { - pendingCallback = null - resourcePath = undefined - pathError = undefined - } - } - - $effect(() => { - if ( - page.url.searchParams.has('code') && - page.url.searchParams.has('state') && - page.url.searchParams.has('service') && - $workspaceStore - ) { - const service = page.url.searchParams.get('service')! as NativeServiceName - const code = page.url.searchParams.get('code')! - const state = page.url.searchParams.get('state')! - handleOAuthCallback($workspaceStore, service, code, state) - } - }) - - function getRedirectUri(serviceName: string): string { - return `${window.location.origin}/workspace_settings?tab=native_triggers&service=${serviceName}` - } - $effect(() => { if ($workspaceStore) { loadIntegrations() @@ -329,49 +304,12 @@ <div class="flex flex-col"> <SettingsPageHeader - title="Native Triggers" - description="Connect your workspace to external services for native triggers and enhanced functionality. These connections are shared across all workspace members and are required for native triggers to work." + title="Native triggers" + description="Configure the OAuth app of each service. Members connect their own account when creating a trigger, or use the shared account, and each trigger acts as the account it was created with." link="https://www.windmill.dev/docs/core_concepts/native_triggers" /> - {#if pendingCallback} - {@const serviceName = pendingCallback.serviceName} - {@const config = supportedServices[serviceName]} - <div class="border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-surface-tertiary"> - <div class="text-sm font-semibold text-emphasis mb-2"> - Save {config?.displayName ?? serviceName} credentials as resource - </div> - <div class="text-xs text-secondary mb-3"> - Choose where to save the OAuth resource. This resource will store the access token for the - integration. - </div> - <Path - kind="resource" - initialPath={resourcePath ?? ''} - namePlaceholder={'native_' + serviceName} - bind:path={resourcePath} - bind:error={pathError} - /> - <div class="flex gap-2 mt-3"> - <Button - variant="accent" - disabled={!resourcePath || !!pathError} - onclick={finalizePendingCallback} - > - Save - </Button> - <Button - onclick={() => { - pendingCallback = null - resourcePath = undefined - pathError = undefined - }} - > - Cancel - </Button> - </div> - </div> - {:else if loading} + {#if loading} <div class="space-y-4"> {#each new Array(3) as _} <Skeleton layout={[[6], 0.4]} /> @@ -381,164 +319,144 @@ <div class="space-y-4"> {#each Object.entries(supportedServices) as [serviceName, config]} {@const integration = getIntegrationByService(serviceName)} - {@const isConnecting = connecting === serviceName} - {@const isOAuthConfigured = integration && isConfigured(integration)} - {@const isServiceConnected = integration && isConnected(integration)} - {@const isShowingConfig = showingConfig === serviceName} + {@const workspaceApp = hasWorkspaceApp(integration)} + {@const usesInstanceApp = !workspaceApp && instanceSharingAvailable[serviceName]} + {@const workspaceConnection = connections[serviceName]?.find((c) => c.workspace)?.path} - <div class="border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-surface-tertiary"> - <div class="flex items-center justify-between"> - <div class="flex items-center gap-3"> - <div class="w-8 h-8 flex items-center justify-center"> - <config.icon class="w-6 h-6" /> - </div> - <div class="flex flex-col"> - <div class="text-sm font-semibold text-emphasis">{config.displayName}</div> - <div class="text-xs font-normal text-primary">{config.description}</div> - </div> - </div> - - <div class="flex items-center gap-2"> - {#if isServiceConnected} - <div class="flex items-center gap-1 text-green-600 text-xs"> - <Check size={16} /> - <span class="font-semibold">Connected</span> - </div> - <Button - onclick={() => - integration?.oauth_data?.instance_shared - ? connectWithInstanceCredentials(serviceName) - : connectService(serviceName, getRedirectUri(serviceName))} - disabled={isConnecting} - startIcon={{ icon: Plug }} - > - {isConnecting ? 'Reconnecting...' : 'Reconnect'} - </Button> - <Button - destructive - onclick={() => deleteIntegration(serviceName)} - startIcon={{ icon: X }} - > - Delete - </Button> - {:else if isOAuthConfigured} - <Button - variant="accent" - onclick={() => connectService(serviceName, getRedirectUri(serviceName))} - disabled={isConnecting} - startIcon={{ icon: Plug }} - > - {isConnecting ? 'Connecting...' : 'Connect'} - </Button> - <Button - destructive - onclick={() => deleteIntegration(serviceName)} - startIcon={{ icon: X }} - > - Delete - </Button> - {:else if instanceSharingAvailable[serviceName]} - <Button - variant="accent" - onclick={() => connectWithInstanceCredentials(serviceName)} - disabled={isConnecting} - startIcon={{ icon: Plug }} - > - {isConnecting ? 'Connecting...' : 'Connect'} - </Button> - {:else} - <Button - variant="accent" - onclick={() => - (showingConfig = showingConfig === serviceName ? null : serviceName)} - startIcon={{ icon: Cog }} - > - Configure OAuth - </Button> - {/if} - - {#if config.docsUrl} - <Button href={config.docsUrl} target="_blank" startIcon={{ icon: ExternalLink }}> - Docs - </Button> - {/if} + <div class="border border-light rounded-md p-4 bg-surface-tertiary flex flex-col gap-3"> + <div class="flex items-center gap-3"> + <config.icon class="w-6 h-6 shrink-0" /> + <div class="flex flex-col flex-1 min-w-0"> + <div class="text-sm font-semibold text-emphasis">{config.displayName}</div> + <div class="text-xs text-secondary">{config.description}</div> </div> + {#if workspaceApp || usesInstanceApp} + <DropdownV2 + items={workspaceApp + ? [ + { + displayName: 'Edit OAuth app', + icon: Pencil, + action: () => openConfig(serviceName, false) + }, + ...docsItem(config), + { + displayName: 'Remove configuration', + icon: Trash2, + type: 'delete', + action: () => deleteIntegration(serviceName) + } + ] + : [ + { + displayName: 'Use a workspace OAuth app', + icon: KeyRound, + action: () => openConfig(serviceName, true) + }, + ...docsItem(config) + ]} + /> + {:else} + <Button + unifiedSize="sm" + variant="default" + onclick={() => openConfig(serviceName, false)} + > + Set up + </Button> + {/if} </div> - {#if instanceSharingAvailable[serviceName] && !isOAuthConfigured} - <div class="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700"> - <Alert type="info" title="Redirect URI required"> - <p class="text-sm mb-2"> - Your instance admin has configured Google OAuth for native triggers. Before - connecting, ensure the following redirect URI has been added to the - <a - href="https://console.cloud.google.com/apis/credentials" - target="_blank" - rel="noopener noreferrer" - class="underline">Google Cloud Console</a - > by the instance admin: - </p> - <ClipboardPanel content={getRedirectUri(serviceName)} size="sm" /> + {#if !workspaceApp && !usesInstanceApp} + <div class="text-xs text-primary"> + Not configured. Members can't create {config.displayName} triggers yet. + </div> + {:else} + <div class="flex items-start gap-1.5 text-xs text-primary"> + <Check size={14} class="shrink-0 mt-0.5" /> + <span> + {workspaceApp ? 'Configured in workspace.' : 'Configured by instance.'} + Members connect their own {config.displayName} account when they create a trigger. + </span> + </div> + + {#if serviceName === 'nextcloud' && !workspaceConnection} + <Alert + type="info" + title="Creating Nextcloud triggers requires a Nextcloud admin account" + > + We recommend connecting one below and sharing it with the workspace. </Alert> + {/if} + + <div class="flex flex-col gap-1"> + <div class="text-xs font-semibold text-emphasis">Shared account</div> + <div class="text-xs text-secondary"> + Members can create triggers as this account and pick from what it can access, + without seeing its token. + </div> + <div class="max-w-md"> + <!-- Remounted so its list includes an account connected from elsewhere on the page. --> + {#key workspaceConnection} + <NativeConnectionPicker + service={serviceName as NativeServiceName} + value={workspaceConnection} + autoSelect={false} + clearable + labelWorkspace={false} + placeholder="None" + onSelect={(path) => setWorkspaceConnection(serviceName, path)} + onConnectionsChange={() => loadConnections(serviceName)} + /> + {/key} + </div> </div> {/if} - {#if isShowingConfig} - <div class="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700"> + <OAuthClientConfig + bind:open={configOpen[serviceName]} + {serviceName} + redirectUri={nativeOAuthRedirectUri(serviceName as NativeServiceName)} + serviceDisplayName={config.displayName} + existingConfig={workspaceApp ? integration?.oauth_data : null} + requiresBaseUrl={config.requiresBaseUrl !== false} + clientIdPlaceholder={config.clientIdPlaceholder} + clientSecretPlaceholder={config.clientSecretPlaceholder} + setupInstructions={config.setupInstructions} + onConfigSaved={async (oauthData) => { + await createOrUpdateIntegration(serviceName, oauthData) + configOpen[serviceName] = false + }} + > + {#snippet requirements()} {#if serviceName === 'nextcloud'} - <Alert type="info" title="Requirements" class="mb-4"> - <p>Nextcloud integration requires:</p> - <ul class="list-disc pl-4 mt-2 space-y-1"> + <Alert type="info" title="Nextcloud requirements"> + <ul class="list-disc pl-4 flex flex-col gap-1"> <li>Nextcloud 33 or later.</li> <li> The <a href="https://apps.nextcloud.com/apps/integration_windmill" target="_blank" rel="noopener noreferrer" - class="underline hover:text-blue-600" - > - Windmill integration app - </a> to be installed on your Nextcloud instance. + class="underline">Windmill integration app</a + > installed. </li> <li> <a href="https://docs.nextcloud.com/server/latest/admin_manual/installation/source_installation.html#pretty-urls" target="_blank" rel="noopener noreferrer" - class="underline hover:text-blue-600" - > - Pretty URLs - </a> - to be enabled on your Nextcloud instance. + class="underline">Pretty URLs</a + > enabled. </li> </ul> </Alert> {/if} - <OAuthClientConfig - {serviceName} - redirectUri={getRedirectUri(serviceName)} - serviceDisplayName={config.displayName} - existingConfig={integration?.oauth_data} - requiresBaseUrl={config.requiresBaseUrl !== false} - clientIdPlaceholder={config.clientIdPlaceholder} - clientSecretPlaceholder={config.clientSecretPlaceholder} - setupInstructions={config.setupInstructions} - onConfigSaved={async (oauthData) => { - await createOrUpdateIntegration(serviceName, oauthData) - showingConfig = null - }} - /> - </div> - {/if} + {/snippet} + </OAuthClientConfig> </div> {/each} </div> - - {#if integrations.length === 0} - <Alert type="warning" title="No Integrations Connected"> - Connect to external services above to enable native triggers for your workspace. - </Alert> - {/if} {/if} </div> diff --git a/frontend/src/lib/components/workspaceSettings/projectBundle.ts b/frontend/src/lib/components/workspaceSettings/projectBundle.ts index 8adedeb559..047f7ee7fa 100644 --- a/frontend/src/lib/components/workspaceSettings/projectBundle.ts +++ b/frontend/src/lib/components/workspaceSettings/projectBundle.ts @@ -148,6 +148,8 @@ function runnableRef(node: Record<string, any>): Ref | undefined { if (!isRunnableByPath(node as any) || typeof node.path !== 'string') return undefined if (node.runType === 'flow') return { kind: 'flow', path: node.path } if (node.runType === 'script') return { kind: 'script', path: node.path } + // A saved agent is an `ai_agent` resource. + if (node.runType === 'agent') return { kind: 'resource', path: node.path } return undefined // hubscript -> external hub, ignored } diff --git a/frontend/src/lib/consts.ts b/frontend/src/lib/consts.ts index a6bbc25d49..62108cf23b 100644 --- a/frontend/src/lib/consts.ts +++ b/frontend/src/lib/consts.ts @@ -10,6 +10,9 @@ export const DEFAULT_WEBHOOK_TYPE: 'async' | 'sync' = 'async' export const HOME_SHOW_HUB = true +/** The width of Home's one column: the composer and the items list below it. */ +export const HOME_COLUMN_WIDTH = 'max-w-[1120px]' + export const HOME_SHOW_CREATE_FLOW = true export const HOME_SEARCH_SHOW_FLOW = true diff --git a/frontend/src/lib/editRights.test.ts b/frontend/src/lib/editRights.test.ts index a6d36f693c..ef344d7d6d 100644 --- a/frontend/src/lib/editRights.test.ts +++ b/frontend/src/lib/editRights.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest' +import type { RoleCapabilities } from '$lib/gen' import type { UserExt } from '$lib/stores' +import { FULL_CAPABILITIES, legacyOperatorCapabilities } from '$lib/roleCapabilities' import { canEditItem, roleCanAuthor, roleCanDraft } from './editRights' function user(overrides: Partial<UserExt>): UserExt { @@ -20,40 +22,52 @@ function user(overrides: Partial<UserExt>): UserExt { } as UserExt } +const role = (overrides: Partial<RoleCapabilities>): RoleCapabilities => ({ + ...legacyOperatorCapabilities(undefined), + ...overrides +}) + describe('edit rights', () => { - it('lets a builder operator author flows and nothing else', () => { - const builder = { builder_flows: true } - expect(roleCanAuthor('flow', user({}), builder)).toBe(true) - expect(roleCanAuthor('script', user({}), builder)).toBe(false) - expect(roleCanAuthor('flow', user({}), undefined)).toBe(false) - expect(roleCanDraft('raw_app', user({}), builder)).toBe(false) - expect(roleCanDraft('raw_app', user({}), { builder_apps: true })).toBe(true) + it('lets a compose-only flow role author flows and agents and nothing else', () => { + const builder = role({ flows: 'compose' }) + expect(roleCanAuthor('flow', builder)).toBe(true) + expect(roleCanAuthor('agent', builder)).toBe(true) + expect(roleCanDraft('agent', builder)).toBe(true) + expect(roleCanAuthor('agent', role({ apps: 'compose' }))).toBe(false) + expect(roleCanAuthor('script', builder)).toBe(false) + expect(roleCanAuthor('raw_app', builder)).toBe(false) + expect(roleCanDraft('raw_app', builder)).toBe(false) + expect(roleCanDraft('raw_app', role({ apps: 'compose' }))).toBe(true) }) - // drafts.rs admits an admin before its operator branch; the item handlers do not. - it('lets an admin who is also an operator save drafts, but not author code', () => { - const adminOperator = user({ is_admin: true }) - expect(roleCanDraft('script', adminOperator, undefined)).toBe(true) - expect(roleCanAuthor('script', adminOperator, undefined)).toBe(false) + // apps.rs `require_full_apps`: a composing role builds full-code apps, never low-code ones. + it('keeps low-code apps for full app authors', () => { + expect(roleCanAuthor('app', role({ apps: 'compose' }))).toBe(false) + expect(roleCanAuthor('raw_app', role({ apps: 'compose' }))).toBe(true) + const scripter = { ...FULL_CAPABILITIES, apps: 'none' as const } + expect(roleCanAuthor('script', scripter)).toBe(true) + expect(roleCanAuthor('app', scripter)).toBe(false) + expect(roleCanAuthor('raw_app', scripter)).toBe(false) }) - // drafts.rs admits an operator's draft of a kind they could deploy, and no other. - it('lets an operator draft schedules and triggers until the right is withdrawn', () => { - expect(roleCanDraft('schedule', user({}), undefined)).toBe(true) - expect(roleCanDraft('trigger', user({}), undefined)).toBe(true) - expect(roleCanDraft('schedule', user({}), { manage_schedules: false })).toBe(false) - expect(roleCanDraft('trigger', user({}), { manage_triggers: false })).toBe(false) + // drafts.rs admits a restricted role's draft of a kind it could deploy, and no other. + it('lets a role draft schedules and triggers until the right is withdrawn', () => { + expect(roleCanDraft('schedule', role({}))).toBe(true) + expect(roleCanDraft('trigger', role({}))).toBe(true) + expect(roleCanDraft('schedule', role({ manage_schedules: false }))).toBe(false) + expect(roleCanDraft('trigger', role({ manage_triggers: false }))).toBe(false) }) - it('lets an operator draft resources and variables, but not scripts', () => { - expect(roleCanDraft('resource', user({}), undefined)).toBe(true) - expect(roleCanDraft('variable', user({}), undefined)).toBe(true) - expect(roleCanDraft('script', user({}), undefined)).toBe(false) + it('lets any role draft resources and variables, but scripts only with code', () => { + expect(roleCanDraft('resource', role({}))).toBe(true) + expect(roleCanDraft('variable', role({}))).toBe(true) + expect(roleCanDraft('script', role({}))).toBe(false) + expect(roleCanDraft('script', role({ code: true }))).toBe(true) }) // The role alone is not enough: a builder still cannot edit a flow in a folder they only read. it('requires write access to the item on top of the role', () => { - const builder = { builder_flows: true } + const builder = role({ flows: 'compose' }) expect(canEditItem('flow', 'f/demo/sum', {}, user({}), builder)).toBe(false) expect(canEditItem('flow', 'u/op/sum', {}, user({}), builder)).toBe(true) }) diff --git a/frontend/src/lib/editRights.ts b/frontend/src/lib/editRights.ts index 888b61e818..24022cc680 100644 --- a/frontend/src/lib/editRights.ts +++ b/frontend/src/lib/editRights.ts @@ -1,16 +1,17 @@ -import type { OperatorSettings } from '$lib/gen' +import type { RoleCapabilities } from '$lib/gen' import type { UserExt } from '$lib/stores' import { canWrite } from '$lib/utils' +import { isRestricted } from '$lib/roleCapabilities' /** * The frontend's one copy of "may this user edit this item". The server decides — drafts.rs - * `require_can_write_path`, the item handlers' operator refusals, `gate_operator_writes`, and + * `require_can_write_path`, the item handlers' role refusals, `gate_operator_writes`, and * row-level security — and this mirrors it so a control the server would refuse is never * offered. Check edits through `canEditItem` (or `useEditRights` in a component), never by - * pairing `canWrite` with an operator test of your own. + * pairing `canWrite` with a role test of your own. */ -/** Kinds whose role half differs. Any other kind is code an operator never authors. */ +/** Kinds whose role half differs. Any other kind is code, authored under `code`. */ export type EditKind = | 'script' | 'flow' @@ -25,81 +26,54 @@ export type EditKind = | 'group' | (string & {}) -type OperatorRights = - | Pick< - NonNullable<OperatorSettings>, - 'builder_flows' | 'builder_apps' | 'manage_schedules' | 'manage_triggers' - > - | null - | undefined - /** - * Whether a user's role lets them author items of `kind` — create, edit, deploy or delete one — - * in a workspace with these `operator_settings`: the role half of every check against the item - * handlers. Saving a draft is `roleCanDraft`'s rule, and which items they may write is - * `canEditItem`'s other half. For an operator: - * - code (scripts, low-code apps, agents, pipelines): never; - * - flows and full-code apps: where the workspace grants `builder_flows` / `builder_apps` - * (`check_operator_can_build`); - * - schedules and triggers: unless the workspace set `manage_*` to false — a withdrawable - * right, so an unset key grants it (docs/operator-write-rights.md); + * Whether a role with `caps` lets its member author items of `kind` (create, edit, deploy or + * delete one): the role half of every check against the item handlers. Saving a draft is + * `roleCanDraft`'s rule, and which items they may write is `canEditItem`'s other half. + * - code (scripts, pipelines): `code`; + * - flows, agents and full-code apps: `compose` or above (`check_operator_can_build`). An + * agent's tools are checked as a composed flow's steps are, under the flows right; + * - low-code apps: `full` apps only (apps.rs `require_full_apps`); + * - schedules and triggers: the matching manage right; * - resources, variables and groups: always, their permissions alone decide. */ -export function roleCanAuthor( - kind: EditKind, - user: Pick<UserExt, 'operator'> | undefined, - operatorSettings: OperatorRights -): boolean { - if (!user?.operator) return true +export function roleCanAuthor(kind: EditKind, caps: RoleCapabilities): boolean { switch (kind) { case 'flow': + case 'agent': + return caps.flows !== 'none' case 'raw_app': - return builderGrants(kind, operatorSettings) + return caps.apps !== 'none' + case 'app': + return caps.apps === 'full' case 'schedule': - return operatorSettings?.manage_schedules !== false + return caps.manage_schedules case 'trigger': - return operatorSettings?.manage_triggers !== false + return caps.manage_triggers case 'resource': case 'variable': case 'group': return true default: - return false + return caps.code } } /** - * Whether the user may save drafts of `kind` — what every session editor and the chat's draft - * tools write. Mirrors drafts.rs `require_can_write_path`, which differs from the item handlers - * both ways: it admits an admin before its operator branch, and an operator drafts only the kinds - * they could deploy — resources and variables always, flows and full-code apps under their builder - * right, schedules and triggers under the manage rights. + * Whether the role may save drafts of `kind`, which every session editor and the chat's draft + * tools write. Mirrors drafts.rs `operator_can_draft`: a restricted role drafts only the kinds it + * could deploy, and resources and variables always. An unrestricted role drafts every kind. */ -export function roleCanDraft( - kind: EditKind, - user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'> | undefined, - operatorSettings: OperatorRights -): boolean { - if (user?.is_admin || user?.is_super_admin || !user?.operator) return true - switch (kind) { - case 'flow': - case 'raw_app': - return builderGrants(kind, operatorSettings) - case 'schedule': - case 'trigger': - return roleCanAuthor(kind, user, operatorSettings) - case 'resource': - case 'variable': - return true - default: - return false - } +export function roleCanDraft(kind: EditKind, caps: RoleCapabilities): boolean { + if (!isRestricted(caps)) return true + return kind === 'group' ? false : roleCanAuthor(kind, caps) } -function builderGrants(kind: EditKind, operatorSettings: OperatorRights): boolean { - return ( - (kind === 'flow' && operatorSettings?.builder_flows === true) || - (kind === 'raw_app' && operatorSettings?.builder_apps === true) +/** Whether the role builds anything: code, flows, apps, schedules or triggers. Resources and + * variables do not count, since every role edits them. */ +export function buildsAnything(caps: RoleCapabilities): boolean { + return (['script', 'flow', 'raw_app', 'schedule', 'trigger'] as const).some((kind) => + roleCanDraft(kind, caps) ) } @@ -109,9 +83,9 @@ export function canDraftItem( path: string, extraPerms: Record<string, boolean> | undefined, user: UserExt | undefined, - operatorSettings: OperatorRights + caps: RoleCapabilities ): boolean { - return roleCanDraft(kind, user, operatorSettings) && canWrite(path, extraPerms ?? {}, user) + return roleCanDraft(kind, caps) && canWrite(path, extraPerms ?? {}, user) } /** Whether `user` may edit the item at `path`: their role authors `kind`, and the item's own @@ -121,7 +95,7 @@ export function canEditItem( path: string, extraPerms: Record<string, boolean> | undefined, user: UserExt | undefined, - operatorSettings: OperatorRights + caps: RoleCapabilities ): boolean { - return roleCanAuthor(kind, user, operatorSettings) && canWrite(path, extraPerms ?? {}, user) + return roleCanAuthor(kind, caps) && canWrite(path, extraPerms ?? {}, user) } diff --git a/frontend/src/lib/hub.ts b/frontend/src/lib/hub.ts index 9f81614258..41e0c41f66 100644 --- a/frontend/src/lib/hub.ts +++ b/frontend/src/lib/hub.ts @@ -86,6 +86,8 @@ type HubPaths = { teamsErrorHandler: string teamsRecoveryHandler: string teamsSuccessHandler: string + slackVariableExpirationHandler: string + teamsVariableExpirationHandler: string emailErrorHandler: string cloneRepoToS3forGitRepoViewer: string appReport: string diff --git a/frontend/src/lib/hubPaths.json b/frontend/src/lib/hubPaths.json index 74c2d6f9f4..41f7f50c33 100644 --- a/frontend/src/lib/hubPaths.json +++ b/frontend/src/lib/hubPaths.json @@ -8,6 +8,8 @@ "teamsErrorHandler": "hub/19742/workspace-or-schedule-error-handler-teams", "teamsRecoveryHandler": "hub/11593/schedule-recovery-handler-teams", "teamsSuccessHandler": "hub/11596/schedule-success-handler-teams", + "slackVariableExpirationHandler": "hub/30049/variable-expiration-handler-slack", + "teamsVariableExpirationHandler": "hub/30048/variable-expiration-handler-teams", "slackReport": "hub/28792/slack", "discordReport": "hub/9085/discord", "smtpReport": "hub/28242/smtp", diff --git a/frontend/src/lib/infer.ts b/frontend/src/lib/infer.ts index 9e9cddeb00..3c1d30bc87 100644 --- a/frontend/src/lib/infer.ts +++ b/frontend/src/lib/infer.ts @@ -1,11 +1,14 @@ import { ScriptService, + ResourceService, type MainArgSignature, FlowService, type Script, type AssetUsageAccessType } from '$lib/gen' import { get, writable } from 'svelte/store' +import type { PathRunType } from './components/apps/inputType.js' +import { agentRunnableSchema } from './components/raw_apps/agentRunnable.js' import type { Schema, SupportedLanguage } from './common.js' import { type DynamicInput, @@ -658,9 +661,15 @@ async function inferSchemaIfNecessary(script: Script) { export async function loadSchema( workspace: string, path: string, - runType: 'script' | 'flow' | 'hubscript' + runType: PathRunType ): Promise<{ schema: Schema; summary: string | undefined }> { - if (runType === 'script') { + if (runType === 'agent') { + const agent = await ResourceService.getResource({ workspace, path }) + return { + schema: agentRunnableSchema((agent.value as any)?.memory), + summary: agent.description || undefined + } + } else if (runType === 'script') { const script = await ScriptService.getScriptByPath({ workspace, path diff --git a/frontend/src/lib/mcpEndpointTools.ts b/frontend/src/lib/mcpEndpointTools.ts index e53beeb53b..a81110805c 100644 --- a/frontend/src/lib/mcpEndpointTools.ts +++ b/frontend/src/lib/mcpEndpointTools.ts @@ -193,7 +193,12 @@ export const mcpEndpointTools: EndpointTool[] = [ }, "expires_at": { "type": "string", - "description": "The expiration date of the variable", + "description": "When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry \u2014 see value_valid_until.\n", + "format": "date-time" + }, + "value_valid_until": { + "type": "string", + "description": "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it, by the handler's `notify_before_secs` (1 day by default); never causes the variable to be deleted.\n", "format": "date-time" }, "labels": { @@ -281,6 +286,12 @@ export const mcpEndpointTools: EndpointTool[] = [ "type": "string", "description": "The new description of the variable" }, + "value_valid_until": { + "type": "string", + "nullable": true, + "description": "When the value stored in this variable stops working. Omit to leave it unchanged; send null to clear it. Changing it re-arms the workspace's variable expiration handler.\n", + "format": "date-time" + }, "labels": { "type": "array", "items": { diff --git a/frontend/src/lib/operatorWriteRights.ts b/frontend/src/lib/operatorWriteRights.ts index 916e39dce6..5684a8ee56 100644 --- a/frontend/src/lib/operatorWriteRights.ts +++ b/frontend/src/lib/operatorWriteRights.ts @@ -1,29 +1,48 @@ -import { derived, fromStore, get, readable, type Readable } from 'svelte/store' -import { userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' -import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' +import { derived, fromStore, get, readable, toStore, type Readable } from 'svelte/store' +import type { RoleCapabilities } from '$lib/gen' +import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' +import { + useOperatingWorkspace, + useReadOnlyWorkspace +} from '$lib/components/operatingWorkspace.svelte' import { useActingUser } from '$lib/actingUser.svelte' import { canDraftItem, canEditItem, roleCanAuthor, roleCanDraft } from '$lib/editRights' +import { capabilitiesIn, withoutBuilding } from '$lib/roleCapabilities' /** * The `editRights` rules (`roleCanAuthor` / `canEditItem` for the item handlers, `roleCanDraft` / - * `canDraftItem` for drafts) answered for the user acting in the operating workspace, - * with that workspace's `operator_settings` — or in `workspace`, for a component that is handed - * one rather than sitting under a host that declares it. Reads context and registers an effect: - * call during component initialisation. + * `canDraftItem` for drafts) answered for the user acting in the operating workspace, with their + * role's capabilities there, or in `workspace`, for a component that is handed one rather than + * sitting under a host that declares it. Reads context and registers an effect: call during + * component initialisation. */ export function useEditRights(workspace?: () => string | undefined) { const operating = fromStore(useOperatingWorkspace()) const ws = workspace ?? (() => operating.current) const user = useActingUser(ws) + const readOnly = useReadOnlyWorkspace() const workspaces = fromStore(userWorkspaces) - const settings = () => workspaces.current.find((w) => w.id === ws())?.operator_settings + const open = () => !readOnly(ws()) + // A read-only workspace leaves the role building nothing, so a gate reading `capabilities` + // follows it as the four checks below do. Those keep their own guard: every role edits + // resources and variables. + const caps = () => { + const roleCaps = capabilitiesIn( + user.current, + workspaces.current.find((w) => w.id === ws()) + ) + return open() ? roleCaps : withoutBuilding(roleCaps) + } return { - roleCanAuthor: (kind: string) => roleCanAuthor(kind, user.current, settings()), + get capabilities(): RoleCapabilities { + return caps() + }, + roleCanAuthor: (kind: string) => open() && roleCanAuthor(kind, caps()), canEditItem: (kind: string, path: string, extraPerms: Record<string, boolean> | undefined) => - canEditItem(kind, path, extraPerms, user.current, settings()), - roleCanDraft: (kind: string) => roleCanDraft(kind, user.current, settings()), + open() && canEditItem(kind, path, extraPerms, user.current, caps()), + roleCanDraft: (kind: string) => open() && roleCanDraft(kind, caps()), canDraftItem: (kind: string, path: string, extraPerms: Record<string, boolean> | undefined) => - canDraftItem(kind, path, extraPerms, user.current, settings()), + open() && canDraftItem(kind, path, extraPerms, user.current, caps()), /** This hook looks the user up on its own, so an editor that retries a failed lookup on * its acting user (`forgetFailures`) must retry this one too, or it stays read-only. */ forgetFailures: () => user.forgetFailures() @@ -31,19 +50,48 @@ export function useEditRights(workspace?: () => string | undefined) { } /** - * Why writes of this kind are locked in the operating workspace, or `undefined` when they are not — + * The role's capabilities in `workspace`, from the workspace list alone: `$userStore` describes + * only the navigation workspace, so elsewhere only superadmin carries over. Admins get full + * capabilities from the server's list. + */ +function capabilitiesStore(workspace: Readable<string | undefined>): Readable<RoleCapabilities> { + return derived( + [userStore, workspaceStore, userWorkspaces, workspace], + ([$user, $nav, $workspaces, $ws]) => + capabilitiesIn( + $ws === $nav && $user?.workspace_id === $ws + ? $user + : { is_super_admin: $user?.is_super_admin }, + $workspaces.find((w) => w.id === $ws) + ) + ) +} + +/** The role's capabilities in the operating workspace. Reads context: call during component + * initialisation. Code outside any component reads `roleCapabilities` (navigation workspace) or + * `capabilitiesInWorkspace`. */ +export const useRoleCapabilities = () => capabilitiesStore(useOperatingWorkspace()) + +/** The role's capabilities in a given workspace, read once: for code acting on an explicit + * workspace rather than the nav's, such as the global AI chat. */ +export const capabilitiesInWorkspace = (workspace: string | undefined) => + get(capabilitiesStore(readable(workspace))) + +/** + * Why writes of this kind are locked in the operating workspace, or `undefined` when they are not: * the shape `title` and `disabled` both want. See `docs/operator-write-rights.md`. - * - * The role half of `roleCanAuthor`, phrased for the controls that explain it. `operator_settings` - * is non-null exactly for an operator (`isOperatorInWorkspace`), so it stands in for the user. */ function writeLock(kind: 'schedule' | 'trigger', noun: string) { - return derived([userWorkspaces, useOperatingWorkspace()], ([$userWorkspaces, $workspace]) => { - const settings = $userWorkspaces.find((w) => w.id === $workspace)?.operator_settings + const workspace = fromStore(useOperatingWorkspace()) + const readOnly = useReadOnlyWorkspace() + // A store, so a session switched to Use mid-page locks the toggles already shown. + const sessionReadOnly = toStore(() => readOnly(workspace.current)) + return derived([useRoleCapabilities(), sessionReadOnly], ([caps, inUse]) => { + if (inUse) return `A session in Use mode cannot manage ${noun}` // Worded as the server words its refusal of the same write. - return roleCanAuthor(kind, { operator: settings != null }, settings) + return roleCanAuthor(kind, caps) ? undefined - : `Operators cannot manage ${noun} in this workspace` + : `Your role cannot manage ${noun} in this workspace` }) } @@ -52,55 +100,9 @@ export const useScheduleLock = () => writeLock('schedule', 'schedules') /** Reads context: call during component initialisation. */ export const useTriggerLock = () => writeLock('trigger', 'triggers') -/** - * True when the user is an operator of `workspace` and it granted operators the right to compose - * this kind out of runnables that are already deployed. They still author no code, and everywhere - * else `operator` keeps meaning read-only, so a gate on the operator role has to consult this before - * refusing. `operator_settings` is null for a non-operator, so this is false for them. - * - * The two rights are granted independently: anything that authors one kind must gate on that - * kind, or a flows-only workspace offers app affordances the backend then refuses. - */ -function builderRight( - key: 'builder_flows' | 'builder_apps', - workspace: Readable<string | undefined> -): Readable<boolean> { - return derived( - [userWorkspaces, workspace], - ([$userWorkspaces, $workspace]) => - $userWorkspaces.find((w) => w.id === $workspace)?.operator_settings?.[key] === true - ) -} - -/** Either right, only for surfaces that are not per-kind, such as the create menu's visibility. */ -function anyBuilderRight(workspace: Readable<string | undefined>): Readable<boolean> { - return derived( - [builderRight('builder_flows', workspace), builderRight('builder_apps', workspace)], - ([flows, apps]) => flows || apps - ) -} - -/** Builder rights in the operating workspace. Reads context: call during component - * initialisation. */ -export const useOperatorBuilderFlows = () => builderRight('builder_flows', useOperatingWorkspace()) -/** Reads context: call during component initialisation. */ -export const useOperatorBuilderApps = () => builderRight('builder_apps', useOperatingWorkspace()) -/** Reads context: call during component initialisation. */ -export const useOperatorBuilderRights = () => anyBuilderRight(useOperatingWorkspace()) - -/** Builder rights in the navigation workspace, for code outside any component: the legacy AI - * chat is one instance for the whole app and acts on the workspace the nav is on. */ -export const navigationOperatorBuilderFlows = builderRight('builder_flows', workspaceStore) -export const navigationOperatorBuilderApps = builderRight('builder_apps', workspaceStore) -export const navigationOperatorBuilderRights = anyBuilderRight(workspaceStore) - -/** The app builder right in a given workspace, read once: for code acting on an explicit - * workspace rather than the nav's, such as the global AI chat. */ -export const operatorBuilderAppsIn = (workspace: string | undefined) => - get(builderRight('builder_apps', readable(workspace))) - -/** Resolves once the workspace list has loaded. Every builder right reads false until then, so - * code that picks what a builder starts with on a fresh page load has to wait for it. */ +/** Resolves once the workspace list has loaded. Capabilities fall back to the user's legacy + * operator flag until then, so code that picks what a builder starts with on a fresh page load + * has to wait for it. */ export async function workspaceListLoaded(): Promise<void> { let unsubscribe = () => {} await new Promise<void>((resolve) => { diff --git a/frontend/src/lib/roleCapabilities.test.ts b/frontend/src/lib/roleCapabilities.test.ts new file mode 100644 index 0000000000..1962414042 --- /dev/null +++ b/frontend/src/lib/roleCapabilities.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import type { RoleCapabilities } from '$lib/gen' +import { capabilitiesIn, FULL_CAPABILITIES, hidesPages, isRestricted } from './roleCapabilities' + +const scripter: RoleCapabilities = { + ...FULL_CAPABILITIES, + apps: 'none', + visibility: { ...FULL_CAPABILITIES.visibility, workers: false } +} + +describe('capabilitiesIn', () => { + it("takes the server's capabilities, whatever the legacy operator flag says", () => { + const caps = capabilitiesIn({ operator: false }, { capabilities: scripter }) + expect(caps).toEqual(scripter) + expect(isRestricted(caps)).toBe(true) + }) + + it('gives an admin everything', () => { + expect(capabilitiesIn({ is_admin: true }, { capabilities: scripter })).toBe(FULL_CAPABILITIES) + }) + + // A server that predates roles sends `operator` and `operator_settings` only. + it('derives an operator from operator_settings on an older server', () => { + const caps = capabilitiesIn( + { operator: true }, + { operator_settings: { runs: true, builder_flows: true, manage_triggers: false } as any } + ) + expect(caps.code).toBe(false) + expect(caps.flows).toBe('compose') + expect(caps.apps).toBe('none') + expect(caps.manage_schedules).toBe(true) + expect(caps.manage_triggers).toBe(false) + expect(caps.visibility.runs).toBe(true) + // `=== true`: a flag the settings never mention, or settings never written, hide the page. + expect(caps.visibility.workers).toBe(false) + expect(capabilitiesIn({ operator: true }, undefined).visibility.runs).toBe(false) + expect(capabilitiesIn({ operator: false }, undefined)).toBe(FULL_CAPABILITIES) + }) + + // `RoleCapabilities::is_restricted` leaves visibility out, so a full author keeps forking. + it('does not restrict a full role that only hides pages', () => { + const hidden = { ...FULL_CAPABILITIES, visibility: { ...FULL_CAPABILITIES.visibility, workers: false } } + expect(isRestricted(hidden)).toBe(false) + expect(hidesPages(hidden)).toBe(true) + }) +}) diff --git a/frontend/src/lib/roleCapabilities.ts b/frontend/src/lib/roleCapabilities.ts new file mode 100644 index 0000000000..1a9fc70a61 --- /dev/null +++ b/frontend/src/lib/roleCapabilities.ts @@ -0,0 +1,87 @@ +import type { OperatorSettings, RoleCapabilities, RoleVisibility } from '$lib/gen' +import type { UserExt, UserWorkspace } from '$lib/stores' +import { FULL_CAPABILITIES, VISIBILITY_KEYS } from '$lib/workspaceRoles' + +/** + * What a member's workspace role lets them author, manage and see: the frontend's copy of + * `windmill_common::roles`, see `docs/workspace-roles.md`. Gate on these, never on + * `UserExt.operator`, which only says "this role cannot write code" and so lets through a role + * that may code but not, say, build apps. + */ + +export type VisibilityKey = keyof RoleVisibility + +export { FULL_CAPABILITIES } + +const VISIBILITY = VISIBILITY_KEYS.map((v) => v.key) + +/** + * The operator role as a server that predates roles describes it, through `operator_settings`: + * builder rights are `compose`, the manage rights are granted unless withdrawn, and a page is + * visible only when its flag is `true` (absent settings hide every page, as they always did). + */ +export function legacyOperatorCapabilities( + settings: OperatorSettings | null | undefined +): RoleCapabilities { + const visibility = Object.fromEntries( + VISIBILITY.map((k) => [k, settings?.[k] === true]) + ) as RoleVisibility + return { + code: false, + flows: settings?.builder_flows === true ? 'compose' : 'none', + apps: settings?.builder_apps === true ? 'compose' : 'none', + manage_schedules: settings?.manage_schedules !== false, + manage_triggers: settings?.manage_triggers !== false, + visibility + } +} + +export type CapabilitiesUser = Partial<Pick<UserExt, 'is_admin' | 'is_super_admin' | 'operator'>> +export type CapabilitiesWorkspace = Pick<UserWorkspace, 'capabilities' | 'operator_settings'> + +/** + * The capabilities of `user` in `workspace` (its entry of `$userWorkspaces`). An admin holds + * everything. The server's `capabilities` win; an older server sends none, and the role is then + * derived from `operator` and `operator_settings` the way it read them. Without a user, a + * non-null `operator_settings` is what marks an operator, as the server sends it to them only. + */ +export function capabilitiesIn( + user: CapabilitiesUser | undefined, + workspace: CapabilitiesWorkspace | undefined +): RoleCapabilities { + if (user?.is_admin || user?.is_super_admin) return FULL_CAPABILITIES + if (workspace?.capabilities) return workspace.capabilities + const operator = user?.operator ?? workspace?.operator_settings != null + return operator ? legacyOperatorCapabilities(workspace?.operator_settings) : FULL_CAPABILITIES +} + +/** Whether the role is gated at all, as `RoleCapabilities::is_restricted`: visibility is left out, + * since hiding a page must not cost a full author what restricted roles are refused, such as + * forking. */ +export function isRestricted(caps: RoleCapabilities): boolean { + return ( + !caps.code || + caps.flows !== 'full' || + caps.apps !== 'full' || + !caps.manage_schedules || + !caps.manage_triggers + ) +} + +/** The role with nothing left to build and the same pages in view: what a session in Use mode + * acts as. */ +export function withoutBuilding(caps: RoleCapabilities): RoleCapabilities { + return { + ...caps, + code: false, + flows: 'none', + apps: 'none', + manage_schedules: false, + manage_triggers: false + } +} + +/** Whether the role hides any page. */ +export function hidesPages(caps: RoleCapabilities): boolean { + return VISIBILITY.some((k) => !caps.visibility[k]) +} diff --git a/frontend/src/lib/stores.ts b/frontend/src/lib/stores.ts index a3147b171c..16b62da863 100644 --- a/frontend/src/lib/stores.ts +++ b/frontend/src/lib/stores.ts @@ -5,6 +5,7 @@ import type { IntrospectionQuery } from 'graphql' import { CancelablePromise, type OperatorSettings, + type RoleCapabilities, type TokenResponse, type UserWorkspaceList, type Workspace, @@ -12,6 +13,7 @@ import { WorkspaceService } from './gen' import { getLocalSetting, type StateStore } from './utils' +import { capabilitiesIn } from './roleCapabilities' import { createState } from './svelte5Utils.svelte' import { DEFAULT_HUB_BASE_URL } from './hub' import type { DbManagerUriState } from './components/dbManagerDrawerModel.svelte' @@ -46,6 +48,9 @@ export interface UserWorkspace { username: string color?: string operator_settings?: OperatorSettings + /** Absent from a server that predates roles; read it through `capabilitiesIn`. */ + role?: string + capabilities?: RoleCapabilities parent_workspace_id?: string | null is_dev_workspace?: boolean dev_workspace_label?: string | null @@ -191,6 +196,18 @@ export const userWorkspaces: Readable<Array<UserWorkspace>> = derived( } ) +/** The user's role capabilities in the navigation workspace. A component acting on another + * workspace (an AI session) reads `useRoleCapabilities` instead. */ +export const roleCapabilities: Readable<RoleCapabilities> = derived( + [userStore, userWorkspaces, workspaceStore], + ([user, workspaces, workspace]) => + capabilitiesIn( + // Mid-switch `user` still describes the workspace being left: only superadmin carries over. + user?.workspace_id === workspace ? user : { is_super_admin: user?.is_super_admin }, + workspaces.find((w) => w.id === workspace) + ) +) + export const codeCompletionLoading = writable<boolean>(false) export const metadataCompletionEnabled = writable<boolean>(true) export const stepInputCompletionEnabled = writable<boolean>(true) diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts index 07216d341f..65cef7085c 100644 --- a/frontend/src/lib/utils.test.ts +++ b/frontend/src/lib/utils.test.ts @@ -367,7 +367,8 @@ describe('cleanValueProperties', () => { 'edited_by', 'workspace_id', 'parent_hashes', - 'lock_error_logs' + 'lock_error_logs', + 'starred' ] it('strips every server-managed bookkeeping key', () => { diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 13ae454c92..f3dfb01746 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -1422,7 +1422,8 @@ function replaceFalseWithUndefinedRec(obj: any) { // `hash` is the deployed version's identity, `assets` is re-derived from the // script content by the editor, and `inherited_labels` is computed at read time // from the parent folder — none is editable content, so all three are noise in a -// fork/workspace or version diff. +// fork/workspace or version diff. `starred` is the viewer's own favorite flag, and a +// starred item's `starred: true` survives `replaceFalseWithUndefined`. // // `lock` and `extra_perms` are deliberately NOT in this set: both are legitimate, // user-meaningful fields in some diff contexts (lockfile changes in version-to-version @@ -1447,7 +1448,8 @@ const CLEANED_VALUE_KEYS = new Set([ 'edited_by', 'workspace_id', 'parent_hashes', - 'lock_error_logs' + 'lock_error_logs', + 'starred' ]) export function cleanValueProperties(obj: Value) { @@ -1657,12 +1659,15 @@ export type Item = { href?: string hrefTarget?: '_blank' | '_self' | '_parent' | '_top' disabled?: boolean - type?: 'action' | 'delete' + /** `ai` sets the row in the AI colour, for an action that hands something to the assistant. */ + type?: 'action' | 'delete' | 'ai' hide?: boolean | undefined extra?: Snippet id?: string tooltip?: string separatorTop?: boolean + /** A heading above the row, opening a section of the menu. */ + sectionTitle?: string /** Renders an on/off switch at the end of the row, so `icon` keeps the leading * slot. Presentational: the row's own click is what flips it, so `action` must * apply the change. */ diff --git a/frontend/src/lib/utils/editInFork.ts b/frontend/src/lib/utils/editInFork.ts index d43c3644c9..9e74878f39 100644 --- a/frontend/src/lib/utils/editInFork.ts +++ b/frontend/src/lib/utils/editInFork.ts @@ -1,5 +1,8 @@ import { get } from 'svelte/store' +import { isRestricted } from '$lib/roleCapabilities' +import type { RoleCapabilities } from '$lib/gen' import { + roleCapabilities, userStore, userWorkspaces, workspaceStore, @@ -19,16 +22,17 @@ export type ItemType = 'script' | 'flow' | 'app' | 'raw_app' * Whether to show the "edit in fork / dev workspace" affordance. Allowed when the user may create a * fork, OR when the current workspace has a canonical dev to route to — routing into an existing dev * workspace creates no fork, so it survives a locked prod that has `DisableWorkspaceForking` set. - * Never for an operator, who has nothing to edit at the other end either way. User identity is read - * non-reactively (it's stable within a session); reactivity comes from the workspace args. + * Never for a role without `code`, which has nothing to edit at the other end either way. User + * identity is read non-reactively (it's stable within a session); reactivity comes from the + * workspace args. */ export function editInForkAllowed( currentWorkspaceId: string | undefined, allWorkspaces: UserWorkspace[] ): boolean { - const user = get(userStore) - if (user?.operator) return false - return canCreateFork(user) || !!findCanonicalDevWorkspace(currentWorkspaceId, allWorkspaces) + const caps = get(roleCapabilities) + if (!caps.code) return false + return canCreateFork(get(userStore), caps) || !!findCanonicalDevWorkspace(currentWorkspaceId, allWorkspaces) } /** Label for the affordance: "Edit in <dev name>" when routed to a canonical dev, else "Edit in fork". */ @@ -54,17 +58,17 @@ export function editInForkDescription( } /** - * Whether the user may CREATE a new fork of the current workspace: not an operator, and either - * forking isn't disabled or they can bypass the rule (workspace admins). Keeps the "Fork workspace" - * entry available to admins as the last-resort escape hatch on a locked prod. + * Whether the user may CREATE a new fork of the current workspace: their role is unrestricted, and + * either forking isn't disabled or they can bypass the rule (workspace admins). Keeps the "Fork + * workspace" entry available to admins as the last-resort escape hatch on a locked prod. * - * An operator is refused because a fork does not carry the role: the server writes the forker's - * membership row from the parent's `is_admin` and lets `operator` fall to its `false` default, so - * forking would hand an operator a full-rights copy of the workspace. The server does not refuse it - * — this hides the affordance, it does not enforce the rule. + * Any restricted role is refused because a fork does not carry the role: the server writes the + * forker's membership row from the parent's `is_admin` alone, so the forker gets the default role + * and forking would hand a restricted member a full-rights copy of the workspace. The server does + * not refuse it: this hides the affordance, it does not enforce the rule. */ -export function canCreateFork(user: UserExt | undefined): boolean { - if (user?.operator) return false +export function canCreateFork(user: UserExt | undefined, caps: RoleCapabilities): boolean { + if (isRestricted(caps)) return false return ( !isRuleActive('DisableWorkspaceForking') || canUserBypassRuleKind('DisableWorkspaceForking', user) diff --git a/frontend/src/lib/utils/preloadComponent.svelte.ts b/frontend/src/lib/utils/preloadComponent.svelte.ts new file mode 100644 index 0000000000..16ea5b5aca --- /dev/null +++ b/frontend/src/lib/utils/preloadComponent.svelte.ts @@ -0,0 +1,19 @@ +/** + * Starts loading a component's chunk when the calling module is evaluated and exposes it once + * loaded. Call it from a `<script module>` so a mount after the load renders the component in its + * first frame: an `{#await import()}` shows its pending branch for a tick even on a cached chunk. + * A failed load is left unhandled on purpose: the root layout reports chunk-load failures. + */ +export function preloadComponent<T>(load: () => Promise<{ default: T }>): { + readonly current: T | undefined +} { + let current = $state.raw<T | undefined>(undefined) + load().then((m) => { + current = m.default + }) + return { + get current() { + return current + } + } +} diff --git a/frontend/src/lib/utils/previewOnBehalfOf.ts b/frontend/src/lib/utils/previewOnBehalfOf.ts index 5ca4d9133c..3b28223b88 100644 --- a/frontend/src/lib/utils/previewOnBehalfOf.ts +++ b/frontend/src/lib/utils/previewOnBehalfOf.ts @@ -5,8 +5,9 @@ type ActingUser = /** * The identity an editor preview should run as: the runnable's configured run-as identity, so a * test behaves like the current deployed run. Only admins and `wm_deployers` may preview as - * someone else, and never operators (the server refuses everyone else); anyone else previews as - * themselves, which is also what their own save would record. + * someone else, and never a role without `code`, which is what `operator` carries (the server + * refuses everyone else); anyone else previews as themselves, which is also what their own save + * would record. */ export function previewOnBehalfOf( user: ActingUser, diff --git a/frontend/src/lib/utils_draft_deploy.test.ts b/frontend/src/lib/utils_draft_deploy.test.ts index c141af3a3b..71ee7b560b 100644 --- a/frontend/src/lib/utils_draft_deploy.test.ts +++ b/frontend/src/lib/utils_draft_deploy.test.ts @@ -6,7 +6,7 @@ vi.mock('$lib/gen', () => ({ FlowService: { getFlowByPath: vi.fn(), createFlow: vi.fn(), updateFlow: vi.fn() }, DraftService: { deleteDraft: vi.fn() }, AppService: {}, - VariableService: {}, + VariableService: { getVariable: vi.fn(), createVariable: vi.fn(), updateVariable: vi.fn() }, ResourceService: { getResource: vi.fn(), updateResource: vi.fn(), createResource: vi.fn() }, ScheduleService: {}, HttpTriggerService: {}, @@ -32,7 +32,7 @@ vi.mock('$lib/components/raw_apps/utils', () => ({ canonicalRawAppDiffValue: vi. vi.mock('$lib/appDiffSides', () => ({ classicAppDraftParts: vi.fn() })) vi.mock('$lib/utils_deployable', () => ({ TRIGGER_RUNTIME_IGNORE: [] })) -import { ScriptService, FlowService, ResourceService } from '$lib/gen' +import { ScriptService, FlowService, VariableService, ResourceService } from '$lib/gen' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' // draftBaseIsStale compares a draft's base pointer against the deployed head @@ -143,6 +143,62 @@ describe('deployDraft preserves on_behalf_of', () => { }) }) +// The deploy bodies are built field by field, so a forgotten field is dropped silently. +describe('deployDraft variable value_valid_until', () => { + beforeEach(() => vi.clearAllMocks()) + + const DATE = '2027-03-15T08:30:00.000Z' + + function mockVariable(deployedExpiry: string | undefined, draftExpiry: string | undefined) { + vi.mocked(VariableService.getVariable).mockResolvedValueOnce({ + path: 'u/admin/key', + value: 'v', + is_secret: false, + description: '', + value_valid_until: deployedExpiry, + draft: { + path: 'u/admin/key', + variable: { value: 'v', is_secret: false, description: '' }, + value_valid_until: draftExpiry + } + } as any) + } + + const updateBody = () => + vi.mocked(VariableService.updateVariable).mock.calls[0][0].requestBody as any + + it('sends a date the draft set on a variable that had none', async () => { + mockVariable(undefined, DATE) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBe(DATE) + }) + + it('sends null when the draft cleared the deployed date', async () => { + mockVariable(DATE, undefined) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBeNull() + }) + + it('omits it when the draft leaves the deployed date alone', async () => { + mockVariable(DATE, DATE) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBeUndefined() + }) + + it('omits it when the draft spells the deployed moment differently', async () => { + mockVariable('2027-03-15T08:30:00Z', DATE) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBeUndefined() + }) + + it('carries the date onto a draft-only variable', async () => { + mockVariable(undefined, DATE) + await deployDraft('variable', 'u/admin/key', 'ws', { draftOnly: true }) + const body = vi.mocked(VariableService.createVariable).mock.calls[0][0].requestBody as any + expect(body.value_valid_until).toBe(DATE) + }) +}) + // The backend skips the dependency job when `lock` is set, so a draft that inherited the // deployed lock would deploy new content against the old lockfile. describe('deployDraft: script lock', () => { diff --git a/frontend/src/lib/utils_draft_deploy.ts b/frontend/src/lib/utils_draft_deploy.ts index 96b83239b7..716eaca9d7 100644 --- a/frontend/src/lib/utils_draft_deploy.ts +++ b/frontend/src/lib/utils_draft_deploy.ts @@ -219,14 +219,15 @@ function stripScheduleTriggerRuntime(row: any): Record<string, unknown> { function canonicalizeDraftDiffValue(kind: DraftKind, raw: any, isDraft: boolean): unknown { if (!raw || typeof raw !== 'object') return raw ?? {} if (kind === 'variable') { - // draft: { variable: { value, is_secret, description }, labels, wsSpecific } - // deployed row: { value, is_secret, description, labels, ws_specific } + // draft: { variable: { value, is_secret, description }, value_valid_until, labels, wsSpecific } + // deployed row: { value, is_secret, description, value_valid_until, labels, ws_specific } const v = isDraft ? (raw.variable ?? {}) : raw const is_secret = !!v.is_secret return { value: is_secret ? '<secret>' : (v.value ?? ''), is_secret, description: v.description ?? '', + value_valid_until: raw.value_valid_until ?? undefined, labels: raw.labels ?? undefined, ws_specific: (isDraft ? raw.wsSpecific : raw.ws_specific) ?? undefined } @@ -446,6 +447,10 @@ async function deployDraftTriggers( await deployTriggers(triggers, workspace, isAdmin, writable<string[]>([]), path, isNew) } +function timeOf(date: string | null | undefined): number | undefined { + return date ? new Date(date).getTime() : undefined +} + /** * Promote a draft to deployed by replaying the editor's create/update call with * the stored draft value. The matching draft row is deleted server-side by the @@ -594,7 +599,7 @@ export async function deployDraft( } else if (kind === 'variable') { const { deployed, draft: d } = splitOverlay(await OVERLAY_GETTERS.variable!(workspace, path)) // VariableEditor's `VariableState` draft shape: - // { path, variable: { value, is_secret, description }, labels?, wsSpecific } + // { path, variable: { value, is_secret, description }, value_valid_until?, labels?, wsSpecific } if (draftOnly) { await VariableService.createVariable({ workspace, @@ -603,6 +608,7 @@ export async function deployDraft( value: d.variable?.value ?? '', is_secret: !!d.variable?.is_secret, description: d.variable?.description ?? '', + value_valid_until: d.value_valid_until, labels: d.labels, ws_specific: d.wsSpecific } @@ -617,12 +623,17 @@ export async function deployDraft( value: d.variable?.value === '' ? undefined : d.variable?.value, is_secret: d.variable?.is_secret, description: d.variable?.description, + // `null` clears, absent keeps. Diffed against the deployed row by moment, since + // an absent date in the draft means "no expiry", not "unchanged". + value_valid_until: + timeOf(deployed.value_valid_until) !== timeOf(d.value_valid_until) + ? (d.value_valid_until ?? null) + : undefined, labels: d.labels, ws_specific: d.wsSpecific } }) } - void deployed } else if (kind === 'resource') { const overlay = await OVERLAY_GETTERS.resource!(workspace, path) // Adopt the row this promote is based on as the baseline for the delete below. Without one diff --git a/frontend/src/lib/utils_workspace_deploy.test.ts b/frontend/src/lib/utils_workspace_deploy.test.ts index dfac557d20..5db05d041a 100644 --- a/frontend/src/lib/utils_workspace_deploy.test.ts +++ b/frontend/src/lib/utils_workspace_deploy.test.ts @@ -32,8 +32,8 @@ vi.mock('$lib/gen', async (importOriginal) => ({ } })) -// The deploy runs the published shared package, whose variable body has no `labels`: this -// pins that the adapter still carries them until a version that does is installed. +// The variable body is built by the installed shared package: this pins that a deploy from the +// app sends the source's labels on create and on update. describe('deploying a variable to another workspace', () => { it('carries its labels on create and on update', async () => { for (const workspaceTo of ['lacks-it', 'has-it']) { @@ -239,14 +239,17 @@ describe('workspace-level deploy permission', () => { expect(res.reason).toContain('Direct deployment') }) - // The server refuses an operator in the item handler regardless of their global role: a - // superadmin who is an operator in the workspace still gets 401 creating a script. So the - // operator term has to stay above the admin/superadmin short-circuit — hoisting the admin - // checks would offer a deploy the server refuses. - it('refuses an operator who is also a superadmin', async () => { + // Authentication merges superadmin into admin, and `caller_capabilities` gives an admin every + // capability, whatever the workspace role. + it('lets a superadmin whose role is operator deploy', async () => { const res = await permission({ ...member, operator: true, is_super_admin: true }, []) + expect(res.ok).toBe(true) + }) + + it('refuses a member whose role cannot code', async () => { + const res = await permission({ ...member, operator: true }, []) expect(res.ok).toBe(false) - expect(res.reason).toContain('operator') + expect(res.reason).toContain('role') }) }) diff --git a/frontend/src/lib/utils_workspace_deploy.ts b/frontend/src/lib/utils_workspace_deploy.ts index 91820b581e..272b2f1dad 100644 --- a/frontend/src/lib/utils_workspace_deploy.ts +++ b/frontend/src/lib/utils_workspace_deploy.ts @@ -22,6 +22,11 @@ import { type User } from '$lib/gen' import type { UserDraftItemKind } from '$lib/gen' +import { get } from 'svelte/store' +import { userWorkspaces } from '$lib/stores' +import { capabilitiesIn } from '$lib/roleCapabilities' +import { roleCanAuthor } from '$lib/editRights' +import type { ProtectionRuleset, RoleCapabilities } from '$lib/gen' import { fetchProtectionRulesForWorkspace, canUserBypassRuleKindInRulesets @@ -181,30 +186,13 @@ export type AppIdentity = { email: string; permissionedAs: string } export type DeployConflict = { hit: boolean } /** - * `deployItem` overrides only the email half of the identity, while the body it builds - * spreads the *source* item — which carries the source workspace's permissioned_as, valid - * nowhere else since usernames are per-workspace. The key is therefore always overwritten: - * with the picked user's principal for a custom choice, and cleared otherwise so the - * backend derives the target's own from the email it is given. The shared `deployItem` - * does the same, but this app consumes the published package, so the rewrite has to exist - * on both sides until that version ships. - * - * An app carries both halves inside its `policy` instead, so it needs both stamped here: - * the published package leaves the policy untouched, and a source principal beside a - * target address is rejected as a pair naming two different accounts. - * - * A group kept as the target identity travels as its synthetic `group-*@windmill.dev` - * address, which an admin-created account holding it would win on the backend: known and - * accepted, see `users::permissioned_as_from_email`. - * - * An agent carries its principal inside its resource value, and is handed the chosen one as a - * principal, as a trigger is. Every read here drops the source's, so a diff never shows it and - * the published `deployItem` copies none; the write then stamps the chosen one, or none, which - * leaves the backend to make it the deployer's. + * `deployItem` takes the identity only as an email and clears the source workspace's + * principal, leaving the backend to derive the target's own from that email. When the user + * picked a specific user, their principal is known here, so it is stamped on the body: on a + * flow or script directly, and inside the `policy` for an app, which holds both halves. */ function makeProvider( onBehalfOfPrincipal?: string, - onBehalfOf?: string, /** * Refuse the writes the shared `deployItem` reaches for only when the item already exists in * the target, turning its silent switch to an update into a failure the caller can act on. @@ -214,48 +202,16 @@ function makeProvider( */ conflict?: DeployConflict ): DeployProvider { - const withPermissionedAs = <T extends Record<string, any>>(requestBody: T): T => ({ - ...requestBody, - on_behalf_of: onBehalfOfPrincipal - }) + const withPermissionedAs = <T extends Record<string, any>>(requestBody: T): T => + onBehalfOfPrincipal ? { ...requestBody, on_behalf_of: onBehalfOfPrincipal } : requestBody const withPolicyIdentity = <T extends Record<string, any>>(app: T): T => - app.policy - ? { - ...app, - policy: { - ...app.policy, - on_behalf_of: onBehalfOfPrincipal, - on_behalf_of_email: onBehalfOf - } - } + onBehalfOfPrincipal && app.policy + ? { ...app, policy: { ...app.policy, on_behalf_of: onBehalfOfPrincipal } } : app - const agents = new Set<string>() - const withAgentIdentity = <T extends Record<string, any>>(requestBody: T, path: string): T => - agents.has(path) && requestBody.value && typeof requestBody.value === 'object' - ? { - ...requestBody, - value: onBehalfOf - ? { ...requestBody.value, on_behalf_of: onBehalfOf } - : requestBody.value, - preserve_on_behalf_of: onBehalfOf !== undefined - } - : requestBody const refuseUpdate = (): never => { if (conflict) conflict.hit = true throw new Error('item already exists in the target workspace') } - // The published package builds variable, resource and folder bodies field by field without - // `labels`, so carry the source item's across from the read `deployItem` does just before the - // write. One provider serves one deploy, so the read always belongs to the write that follows. - let sourceLabels: string[] | undefined - const readLabels = <T extends { labels?: string[] }>(item: T): T => { - sourceLabels = item.labels - return item - } - const withLabels = <T extends Record<string, any>>(requestBody: T): T => ({ - ...requestBody, - labels: sourceLabels - }) return { existsFlowByPath: (p) => FlowService.existsFlowByPath(p), existsScriptByPath: (p) => ScriptService.existsScriptByPath(p), @@ -300,43 +256,21 @@ function makeProvider( getPublicSecretOfLatestVersionOfApp: (p) => AppService.getPublicSecretOfLatestVersionOfApp(p), getRawAppData: (p) => AppService.getRawAppData(p), deleteApp: (p) => AppService.deleteApp(p), - getVariable: (p) => VariableService.getVariable(p).then(readLabels), - createVariable: (p) => - VariableService.createVariable({ ...p, requestBody: withLabels(p.requestBody) }), - updateVariable: (p) => - VariableService.updateVariable({ ...p, requestBody: withLabels(p.requestBody) }), + getVariable: (p) => VariableService.getVariable(p), + createVariable: (p) => VariableService.createVariable(p), + updateVariable: (p) => VariableService.updateVariable(p), deleteVariable: (p) => VariableService.deleteVariable(p), - getResource: async (p) => { - const resource = readLabels(await ResourceService.getResource(p)) - if (resource.resource_type !== 'ai_agent' || !resource.value) return resource - agents.add(p.path) - const { on_behalf_of: _, ...value } = resource.value as Record<string, any> - return { ...resource, value } - }, - createResource: (p) => - ResourceService.createResource({ - ...p, - requestBody: withAgentIdentity(withLabels(p.requestBody), p.requestBody.path) - }), - updateResource: (p) => - ResourceService.updateResource({ - ...p, - requestBody: withAgentIdentity(withLabels(p.requestBody), p.path) - }), + getResource: (p) => ResourceService.getResource(p), + createResource: (p) => ResourceService.createResource(p), + updateResource: (p) => ResourceService.updateResource(p), deleteResource: (p) => ResourceService.deleteResource(p), getResourceType: (p) => ResourceService.getResourceType(p), createResourceType: (p) => ResourceService.createResourceType(p), updateResourceType: (p) => ResourceService.updateResourceType(p), deleteResourceType: (p) => ResourceService.deleteResourceType(p), - getFolder: (p) => FolderService.getFolder(p).then(readLabels), - createFolder: (p) => - FolderService.createFolder({ ...p, requestBody: withLabels(p.requestBody) }), - // A folder with no labels reads back without the field, so clearing them needs an explicit []. - updateFolder: (p) => - FolderService.updateFolder({ - ...p, - requestBody: { ...p.requestBody, labels: sourceLabels ?? [] } - }), + getFolder: (p) => FolderService.getFolder(p), + createFolder: (p) => FolderService.createFolder(p), + updateFolder: (p) => FolderService.updateFolder(p), deleteFolder: (p) => FolderService.deleteFolder(p), // Triggers existsTriggerByKind: (kind, p) => triggerServiceFor(kind).exists(p), @@ -478,7 +412,7 @@ export async function deployItem( const conflict: DeployConflict | undefined = createOnly ? { hit: false } : undefined const result = await sharedDeployItem( - makeProvider(onBehalfOfPrincipal, onBehalfOf, conflict), + makeProvider(onBehalfOfPrincipal, conflict), kind as DeployKind, path, workspaceFrom, @@ -836,6 +770,24 @@ export function kindGatedByDeployRules(kind: Kind | UserDraftItemKind): boolean return GATED_KIND_NAMES.has(kind) } +// The kinds whose item handlers refuse a role per kind (`check_role_can_code`, +// `check_operator_can_build`, `require_full_apps`). `checkDeployPermission` only asks for `code`, +// so a role that codes but cannot author flows or apps is caught here. +const ROLE_GATED_KINDS = new Set<string>(['script', 'flow', 'app', 'raw_app', 'data_pipeline']) + +function roleRefusal( + kind: Kind | UserDraftItemKind, + caps: RoleCapabilities +): DeployPermission | undefined { + if (!ROLE_GATED_KINDS.has(kind) || roleCanAuthor(kind === 'data_pipeline' ? 'script' : kind, caps)) + return undefined + return { + ok: false, + reason: `Your role in this workspace can't deploy ${kind.replace('_', ' ')}s`, + refusedBy: 'operator' + } +} + /** * Narrow a workspace-level refusal to one item kind. Only the direct-deployment term is scoped: * the deployers-only term over-reaches the same way, but it does so on `main` too, and loosening @@ -843,8 +795,11 @@ export function kindGatedByDeployRules(kind: Kind | UserDraftItemKind): boolean */ export function deployPermissionForKind( perm: DeployPermission, - kind: Kind | UserDraftItemKind + kind: Kind | UserDraftItemKind, + caps?: RoleCapabilities ): DeployPermission { + const refusal = caps && roleRefusal(kind, caps) + if (refusal) return refusal if (perm.ok) return perm if (perm.refusedBy === 'DisableDirectDeployment' && !kindGatedByDeployRules(kind)) { return { ok: true } @@ -855,8 +810,11 @@ export function deployPermissionForKind( /** The refusal a bulk action carries: it applies as soon as one selected kind is still refused. */ export function deployPermissionForKinds( perm: DeployPermission, - kinds: (Kind | UserDraftItemKind)[] + kinds: (Kind | UserDraftItemKind)[], + caps?: RoleCapabilities ): DeployPermission { + const refusal = caps && kinds.map((k) => roleRefusal(k, caps)).find((r) => r) + if (refusal) return refusal if (perm.ok) return perm // An empty selection keeps the workspace-level refusal, which is then the only thing left // to say why the action is unavailable. @@ -880,7 +838,9 @@ export async function checkDeployRules( workspace: string, /** Pre-fetched identity for `workspace`, to save a round trip. Narrowed to the fields * read so a caller holding a `UserExt` can pass it without a cast. */ - whoami?: Pick<User, 'is_admin' | 'is_super_admin' | 'username' | 'groups'> + whoami?: Pick<User, 'is_admin' | 'is_super_admin' | 'username' | 'groups'>, + /** Pre-fetched protection rules for `workspace`, to save another. */ + knownRulesets?: ProtectionRuleset[] ): Promise<DeployPermission> { try { const me = whoami ?? (await UserService.whoami({ workspace })) @@ -893,7 +853,7 @@ export async function checkDeployRules( // A superadmin who is only a plain member of the workspace still bypasses every rule, // so dropping either term here refuses a deploy the server accepts. if (!userInfo.is_admin && !userInfo.is_super_admin) { - const rulesets = await fetchProtectionRulesForWorkspace(workspace) + const rulesets = knownRulesets ?? (await fetchProtectionRulesForWorkspace(workspace)) if (!canUserBypassRuleKindInRulesets(rulesets, 'DisableDirectDeployment', userInfo)) { // The reserved dev-workspace lock carries DisableWorkspaceForking alongside this rule, // so suggesting a fork unconditionally would point at a second blocked action. @@ -933,9 +893,9 @@ export async function checkDeployRules( /** * Whether the current user may deploy into `workspace` at all: the protection rules above, - * plus a refusal of every operator. + * plus a refusal of every role without `code`. * - * That refusal is not part of the `check_deploy_rules` mirror. The server refuses operators + * That refusal is not part of the `check_deploy_rules` mirror. The server refuses such roles * in the item handlers instead, and for fewer kinds, so refusing them for everything here is * deliberately stricter than the server rather than a faithful copy of it. A caller mirroring * one handler wants `checkDeployRules`. @@ -948,10 +908,10 @@ export async function checkDeployPermission( ): Promise<DeployPermission> { try { const me = whoami ?? (await UserService.whoami({ workspace })) - if (me.operator) { + if (!capabilitiesIn(me, get(userWorkspaces).find((w) => w.id === workspace)).code) { return { ok: false, - reason: "You're an operator in this workspace — operators can't deploy", + reason: "Your role in this workspace can't deploy", refusedBy: 'operator' } } diff --git a/frontend/src/lib/workspaceProtectionRules.svelte.ts b/frontend/src/lib/workspaceProtectionRules.svelte.ts index 01d122794d..af40138f7d 100644 --- a/frontend/src/lib/workspaceProtectionRules.svelte.ts +++ b/frontend/src/lib/workspaceProtectionRules.svelte.ts @@ -89,12 +89,19 @@ export async function loadProtectionRules(workspace: string): Promise<void> { export async function fetchProtectionRulesForWorkspace( workspace: string ): Promise<ProtectionRuleset[]> { + return (await readProtectionRulesForWorkspace(workspace)) ?? [] +} + +/** The same rules, but `undefined` when they cannot be read, for a caller that has to fail + * closed rather than read an error as "no rules". */ +export async function readProtectionRulesForWorkspace( + workspace: string +): Promise<ProtectionRuleset[] | undefined> { try { - const rulesets = await WorkspaceService.listProtectionRules({ workspace }) - return rulesets + return await WorkspaceService.listProtectionRules({ workspace }) } catch (error) { console.error(`Failed to fetch protection rules for workspace ${workspace}:`, error) - return [] + return undefined } } diff --git a/frontend/src/lib/workspaceRoles.test.ts b/frontend/src/lib/workspaceRoles.test.ts new file mode 100644 index 0000000000..84f3ff8a71 --- /dev/null +++ b/frontend/src/lib/workspaceRoles.test.ts @@ -0,0 +1,64 @@ +import { describe, it, expect } from 'vitest' +import type { EffectiveRole } from '$lib/gen' +import { + applyCapabilitiesPatch, + baseCapabilitiesFor, + FULL_CAPABILITIES, + validRoleOr, + workspaceRolesErrors +} from './workspaceRoles' + +// These mirror `windmill_common::roles`; the server refuses what they let through. +describe('role capability layering', () => { + it('falls back to full for developer and to the operator rights for any other name', () => { + expect(baseCapabilitiesFor('developer')).toEqual(FULL_CAPABILITIES) + const other = baseCapabilitiesFor('reviewer') + expect([other.code, other.flows, other.manage_schedules]).toEqual([false, 'none', true]) + }) + + it('applies only the keys a patch sets', () => { + const caps = applyCapabilitiesPatch(baseCapabilitiesFor('x'), { + flows: 'compose', + visibility: { workers: false } + }) + expect(caps.flows).toBe('compose') + expect(caps.apps).toBe('none') + expect(caps.visibility.workers).toBe(false) + expect(caps.visibility.runs).toBe(true) + }) + + it('treats a stored null as unset, as serde reads it', () => { + const caps = applyCapabilitiesPatch(baseCapabilitiesFor('developer'), { + code: null as any, + visibility: { runs: null as any } + }) + expect(caps).toEqual(FULL_CAPABILITIES) + expect( + workspaceRolesErrors([{ name: 'developer', capabilities: { code: null as any } }]) + ).toEqual({}) + }) + + it('refuses what parse_instance_roles refuses', () => { + expect(workspaceRolesErrors(undefined)).toEqual({}) + expect(workspaceRolesErrors([])).toHaveProperty('list') + expect(workspaceRolesErrors([{ name: 'admin' }])).toHaveProperty('0.name') + expect(workspaceRolesErrors([{ name: 'a' }, { name: 'a' }])).toHaveProperty('1.name') + expect(workspaceRolesErrors([{ name: 'x', capabilities: { flows: 'full' } }])).toHaveProperty( + '0.capabilities' + ) + expect( + workspaceRolesErrors([{ name: 'developer', capabilities: { apps: 'compose' } }]) + ).toEqual({}) + }) +}) + +describe('validRoleOr', () => { + const role = (name: string) => ({ name }) as EffectiveRole + + it('falls back to developer, or the first role when the instance dropped it', () => { + expect(validRoleOr([role('operator'), role('developer')], undefined)).toBe('developer') + expect(validRoleOr([role('builder'), role('viewer')], undefined)).toBe('builder') + expect(validRoleOr([role('builder'), role('viewer')], 'developer')).toBe('builder') + expect(validRoleOr([role('builder')], 'admin')).toBe('admin') + }) +}) diff --git a/frontend/src/lib/workspaceRoles.ts b/frontend/src/lib/workspaceRoles.ts new file mode 100644 index 0000000000..4cfb3a6089 --- /dev/null +++ b/frontend/src/lib/workspaceRoles.ts @@ -0,0 +1,218 @@ +import { + WorkspaceService, + type AuthorLevel, + type EffectiveRole, + type RoleCapabilities, + type RoleCapabilitiesPatch, + type RoleDefinition, + type RoleVisibility, + type WorkspaceRoles +} from '$lib/gen' + +/** Not a role: the `is_admin` flag, offered next to the roles wherever a member's access is picked. */ +export const ADMIN_ROLE = 'admin' + +export const DEVELOPER_ROLE = 'developer' +export const OPERATOR_ROLE = 'operator' + +export const VISIBILITY_KEYS: { key: keyof RoleVisibility; label: string }[] = [ + { key: 'runs', label: 'Runs' }, + { key: 'schedules', label: 'Schedules' }, + { key: 'resources', label: 'Resources' }, + { key: 'variables', label: 'Variables' }, + { key: 'assets', label: 'Assets' }, + { key: 'triggers', label: 'Triggers' }, + { key: 'audit_logs', label: 'Audit logs' }, + { key: 'groups', label: 'Groups' }, + { key: 'folders', label: 'Folders' }, + { key: 'workers', label: 'Workers' } +] + +const ALL_VISIBLE: RoleVisibility = { + runs: true, + schedules: true, + resources: true, + variables: true, + assets: true, + triggers: true, + audit_logs: true, + groups: true, + folders: true, + workers: true +} + +// Mirror `RoleCapabilities::FULL` and `RoleCapabilities::OPERATOR` in `windmill_common::roles`. +export const FULL_CAPABILITIES: RoleCapabilities = { + code: true, + flows: 'full', + apps: 'full', + manage_schedules: true, + manage_triggers: true, + visibility: ALL_VISIBLE +} + +const OPERATOR_CAPABILITIES: RoleCapabilities = { + code: false, + flows: 'none', + apps: 'none', + manage_schedules: true, + manage_triggers: true, + visibility: ALL_VISIBLE +} + +export const DEFAULT_INSTANCE_ROLES: RoleDefinition[] = [ + { name: DEVELOPER_ROLE, label: 'Developer', capabilities: {} }, + { name: OPERATOR_ROLE, label: 'Operator', capabilities: {} } +] + +/** What a role named `name` holds before any configuration: `RoleCapabilities::base_for`. */ +export function baseCapabilitiesFor(name: string): RoleCapabilities { + return applyCapabilitiesPatch( + name === DEVELOPER_ROLE ? FULL_CAPABILITIES : OPERATOR_CAPABILITIES, + undefined + ) +} + +export function applyCapabilitiesPatch( + base: RoleCapabilities, + patch: RoleCapabilitiesPatch | undefined +): RoleCapabilities { + // Spread rather than `structuredClone`: `base` may be a Svelte state proxy, which cannot be cloned. + const out: RoleCapabilities = { ...base, visibility: { ...base.visibility } } + if (!patch) return out + // `!= null`: a stored `null` deserializes to `None` server-side, so it is unset like `undefined`. + if (patch.code != null) out.code = patch.code + if (patch.flows != null) out.flows = patch.flows + if (patch.apps != null) out.apps = patch.apps + if (patch.manage_schedules != null) out.manage_schedules = patch.manage_schedules + if (patch.manage_triggers != null) out.manage_triggers = patch.manage_triggers + for (const { key } of VISIBILITY_KEYS) { + const v = patch.visibility?.[key] + if (v != null) out.visibility[key] = v + } + return out +} + +/** The error the server raises for these capabilities, if any (`RoleCapabilities::validate`). */ +export function capabilitiesError(caps: RoleCapabilities): string | undefined { + if (!caps.code && (caps.flows === 'full' || caps.apps === 'full')) { + return 'Full flow or app authoring requires the code capability' + } + return undefined +} + +/** `validate_role_name` in `windmill_common::roles`. */ +export function roleNameError(name: string): string | undefined { + if (name === ADMIN_ROLE) return 'The name admin is reserved' + if (!/^[a-z0-9_-]{1,50}$/.test(name)) { + return 'Use 1 to 50 lowercase letters, digits, underscores or hyphens' + } + return undefined +} + +/** A patch with no key set, so it is dropped rather than stored as `{}`. */ +export function isEmptyPatch(patch: RoleCapabilitiesPatch | undefined): boolean { + if (!patch) return true + const { visibility, ...rest } = patch + return ( + Object.values(rest).every((v) => v == null) && + Object.values(visibility ?? {}).every((v) => v == null) + ) +} + +/** + * What `parse_instance_roles` would refuse in a `workspace_roles` value, keyed `<index>.name`, + * `<index>.capabilities` or `list`. An unset value is the defaults and always valid. + */ +export function workspaceRolesErrors(value: unknown): Record<string, string> { + if (value == undefined) return {} + if (!Array.isArray(value)) return { list: 'Expected a list of roles' } + if (value.length === 0) return { list: 'Keep at least one role' } + const errors: Record<string, string> = {} + const seen = new Set<string>() + value.forEach((r: RoleDefinition, i) => { + const nameError = roleNameError(r?.name ?? '') + if (nameError) errors[`${i}.name`] = nameError + else if (seen.has(r.name)) errors[`${i}.name`] = 'Another role has this name' + seen.add(r?.name) + const capsError = capabilitiesError( + applyCapabilitiesPatch(baseCapabilitiesFor(r?.name ?? ''), r?.capabilities) + ) + if (capsError) errors[`${i}.capabilities`] = capsError + }) + return errors +} + +/** Whether `roles` is the default list, which is stored as no value at all. */ +export function isDefaultInstanceRoles(roles: RoleDefinition[]): boolean { + return ( + roles.length === DEFAULT_INSTANCE_ROLES.length && + roles.every( + (r, i) => + r.name === DEFAULT_INSTANCE_ROLES[i].name && + (r.label ?? '') === DEFAULT_INSTANCE_ROLES[i].label && + isEmptyPatch(r.capabilities) + ) + ) +} + +export function authorLevelLabel(level: AuthorLevel): string { + return level === 'none' ? 'None' : level === 'compose' ? 'Compose' : 'Full' +} + +export async function loadWorkspaceRoles(workspace: string): Promise<WorkspaceRoles> { + return await WorkspaceService.listWorkspaceRoles({ workspace }) +} + +/** + * The role a new member gets when none is picked: `developer` while the workspace defines it, + * the first role otherwise, as the server picks one. + */ +export function defaultRoleName(roles: EffectiveRole[] | undefined): string { + if (!roles?.length || roles.some((r) => r.name === DEVELOPER_ROLE)) return DEVELOPER_ROLE + return roles[0].name +} + +/** `value` while the workspace still defines it (or it is Admin), the default role otherwise. */ +export function validRoleOr(roles: EffectiveRole[] | undefined, value: string | undefined): string { + if (value === ADMIN_ROLE || (value && (!roles || roles.some((r) => r.name === value)))) { + return value + } + return defaultRoleName(roles) +} + +/** Role picker items: the workspace's roles in their order, then Admin. */ +export function roleItems( + roles: EffectiveRole[] | undefined, + opts: { admin?: boolean } = {} +): { label: string; value: string }[] { + const items = (roles ?? []).map((r) => ({ label: r.label, value: r.name })) + if (opts.admin ?? true) items.push({ label: 'Admin', value: ADMIN_ROLE }) + return items +} + +export function roleLabel(roles: EffectiveRole[] | undefined, name: string | undefined): string { + if (!name) return '' + if (name === ADMIN_ROLE) return 'Admin' + return roles?.find((r) => r.name === name)?.label ?? name +} + +/** The picker value of a member, invite or mapping: `admin` for an admin, its role otherwise. */ +export function pickerValue(m: { is_admin?: boolean; role?: string; operator?: boolean }): string { + if (m.is_admin) return ADMIN_ROLE + return m.role ?? (m.operator ? OPERATOR_ROLE : DEVELOPER_ROLE) +} + +/** + * The fields a picked value is sent as. An admin keeps a role underneath the flag, `developer` + * being what the server gives one when none is named; `operator` is set for servers that predate + * roles. + */ +export function roleRequestFields(value: string): { + is_admin: boolean + operator: boolean + role?: string +} { + if (value === ADMIN_ROLE) return { is_admin: true, operator: false } + return { is_admin: false, operator: value === OPERATOR_ROLE, role: value } +} diff --git a/frontend/src/routes/(root)/(logged)/+layout.svelte b/frontend/src/routes/(root)/(logged)/+layout.svelte index 3084d7dfc2..6b79582958 100644 --- a/frontend/src/routes/(root)/(logged)/+layout.svelte +++ b/frontend/src/routes/(root)/(logged)/+layout.svelte @@ -54,10 +54,12 @@ nonMemberWorkspaces, setNonMemberWorkspaces, clearNonMemberWorkspaces, + roleCapabilities, type UserWorkspace } from '$lib/stores' import CenteredModal from '$lib/components/CenteredModal.svelte' - import { afterNavigate, beforeNavigate } from '$app/navigation' + import { afterNavigate, beforeNavigate, onNavigate } from '$app/navigation' + import { homeSessionsTransition } from '$lib/components/sessions/homeSessionsTransition.svelte' import { goto } from '$lib/navigation' import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte' import type UserSettings from '$lib/components/UserSettings.svelte' @@ -93,7 +95,6 @@ import { overlayStack } from '$lib/components/common/overlayHost.svelte' import PageHeaderBar from '$lib/components/PageHeaderBar.svelte' import { BAR_HEIGHT_PX, pageHeader } from '$lib/components/pageHeaderRegistry.svelte' - import { sidebarPageAllowed } from '$lib/components/sidebar/operatorRoutes' import type GlobalSearchModal from '$lib/components/search/GlobalSearchModal.svelte' import MenuButton from '$lib/components/sidebar/MenuButton.svelte' import MenuLink from '$lib/components/sidebar/MenuLink.svelte' @@ -166,7 +167,7 @@ let collapsedState = $state(collapsePref.val) // Operators never get the icon-only rail: their docked sidebar is always expanded (a sidebar // they want out of the way is what detaching is for). - let isCollapsed = $derived(collapsedState && !$userStore?.operator) + let isCollapsed = $derived(collapsedState && $roleCapabilities.code) // Resizable desktop rail, sized in REM so it scales with the root font-size the // same way the old `w-52`/`w-12` classes did — `:root` jumps to 18px on screens @@ -247,7 +248,7 @@ // instead: dragging the sidebar off the left edge puts it behind the handle. // Detaching is not a resize, so the width the drag started from is what gets // persisted — re-attaching restores the sidebar at the size it had. - if (collapse && $userStore?.operator) { + if (collapse && !$roleCapabilities.code) { sidebarWidth = widthAtStart stop() setDetached(true) @@ -306,7 +307,7 @@ // (SessionModeSwitch) just navigates in and out of that route. // An operator without the opt-in (`gate.ts`) is refused by /sessions, so their sidebar is not // handed over to a session list the page behind it declines, and they keep the docked chat. - const sessionsAllowed = $derived(sessionsAllowedFor($userStore?.operator)) + const sessionsAllowed = $derived(sessionsAllowedFor(!$roleCapabilities.code)) let sessionMode = $derived(page.url.pathname.startsWith('/sessions') && sessionsAllowed) // Session mode points the bottom settings entry at the open session's own // workspace. An unsent draft hasn't committed one yet, so it falls back to @@ -449,6 +450,8 @@ return kind ? { kind, path: route.itemPath } : undefined } + onNavigate(homeSessionsTransition) + beforeNavigate((navigation) => { if (preserveMenuOnNextNav) { preserveMenuOnNextNav = false @@ -661,27 +664,37 @@ } async function loadFavorites() { - const scripts = await ScriptService.listScripts({ - workspace: $workspaceStore ?? '', - starredOnly: true, - includeWithoutMain: true, - withoutDescription: true - }) - const flows = await FlowService.listFlows({ - workspace: $workspaceStore ?? '', - starredOnly: true, - withoutDescription: true - }) - const apps = await AppService.listApps({ - workspace: $workspaceStore ?? '', - starredOnly: true - }) - const agents = await ResourceService.listResource({ - workspace: $workspaceStore ?? '', - resourceType: 'ai_agent', - starredOnly: true - }) - const assets = await AssetService.listFavoriteAssets({ workspace: $workspaceStore ?? '' }) + const workspace = $workspaceStore ?? '' + try { + await loadFavoritesFor(workspace) + } catch (e) { + // `current` still holds another workspace's favorites, which `loadedFor` is about to + // vouch for as this one's. + if (favoriteManager.loadedFor !== workspace && ($workspaceStore ?? '') === workspace) + favoriteManager.current = [] + throw e + } finally { + // Set on failure too: Home holds its shortcuts back until this says the favorites + // are in, and a failed read must not hold them back for good. Not once the workspace + // has changed: a slow load for the last one would name it and hide them in this one. + if (($workspaceStore ?? '') === workspace) favoriteManager.loadedFor = workspace + } + } + + async function loadFavoritesFor(workspace: string) { + const [scripts, flows, apps, agents, assets] = await Promise.all([ + ScriptService.listScripts({ + workspace, + starredOnly: true, + includeWithoutMain: true, + withoutDescription: true + }), + FlowService.listFlows({ workspace, starredOnly: true, withoutDescription: true }), + AppService.listApps({ workspace, starredOnly: true }), + ResourceService.listResource({ workspace, resourceType: 'ai_agent', starredOnly: true }), + AssetService.listFavoriteAssets({ workspace }) + ]) + if (($workspaceStore ?? '') !== workspace) return favoriteManager.current = [ ...scripts.map((s) => ({ label: s.summary || getFavoriteLabel(s.path, 'script'), @@ -1146,11 +1159,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden label="Runs" href="/runs" icon={Play} - disabled={!sidebarPageAllowed( - $userStore?.operator, - $userWorkspaces?.find((w) => w.id === $workspaceStore), - 'runs' - )} + disabled={!$roleCapabilities.visibility.runs} isCollapsed={collapsed} aiId="sidebar-menu-link-runs" aiDescription="Button to navigate to runs" @@ -1182,7 +1191,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden with a sidebar they cannot return. --> {#snippet sidebarToggle()} {@const hidden = navDetached.val} - {#if hidden || $userStore?.operator} + {#if hidden || !$roleCapabilities.code} <Tooltip class="flex" placement="bottom" small> <button class={SIDEBAR_ICON_BUTTON} @@ -1362,7 +1371,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden {/if} <!-- Collapsing belongs to the rail: the panel is over the page already, and the way out of it is the handle in the band or a click outside. --> - {#if !panel && !$userStore?.operator} + {#if !panel && $roleCapabilities.code} <button class={SIDEBAR_ICON_BUTTON} title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'} diff --git a/frontend/src/routes/(root)/(logged)/+page.svelte b/frontend/src/routes/(root)/(logged)/+page.svelte index c20698fae0..d23f92de96 100644 --- a/frontend/src/routes/(root)/(logged)/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/+page.svelte @@ -1,6 +1,7 @@ <script lang="ts"> import { AppService, FlowService, type OpenFlow, type Script } from '$lib/gen' - import { userStore, workspaceStore } from '$lib/stores' + import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' + import { HOME_COLUMN_WIDTH } from '$lib/consts' import { Alert, Button, Drawer, DrawerContent } from '$lib/components/common' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' @@ -97,6 +98,12 @@ // the mount animation below never covers. Replay it by hand instead of keying the page on the // workspace: a remount would drop the list's own state and refetch what it is already loading. let pageEl: HTMLDivElement | undefined = $state(undefined) + + // Back from AI Sessions the view transition (homeSessionsTransition.svelte.ts) carries the arrival, so + // the page skips its own fade-in. Decided once at mount: gating the class on the attribute + // instead would start the fade from transparent the moment the transition removes it. + const fadeIn = + typeof document === 'undefined' || !document.documentElement.dataset.homeSessionsTransition const reducedMotion = useReducedMotion() let animatedWorkspace = $workspaceStore $effect(() => { @@ -131,7 +138,7 @@ replaceState(url, page.state) // Gated here too: the parameter is part of a URL anyone can type, and the tour // describes a home page that only operators see. - if (user.operator) startTour() + if (!$roleCapabilities.code) startTour() }) }) @@ -139,7 +146,7 @@ // Operators get the tour once, and only when they have not been through it: they cannot // create anything, so the home page is the whole product to them and it is worth naming // its three tabs. Anyone who can build gets nothing — they have the create button. - if (!$userStore?.operator || page.url.searchParams.has(TOUR_PARAM)) return + if ($roleCapabilities.code || page.url.searchParams.has(TOUR_PARAM)) return if (await hasSeenOperatorTour()) return startTour() }) @@ -285,7 +292,7 @@ <div bind:this={pageEl} - class="wm-page-in flex flex-col w-full h-full overflow-y-auto items-center" + class="{fadeIn ? 'wm-page-in' : ''} flex flex-col w-full h-full overflow-y-auto items-center" style="scrollbar-gutter: stable both-edges;" > <!-- Where edits to this workspace are made is a fact about the workspace, so it sits in the @@ -294,7 +301,7 @@ <ForkWorkspaceBanner /> <WorkspaceDraftsBanner /> - <div class="max-w-7xl px-4 sm:px-8 md:px-8 h-fit w-full mb-6"> + <div class="{HOME_COLUMN_WIDTH} px-4 sm:px-8 md:px-8 h-fit w-full mb-6 shrink-0"> <!-- HomeAIChat carries both the AI composer and the AI-independent CLI/MCP connect row, so it shows whenever the sessions beta is on; the composer itself is gated on the workspace inside the component, which owns its own vertical spacing @@ -391,7 +398,7 @@ {/if} </div> -{#if $userStore?.operator} +{#if !$roleCapabilities.code} <OperatorTour bind:this={operatorTour} /> {/if} diff --git a/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte index e8b961b72a..7c6b5f9571 100644 --- a/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte @@ -5,6 +5,9 @@ import { copilotInfo } from '$lib/aiStore' import AgentEditorModal from '$lib/components/flows/content/AgentEditorModal.svelte' import { openAgentEditor } from '$lib/components/flows/agentEditorStore.svelte' + import { recentItems } from '$lib/components/home/recentItems.svelte' + import { workspaceStore } from '$lib/stores' + import { ResourceService } from '$lib/gen' let path = $derived(page.params.path ?? '') /** Set by `/agents/add` on the path it minted: a missing agent there is a new one, not an error. */ @@ -12,8 +15,27 @@ $effect(() => { const target = { path, isNew } - untrack(() => openAgentEditor(target)) + untrack(() => { + openAgentEditor(target) + if (!isNew) recordRecent(target.path) + }) }) + + // The agent loads inside the editor, so it is read again here. Only a deployed agent is + // recorded: a draft-only one 404s, and has no page for Home's card to open. + async function recordRecent(agentPath: string) { + const workspace = $workspaceStore + if (!workspace) return + try { + const agent = await ResourceService.getResource({ workspace, path: agentPath }) + recentItems.record(workspace, { + kind: 'agent', + path: agentPath, + summary: agent.description, + via: 'edit' + }) + } catch {} + } </script> <div class="h-full w-full"> diff --git a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte index ed50528dbd..f05203e231 100644 --- a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte @@ -18,12 +18,14 @@ import AgentEditorHost from '$lib/components/flows/content/AgentEditorHost.svelte' import AgentConfigModal from '$lib/components/flows/content/AgentConfigModal.svelte' import RunForm from '$lib/components/RunForm.svelte' - import { Alert } from '$lib/components/common' + import { Alert, Tab, Tabs } from '$lib/components/common' import { keepsManagedMemory } from '$lib/components/flows/agentFormFields' import { agentMenuItems, deleteAgent } from '$lib/components/flows/agentActions' import AgentHistory from '$lib/components/flows/AgentHistory.svelte' import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { userStore, workspaceStore } from '$lib/stores' + import { useEditRights } from '$lib/operatorWriteRights' import { sendUserToast } from '$lib/toast' /** @@ -40,7 +42,23 @@ let testPane = $derived(host?.testPaneHandle()) let config = $derived(agent?.state?.args) let chatAvailable = $derived(keepsManagedMemory(config?.memory)) - let canEdit = $derived(config != undefined && (agent?.canWrite ?? false) && !$userStore?.operator) + const editRights = useEditRights() + let canAuthor = $derived(editRights.roleCanAuthor('agent')) + let canCode = $derived(editRights.capabilities.code) + let canEdit = $derived(config != undefined && (agent?.canWrite ?? false) && canAuthor) + + // Recorded once the agent is in: a path with nothing deployed never loads one. + let loaded = $derived(config != undefined) + $effect(() => { + if (ws && loaded) { + recentItems.record(ws, { + kind: 'agent', + path, + summary: agent?.state?.description, + via: 'view' + }) + } + }) let configModal: AgentConfigModal | undefined = $state(undefined) let shareModal: ShareModal | undefined = $state(undefined) @@ -49,6 +67,10 @@ let deleteOpen = $state(false) let evalsModal: AgentEvalsModal | undefined = $state(undefined) let clientWidth = $state(window.innerWidth) + let pickedMobileTab = $state('agent') + // The page is reused across agents, and an agent without managed memory has no Slack tab. + let mobileTab = $derived(pickedMobileTab === 'slack' && !chatAvailable ? 'api' : pickedMobileTab) + let wide = $derived(clientWidth >= 1024) const slack = resource( () => ({ workspace: ws, path }), @@ -62,7 +84,7 @@ // while the chat shows, and the chat's composer owns the key then. function onKeyDown(event: KeyboardEvent) { if (event.defaultPrevented || event.key !== 'Enter' || !(event.ctrlKey || event.metaKey)) return - if (!runForm || testPane?.mode === 'chat') return + if (!runForm || testPane?.mode === 'chat' || (!wide && mobileTab !== 'agent')) return if (isValid) { event.preventDefault() runForm.run() @@ -80,12 +102,13 @@ () => ws, () => getDeployUiSettings() ) - // Operators get no menu, as on a flow's or a script's page. + // A role that cannot build agents gets no menu, as on a flow's page. let menuItems = $derived( - config != undefined && !$userStore?.operator + config != undefined && canAuthor ? agentMenuItems({ path, canWrite: canEdit, + noCode: !canCode, wsSpecific: agent?.state?.wsSpecific, deployUiSettings: deployUiSettings.current, onPermissions: () => shareModal?.openDrawer?.(path, 'resource'), @@ -141,8 +164,9 @@ } : undefined} mainButtons={[ - // Evaluating an agent builds datasets and runs against it: authoring, as editing is. - ...(canEdit + // Evaluating an agent builds datasets and runs against it: authoring, as editing is, and + // eval datasets are refused to a role without `code` whatever its flows right. + ...(canEdit && canCode ? [ { label: 'Evals', @@ -153,7 +177,11 @@ title: 'Run this agent against a dataset of cases', onClick: () => evalsModal?.openModal() } - }, + } + ] + : []), + ...(canEdit + ? [ { label: 'Edit', buttonProps: { @@ -207,67 +235,97 @@ {/if} {/snippet} </DetailPageHeader> - <div class="flex-1 min-h-0" bind:clientWidth> + <!-- Below `lg` the split would squeeze the chat, so the panel's sections become tabs of the + page, as on a script's or a flow's page. They cover the agent rather than replacing it: + unmounting the host destroys the chat and any turn in flight, so the agent pane keeps one + parent at every width. --> + {#if !wide && ws && config} + <Tabs + bind:selected={() => mobileTab, (t) => (pickedMobileTab = t)} + wrapperClass="flex-none no-scrollbar" + > + <Tab value="agent" label={testPane?.mode === 'chat' ? 'Chat' : 'Run form'} /> + <Tab value="api" label="API" /> + {#if chatAvailable} + <Tab value="slack" label="Slack" /> + {/if} + </Tabs> + {/if} + <div class="relative flex-1 min-h-0" bind:clientWidth> <Splitpanes> - <Pane size={65} minSize={50}> - {#key `${ws}:${path}:${reloaded}`} - <AgentEditorHost - bind:this={host} - {path} - workspace={ws} - enableAi={$copilotInfo.enabled} - view - onOpenConfig={() => configModal?.open()} - > - {#snippet viewForm({ schema, run, loading, actions })} - {#if config && !chatAvailable} - <Alert type="info" size="xs" title="Managed memory is off" class="mb-4"> - Each run is answered on its own inputs, so this agent has no chat. That suits - reusing it as a step in a flow.{canEdit - ? ' Turn on managed memory in its configuration to chat with it.' - : ''} - </Alert> - {/if} - <RunForm - runnable={{ schema, path }} - runAction={run} - schedulable={false} - detailed={false} - autofocus - {loading} - {actions} - bind:isValid - bind:this={runForm} - /> - {/snippet} - </AgentEditorHost> - {/key} + <Pane size={wide ? 65 : 100} minSize={50}> + <div class="h-full" inert={!wide && mobileTab !== 'agent'}> + {@render agentPane()} + </div> </Pane> - <!-- ponytail: no panel below `lg`, where the split would squeeze the chat; give it a tab - there, as a script's page does, once people use it from small screens. --> - {#if ws && config && clientWidth >= 1024} + {#if wide && ws && config} <Pane size={35} minSize={15}> - <AgentUsePanel - agentPath={path} - workspace={ws} - isAdmin={!!($userStore?.is_admin || $userStore?.is_super_admin)} - chat={chatAvailable} - slackLoading={slack.loading && !slack.current} - slackTeamName={slack.current?.slack_team_name} - botName={slack.current?.bot_name} - missingScopes={slack.current?.missing_scopes ?? []} - signingSecretSet={slack.current?.signing_secret_set ?? true} - runsAs={slack.current?.runs_as} - anyone={slack.current?.anyone ?? false} - canShare={slack.current?.can_share ?? false} - channels={slack.current?.channels ?? []} - /> + {@render usePane(ws)} </Pane> {/if} </Splitpanes> + {#if !wide && ws && config} + <div class={['absolute inset-0 z-10 bg-surface', mobileTab === 'agent' && 'hidden']}> + {@render usePane(ws, mobileTab === 'slack' ? 'slack' : 'api')} + </div> + {/if} </div> </main> +{#snippet agentPane()} + {#key `${ws}:${path}:${reloaded}`} + <AgentEditorHost + bind:this={host} + {path} + workspace={ws} + enableAi={$copilotInfo.enabled} + view + onOpenConfig={() => configModal?.open()} + > + {#snippet viewForm({ schema, run, loading, actions })} + {#if config && !chatAvailable} + <Alert type="info" size="xs" title="Managed memory is off" class="mb-4"> + Each run is answered on its own inputs, so this agent has no chat. That suits reusing it + as a step in a flow.{canEdit + ? ' Turn on managed memory in its configuration to chat with it.' + : ''} + </Alert> + {/if} + <RunForm + runnable={{ schema, path }} + runAction={run} + schedulable={false} + detailed={false} + autofocus + {loading} + {actions} + bind:isValid + bind:this={runForm} + /> + {/snippet} + </AgentEditorHost> + {/key} +{/snippet} + +{#snippet usePane(ws: string, section?: 'api' | 'slack')} + <AgentUsePanel + agentPath={path} + workspace={ws} + isAdmin={!!($userStore?.is_admin || $userStore?.is_super_admin)} + chat={chatAvailable} + slackLoading={slack.loading && !slack.current} + slackTeamName={slack.current?.slack_team_name} + botName={slack.current?.bot_name} + missingScopes={slack.current?.missing_scopes ?? []} + signingSecretSet={slack.current?.signing_secret_set ?? true} + runsAs={slack.current?.runs_as} + anyone={slack.current?.anyone ?? false} + canShare={slack.current?.can_share ?? false} + channels={slack.current?.channels ?? []} + {section} + /> +{/snippet} + {#if ws} <AgentEvalsModal bind:this={evalsModal} agentPath={path} workspace={ws} /> {/if} diff --git a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte index 57e387ad20..d32c279802 100644 --- a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte @@ -17,6 +17,7 @@ import { importStore } from '$lib/components/apps/store' import { onDestroy, untrack } from 'svelte' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { UserDraft } from '$lib/userDraft.svelte' import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import { OtherUserDraftLoad } from '$lib/components/otherUserDraftLoad.svelte' @@ -206,6 +207,15 @@ getDraft }) if (tok !== loadAppToken) return + // A draft-only app has no page for Home's card to open. + if (!backendApp.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'app', + path: backendApp.path, + summary: backendApp.summary, + via: 'edit' + }) + } // Deployed App value for AppEditor's autosave `discardIf`, captured BEFORE // the draft swap below replaces `backendApp.value`. `undefined` when // there's no deployed row (draft-only path). diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts b/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts index 8bd1ba1ba3..14bb56c86f 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts +++ b/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts @@ -2,7 +2,7 @@ import { redirect } from '@sveltejs/kit' import { get } from 'svelte/store' import { makeDraftAddLoad } from '$lib/draftAddRedirect' import { mintDraftPath } from '$lib/mintDraftPath' -import { userStore, workspaceStore } from '$lib/stores' +import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' import { copilotInfo, copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' import { prefersSessionHandoff } from '$lib/components/copilot/chat/global/gate' @@ -26,7 +26,7 @@ async function newAppSessionHref(url: URL): Promise<string | undefined> { const user = get(userStore) const workspace = get(workspaceStore) // Neither is known yet on a cold load of this URL, which then opens the editor. - if (!user || !workspace || !prefersSessionHandoff(user.operator)) return undefined + if (!user || !workspace || !prefersSessionHandoff(!get(roleCapabilities).code)) return undefined if ((url.searchParams.get('workspace') ?? workspace) !== workspace) return undefined if (get(copilotWorkspace) !== workspace) await loadCopilot(workspace) if (get(copilotWorkspace) !== workspace || !get(copilotInfo).enabled) return undefined diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte index 8956f42441..aa51d62ea8 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte @@ -4,7 +4,7 @@ import { AppService } from '$lib/gen' import { userStore, workspaceStore } from '$lib/stores' - import { useOperatorBuilderApps, workspaceListLoaded } from '$lib/operatorWriteRights' + import { useRoleCapabilities, workspaceListLoaded } from '$lib/operatorWriteRights' import { readFieldsRecursively } from '$lib/utils' import { goto } from '$lib/navigation' import { sendUserToast } from '$lib/toast' @@ -15,6 +15,7 @@ import { openEditorInSession } from '$lib/components/sessions/sessionSwitch.svelte' import { stateSnapshot } from '$lib/svelte5Utils.svelte' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { type RawAppData, DEFAULT_DATA, @@ -102,7 +103,8 @@ // edits to the just-deployed app autosaved to a dead key (autosave appeared // broken). See /scripts/edit, which derives its draft path the same way. // effectivePath omitted: the live-editor-draft entry is owned by RawAppEditor. - const operatorBuilderApps = useOperatorBuilderApps() + const roleCaps = useRoleCapabilities() + const composeOnlyApps = $derived($roleCaps.apps === 'compose') const draftSync = usePageDraftSync<RawAppDraft>({ itemKind: 'raw_app', @@ -281,7 +283,7 @@ // Seed the React 19 template so the editor has a usable state even if the // user dismisses the picker without selecting. const seedFiles = { - ...($operatorBuilderApps ? BUILDER_FRAMEWORK_TEMPLATES.react19 : react19Template) + ...(composeOnlyApps ? BUILDER_FRAMEWORK_TEMPLATES.react19 : react19Template) } const seedRunnables = starterRunnables() savedApp = { @@ -311,6 +313,15 @@ rawApp: true })) as any if (tok !== loadAppToken) return + // A draft-only app has no page for Home's card to open. + if (!backendApp.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'raw_app', + path: backendApp.path, + summary: backendApp.summary, + via: 'edit' + }) + } // `other_drafts_users` only computed when `getDraft`; don't clobber the // known list on a `getDraft:false` reload. See /scripts/edit's loader. if (getDraft) { @@ -532,10 +543,10 @@ let rawAppEditor: RawAppEditor | undefined = $state() - // The starter runnables are inline scripts, which the backend refuses from an operator with - // builder rights: seeding them would make their very first deploy fail. + // The starter runnables are inline scripts, which the backend refuses from a role that only + // composes apps: seeding them would make their very first deploy fail. function starterRunnables() { - return $operatorBuilderApps ? {} : structuredClone(STARTER_RUNNABLES) + return composeOnlyApps ? {} : structuredClone(STARTER_RUNNABLES) } async function onTemplatePickerStart(result: RawAppTemplatePickerResult, mode: RawAppBuildMode) { @@ -547,7 +558,7 @@ policy: result.policy } const workspace = $workspaceStore - if (mode === 'ai' && prefersSessionHandoff($userStore?.operator) && workspace) { + if (mode === 'ai' && prefersSessionHandoff(!$roleCaps.code) && workspace) { // The session loads the app by path, so the picked setup is saved before it // opens. `new_draft` tells it the app is still the starter template. try { @@ -646,6 +657,7 @@ <RawAppEditor bind:this={rawAppEditor} ownsPageHeader + compact={page.url.searchParams.get('view') === 'preview'} onDetails={(e) => goto(`/apps_raw/get/${e.path}?workspace=${$workspaceStore}`)} onSavedNewAppPath={(savedPath) => { draftSync.remove() diff --git a/frontend/src/routes/(root)/(logged)/assets/+page.svelte b/frontend/src/routes/(root)/(logged)/assets/+page.svelte index b2f2f1b896..fec8bda036 100644 --- a/frontend/src/routes/(root)/(logged)/assets/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/assets/+page.svelte @@ -16,7 +16,7 @@ import { userStore, workspaceStore, - userWorkspaces, + roleCapabilities, globalDbManagerDrawer, superadmin } from '$lib/stores' @@ -120,7 +120,11 @@ // A `dbt://` asset's rows, previewed through the dbt project that writes it. // The producer is the asset's own WRITE usage — a table nobody writes has no // project to ask, and no `ref()` to resolve the relation with. - type AssetRow = { path: string; kind: string; usages: { path: string; kind: string; access_type?: string }[] } + type AssetRow = { + path: string + kind: string + usages: { path: string; kind: string; access_type?: string }[] + } function dbtProducerOf(asset: AssetRow): string | undefined { if (asset.kind !== 'dbt') return undefined // A DEFINITE writer. A bare `dbt://…` literal in a native script is stored @@ -168,7 +172,9 @@ ) } if (producer.language !== 'dbt') { - return fail(`${script} writes this table but is not a dbt script, so there is no model to preview.`) + return fail( + `${script} writes this table but is not a dbt script, so there is no model to preview.` + ) } // A project whose descriptor interpolates `{{ }}` needs those values to // run at all, and this page has nowhere to ask for them. Say so instead @@ -223,7 +229,6 @@ } } - let allS3Storages = resource( () => $workspaceStore, () => @@ -263,10 +268,10 @@ } </script> -{#if $userStore?.operator && $workspaceStore && !$userWorkspaces.find((_) => _.id === $workspaceStore)?.operator_settings?.assets} +{#if $workspaceStore && !$roleCapabilities.visibility.assets} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage id="scrollable-container"> @@ -303,7 +308,7 @@ > See documentation </Button> - {#if !($userStore?.operator || (!$userStore?.is_admin && !$superadmin))} + {#if $roleCapabilities.code && ($userStore?.is_admin || $superadmin)} <Button wrapperClasses="h-fit" variant={props.data.current?.length === 0 && !props.data.loading @@ -496,10 +501,10 @@ </a> </Cell> <Cell class="w-24"> - {#if assetCanBeExplored(asset, asset.metadata) && !$userStore?.operator} + {#if assetCanBeExplored(asset, asset.metadata) && $roleCapabilities.code} <ExploreAssetButton {asset} {s3FilePicker} _resourceMetadata={asset.metadata} /> {/if} - {#if dbtProducerOf(asset) && !$userStore?.operator} + {#if dbtProducerOf(asset) && $roleCapabilities.code} <Button size="xs2" color="light" diff --git a/frontend/src/routes/(root)/(logged)/audit_logs/+page.svelte b/frontend/src/routes/(root)/(logged)/audit_logs/+page.svelte index 42d8ff996e..cbd615e62a 100644 --- a/frontend/src/routes/(root)/(logged)/audit_logs/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/audit_logs/+page.svelte @@ -15,7 +15,7 @@ import type { AuditLog } from '$lib/gen' import { AuditService } from '$lib/gen' - import { enterpriseLicense, userStore, workspaceStore, userWorkspaces } from '$lib/stores' + import { enterpriseLicense, workspaceStore, roleCapabilities } from '$lib/stores' import { Splitpanes, Pane } from 'svelte-splitpanes' import AuditLogsTimeline from '$lib/components/auditLogs/AuditLogsTimeline.svelte' import { useAuditLogsLoader } from '$lib/components/auditLogs/useAuditLogsLoader.svelte' @@ -128,10 +128,10 @@ } </script> -{#if $userStore?.operator && $workspaceStore && !$userWorkspaces.find((_) => _.id === $workspaceStore)?.operator_settings?.audit_logs} +{#if $workspaceStore && !$roleCapabilities.visibility.audit_logs} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <!-- `h-full`, not `h-screen`: the band sits above this box, so a viewport floor would overhang diff --git a/frontend/src/routes/(root)/(logged)/dev/composer-suggestions/+page.svelte b/frontend/src/routes/(root)/(logged)/dev/composer-suggestions/+page.svelte new file mode 100644 index 0000000000..7053fa8d3f --- /dev/null +++ b/frontend/src/routes/(root)/(logged)/dev/composer-suggestions/+page.svelte @@ -0,0 +1,364 @@ +<script lang="ts"> + // DEV-ONLY playground for the composer's suggestion rules: pick a role, edit the signals by + // hand or load a workspace's real ones, and see the pills the starter would show. Not + // linked anywhere; open at /dev/composer-suggestions. Only reachable on dev builds. + import { Badge, Button } from '$lib/components/common' + import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' + import TextInput from '$lib/components/text_input/TextInput.svelte' + import Select from '$lib/components/select/Select.svelte' + import ComposerSuggestions from '$lib/components/copilot/chat/starter/ComposerSuggestions.svelte' + import { + CHANNEL_TYPES, + composerSuggestions, + DATABASE_TYPES, + type ComposerRole, + type ComposerSignals + } from '$lib/components/copilot/chat/starter/composerSuggestions' + import { readComposerSignals } from '$lib/components/copilot/chat/starter/starterPrompts.svelte' + import { userWorkspaces, workspaceStore } from '$lib/stores' + import { Download } from 'lucide-svelte' + + type RoleName = + | 'operator' + | 'developer' + | 'workspaceAdmin' + | 'instanceAdmin' + | 'instanceAdminMember' + const ROLES: Record<RoleName, ComposerRole> = { + operator: { operator: true, workspaceAdmin: false, instanceAdmin: false }, + developer: { operator: false, workspaceAdmin: false, instanceAdmin: false }, + workspaceAdmin: { operator: false, workspaceAdmin: true, instanceAdmin: false }, + // Not a member: `whoami` makes them the workspace's admin. + instanceAdmin: { operator: false, workspaceAdmin: true, instanceAdmin: true }, + // A member keeps the role of their member row. + instanceAdminMember: { operator: false, workspaceAdmin: false, instanceAdmin: true } + } + + // Every field as the form holds it: a blank field is an absent signal, which fires no rule. + // "none" is a list that answered and holds none, which fires the pills that teach it. + type Form = { + itemCount: string + draftPath: string + sharedFlowPath: string + scriptPath: string + appPath: string + agentPath: string + folderItemPath: string + favoritePath: string + dataTables: string + databasePath: string + databaseType: string + channelPath: string + channelType: string + } + const BLANK: Form = { + itemCount: '', + draftPath: '', + sharedFlowPath: '', + scriptPath: '', + appPath: '', + agentPath: '', + folderItemPath: '', + favoritePath: '', + dataTables: '', + databasePath: '', + databaseType: 'postgresql', + channelPath: '', + channelType: 'slack' + } + const PRESETS: Record<string, Partial<Form>> = { + 'Empty workspace': { itemCount: '0' }, + 'Fresh workspace': { + itemCount: '0', + dataTables: 'none', + channelType: 'none' + }, + 'Empty, connected': { + itemCount: '0', + dataTables: 'main', + databasePath: 'f/data/main_db', + channelPath: 'f/team/slack' + }, + 'Has items': { itemCount: '25' }, + 'Own work': { + itemCount: '25', + draftPath: 'f/billing/sync_invoices' + }, + Established: { + itemCount: '25', + sharedFlowPath: 'f/billing/charge_customers', + scriptPath: 'f/ops/check_ssl_expiry', + appPath: 'f/ops/console', + folderItemPath: 'f/billing/charge_customers', + favoritePath: 'f/ops/check_ssl_expiry', + dataTables: 'main', + databasePath: 'f/data/main_db', + channelPath: 'f/team/slack' + } + } + type PathKey = + | 'draftPath' + | 'sharedFlowPath' + | 'scriptPath' + | 'appPath' + | 'agentPath' + | 'folderItemPath' + | 'favoritePath' + | 'dataTables' + const PATH_FIELDS: { key: PathKey; label: string; placeholder?: string }[] = [ + { key: 'draftPath', label: 'My latest draft (flow path)' }, + { key: 'sharedFlowPath', label: 'Newest shared flow (path)' }, + { key: 'scriptPath', label: 'Newest script (path)' }, + { key: 'appPath', label: 'Newest full-code app (path)' }, + { key: 'agentPath', label: 'Newest AI agent (path)' }, + { key: 'folderItemPath', label: 'Newest item in a folder (path)' }, + { key: 'favoritePath', label: 'Favorite (script path)' }, + { key: 'dataTables', label: 'Data tables (names, or none)', placeholder: 'unknown' } + ] + const NONE = { value: 'none', label: 'None connected' } + const DATABASE_ITEMS = Object.entries(DATABASE_TYPES).map(([value, label]) => ({ value, label })) + const CHANNEL_ITEMS = [ + NONE, + ...Object.entries(CHANNEL_TYPES).map(([value, { name }]) => ({ value, label: name })) + ] + + let roleName = $state<RoleName>('instanceAdmin') + let form = $state<Form>({ ...BLANK, ...PRESETS['Has items'] }) + let workspace = $state<string | undefined>($workspaceStore ?? undefined) + let loading = $state(false) + let picked = $state<string>() + /** The kinds a loaded workspace reported, which the form's path fields do not hold. */ + let loadedKinds = $state<{ draft?: string; folderItem?: string; favorite?: string }>({}) + + const num = (s: string) => (s.trim() === '' || isNaN(Number(s)) ? undefined : Number(s)) + + const item = (kind: string, path: string) => + path.trim() ? { kind, path: path.trim(), name: path.trim().split('/').pop()! } : undefined + const connection = (type: string, path: string) => { + const i = item(type, path) + return i && { type: i.kind, path: i.path, name: i.name } + } + const names = (text: string) => { + const t = text.trim() + if (t === '') return undefined + if (t === 'none') return [] + return t + .split(',') + .map((n) => n.trim()) + .filter(Boolean) + } + + const signals: ComposerSignals = $derived({ + itemCount: num(form.itemCount), + myDraft: item(loadedKinds.draft ?? 'flow', form.draftPath), + sharedFlow: item('flow', form.sharedFlowPath), + script: item('script', form.scriptPath), + app: item('app', form.appPath), + agent: item('agent', form.agentPath), + folderItem: item(loadedKinds.folderItem ?? 'flow', form.folderItemPath), + favorite: item(loadedKinds.favorite ?? 'script', form.favoritePath), + database: connection(form.databaseType, form.databasePath), + channel: form.channelType === 'none' ? null : connection(form.channelType, form.channelPath), + dataTables: names(form.dataTables) + }) + const suggestions = $derived(composerSuggestions(signals, ROLES[roleName])) + + function applyPreset(name: string) { + form = { ...BLANK, ...PRESETS[name] } + loadedKinds = {} + picked = undefined + } + + async function loadWorkspace() { + const requested = workspace + if (!requested) return + loading = true + // A failed list reads as 10 items with nothing of yours; the console says why. + const s = await readComposerSignals(requested) + loading = false + // The selection changed while this was loading: these signals describe another workspace. + if (workspace !== requested) return + loadedKinds = { + draft: s.myDraft?.kind, + folderItem: s.folderItem?.kind, + favorite: s.favorite?.kind + } + form = { + itemCount: String(s.itemCount ?? ''), + draftPath: s.myDraft?.path ?? '', + sharedFlowPath: s.sharedFlow?.path ?? '', + scriptPath: s.script?.path ?? '', + appPath: s.app?.path ?? '', + agentPath: s.agent?.path ?? '', + folderItemPath: s.folderItem?.path ?? '', + favoritePath: s.favorite?.path ?? '', + dataTables: s.dataTables === undefined ? '' : s.dataTables.join(', ') || 'none', + databasePath: s.database?.path ?? '', + databaseType: s.database?.type ?? BLANK.databaseType, + channelPath: s.channel?.path ?? '', + channelType: s.channel === null ? 'none' : (s.channel?.type ?? BLANK.channelType) + } + picked = undefined + } +</script> + +{#if import.meta.env.DEV} + <div class="max-w-6xl mx-auto px-6 py-8 flex flex-col gap-8"> + <div class="flex flex-col gap-1"> + <h1 class="text-lg font-semibold text-emphasis">Composer suggestions</h1> + <p class="text-xs text-secondary"> + The pills <code>composerSuggestions(signals, role)</code> returns. A blank path means no such + item. Invitation prompts, which replace all of these, are not simulated. + </p> + </div> + + <div class="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-8"> + <div class="flex flex-col gap-6"> + <section class="flex flex-col gap-2"> + <h2 class="text-xs font-semibold text-emphasis">Role</h2> + <ToggleButtonGroup bind:selected={roleName} wrap> + {#snippet children({ item })} + <ToggleButton value="operator" label="Operator" {item} /> + <ToggleButton value="developer" label="Developer" {item} /> + <ToggleButton value="workspaceAdmin" label="Workspace admin" {item} /> + <ToggleButton value="instanceAdmin" label="Instance admin" {item} /> + <ToggleButton + value="instanceAdminMember" + label="Instance admin, developer member" + {item} + /> + {/snippet} + </ToggleButtonGroup> + <p class="text-2xs text-hint">An instance admin here is also a workspace admin.</p> + </section> + + <section class="flex flex-col gap-2"> + <h2 class="text-xs font-semibold text-emphasis">Load a real workspace</h2> + <div class="flex flex-row gap-2 items-center"> + <Select + class="grow" + items={$userWorkspaces.map((w) => ({ label: `${w.name} (${w.id})`, value: w.id }))} + bind:value={workspace} + placeholder="Workspace" + /> + <Button + variant="default" + unifiedSize="md" + startIcon={{ icon: Download }} + disabled={!workspace} + {loading} + onClick={loadWorkspace} + > + Load signals + </Button> + </div> + <p class="text-2xs text-hint"> + Fills the form with what the starter would read there. Answers are reused for 30 s. + </p> + </section> + + <section class="flex flex-col gap-2"> + <h2 class="text-xs font-semibold text-emphasis">Presets</h2> + <div class="flex flex-row flex-wrap gap-2"> + {#each Object.keys(PRESETS) as name (name)} + <Button variant="subtle" unifiedSize="sm" onClick={() => applyPreset(name)}> + {name} + </Button> + {/each} + <Button variant="subtle" unifiedSize="sm" onClick={() => applyPreset('')}>Clear</Button> + </div> + </section> + + <section class="flex flex-col gap-3"> + <h2 class="text-xs font-semibold text-emphasis">Signals</h2> + <label class="flex flex-col gap-1"> + <span class="text-xs text-primary">Items</span> + <TextInput + bind:value={() => form.itemCount, (v) => (form.itemCount = String(v ?? ''))} + size="sm" + inputProps={{ type: 'number', min: 0, placeholder: 'absent' }} + /> + <span class="text-2xs text-hint">0 is empty, under 10 is new; the list reads 25</span> + </label> + {#each PATH_FIELDS as field (field.key)} + <label class="flex flex-col gap-1"> + <span class="text-xs text-primary">{field.label}</span> + <TextInput + bind:value={() => form[field.key], (v) => (form[field.key] = String(v ?? ''))} + size="sm" + inputProps={{ placeholder: field.placeholder ?? 'none' }} + /> + </label> + {/each} + <div class="flex flex-col gap-1"> + <span class="text-xs text-primary">Database (type and path)</span> + <div class="flex flex-row gap-2"> + <Select class="w-40" items={DATABASE_ITEMS} bind:value={form.databaseType} /> + <TextInput + class="grow" + bind:value={form.databasePath} + size="sm" + inputProps={{ placeholder: 'none' }} + /> + </div> + </div> + <div class="flex flex-col gap-1"> + <span class="text-xs text-primary">Channel (type and path)</span> + <div class="flex flex-row gap-2"> + <Select class="w-40" items={CHANNEL_ITEMS} bind:value={form.channelType} /> + <TextInput + class="grow" + bind:value={form.channelPath} + size="sm" + inputProps={{ placeholder: 'none' }} + /> + </div> + </div> + </section> + </div> + + <div class="flex flex-col gap-6"> + <section class="flex flex-col gap-2"> + <h2 class="text-xs font-semibold text-emphasis">Pills</h2> + <div class="rounded-md border border-border-light bg-surface p-3 min-h-12"> + {#if suggestions.length} + <ComposerSuggestions {suggestions} onPick={(p) => (picked = p)} /> + {:else} + <p class="text-xs text-hint">No pills.</p> + {/if} + </div> + {#if picked} + <div class="flex flex-col gap-1"> + <span class="text-2xs text-hint">Clicking that pill puts this in the box:</span> + <p class="text-xs text-primary whitespace-pre-wrap">{picked}</p> + </div> + {/if} + </section> + + <section class="flex flex-col gap-2"> + <h2 class="text-xs font-semibold text-emphasis">In order</h2> + <ol class="flex flex-col gap-3"> + {#each suggestions as s, i (s.label)} + <li class="flex flex-col gap-1"> + <div class="flex flex-row gap-2 items-center"> + <span class="text-2xs text-hint w-3">{i + 1}</span> + <Badge color={s.mode === 'use' ? 'blue' : 'green'}>{s.mode}</Badge> + <span class="text-xs font-medium text-emphasis">{s.label}</span> + </div> + <p class="text-2xs text-secondary pl-5">{s.prompt}</p> + </li> + {/each} + </ol> + </section> + + <section class="flex flex-col gap-2"> + <h2 class="text-xs font-semibold text-emphasis">Signals passed</h2> + <pre class="text-2xs text-secondary bg-surface-secondary rounded-md p-3 overflow-x-auto" + >{JSON.stringify(signals, null, 2)}</pre + > + </section> + </div> + </div> + </div> +{/if} diff --git a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte index d724c4873d..8f2ae0b65c 100644 --- a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte @@ -21,6 +21,7 @@ import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import type { stepState } from '$lib/components/stepHistoryLoader.svelte' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { UserDraft, draftValuesEqual } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import UnsavedConfirmationModal from '$lib/components/common/confirmationModal/UnsavedConfirmationModal.svelte' @@ -338,7 +339,6 @@ v = undefined } if (tok !== loadFlowToken) return - version = v const backendFlow = await FlowService.getFlowByPath({ workspace: $workspaceStore!, @@ -346,6 +346,15 @@ getDraft }) if (tok !== loadFlowToken) return + // A draft-only flow has no page for Home's card to open. + if (!backendFlow.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'flow', + path: backendFlow.path, + summary: backendFlow.summary, + via: 'edit' + }) + } // `other_drafts_users` only computed when `getDraft`; don't clobber the // known list on a `getDraft:false` reload. See /scripts/edit's loader. if (getDraft) { @@ -366,6 +375,9 @@ // Layer the draft (`.draft`, if any) over the deployed payload at the field // level. See /scripts/edit's loader for the rationale. const { draft: draftFromBackend, ...deployedFlow } = backendFlow as any + // Set together with the base below: across the await above, a new head beside + // the previous load's base reads as stale, and the stale prompt latches open. + version = v // The flow_version the draft forked from; undefined when editing the deployed // flow directly (no draft) or for a draft never forked from a deploy. draftBaseVersion = backendFlow.draft_base @@ -385,13 +397,16 @@ deployedBaseline = backendFlow.no_deployed ? undefined : (structuredClone($state.snapshot(deployedFlow)) as Flow) - // Surface the saved `draft_path` to the Path widget so the topbar shows the - // pending name, not the `draft_{uuid}` URL. Else the widget seeds from the - // URL, the first edit clobbers `draft_path`, and the friendly name is lost. - // Otherwise the URL, set on every load: this route instance is reused when the - // editor follows its draft to a moved item, and the path it opened on is where - // deploy would look for the flow. - const renderedDraftPath = (effectiveFlow as any).draft_path as string | undefined + // A draft-only flow surfaces its saved `draft_path` to the Path widget so the + // topbar shows the pending name, not the `draft_{uuid}` URL. Else the widget + // seeds from the URL, the first edit clobbers `draft_path`, and the friendly + // name is lost. A deployed flow keeps the URL even with a staged move: it is + // where deploy updates the flow and where its triggers live (FlowBuilder shows + // the staged path). Set on every load: this route instance is reused when the + // editor follows its draft to a moved item. + const renderedDraftPath = backendFlow.no_deployed + ? ((effectiveFlow as any).draft_path as string | undefined) + : undefined flowInitialPath = renderedDraftPath || (page.params.path ?? '') // "Load another user's draft" handoff: render their value over the deployed diff --git a/frontend/src/routes/(root)/(logged)/folders/+page.svelte b/frontend/src/routes/(root)/(logged)/folders/+page.svelte index b184e4aa4a..ab458f90de 100644 --- a/frontend/src/routes/(root)/(logged)/folders/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/folders/+page.svelte @@ -6,7 +6,7 @@ import Dropdown from '$lib/components/DropdownV2.svelte' import FolderEditorDrawer from '$lib/components/FolderEditorDrawer.svelte' import PageHeader from '$lib/components/PageHeader.svelte' - import { userStore, workspaceStore, userWorkspaces } from '$lib/stores' + import { userStore, workspaceStore, roleCapabilities } from '$lib/stores' import { Button, Drawer, DrawerContent, EmptyState, Skeleton } from '$lib/components/common' import FolderInfo from '$lib/components/FolderInfo.svelte' import FolderUsageInfo from '$lib/components/FolderUsageInfo.svelte' @@ -98,10 +98,10 @@ </DrawerContent> </Drawer> -{#if $userStore?.operator && $workspaceStore && !$userWorkspaces.find((_) => _.id === $workspaceStore)?.operator_settings?.folders} +{#if $workspaceStore && !$roleCapabilities.visibility.folders} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage> diff --git a/frontend/src/routes/(root)/(logged)/groups/+page.svelte b/frontend/src/routes/(root)/(logged)/groups/+page.svelte index c17c6c188e..9d7a70ca7e 100644 --- a/frontend/src/routes/(root)/(logged)/groups/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/groups/+page.svelte @@ -11,7 +11,7 @@ import GroupInfo from '$lib/components/GroupInfo.svelte' import PageHeader from '$lib/components/PageHeader.svelte' import SharedBadge from '$lib/components/SharedBadge.svelte' - import { userStore, workspaceStore, userWorkspaces } from '$lib/stores' + import { userStore, workspaceStore, roleCapabilities } from '$lib/stores' import { useEditRights } from '$lib/operatorWriteRights' import { Pen, Plus, Trash } from 'lucide-svelte' import DataTable from '$lib/components/table/DataTable.svelte' @@ -70,10 +70,10 @@ </DrawerContent> </Drawer> -{#if $userStore?.operator && $workspaceStore && !$userWorkspaces.find((_) => _.id === $workspaceStore)?.operator_settings?.groups} +{#if $workspaceStore && !$roleCapabilities.visibility.groups} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage> diff --git a/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte b/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte index 004799baed..769cc2d5fb 100644 --- a/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte @@ -16,7 +16,7 @@ getLocalSetting, storeLocalSetting } from '$lib/utils' - import { userStore, workspaceStore, userWorkspaces, usedTriggerKinds } from '$lib/stores' + import { userStore, workspaceStore, roleCapabilities, usedTriggerKinds } from '$lib/stores' import CenteredPage from '$lib/components/CenteredPage.svelte' import PageHeader from '$lib/components/PageHeader.svelte' import { Button, Alert, EmptyState, Skeleton } from '$lib/components/common' @@ -110,7 +110,7 @@ serviceAvailable = await isServiceAvailable(serviceName, $workspaceStore) if (!serviceAvailable) { sendUserToast( - `${serviceName} integration not available, set it in the workspace settings`, + `${serviceConfig.serviceDisplayName} isn't configured in this workspace`, true ) } @@ -145,7 +145,10 @@ } if (!serviceAvailable) { - sendUserToast('Cannot sync triggers: workspace integration not connected', true) + sendUserToast( + `Cannot sync: ${serviceConfig.serviceDisplayName} isn't configured in this workspace`, + true + ) return } @@ -159,17 +162,7 @@ loadTriggers() } catch (err: any) { const errorMessage = err.body || err.message - if ( - errorMessage.includes('workspace integration') || - errorMessage.includes('not connected') - ) { - sendUserToast( - `Cannot sync: ${serviceConfig.serviceDisplayName} workspace integration not connected. Please connect it in workspace settings.`, - true - ) - } else { - sendUserToast(`Failed to sync triggers: ${errorMessage}`, true) - } + sendUserToast(`Failed to sync triggers: ${errorMessage}`, true) } } @@ -197,10 +190,10 @@ f={(trigger) => `${formatTriggerDisplayName(trigger)}`} /> -{#if $userStore?.operator && $workspaceStore && !$userWorkspaces.find((_) => _.id === $workspaceStore)?.operator_settings?.triggers} +{#if $workspaceStore && !$roleCapabilities.visibility.triggers} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else if !serviceSupported} <CenteredPage> @@ -237,8 +230,7 @@ type="warning" > <div class="flex flex-col gap-2 mt-2"> - The workspace doesn't have a {serviceConfig?.serviceDisplayName || serviceName} integration - connected + {serviceConfig?.serviceDisplayName || serviceName} isn't configured in this workspace yet. <div class="flex gap-2"> <Button variant="accent" href="/workspace_settings?tab=native_triggers"> Manage native triggers diff --git a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte index 830e545719..3daaeba05c 100644 --- a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte +++ b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte @@ -6,10 +6,11 @@ import { page } from '$app/state' import CenteredModal from '$lib/components/CenteredModal.svelte' import { Button } from '$lib/components/common' - import Select from '$lib/components/select/Select.svelte' + import MultiSelect from '$lib/components/select/MultiSelect.svelte' + import Toggle from '$lib/components/Toggle.svelte' + import McpAccessPicker, { type McpAccess } from '$lib/components/mcp/McpAccessPicker.svelte' import { WorkspaceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' - import McpScopeSelector from '$lib/components/mcp/McpScopeSelector.svelte' import Check from 'lucide-svelte/icons/check' // Get OAuth params from URL @@ -18,7 +19,19 @@ let clientId = page.url.searchParams.get('client_id') || '' let clientName = page.url.searchParams.get('client_name') || 'Unknown Client' let redirectUri = page.url.searchParams.get('redirect_uri') || '' - let scope = $state(page.url.searchParams.get('scope') || 'mcp:all') + // What the client asked for seeds the access picker; what is approved is the picker's. + const askedScopes = (page.url.searchParams.get('scope') || 'mcp:all') + .split(' ') + .filter((s) => s.startsWith('mcp:')) + // Both narrowings at once is a client requesting every scope it was offered, not a choice. + const requestedScopes = + askedScopes.includes('mcp:all') && + askedScopes.includes('mcp:read_only') && + askedScopes.includes('mcp:read_run') + ? askedScopes.filter((s) => s !== 'mcp:read_only' && s !== 'mcp:read_run') + : askedScopes + let scopes = $state<string[]>([]) + let access = $state<McpAccess>() let oauthState = page.url.searchParams.get('state') || '' let codeChallenge = page.url.searchParams.get('code_challenge') || '' let codeChallengeMethod = page.url.searchParams.get('code_challenge_method') || '' @@ -41,9 +54,21 @@ let success = $state(false) let successRedirectUrl = $state('') - // Gateway mode: fetch user's workspaces for the picker + // Gateway mode: fetch user's workspaces for the picker. One picked workspace binds the + // token to it; several, or all of them, leave it unbound and its tools name their workspace. let workspaces: Array<{ value: string; label: string }> = $state([]) + let pickedWorkspaces = $state<string[]>([]) + let allWorkspaces = $state(false) let loadingWorkspaces = $state(false) + const grantsWorkspace = $derived(!isGateway || allWorkspaces || pickedWorkspaces.length > 0) + // Selected scripts and flows are listed per workspace: across several, a path could be two. + const selectionNeedsOneWorkspace = $derived( + isGateway && access === 'selected' && (allWorkspaces || pickedWorkspaces.length !== 1) + ) + // The workspace the scope picker browses scripts and flows in. + const scopeWorkspaceId = $derived( + isGateway ? (pickedWorkspaces[0] ?? (allWorkspaces ? workspaces[0]?.value : '')) : workspaceId + ) if (isGateway) { loadingWorkspaces = true @@ -57,10 +82,12 @@ })) // Auto-select if only one workspace if (workspaces.length === 1) { - workspaceId = workspaces[0].value + pickedWorkspaces = [workspaces[0].value] } }) - .catch(() => { + .catch((e) => { + // Logged out: the root layout is already sending the browser to the login page. + if (e?.status === 401) return sendUserToast('Failed to load workspaces', true) }) .finally(() => { @@ -83,7 +110,7 @@ async function onApprove() { if (!redirectUriValid) return - if (!workspaceId) { + if (!grantsWorkspace) { sendUserToast('Please select a workspace', true) return } @@ -95,18 +122,19 @@ ? `/api/mcp/gateway/oauth/server/approve` : `/api/w/${workspaceId}/mcp/oauth/server/approve` - const body: Record<string, string> = { + const body: Record<string, unknown> = { client_id: clientId, redirect_uri: redirectUri, - scope: scope, + scope: scopes.join(' '), state: oauthState, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod } - // Gateway mode sends workspace_id in the body + // Gateway mode sends the workspaces in the body if (isGateway) { - body.workspace_id = workspaceId + body.workspace_ids = allWorkspaces ? [] : pickedWorkspaces + body.all_workspaces = allWorkspaces } const response = await fetch(approveUrl, { @@ -170,8 +198,8 @@ <p class="text-center text-sm text-primary mb-6"> <span class="font-semibold text-accent">{clientName}</span> is requesting access to - {#if isGateway && !workspaceId} - your Windmill workspace. + {#if isGateway} + your Windmill workspaces. {:else} your <span class="font-semibold text-accent">{workspaceId}</span> @@ -180,30 +208,53 @@ </p> {#if isGateway} - <div class="mb-6"> - <p class="text-xs font-semibold text-emphasis mb-2">Select a workspace:</p> + <div class="mb-6 flex flex-col gap-2"> + <p class="text-xs font-semibold text-emphasis">Workspaces it may work in:</p> {#if loadingWorkspaces} <p class="text-xs text-secondary">Loading workspaces...</p> {:else if workspaces.length === 0} <p class="text-xs text-secondary">No workspaces available.</p> {:else} - <Select items={workspaces} bind:value={workspaceId} placeholder="Choose a workspace" /> + <Toggle + bind:checked={allWorkspaces} + options={{ right: 'All my workspaces, including ones I join later' }} + size="xs" + /> + {#if !allWorkspaces} + <MultiSelect + items={workspaces} + bind:value={pickedWorkspaces} + placeholder="Choose workspaces" + reorderable={false} + /> + {/if} {/if} </div> {/if} - {#if workspaceId} - <div class="mb-6"> - <McpScopeSelector {workspaceId} bind:scope /> - </div> - {/if} + <div class="mb-6 flex flex-col gap-1"> + <McpAccessPicker + workspaceId={scopeWorkspaceId ?? ''} + initialScopes={requestedScopes} + bind:scopes + bind:access + /> + {#if selectionNeedsOneWorkspace} + <p class="text-2xs text-secondary"> + Selected scripts and flows come from one workspace: pick one. + </p> + {/if} + </div> <div class="flex flex-row justify-around gap-x-4"> <Button variant="border" size="lg" disabled={loading} onClick={onDeny}>Deny</Button> <Button variant="accent" size="lg" - disabled={loading || (isGateway && !workspaceId)} + disabled={loading || + !grantsWorkspace || + selectionNeedsOneWorkspace || + scopes.length === 0} {loading} onClick={onApprove}>Approve</Button > diff --git a/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte b/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte index d7972d3ef1..3caf6bcb84 100644 --- a/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { userStore, workspaceStore } from '$lib/stores' + import { roleCapabilities, workspaceStore } from '$lib/stores' import PipelineFolderList from '$lib/components/assets/AssetGraph/PipelineFolderList.svelte' import PipelineSetupSignpost from '$lib/components/assets/AssetGraph/PipelineSetupSignpost.svelte' import PipelineAlphaAckModal from '$lib/components/assets/AssetGraph/PipelineAlphaAckModal.svelte' @@ -64,12 +64,12 @@ </a> </div> - {#if !$userStore?.operator && $workspaceStore} + {#if $roleCapabilities.code && $workspaceStore} <PipelineSetupSignpost workspace={$workspaceStore} /> {/if} - <!-- Operators cannot pick an arbitrary folder, so the list is their only way in. --> - <PipelineFolderList hideExisting={!$userStore?.operator} /> + <!-- A role without code cannot pick an arbitrary folder, so the list is its only way in. --> + <PipelineFolderList hideExisting={$roleCapabilities.code} /> </div> </div> </div> diff --git a/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte b/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte index f5833527b0..224409c2b9 100644 --- a/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte @@ -1,8 +1,9 @@ <script lang="ts"> import pLimit from 'p-limit' - import { workspaceStore, userStore } from '$lib/stores' + import { roleCapabilities, workspaceStore, userStore } from '$lib/stores' import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import { page } from '$app/state' import Button from '$lib/components/common/button/Button.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' @@ -202,11 +203,11 @@ // Page mode, URL-addressable via `?mode=`. No param = view (the // default): deployed-only graph focused on past/live executions. - // Operators are clamped to view — the derived ignores a hand-typed - // `?mode=edit` rather than redirecting. - let isOperator = $derived($userStore?.operator ?? false) + // A role without `code` (pipeline steps are scripts) is clamped to view: the + // derived ignores a hand-typed `?mode=edit` rather than redirecting. + let viewOnly = $derived(!$roleCapabilities.code) let urlMode = $derived(page.url.searchParams.get('mode')) - let mode = $derived<PipelineMode>(isOperator ? 'view' : urlMode === 'edit' ? 'edit' : 'view') + let mode = $derived<PipelineMode>(viewOnly ? 'view' : urlMode === 'edit' ? 'edit' : 'view') // The edit-mode pane, set aside while View shows the activity feed, so coming // back to Edit reopens it. let editPane: @@ -512,7 +513,7 @@ ensureEditable: () => { // Auto-enter edit so AI changes are visible/actionable, unless the user // is an operator (no edit permission) — then refuse with a clear error. - if (isOperator) { + if (viewOnly) { throw new Error('This pipeline is read-only for your role; AI edits are disabled.') } if (mode !== 'edit') setMode('edit') @@ -532,7 +533,8 @@ // autosave still inside its debounce has to land first. async function persistDraftsForSession(): Promise<void> { const workspace = $workspaceStore - if (!workspace) return + // A role that cannot code only views the pipeline, so there is no draft of theirs to save. + if (!workspace || viewOnly) return await tick() const draft = { workspace, itemKind: PIPELINE_DRAFT_KIND, path: pipelineDraftPath } await UserDraftDbSyncer.flush(draft) @@ -552,15 +554,11 @@ bypassNavigationGuard = true } - const sessionOpen: OpenInSessionSource | undefined = $derived( - isOperator - ? undefined - : { - target: { kind: 'pipeline', path: folder }, - workspaceId: $workspaceStore ?? undefined, - beforeOpen: persistDraftsForSession - } - ) + const sessionOpen: OpenInSessionSource = $derived({ + target: { kind: 'pipeline', path: folder }, + workspaceId: $workspaceStore ?? undefined, + beforeOpen: persistDraftsForSession + }) // Lets the navigation rail's session switch open this pipeline, with its drafts. setOpenInSessionHandoff({ source: () => sessionOpen }) @@ -1212,7 +1210,7 @@ let nodeFixes = $derived.by(() => { const fixes = new Map<string, NodeFixSpec>() - if (isOperator) return fixes + if (viewOnly) return fixes for (const [path, asset] of nodeErrors.waitsOn) { fixes.set(`script:${path}`, { explainer: [ @@ -1887,9 +1885,45 @@ // overflow (⋮) menu so the bar stays legible on small screens; only primary // actions stay inline. Recording lives here rather than on the bar at all // times — while armed it surfaces a compact inline pill (below) instead. + // The bar folds the actions (`actionFolds` below) once its breadcrumb has given all it can, + // moving them into the ⋮ menu rather than dropping their labels: first the view helpers, then + // the run and the drafts overlay. The mode toggle and Save all stay on the bar. + const viewHelpersInMenu = $derived(pageHeader.actionFold >= 1) + const runInMenu = $derived(pageHeader.actionFold >= 2) + let overflowMenuItems = $derived.by<Item[]>(() => { const items: Item[] = [] - if (!isOperator && allPipelineScripts.length > 0) { + if (runInMenu && !viewOnly && allPipelineScripts.length > 0) { + items.push({ + displayName: cascadeRunningRoot ? 'Running…' : 'Run pipeline', + icon: Play, + disabled: !!cascadeRunningRoot, + action: () => runWholePipeline() + }) + } + if (runInMenu && !viewOnly && mode === 'view' && pendingCount > 0) { + items.push({ + displayName: `${includeDrafts ? 'Hide' : 'Show'} ${pendingCount} draft${pendingCount === 1 ? '' : 's'}`, + icon: Telescope, + action: () => (includeDrafts = !includeDrafts) + }) + } + if (viewHelpersInMenu) { + if (mode === 'view') { + items.push({ + displayName: activityShowing ? 'Hide activity' : 'Activity', + icon: History, + action: () => toggleActivity() + }) + } + items.push({ + displayName: 'Refresh', + icon: RefreshCw, + disabled: graphRes.loading, + action: () => graphRes.refetch() + }) + } + if (!viewOnly && allPipelineScripts.length > 0) { items.push({ displayName: recordingMode ? 'Disarm recorder' : 'Record next run', icon: Circle, @@ -2300,6 +2334,10 @@ .filter((r) => r.usage_kind === 'script' && r.in_pipeline) .map((r) => r.path) ) + // What the bar shows of the page's main actions: the session button goes right before them. + const saveAllShown = $derived(mode === 'edit' && pendingCount > 0) + const runPipelineShown = $derived(!viewOnly && allPipelineScripts.length > 0 && !runInMenu) + // Run the whole pipeline: hand every script to the bounded-cascade engine, // which topo-orders them (roots first) and fans downstream — i.e. run + all // downstream from every source at once. Reuses the same per-hop launch/poll @@ -2709,7 +2747,7 @@ const f = folder if (!g || graphRes.loading || autoEditCheckedFolder === f) return autoEditCheckedFolder = f - if (untrack(() => urlMode) != null || untrack(() => isOperator)) return + if (untrack(() => urlMode) != null || untrack(() => viewOnly)) return if (g.runnables.length === 0 && g.assets.length === 0) { setMode('edit', { replace: true }) } @@ -2816,7 +2854,8 @@ <PageHeaderContent section={{ label: 'Pipelines', content: pipelineCrumb }} actions={pipelineActions} - actionsFlexible + sessionSource={sessionOpen} + actionFolds={2} /> {#snippet pipelineCrumb()} @@ -2866,19 +2905,16 @@ {/snippet} {#snippet pipelineActions()} - <!-- This page carries more actions than any other in the band, so the set scrolls rather than - being pushed off the end. `actionsFlexible` on the registration is what lets this box - shrink far enough for that to matter. --> - <div - class="flex flex-row items-center gap-2 min-w-0 overflow-x-auto scrollbar-hidden whitespace-nowrap" - > - {#if !isOperator} + <!-- This page carries more actions than any other in the band; what does not fit folds into + the ⋮ menu (see `viewHelpersInMenu`). --> + <div class="flex flex-row items-center gap-2 whitespace-nowrap"> + {#if !viewOnly} <!-- Center group: the mode toggle is the page's primary control — anchored between the two flex-1 side groups so it stays centered, with breathing room on both sides. --> <div class="flex flex-row items-center gap-2 shrink-0"> <PipelineModeToggle {mode} draftCount={pendingCount} onModeChange={(m) => setMode(m)} /> - {#if mode === 'view' && pendingCount > 0} + {#if mode === 'view' && pendingCount > 0 && !runInMenu} <!-- View variant: overlay the unsaved drafts onto the deployed graph — "what View will show once they're deployed". --> <Button @@ -2899,7 +2935,7 @@ {/if} </div> {/if} - {#if !isOperator && allPipelineScripts.length > 0} + {#if !viewOnly && allPipelineScripts.length > 0} <!-- Only the armed state surfaces on the bar (arming lives in the ⋮ menu) — a compact disarm pill. --> {#if recordingMode} @@ -2914,33 +2950,39 @@ Recording </button> {/if} - <!-- Pipeline-level run: always visible in both View and Edit so a + <!-- Pipeline-level run: in both View and Edit, on the bar or in the ⋮ menu, so a run never requires hunting for a specific node's play button (dbt `build` / Dagster "Materialize all"). Runs every script in dependency order (roots first, cascading downstream) over the displayed graph — deployed in View, draft-overlaid in Edit. --> - <Button - variant="accent-secondary" - unifiedSize="sm" - startIcon={{ - icon: cascadeRunningRoot ? Loader2 : Play, - classes: cascadeRunningRoot ? 'animate-spin' : undefined - }} - onclick={runWholePipeline} - disabled={!!cascadeRunningRoot} - title={cascadeRunningRoot - ? 'A pipeline run is already in progress' - : `Run all ${allPipelineScripts.length} script${ - allPipelineScripts.length === 1 ? '' : 's' - } in dependency order (roots first, cascading downstream)`} - > - {cascadeRunningRoot ? 'Running…' : 'Run pipeline'} - </Button> + {#if !runInMenu} + {#if !saveAllShown} + {@render sessionButton()} + {/if} + <Button + variant="accent-secondary" + unifiedSize="sm" + startIcon={{ + icon: cascadeRunningRoot ? Loader2 : Play, + classes: cascadeRunningRoot ? 'animate-spin' : undefined + }} + onclick={runWholePipeline} + disabled={!!cascadeRunningRoot} + title={cascadeRunningRoot + ? 'A pipeline run is already in progress' + : `Run all ${allPipelineScripts.length} script${ + allPipelineScripts.length === 1 ? '' : 's' + } in dependency order (roots first, cascading downstream)`} + > + {cascadeRunningRoot ? 'Running…' : 'Run pipeline'} + </Button> + {/if} {/if} {#if mode === 'edit' && saveErrors.size > 0} <PipelineDeployErrors errors={saveErrors} bind:open={saveErrorsOpen} /> {/if} - {#if mode === 'edit' && pendingCount > 0} + {#if saveAllShown} + {@render sessionButton()} <Button variant="accent" unifiedSize="sm" @@ -2952,7 +2994,7 @@ {savingAll ? 'Saving…' : `Save all (${pendingCount})`} </Button> {/if} - {#if mode === 'view'} + {#if mode === 'view' && !viewHelpersInMenu} <Button variant={activityShowing ? 'accent-secondary' : 'subtle'} unifiedSize="sm" @@ -2965,20 +3007,29 @@ Activity </Button> {/if} - <OpenInSessionButton source={sessionOpen} /> - <Button - variant="subtle" - unifiedSize="sm" - startIcon={{ icon: RefreshCw }} - onclick={() => graphRes.refetch()} - disabled={graphRes.loading} - iconOnly - title="Refresh" - /> + {#if !viewHelpersInMenu} + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: RefreshCw }} + onclick={() => graphRes.refetch()} + disabled={graphRes.loading} + iconOnly + title="Refresh" + /> + {/if} <DropdownV2 size="sm" items={overflowMenuItems} /> + {#if !saveAllShown && !runPipelineShown} + {@render sessionButton()} + {/if} </div> {/snippet} +{#snippet sessionButton()} + <!-- Right before the page's main action: Save all while there are drafts, else Run pipeline. --> + <OpenInSessionButton source={sessionOpen} /> +{/snippet} + <div class="flex flex-col h-full"> <div class="flex-1 min-h-0"> {#if graphRes.loading && !graphRes.current} @@ -3013,8 +3064,8 @@ {runsRefreshKey} {runsPendingJobId} {boundPick} - validStartPaths={isOperator ? undefined : validStartPaths} - onStartBoundedRun={isOperator ? undefined : startBoundedRun} + validStartPaths={viewOnly ? undefined : validStartPaths} + onStartBoundedRun={viewOnly ? undefined : startBoundedRun} onPickEnd={pickBoundEnd} {panToNodeId} onCreateMissingTrigger={mode === 'edit' ? openMissingTriggerDrawer : undefined} @@ -3033,10 +3084,10 @@ onAddScriptForAsset={mode === 'edit' ? handleAddScriptForAsset : undefined} onAddPipelineScript={mode === 'edit' ? handleAddPipelineScript : undefined} onRunnableMenuRemove={mode === 'edit' ? handleRunnableMenuRemove : undefined} - onDeleteAssetUpstream={isOperator ? undefined : (t) => (assetDeleteTarget = t)} + onDeleteAssetUpstream={viewOnly ? undefined : (t) => (assetDeleteTarget = t)} {nodeFixes} assetDeleteVerb={canHardDeleteScripts ? 'Delete' : 'Archive'} - onEdgeAction={isOperator + onEdgeAction={viewOnly ? undefined : ({ action, @@ -3061,7 +3112,7 @@ } ) }} - onAddAssetTrigger={isOperator || mode !== 'edit' + onAddAssetTrigger={viewOnly || mode !== 'edit' ? undefined : ({ scripts, @@ -3076,7 +3127,7 @@ ) }} onRunProducer={mode === 'edit' ? handleRunProducer : undefined} - onRequestEdit={isOperator ? undefined : () => setMode('edit')} + onRequestEdit={viewOnly ? undefined : () => setMode('edit')} canRunByPath={openScriptHasDataUpload} onRunByPath={runByPathLegit} {selectionProducers} diff --git a/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte index 6110af0fef..003f6c7752 100644 --- a/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte @@ -18,6 +18,7 @@ import { onDestroy, untrack } from 'svelte' import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { UserDraft, draftValuesEqual } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { discardDraftAfterDeploy, runResetToDeployed } from '$lib/userDraftToast' @@ -311,6 +312,15 @@ getDraft }) if (tok !== loadScriptToken) return + // A draft-only script has no page for Home's card to open. + if (!backendScript.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'script', + path: backendScript.path, + summary: backendScript.summary, + via: 'edit' + }) + } // The editor re-infers the schema as soon as it mounts, so a baseline // taken from the raw stored schema would flag every unedited open of a // script whose stored schema differs from what this parser emits. diff --git a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte index 19177dc463..19e7b60462 100644 --- a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte @@ -1,3 +1,13 @@ +<script module lang="ts"> + import { preloadComponent } from '$lib/utils/preloadComponent.svelte' + + // The preview tabs render whole items, through most of AIChat's code (Monaco among it): + // loaded beside the page, not as part of it, so the page shows without waiting on them. + const previewTabHostComponent = preloadComponent( + () => import('$lib/components/sessions/PreviewTabHost.svelte') + ) +</script> + <script lang="ts"> import { onDestroy, onMount, tick, untrack } from 'svelte' import { SvelteSet } from 'svelte/reactivity' @@ -25,10 +35,9 @@ type Scope } from '$lib/components/sessions/PreviewRouterPicker.svelte' import { goto } from '$lib/navigation' - import { resource } from 'runed' - import { WorkspaceService } from '$lib/gen' + import { useWorkspaceAiHidden } from '$lib/components/copilot/workspaceAiHidden.svelte' import SessionWrapper from '$lib/components/sessions/SessionWrapper.svelte' - import PreviewTabHost from '$lib/components/sessions/PreviewTabHost.svelte' + import type PreviewTabHost from '$lib/components/sessions/PreviewTabHost.svelte' import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte' import { createSession, @@ -44,7 +53,12 @@ import { withWorkspaceParam } from '$lib/components/sessions/sessionMode.svelte' import { enterSessionMode } from '$lib/components/sessions/sessionSwitch.svelte' import type { SessionPreviewTabs } from '$lib/components/sessions/sessionPreviewTabs.svelte' - import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' + import { + roleCapabilities, + userWorkspaces, + usersWorkspaceStore, + workspaceStore + } from '$lib/stores' import { getOrCreateRuntime, getRuntime, @@ -205,7 +219,7 @@ // load. `recovering` also guards re-entry: recovery mutates the session list // this effect tracks, while the URL that would stop it only updates on `goto`. $effect(() => { - if (embedded || !globalEnabled || !sessionsAllowedFor($userStore?.operator)) return + if (embedded || !globalEnabled || !sessionsAllowedFor(!$roleCapabilities.code)) return if (!sessionState.hydrated || recovering) return // A deliberate delete removes the open session ahead of its own navigation. // Claiming that gap would take over the URL and tell the user the session @@ -324,35 +338,16 @@ (activeSession ? getEffectiveWorkspaceId(activeSession) : undefined) ?? $workspaceStore ) - // Whether that workspace hid the AI assistant (`ai_config.copilot_disabled`). Read - // directly rather than from `copilotInfo`: that store holds whichever workspace loaded - // last, and the gate below unmounts the session wrapper that would refresh it, so a - // hidden verdict would stick across session and workspace switches. Tagged with its - // workspace and guarded against a superseded response like the protection-rules - // resource: runed keeps the previous `current` while a new source loads, so a switch - // would otherwise be judged on the previous workspace's verdict. A failed read leaves - // the page usable, as an unloaded config does everywhere else. - const workspaceAiHidden = resource( - () => previewWorkspace, - async (workspace, _prev, { signal }) => { - if (!workspace) return { workspace, hidden: false } - let hidden = false - try { - hidden = (await WorkspaceService.getCopilotInfo({ workspace })).copilot_disabled === true - } catch (e) { - console.error(`Failed to read the AI config of workspace ${workspace}:`, e) - } - // The generated client can't take an abort signal, so drop a superseded response here. - if (signal.aborted) throw new DOMException('superseded', 'AbortError') - return { workspace, hidden } - } + // Whether that workspace hid the AI assistant. The gate below unmounts the session wrapper + // that would refresh `copilotInfo`, so the verdict is read for the workspace itself. + const workspaceAiHidden = useWorkspaceAiHidden(() => previewWorkspace) + const aiHiddenVerdict = $derived(workspaceAiHidden.hidden) + // The full loader is for the page's first verdict only. Later, picking another workspace in + // "Acting on" leaves the session on screen, inert until its verdict lands: covering it for + // a request reads as the page reloading. + const firstVerdictPending = $derived( + aiHiddenVerdict === undefined && !workspaceAiHidden.settledOnce ) - // Only a verdict for the workspace currently judged counts; `undefined` means it has not - // landed yet. - const aiHiddenVerdict = $derived.by(() => { - const current = workspaceAiHidden.current - return current && current.workspace === previewWorkspace ? current.hidden : undefined - }) // Lazy-mount gate: a tab's content only renders once its key lands here (on // first activation) — so restoring a session with N saved tabs boots just @@ -857,13 +852,16 @@ // cell reactively, so the editor mirrors the name onto the tab model). Before // that, the workspace listing names it. Falls back to the plain location label // for summary-less items and non-item pages. - function tabLabelFor(tab: SessionPreviewTab, workspace: string): string { + function tabNameFor(tab: SessionPreviewTab, workspace: string): string { const listed = listedItemFor(tab, workspace) - const name = + return ( tab.friendlyLabel ?? (listed && itemDisplayName(listed.path, listed.draftPath, listed.summary)) ?? previewLocationLabel(tab.loc) - return name + sideSuffix(tab.url) + ) + } + function tabLabelFor(tab: SessionPreviewTab, workspace: string): string { + return tabNameFor(tab, workspace) + sideSuffix(tab.url) } // Hover title for a tab. A summary label is free text the strip truncates, and @@ -1023,11 +1021,11 @@ }}>Open sessions</Button > </div> - {:else if !sessionsAllowedFor($userStore?.operator)} - <!-- Operators without the opt-in keep the legacy docked chat (see `gate.ts`); a direct - URL must not bypass that. --> + {:else if !sessionsAllowedFor(!$roleCapabilities.code)} + <!-- A role that cannot code keeps the legacy docked chat without the opt-in (see `gate.ts`); + a direct URL must not bypass that. --> <div class="p-8 flex flex-col items-start gap-3 text-secondary text-sm"> - <p class="text-primary font-medium">AI Sessions are not available for operators</p> + <p class="text-primary font-medium">AI Sessions are not available for your role</p> <p>Use the Ask AI chat instead.</p> <Button unifiedSize="xs" @@ -1119,7 +1117,13 @@ : 'z-0 opacity-0 pointer-events-none'}" aria-hidden={s.id !== activeSession?.id} > - <SessionWrapper sessionId={s.id} headerInPage={s.id === activeSession?.id} /> + <SessionWrapper + sessionId={s.id} + headerInPage={s.id === activeSession?.id} + covered={aiHiddenVerdict !== false} + previewTabName={(tab) => + tabNameFor(tab, getEffectiveWorkspaceId(s) ?? $workspaceStore ?? '')} + /> </div> {/each} </div> @@ -1195,32 +1199,35 @@ content-gated by the shared mount MRU. Each host renders a live editor (script/flow/raw_app target) or an iframe fallback. --> <div class="relative flex-1 min-h-0"> - {#each warmSessions as s (s.id)} - {@const rt = getRuntime(s.id)} - {@const tabs = rt?.previewTabs} - {#each tabs?.tabs ?? [] as tab (tab.id)} - <!-- tabHosts is an imperative ref-bag (only tabHosts[key]?.reload() in + {#if previewTabHostComponent.current} + {@const TabHost = previewTabHostComponent.current} + {#each warmSessions as s (s.id)} + {@const rt = getRuntime(s.id)} + {@const tabs = rt?.previewTabs} + {#each tabs?.tabs ?? [] as tab (tab.id)} + <!-- tabHosts is an imperative ref-bag (only tabHosts[key]?.reload() in reloadTabs); it is intentionally a plain object so component instances aren't proxied. Nothing reads it reactively, so the non-reactive binding is fine. --> - <!-- svelte-ignore binding_property_non_reactive --> - <PreviewTabHost - bind:this={tabHosts[tabKey(s.id, tab.id)]} - {tab} - session={s} - runtime={rt} - active={s.id === activeSession?.id && tab.id === tabs?.activeId} - collapsed={(tabs?.collapsed ?? false) && !fullscreen} - mounted={mountedTabKeys.has(tabKey(s.id, tab.id))} - label={tabLabelFor(tab, s.workspace_id ?? '')} - darkMode={isDarkMode.val} - {fullscreen} - onNavigate={navigateEditorTo} - onSeeDetails={seeDetailsInPreview} - onLoad={(frame) => tabs && onTabLoad(tabs, tab, frame)} - /> + <!-- svelte-ignore binding_property_non_reactive --> + <TabHost + bind:this={tabHosts[tabKey(s.id, tab.id)]} + {tab} + session={s} + runtime={rt} + active={s.id === activeSession?.id && tab.id === tabs?.activeId} + collapsed={(tabs?.collapsed ?? false) && !fullscreen} + mounted={mountedTabKeys.has(tabKey(s.id, tab.id))} + label={tabLabelFor(tab, s.workspace_id ?? '')} + darkMode={isDarkMode.val} + {fullscreen} + onNavigate={navigateEditorTo} + onSeeDetails={seeDetailsInPreview} + onLoad={(frame) => tabs && onTabLoad(tabs, tab, frame)} + /> + {/each} {/each} - {/each} + {/if} {#if (owner?.tabs.length ?? 0) === 0} <!-- New session with nothing to preview: an empty state with a picker to open one, instead of defaulting to the home page. --> @@ -1256,6 +1263,7 @@ <PreviewRouterPicker workspaceId={previewWorkspace} artifacts={sessionArtifacts} + chat={activeRuntime?.manager} onPick={(t) => { emptyStateNewTabOpen = false openInNewTab(t) @@ -1271,15 +1279,16 @@ </Pane> </Splitpanes> </div> - {#if aiHiddenVerdict === undefined} + {#if firstVerdictPending} <div class="absolute inset-0 z-20 flex items-center justify-center bg-surface"> <Loader2 class="animate-spin" /> </div> {:else if aiHiddenVerdict} <!-- The workspace hid the assistant, and the sidebar switch with it, so only a direct URL or a session acting on such a workspace lands here. --> + <!-- Centred like the loader above: the page header overlays this pane's top edge. --> <div - class="absolute inset-0 z-20 bg-surface p-8 flex flex-col items-start gap-3 text-secondary text-sm" + class="absolute inset-0 z-20 bg-surface p-8 flex flex-col items-center justify-center gap-3 text-secondary text-sm text-center" > <p class="text-primary font-medium">AI Sessions are hidden in this workspace</p> <p>A workspace admin hid AI sessions in the workspace settings.</p> @@ -1390,6 +1399,7 @@ {currentItem} workspaceId={previewWorkspace} artifacts={sessionArtifacts} + chat={activeRuntime?.manager} onPick={(t) => { activeTabPickerOpen = false navigatePreviewTo(t) @@ -1421,6 +1431,7 @@ <PreviewRouterPicker workspaceId={previewWorkspace} artifacts={sessionArtifacts} + chat={activeRuntime?.manager} onPick={(t) => { newTabOpen = false openInNewTab(t) diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/fork_workspace/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/fork_workspace/+page.svelte index 3be417202c..bb72bc844e 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/fork_workspace/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/fork_workspace/+page.svelte @@ -1,16 +1,17 @@ <script lang="ts"> import CreateWorkspace from '$lib/components/workspaceSettings/CreateWorkspace.svelte' import { Alert } from '$lib/components/common' - import { userStore } from '$lib/stores' + import { roleCapabilities } from '$lib/stores' + import { isRestricted } from '$lib/roleCapabilities' </script> -<!-- The form is reachable by URL whatever the pickers show, and forking is what turns an operator - into a full member of the copy (the fork's membership row carries `is_admin` but not - `operator`). The server still accepts the call — this refuses the page, it does not enforce +<!-- The form is reachable by URL whatever the pickers show, and forking is what turns a restricted role + into a full member of the copy (the fork's membership row carries `is_admin` but not the + role). The server still accepts the call: this refuses the page, it does not enforce the rule; see docs/operator-write-rights.md. --> -{#if $userStore?.operator} +{#if isRestricted($roleCapabilities)} <div class="p-4 mt-12"> - <Alert type="error" title="Unauthorized">Page not available for operators</Alert> + <Alert type="error" title="Unauthorized">Page not available for your role</Alert> </div> {:else} <CreateWorkspace isFork={true} /> diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte index 8bcd94ce24..8500593592 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte @@ -8,7 +8,8 @@ workspaceStore, userStore, enterpriseLicense, - whitelabelNameStore + whitelabelNameStore, + roleCapabilities } from '$lib/stores' import { emptyString, parseQueryParams } from '$lib/utils' import { getUserExt } from '$lib/user' @@ -96,7 +97,7 @@ workspaceStore.set(allWorkspaces[0].id) $userStore = await getUserExt($workspaceStore!) - if (!$userStore?.is_super_admin && $userStore?.operator) { + if (!$roleCapabilities.code) { let defaultApp = await WorkspaceService.getWorkspaceDefaultApp({ workspace: $workspaceStore! }) diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte index 046f723e85..4ed63729e4 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte @@ -14,7 +14,8 @@ userWorkspaces, workspaceStore, userStore, - getWorkspaceFromStorage + getWorkspaceFromStorage, + roleCapabilities } from '$lib/stores' import { Button, Skeleton } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' @@ -235,7 +236,7 @@ workspaceStore.set(undefined) workspaceStore.set(workspaceId) $userStore = await getUserExt($workspaceStore!) - if (!$userStore?.is_super_admin && $userStore?.operator) { + if (!$roleCapabilities.code) { let defaultApp = await WorkspaceService.getWorkspaceDefaultApp({ workspace: $workspaceStore! }) diff --git a/frontend/src/routes/(root)/(logged)/workers/+page.svelte b/frontend/src/routes/(root)/(logged)/workers/+page.svelte index 5fa5ef7f56..93f0902800 100644 --- a/frontend/src/routes/(root)/(logged)/workers/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workers/+page.svelte @@ -29,9 +29,8 @@ enterpriseLicense, superadmin, devopsRole, - userStore, workspaceStore, - userWorkspaces + roleCapabilities } from '$lib/stores' import { sendUserToast } from '$lib/toast' import { displayDate, groupBy, pluralize, retrieveCommonWorkerPrefix, truncate } from '$lib/utils' @@ -746,10 +745,10 @@ </DrawerContent> </Drawer> -{#if $userStore?.operator && $workspaceStore && !$userWorkspaces.find((_) => _.id === $workspaceStore)?.operator_settings?.workers} +{#if $workspaceStore && !$roleCapabilities.visibility.workers} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> - <p>Page not available for operators</p> + <p>Page not available for your role</p> </div> {:else} <CenteredPage> diff --git a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte index aba1b9832b..5ba85cdbe0 100644 --- a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte @@ -3,7 +3,7 @@ import { page } from '$app/stores' import { isCloudHosted } from '$lib/cloud' import CenteredPage from '$lib/components/CenteredPage.svelte' - import { Alert, Button, Section, Skeleton, Tab, Tabs } from '$lib/components/common' + import { Alert, Button, SecondsInput, Section, Skeleton, Tab, Tabs } from '$lib/components/common' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' @@ -18,6 +18,10 @@ type HandlerDraft } from '$lib/components/handlerDraft.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' + import { WORKSPACE_SETTINGS_PATH } from '$lib/components/sessions/previewPaths' + import OpenInSessionButton, { + type OpenInSessionSource + } from '$lib/components/sessions/OpenInSessionButton.svelte' import ScriptPicker from '$lib/components/ScriptPicker.svelte' import Tooltip from '$lib/components/Tooltip.svelte' @@ -50,10 +54,13 @@ import { clone, emptyString, encodeState, hasUnsavedChanges } from '$lib/utils' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' import { ExternalLink, Slack, Target } from 'lucide-svelte' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import SidebarNavigation from '$lib/components/common/sidebar/SidebarNavigation.svelte' import PremiumInfo from '$lib/components/settings/PremiumInfo.svelte' import Toggle from '$lib/components/Toggle.svelte' + import Popover from '$lib/components/Popover.svelte' import SlackChannelAgents from '$lib/components/workspaceSettings/SlackChannelAgents.svelte' import ChangeWorkspaceName from '$lib/components/settings/ChangeWorkspaceName.svelte' @@ -73,6 +80,9 @@ import Trashbin from '$lib/components/settings/Trashbin.svelte' import { untrack } from 'svelte' import { resource } from 'runed' + import NativeOAuthCallback from '$lib/components/triggers/native/NativeOAuthCallback.svelte' + import { nativeOAuthRedirectUri } from '$lib/components/triggers/native/utils' + import type { NativeServiceName } from '$lib/gen' import DbtSettings, { convertDbtSettingsFromBackend, type DbtSettingsType @@ -91,6 +101,7 @@ } from '$lib/components/sessions/sessionState.svelte' import TextInput from '$lib/components/text_input/TextInput.svelte' import CollapseLink from '$lib/components/CollapseLink.svelte' + import SlackAppSetup from '$lib/components/common/slack/SlackAppSetup.svelte' import { validateWebhookUrl, validateEncryptionKey } from '$lib/validators/workspaceSettings' import DataTableSettings, { convertDataTableSettingsFromBackend, @@ -174,11 +185,12 @@ // links here with `agents=true`. let slackAgents = $state($page.url.searchParams.get('agents') === 'true') let slackAppType: 'instance' | 'workspace' = $state('instance') - // Agents verify Slack's requests with the server's signing secret, which only the instance's - // Slack app is signed with, so the toggle is offered for that app alone. - let slackAgentsScopes = $derived(slackAgents && slackAppType === 'instance') + // Agents answer only once Windmill can verify Slack's requests with the signing secret of the + // app the workspace connects through. + let slackSigningSecret: string = $state('') + let slackSigningSecretSet: boolean = $state(false) const slackAgentsStatus = resource( - () => (slackAgentsScopes ? $workspaceStore : undefined), + () => (slackAgents ? $workspaceStore : undefined), async (workspace) => workspace ? await SlackAgentsService.getSlackAgentsStatus({ workspace }) : undefined ) @@ -211,6 +223,21 @@ let errorHandlerMutedOnCancel: boolean | undefined = $state(undefined) let errorHandlerMutedOnUserPath: boolean | undefined = $state(undefined) let successHandlerScriptPath: string | undefined = $state(undefined) + const noVariableExpirationHandler = handlerDraftFromStored('variableExpiration', undefined) + let variableExpirationDraft: HandlerDraft = $state(cloneHandlerDraft(noVariableExpirationHandler)) + let variableExpirationMutedOnUserPath: boolean = $state(false) + // The sweep's default when the stored handler has no `notify_before_secs`. + const defaultNotifyBeforeSecs = 24 * 3600 + let variableExpirationNotifyBeforeSecs: number = $state(defaultNotifyBeforeSecs) + let variableExpirationRemindEverySecs: number | undefined = $state(undefined) + // The sweep runs every 5 minutes, so shorter intervals count as 5 minutes. + let variableExpirationRuns = $derived( + variableExpirationRemindEverySecs + ? Math.ceil( + variableExpirationNotifyBeforeSecs / Math.max(variableExpirationRemindEverySecs, 300) + ) + : 1 + ) let criticalAlertUIMuted: boolean | undefined = $state(undefined) let initialCriticalAlertUIMuted: boolean | undefined = $state(undefined) let publicAppRateLimitPerMinute: number | undefined = $state(undefined) @@ -280,6 +307,14 @@ // Track initial success handler for unsaved changes detection let initialSuccessHandlerScriptPath: string | undefined = $state(undefined) + // Track initial variable expiration handler for unsaved changes detection + let initialVariableExpirationDraft: HandlerDraft = $state( + cloneHandlerDraft(noVariableExpirationHandler) + ) + let initialVariableExpirationMutedOnUserPath: boolean = $state(false) + let initialVariableExpirationNotifyBeforeSecs: number = $state(defaultNotifyBeforeSecs) + let initialVariableExpirationRemindEverySecs: number | undefined = $state(undefined) + let s3ResourceSettings: S3ResourceSettings = $state({ resourceType: 's3', resourcePath: undefined, @@ -337,6 +372,43 @@ ) }) + // The mute flag is stored inside the handler setting, which saving with no handler + // clears, so the toggle is gated on having one. + let variableExpirationHasHandler = $derived(!!handlerDraftToStored(variableExpirationDraft).path) + + // The stored handler is nested because `hasUnsavedChanges` drops a top-level `path`. + function variableExpirationSettingsValue( + draft: HandlerDraft, + mutedOnUserPath: boolean, + notifyBeforeSecs: number, + remindEverySecs: number | undefined + ) { + return { + handler: handlerDraftToStored(draft), + mutedOnUserPath, + notifyBeforeSecs, + remindEverySecs: remindEverySecs || undefined + } + } + + let hasVariableExpirationChanges = $derived.by(() => { + if (tab !== 'variable_expiration') return false + return hasUnsavedChanges( + variableExpirationSettingsValue( + initialVariableExpirationDraft, + initialVariableExpirationMutedOnUserPath, + initialVariableExpirationNotifyBeforeSecs, + initialVariableExpirationRemindEverySecs + ), + variableExpirationSettingsValue( + variableExpirationDraft, + variableExpirationMutedOnUserPath, + variableExpirationNotifyBeforeSecs, + variableExpirationRemindEverySecs + ) + ) + }) + // Derived state for checking unsaved changes in critical alert mute setting let hasCriticalAlertMuteChanges = $derived.by(() => { if (tab !== 'critical_alerts') return false @@ -399,6 +471,13 @@ // The deploy filters configure what may be promoted into the parent, so they only mean // something for a fork. A root workspace deploys nowhere by lineage. const showDeployToTab = $derived(Boolean(currentWorkspace?.parent_workspace_id)) + // The page native trigger OAuth providers redirect to. Anyone can connect an account, so the + // callback is handled before the admin gate. + const nativeOAuthService = $derived( + $page.url.searchParams.get('tab') === 'native_triggers' && $page.url.searchParams.has('state') + ? ($page.url.searchParams.get('service') as NativeServiceName | null) + : null + ) const canAdmin = $derived(($userStore?.is_admin ?? false) || Boolean($superadmin)) let yamlMode = $state(false) // A workspace where the user is not an admin hides the toggle, so it must not stay in YAML mode. @@ -473,6 +552,7 @@ | 'dev_workspace' | 'error_handler' | 'success_handler' + | 'variable_expiration' | 'critical_alerts' | 'ai' | 'windmill_data_tables' @@ -791,6 +871,20 @@ | { path?: string; extra_args?: any } | undefined successHandlerScriptPath = (successHandler?.path ?? '').split('/').slice(1).join('/') + const variableExpirationHandler = settings.variable_expiration_handler + const [variableExpirationKind, ...variableExpirationPath] = ( + variableExpirationHandler?.path ?? '' + ).split('/') + variableExpirationDraft = handlerDraftFromStored( + 'variableExpiration', + variableExpirationPath.join('/'), + variableExpirationKind === 'flow' ? 'flow' : 'script', + variableExpirationHandler?.extra_args + ) + variableExpirationMutedOnUserPath = variableExpirationHandler?.muted_on_user_path ?? false + variableExpirationNotifyBeforeSecs = + variableExpirationHandler?.notify_before_secs ?? defaultNotifyBeforeSecs + variableExpirationRemindEverySecs = variableExpirationHandler?.remind_every_secs || undefined workspaceDefaultAppPath = settings.default_app initialWorkspaceDefaultAppPath = settings.default_app @@ -842,6 +936,12 @@ // Store initial success handler state for unsaved changes detection initialSuccessHandlerScriptPath = successHandlerScriptPath + // Store initial variable expiration handler state for unsaved changes detection + initialVariableExpirationDraft = cloneHandlerDraft(variableExpirationDraft) + initialVariableExpirationMutedOnUserPath = variableExpirationMutedOnUserPath + initialVariableExpirationNotifyBeforeSecs = variableExpirationNotifyBeforeSecs + initialVariableExpirationRemindEverySecs = variableExpirationRemindEverySecs + loadedSettings = true } @@ -857,6 +957,7 @@ slackOAuthClientId = config.slack_oauth_client_id || '' slackOAuthClientSecret = config.slack_oauth_client_secret || '' slackOAuthConfigLoaded = !!config.slack_oauth_client_id + slackSigningSecretSet = !!config.slack_signing_secret } catch (e) { console.error('Failed to load Slack OAuth config:', e) } @@ -892,15 +993,38 @@ slack_oauth_client_secret: slackOAuthClientSecret } }) + if (slackSigningSecret.trim()) { + await WorkspaceService.setWorkspaceSlackSigningSecret({ + workspace: $workspaceStore, + requestBody: { slack_signing_secret: slackSigningSecret } + }) + } // Redirect to OAuth flow - window.location.href = `/api/oauth/connect_slack?workspace=${$workspaceStore}` + window.location.href = `/api/oauth/connect_slack?workspace=${$workspaceStore}${slackAgents ? '&agents=true' : ''}` } catch (e) { sendUserToast('Failed to save Slack OAuth configuration', true) console.error(e) } } + async function saveSlackSigningSecret(): Promise<void> { + if (!$workspaceStore) return + const secret = slackSigningSecret.trim() || null + try { + await WorkspaceService.setWorkspaceSlackSigningSecret({ + workspace: $workspaceStore, + requestBody: { slack_signing_secret: secret } + }) + slackSigningSecret = '' + slackSigningSecretSet = !!secret + sendUserToast(secret ? 'Signing secret saved' : 'Signing secret removed') + } catch (e) { + sendUserToast('Failed to save the signing secret', true) + console.error(e) + } + } + async function deleteSlackOAuthConfig(): Promise<void> { if (!$workspaceStore) return @@ -918,6 +1042,7 @@ slackOAuthClientId = '' slackOAuthClientSecret = '' slackOAuthConfigLoaded = false + slackSigningSecretSet = false await loadSettings() sendUserToast('Workspace Slack app deleted') } catch (e) { @@ -1023,6 +1148,46 @@ initialErrorHandlerMutedOnUserPath = errorHandlerMutedOnUserPath } + async function editVariableExpirationHandler() { + const handler = handlerDraftToStored(variableExpirationDraft) + await WorkspaceService.editVariableExpirationHandler({ + workspace: $workspaceStore!, + requestBody: { + path: handler.path ? `${handler.kind}/${handler.path}` : undefined, + extra_args: handler.args, + muted_on_user_path: variableExpirationMutedOnUserPath, + notify_before_secs: variableExpirationNotifyBeforeSecs, + remind_every_secs: variableExpirationRemindEverySecs || undefined + } + }) + sendUserToast( + handler.path + ? `Variable expiration handler set to ${handler.path}` + : handlerDraftToStored(initialVariableExpirationDraft).path + ? 'Variable expiration handler removed' + : 'Variable expiration settings saved' + ) + + // Rebuilt from what was stored, so Discard also drops the other tabs' unsaved edits. + initialVariableExpirationDraft = handlerDraftFromStored( + 'variableExpiration', + handler.path, + handler.kind, + handler.args, + { emptySelected: variableExpirationDraft.selected } + ) + initialVariableExpirationMutedOnUserPath = variableExpirationMutedOnUserPath + initialVariableExpirationNotifyBeforeSecs = variableExpirationNotifyBeforeSecs + initialVariableExpirationRemindEverySecs = variableExpirationRemindEverySecs + } + + function discardVariableExpirationChanges() { + variableExpirationDraft = cloneHandlerDraft(initialVariableExpirationDraft) + variableExpirationMutedOnUserPath = initialVariableExpirationMutedOnUserPath + variableExpirationNotifyBeforeSecs = initialVariableExpirationNotifyBeforeSecs + variableExpirationRemindEverySecs = initialVariableExpirationRemindEverySecs + } + async function editSuccessHandler() { if (successHandlerScriptPath) { await WorkspaceService.editSuccessHandler({ @@ -1287,6 +1452,21 @@ } } } + case 'variable_expiration': + return { + savedValue: variableExpirationSettingsValue( + initialVariableExpirationDraft, + initialVariableExpirationMutedOnUserPath, + initialVariableExpirationNotifyBeforeSecs, + initialVariableExpirationRemindEverySecs + ), + modifiedValue: variableExpirationSettingsValue( + variableExpirationDraft, + variableExpirationMutedOnUserPath, + variableExpirationNotifyBeforeSecs, + variableExpirationRemindEverySecs + ) + } case 'critical_alerts': return { savedValue: { criticalAlertUIMuted: initialCriticalAlertUIMuted }, @@ -1331,6 +1511,9 @@ discardErrorHandlerSettingsChanges() successHandlerScriptPath = initialSuccessHandlerScriptPath break + case 'variable_expiration': + discardVariableExpirationChanges() + break case 'critical_alerts': criticalAlertUIMuted = initialCriticalAlertUIMuted break @@ -1438,6 +1621,13 @@ 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', @@ -1544,10 +1734,19 @@ const tabLabel = $derived( navigationGroups.flatMap((g) => g.items).find((i) => i.id === tab)?.label ) + + const sessionSource: OpenInSessionSource = $derived({ + // Read at click time: the tab lives in the query, so the preview opens on the tab being + // viewed. YAML mode is component state and does not carry over. + page: () => WORKSPACE_SETTINGS_PATH + window.location.search, + workspaceId: $workspaceStore ?? undefined + }) </script> <CenteredPage wrapperClasses="pb-0 h-full" handleOverflow={false} class="flex flex-col h-full"> - {#if canAdmin || isForkOwner} + {#if nativeOAuthService} + <NativeOAuthCallback redirectUri={nativeOAuthRedirectUri(nativeOAuthService)} /> + {:else if canAdmin || isForkOwner} <!-- No title of its own: the band already says which workspace's settings these are, and the 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. --> @@ -1558,6 +1757,8 @@ ? { parent: 'Workspace settings', label: tabLabel } : undefined} actions={settingsActions} + {sessionSource} + actionFolds={1} separator="always" /> @@ -1733,7 +1934,7 @@ } }} onSelect={editSlackCommand} - connectHref="/api/oauth/connect_slack{slackAgentsScopes ? '?agents=true' : ''}" + connectHref="/api/oauth/connect_slack{slackAgents ? '?agents=true' : ''}" createScriptHref="/scripts/add?hub=hub%2F28071%2Fslack%2Fexample_of_responding_to_a_slack_command_slack" createFlowHref="/flows/add?hub=28" documentationLink="https://www.windmill.dev/docs/integrations/slack" @@ -1763,27 +1964,24 @@ {/snippet} </ToggleButtonGroup> <div class="text-2xs text-hint" - >Use the Slack app configured at the instance level if you want to use - the same Slack app for all workspaces. Configure your Slack app here - if you want to use a specific Slack app for this workspace.</div + >The instance app is shared by all workspaces. A workspace app is your + own, for this workspace only.</div > </div> - {#if slackAppType === 'instance'} - <Toggle - size="xs" - bind:checked={slackAgents} - options={{ - right: 'Let AI agents answer in Slack', - rightTooltip: - 'Lets editors share agents in Slack channels, where people ask them by mentioning the bot. Needs users:read, users:read.email and channels:read on the Slack app.' - }} - /> - {#if slackAgentsStatus.current?.signing_secret_set === false} - <Alert type="warning" size="xs" title="Agents won't answer yet"> - An instance admin needs to set the Slack app's signing secret as the - <code>SLACK_SIGNING_SECRET</code> environment variable. - </Alert> - {/if} + <Toggle + size="xs" + bind:checked={slackAgents} + options={{ + right: 'Let AI agents answer in Slack', + rightTooltip: + 'Lets editors share agents in Slack channels, where people ask them by mentioning the bot. Needs users:read, users:read.email and channels:read on the Slack app.' + }} + /> + {#if slackAppType === 'instance' && slackAgentsStatus.current?.signing_secret_set === false} + <Alert type="warning" size="xs" title="Agents won't answer yet"> + An instance admin needs to set the Slack app's signing secret in the + instance settings. + </Alert> {/if} </div> {/if} @@ -1802,6 +2000,32 @@ >Client ID for the Slack app configured at the workspace level</div > </div> + <div class="flex flex-col gap-1"> + <div class="text-xs text-primary font-normal">Signing secret</div> + <div class="flex gap-2"> + <TextInput + inputProps={{ + type: 'password', + placeholder: slackSigningSecretSet + ? '••••••••••••••••••••••••••••••••' + : 'Enter signing secret' + }} + bind:value={slackSigningSecret} + /> + <Button + unifiedSize="md" + variant="default" + onclick={saveSlackSigningSecret} + disabled={!slackSigningSecret.trim() && !slackSigningSecretSet} + > + {slackSigningSecret.trim() || !slackSigningSecretSet ? 'Save' : 'Remove'} + </Button> + </div> + <div class="text-2xs text-hint" + >Lets Windmill check that requests come from Slack. Required for AI + agents; recommended for <code>/windmill</code> commands.</div + > + </div> {:else if slackAppType === 'workspace'} <div class="flex flex-col gap-6"> <label class="flex flex-col gap-1"> @@ -1826,21 +2050,23 @@ /> </label> + <label class="flex flex-col gap-1"> + <span class="text-primary font-semibold text-xs">Signing secret</span> + <TextInput + inputProps={{ + type: 'password', + placeholder: 'Enter signing secret' + }} + bind:value={slackSigningSecret} + /> + <span class="text-2xs text-hint" + >Lets Windmill check that requests come from Slack. Required for AI + agents; recommended for <code>/windmill</code> commands.</span + > + </label> + <CollapseLink text="Instructions"> - <div class="text-xs text-secondary"> - Create a Slack app at{' '} - <a - href="https://api.slack.com/apps" - target="_blank" - rel="noopener noreferrer" - class="text-blue-600 dark:text-blue-400 hover:underline" - > - Slack API - </a>. Set the redirect URI to:{' '} - <code class="bg-gray-100 dark:bg-gray-800 px-1 py-0.5 rounded"> - {window.location.origin}/oauth/callback_slack - </code> - </div> + <SlackAppSetup /> </CollapseLink> <div class="pt-2"> @@ -1848,7 +2074,9 @@ size="xs" variant="accent" onclick={saveAndConnectSlack} - disabled={!slackOAuthClientId || !slackOAuthClientSecret} + disabled={!slackOAuthClientId || + !slackOAuthClientSecret || + (slackAgents && !slackSigningSecret.trim())} startIcon={{ icon: Slack }} btnClasses="w-fit" > @@ -2212,6 +2440,125 @@ export async function main( disabled={!$enterpriseLicense} /> </Section> + {:else if tab == 'variable_expiration'} + <SettingsPageHeader + title="Variable expiration handler" + description="Run a script or flow ahead of the date the value of a workspace variable expires, so it can be rotated before it stops working." + link="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" + /> + + {#if !$enterpriseLicense && variableExpirationDraft.selected !== 'custom'} + <Alert type="warning" title="Slack and Teams handlers are an EE feature"> + Connecting a workspace to Slack or Teams is a Windmill EE feature. + </Alert> + {/if} + + <Section label="Handler"> + <div class="flex flex-col gap-6"> + <ErrorOrRecoveryHandler + noMargin + isEditable={true} + errorOrRecovery="variableExpiration" + customRequiresEE={false} + toggleText="Notify when a variable is about to expire" + bind:draft={variableExpirationDraft} + customScriptTemplate="/scripts/add?hub=hub%2F30050%2Fwindmill%2Fworkspace_variable_expiration_handler_template" + /> + + <SettingCard + label="Notify before expiry" + description="How long before a variable's value expires the handler runs" + class="gap-2" + > + <SecondsInput + bind:seconds={variableExpirationNotifyBeforeSecs} + disabled={!variableExpirationHasHandler} + hideSeconds + hideTotal + /> + <div class="flex flex-col gap-1 mt-4"> + <span class="text-xs font-semibold text-emphasis">Remind every</span> + <span class="text-xs text-secondary"> + Run the handler again at this interval until the value expires. Expiries are + checked every 5 minutes, so shorter intervals act as 5 minutes. Leave empty + or at 0 for a single notice. + </span> + <SecondsInput + bind:seconds={variableExpirationRemindEverySecs} + disabled={!variableExpirationHasHandler} + clearable + hideSeconds + hideTotal + /> + {#if variableExpirationRemindEverySecs && variableExpirationRemindEverySecs >= variableExpirationNotifyBeforeSecs} + <span class="text-xs text-yellow-600 dark:text-yellow-400"> + No reminder will be sent: the interval must be shorter than Notify before + expiry. + </span> + {:else if variableExpirationRuns >= 24} + <span class="text-xs text-yellow-600 dark:text-yellow-400"> + This runs the handler up to {variableExpirationRuns} times before the value + expires. + </span> + {/if} + </div> + </SettingCard> + + <SettingCard class="gap-2"> + <!-- `w-fit`: the trigger is a flex item of the card, so it would otherwise + stretch the full width and anchor the popup away from the toggle. --> + <Popover + notClickable + disablePopup={variableExpirationHasHandler} + placement="bottom-start" + class="w-fit" + > + <Toggle + bind:checked={variableExpirationMutedOnUserPath} + disabled={!variableExpirationHasHandler} + options={{ + right: 'Do not run the handler for variables in u/ paths' + }} + /> + {#snippet text()} + Select a handler first + {/snippet} + </Popover> + </SettingCard> + + <Alert type="info" title="Runs as g/variable_expiration_handler"> + {#if variableExpirationDraft.selected === 'custom'} + The handler is executed by the automatically created group + g/variable_expiration_handler. Rotating a variable means writing to it, so + grant that group write access to the variables it is meant to rotate. It + starts with none. A script that carries an on-behalf-of identity is the + exception: it runs as that user, with their permissions rather than the + group's. + {:else} + The handler is executed by the automatically created group + g/variable_expiration_handler. It only posts a message, so it needs no access + to your variables: it is given the path and the expiry date, never the value. + {#if variableExpirationDraft.selected === 'slack'} + Access to the Slack bot token is granted for you. + {/if} + {/if} + </Alert> + <span class="text-xs text-secondary"> + If the handler fails to start, a critical alert is raised once and the handler + is tried again at every check. The alert is resolved as soon as it starts. + </span> + </div> + + <SettingsFooter + class="mt-6" + inline + hasUnsavedChanges={hasVariableExpirationChanges} + onSave={editVariableExpirationHandler} + onDiscard={discardVariableExpirationChanges} + saveLabel="Save variable expiration handler" + disabled={!$enterpriseLicense && variableExpirationDraft.selected !== 'custom'} + /> + </Section> {:else if tab == 'critical_alerts'} <SettingsPageHeader title="Workspace critical alerts" @@ -2561,10 +2908,21 @@ export async function main( {/key} {/if} {#if $superadmin} - <Button variant="default" unifiedSize="sm" on:click={() => goto('#superadmin-settings')}> - Instance settings - </Button> + <!-- Goes into a menu on a phone, where the AI session button that ends the row would + otherwise squeeze the breadcrumb under these controls. --> + {#if pageHeader.actionFold >= 1} + <DropdownV2 + size="sm" + items={[{ displayName: 'Instance settings', action: () => goto('#superadmin-settings') }]} + /> + {:else} + <Button variant="default" unifiedSize="sm" on:click={() => goto('#superadmin-settings')}> + Instance settings + </Button> + {/if} {/if} + <!-- No main action on this page: the session button ends the row. --> + <OpenInSessionButton source={sessionSource} /> {/snippet} <style> diff --git a/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte b/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte index 327f64f962..32646b13f0 100644 --- a/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte +++ b/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte @@ -113,6 +113,7 @@ ? { ok: true as const } : { ok: false as const, reason: 'Deploy disabled by the playground toggle' } }, + readOnly: false, async deployRow(item: DeployItem) { setStatus(item.key, { status: 'loading' }) deploying = true diff --git a/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte b/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte index bfb6a9b10b..f91e26c976 100644 --- a/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte +++ b/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte @@ -29,16 +29,16 @@ // goto('/resources') } else if (code && state) { try { - const extraParams = Object.fromEntries( + const params = Object.fromEntries( Array.from(Object.entries(urlParamsToObject(page.url.searchParams))).filter( ([key]) => key !== 'code' && key !== 'state' && key !== 'error' ) ) const res = await OauthService.connectCallback({ clientName: client_name ?? '', - requestBody: { code, state } + requestBody: { code, state, params } }) - const message = { type: 'success', res, resource_type: client_name, extra: extraParams } + const message = { type: 'success', res, resource_type: client_name } sendUserToast('successful', false) if (window.opener) { console.log('Sending oauth popup message') diff --git a/frontend/src/routes/oauth/callback/[client_name]/native_trigger/+page.svelte b/frontend/src/routes/oauth/callback/[client_name]/native_trigger/+page.svelte new file mode 100644 index 0000000000..9bc941520b --- /dev/null +++ b/frontend/src/routes/oauth/callback/[client_name]/native_trigger/+page.svelte @@ -0,0 +1,8 @@ +<script lang="ts"> + import { page } from '$app/state' + import NativeOAuthCallback from '$lib/components/triggers/native/NativeOAuthCallback.svelte' +</script> + +<!-- Where native trigger connections made with the instance GitHub OAuth app land: that app only + redirects below its registered callback, /oauth/callback/github. --> +<NativeOAuthCallback redirectUri="{page.url.origin}/oauth/callback/github/native_trigger" /> diff --git a/imgs/architecture-dark.svg b/imgs/architecture-dark.svg new file mode 100644 index 0000000000..d69d89bfa0 --- /dev/null +++ b/imgs/architecture-dark.svg @@ -0,0 +1,94 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="700" viewBox="0 0 1200 700" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif"> +<title>Windmill architecture + + + +BUILD AND TRIGGER + +Business teams +Build with AI in AI sessions, +in the Windmill UI, in a fork +or a dev workspace + +Engineers +Code in 20+ languages, +CLI, VS Code, coding agents, +Git sync and CI + +Triggers and callers +HTTP routes and webhooks +Schedules +Kafka, NATS, SQS, MQTT +Postgres CDC, email, WebSocket +Apps and auto-generated UIs +Your services, via the REST API +MCP clients + +WINDMILL CONTROL PLANE + +API servers and web UI +Stateless, scale horizontally: +editor, AI sessions, apps, REST API + +Workspaces + +dev / forks +AI-built and new +changes land here + +prod +Locked: deploys +only after review + + +Review and promotion +Protection rulesets, Compare & Deploy, +Git pull requests, CI tests, audit logs + +PostgreSQL +Job queue, workspaces, scripts, flows, +apps, resources, encrypted secrets, +run history and audit logs + +Object storage (optional) +S3, Azure Blob or GCS: large logs, +dependency cache, pipeline data + +EXECUTION ON YOUR INFRA + +Worker group: dev +Runs jobs from dev and forks, +in a network that only reaches +dev systems + +Worker group: prod +Runs reviewed code only, +next to production systems + +Native workers +SQL, REST and GraphQL jobs + +Agent workers +Remote, connect over HTTP, +no direct database access + +Your systems +Databases and warehouses +Internal APIs and SaaS +AI model providers you +configure, local models included + + + + + + +pull jobs from the queue, by tag + +HTTP + + + + + + \ No newline at end of file diff --git a/imgs/architecture-light.svg b/imgs/architecture-light.svg new file mode 100644 index 0000000000..fb7a74df58 --- /dev/null +++ b/imgs/architecture-light.svg @@ -0,0 +1,94 @@ + +Windmill architecture + + + +BUILD AND TRIGGER + +Business teams +Build with AI in AI sessions, +in the Windmill UI, in a fork +or a dev workspace + +Engineers +Code in 20+ languages, +CLI, VS Code, coding agents, +Git sync and CI + +Triggers and callers +HTTP routes and webhooks +Schedules +Kafka, NATS, SQS, MQTT +Postgres CDC, email, WebSocket +Apps and auto-generated UIs +Your services, via the REST API +MCP clients + +WINDMILL CONTROL PLANE + +API servers and web UI +Stateless, scale horizontally: +editor, AI sessions, apps, REST API + +Workspaces + +dev / forks +AI-built and new +changes land here + +prod +Locked: deploys +only after review + + +Review and promotion +Protection rulesets, Compare & Deploy, +Git pull requests, CI tests, audit logs + +PostgreSQL +Job queue, workspaces, scripts, flows, +apps, resources, encrypted secrets, +run history and audit logs + +Object storage (optional) +S3, Azure Blob or GCS: large logs, +dependency cache, pipeline data + +EXECUTION ON YOUR INFRA + +Worker group: dev +Runs jobs from dev and forks, +in a network that only reaches +dev systems + +Worker group: prod +Runs reviewed code only, +next to production systems + +Native workers +SQL, REST and GraphQL jobs + +Agent workers +Remote, connect over HTTP, +no direct database access + +Your systems +Databases and warehouses +Internal APIs and SaaS +AI model providers you +configure, local models included + + + + + + +pull jobs from the queue, by tag + +HTTP + + + + + + \ No newline at end of file diff --git a/imgs/architecture.svg b/imgs/architecture.svg deleted file mode 100644 index 570f4ebc54..0000000000 --- a/imgs/architecture.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - -
worker
(Rust)
worker...
worker
(Rust)
worker...
worker
(Rust)
worker...
frontend
(SPA svelte)
frontend...
DB (Postgres)
DB (Postgr...
Database shardable by workspace_id
Database shardable by...
server
server
HTTPS
HTTPS
server
server
API server
(stateless Rust)
API server...
HTTPS
HTTPS
Cloud / on-prem
Cloud / on-prem
Co-located with API servers or remote
Co-located with API servers or remote
Browser
Browser


nsjail

nsjail
Python/TS
script exec
Python/TS...
your DB
your DB
your API
your API
Internet
Internet
Horizontally scalable
Horizontally scalable
Horizontally scalable
Horizontally scalable
If workers co-located with your internal DB/Services
If workers co-l...
Text is not SVG - cannot display
\ No newline at end of file diff --git a/imgs/diagram.svg b/imgs/diagram.svg deleted file mode 100644 index a7f50abfd3..0000000000 --- a/imgs/diagram.svg +++ /dev/null @@ -1,780 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/integration_tests/test/identity_script_test.py b/integration_tests/test/identity_script_test.py index 638919fb22..c4689e1874 100644 --- a/integration_tests/test/identity_script_test.py +++ b/integration_tests/test/identity_script_test.py @@ -24,12 +24,6 @@ func main(x int) (interface{}, error) { "python3": """ def main(x: int): return x -""", - "php": """=1.841.0" +wmill = ">=1.849.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 57e5009b90..91a2d4b79e 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.841.0 + version: 1.849.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 35e7468900..786d50f9fa 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.841.0' + ModuleVersion = '1.849.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 2c9f5143bf..b365d607b8 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.841.0" +version = "1.849.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/python-client/wmill/uv.lock b/python-client/wmill/uv.lock index 1c366b42bd..c6ebad85d8 100644 --- a/python-client/wmill/uv.lock +++ b/python-client/wmill/uv.lock @@ -15,7 +15,9 @@ name = "anyio" version = "4.12.1" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/96/f0/5eb65b2bb0d09ac6776f2eb54adee6abe8228ea05b20a5ad0e4945de8aac/anyio-4.12.1.tar.gz", hash = "sha256:41cfcc3a4c85d3f05c932da7c26d0201ac36f72abd4435ba90d0464a3ffed703", size = 228685, upload-time = "2026-01-06T11:45:21.246Z" } wheels = [ @@ -24,11 +26,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.2.25" +version = "2026.10.19" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/af/2d/7bf41579a8986e348fa033a31cdd0e4121114f6bce2457e8876010b092dd/certifi-2026.2.25.tar.gz", hash = "sha256:e887ab5cee78ea814d3472169153c2d12cd43b14bd03329a39a9c6e2e80bfba7", size = 155029, upload-time = "2026-02-25T02:54:17.342Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/3c/c17fb3ca2d9c3acff52e30b309f538586f9f5b9c9cf454f3845fc9af4881/certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa", size = 153684, upload-time = "2026-02-25T02:54:15.766Z" }, + { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, ] [[package]] @@ -40,6 +42,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "exceptiongroup" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" }, +] + [[package]] name = "h11" version = "0.16.0" @@ -128,12 +142,95 @@ version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, { name = "pygments" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] + +[[package]] +name = "tomli" +version = "2.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b0/78/9ad63712633ed3ab5cc1a648d863d7e7da371e9425e209555a0fe711b695/tomli-2.5.0.tar.gz", hash = "sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6", size = 17662, upload-time = "2026-10-07T12:23:37.892Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/ab99b60ee52acd949684febabc3005d0045d0f66bebd9cdebd67372d26dd/tomli-2.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c4dc1c1781f2f716de763d1e9a7b34c6a894e167e291c7c5d16c72f7a9538545", size = 163901, upload-time = "2026-10-07T12:22:15.601Z" }, + { url = "https://files.pythonhosted.org/packages/bc/00/ee01b7ed4579180fff07142d290257f25ba786f23f3ec6005f620933c2f5/tomli-2.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:eff8babca5a7999bc137acbc7482a8b7e17ffca5075ab41f5d770ab408c7bfef", size = 163756, upload-time = "2026-10-07T12:22:16.957Z" }, + { url = "https://files.pythonhosted.org/packages/72/c2/4efebf65372f6583185f79799312109dddb61102d47e5c33dcfd1a297aca/tomli-2.5.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:86665cee9c4835b7a7f1e8ec2c719b5258d4dc782887aded5a8ae7352a96843b", size = 268038, upload-time = "2026-10-07T12:22:18.135Z" }, + { url = "https://files.pythonhosted.org/packages/53/07/5850468e925d898abb36038666f9c333a94d2a223e802a8ba5b6d319d23f/tomli-2.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7e369fd63331746182360977b1892bfc215476a30d61612d732425311639f56", size = 276422, upload-time = "2026-10-07T12:22:19.567Z" }, + { url = "https://files.pythonhosted.org/packages/b4/87/f293984cdcf83c054196d4fd3dad44fc68ae55b4b8c44bc76cef360c3150/tomli-2.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7ad1ea345759240d6463efa0ed1c704402752e49aa21476620738d74d72d8aa1", size = 272616, upload-time = "2026-10-07T12:22:20.794Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ce/db582886b3c1219d3fec93ebd669332482e5aee7a91e0f7838d84f2d1759/tomli-2.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96243987194634bd411066ce40c952e108f86af04db533ecd8ac3ff2a85b1885", size = 276593, upload-time = "2026-10-07T12:22:22.12Z" }, + { url = "https://files.pythonhosted.org/packages/bf/72/7619b87dea4261fc27dd7b54c4461c129c1f7d9bb7ba3aec89c797a431b8/tomli-2.5.0-cp311-cp311-win32.whl", hash = "sha256:610b27d99f28ec5f191c7064a48f3ddb179a1fe6ca73d571483ae859f57b605e", size = 101830, upload-time = "2026-10-07T12:22:23.651Z" }, + { url = "https://files.pythonhosted.org/packages/1e/74/220106da34502304b6751a2a9b8a9fbca6c3fd47e737a2e2e3da7c61c9db/tomli-2.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:c804ae44fe7b4bab5da295e4f980a1ff04670bca9d23fe0a4e887e08ebd741a8", size = 112742, upload-time = "2026-10-07T12:22:24.972Z" }, + { url = "https://files.pythonhosted.org/packages/27/99/7d9c8b41837a7773613e169504147375c157a290167aa59ad74a085f521f/tomli-2.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:cfac177ebd6236003846ea339981f71457cb6eb748f23381eb257e45092e3980", size = 109332, upload-time = "2026-10-07T12:22:26.117Z" }, + { url = "https://files.pythonhosted.org/packages/52/ed/7baa86f87493646a594de388c7c1c40a39dd0461f7e9c0359cbeefc91fe8/tomli-2.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df", size = 164854, upload-time = "2026-10-07T12:22:27.444Z" }, + { url = "https://files.pythonhosted.org/packages/a5/b1/44c0341f2224397855723c7a8a39f718ea6fcbcc3dacc66e5aeca0f334e3/tomli-2.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b", size = 164074, upload-time = "2026-10-07T12:22:28.679Z" }, + { url = "https://files.pythonhosted.org/packages/23/04/e2d5b7d3fba47adedb23de616c16d428ea076c79a3d8e1d95d649ffe197e/tomli-2.5.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0", size = 274274, upload-time = "2026-10-07T12:22:29.804Z" }, + { url = "https://files.pythonhosted.org/packages/43/90/6090e706ff27a6f89f4a40578e3324b95c3cd8c4150868aabf33a8f414c3/tomli-2.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6", size = 286435, upload-time = "2026-10-07T12:22:31.297Z" }, + { url = "https://files.pythonhosted.org/packages/0a/9e/a2c40768df16c408f22430afb0a73e9d7e5f79c950884954649d1146b74d/tomli-2.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc", size = 278119, upload-time = "2026-10-07T12:22:32.601Z" }, + { url = "https://files.pythonhosted.org/packages/12/25/3c0cb485b98e9cfac495629b1c93c87ccf0b72fbe9d2689fd8fe62c6d5a3/tomli-2.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7", size = 286177, upload-time = "2026-10-07T12:22:33.745Z" }, + { url = "https://files.pythonhosted.org/packages/77/8b/0144c65f0e37e51c18d04ae15c21b19431c165002d0131fe9aa8b0b8b1e8/tomli-2.5.0-cp312-cp312-win32.whl", hash = "sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2", size = 102760, upload-time = "2026-10-07T12:22:34.887Z" }, + { url = "https://files.pythonhosted.org/packages/de/32/5d6d8f42fc9a05fce69354e00ff256484192f5f2fc9a2165718fa0de61ec/tomli-2.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7", size = 112722, upload-time = "2026-10-07T12:22:36.162Z" }, + { url = "https://files.pythonhosted.org/packages/30/65/df18032218db0fb9b769fb23c8039a051f15c811993995ea04c350273a32/tomli-2.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea", size = 109534, upload-time = "2026-10-07T12:22:37.296Z" }, + { url = "https://files.pythonhosted.org/packages/42/e5/51736d70da209350969e15aca5c5ab6e2ce1ea87a0a892a6c13aec172a86/tomli-2.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea", size = 163328, upload-time = "2026-10-07T12:22:38.373Z" }, + { url = "https://files.pythonhosted.org/packages/ec/55/086f80dab4ab497602644274e6dea7ec5dd0b4e262e443a8ad3bb7edee2d/tomli-2.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043", size = 162246, upload-time = "2026-10-07T12:22:39.673Z" }, + { url = "https://files.pythonhosted.org/packages/aa/eb/3ecc94459f3635c92321f4e7bde571323fdb2267c50e19e3188a281eae3b/tomli-2.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0", size = 272655, upload-time = "2026-10-07T12:22:41.08Z" }, + { url = "https://files.pythonhosted.org/packages/c0/d7/494fd1f0c37a621f1ad9975c2efadb523e8101f144ed6edb2e7fe64738f2/tomli-2.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b", size = 283595, upload-time = "2026-10-07T12:22:42.222Z" }, + { url = "https://files.pythonhosted.org/packages/70/51/bb8d62b1317e6640866f6949b2d5855e5300f2c99d46de1cd245570bba65/tomli-2.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066", size = 276253, upload-time = "2026-10-07T12:22:43.625Z" }, + { url = "https://files.pythonhosted.org/packages/66/f4/f46bd7f0763cd47de2db697dca9257c6a4adfd1a93b018cc75c8190ed5a8/tomli-2.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b", size = 283582, upload-time = "2026-10-07T12:22:44.983Z" }, + { url = "https://files.pythonhosted.org/packages/ac/03/70f2bcb2923a6db37818d917e124270a7f4cfd38ea576f5aa753a91c0ef5/tomli-2.5.0-cp313-cp313-win32.whl", hash = "sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68", size = 102628, upload-time = "2026-10-07T12:22:46.508Z" }, + { url = "https://files.pythonhosted.org/packages/dc/98/d52024bb5b0ff68b4f0d276d867f634c84a67319a7e9f6b7708a37742333/tomli-2.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc", size = 113301, upload-time = "2026-10-07T12:22:47.647Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f2/540db3a70572a8c23a28aba3e9c358ce0ffffbafc990905c1343aa265b31/tomli-2.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84", size = 109744, upload-time = "2026-10-07T12:22:48.925Z" }, + { url = "https://files.pythonhosted.org/packages/e4/49/caf6b307766eb9567664a8707e9d6be5fcc0e8903f18781c6677a60d80c7/tomli-2.5.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105", size = 162899, upload-time = "2026-10-07T12:22:50.088Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c8/68cfce773a2733a49c74f99d627fb461bd990756860099eac25617889585/tomli-2.5.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646", size = 162080, upload-time = "2026-10-07T12:22:51.558Z" }, + { url = "https://files.pythonhosted.org/packages/7e/b2/e5bb8651fdad593f670501a7d718b1a7f73f064d44dea15e04c04dfef45d/tomli-2.5.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b", size = 273380, upload-time = "2026-10-07T12:22:52.918Z" }, + { url = "https://files.pythonhosted.org/packages/8d/d2/9e2d7f8b1dfe0e2b34c245986ebd55c4c553ea4ce6c47c443b332673253f/tomli-2.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75", size = 283228, upload-time = "2026-10-07T12:22:54.173Z" }, + { url = "https://files.pythonhosted.org/packages/ba/df/ec7b876b7b1a2718bd74a3743c076fff565b04029ba33e8f61fac262739f/tomli-2.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb", size = 277189, upload-time = "2026-10-07T12:22:55.342Z" }, + { url = "https://files.pythonhosted.org/packages/7d/7b/e192d9eed0b9cb80da799f4d77052297fb9a2c3cc9b19f571f56ea88add6/tomli-2.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3", size = 283632, upload-time = "2026-10-07T12:22:56.735Z" }, + { url = "https://files.pythonhosted.org/packages/84/50/ff94454e75461d75623e47401ed323d65c10aab8fe9033242c20cd2fdf32/tomli-2.5.0-cp314-cp314-win32.whl", hash = "sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b", size = 103535, upload-time = "2026-10-07T12:22:58.084Z" }, + { url = "https://files.pythonhosted.org/packages/54/0b/bdacf05f963bd6026ebf6eeb0beda847d1d60e03e440725c64a4e08a0afd/tomli-2.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a", size = 114621, upload-time = "2026-10-07T12:22:59.2Z" }, + { url = "https://files.pythonhosted.org/packages/61/99/53f438fa6ae4f9d4ed0ddde3e7242b3bdc34b48c8f9948b72b9e9b127676/tomli-2.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3", size = 111572, upload-time = "2026-10-07T12:23:00.479Z" }, + { url = "https://files.pythonhosted.org/packages/b9/20/1f88f19427d380a40e90a770e087489eaafe4aeee070ae88ed2bbec00acd/tomli-2.5.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4", size = 171814, upload-time = "2026-10-07T12:23:01.914Z" }, + { url = "https://files.pythonhosted.org/packages/d0/56/cbe5079c9f9a54b9b3e27fc82f08f3cb36edee75561679f53d2380c801d6/tomli-2.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d", size = 171324, upload-time = "2026-10-07T12:23:03.18Z" }, + { url = "https://files.pythonhosted.org/packages/2b/30/1d53fd3b0f1cb3ba542e345ec32c26aefdddc4e829e4f3429af8a4f27782/tomli-2.5.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9", size = 297441, upload-time = "2026-10-07T12:23:04.345Z" }, + { url = "https://files.pythonhosted.org/packages/66/d9/0800acb6a111686f764c1b91ef15cc42a20a66a46013bb42220f1d2c61c1/tomli-2.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f", size = 307476, upload-time = "2026-10-07T12:23:05.671Z" }, + { url = "https://files.pythonhosted.org/packages/e8/63/30a8f3cd51b5bec37f04744bad0b0dc6160df84aad4f27b0e9283d66f221/tomli-2.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374", size = 296113, upload-time = "2026-10-07T12:23:07.202Z" }, + { url = "https://files.pythonhosted.org/packages/ab/18/0b9ffc597e69c5a1e20a7823cb60d54b39a9f54e91edcb8574f022186758/tomli-2.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442", size = 307725, upload-time = "2026-10-07T12:23:08.508Z" }, + { url = "https://files.pythonhosted.org/packages/ab/c7/18f8baae0b5607a60e8e19b4a7fedee43a8ff6458e3896dcbbadeeac9c22/tomli-2.5.0-cp314-cp314t-win32.whl", hash = "sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03", size = 108546, upload-time = "2026-10-07T12:23:09.956Z" }, + { url = "https://files.pythonhosted.org/packages/72/34/4cca9739254130627bde87500b3f2b512154fe2f278efa7e2a5e10ad4bcb/tomli-2.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1", size = 117814, upload-time = "2026-10-07T12:23:11.486Z" }, + { url = "https://files.pythonhosted.org/packages/7d/fb/afa530d47dd80a78fce43beac6bc6e00f84558eafcffbc6f37b21e80d056/tomli-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0", size = 115188, upload-time = "2026-10-07T12:23:12.728Z" }, + { url = "https://files.pythonhosted.org/packages/66/98/316fdc00f8c0939e6fe50461dd343c162d3ad51d1286eb25b7db54361d50/tomli-2.5.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc", size = 162775, upload-time = "2026-10-07T12:23:13.941Z" }, + { url = "https://files.pythonhosted.org/packages/c5/22/7b10fa5bb01c9539f53f69b619361b19350acc73657772ea7ac70ba309a8/tomli-2.5.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276", size = 161406, upload-time = "2026-10-07T12:23:15.215Z" }, + { url = "https://files.pythonhosted.org/packages/9c/e7/1a069d86dfd20f1f84f71c63faed9f83c1d890bc06c27d82dc7d888fb573/tomli-2.5.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52", size = 273855, upload-time = "2026-10-07T12:23:16.471Z" }, + { url = "https://files.pythonhosted.org/packages/ae/83/d1ef43d1687d092ab9c235455c76e6e709483b346b056f086095c7c263a5/tomli-2.5.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7", size = 284910, upload-time = "2026-10-07T12:23:18.166Z" }, + { url = "https://files.pythonhosted.org/packages/cc/05/f4d9cf7de61822ece0c3873f30d291e324911c71a378b8bfe5ced13fd9f5/tomli-2.5.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391", size = 277723, upload-time = "2026-10-07T12:23:19.355Z" }, + { url = "https://files.pythonhosted.org/packages/42/28/78262493141fa543151cf005760c3cb01d09fc28a11f993c05109902cb8c/tomli-2.5.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859", size = 285115, upload-time = "2026-10-07T12:23:20.698Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b9/e1dab9a30bcb677b5cc5cee810609cfd64f24306a3055767dd3fda00b1e0/tomli-2.5.0-cp315-cp315-win32.whl", hash = "sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb", size = 103475, upload-time = "2026-10-07T12:23:21.941Z" }, + { url = "https://files.pythonhosted.org/packages/4c/bd/31a3790c11d6ea95fcf5e6022ac0f8d0543c9b61120b730fc481bd43d3b4/tomli-2.5.0-cp315-cp315-win_amd64.whl", hash = "sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5", size = 114589, upload-time = "2026-10-07T12:23:23.098Z" }, + { url = "https://files.pythonhosted.org/packages/47/a2/4f6310fa699364f0e3af7ee3af88dddd9af066d33e716a0265bbe2b3ea84/tomli-2.5.0-cp315-cp315-win_arm64.whl", hash = "sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd", size = 111493, upload-time = "2026-10-07T12:23:24.233Z" }, + { url = "https://files.pythonhosted.org/packages/68/14/00853f0b396d8971107ae1921bb5b322fdee1650d2f16bf06c20adb532e5/tomli-2.5.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57", size = 171380, upload-time = "2026-10-07T12:23:25.512Z" }, + { url = "https://files.pythonhosted.org/packages/89/ad/fa6949321dadee46b27363974fb197b94c911c3b0f7a5fd26d7dc18fc2a0/tomli-2.5.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd", size = 170553, upload-time = "2026-10-07T12:23:26.855Z" }, + { url = "https://files.pythonhosted.org/packages/53/aa/3056c919eb3e084df3752b2cf5f865dcc04af0b27dba2f66d7b28af4633a/tomli-2.5.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01", size = 294428, upload-time = "2026-10-07T12:23:28.132Z" }, + { url = "https://files.pythonhosted.org/packages/96/b2/faeeb5d8769ea3832021d73e892c8391eae7b4b4f8b55a789127bd8b18a9/tomli-2.5.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f", size = 304909, upload-time = "2026-10-07T12:23:29.381Z" }, + { url = "https://files.pythonhosted.org/packages/f6/52/f094c09e73fb654b621716d019acb5d29bdfd1be01df80c281d552bda48d/tomli-2.5.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a", size = 293220, upload-time = "2026-10-07T12:23:30.608Z" }, + { url = "https://files.pythonhosted.org/packages/86/f5/0c30541078ca4b505ce3bd76ed931facbfec524dd018535d691d1af0a6d2/tomli-2.5.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142", size = 305705, upload-time = "2026-10-07T12:23:32.181Z" }, + { url = "https://files.pythonhosted.org/packages/05/74/590e7d19d6a118fc5cc5704ff358e21d95b8573f6b9443b1519f29ca8825/tomli-2.5.0-cp315-cp315t-win32.whl", hash = "sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5", size = 108432, upload-time = "2026-10-07T12:23:33.496Z" }, + { url = "https://files.pythonhosted.org/packages/1c/b8/63a75cfb27a17c38550e44025d3a6e7be64516fd8608a3b75703bf37d81b/tomli-2.5.0-cp315-cp315t-win_amd64.whl", hash = "sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571", size = 117281, upload-time = "2026-10-07T12:23:34.648Z" }, + { url = "https://files.pythonhosted.org/packages/72/01/e8c1debb2173973372934c68fc8e46170ab60ef23ed4592dff4dec6e8993/tomli-2.5.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7", size = 115069, upload-time = "2026-10-07T12:23:35.77Z" }, + { url = "https://files.pythonhosted.org/packages/60/3f/3e3f8fd0919249b0200c80fbc4f9a1e70be19f9883da71dfb7f8b9ab8aca/tomli-2.5.0-py3-none-any.whl", hash = "sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b", size = 14765, upload-time = "2026-10-07T12:23:36.875Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] diff --git a/rust-client/src/client.rs b/rust-client/src/client.rs index ea3d92bf28..6e03372865 100644 --- a/rust-client/src/client.rs +++ b/rust-client/src/client.rs @@ -247,6 +247,7 @@ impl Windmill { account: None, is_oauth: None, expires_at: None, + value_valid_until: None, labels: None, ws_specific: None, }, @@ -263,6 +264,7 @@ impl Windmill { value: Some(value), is_secret: None, description: None, + value_valid_until: None, labels: None, ws_specific: None, }, diff --git a/system_prompts/README.md b/system_prompts/README.md index 9051a71112..32c0c521c4 100644 --- a/system_prompts/README.md +++ b/system_prompts/README.md @@ -10,6 +10,10 @@ are built from it: `cli/src/guidance/skills.gen.ts`, next to the `AGENTS.wmill.md` template in `cli/src/guidance/core.ts`. +The workspace MCP server (`backend/windmill-api/src/mcp/session/`) is a third reader, one step +removed: it serves the global chat's own `get_instructions` texts and system prompt, rendered for +an external client by `npm run gen:mcp-session` in `frontend/`. Rerun that after `generate.py`. + Guidance written in one consumer only is guidance the other never gets. Write it here. ## Structure diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 5b8c3cbe8c..e8ccf219d6 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1054,7 +1054,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply 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. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`@windmill-labs/chat-sdk\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. @@ -1067,9 +1067,26 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) \`@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. +#### A saved agent: an \`agent\` runnable + +Chat 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: + +\`\`\`json +{ "chat": { "type": "agent", "path": "f/support/agent" } } +\`\`\` + +\`\`\`tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +\`\`\` + +\`runnable\` is the runnable's key; each runnable keeps its own conversations. The runnable takes \`user_message\` and \`memory_id\`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as \`backend.({ user_message })\` without \`memory_id\`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes \`previous_messages\` (chat messages) instead of \`memory_id\`, 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. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -1077,6 +1094,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | \`script\` | Reference to an existing workspace script by path. | | \`flow\` | Reference to an existing workspace flow by path. | | \`hubscript\` | Reference to a hub script by path. | +| \`agent\` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -1117,9 +1135,9 @@ An inline runnable runs as an ordinary Windmill job. \`import * as wmill from 'w Use 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. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When \`type\` is \`script\`, \`flow\`, or \`hubscript\`, 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. +When \`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 \`memory_id\` when the agent keeps managed memory or \`previous_messages\` when its memory is off. Before 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///\`) for a third-party service, and reference it instead of copying its logic. @@ -1128,7 +1146,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **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. -- **Path runnables (\`script\` / \`flow\` / \`hubscript\`) 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. +- **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. So 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. @@ -1227,7 +1245,7 @@ def main(user_id: str): 7. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow 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 }\`. `; export const PIPELINE_BASE = `# Data pipeline authoring @@ -1465,7 +1483,7 @@ write a secret you were not given: keep the placeholder. | \`ai_config\` | Providers, default and completion models, custom prompts, \`copilot_disabled\`. | | \`large_file_storage\` | Workspace object storage: \`{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }\`. | | \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | -| \`datatable\` | \`{ datatables: { : { database: { resource_type, resource_path? } } } }\`. Role permissions are \`datatable_permissions\`. | +| \`datatable\` | \`{ datatables: { : { database: { resource_type, resource_path } } } }\`, both required: \`resource_type: postgresql\` with \`resource_path\` a Postgres resource's path, or \`instance\`, or \`external_instance\` (Enterprise only), with \`resource_path\` the name of a database a superadmin set up. A fork's entry can instead be \`{ reference: { workspace_id, datatable } }\`, pointing at its parent's data table; keep it as is. \`main\` is the one scripts use by default. Role permissions are \`datatable_permissions\`. | | \`datatable_permissions\` | \`{ : { default_role, roles: { : [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/\`, \`g/\`, \`f/\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | | \`protection_rules\` | \`{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { : { catalog, storage, ... } } }\`. | diff --git a/system_prompts/auto-generated/skills/raw-app/SKILL.md b/system_prompts/auto-generated/skills/raw-app/SKILL.md index df5e7ece6a..f45b85402d 100644 --- a/system_prompts/auto-generated/skills/raw-app/SKILL.md +++ b/system_prompts/auto-generated/skills/raw-app/SKILL.md @@ -380,7 +380,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply 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. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential. @@ -393,9 +393,31 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) `@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. +#### A saved agent: an `agent` runnable + +Chat 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: + +In `raw_app.yaml`: + +```yaml +runnables: + chat: + type: agent + path: f/support/agent +``` + +```tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +``` + +`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, 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. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -403,6 +425,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | `script` | Reference to an existing workspace script by path. | | `flow` | Reference to an existing workspace flow by path. | | `hubscript` | Reference to a hub script by path. | +| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -444,9 +467,9 @@ An inline runnable runs as an ordinary Windmill job. `import * as wmill from 'wi Use 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. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When `type` is `script`, `flow`, or `hubscript`, 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. +When `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 `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off. Before 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///`) for a third-party service, and reference it instead of copying its logic. @@ -455,7 +478,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **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. -- **Path runnables (`script` / `flow` / `hubscript`) 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. +- **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. So 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. @@ -565,4 +588,4 @@ def main(user_id: str): 7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow 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 }`. diff --git a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md index 6216b92db6..21f02750db 100644 --- a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md +++ b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md @@ -44,7 +44,7 @@ write a secret you were not given: keep the placeholder. | `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. | | `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \| azure_blob_resource_path \| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. | | `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | -| `datatable` | `{ datatables: { : { database: { resource_type, resource_path? } } } }`. Role permissions are `datatable_permissions`. | +| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. | | `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | | `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. | diff --git a/system_prompts/base/raw-app.md b/system_prompts/base/raw-app.md index dc70d0b94d..69c03594db 100644 --- a/system_prompts/base/raw-app.md +++ b/system_prompts/base/raw-app.md @@ -139,7 +139,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply 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. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential. @@ -152,9 +152,38 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) `@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. +#### A saved agent: an `agent` runnable + +Chat 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: + + +In `raw_app.yaml`: + +```yaml +runnables: + chat: + type: agent + path: f/support/agent +``` + + +```json +{ "chat": { "type": "agent", "path": "f/support/agent" } } +``` + + +```tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +``` + +`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, 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. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -162,6 +191,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | `script` | Reference to an existing workspace script by path. | | `flow` | Reference to an existing workspace flow by path. | | `hubscript` | Reference to a hub script by path. | +| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -205,9 +235,9 @@ An inline runnable runs as an ordinary Windmill job. `import * as wmill from 'wi Use 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. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When `type` is `script`, `flow`, or `hubscript`, 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. +When `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 `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off. Before 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///`) for a third-party service, and reference it instead of copying its logic. @@ -216,7 +246,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **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. -- **Path runnables (`script` / `flow` / `hubscript`) 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. +- **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. So 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. @@ -345,4 +375,4 @@ def main(user_id: str): 7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow 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 }`. diff --git a/system_prompts/base/workspace-settings.md b/system_prompts/base/workspace-settings.md index ba4e863b85..0a2ae51866 100644 --- a/system_prompts/base/workspace-settings.md +++ b/system_prompts/base/workspace-settings.md @@ -39,7 +39,7 @@ write a secret you were not given: keep the placeholder. | `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. | | `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \| azure_blob_resource_path \| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. | | `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | -| `datatable` | `{ datatables: { : { database: { resource_type, resource_path? } } } }`. Role permissions are `datatable_permissions`. | +| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. | | `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | | `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. | diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 4fe0db6362..7606c7fd06 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.841.0", + "version": "1.849.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 28d7c1a372..70dec2bd09 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.841.0", + "version": "1.849.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index d3f2471c1f..d8b82c7f85 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.841.0 +1.849.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 7dd2fc2d48..211d9f0455 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.841.0", + "version": "1.849.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.841.0", + "version": "1.849.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index ea082c2268..abfe2607d0 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.841.0", + "version": "1.849.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts",