diff --git a/.agents/skills/ai-evals/SKILL.md b/.agents/skills/ai-evals/SKILL.md index ad334e2c6b..3acb0f7362 100644 --- a/.agents/skills/ai-evals/SKILL.md +++ b/.agents/skills/ai-evals/SKILL.md @@ -36,6 +36,10 @@ WMILL_AI_EVAL_BACKEND_URL=http://127.0.0.1: WMILL_AI_EVAL_BACKEND_WORKSPAC `WMILL_AI_EVAL_BACKEND_WORKSPACE=integration-tests` (or any existing workspace) to reuse one. The only side effect of a run is upserting an `f/evals/ai/` resource there. +- **Global mode creates its own workspace per attempt** and seeds the case's fixture in it, + because the session's tools run on the backend; it ignores + `WMILL_AI_EVAL_BACKEND_WORKSPACE` and needs a `postgresql` (native) worker for datatable + cases. `ai_evals/README.md` ("Global mode runs against a real workspace") lists the rest. - Provider keys live in `ai_evals/.env` and are auto-loaded by bun. The judge is a separate Anthropic call (default `claude-sonnet-4-6`) regardless of the model under test. diff --git a/.github/workflows/ai-evals-scheduled.yml b/.github/workflows/ai-evals-scheduled.yml index 2bd8cdb181..f92a90bae5 100644 --- a/.github/workflows/ai-evals-scheduled.yml +++ b/.github/workflows/ai-evals-scheduled.yml @@ -105,16 +105,25 @@ jobs: SQLX_OFFLINE: true CARGO_BUILD_JOBS: 12 RUSTFLAGS: "" - run: cargo build --features quickjs + # The global suite's hub cases search the hub embeddings index; its trigger cases + # write HTTP triggers, whose routes the feature mounts. + run: cargo build --features quickjs,embedding,http_trigger - name: Start Windmill working-directory: ./backend env: DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill RUST_LOG: info + # Each global case seeds resource types and waits until the search indexes them. + RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS: "2" run: | mkdir -p ../ai_evals/logs + # A model may test-run the script it drafts; the worker looks for bun at /usr/bin/bun, + # where setup-bun does not put it. + export BUN_PATH="$(command -v bun)" ./target/debug/windmill > ../ai_evals/logs/windmill.log 2>&1 & + # The global suite's datatable cases run SQL on the `postgresql` tag, a native worker's. + MODE=worker WORKER_GROUP=native PORT=8001 ./target/debug/windmill > ../ai_evals/logs/windmill-native.log 2>&1 & for i in $(seq 1 60); do curl -sf http://localhost:8000/api/version > /dev/null 2>&1 && break sleep 2 @@ -142,6 +151,8 @@ jobs: MODEL: ${{ matrix.model }} WMILL_AI_EVAL_BACKEND_URL: http://localhost:8000 WMILL_AI_EVAL_BACKEND_WORKSPACE: integration-tests + # Global fixtures whose user is not the admin are created in the backend's database. + WMILL_AI_EVAL_DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} GEMINI_API_KEY: ${{ secrets.GOOGLE_API_KEY }} diff --git a/.github/workflows/ai-evals-test.yml b/.github/workflows/ai-evals-test.yml index 4dd266c364..a34271ad17 100644 --- a/.github/workflows/ai-evals-test.yml +++ b/.github/workflows/ai-evals-test.yml @@ -3,8 +3,9 @@ name: AI Evals (global mode) # Smoke-tests the production global AI chat proxy/frontend execution path via # the ai_evals harness, one case across one cheap model per provider. Runs only # when the eval harness or the global chat code change, since each run makes real -# (paid) LLM calls. The backend is built from source purely as the AI proxy the -# harness routes model calls through; the global tools/drafts run in-process in +# (paid) LLM calls. The backend is built from source as the AI proxy the harness +# routes model calls through and as the server the global tools run on, in a +# workspace the harness creates per attempt; the chat itself runs in-process in # the Vitest bridge against production frontend code. To avoid spending on every # commit, the PR side triggers only when a PR is marked ready for review (out of # draft) — not on `synchronize` — plus push to main and manual dispatch. @@ -15,6 +16,7 @@ on: paths: - "ai_evals/**" - "backend/windmill-api/src/ai.rs" + - "backend/windmill-api/src/ai_session_tools/**" - "backend/windmill-ai/**" - "frontend/src/lib/components/copilot/**" # The eval harness runs production frontend code in-process; these are the @@ -29,6 +31,7 @@ on: paths: - "ai_evals/**" - "backend/windmill-api/src/ai.rs" + - "backend/windmill-api/src/ai_session_tools/**" - "backend/windmill-ai/**" - "frontend/src/lib/components/copilot/**" # The eval harness runs production frontend code in-process; these are the @@ -103,7 +106,11 @@ jobs: RUST_LOG: info run: | mkdir -p ../ai_evals/logs + # A model may test-run the script it drafts. The worker looks for bun at /usr/bin/bun, + # where setup-bun does not put it, and `//native` scripts run on a native worker's tag. + export BUN_PATH="$(command -v bun)" ./target/debug/windmill > ../ai_evals/logs/windmill.log 2>&1 & + MODE=worker WORKER_GROUP=native PORT=8001 ./target/debug/windmill > ../ai_evals/logs/windmill-native.log 2>&1 & echo "Waiting for Windmill to be ready..." for i in $(seq 1 60); do if curl -sf http://localhost:8000/api/version > /dev/null 2>&1; then @@ -137,6 +144,8 @@ jobs: env: WMILL_AI_EVAL_BACKEND_URL: http://localhost:8000 WMILL_AI_EVAL_BACKEND_WORKSPACE: integration-tests + # Global fixtures whose user is not the admin are created in the backend's database. + WMILL_AI_EVAL_DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill # Anthropic backs the haiku model. Google AI uses GEMINI_API_KEY. ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} diff --git a/.github/workflows/publish_extra.yml b/.github/workflows/publish_extra.yml index c33d806183..c1db4a654d 100644 --- a/.github/workflows/publish_extra.yml +++ b/.github/workflows/publish_extra.yml @@ -71,6 +71,7 @@ jobs: docker run -d --name windmill-extra-test \ -p 3001:3001 -p 3002:3002 -p 3003:3003 \ -e ENABLE_LSP=true \ + -e REQUIRE_SIGNED_LSP_REQUESTS=false \ -e ENABLE_MULTIPLAYER=true \ -e ENABLE_DEBUGGER=true \ -e DEBUGGER_PORT=3003 \ diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7805631ded..4e3f82e1bc 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.856.0" + ".": "1.858.0" } diff --git a/AGENTS.md b/AGENTS.md index 4c99482d43..a1fb608291 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,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). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `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). For MCP Apps clients the server adds tools of its own, defined in Rust (`session/views.rs`) rather than generated: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`session/card.html`; bump `CARD_URI` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. It exists only on the MCP side, so `core.ts` has nothing to mirror. +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/CHANGELOG.md b/CHANGELOG.md index f3a0451e5e..9ca4be3ba6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,39 @@ # Changelog +## [1.858.0](https://github.com/windmill-labs/windmill/compare/v1.857.0...v1.858.0) (2026-11-03) + + +### Features + +* resolved runs on home, an easier resolve action, and load fades ([#12167](https://github.com/windmill-labs/windmill/issues/12167)) ([1a6e544](https://github.com/windmill-labs/windmill/commit/1a6e5440ba02ef9ce9984dbc10d274f796b2703d)) + +## [1.857.0](https://github.com/windmill-labs/windmill/compare/v1.856.0...v1.857.0) (2026-11-03) + + +### Features + +* add a recently run panel to the workspace home ([#12105](https://github.com/windmill-labs/windmill/issues/12105)) ([d1a2c13](https://github.com/windmill-labs/windmill/commit/d1a2c13cf27f6e1ad920310b80ebede25acb4d98)) +* add home's folders, users and cards to the ai session context ([#12104](https://github.com/windmill-labs/windmill/issues/12104)) ([263088a](https://github.com/windmill-labs/windmill/commit/263088a8ac718823859e2909db70129b86f829e4)) +* name a materialized table after its script when the target names none ([#12157](https://github.com/windmill-labs/windmill/issues/12157)) ([116c902](https://github.com/windmill-labs/windmill/commit/116c90280e8fe59a6f0b1b186c109066c894165b)) +* publish a folder sub-path to the Hub as its own project ([#12081](https://github.com/windmill-labs/windmill/issues/12081)) ([23fbf1e](https://github.com/windmill-labs/windmill/commit/23fbf1edfe62339eaff2b576aeea32d81e37d97b)) +* upgrade the bundled DuckDB engine to 2.0.0 LTS ([#11924](https://github.com/windmill-labs/windmill/issues/11924)) ([3d0ca92](https://github.com/windmill-labs/windmill/commit/3d0ca92ef2ad98b1c3e5abe68a7a5b10c94f05df)) + + +### Bug Fixes + +* order ai sessions by their last turn instead of creation time ([#12147](https://github.com/windmill-labs/windmill/issues/12147)) ([b451e8e](https://github.com/windmill-labs/windmill/commit/b451e8edca6a8fb8de1de442879147a8163a7543)) +* parse runnable references once at the API run entry points ([#12153](https://github.com/windmill-labs/windmill/issues/12153)) ([088c83e](https://github.com/windmill-labs/windmill/commit/088c83e3f89bd151980e6363e556e69f6745bc03)) +* reserve the username anonymous used by logged-out visitors ([#12146](https://github.com/windmill-labs/windmill/issues/12146)) ([2aa6059](https://github.com/windmill-labs/windmill/commit/2aa6059e58e1cf4708ba65927d6e6338d364127a)) +* scope user deletion's group cleanup to its workspaces ([#12145](https://github.com/windmill-labs/windmill/issues/12145)) ([66be711](https://github.com/windmill-labs/windmill/commit/66be711dbd47a1ac8c066b8e1f323c982fa7e7bc)) + + +### Performance Improvements + +* load click-only features after the app shell paints ([#12161](https://github.com/windmill-labs/windmill/issues/12161)) ([3481adf](https://github.com/windmill-labs/windmill/commit/3481adf3dca9de201f729174da00184d72ad1829)) +* paint a snapshot of the last home in place of the boot splash ([#12158](https://github.com/windmill-labs/windmill/issues/12158)) ([0ac2b61](https://github.com/windmill-labs/windmill/commit/0ac2b6103452dc69201fe8a7d1107095e10fac97)) +* paint home from a persisted cache and the last confirmed user ([#12154](https://github.com/windmill-labs/windmill/issues/12154)) ([2d10518](https://github.com/windmill-labs/windmill/commit/2d105189b2e4b226ce78475790ca4f291781f9ca)) +* stop vite's preload helper from rescanning every link per dependency ([#12155](https://github.com/windmill-labs/windmill/issues/12155)) ([40cb945](https://github.com/windmill-labs/windmill/commit/40cb945a1acc96d4c0664fb2e91806785a260776)) + ## [1.856.0](https://github.com/windmill-labs/windmill/compare/v1.855.1...v1.856.0) (2026-11-02) diff --git a/ai_evals/README.md b/ai_evals/README.md index 67592daee4..95056fc955 100644 --- a/ai_evals/README.md +++ b/ai_evals/README.md @@ -170,13 +170,69 @@ chose in the artifact's version picker — which only `get_preview_status` repor Global initial fixtures can seed `workspace.variables` with `{ path, value, is_secret, description?, labels?, ws_specific? }` entries so cases can -read and edit variables that already exist in the workspace. The mock mirrors the real -`get_variable`, **decrypt-by-default included**: a secret's `value` is withheld only -when the caller explicitly passes `decryptSecret: false`, and omitting the flag returns -the decrypted value, exactly as against a real backend. The chat's read path passes -`decryptSecret: false`, so a case can verify it never invents a value it was not shown. -Seed a recognizable secret (the existing fixture uses `sk_live_do_not_leak_me`) and -assert it via `valueExcludes` to catch a leak. +read and edit variables that already exist in the workspace. Seed a recognizable secret +(the existing fixture uses `sk_live_do_not_leak_me`) and assert it via `valueExcludes` to +catch a leak. + +### Global mode runs against a real workspace + +The session's tools run on the backend, so each global attempt creates its own workspace on +the eval backend, seeds the fixture there through the API, and deletes it afterwards. What +that backend needs: + +- a worker serving the `postgresql` tag (the `native` group) for datatable fixtures and the + SQL tools, and `WMILL_AI_EVAL_DATATABLE_PG_URL` (default + `postgres://postgres:changeme@localhost:5432/postgres`) naming a Postgres the worker can + reach, where each datatable fixture gets a scratch database; +- a superadmin login (the default `admin@windmill.dev`), since it creates and deletes + workspaces. `WMILL_AI_EVAL_BACKEND_WORKSPACE` does not apply to global mode. A CE backend + allows two workspaces besides `admins`, so attempts past that wait for a free slot; +- `WMILL_AI_EVAL_DATABASE_URL`, the eval backend's own database, for fixtures whose `user` is + not the admin: the harness writes that user and a token of theirs there with `psql` (CE cannot create + users through the API), adds them to the workspace, and revokes the token afterwards; +- network access to the hub, which the hub tools reach through the backend, and the + `embedding` cargo feature, without which `search_hub_scripts` has no index to search; +- the `http_trigger` cargo feature, which mounts the routes HTTP trigger drafts are checked + against; +- `RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS` set low (CI uses 2): each attempt seeds the + hub's resource types into its workspace and waits until the resource type search sees them, + which takes up to that interval (60 s by default). + +#### Running the pipeline a case built + +A case with `validate.pipelineRun` runs the data pipeline the chat drafted, once the chat is +over. The harness deploys every pipeline node drafted under `f//`, waits for the +deployments, points each DuckLake at an empty catalog, runs the nodes that no other node +feeds, and waits for the asset triggers to run the rest. Then it runs the case's `queries` +(DuckDB, with the lake attached as `dl`) and checks their rows. A node that never ran fails +its check, so a downstream node whose `on` wiring is wrong cannot pass on the tables the +model's own test runs left behind. A node is started directly when no recorded read or +trigger ties it to another node's output, which also happens when the asset parser records a +read under another path than the write it matches; `maxRoots` caps how many nodes may start +that way. The run's outcome is part of the drafts the judge reads. + +The fixture's `workspace.objectStorage` gives the workspace an S3 storage holding its +`files`, and turns its `ducklakes` into catalogs on that storage. That needs more of the +backend: + +- the `duckdb`, `parquet` and `private` cargo features, and the DuckDB runner + (`backend/windmill-duckdb-ffi-internal/build_dev.sh`). `private` provides the S3 proxy + DuckDB reaches the storage through. A CE build without a license key is enough; +- an S3-compatible store with an existing bucket: `WMILL_AI_EVAL_S3_ENDPOINT` (e.g. + `http://localhost:9000`), `WMILL_AI_EVAL_S3_BUCKET` (default `evals`), + `WMILL_AI_EVAL_S3_ACCESS_KEY` / `WMILL_AI_EVAL_S3_SECRET_KEY` (default `minioadmin`) and + `WMILL_AI_EVAL_S3_REGION` (default `us-east-1`). Attempts share the bucket and seed the same + keys; each one's DuckLake data goes under `ai_evals_lakes//`, which nothing + deletes. MinIO, or `docker run -p 8333:8333 chrislusf/seaweedfs server -s3` (any key, and + `curl -X PUT localhost:8333/evals` creates the bucket), both work. + +Without `WMILL_AI_EVAL_S3_ENDPOINT` the run is skipped with a warning, and the case is +checked on its drafts and judge alone. + +A fixture's `jobs` become completed preview runs with the given id, path, args, logs and +outcome; `createdBy` is not reproduced. Its `resourceTypes` are created as workspace types, +alongside whatever types the instance already holds; a fixture that sets none gets the types +of an instance synced with the hub. `runtime.userAnswers` scripts the user's side of `askUserQuestion` in a global case: one answer per question, in the order they are asked, and a question past the last answer is @@ -213,24 +269,12 @@ recorded call to that tool may pass the field at all (an explicit `null` counts passing it). Use it for partial-update tools, where supplying a field the model could not have read is itself the failure — e.g. `write_variable.value` on a secret variable. -Global (and flow) initial fixtures can seed `workspace.datatables` so the -`list_datatables`, `get_datatable_table_schema`, and `exec_datatable_sql` tools -return seeded data during evals. Each entry is +Global initial fixtures can seed `workspace.datatables`. Each entry is `{ datatable_name, schemas: { : { : { columns, rows? } } } }`, plus `migrations_enabled: true` and `migrations: [{ timestamp, name, code_up, code_down?, applied? }]` -for a datatable that keeps its schema as migrations, which the migration tools then -read and write in memory. -SQL runs through a small in-memory engine (`datatableSqlEngine.ts`), not a real -database. Writes are **stateful within a case**: `CREATE`/`DROP`/`INSERT`/`UPDATE`/ -`DELETE` mutate the seeded datatable in place, so a later `list_datatables`, -`get_datatable_table_schema`, `SELECT`, or `information_schema` query reflects them -— this is what stops a model from looping when it re-queries to verify a write. -The engine is best-effort: `SELECT` returns all rows of the referenced (or first) -table with no WHERE filtering/projection/joins, `WHERE` on UPDATE/DELETE supports -`col = value` predicates joined by `AND`, and anything unparseable is a no-op -success. So validate datatable cases through tool-use and SQL-argument assertions -(`requiredToolsUsed`, `stringIncludesAnyOf`) — not through exact returned row -values. An empty/absent `datatables` seed makes `list_datatables` return `[]`, +for a datatable that keeps its schema as migrations. Each one becomes a real datatable of +the case's workspace, backed by its scratch database, so the datatable and SQL tools see +exactly what a query would. An absent `datatables` seed leaves the workspace with none, which is what the "no datatable configured" blocking cases rely on. Set `WMILL_AI_EVAL_DISABLE_ACTIVE_EDITOR_CONTEXT=1` to run those cases with diff --git a/ai_evals/adapters/frontend/aiProviderModels.vitest.ts b/ai_evals/adapters/frontend/aiProviderModels.vitest.ts deleted file mode 100644 index d5f097242a..0000000000 --- a/ai_evals/adapters/frontend/aiProviderModels.vitest.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - handleBenchmarkApiFetch, - hasBenchmarkApiHandler, - registerBenchmarkWorkspaceRunnables, - unregisterBenchmarkWorkspace -} from './mockBackend' - -// A global eval run registers its workspace under a mkdtemp path, so the workspace id the -// frontend interpolates into the models URL carries slashes. A handler that assumed a single -// path segment silently fell through to the network, and every run took the offline fallback. -const WORKSPACE = '/tmp/wmill-frontend-global-benchmark-abc123' -const RESOURCE = 'f/evals/global/anthropic_main' -const URL_FOR = (workspace: string) => - `http://benchmark.local/api/w/${workspace}/ai/proxy/models` - -describe('benchmark /ai/proxy/models', () => { - it('serves the seeded listing for a workspace id that is a path', async () => { - registerBenchmarkWorkspaceRunnables(WORKSPACE, { - aiProviders: [ - { path: RESOURCE, kind: 'anthropic', models: ['claude-sonnet-5', 'claude-opus-5'] } - ] - }) - try { - expect(hasBenchmarkApiHandler(URL_FOR(WORKSPACE))).toBe(true) - const response = handleBenchmarkApiFetch(URL_FOR(WORKSPACE), { - headers: { 'X-Resource-Path': RESOURCE, 'X-Provider': 'anthropic' } - }) - await expect(response.json()).resolves.toEqual({ - data: [{ id: 'claude-sonnet-5' }, { id: 'claude-opus-5' }] - }) - } finally { - unregisterBenchmarkWorkspace(WORKSPACE) - } - }) -}) diff --git a/ai_evals/adapters/frontend/core/global/evalPipelineEditors.ts b/ai_evals/adapters/frontend/core/global/evalPipelineEditors.ts new file mode 100644 index 0000000000..cbc3560cd0 --- /dev/null +++ b/ai_evals/adapters/frontend/core/global/evalPipelineEditors.ts @@ -0,0 +1,95 @@ +// The pipeline editors a session chat opens with open_preview(kind="pipeline"). In production +// PipelineEditorView mounts one per folder and registers its helpers once the canvas is up; +// here the same state and helper factory run without a canvas, so build_pipeline_node and +// edit_pipeline_node stage drafts exactly as they would in a session. +import { AssetService } from "$lib/gen"; +import { DATA_ASSET_KINDS } from "../../../../../frontend/src/lib/components/assets/AssetGraph/cascadeRun"; +import { createPipelineAiHelpers } from "../../../../../frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers"; +import { PipelineEditorState } from "../../../../../frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.svelte"; +import { resolveGraph } from "../../../../../frontend/src/lib/components/assets/AssetGraph/resolveGraph"; +import type { AssetGraphResponse } from "../../../../../frontend/src/lib/components/assets/AssetGraph/types"; +import type { + PipelineAIChatHelpers, + PipelineToolHelpers, +} from "../../../../../frontend/src/lib/components/copilot/chat/pipeline/core"; +import { normalizePipelineFolder } from "../../../../../frontend/src/lib/utils/pipelineFolder"; +import type { GlobalDraft } from "../../../../core/validators"; + +interface Editor { + state: PipelineEditorState; + helpers: PipelineAIChatHelpers; +} + +export interface EvalPipelineEditors { + /** Opens the folder's editor, as the session's pipeline preview tab mounts one. */ + open(folder: string): Promise; + folders(): string[]; + toolHelpers: PipelineToolHelpers; + /** The nodes the editors staged, as the script drafts a deploy of the pipeline writes. */ + drafts(): GlobalDraft[]; +} + +export function createEvalPipelineEditors(workspace: string): EvalPipelineEditors { + const editors = new Map(); + + async function open(folder: string): Promise { + const key = normalizePipelineFolder(folder); + if (editors.has(key)) return key; + const state = new PipelineEditorState(); + state.folder = key; + const base = (await AssetService.getAssetsGraph({ + workspace, + folder: key, + assetKinds: DATA_ASSET_KINDS.join(","), + })) as AssetGraphResponse; + const helpers = createPipelineAiHelpers({ + getFolder: () => key, + getWorkspace: () => workspace, + getResolvedGraph: () => + resolveGraph({ + base, + drafts: state.drafts, + liveBodyAssets: state.liveBodyAssets, + liveAnnotations: state.liveAnnotations, + // Filled from deployed sources by the view's prefetch; a fixture deploys none. + inferredWritesByPath: new Map(), + inferredReadsByPath: new Map(), + annotatedNativeKindsByPath: new Map(), + triggerDrafts: state.triggerDrafts.values(), + }), + getDrafts: () => state.drafts, + setDrafts: (next) => (state.drafts = next), + newDraftLocalId: state.newDraftLocalId, + hasTriggerDrafts: () => state.triggerDrafts.size > 0, + getTriggerDrafts: () => state.triggerDrafts, + setTriggerDraft: state.setTriggerDraft, + onForgetPath: (path) => { + state.forgetPath(path); + state.discardTriggerDraftsFor(path); + }, + }); + editors.set(key, { state, helpers }); + return key; + } + + return { + open, + folders: () => [...editors.keys()], + toolHelpers: { + pipelines: () => [...editors.values()].map((e) => e.helpers), + pipelineFolders: () => [...editors.keys()], + ensurePipeline: async (folder) => editors.get(normalizePipelineFolder(folder))?.helpers, + }, + drafts: () => + [...editors.values()].flatMap((e) => + [...e.state.drafts.values()].map((d) => ({ + type: "script", + path: d.script.path, + language: d.script.language, + summary: d.script.summary, + value: d.script.content, + isDraft: true, + })), + ), + }; +} diff --git a/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts b/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts index b6af04e6ec..555e914993 100644 --- a/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts +++ b/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts @@ -42,6 +42,7 @@ export interface EvalPreviewTabFixture { // by session id: global cases run concurrently, so a per-run registration would have every // case answering out of whichever run registered last. const panels = new Map(); +const pipelineOpeners = new Map Promise>(); const NO_SESSION = "No active session; the preview panel is unavailable."; @@ -62,9 +63,15 @@ setOpenPreviewHandler(async ({ sessionId, kind, path }) => { if (!target) { return `Error: ${kind} targets cannot be shown in the preview panel.`; } - // The pipeline branch of the production handler waits on an editor that only exists once - // a canvas mounts, which never happens here — a pipeline preview reports as any other. const result = owner.open(target); + const openPipeline = pipelineOpeners.get(sessionId!); + if (kind === "pipeline" && openPipeline) { + const folder = await openPipeline(path); + // Production's success text (sessionRuntime.svelte.ts): it names the node path prefix. + return `${ + result.status === "focused" ? "Focused the" : "Opened the" + } pipeline editor for folder "${folder}" in the side panel. build_pipeline_node, edit_pipeline_node and the other pipeline tools are now in your tool list: call them in your next step. Its nodes go at paths under \`f/${folder}/\` (e.g. \`f/${folder}/\`).`; + } return result.status === "focused" ? `A preview tab is already showing ${kind} "${path}" — focused it.` : `Opened ${kind} preview for ${path} in a new tab in the side panel.`; @@ -112,6 +119,8 @@ export function createEvalPreviewPanel(input: { tabs: EvalPreviewTabFixture[]; /** Artifact ids by name, from the artifact fixture seeding. */ artifactIds: Map; + /** Mounts the folder's pipeline editor and resolves to its normalized folder. */ + openPipeline: (folder: string) => Promise; }): EvalPreviewPanel { // Nothing durable to write back to, and no debounce worth waiting on. const owner = new SessionPreviewTabs( @@ -129,6 +138,7 @@ export function createEvalPreviewPanel(input: { if (requestedActive) owner.select(requestedActive); // Registered last: seeding throws on a malformed fixture, and this map outlives the run. panels.set(input.sessionId, owner); + pipelineOpeners.set(input.sessionId, input.openPipeline); return { openArtifact: (id, name, version) => { @@ -143,6 +153,7 @@ export function createEvalPreviewPanel(input: { }, dispose: () => { panels.delete(input.sessionId); + pipelineOpeners.delete(input.sessionId); }, }; } diff --git a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts index c648848387..330f23583d 100644 --- a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts +++ b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts @@ -1,6 +1,3 @@ -import { mkdtemp, rm } from "fs/promises"; -import { tmpdir } from "os"; -import { join } from "path"; import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs"; import type { AIProvider, OperatorSettings } from "$lib/gen/types.gen"; import { @@ -28,7 +25,10 @@ import { resolveResourceTypeSync } from "../../../../../frontend/src/lib/compone import { appendPlanModeInstructions } from "../../../../../frontend/src/lib/components/copilot/chat/planMode"; import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared"; import { createEvalPlanTools } from "./planModeTools"; +import { createEvalPipelineEditors } from "./evalPipelineEditors"; +import { pipelineTools } from "../../../../../frontend/src/lib/components/copilot/chat/pipeline/core"; import { UserDraft } from "../../../../../frontend/src/lib/userDraft.svelte"; +import { DraftService } from "$lib/gen"; import { createEvalArtifactHelpers, type SeededArtifact, @@ -38,15 +38,19 @@ import { type EvalPreviewPanel, type EvalPreviewTabFixture, } from "./evalPreviewTabs"; -import type { EvalCaseProfile, ModeRunContext } from "../../../../core/types"; +import type { + EvalCaseProfile, + ModeRunContext, + PipelineRunSpec, +} from "../../../../core/types"; import type { GlobalDraftState } from "../../../../core/validators"; import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings"; import { - registerBenchmarkWorkspaceRunnables, - seedBenchmarkDraft, + registerBenchmarkAiModels, unregisterBenchmarkWorkspaceRunnables, type BenchmarkWorkspaceRunnables, } from "../../mockBackend"; +import { createRealWorkspace } from "./realWorkspace"; import { runEval } from "../shared"; import type { TokenUsage, ToolCallDetail } from "../shared/types"; @@ -135,12 +139,13 @@ export interface GlobalEvalOptions { planMode?: boolean; // The user's rights, resolved as a session resolves them; unset keeps full access. profile?: EvalCaseProfile; + // Run the pipeline the chat drafted once it is over (`validate.pipelineRun`). + pipelineRun?: PipelineRunSpec; model?: string; maxIterations?: number; userAnswers?: string[]; provider?: AIProvider; backend: WindmillBackendSettings; - workspaceRoot?: string; // Artifacts the session already holds when the run starts. artifacts?: SeededArtifact[]; /** Tabs already open in the side panel, including any artifact version the reader pinned. */ @@ -153,18 +158,22 @@ export async function runGlobalEval( apiKey: string, options: GlobalEvalOptions, ): Promise { - const workspaceRoot = - options.workspaceRoot ?? - (await mkdtemp(join(tmpdir(), "wmill-frontend-global-benchmark-"))); + const realWorkspace = await createRealWorkspace({ + settings: options.backend, + caseId: options.runContext?.caseId ?? "global", + attempt: options.runContext?.attempt ?? 1, + fixtures: options.workspaceFixtures ?? {}, + user: options.user, + profile: options.profile, + }); + const workspaceRoot = realWorkspace.id; clearGlobalDrafts(workspaceRoot); - registerBenchmarkWorkspaceRunnables( + registerBenchmarkAiModels( workspaceRoot, - options.workspaceFixtures ?? {}, + options.workspaceFixtures?.aiProviders ?? [], ); - seedLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []); - // 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`. + // The eval workspace has no deploy rules, so they always pass. const roleAccess = options.profile && capabilitiesForRole({ @@ -187,6 +196,7 @@ export async function runGlobalEval( let panel: EvalPreviewPanel | undefined; try { + await seedLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []); const evalArtifacts = createEvalArtifactHelpers(options.artifacts); // Only a session chat has a side panel, so only it gets one here. Seeded tabs would // otherwise vanish without a word, and the case would measure an empty panel. @@ -201,11 +211,15 @@ export async function runGlobalEval( "This case sets runtime.profile, which only a session chat applies — set runtime.sessionChat: true on the case.", ); } + const pipelineEditors = options.sessionChat + ? createEvalPipelineEditors(workspaceRoot) + : undefined; if (options.sessionChat) { panel = createEvalPreviewPanel({ sessionId: evalArtifacts.sessionId, tabs: options.previewTabs ?? [], artifactIds: evalArtifacts.seededIds, + openPipeline: pipelineEditors!.open, }); } const model = options.model ?? "claude-haiku-4-5-20251001"; @@ -220,33 +234,47 @@ 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 = assembleGlobalSystemMessage(undefined, { - user: options.user, - previewTools: options.sessionChat ?? false, - access, - ...(heldInUse && { - sessionContext: { workspaceId: workspaceRoot, useMode: "role" as const }, - }), - }); + // Production adds the pipeline section and tools once a pipeline editor is open. + const assembleSystemMessage = () => + assembleGlobalSystemMessage(undefined, { + user: options.user, + previewTools: options.sessionChat ?? false, + access, + ...(heldInUse && { + sessionContext: { workspaceId: workspaceRoot, useMode: "role" as const }, + }), + pipelineFolders: pipelineEditors?.folders(), + }); + const baseSystemMessage = assembleSystemMessage(); const helpers = { ...evalArtifacts.helpers, + // A standalone chat has no session: the tools that behave differently in one (a pipeline + // node is built into the pipeline draft there, not written as a script) read this. + sessionId: options.sessionChat ? evalArtifacts.helpers.sessionId : undefined, access, ...(panel && { openArtifact: panel.openArtifact }), + ...pipelineEditors?.toolHelpers, }; + const pipelineToolNames = new Set(pipelineTools.map((t) => t.def.function.name)); const rawResult = await runEval({ userPrompt, systemMessage: baseSystemMessage, // Re-derived per request, as production's getter is: the instructions have to leave // the prompt when the plan is approved, or the model is still told it may not build // while the gate has already opened. - getSystemMessage: planMode - ? () => - planMode.isPlanModeActive() - ? appendPlanModeInstructions(baseSystemMessage, 0) - : baseSystemMessage - : undefined, + getSystemMessage: + planMode || pipelineEditors + ? () => { + const message = assembleSystemMessage(); + return planMode?.isPlanModeActive() + ? appendPlanModeInstructions(message, 0) + : message; + } + : undefined, isPlanModeActive: planMode?.isPlanModeActive, - isToolAvailable: planMode?.isToolAvailable, + isToolAvailable: (name) => + (!pipelineToolNames.has(name) || (pipelineEditors?.folders().length ?? 0) > 0) && + (planMode?.isToolAvailable?.(name) ?? true), userMessage: prepareGlobalUserMessage(userPrompt, [], { ...(injectActiveEditorContext ? { workspace: workspaceRoot } : {}), activePreview: panel?.activePreview(), @@ -257,14 +285,20 @@ export async function runGlobalEval( getGlobalEvalTools(options.sessionChat ?? false), access, ), + ...(pipelineEditors + ? filterSessionTools(pipelineTools as ProductionTool<{}>[], access) + : []), ...(planMode?.tools ?? []), ], helpers, apiKey, - getOutput: async () => ({ - ...(await collectGlobalDraftState(workspaceRoot)), - artifacts: evalArtifacts.snapshot(), - }), + getOutput: async () => { + const state = await collectGlobalDraftState(workspaceRoot); + return { + drafts: [...state.drafts, ...(pipelineEditors?.drafts() ?? [])], + artifacts: evalArtifacts.snapshot(), + }; + }, onAssistantMessageStart: options.runContext?.onAssistantMessageStart, onAssistantToken: options.runContext?.onAssistantChunk, onAssistantMessageEnd: options.runContext?.onAssistantMessageEnd, @@ -275,14 +309,27 @@ export async function runGlobalEval( model, workspace: workspaceRoot, provider: options.provider, - backend: options.backend, + backend: realWorkspace.backend, caseId: options.runContext?.caseId, attempt: options.runContext?.attempt, }, }); + const state: GlobalDraftState = options.pipelineRun + ? { + ...rawResult.output, + pipelineRun: await realWorkspace.runPipeline( + options.pipelineRun, + rawResult.output.drafts, + ), + } + : rawResult.output; + if (state.pipelineRun?.skipped) { + console.warn(`[ai_evals] pipeline run skipped: ${state.pipelineRun.skipped}`); + } + return { - state: rawResult.output, + state, success: rawResult.success, error: rawResult.error, assistantMessageCount: rawResult.iterations, @@ -299,9 +346,7 @@ export async function runGlobalEval( clearLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []); seedOperatorSettings(workspaceRoot, undefined); unregisterBenchmarkWorkspaceRunnables(workspaceRoot); - if (!options.workspaceRoot) { - await rm(workspaceRoot, { recursive: true, force: true }); - } + await realWorkspace.dispose(); } } @@ -331,17 +376,22 @@ async function collectGlobalDraftState( return { drafts: drafts as GlobalDraftState["drafts"] }; } -function seedLiveEditorDrafts( +async function seedLiveEditorDrafts( workspace: string, fixtures: GlobalLiveEditorDraftFixture[], -): void { +): Promise { for (const fixture of fixtures) { const itemKind = LIVE_EDITOR_ITEM_KINDS[fixture.type]; const storagePath = fixture.storagePath ?? fixture.effectivePath ?? ""; if (fixture.value !== undefined) { // Seed as a backend draft row, not an in-tab cell: a cell would shadow the // model's DB-backed edit when the output is read back via listGlobalDrafts. - seedBenchmarkDraft(workspace, itemKind, storagePath, fixture.value); + await DraftService.updateDraft({ + workspace, + kind: itemKind, + path: storagePath, + requestBody: { value: fixture.value, force: true }, + }); } UserDraft.setLiveEditorDraft({ workspace, @@ -382,6 +432,10 @@ function seedOperatorSettings( username: "", color: "", operator_settings: operatorSettings as OperatorSettings, + role: "operator", + capabilities: legacyOperatorCapabilities( + operatorSettings as OperatorSettings, + ), is_dev_workspace: false, disabled: false, }); diff --git a/ai_evals/adapters/frontend/core/global/pipelineRun.test.ts b/ai_evals/adapters/frontend/core/global/pipelineRun.test.ts new file mode 100644 index 0000000000..31812023d4 --- /dev/null +++ b/ai_evals/adapters/frontend/core/global/pipelineRun.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "bun:test"; +import { rootNodes } from "./pipelineRun"; + +describe("rootNodes", () => { + const paths = ["f/shop/ingest", "f/shop/daily"]; + const edges = [ + { runnable_path: "f/shop/ingest", asset_kind: "ducklake", asset_path: "main/orders", access_type: "w" as const }, + { runnable_path: "f/shop/daily", asset_kind: "ducklake", asset_path: "main/orders", access_type: "r" as const }, + ]; + + it("does not run a node that reads an upstream table directly, whatever it triggers on", () => { + const triggers = [ + { trigger_kind: "asset", asset_kind: "ducklake", asset_path: "main/order", runnable_path: "f/shop/daily" }, + ]; + expect(rootNodes(paths, triggers, edges)).toEqual(["f/shop/ingest"]); + }); + + it("keeps a node that reads its own materialized table a root", () => { + const selfRead = [ + { runnable_path: "f/shop/ingest", asset_kind: "ducklake", asset_path: "main/orders", access_type: "rw" as const }, + ]; + expect(rootNodes(["f/shop/ingest"], [], selfRead)).toEqual(["f/shop/ingest"]); + }); +}); diff --git a/ai_evals/adapters/frontend/core/global/pipelineRun.ts b/ai_evals/adapters/frontend/core/global/pipelineRun.ts new file mode 100644 index 0000000000..0744dba1b7 --- /dev/null +++ b/ai_evals/adapters/frontend/core/global/pipelineRun.ts @@ -0,0 +1,241 @@ +// Runs the pipeline a case built, on the case's own workspace, once the chat is over: its nodes +// are deployed, the nodes nothing upstream feeds are run, and the server's asset triggers run +// the rest. What a case then asserts is the data the pipeline produced, not how its source reads. +import type { GlobalDraft } from "../../../../core/validators"; +import type { + PipelineRunQuery, + PipelineRunResult, + PipelineRunSpec, +} from "../../../../core/types"; + +export type Api = (method: string, path: string, body?: unknown) => Promise; + +const DEFAULT_TIMEOUT_SECONDS = 300; +/** Past `LISTEN_NEW_EVENTS_INTERVAL_SEC` (10 s by default). */ +const PRODUCER_CACHE_EVICTION_MS = 12_000; +/** Deployments and the cascade are over once no job of the folder has been queued or running + * for this long. */ +const QUIET_MS = 5_000; + +interface GraphTrigger { + trigger_kind: string; + asset_kind?: string; + asset_path?: string; + runnable_path: string; +} + +interface GraphEdge { + runnable_path: string; + asset_kind: string; + asset_path: string; + access_type: "r" | "w" | "rw" | null; +} + +export async function runPipeline( + api: Api, + spec: PipelineRunSpec, + drafts: GlobalDraft[], + /** Points every DuckLake at an empty catalog. The model's test runs fill the lake it worked + * on, and a materialize that rewrites a table unchanged triggers nothing downstream. */ + emptyLakes: () => Promise, +): Promise { + const prefix = `f/${spec.folder}/`; + const nodes = drafts.filter( + (d) => + d.type === "script" && + d.path.startsWith(prefix) && + typeof d.value === "string" && + isPipelineNode(d.value), + ); + const result: PipelineRunResult = { nodes: [], queries: [] }; + if (nodes.length === 0) { + result.error = `no pipeline node was drafted under ${prefix}`; + return result; + } + const deadline = Date.now() + (spec.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000; + + for (const node of nodes) { + try { + await api("POST", "scripts/create", { + path: node.path, + summary: node.summary ?? "", + description: "", + content: node.value, + language: node.language ?? "duckdb", + }); + } catch (error) { + result.nodes.push({ path: node.path, deployError: String(error) }); + } + } + const deployed = nodes + .map((n) => n.path) + .filter((p) => !result.nodes.some((r) => r.path === p)); + // A failure past this point is the pipeline's outcome, not the harness's: it is recorded so + // the case keeps its drafts and judge. + try { + await runFromRoots(api, spec, deployed, deadline, emptyLakes, result); + } catch (error) { + result.error = String(error); + } + for (const query of spec.queries ?? []) { + result.queries.push(await runQuery(api, query)); + } + return result; +} + +async function runFromRoots( + api: Api, + spec: PipelineRunSpec, + deployed: string[], + deadline: number, + emptyLakes: () => Promise, + result: PipelineRunResult, +): Promise { + const prefix = `f/${spec.folder}/`; + // A node's asset triggers are recorded when its deployment job completes, not at create. + await waitForQuietQueue(api, spec.folder, deadline); + // Dispatch reads a per-process cache of which scripts produce what, which the model's test + // runs have filled; a deploy evicts it only at each process's next notify-event poll. + await new Promise((resolve) => setTimeout(resolve, PRODUCER_CACHE_EVICTION_MS)); + + const graph = await api("GET", `assets/graph?folder=${encodeURIComponent(spec.folder)}`); + const roots = rootNodes( + deployed, + (graph.triggers ?? []) as GraphTrigger[], + (graph.edges ?? []) as GraphEdge[], + ); + result.roots = roots; + await emptyLakes(); + const startedAt = new Date(Date.now() - 1_000).toISOString(); + for (const path of roots) { + await api("POST", `jobs/run/p/${path}`, {}); + } + await waitForQuietQueue(api, spec.folder, deadline).catch((error) => { + result.error = String(error); + }); + + const jobs: Array<{ + script_path?: string; + success?: boolean; + type?: string; + created_by?: string; + id: string; + }> = await api( + "GET", + // Deployed runs of this run only: the model's own test runs are previews. + `jobs/list?script_path_start=${encodeURIComponent(prefix)}&job_kinds=script` + + `&created_after=${encodeURIComponent(startedAt)}&per_page=100`, + ); + for (const path of deployed) { + // Newest first: the last run of the node is what its table holds. + const run = jobs.find((j) => j.script_path === path && j.type === "CompletedJob"); + const entry: PipelineRunResult["nodes"][number] = { path, ran: !!run }; + if (run) { + entry.success = run.success === true; + entry.triggeredBy = run.created_by; + if (!entry.success) { + const failed = await api("GET", `jobs_u/completed/get_result/${run.id}`).catch( + (error) => ({ error: String(error) }), + ); + entry.error = summarize(failed); + } + } + result.nodes.push(entry); + } +} + +function isPipelineNode(content: string): boolean { + return /^\s*(--|\/\/|#)\s*pipeline\b/m.test(content); +} + +/** + * Nodes no other node of the pipeline feeds: none of the assets they read or trigger on is + * written by another node. Reads count too, so a node that reads an upstream table but + * triggers on the wrong asset is never run directly, and fails as never having run. + */ +export function rootNodes( + paths: string[], + triggers: GraphTrigger[], + edges: GraphEdge[], +): string[] { + const inPipeline = new Set(paths); + const writers = new Map>(); + for (const e of edges) { + if (inPipeline.has(e.runnable_path) && (e.access_type === "w" || e.access_type === "rw")) { + const key = `${e.asset_kind}:${e.asset_path}`; + writers.set(key, (writers.get(key) ?? new Set()).add(e.runnable_path)); + } + } + const fedByAnother = (path: string, kind: string | undefined, assetPath: string | undefined) => + [...(writers.get(`${kind}:${assetPath}`) ?? [])].some((writer) => writer !== path); + return paths.filter( + (path) => + !triggers.some( + (t) => + t.trigger_kind === "asset" && + t.runnable_path === path && + fedByAnother(path, t.asset_kind, t.asset_path), + ) && + !edges.some( + (e) => + e.runnable_path === path && + (e.access_type === "r" || e.access_type === "rw") && + fedByAnother(path, e.asset_kind, e.asset_path), + ), + ); +} + +async function waitForQuietQueue(api: Api, folder: string, deadline: number): Promise { + let quietSince: number | undefined; + await waitUntil(deadline, `the jobs of f/${folder} to finish`, async () => { + const active: unknown[] = await api( + "GET", + `jobs/queue/list?script_path_start=${encodeURIComponent(`f/${folder}/`)}&per_page=10`, + ); + if (active.length > 0) { + quietSince = undefined; + return false; + } + quietSince ??= Date.now(); + return Date.now() - quietSince >= QUIET_MS; + }); +} + +async function runQuery(api: Api, query: PipelineRunQuery) { + const lake = query.ducklake ?? "main"; + const content = `ATTACH 'ducklake://${lake}' AS dl;\n${query.sql}`; + const result = await api("POST", "jobs/run_wait_result/preview", { + content, + language: "duckdb", + args: {}, + }).catch((error) => ({ error: String(error) })); + if (result && typeof result === "object" && !Array.isArray(result) && "error" in result) { + return { name: query.name, error: summarize(result) }; + } + return { name: query.name, rows: Array.isArray(result) ? result : [result] }; +} + +function summarize(value: unknown): string { + const error = + value && typeof value === "object" && "error" in value + ? (value as { error: unknown }).error + : value; + const text = + error && typeof error === "object" && "message" in error + ? String((error as { message: unknown }).message) + : typeof error === "string" + ? error + : JSON.stringify(error); + return text.length > 600 ? `${text.slice(0, 600)}…` : text; +} + +async function waitUntil( + deadline: number, + what: string, + done: () => Promise, +): Promise { + while (!(await done())) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((resolve) => setTimeout(resolve, 1_000)); + } +} diff --git a/ai_evals/adapters/frontend/core/global/realWorkspace.ts b/ai_evals/adapters/frontend/core/global/realWorkspace.ts new file mode 100644 index 0000000000..a1cb54387e --- /dev/null +++ b/ai_evals/adapters/frontend/core/global/realWorkspace.ts @@ -0,0 +1,786 @@ +// A real Windmill workspace per global-mode attempt. The session's tools run on the backend +// (`/api/w//ai_session_tools/`), so a case's fixture has to exist there: this creates +// the workspace, seeds it through the public API, and deletes it afterwards. +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { promisify } from "node:util"; +import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings"; +import type { EvalCaseProfile } from "../../../../core/types"; +import { + syncedResourceTypes, + type BenchmarkDatatableSeed, + type BenchmarkWorkspaceRunnables, +} from "../../mockBackend"; +import { WindmillBackendClient } from "../../windmillBackend"; +import { buildWorkspaceId } from "../../workspaceId"; +import type { GlobalUserFixture } from "./globalEvalRunner"; +import { runPipeline, type Api } from "./pipelineRun"; +import type { GlobalDraft } from "../../../../core/validators"; +import type { PipelineRunResult, PipelineRunSpec } from "../../../../core/types"; + +/** Workspace id -> the token its case runs as. Read by the adapter's fetch stub. */ +const activeWorkspaces = new Map(); +let adminToken: string | undefined; +let baseUrl: string | undefined; + +export function realWorkspaceRoute( + url: string, +): { url: string; token: string } | undefined { + if (!baseUrl || !adminToken || !url.startsWith("/api/")) return undefined; + const workspace = /^\/api\/w\/([^/?]+)/.exec(url)?.[1]; + const token = workspace + ? activeWorkspaces.get(decodeURIComponent(workspace)) + : activeWorkspaces.size > 0 + ? adminToken + : undefined; + return token ? { url: `${baseUrl}${url}`, token } : undefined; +} + +// Without the `postgresql` tag (a `native` worker group) datatable fixtures and SQL tools hang. +const DATATABLE_PG_URL = + process.env.WMILL_AI_EVAL_DATATABLE_PG_URL ?? + "postgres://postgres:changeme@localhost:5432/postgres"; +const ROOT_PG_RESOURCE = "$res:u/admin/ai_evals_pg_root"; +const RESOURCE_TYPE_INDEX_WAIT_MS = 120_000; +const WORKSPACE_SLOT_WAIT_MS = 30 * 60_000; +/** The eval backend's own database, where a fixture user that is not the admin is created. */ +const DATABASE_URL = process.env.WMILL_AI_EVAL_DATABASE_URL; +/** An S3-compatible store the eval backend reaches, for fixtures with `objectStorage`. */ +const S3_ENDPOINT = process.env.WMILL_AI_EVAL_S3_ENDPOINT; + +export interface RealWorkspace { + id: string; + /** Settings that make the model proxy reuse this workspace instead of creating another. */ + backend: WindmillBackendSettings; + /** Deploys and runs the pipeline the case drafted; see `validate.pipelineRun`. */ + runPipeline(spec: PipelineRunSpec, drafts: GlobalDraft[]): Promise; + dispose(): Promise; +} + +export async function createRealWorkspace(input: { + settings: WindmillBackendSettings; + caseId: string; + attempt: number; + fixtures: BenchmarkWorkspaceRunnables; + user?: GlobalUserFixture; + profile?: EvalCaseProfile; +}): Promise { + // Job ids are unique across the instance, and a case prompt can name a fixture job by its + // id: attempts that seed the same ids take turns, each holding them until it is deleted. + const releaseJobIds = await holdJobIds( + (input.fixtures.jobs ?? []).flatMap((job) => (job.id ? [job.id] : [])), + ); + const client = new WindmillBackendClient(input.settings); + baseUrl = input.settings.baseUrl; + const id = buildWorkspaceId(input.caseId, input.attempt); + const api = apiFor(client, id); + try { + adminToken = await client.getToken(); + await createWorkspace(api, id); + } catch (error) { + releaseJobIds(); + throw error; + } + const scratchDbs: string[] = []; + let userToken: string | undefined; + const dispose = async () => { + activeWorkspaces.delete(id); + if (input.user && DATABASE_URL) { + await psql(`DELETE FROM token WHERE label = ${literal(tokenLabel(id))}`).catch( + () => undefined, + ); + } + const workers = (input.fixtures.workers ?? []).map((w) => literal(w.worker)); + if (workers.length) { + await psql(`DELETE FROM worker_ping WHERE worker IN (${workers.join(", ")})`).catch( + () => undefined, + ); + } + for (const database of scratchDbs) { + await sql( + api, + ROOT_PG_RESOURCE, + `DROP DATABASE IF EXISTS "${database}" WITH (FORCE)`, + ).catch(() => undefined); + } + await api("DELETE", `/workspaces/delete/${id}`).catch(() => undefined); + releaseJobIds(); + }; + try { + activeWorkspaces.set(id, adminToken); + userToken = await seedUser(api, id, input.user, input.profile); + const storage = await seed(api, id, input.fixtures, scratchDbs); + activeWorkspaces.set(id, userToken ?? adminToken); + return { + id, + backend: { ...input.settings, workspaceOverride: id }, + runPipeline: async (spec, drafts) => + storage === "runnable" + ? runPipeline(api, spec, drafts, () => + configureLakes(api, id, input.fixtures.ducklakes ?? [], scratchDbs, "run"), + ) + : { + skipped: + storage === "unconfigured" + ? "WMILL_AI_EVAL_S3_ENDPOINT is not set, so the workspace has no object storage to run the pipeline on" + : "the fixture seeds no objectStorage", + nodes: [], + queries: [], + }, + dispose, + }; + } catch (error) { + await dispose(); + throw error; + } +} + +/** Job id -> the turn of the last attempt that asked for it. */ +const jobIdTurns = new Map>(); + +async function holdJobIds(ids: string[]): Promise<() => void> { + let release!: () => void; + const turn = new Promise((resolve) => (release = resolve)); + const previous = ids.map((id) => jobIdTurns.get(id) ?? Promise.resolve()); + for (const id of ids) jobIdTurns.set(id, turn); + await Promise.all(previous); + return release; +} + +function apiFor(client: WindmillBackendClient, workspace: string): Api { + return async (method, path, body) => { + const scoped = path.startsWith("/") ? path : `/w/${workspace}/${path}`; + const response = await client.request(scoped, { + method, + ...(body instanceof FormData || body instanceof Blob + ? { body } + : body === undefined + ? {} + : { + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }), + }); + const text = await response.text(); + if (!response.ok) { + throw new Error(`${method} ${scoped}: ${response.status} ${text}`); + } + try { + return JSON.parse(text); + } catch { + return text; + } + }; +} + +// CE caps the number of workspaces, so a run with more concurrent attempts than slots waits. +async function createWorkspace(api: Api, id: string): Promise { + const deadline = Date.now() + WORKSPACE_SLOT_WAIT_MS; + for (;;) { + try { + await api("POST", "/workspaces/create", { id, name: id }); + return; + } catch (error) { + if ( + !String(error).includes("maximum number of workspaces") || + Date.now() > deadline + ) { + throw error; + } + await new Promise((resolve) => setTimeout(resolve, 5_000)); + } + } +} + +// The admin running the eval is `admin` in every workspace it creates. Any other identity is a +// real member, so the backend enforces its rights as it would for that user; CE cannot create +// users, so there the case runs as the admin, with the prompt alone describing the fixture user. +async function seedUser( + api: Api, + workspace: string, + user: GlobalUserFixture | undefined, + profile: EvalCaseProfile | undefined, +): Promise { + const username = user?.username ?? "admin"; + const writable = new Set(user?.folders ?? []); + const readable = new Set([...(user?.folders_read ?? []), ...writable]); + const asAdmin = username === "admin" && (user?.is_admin ?? true); + let token: string | undefined; + if (!asAdmin) { + // CE cannot create users through the API, so the user and a token of theirs are written + // straight into the instance database, as the backend's own tests do. The workspace + // membership still goes through the API. + const email = `${username}@ai-evals.windmill.dev`; + token = `aievals${randomUUID().replace(/-/g, "")}`; + await psql( + `INSERT INTO password (email, password_hash, login_type, super_admin, verified, name, username) + VALUES (${literal(email)}, 'ai-evals-no-login', 'password', false, true, ${literal(username)}, + ${literal(username)}) + ON CONFLICT (email) DO UPDATE SET username = EXCLUDED.username; + INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256(${literal(token)}::bytea), 'hex'), ${literal(token.slice(0, 10))}, + ${literal(token)}, ${literal(email)}, ${literal(tokenLabel(workspace))}, false);`, + ); + await api("POST", "workspaces/add_user", { + email, + is_admin: user?.is_admin ?? false, + operator: profile?.operator ?? false, + }); + } + if (profile?.operator && profile.operatorSettings) { + await api("POST", "workspaces/operator_settings", profile.operatorSettings); + } + for (const folder of readable) { + await api("POST", "folders/create", { + name: folder, + ...(asAdmin ? {} : { extra_perms: { [`u/${username}`]: writable.has(folder) } }), + }); + } + return token; +} + +/** Seeds every fixture kind, recording the scratch databases it creates; returns whether a + * pipeline can run on the workspace's storage. */ +async function seed( + api: Api, + workspace: string, + fixtures: BenchmarkWorkspaceRunnables, + scratchDbs: string[], +): Promise<"runnable" | "unconfigured" | "none"> { + // A fixture that sets no `resourceTypes` stands for an instance synced with the hub, + // which an eval backend usually is not; the types the instance already holds stay its own. + const held = new Set(await api("GET", "resources/type/listnames")); + const resourceTypes = (fixtures.resourceTypes ?? syncedResourceTypes()).filter( + (rt) => !held.has(rt.name), + ); + for (const rt of resourceTypes) { + await api("POST", "resources/type/create", { + name: rt.name, + schema: rt.schema ?? {}, + description: rt.description ?? "", + }); + } + // The resource type search reads an index the server rebuilds every + // RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS: a case must not start before it holds them. + const last = resourceTypes[resourceTypes.length - 1]?.name; + for (const deadline = Date.now() + RESOURCE_TYPE_INDEX_WAIT_MS; last; ) { + const found: { name: string }[] = await api( + "GET", + `embeddings/query_resource_types?text=${encodeURIComponent(last)}&limit=10`, + ); + if (found.some((rt) => rt.name === last)) break; + if (Date.now() > deadline) { + throw new Error(`the resource type search never found the seeded "${last}"`); + } + await new Promise((resolve) => setTimeout(resolve, 2_000)); + } + for (const group of fixtures.groups ?? []) { + await api("POST", "groups/create", { name: group.name, summary: group.summary }); + // A fixture names members who are not users of the instance; a membership row needs none. + for (const member of group.members ?? []) { + await psql( + `INSERT INTO usr_to_group (workspace_id, usr, group_) + VALUES (${literal(workspace)}, ${literal(member)}, ${literal(group.name)})`, + "This fixture seeds group members", + ); + } + } + for (const folder of fixtures.folders ?? []) { + await api("POST", "folders/create", { + name: folder.name, + summary: folder.summary, + owners: folder.owners ?? [], + extra_perms: folder.extra_perms ?? {}, + }); + } + for (const script of fixtures.scripts ?? []) { + await api("POST", "scripts/create", { + path: script.path, + summary: script.summary, + description: script.description ?? "", + content: script.content, + language: script.language, + schema: script.schema ?? {}, + }); + } + for (const flow of fixtures.flows ?? []) { + await api("POST", "flows/create", { + path: flow.path, + summary: flow.summary, + description: flow.description ?? "", + value: flow.value, + schema: flow.schema ?? {}, + }); + } + for (const app of fixtures.apps ?? []) { + await seedApp(api, app); + } + for (const variable of fixtures.variables ?? []) { + await api("POST", "variables/create", { + path: variable.path, + value: variable.value, + is_secret: variable.is_secret, + description: variable.description ?? "", + ...(variable.labels ? { labels: variable.labels } : {}), + }); + } + for (const resource of fixtures.resources ?? []) { + await api("POST", "resources/create", { + path: resource.path, + resource_type: resource.resource_type, + value: resource.value ?? {}, + description: resource.description ?? "", + }); + } + await seedAiProviders(api, fixtures.aiProviders ?? []); + for (const job of fixtures.jobs ?? []) { + await seedJob(api, workspace, job); + } + for (const schedule of fixtures.schedules ?? []) { + await api("POST", "schedules/create", { + path: schedule.path, + schedule: schedule.schedule, + timezone: "UTC", + script_path: schedule.script_path, + is_flow: schedule.is_flow ?? false, + args: {}, + enabled: schedule.enabled ?? true, + summary: schedule.summary, + }); + } + await seedWorkers(fixtures.workers ?? []); + const storage = !fixtures.objectStorage ? "none" : S3_ENDPOINT ? "runnable" : "unconfigured"; + if (storage === "unconfigured") { + console.warn( + `[ai_evals] ${workspace}: the fixture seeds objectStorage but WMILL_AI_EVAL_S3_ENDPOINT is not set; its pipeline will not run.`, + ); + } + if (storage === "runnable") { + await seedObjectStorage(api, workspace, fixtures, scratchDbs); + } else if (fixtures.ducklakes?.length) { + await api("POST", "workspaces/edit_ducklake_config", { + settings: { + ducklakes: Object.fromEntries( + fixtures.ducklakes.map((name) => [ + name, + { + catalog: { resource_type: "instance", resource_path: `${workspace}_${name}` }, + storage: { storage: null, path: name }, + }, + ]), + ), + }, + }); + } + await seedDataMetrics(api, fixtures.dataMetrics ?? []); + const datatables = fixtures.datatables ?? []; + if (datatables.length > 1) { + throw new Error("A global fixture seeds at most one datatable."); + } + if (datatables[0]) { + scratchDbs.push(await seedDatatable(api, workspace, datatables[0])); + } + return storage; +} + +// Every attempt shares the bucket: seeded objects are the same for every attempt of a case, and +// each DuckLake gets its own catalog database and data path, so attempts never see each +// other's tables. +async function seedObjectStorage( + api: Api, + workspace: string, + fixtures: BenchmarkWorkspaceRunnables, + scratchDbs: string[], +): Promise { + await api("POST", "resources/create", { + path: "u/admin/ai_evals_s3", + resource_type: "s3", + value: { + bucket: process.env.WMILL_AI_EVAL_S3_BUCKET ?? "evals", + region: process.env.WMILL_AI_EVAL_S3_REGION ?? "us-east-1", + // The resource takes the host alone; `useSSL` carries the scheme. + endPoint: S3_ENDPOINT!.replace(/^https?:\/\//, ""), + useSSL: S3_ENDPOINT!.startsWith("https:"), + accessKey: process.env.WMILL_AI_EVAL_S3_ACCESS_KEY ?? "minioadmin", + secretKey: process.env.WMILL_AI_EVAL_S3_SECRET_KEY ?? "minioadmin", + pathStyle: true, + }, + }); + await api("POST", "workspaces/edit_large_file_storage_config", { + large_file_storage: { + type: "S3Storage", + s3_resource_path: "$res:u/admin/ai_evals_s3", + public_resource: false, + advanced_permissions: null, + secondary_storage: {}, + }, + }); + for (const file of fixtures.objectStorage?.files ?? []) { + await api( + "POST", + `job_helpers/upload_s3_file?file_key=${encodeURIComponent(file.key)}`, + new Blob([file.content], { type: "application/octet-stream" }), + ); + } + await configureLakes(api, workspace, fixtures.ducklakes ?? [], scratchDbs, "chat"); +} + +/** Points each named DuckLake at a new, empty catalog database and data path. */ +async function configureLakes( + api: Api, + workspace: string, + names: string[], + scratchDbs: string[], + generation: string, +): Promise { + if (!names.length) return; + await ensureRootPgResource(api); + const ducklakes: Record = {}; + for (const name of names) { + // The workspace id ends with the attempt and a random suffix: keep that end. + const database = `lake_${generation}_${name}_${workspace.replace(/-/g, "_").slice(-40)}`.slice( + 0, + 63, + ); + await sql(api, ROOT_PG_RESOURCE, `CREATE DATABASE "${database}"`); + scratchDbs.push(database); + const path = `u/admin/ai_evals_lake_${name}_${generation}`; + await api("POST", "resources/create", { + path, + resource_type: "postgresql", + value: pgResource(database), + }); + ducklakes[name] = { + catalog: { resource_type: "postgresql", resource_path: path }, + storage: { storage: null, path: `ai_evals_lakes/${workspace}/${generation}/${name}` }, + }; + } + await api("POST", "workspaces/edit_ducklake_config", { settings: { ducklakes } }); +} + +function pgResource(dbname: string) { + const root = new URL(DATATABLE_PG_URL); + return { + host: root.hostname, + port: Number(root.port || 5432), + user: decodeURIComponent(root.username), + password: decodeURIComponent(root.password), + dbname, + sslmode: root.searchParams.get("sslmode") ?? "disable", + }; +} + +async function ensureRootPgResource(api: Api): Promise { + const exists = await api("GET", "resources/exists/u/admin/ai_evals_pg_root"); + if (exists === true) return; + const root = new URL(DATATABLE_PG_URL); + await api("POST", "resources/create", { + path: "u/admin/ai_evals_pg_root", + resource_type: "postgresql", + value: pgResource(root.pathname.slice(1) || "postgres"), + }); +} + +async function seedApp( + api: Api, + app: NonNullable[number], +): Promise { + const policy = { execution_mode: "publisher", triggerables_v2: {} }; + if (app.rawApp === false) { + await api("POST", "apps/create", { + path: app.path, + summary: app.summary, + value: app.value, + policy, + }); + return; + } + const form = new FormData(); + form.append( + "app", + JSON.stringify({ + path: app.path, + summary: app.summary, + value: { ...app.value, data: app.value.data ?? { tables: [] } }, + policy, + }), + ); + form.append("js", ""); + form.append("css", ""); + await api("POST", "apps/create_raw", form); +} + +async function seedAiProviders( + api: Api, + providers: NonNullable, +): Promise { + if (!providers.length) return; + const config: Record = {}; + let defaultModel: { model: string; provider: string } | undefined; + for (const provider of providers) { + await api("POST", "resources/create", { + path: provider.path, + resource_type: provider.kind, + value: { + api_key: "ai-evals-placeholder", + ...(provider.base_url ? { base_url: provider.base_url } : {}), + }, + }); + const models = provider.configuredModels ?? provider.models ?? []; + config[provider.kind] = { resource_path: provider.path, models }; + if (provider.isDefault && models[0]) { + defaultModel = { model: models[0], provider: provider.kind }; + } + } + await api("POST", "workspaces/edit_copilot_config", { + providers: config, + ...(defaultModel ? { default_model: defaultModel } : {}), + }); +} + +// A completed run with the fixture's id, path, args, logs and outcome. It is a preview job run +// by the admin, so `createdBy` and a `script` job kind are not reproduced. +async function seedJob( + api: Api, + workspace: string, + job: NonNullable[number], +): Promise { + const args = job.args ?? {}; + const id = job.id ?? randomUUID(); + const state = job.state ?? "completed"; + if (state === "suspended") { + // A flow parked on an approval step: its first step suspends, as the fixture flow's does. + await api("POST", `jobs/run/f/${job.scriptPath}?job_id=${id}`, args); + await waitFor(`run ${id} to suspend`, async () => { + const run = await api("GET", `jobs_u/get/${id}?no_logs=true`); + return (run.flow_status?.modules ?? []).some( + (module: { type?: string }) => module.type === "WaitingForEvents", + ); + }); + } else if (state === "queued") { + // Stays queued only on a tag no worker of the eval backend serves, as the fixture's does. + await api("POST", `jobs/run/preview?job_id=${id}`, { + content: "export async function main() {}", + language: "bun", + path: job.scriptPath, + args, + tag: job.tag, + }); + } else if (state === "completed") { + const content = [ + `export async function main(${Object.keys(args).join(", ")}) {`, + ` console.log(${JSON.stringify(job.logs ?? "")});`, + job.success === false + ? ` throw new Error(${JSON.stringify(lastLine(job.logs) ?? "Job failed")});` + : ` return ${JSON.stringify(job.result ?? null)};`, + `}`, + ].join("\n"); + await api("POST", `jobs/run_wait_result/preview?job_id=${id}`, { + content, + language: "bun", + path: job.scriptPath, + args, + }).catch((error) => { + // A failing fixture run answers with its error, which is the point. + if (job.success !== false) throw error; + }); + } else { + throw new Error(`A ${state} fixture run cannot be seeded on a real backend.`); + } + // Who ran it, when and where cannot be asked of the API: the run is rewritten to match. + if ( + job.createdBy === undefined && + job.createdMinutesAgo === undefined && + job.durationMs === undefined && + job.tag === undefined && + job.schedulePath === undefined && + job.label === undefined + ) { + return; + } + const createdAt = + job.createdMinutesAgo === undefined + ? "created_at" + : `now() - interval '${Number(job.createdMinutesAgo)} minutes'`; + await psql( + `UPDATE v2_job SET created_at = ${createdAt}, + created_by = COALESCE(${literal(job.createdBy)}, created_by), + tag = COALESCE(${literal(job.tag)}, tag), + labels = COALESCE(${job.label === undefined ? "NULL" : `ARRAY[${literal(job.label)}]`}, labels) + ${job.schedulePath ? `, trigger = ${literal(job.schedulePath)}, trigger_kind = 'schedule'` : ""} + WHERE id = ${literal(id)} AND workspace_id = ${literal(workspace)}; + UPDATE v2_job_queue q SET created_at = j.created_at, scheduled_for = j.created_at + FROM v2_job j WHERE q.id = j.id AND q.id = ${literal(id)}; + UPDATE v2_job_completed c SET started_at = j.created_at, + duration_ms = COALESCE(${literal(job.durationMs)}, c.duration_ms), + completed_at = j.created_at + make_interval(secs => COALESCE(${literal(job.durationMs)}, c.duration_ms) / 1000.0) + FROM v2_job j WHERE c.id = j.id AND c.id = ${literal(id)};`, + "This fixture seeds who ran a run, when or where", + ); +} + +/** Fixture workers, listed beside the instance's own until the attempt ends. */ +async function seedWorkers( + workers: NonNullable, +): Promise { + // ponytail: rows are instance-wide, so concurrent attempts of one case share them. + for (const worker of workers) { + await psql( + `INSERT INTO worker_ping (worker, worker_instance, ping_at, started_at, ip, jobs_executed, + custom_tags, worker_group) + VALUES (${literal(worker.worker)}, ${literal(worker.worker)}, + now() - interval '${Number(worker.lastPingSecondsAgo ?? 0)} seconds', now(), 'ai-evals', + ${Number(worker.jobs_executed ?? 0)}, + ARRAY[${(worker.custom_tags ?? []).map(literal).join(", ")}]::varchar[], + ${literal(worker.worker_group)}) + ON CONFLICT (worker) DO UPDATE SET ping_at = EXCLUDED.ping_at`, + "This fixture seeds workers", + ); + } +} + +async function waitFor(what: string, done: () => Promise): Promise { + for (const deadline = Date.now() + 60_000; !(await done()); ) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((resolve) => setTimeout(resolve, 500)); + } +} + +function lastLine(text: string | undefined): string | undefined { + return text?.trim().split("\n").pop(); +} + +// Metrics are catalogued from a DuckDB node's annotations when it is deployed. +async function seedDataMetrics( + api: Api, + metrics: NonNullable, +): Promise { + const byScript = new Map(); + for (const metric of metrics) { + const key = `${metric.script_path}\n${metric.table_path}`; + byScript.set(key, [...(byScript.get(key) ?? []), metric]); + } + for (const [key, entries] of byScript) { + const [scriptPath, tablePath] = key.split("\n"); + // `/.
`, as the catalog canonicalizes `ducklake:///
`. + const [lake, qualified] = tablePath.split("/"); + const table = qualified.split(".").pop(); + const lines = [`-- materialize ducklake://${lake}/${table}`]; + for (const metric of entries) { + lines.push( + metric.kind === "measure" + ? `-- measure ${metric.name} = ${metric.expr}${metric.filter ? ` where ${metric.filter}` : ""}` + : `-- dimension ${metric.name} = ${metric.expr}`, + ); + } + lines.push("SELECT 1"); + await api("POST", "scripts/create", { + path: scriptPath, + summary: "", + description: "", + content: lines.join("\n"), + language: "duckdb", + schema: {}, + }); + } +} + +async function seedDatatable( + api: Api, + workspace: string, + seed: BenchmarkDatatableSeed, +): Promise { + const database = `${workspace.replace(/-/g, "_")}_dt`.slice(0, 63); + await ensureRootPgResource(api); + await sql(api, ROOT_PG_RESOURCE, `CREATE DATABASE "${database}"`); + await api("POST", "resources/create", { + path: "u/admin/ai_evals_datatable", + resource_type: "postgresql", + value: pgResource(database), + }); + await api("POST", "workspaces/edit_datatable_config", { + settings: { + datatables: { + [seed.datatable_name]: { + database: { resource_type: "postgresql", resource_path: "u/admin/ai_evals_datatable" }, + }, + }, + }, + }); + // A new datatable keeps its schema as migrations; a fixture says when this one does not. + if (!seed.migrations_enabled) { + await api("POST", `workspaces/disable_datatable_migrations/${seed.datatable_name}`); + } + const target = `datatable://${seed.datatable_name}`; + for (const migration of seed.migrations ?? []) { + await api("POST", `workspaces/upsert_datatable_migration/${seed.datatable_name}`, { + timestamp: migration.timestamp, + name: migration.name, + code_up: migration.code_up, + ...(migration.code_down ? { code_down: migration.code_down } : {}), + }); + if (migration.applied) { + await api( + "POST", + `workspaces/run_datatable_migrations/${seed.datatable_name}?only=${migration.timestamp}`, + ); + } + } + const statements: string[] = []; + for (const [schema, tables] of Object.entries(seed.schemas)) { + statements.push(`CREATE SCHEMA IF NOT EXISTS "${schema}"`); + for (const [table, { columns, rows }] of Object.entries(tables)) { + const name = `"${schema}"."${table}"`; + statements.push( + `CREATE TABLE IF NOT EXISTS ${name} (${Object.entries(columns) + .map(([column, type]) => `"${column}" ${type}`) + .join(", ")})`, + ); + for (const row of rows ?? []) { + const keys = Object.keys(row); + statements.push( + `INSERT INTO ${name} (${keys.map((k) => `"${k}"`).join(", ")}) VALUES (${keys + .map((k) => literal(row[k])) + .join(", ")})`, + ); + } + } + } + await sql(api, target, statements.join(";\n")); + return database; +} + +function literal(value: unknown): string { + if (value === null || value === undefined) return "NULL"; + if (typeof value === "number" || typeof value === "boolean") return String(value); + const text = typeof value === "string" ? value : JSON.stringify(value); + return `'${text.replace(/'/g, "''")}'`; +} + +async function sql(api: Api, database: string, content: string): Promise { + const result = await api("POST", "jobs/run_wait_result/preview", { + content, + language: "postgresql", + args: { database }, + }); + if (result && typeof result === "object" && "error" in result) { + throw new Error(`seeding SQL failed: ${JSON.stringify(result.error)}`); + } +} + +/** Each attempt's user token carries its workspace, so the attempt revokes exactly its own. */ +function tokenLabel(workspace: string): string { + return `ai-evals ${workspace}`; +} + +async function psql( + sql: string, + why = "This fixture's user is not the admin", +): Promise { + if (!DATABASE_URL) { + throw new Error( + `${why}: set WMILL_AI_EVAL_DATABASE_URL to the eval backend's database URL so the harness can write it.`, + ); + } + await promisify(execFile)("psql", [DATABASE_URL, "-v", "ON_ERROR_STOP=1", "-qc", sql]); +} diff --git a/ai_evals/adapters/frontend/core/shared/baseEvalRunner.ts b/ai_evals/adapters/frontend/core/shared/baseEvalRunner.ts index 13aaa59806..13cb852229 100644 --- a/ai_evals/adapters/frontend/core/shared/baseEvalRunner.ts +++ b/ai_evals/adapters/frontend/core/shared/baseEvalRunner.ts @@ -138,7 +138,7 @@ export async function runEval( // Accepts the run form exactly as the model prefilled it: there is nobody here to // edit the arguments, so a case can assert what the model proposed but never how // it reacts to the user changing something. - requestRunArgs: async (_toolId, form) => form.args, + requestRunArgs: async (_toolId, form) => ({ kind: "args", args: form.args }), ...(pendingAnswers && { requestUserQuestion: async () => { const answer = pendingAnswers.shift(); diff --git a/ai_evals/adapters/frontend/datatableSqlEngine.test.ts b/ai_evals/adapters/frontend/datatableSqlEngine.test.ts deleted file mode 100644 index e0398b407b..0000000000 --- a/ai_evals/adapters/frontend/datatableSqlEngine.test.ts +++ /dev/null @@ -1,262 +0,0 @@ -import { describe, expect, it } from 'bun:test' -import { applyDatatableSql, type BenchmarkDatatableSeed } from './datatableSqlEngine' - -function makeDatatable(): BenchmarkDatatableSeed { - return { - datatable_name: 'main', - schemas: { - public: { - orders: { - columns: { id: 'int4', customer_id: 'int4', total: 'numeric', status: 'text' }, - rows: [ - { id: 1, customer_id: 1, total: 42.5, status: 'shipped' }, - { id: 2, customer_id: 2, total: 19.99, status: 'pending' }, - { id: 3, customer_id: 1, total: 88, status: 'shipped' } - ] - }, - customers: { - columns: { id: 'int4', name: 'text' }, - rows: [{ id: 1, name: 'Alice' }] - } - } - } - } -} - -describe('SELECT', () => { - it('returns the referenced table rows', () => { - const dt = makeDatatable() - expect(applyDatatableSql(dt, 'SELECT id, name FROM customers').rows).toEqual([ - { id: 1, name: 'Alice' } - ]) - }) - - it('falls back to the first table when no known table is referenced', () => { - const dt = makeDatatable() - expect(applyDatatableSql(dt, 'select 1').rows).toHaveLength(3) - }) - - it('resolves a schema-qualified table', () => { - const dt = makeDatatable() - expect(applyDatatableSql(dt, 'SELECT * FROM public.customers').rows).toEqual([ - { id: 1, name: 'Alice' } - ]) - }) -}) - -describe('CREATE TABLE', () => { - it('adds a table with parsed columns, skipping table constraints and FK clauses', () => { - const dt = makeDatatable() - const result = applyDatatableSql( - dt, - 'CREATE TABLE public.refunds (\n order_id int4 NOT NULL REFERENCES public.orders(id),\n amount numeric(10,2),\n PRIMARY KEY (order_id)\n)' - ) - expect(result.rows).toEqual([]) - expect(dt.schemas.public.refunds).toEqual({ - columns: { order_id: 'int4', amount: 'numeric(10,2)' }, - rows: [] - }) - }) - - it('defaults an unqualified table to the public schema', () => { - const dt = makeDatatable() - applyDatatableSql(dt, 'CREATE TABLE notes (id int4, body text)') - expect(dt.schemas.public.notes.columns).toEqual({ id: 'int4', body: 'text' }) - }) - - it('is a no-op for an existing table with IF NOT EXISTS', () => { - const dt = makeDatatable() - applyDatatableSql(dt, 'CREATE TABLE IF NOT EXISTS public.orders (x int4)') - expect(Object.keys(dt.schemas.public.orders.columns)).toContain('status') - }) -}) - -describe('DROP TABLE', () => { - it('removes the table', () => { - const dt = makeDatatable() - applyDatatableSql(dt, 'DROP TABLE IF EXISTS public.customers') - expect(dt.schemas.public.customers).toBeUndefined() - }) -}) - -describe('INSERT', () => { - it('appends a row using an explicit column list', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "INSERT INTO customers (id, name) VALUES (2, 'Bob')") - expect(dt.schemas.public.customers.rows).toContainEqual({ id: 2, name: 'Bob' }) - }) - - it('infers columns from the table when none are given, and appends multiple tuples', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "INSERT INTO customers VALUES (2, 'Bob'), (3, 'Carol')") - expect(dt.schemas.public.customers.rows).toHaveLength(3) - }) - - it('returns the inserted rows when RETURNING is present', () => { - const dt = makeDatatable() - const result = applyDatatableSql( - dt, - "INSERT INTO customers (id, name) VALUES (2, 'Bob') RETURNING *" - ) - expect(result.rows).toEqual([{ id: 2, name: 'Bob' }]) - }) -}) - -describe('UPDATE', () => { - it('updates only the rows matching an equality WHERE', () => { - const dt = makeDatatable() - const result = applyDatatableSql( - dt, - "UPDATE public.orders SET status = 'shipped' WHERE id = 2" - ) - expect(result.rows).toEqual([]) - expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('shipped') - expect(dt.schemas.public.orders.rows?.find((r) => r.id === 1)?.status).toBe('shipped') - }) - - it('strips a Postgres cast in the WHERE value', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "UPDATE orders SET status = 'done' WHERE id = 2::int4") - expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('done') - }) - - it('matches multiple AND predicates including a numeric literal', () => { - const dt = makeDatatable() - applyDatatableSql( - dt, - "UPDATE orders SET status = 'done' WHERE customer_id = 2 AND total = 19.99" - ) - expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('done') - expect(dt.schemas.public.orders.rows?.find((r) => r.id === 1)?.status).toBe('shipped') - }) - - it('updates every row when there is no WHERE', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "UPDATE orders SET status = 'archived'") - expect(dt.schemas.public.orders.rows?.every((r) => r.status === 'archived')).toBe(true) - }) - - it('returns the affected rows when RETURNING is present', () => { - const dt = makeDatatable() - const result = applyDatatableSql( - dt, - "UPDATE orders SET status = 'shipped' WHERE id = 2 RETURNING *" - ) - expect(result.rows).toHaveLength(1) - expect(result.rows[0]).toMatchObject({ id: 2, status: 'shipped' }) - }) - - it('affects no rows when the WHERE clause cannot be parsed', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "UPDATE orders SET status = 'x' WHERE total > 20") - expect(dt.schemas.public.orders.rows?.some((r) => r.status === 'x')).toBe(false) - }) -}) - -describe('DELETE', () => { - it('removes only the matching rows', () => { - const dt = makeDatatable() - applyDatatableSql(dt, 'DELETE FROM orders WHERE id = 2') - expect(dt.schemas.public.orders.rows?.map((r) => r.id)).toEqual([1, 3]) - }) - - it('returns the removed rows when RETURNING is present', () => { - const dt = makeDatatable() - const result = applyDatatableSql(dt, 'DELETE FROM orders WHERE id = 2 RETURNING *') - expect(result.rows).toEqual([{ id: 2, customer_id: 2, total: 19.99, status: 'pending' }]) - }) -}) - -describe('writes are reflected by later reads', () => { - it('UPDATE then SELECT sees the new value (the verify-loop fix)', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "UPDATE orders SET status = 'shipped' WHERE id = 2") - const seen = applyDatatableSql(dt, 'SELECT * FROM orders').rows - expect(seen.find((r) => r.id === 2)?.status).toBe('shipped') - }) - - it('INSERT then SELECT sees the new row', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "INSERT INTO customers (id, name) VALUES (9, 'Zed')") - const seen = applyDatatableSql(dt, 'SELECT * FROM customers').rows - expect(seen).toContainEqual({ id: 9, name: 'Zed' }) - }) - - it('CREATE then SELECT on the new table returns its (empty) rows', () => { - const dt = makeDatatable() - applyDatatableSql(dt, 'CREATE TABLE public.refunds (order_id int4, amount numeric)') - expect(applyDatatableSql(dt, 'SELECT * FROM refunds').rows).toEqual([]) - }) -}) - -describe('system-catalog queries reflect the current tables/columns', () => { - it('lists current tables (including a freshly created one) via information_schema.tables', () => { - const dt = makeDatatable() - applyDatatableSql(dt, 'CREATE TABLE public.refunds (order_id int4)') - const rows = applyDatatableSql( - dt, - "SELECT table_name FROM information_schema.tables WHERE table_name = 'refunds'" - ).rows - expect(rows.map((r) => r.table_name)).toContain('refunds') - }) - - it('does not list a dropped table', () => { - const dt = makeDatatable() - applyDatatableSql(dt, 'DROP TABLE public.customers') - const rows = applyDatatableSql(dt, 'SELECT table_name FROM information_schema.tables').rows - expect(rows.map((r) => r.table_name)).not.toContain('customers') - }) - - it('reports columns via information_schema.columns', () => { - const dt = makeDatatable() - const rows = applyDatatableSql( - dt, - "SELECT column_name FROM information_schema.columns WHERE table_name = 'orders'" - ).rows - expect(rows.map((r) => r.column_name)).toContain('status') - }) -}) - -describe('parser robustness (string/paren-aware splitting)', () => { - it('does not treat the word "returning" inside a string value as a RETURNING clause', () => { - const dt = makeDatatable() - const result = applyDatatableSql( - dt, - "INSERT INTO customers (id, name) VALUES (5, 'is returning soon')" - ) - expect(result.rows).toEqual([]) - expect(dt.schemas.public.customers.rows).toContainEqual({ id: 5, name: 'is returning soon' }) - }) - - it('does not split on the word "where" inside a SET string value', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "UPDATE orders SET status = 'ship where ordered' WHERE id = 2") - expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('ship where ordered') - expect(dt.schemas.public.orders.rows?.find((r) => r.id === 1)?.status).toBe('shipped') - }) - - it('keeps INSERT tuples intact when a value contains a function call', () => { - const dt = makeDatatable() - applyDatatableSql(dt, "INSERT INTO customers (id, name) VALUES (6, coalesce(NULL, 'x'))") - expect(dt.schemas.public.customers.rows).toHaveLength(2) - expect(dt.schemas.public.customers.rows?.[1]).toMatchObject({ id: 6 }) - }) - - it('CREATE TABLE ignores a trailing semicolon-separated statement', () => { - const dt = makeDatatable() - applyDatatableSql( - dt, - 'CREATE TABLE public.refunds (id int4, amount numeric); INSERT INTO refunds VALUES (1, 5)' - ) - expect(dt.schemas.public.refunds.columns).toEqual({ id: 'int4', amount: 'numeric' }) - expect(dt.schemas.public.refunds.rows).toEqual([]) - }) -}) - -describe('unparseable statements are a safe no-op', () => { - it('returns [] and does not throw', () => { - const dt = makeDatatable() - expect(applyDatatableSql(dt, 'VACUUM ANALYZE').rows).toEqual([]) - expect(applyDatatableSql(dt, 'GRANT SELECT ON orders TO someone').rows).toEqual([]) - }) -}) diff --git a/ai_evals/adapters/frontend/datatableSqlEngine.ts b/ai_evals/adapters/frontend/datatableSqlEngine.ts deleted file mode 100644 index 96a62f6804..0000000000 --- a/ai_evals/adapters/frontend/datatableSqlEngine.ts +++ /dev/null @@ -1,552 +0,0 @@ -/** - * A deliberately small, best-effort SQL engine for the benchmark datatable mock. - * - * This is NOT a real SQL implementation — it exists only so that writes a model - * issues during an eval (`CREATE TABLE`, `INSERT`, `UPDATE`, `DELETE`, `DROP`) - * become visible to its later reads (`list_datatables`, `get_datatable_table_schema`, - * `SELECT`). Without that, a model that re-queries to verify a write sees stale - * seed data, concludes the write failed, and loops until it exhausts its turns. - * - * It parses only the common statement shapes models produce. Anything it cannot - * parse is a no-op success (it never throws) — behavioral evals assert that the - * right statement was issued, not its exact data effects. Notable limits: - * - `SELECT` returns all rows of the referenced (or first) table — no WHERE - * filtering, projection, joins, or aggregation. - * - `WHERE` supports `col = value` predicates joined by `AND` only; an - * unparseable WHERE on UPDATE/DELETE affects zero rows (never the whole table). - */ - -/** One seeded datatable table: its columns (col -> compact_type) and optional rows. */ -export interface BenchmarkDatatableTableSeed { - columns: Record - rows?: Record[] -} - -/** A seeded datatable: `datatable_name` plus a `schema -> table -> seed` map. */ -export interface BenchmarkDatatableSeed { - datatable_name: string - schemas: { - [schema: string]: { - [table: string]: BenchmarkDatatableTableSeed - } - } - /** Whether the datatable keeps its schema as migrations. */ - migrations_enabled?: boolean - migrations?: BenchmarkDatatableMigrationSeed[] -} - -export interface BenchmarkDatatableMigrationSeed { - timestamp: number - name: string - code_up: string - code_down?: string - applied?: boolean -} - -export interface DatatableSqlResult { - rows: Record[] -} - -const DEFAULT_SCHEMA = 'public' - -type ParsedRef = { schema: string; table: string } -type Predicate = { column: string; value: unknown } - -/** - * Apply one SQL statement to `datatable` IN PLACE and return the result rows. - * SELECT returns the referenced/first table's rows; a mutation returns its - * affected rows when it has a RETURNING clause, otherwise `[]`. - */ -export function applyDatatableSql( - datatable: BenchmarkDatatableSeed, - sql: string -): DatatableSqlResult { - const statement = stripTrailingSemicolon(sql.trim()) - if (/^\s*(with|select)\b/i.test(statement)) { - return { rows: selectRows(datatable, statement) } - } - if (/^\s*create\s+table\b/i.test(statement)) { - return { rows: applyCreateTable(datatable, statement) } - } - if (/^\s*drop\s+table\b/i.test(statement)) { - return { rows: applyDropTable(datatable, statement) } - } - if (/^\s*insert\s+into\b/i.test(statement)) { - return { rows: applyInsert(datatable, statement) } - } - if (/^\s*update\b/i.test(statement)) { - return { rows: applyUpdate(datatable, statement) } - } - if (/^\s*delete\s+from\b/i.test(statement)) { - return { rows: applyDelete(datatable, statement) } - } - return { rows: [] } -} - -// ============= Reads ============= - -function selectRows( - datatable: BenchmarkDatatableSeed, - sql: string -): Record[] { - const fromRef = sql.match(/\bfrom\s+([a-zA-Z_"][\w."]*)/i)?.[1] - if (fromRef) { - const catalog = catalogRows(datatable, fromRef) - if (catalog) { - return catalog - } - } - const table = fromRef ? resolveTable(datatable, fromRef) : undefined - const seed = table ?? firstTable(datatable) - return seed?.rows ?? [] -} - -/** - * Synthesize rows for a system-catalog query so a model verifying a `CREATE`/`DROP` - * via `information_schema.tables` / `.columns` (or `pg_tables`) sees the current - * tables/columns instead of fallback data. WHERE is not applied, so the model gets - * the full set and finds (or no longer finds) the table it just changed. - * Returns `undefined` for non-catalog refs so normal table resolution proceeds. - */ -function catalogRows( - datatable: BenchmarkDatatableSeed, - ref: string -): Record[] | undefined { - const normalized = ref.toLowerCase().replace(/"/g, '') - const name = normalized.split('.').pop() - const isCatalog = normalized.includes('information_schema.') || normalized.startsWith('pg_') - if (!isCatalog) { - return undefined - } - const tables = allTables(datatable) - if (name === 'tables' || name === 'pg_tables') { - return tables.map(({ schema, table }) => ({ - table_schema: schema, - table_name: table, - schemaname: schema, - tablename: table - })) - } - if (name === 'columns') { - return tables.flatMap(({ schema, table, seed }) => - Object.entries(seed.columns).map(([column, type]) => ({ - table_schema: schema, - table_name: table, - column_name: column, - data_type: type - })) - ) - } - return undefined -} - -function allTables( - datatable: BenchmarkDatatableSeed -): { schema: string; table: string; seed: BenchmarkDatatableTableSeed }[] { - return Object.entries(datatable.schemas).flatMap(([schema, tables]) => - Object.entries(tables).map(([table, seed]) => ({ schema, table, seed })) - ) -} - -// ============= DDL ============= - -function applyCreateTable( - datatable: BenchmarkDatatableSeed, - sql: string -): Record[] { - const head = sql.match( - /^\s*create\s+table\s+(?:if\s+not\s+exists\s+)?([a-zA-Z_"][\w."]*)/i - ) - // The first top-level paren group is the column-definition list; using it (rather - // than a greedy `(...)` capture) ignores any trailing `;`-separated statement. - const columnText = extractParenGroups(sql)[0] - if (!head || columnText === undefined) { - return [] - } - const { schema, table } = parseRef(head[1]) - const existing = datatable.schemas[schema]?.[table] - if (existing) { - return [] - } - const columns: Record = {} - for (const rawDef of splitTopLevel(columnText)) { - const def = rawDef.trim() - if (!def || isTableConstraint(def)) { - continue - } - const tokens = def.split(/\s+/) - const column = unquoteIdentifier(tokens[0]) - if (!column) { - continue - } - columns[column] = tokens[1] ?? 'text' - } - if (!datatable.schemas[schema]) { - datatable.schemas[schema] = {} - } - datatable.schemas[schema][table] = { columns, rows: [] } - return [] -} - -function applyDropTable( - datatable: BenchmarkDatatableSeed, - sql: string -): Record[] { - const match = sql.match( - /^\s*drop\s+table\s+(?:if\s+exists\s+)?([a-zA-Z_"][\w."]*)/i - ) - if (!match) { - return [] - } - const { schema, table } = parseRef(match[1]) - if (datatable.schemas[schema]?.[table]) { - delete datatable.schemas[schema][table] - } - return [] -} - -// ============= DML ============= - -function applyInsert( - datatable: BenchmarkDatatableSeed, - sql: string -): Record[] { - const { body, returning } = splitOffReturning(sql) - const match = body.match( - /^\s*insert\s+into\s+([a-zA-Z_"][\w."]*)\s*(?:\(([^)]*)\))?\s*values\s*([\s\S]+)$/i - ) - if (!match) { - return [] - } - const table = resolveTable(datatable, match[1]) - if (!table) { - return [] - } - const columns = match[2] - ? splitTopLevel(match[2]).map((entry) => unquoteIdentifier(entry.trim())) - : Object.keys(table.columns) - const inserted: Record[] = [] - for (const tuple of extractParenGroups(match[3])) { - const values = splitTopLevel(tuple).map((entry) => parseValue(entry)) - const row: Record = {} - columns.forEach((column, index) => { - row[column] = values[index] - }) - inserted.push(row) - } - table.rows ??= [] - table.rows.push(...inserted) - return returning ? inserted : [] -} - -function applyUpdate( - datatable: BenchmarkDatatableSeed, - sql: string -): Record[] { - const { body, returning } = splitOffReturning(sql) - const match = body.match(/^\s*update\s+([a-zA-Z_"][\w."]*)\s+set\s+([\s\S]+)$/i) - if (!match) { - return [] - } - const table = resolveTable(datatable, match[1]) - if (!table) { - return [] - } - let assignmentText = match[2] - let whereText: string | undefined - const whereMatch = maskForClauseScan(assignmentText).match(/\swhere\s/i) - if (whereMatch && whereMatch.index !== undefined) { - whereText = assignmentText.slice(whereMatch.index + whereMatch[0].length) - assignmentText = assignmentText.slice(0, whereMatch.index) - } - const predicates = parsePredicates(whereText) - if (predicates === null) { - return [] - } - const assignments: Record = {} - for (const entry of splitTopLevel(assignmentText)) { - const pair = entry.match(/^\s*([a-zA-Z_"][\w."]*)\s*=\s*([\s\S]+?)\s*$/) - if (pair) { - assignments[lastIdentifier(pair[1])] = parseValue(pair[2]) - } - } - const affected = (table.rows ?? []).filter((row) => rowMatches(row, predicates)) - for (const row of affected) { - Object.assign(row, assignments) - } - return returning ? affected : [] -} - -function applyDelete( - datatable: BenchmarkDatatableSeed, - sql: string -): Record[] { - const { body, returning } = splitOffReturning(sql) - const match = body.match(/^\s*delete\s+from\s+([a-zA-Z_"][\w."]*)\s*([\s\S]*)$/i) - if (!match) { - return [] - } - const table = resolveTable(datatable, match[1]) - if (!table) { - return [] - } - const whereText = match[2].replace(/^\s*where\s+/i, '').trim() || undefined - const predicates = parsePredicates(whereText) - if (predicates === null) { - return [] - } - const rows = table.rows ?? [] - const removed = rows.filter((row) => rowMatches(row, predicates)) - table.rows = rows.filter((row) => !rowMatches(row, predicates)) - return returning ? removed : [] -} - -// ============= Parsing helpers ============= - -function resolveTable( - datatable: BenchmarkDatatableSeed, - ref: string -): BenchmarkDatatableTableSeed | undefined { - const { schema, table } = parseRef(ref) - const direct = datatable.schemas[schema]?.[table] - if (direct) { - return direct - } - // Bare table name: fall back to searching every schema for a matching table. - if (!ref.includes('.')) { - for (const tables of Object.values(datatable.schemas)) { - if (tables[table]) { - return tables[table] - } - } - } - return undefined -} - -function firstTable( - datatable: BenchmarkDatatableSeed -): BenchmarkDatatableTableSeed | undefined { - for (const tables of Object.values(datatable.schemas)) { - for (const seed of Object.values(tables)) { - return seed - } - } - return undefined -} - -function parseRef(ref: string): ParsedRef { - const parts = ref.split('.').map(unquoteIdentifier) - if (parts.length >= 2) { - return { schema: parts[parts.length - 2], table: parts[parts.length - 1] } - } - return { schema: DEFAULT_SCHEMA, table: parts[0] } -} - -/** A WHERE clause with no parseable form returns `null`; absent WHERE returns `[]` (match all). */ -function parsePredicates(whereText: string | undefined): Predicate[] | null { - if (whereText === undefined || whereText.trim() === '') { - return [] - } - const predicates: Predicate[] = [] - for (const part of whereText.split(/\s+and\s+/i)) { - const match = part.match(/^\s*([a-zA-Z_"][\w."]*)\s*=\s*([\s\S]+?)\s*$/) - if (!match) { - return null - } - predicates.push({ column: lastIdentifier(match[1]), value: parseValue(match[2]) }) - } - return predicates -} - -function rowMatches(row: Record, predicates: Predicate[]): boolean { - return predicates.every((predicate) => looseEquals(row[predicate.column], predicate.value)) -} - -function looseEquals(left: unknown, right: unknown): boolean { - if (left === null || left === undefined) { - return right === null || right === undefined - } - if (typeof left === 'number' && typeof right === 'number') { - return left === right - } - return String(left) === String(right) -} - -function parseValue(raw: string): unknown { - // Drop a trailing Postgres cast (e.g. `2::int4`) before interpreting the literal. - const token = raw.trim().replace(/::\s*[a-zA-Z_][\w]*(\([^)]*\))?\s*$/, '').trim() - const stringMatch = token.match(/^'([\s\S]*)'$/) - if (stringMatch) { - return stringMatch[1].replace(/''/g, "'") - } - if (/^-?\d+(\.\d+)?$/.test(token)) { - return Number(token) - } - if (/^true$/i.test(token)) { - return true - } - if (/^false$/i.test(token)) { - return false - } - if (/^null$/i.test(token)) { - return null - } - return token -} - -function splitOffReturning(sql: string): { body: string; returning: boolean } { - const match = maskForClauseScan(sql).match(/\sreturning\s/i) - if (!match || match.index === undefined) { - return { body: sql, returning: false } - } - return { body: sql.slice(0, match.index), returning: true } -} - -/** - * A same-length copy of `sql` with the contents of single-quoted strings and - * parenthesized groups blanked to spaces, so a top-level keyword scan - * (WHERE / RETURNING) cannot match inside a string literal or a subquery. Index - * positions in the result map 1:1 back onto the original. - */ -function maskForClauseScan(sql: string): string { - let masked = '' - let depth = 0 - let inString = false - for (let i = 0; i < sql.length; i++) { - const char = sql[i] - if (inString) { - if (char === "'") { - if (sql[i + 1] === "'") { - masked += ' ' - i++ - continue - } - inString = false - } - masked += ' ' - continue - } - if (char === "'") { - inString = true - masked += ' ' - } else if (char === '(') { - depth++ - masked += ' ' - } else if (char === ')') { - depth = Math.max(0, depth - 1) - masked += ' ' - } else { - masked += depth > 0 ? ' ' : char - } - } - return masked -} - -/** - * Inner text of each top-level `( ... )` group in `input`, honoring nested parens - * (e.g. `now()`, `numeric(10,2)`) and single-quoted strings. Used for the CREATE - * column-definition group and INSERT value tuples. - */ -function extractParenGroups(input: string): string[] { - const groups: string[] = [] - let depth = 0 - let inString = false - let current = '' - for (let i = 0; i < input.length; i++) { - const char = input[i] - if (inString) { - current += char - if (char === "'") { - if (input[i + 1] === "'") { - current += input[++i] - } else { - inString = false - } - } - continue - } - if (char === "'") { - inString = true - current += char - } else if (char === '(') { - depth++ - if (depth === 1) { - current = '' - } else { - current += char - } - } else if (char === ')') { - depth = Math.max(0, depth - 1) - if (depth === 0) { - groups.push(current) - current = '' - } else { - current += char - } - } else if (depth > 0) { - current += char - } - } - return groups -} - -/** Split on commas that are not inside parentheses or single-quoted strings. */ -function splitTopLevel(input: string): string[] { - const parts: string[] = [] - let depth = 0 - let inString = false - let current = '' - for (let i = 0; i < input.length; i++) { - const char = input[i] - if (inString) { - current += char - if (char === "'") { - if (input[i + 1] === "'") { - current += input[++i] - } else { - inString = false - } - } - continue - } - if (char === "'") { - inString = true - current += char - } else if (char === '(') { - depth++ - current += char - } else if (char === ')') { - depth = Math.max(0, depth - 1) - current += char - } else if (char === ',' && depth === 0) { - parts.push(current) - current = '' - } else { - current += char - } - } - if (current.trim() !== '') { - parts.push(current) - } - return parts -} - -function isTableConstraint(def: string): boolean { - return /^(primary\s+key|foreign\s+key|constraint|unique|check|exclude|like)\b/i.test(def) -} - -function unquoteIdentifier(identifier: string): string { - const trimmed = identifier.trim() - const quoted = trimmed.match(/^"([\s\S]*)"$/) - return quoted ? quoted[1] : trimmed -} - -/** For a qualified reference like `orders.id`, keep only the final identifier. */ -function lastIdentifier(reference: string): string { - const parts = reference.split('.') - return unquoteIdentifier(parts[parts.length - 1]) -} - -function stripTrailingSemicolon(sql: string): string { - return sql.replace(/;\s*$/, '') -} diff --git a/ai_evals/adapters/frontend/mockBackend.ts b/ai_evals/adapters/frontend/mockBackend.ts index 1de463690b..7145984ea1 100644 --- a/ai_evals/adapters/frontend/mockBackend.ts +++ b/ai_evals/adapters/frontend/mockBackend.ts @@ -3,37 +3,9 @@ import confluenceFixture from '../../fixtures/frontend/global/hub/confluence.jso import servicenowFixture from '../../fixtures/frontend/global/hub/servicenow.json' import outreachFixture from '../../fixtures/frontend/global/hub/outreach.json' import syncedResourceTypesFixture from '../../fixtures/frontend/global/hub/synced_resource_types.json' -import type { - AppWithLastVersion, - CompletedJob, - Flow, - Job, - ListableApp, - ListableResource, - ListableVariable, - Folder, - Group, - QueuedJob, - Resource, - Schedule, - Script, - WorkerPing -} from '../../../frontend/src/lib/gen' -import type { - DataMetric, - DataTableTables, - DataTableTableSchema, - GetDraftForUserResponse, - GetOwnDraftResponse, - ListDraftsResponse, - ScriptLang, - UpdateDraftResponse, - UserDraftItemKind -} from '../../../frontend/src/lib/gen/types.gen' +import type { CompletedJob, Flow, Script } from '../../../frontend/src/lib/gen' +import type { DataMetric, ScriptLang } from '../../../frontend/src/lib/gen/types.gen' import { buildScriptLintResult } from './core/script/preview' -import { applyDatatableSql, type BenchmarkDatatableSeed } from './datatableSqlEngine' - -export type { BenchmarkDatatableSeed, BenchmarkDatatableTableSeed } from './datatableSqlEngine' const BENCHMARK_TIMESTAMP = '1970-01-01T00:00:00.000Z' @@ -174,6 +146,33 @@ export interface BenchmarkWorkspaceSchedule { summary?: string } +/** One seeded datatable table: its columns (col -> compact_type) and optional rows. */ +export interface BenchmarkDatatableTableSeed { + columns: Record + rows?: Record[] +} + +/** A seeded datatable: `datatable_name` plus a `schema -> table -> seed` map. */ +export interface BenchmarkDatatableSeed { + datatable_name: string + schemas: { + [schema: string]: { + [table: string]: BenchmarkDatatableTableSeed + } + } + /** Whether the datatable keeps its schema as migrations. */ + migrations_enabled?: boolean + migrations?: BenchmarkDatatableMigrationSeed[] +} + +export interface BenchmarkDatatableMigrationSeed { + timestamp: number + name: string + code_up: string + code_down?: string + applied?: boolean +} + export interface BenchmarkWorkspaceRunnables { scripts?: BenchmarkWorkspaceScript[] flows?: BenchmarkWorkspaceFlow[] @@ -186,6 +185,11 @@ export interface BenchmarkWorkspaceRunnables { datatables?: BenchmarkDatatableSeed[] /** DuckLake catalog names, as `list_ducklakes` reports them. */ ducklakes?: string[] + /** + * Workspace object storage, with these objects in it. It also makes `ducklakes` real + * catalogs on that storage, so a pipeline can run against them (`validate.pipelineRun`). + */ + objectStorage?: { files?: Array<{ key: string; content: string }> } dataMetrics?: DataMetric[] jobs?: BenchmarkWorkspaceJob[] /** The instance's workers. Unset falls through to the real backend's; `[]` is none. */ @@ -198,18 +202,11 @@ export interface BenchmarkWorkspaceRunnables { } 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< - string, - { workspace: string; job: BenchmarkCompletedJob | BenchmarkQueuedJob } ->() -// What set_workspace_settings applied, per workspace, so get_workspace_settings reads it back. -const benchmarkWorkspaceSettings = new Map>() +// Keyed by `${workspace}::${jobId}` so a job is only visible from the workspace that ran it. +const benchmarkJobs = new Map() function benchmarkJobKey(workspace: string, jobId: string): string { return `${workspace}::${jobId}` @@ -219,15 +216,6 @@ export function resetBenchmarkMockBackend(): void { benchmarkWorkspaces.clear() 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. 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 } export function registerBenchmarkWorkspace(workspace: string): void { @@ -239,53 +227,12 @@ export function registerBenchmarkWorkspaceRunnables( runnables: BenchmarkWorkspaceRunnables ): void { benchmarkWorkspaces.add(workspace) - // Fresh case: drop any drafts left from a prior run on this workspace id. - clearBenchmarkDrafts(workspace) - // Datatables are mutated in place by exec_datatable_sql (a write must be visible - // to later reads), so store an isolated deep copy — never mutate the caller's seed. - benchmarkWorkspaceRunnables.set(workspace, { - ...runnables, - datatables: runnables.datatables ? structuredClone(runnables.datatables) : undefined - }) - // 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, - jobKind: seed.jobKind ?? 'script', - success: seed.success, - scriptPath: seed.scriptPath, - createdBy: seed.createdBy, - label: seed.label, - logs: seed.logs, - args: seed.args, - 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) - } + benchmarkWorkspaceRunnables.set(workspace, runnables) } 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) { benchmarkJobs.delete(jobId) @@ -293,6 +240,15 @@ export function unregisterBenchmarkWorkspace(workspace: string): void { } } +/** Answer a real workspace's provider model listings from its fixture, which no eval run can + * reach the providers for. Leaves its other API calls to the real backend. */ +export function registerBenchmarkAiModels( + workspace: string, + aiProviders: BenchmarkWorkspaceAiProvider[] +): void { + benchmarkWorkspaceRunnables.set(workspace, { aiProviders }) +} + export function unregisterBenchmarkWorkspaceRunnables(workspace: string): void { unregisterBenchmarkWorkspace(workspace) } @@ -341,124 +297,18 @@ export function getBenchmarkFlowByPath(workspace: string, path: string): Flow | return flow ? buildBenchmarkFlow(flow) : null } -export function listBenchmarkApps(workspace: string): ListableApp[] | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - if (!runnables) { - return null - } - return (runnables.apps ?? []).map(buildBenchmarkListableApp) -} - -export function getBenchmarkAppByPath(workspace: string, path: string): AppWithLastVersion | null { - const app = benchmarkWorkspaceRunnables.get(workspace)?.apps?.find((entry) => entry.path === path) - - return app ? buildBenchmarkApp(app) : null -} - -function buildBenchmarkVariable( - workspace: string, - seed: BenchmarkWorkspaceVariable, - decryptSecret: boolean -): ListableVariable { - return { - workspace_id: workspace, - path: seed.path, - // Mirror `get_variable`: a secret's value is withheld unless decryption was - // asked for, so a reader genuinely cannot see it. - value: seed.is_secret && !decryptSecret ? undefined : seed.value, - is_secret: seed.is_secret, - description: seed.description, - labels: seed.labels, - ws_specific: seed.ws_specific ?? false, - extra_perms: {}, - edited_at: BENCHMARK_TIMESTAMP - } -} - -export function listBenchmarkVariables(workspace: string): ListableVariable[] | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - if (!runnables) { - return null - } - // The list route never decrypts. - return (runnables.variables ?? []).map((seed) => buildBenchmarkVariable(workspace, seed, false)) -} - -/** AI provider resources of a benchmark workspace, shaped like `ResourceService.listResource` - * rows (which carry no value). Null when the workspace is not a benchmark one. */ -export function listBenchmarkAiProviderResources(workspace: string): ListableResource[] | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - if (!runnables) { - return null - } - return (runnables.aiProviders ?? []).map((seed) => ({ - workspace_id: workspace, - path: seed.path, - resource_type: seed.kind, - value: null, - is_oauth: false, - is_linked: false, - is_refreshed: false, - extra_perms: {}, - edited_at: BENCHMARK_TIMESTAMP - })) -} - -/** Plain seeded resources of a benchmark workspace, shaped like `ResourceService.listResource` - * rows. Null when the workspace is not a benchmark one. */ -export function listBenchmarkPlainResources(workspace: string): ListableResource[] | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - if (!runnables) { - return null - } - return (runnables.resources ?? []).map((seed) => ({ - workspace_id: workspace, - path: seed.path, - resource_type: seed.resource_type, - description: seed.description, - value: null, - is_oauth: false, - is_linked: false, - is_refreshed: false, - extra_perms: {}, - edited_at: BENCHMARK_TIMESTAMP - })) -} - -function benchmarkResourceTypes(workspace: string): BenchmarkWorkspaceResourceType[] { - return benchmarkWorkspaceRunnables.get(workspace)?.resourceTypes ?? syncedResourceTypes() -} - /** Resource type names of a benchmark workspace, as `ResourceService.listResourceTypeNames` * returns them. Null when the workspace is not a benchmark one. */ export function listBenchmarkResourceTypeNames(workspace: string): string[] | null { if (!benchmarkWorkspaces.has(workspace)) { return null } - return benchmarkResourceTypes(workspace).map((rt) => rt.name) -} - -/** Adds a resource type to a benchmark workspace, as `ResourceService.createResourceType` does, - * so later searches in the same case find it. */ -export function createBenchmarkResourceType( - workspace: string, - resourceType: BenchmarkWorkspaceResourceType -): void { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - if (!runnables) { - throw new Error(`Workspace "${workspace}" is not a benchmark workspace`) - } - const existing = benchmarkResourceTypes(workspace) - if (existing.some((rt) => rt.name === resourceType.name)) { - throw new Error(`Resource type ${resourceType.name} already exists`) - } - runnables.resourceTypes = [...existing, resourceType] + return syncedResourceTypes().map((rt) => rt.name) } /** Stands in for the resource type search: a type matches when a word of the query appears in * its name or description, ranked by how many do. */ export function queryBenchmarkResourceTypes( - workspace: string, text: string, limit = 10 ): { name: string; schema?: unknown; score: number }[] { @@ -466,7 +316,7 @@ export function queryBenchmarkResourceTypes( .toLowerCase() .split(/[^a-z0-9]+/) .filter((word) => word.length >= 3) - return benchmarkResourceTypes(workspace) + return syncedResourceTypes() .map((rt) => { const haystack = `${rt.name} ${rt.description ?? ''}`.toLowerCase() return { name: rt.name, schema: rt.schema, score: words.filter((w) => haystack.includes(w)).length } @@ -476,95 +326,6 @@ 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 - * a row it cannot fetch. */ -export function getBenchmarkResource(workspace: string, path: string): Resource | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - const seed = runnables?.resources?.find((entry) => entry.path === path) - if (seed) { - return { - workspace_id: workspace, - path: seed.path, - resource_type: seed.resource_type, - description: seed.description, - value: seed.value ?? {}, - is_oauth: false, - extra_perms: {} - } as Resource - } - const provider = runnables?.aiProviders?.find((entry) => entry.path === path) - if (!provider) { - return null - } - return { - workspace_id: workspace, - path: provider.path, - resource_type: provider.kind, - value: getBenchmarkResourceValue(workspace, path) ?? {}, - is_oauth: false, - extra_perms: {} - } as Resource -} - -/** The value of a seeded resource. For an AI provider only the endpoint fields are modelled — a - * key is never needed, because no eval run calls the provider through this resource. */ -export function getBenchmarkResourceValue( - workspace: string, - path: string -): Record | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - const plain = runnables?.resources?.find((entry) => entry.path === path) - if (plain) { - return plain.value ?? {} - } - const seed = runnables?.aiProviders?.find((entry) => entry.path === path) - if (!seed) { - return null - } - return seed.base_url ? { base_url: seed.base_url } : {} -} - -/** The AI settings of a benchmark workspace, as `WorkspaceService.getCopilotInfo` returns them. */ -export function getBenchmarkAiConfig(workspace: string): Record | null { - const seeds = benchmarkWorkspaceRunnables.get(workspace)?.aiProviders - if (!seeds) { - return null - } - const providers: Record = {} - let defaultModel: { model: string; provider: string } | undefined - for (const seed of seeds) { - const models = seed.configuredModels ?? seed.models ?? [] - providers[seed.kind] = { resource_path: seed.path, models } - if (seed.isDefault && models[0]) { - defaultModel = { model: models[0], provider: seed.kind } - } - } - return { providers, ...(defaultModel ? { default_model: defaultModel } : {}) } -} - -export function getBenchmarkVariableByPath( - workspace: string, - path: string, - decryptSecret = true -): ListableVariable | null { - const seed = benchmarkWorkspaceRunnables - .get(workspace) - ?.variables?.find((entry) => entry.path === path) - - return seed ? buildBenchmarkVariable(workspace, seed, decryptSecret) : null -} - export function createBenchmarkCompletedJob(input: { workspace: string jobKind: CompletedJob['job_kind'] @@ -572,32 +333,21 @@ export function createBenchmarkCompletedJob(input: { result?: unknown logs?: string scriptPath?: string - scriptHash?: string args?: Record - id?: string - createdBy?: string - label?: string - tag?: string - schedulePath?: string - createdAt?: string - durationMs?: number }): string { - const jobId = input.id ?? `benchmark-job-${randomUUID()}` - const createdAt = input.createdAt ?? new Date().toISOString() - const durationMs = input.durationMs ?? 0 + const jobId = `benchmark-job-${randomUUID()}` + const now = new Date().toISOString() const job: BenchmarkCompletedJob = { type: 'CompletedJob', id: jobId, workspace_id: input.workspace, - created_by: input.createdBy ?? 'ai-evals', - created_at: createdAt, - started_at: createdAt, - completed_at: new Date(Date.parse(createdAt) + durationMs).toISOString(), - duration_ms: durationMs, - schedule_path: input.schedulePath, + created_by: 'ai-evals', + created_at: now, + started_at: now, + completed_at: now, + duration_ms: 0, success: input.success ?? true, script_path: input.scriptPath, - script_hash: input.scriptHash, args: input.args, result: input.result, logs: input.logs, @@ -608,8 +358,7 @@ export function createBenchmarkCompletedJob(input: { is_skipped: false, email: 'ai-evals@local', visible_to_owner: true, - tag: input.tag ?? 'benchmark', - labels: input.label ? [input.label] : undefined + tag: 'benchmark' } benchmarkJobs.set(benchmarkJobKey(input.workspace, jobId), { @@ -619,41 +368,6 @@ 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 @@ -665,614 +379,6 @@ export function getBenchmarkCompletedJob( 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 - * workspace so the caller can fall through to the real backend. Server-side - * filters (path/creator/status/limit) are intentionally not applied: global - * eval cases assert on the recorded `list_runs` tool call, not on filtering. - */ -export function listBenchmarkJobs(workspace: string): Job[] | null { - if (!hasBenchmarkWorkspace(workspace)) { - return null - } - return [...benchmarkJobs.values()] - .filter((entry) => entry.workspace === workspace) - .map((entry) => structuredClone(entry.job) as Job) - .sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? '')) -} - -/** - * Mirror `JobService.getJobLogs` (response is the raw log string). Throws a - * "not found" error for an unknown id, matching the backend 404. - */ -export function getBenchmarkJobLogs(workspace: string, jobId: string): string { - const job = getBenchmarkJob(workspace, jobId) - if (!job) { - throw new Error(`Job Logs not found for "${jobId}"`) - } - return job.logs ?? '' -} - -/** - * Mirror `JobService.getFlowAllResults`, which get_run calls for the execution - * tree. Fixture jobs are single runs with no steps, so only the root entry. - */ -export function getBenchmarkFlowAllResults(workspace: string, jobId: string) { - const job = getBenchmarkJob(workspace, jobId) - if (!job) { - throw new Error(`Job "${jobId}" not found in benchmark workspace`) - } - return { - entries: [ - { - job_id: jobId, - label: 'Flow', - kind: job.job_kind ?? 'script', - depth: 0, - sibling_index: 1, - sibling_count: 1, - ...('success' in job - ? { status: job.success ? 'success' : 'failure', success: job.success } - : { status: job.suspend ? 'suspended' : job.running ? 'running' : 'queued' }) - } - ], - truncated: false, - scope_filtered: false - } -} - -// ============= 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) ============= - -/** - * In-memory stand-in for the per-user draft backend (`DraftService`). The global - * AI chat now persists and reads drafts through the backend DB instead of an - * in-tab `UserDraft` cell, so the eval mocks the draft endpoints it exercises - * (`updateDraft` / `getOwnDraft` / `getDraftForUser` / `listDrafts`) and keeps the - * saved values here, keyed by workspace + draft kind + storage path. Mirrors the - * semantics of the production unit test's mock in - * `frontend/src/lib/components/copilot/chat/global/core.test.ts`. - */ -const benchmarkDrafts = new Map< - string, - { - workspace: string - kind: UserDraftItemKind - path: string - value: unknown - createdAt: string - } ->() - -// Counter-based timestamps: deterministic run-to-run (same event order → same -// values) but MONOTONIC per update, because production bumps a draft row's -// created_at on every upsert and the diff snapshot cache keys patch reuse on -// it — a fixed timestamp would serve stale patches after an edit. No eval -// simulates a concurrent writer, so every save is accepted and the conflict -// branch is never taken. -let benchmarkDraftClock = 0 -function nextBenchmarkDraftTimestamp(): string { - benchmarkDraftClock += 1 - return new Date(benchmarkDraftClock * 1000).toISOString() -} - -function benchmarkDraftKey(workspace: string, kind: string, path: string): string { - return `${workspace}::${kind}::${path}` -} - -export function clearBenchmarkDrafts(workspace: string): void { - for (const [key, entry] of benchmarkDrafts.entries()) { - if (entry.workspace === workspace) { - benchmarkDrafts.delete(key) - } - } -} - -/** - * Seed a draft straight into the store — used by the eval's live-editor draft - * fixtures, which model "the user already has this draft open/saved". Writing it - * here (instead of through `UserDraft.save`) keeps it a backend draft row with no - * shadowing in-tab cell, so a model edit that persists to the backend is what the - * output read-back captures — not the stale seed. - */ -export function seedBenchmarkDraft( - workspace: string, - kind: UserDraftItemKind, - path: string, - value: unknown -): void { - benchmarkDrafts.set(benchmarkDraftKey(workspace, kind, path), { - workspace, - kind, - path, - value, - createdAt: nextBenchmarkDraftTimestamp() - }) -} - -/** Mirror `DraftService.updateDraft`: a `null`/omitted value deletes the row. */ -export function updateBenchmarkDraft(input: { - workspace: string - kind: UserDraftItemKind - path: string - requestBody?: { value?: unknown } -}): UpdateDraftResponse { - const key = benchmarkDraftKey(input.workspace, input.kind, input.path) - const value = input.requestBody?.value - const createdAt = nextBenchmarkDraftTimestamp() - if (value == null) { - benchmarkDrafts.delete(key) - } else { - benchmarkDrafts.set(key, { - workspace: input.workspace, - kind: input.kind, - path: input.path, - value, - createdAt - }) - } - return { status: 'saved', current_timestamp: createdAt } -} - -/** Mirror `DraftService.getDraftForUser`: 404-shaped throw when absent so the - * adapter's narrowed catch treats it as "no draft" instead of re-throwing. */ -export function getBenchmarkDraftForUser(input: { - workspace: string - kind: UserDraftItemKind - path: string -}): GetDraftForUserResponse { - const entry = benchmarkDrafts.get(benchmarkDraftKey(input.workspace, input.kind, input.path)) - if (!entry) { - throw Object.assign(new Error(`no draft for "${input.path}"`), { - status: 404 - }) - } - return { value: entry.value, created_at: entry.createdAt } -} - -/** Mirror `DraftService.getOwnDraft`: `null` (200) when absent — unlike - * `getDraftForUser`, absence is not an error on this route. */ -export function getBenchmarkOwnDraft(input: { - workspace: string - kind: UserDraftItemKind - path: string -}): GetOwnDraftResponse { - const entry = benchmarkDrafts.get(benchmarkDraftKey(input.workspace, input.kind, input.path)) - if (!entry) { - return null - } - return { value: entry.value, created_at: entry.createdAt } -} - -/** Whether a deployed benchmark item exists for a draft row's kind+path — - * drives `draft_only`, which production computes against the deployed tables. */ -function benchmarkDeployedExists( - workspace: string, - kind: UserDraftItemKind, - path: string -): boolean { - if (kind === 'script') return Boolean(getBenchmarkScriptByPath(workspace, path)) - if (kind === 'flow') return Boolean(getBenchmarkFlowByPath(workspace, path)) - if (kind === 'app' || kind === 'raw_app') return Boolean(getBenchmarkAppByPath(workspace, path)) - if (kind === 'variable') return Boolean(getBenchmarkVariableByPath(workspace, path)) - // The remaining drawer kinds (resources/schedules/triggers) have no deployed - // benchmark stores today. - return false -} - -/** Mirror `DraftService.listDrafts`: metadata rows (no value) for a workspace. */ -export function listBenchmarkDrafts(workspace: string): ListDraftsResponse { - return [...benchmarkDrafts.values()] - .filter((entry) => entry.workspace === workspace) - .map((entry) => ({ - kind: entry.kind, - path: entry.path, - summary: (entry.value as { summary?: string } | null)?.summary, - draft_only: !benchmarkDeployedExists(workspace, entry.kind, entry.path), - legacy_draft: false, - created_at: entry.createdAt - })) -} - -// ============= Datatables (best-effort in-memory SQL) ============= - -/** - * Project the seeded datatables down to the `list_datatable_tables` response: - * `datatable_name` + `schema -> table_names`, with no column detail. - * Returns `null` for a non-benchmark workspace so callers can fall through to - * the real backend; an empty seed yields `[]`. - */ -export function listBenchmarkDatatables(workspace: string): DataTableTables[] | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - if (!runnables) { - return null - } - return (runnables.datatables ?? []).map((datatable) => ({ - datatable_name: datatable.datatable_name, - schemas: Object.fromEntries( - Object.entries(datatable.schemas).map(([schema, tables]) => [schema, Object.keys(tables)]) - ), - ...(datatable.migrations_enabled && { migrations_enabled: true }) - })) -} - -// ============= Datatable migrations ============= - -function benchmarkDatatable(workspace: string, datatableName: string): BenchmarkDatatableSeed { - const datatable = (benchmarkWorkspaceRunnables.get(workspace)?.datatables ?? []).find( - (entry) => entry.datatable_name === datatableName - ) - if (!datatable) { - throw new Error(`datatable "${datatableName}" not found`) - } - return datatable -} - -/** Run a migration body through the in-memory engine, one statement at a time and without the - * transaction frame, so the tables it creates show up in later reads. */ -function applyBenchmarkMigrationSql(datatable: BenchmarkDatatableSeed, sql: string): void { - // Split on the semicolons outside single-quoted literals. - for (const statement of sql.match(/(?:'(?:[^']|'')*'|[^;'])+/g) ?? []) { - const trimmed = statement.replace(/^\s*--.*$/gm, '').trim() - if (trimmed !== '' && !/^(begin|end|commit)$/i.test(trimmed)) { - applyDatatableSql(datatable, trimmed) - } - } -} - -export function getBenchmarkDatatableMigrationsStatus(input: { - workspace: string - datatableName: string -}) { - const datatable = benchmarkDatatable(input.workspace, input.datatableName) - if (!datatable.migrations_enabled) { - return { enabled: false, migrations: [] } - } - return { - enabled: true, - migrations: (datatable.migrations ?? []).map(({ applied, ...migration }) => ({ - ...migration, - status: applied ? ('ran' as const) : ('not_run' as const) - })) - } -} - -export function createBenchmarkDatatableMigration(input: { - workspace: string - datatableName: string - requestBody: { name: string; code_up: string; code_down?: string } -}) { - const datatable = benchmarkDatatable(input.workspace, input.datatableName) - if (!datatable.migrations_enabled) { - throw new Error( - `Migrations are not enabled for data table '${input.datatableName}'. Enable them first.` - ) - } - const migrations = (datatable.migrations ??= []) - const timestamp = Math.max(20260101000000, ...migrations.map((m) => m.timestamp)) + 1 - migrations.push({ timestamp, ...input.requestBody }) - return { datatable: input.datatableName, timestamp, ...input.requestBody } -} - -export function upsertBenchmarkDatatableMigration(input: { - workspace: string - datatableName: string - requestBody: { timestamp: number; name: string; code_up: string; code_down?: string } -}): string { - const datatable = benchmarkDatatable(input.workspace, input.datatableName) - const migrations = (datatable.migrations ??= []) - const existing = migrations.find((m) => m.timestamp === input.requestBody.timestamp) - if (existing?.applied) { - throw new Error( - `Migration ${existing.timestamp} on data table '${input.datatableName}' has already been applied and cannot be modified` - ) - } - if (existing) { - // Replaced whole, as the server does: a down left out is stored as none. - delete existing.code_down - Object.assign(existing, input.requestBody) - } else { - migrations.push({ ...input.requestBody }) - migrations.sort((a, b) => a.timestamp - b.timestamp) - } - return `Upserted migration ${input.requestBody.timestamp} in ${input.datatableName}` -} - -export function runBenchmarkDatatableMigrations(input: { - workspace: string - datatableName: string - upTo?: number - only?: number -}) { - const datatable = benchmarkDatatable(input.workspace, input.datatableName) - const applied: { version: number; name: string }[] = [] - for (const migration of datatable.migrations ?? []) { - if ( - migration.applied || - (input.only !== undefined && migration.timestamp !== input.only) || - (input.only === undefined && input.upTo !== undefined && migration.timestamp > input.upTo) - ) { - continue - } - applyBenchmarkMigrationSql(datatable, migration.code_up) - migration.applied = true - applied.push({ version: migration.timestamp, name: migration.name }) - } - return { applied } -} - -export function rollbackBenchmarkDatatableMigration(input: { - workspace: string - datatableName: string - only?: number -}) { - const datatable = benchmarkDatatable(input.workspace, input.datatableName) - const last = (datatable.migrations ?? []) - .filter((m) => m.applied && (input.only === undefined || m.timestamp === input.only)) - .at(-1) - if (!last) { - return { rolled_back: [] } - } - if (last.code_down === undefined) { - throw new Error( - `Cannot roll back migration ${last.timestamp} (${last.name}): it has no down migration` - ) - } - applyBenchmarkMigrationSql(datatable, last.code_down) - last.applied = false - return { rolled_back: [{ version: last.timestamp, name: last.name }] } -} - -// ============= DuckLake catalogs and declared metrics ============= - -/** Seeded DuckLake names, or `null` for a non-benchmark workspace. */ -export function listBenchmarkDucklakes(workspace: string): string[] | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - return runnables ? (runnables.ducklakes ?? []) : null -} - -/** - * Seeded metric declarations, or `null` for a non-benchmark workspace. - * - * The `table` / `path_prefix` filters are ignored: which rows a filter selects is - * `canonical_table_path`'s business and is pinned by `ducklakeTools.test.ts`. - * Re-deriving it here would give the eval its own copy of that spec to drift from, - * and the case this serves measures whether the model reaches for the tool at all. - */ -export function listBenchmarkDataMetrics(workspace: string): DataMetric[] | null { - const runnables = benchmarkWorkspaceRunnables.get(workspace) - return runnables ? (runnables.dataMetrics ?? []) : null -} - -export function getBenchmarkDatatableSchema(input: { - workspace: string - datatableName: string - schemaName: string - tableName: string -}): DataTableTableSchema { - const runnables = benchmarkWorkspaceRunnables.get(input.workspace) - const datatable = (runnables?.datatables ?? []).find( - (entry) => entry.datatable_name === input.datatableName - ) - if (!datatable) { - // Message MUST match the production `isDatatableNotConfiguredError` regex - // (/datatable\s+\S+\s+not found/i in datatableTools.ts) so the - // get_datatable_table_schema not-configured mapping is actually exercised. - throw new Error(`datatable "${input.datatableName}" not found`) - } - const table = datatable.schemas?.[input.schemaName]?.[input.tableName] - if (!table) { - throw new Error( - `table "${input.schemaName}.${input.tableName}" not found in datatable "${input.datatableName}"` - ) - } - return { - datatable_name: input.datatableName, - schema_name: input.schemaName, - table_name: input.tableName, - columns: table.columns - } -} - -/** - * Execute SQL against a seeded datatable through the best-effort in-memory engine - * (`applyDatatableSql`). Writes (CREATE/INSERT/UPDATE/DELETE/DROP) mutate the - * stored datatable in place so a later list/schema/SELECT reflects them; SELECT - * (and RETURNING) yield rows, other statements yield `[]`. Creates a benchmark - * completed job and returns its id, like `runBenchmarkScriptPreview`. - */ -export function runBenchmarkDatatableSql(input: { - workspace: string - datatableName: string - sql: string -}): string { - const runnables = benchmarkWorkspaceRunnables.get(input.workspace) - const datatable = (runnables?.datatables ?? []).find( - (entry) => entry.datatable_name === input.datatableName - ) - const rows = datatable ? applyDatatableSql(datatable, input.sql).rows : [] - return createBenchmarkCompletedJob({ - workspace: input.workspace, - jobKind: 'preview', - success: true, - args: { database: `datatable://${input.datatableName}` }, - result: rows - }) -} - -/** - * Mirror `JobService.getCompletedJobResultMaybe` for benchmark workspaces — the - * shape `pollJobResult` consumes. The job is created synchronously before - * polling, so it is always present and completed. - */ -export function getBenchmarkCompletedJobResultMaybe(input: { workspace: string; id: string }): { - success: boolean - completed: boolean - result: unknown -} { - const job = getBenchmarkCompletedJob(input.workspace, input.id) - if (!job) { - throw new Error(`Job "${input.id}" not found in benchmark workspace`) - } - return { success: job.success, completed: true, result: job.result } -} - export function runBenchmarkScriptPreview(input: { workspace: string requestBody: { @@ -1311,35 +417,6 @@ export function runBenchmarkScriptPreview(input: { }) } -export function runBenchmarkScriptByPath(input: { - workspace: string - path: string - args?: Record -}): string { - const script = getBenchmarkScriptByPath(input.workspace, input.path) - return createBenchmarkCompletedJob({ - workspace: input.workspace, - jobKind: 'script', - success: script !== null, - scriptPath: input.path, - args: input.args, - result: - script !== null - ? { - path: input.path, - args: input.args ?? {}, - mocked: true - } - : { - error: `Script "${input.path}" not found in benchmark workspace` - }, - logs: - script !== null - ? 'Mock benchmark script run completed successfully.' - : `Script "${input.path}" not found in benchmark workspace.` - }) -} - export function runBenchmarkFlowByPath(input: { workspace: string path: string @@ -1368,18 +445,10 @@ export function runBenchmarkFlowByPath(input: { }) } -/** - * Mirror `JobService.runFlowPreview` for benchmark workspaces, including the server's - * refusal of a chat-enabled flow run that names no conversation (`memory_id`). - */ export function runBenchmarkFlowPreview(input: { workspace: string - memoryId?: string - requestBody?: { path?: string; value?: { chat_input_enabled?: boolean }; args?: unknown } + requestBody?: { path?: string; args?: unknown } }): string { - if (input.requestBody?.value?.chat_input_enabled && !input.memoryId) { - throw new Error('Bad request: memory_id is required for chat-enabled flows') - } const args = (input.requestBody?.args ?? {}) as Record return createBenchmarkCompletedJob({ workspace: input.workspace, @@ -1491,44 +560,11 @@ function buildBenchmarkFlow(flow: BenchmarkWorkspaceFlow): Flow { } as Flow } -function buildBenchmarkListableApp(app: BenchmarkWorkspaceApp): ListableApp { - return { - id: 0, - workspace_id: 'benchmark', - path: app.path, - summary: app.summary, - version: 1, - extra_perms: {}, - edited_at: BENCHMARK_TIMESTAMP, - execution_mode: 'viewer', - raw_app: app.rawApp ?? true - } -} - -function buildBenchmarkApp(app: BenchmarkWorkspaceApp): AppWithLastVersion { - return { - id: 0, - workspace_id: 'benchmark', - path: app.path, - summary: app.summary, - versions: [1], - created_by: 'benchmark', - created_at: BENCHMARK_TIMESTAMP, - value: app.value, - policy: (app.value.policy ?? {}) as AppWithLastVersion['policy'], - execution_mode: 'viewer', - extra_perms: {}, - custom_path: app.value.custom_path as string | undefined, - raw_app: app.rawApp ?? true - } -} - -/** A stand-in Windmill hub. `search_hub_scripts` and a `hub/` read go out over - * relative `/api/...` fetches, which have no origin here, so without these the - * hub tools throw and no case can exercise hub reuse. Serving fixtures rather - * than the live hub also keeps assertions on script content stable as the real - * hub republishes new versions. */ -const BENCHMARK_INTEGRATION_META_PATH = /^\/api\/integrations\/hub\/([^/]+)\/meta$/ +// A stand-in Windmill hub. `search_hub_scripts` and a `hub/` read go out over +// relative `/api/...` fetches, which have no origin here, so without these the +// hub tools throw and no case can exercise hub reuse. Serving fixtures rather +// than the live hub also keeps assertions on script content stable as the real +// hub republishes new versions. /** One integration lifted verbatim from the content repo — its shipped scripts, its * authored meta.json and its resource type. Hand-written fixtures make both routes to @@ -1540,10 +576,6 @@ const REAL_HUB_INTEGRATIONS = [ outreachFixture ] as unknown as Array<{ app: string - display_name: string - description: string - docs_url: string - curated: boolean | null meta: unknown resource_type: { name: string; description: string; schema: unknown } scripts: Array<{ @@ -1791,56 +823,32 @@ function listBenchmarkHubScriptsByApp(app: string | null, kind: string | null) { })) } -/** What `/integrations/hub//meta` serves. Carries the integration's conventions - * and none of the endpoints a case asks the model to write, so the tool shortens the - * path to that knowledge without supplying answers. */ -/** The integrations a case writes against, none of which the content repo documents — - * the same majority shape as the live hub, where 18 of ~216 carry a meta.json. Their - * conventions live in their shipped scripts, which is what these cases exercise. */ -const BENCHMARK_HUB_INTEGRATION_META: Record< - string, - { - display_name: string - description: string - docs_url: string - curated: boolean | null - meta: unknown - } -> = { - baremetrics: { - display_name: 'Baremetrics', - description: 'Subscription analytics for recurring-revenue businesses.', - docs_url: 'https://developers.baremetrics.com/reference', - curated: null, - meta: null - }, - holded: { - display_name: 'Holded', - description: 'Invoicing, accounting and CRM for small businesses.', - docs_url: 'https://developers.holded.com/reference', - curated: null, - meta: null - } +/** Display names of the integrations a case writes against, none of which the content repo + * documents — the same majority shape as the live hub, where 18 of ~216 carry a meta.json. + * Their conventions live in their shipped scripts, which is what these cases exercise. */ +const BENCHMARK_HUB_INTEGRATION_NAMES: Record = { + baremetrics: 'Baremetrics', + holded: 'Holded' } -/** The resource type a mocked hub integration takes, as its metadata serves it. */ +/** The resource type a mocked hub integration takes. */ function benchmarkHubIntegrationResourceType(app: string): BenchmarkWorkspaceResourceType | null { const real = REAL_HUB_INTEGRATIONS.find((integration) => integration.app === app) if (real) { return real.resource_type } - const entry = BENCHMARK_HUB_INTEGRATION_META[app] - if (!entry) { + const displayName = BENCHMARK_HUB_INTEGRATION_NAMES[app] + if (!displayName) { return null } return { name: app, - description: `${entry.display_name} credentials`, + description: `${displayName} credentials`, schema: { type: 'object', required: ['apiKey'], properties: { - apiKey: { type: 'string', description: `${entry.display_name} API key` } + apiKey: { type: 'string', description: `${displayName} API key` } } } } @@ -1848,10 +856,12 @@ function benchmarkHubIntegrationResourceType(app: string): BenchmarkWorkspaceRes /** What a hub-synced instance holds: common hub types, plus the one each mocked hub * integration takes, so the hub and the instance agree on them. */ -function syncedResourceTypes(): BenchmarkWorkspaceResourceType[] { +/** The resource types of an instance synced with the hub, what a fixture that sets no + * `resourceTypes` stands for. */ +export function syncedResourceTypes(): BenchmarkWorkspaceResourceType[] { const integrations = [ ...REAL_HUB_INTEGRATIONS.map((integration) => integration.app), - ...Object.keys(BENCHMARK_HUB_INTEGRATION_META) + ...Object.keys(BENCHMARK_HUB_INTEGRATION_NAMES) ] return [ ...syncedResourceTypesFixture, @@ -1859,46 +869,6 @@ function syncedResourceTypes(): BenchmarkWorkspaceResourceType[] { ] } -/** Mirrors the hub's own derivation: hosts seen in the shipped scripts, whether they - * call the provider directly, and how many there are of each kind. */ -function benchmarkDerivedFacts(app: string) { - const scripts = BENCHMARK_HUB_SCRIPTS.filter((script) => script.app === app) - const hosts = new Map() - const languages: Record = {} - for (const script of scripts) { - languages[script.language] = (languages[script.language] ?? 0) + 1 - for (const match of script.content.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)) { - hosts.set(match[1], (hosts.get(match[1]) ?? 0) + 1) - } - } - return { - api_hosts: [...hosts.entries()] - .sort((a, b) => b[1] - a[1]) - .map(([host, count]) => ({ host, count })), - style: 'fetch', - languages, - script_counts: { - total: scripts.length, - by_kind: scripts.reduce>((acc, script) => { - const kind = script.kind ?? 'script' - acc[kind] = (acc[kind] ?? 0) + 1 - return acc - }, {}) - }, - top_scripts: scripts.map((script) => ({ - path: `hub/${script.version_id}/${script.app}/${script.summary.toLowerCase().replaceAll(/\s+/g, '_')}`, - ask_id: script.version_id, - version_id: script.version_id, - summary: script.summary, - description: script.description ?? null, - kind: script.kind ?? 'script', - language: script.language, - views: 0, - votes: 0 - })) - } -} - /** The hub keys a script by its version id; the app and slug segments that * follow are descriptive, so match on the id exactly as the real hub does. */ function getBenchmarkHubScript(path: string) { @@ -1906,29 +876,6 @@ function getBenchmarkHubScript(path: string) { return BENCHMARK_HUB_SCRIPTS.find((script) => script.version_id === versionId) } -const BENCHMARK_WORKERS = [ - { - worker: 'wk-benchmark-1', - worker_instance: 'benchmark-host', - last_ping: 2, - started_at: BENCHMARK_TIMESTAMP, - jobs_executed: 42, - custom_tags: null, - worker_group: 'default', - wm_version: 'benchmark' - }, - { - worker: 'wk-benchmark-2', - worker_instance: 'benchmark-host', - last_ping: 5, - started_at: BENCHMARK_TIMESTAMP, - jobs_executed: 17, - custom_tags: null, - worker_group: 'default', - wm_version: 'benchmark' - } -] - /** True when `handleBenchmarkApiFetch` has an answer for this `/api/...` url. * Any other relative fetch must keep its normal (non-benchmark) behavior — * intercepting it with a synthetic 404 sends the model into retry loops. */ @@ -1939,11 +886,9 @@ const BENCHMARK_AI_MODELS_PATH = /\/api\/w\/(.+)\/ai\/proxy\/models$/ export function hasBenchmarkApiHandler(url: string): boolean { const path = url.split('?')[0] return ( - path === '/api/workers/list' || path === '/api/embeddings/query_hub_scripts' || path === '/api/scripts/hub/top' || path === '/api/integrations/hub/list' || - BENCHMARK_INTEGRATION_META_PATH.test(path) || path.startsWith('/api/scripts/hub/get_full/') || BENCHMARK_AI_MODELS_PATH.test(path) ) @@ -1952,9 +897,6 @@ export function hasBenchmarkApiHandler(url: string): boolean { /** Answer the relative `/api/...` fetches no mocked service covers. */ export function handleBenchmarkApiFetch(url: string, init?: RequestInit): Response { const path = url.split('?')[0] - if (path === '/api/workers/list') { - return Response.json(BENCHMARK_WORKERS) - } // The provider's own model listing, which grounds an AI agent step's model id. Keyed by the // resource the caller names, so two seeded providers can serve different models. const aiModels = BENCHMARK_AI_MODELS_PATH.exec(path) @@ -1978,53 +920,13 @@ export function handleBenchmarkApiFetch(url: string, init?: RequestInit): Respon asks: listBenchmarkHubScriptsByApp(params.get('app'), params.get('kind')) }) } - const integrationMeta = BENCHMARK_INTEGRATION_META_PATH.exec(path) - if (integrationMeta) { - const app = decodeURIComponent(integrationMeta[1]) - const real = REAL_HUB_INTEGRATIONS.find((integration) => integration.app === app) - if (real) { - return Response.json({ - app, - display_name: real.display_name, - description: real.description, - docs_url: real.docs_url, - curated: real.curated, - metadata_source: real.meta ? 'curated' : 'derived', - meta: real.meta, - meta_updated_at: null, - derived: benchmarkDerivedFacts(app), - resource_types: [{ id: 1, ...benchmarkHubIntegrationResourceType(app) }] - }) - } - const entry = BENCHMARK_HUB_INTEGRATION_META[app] - if (!entry) { - return Response.json({ error: 'integration not found' }, { status: 404 }) - } - return Response.json({ - app, - display_name: entry.display_name, - description: entry.description, - docs_url: entry.docs_url, - curated: entry.curated, - metadata_source: entry.meta ? 'curated' : 'derived', - meta: entry.meta, - meta_updated_at: null, - derived: benchmarkDerivedFacts(app), - resource_types: [{ id: 1, ...benchmarkHubIntegrationResourceType(app) }] - }) - } if (path === '/api/integrations/hub/list') { const apps = [...new Set(BENCHMARK_HUB_SCRIPTS.map((script) => script.app))].sort() - // Read off both fixtures the metadata endpoint serves from, or the list would - // call an integration undocumented and then hand back its authored notes. - const documented = new Set([ - ...REAL_HUB_INTEGRATIONS.filter((integration) => integration.meta).map( + const documented = new Set( + REAL_HUB_INTEGRATIONS.filter((integration) => integration.meta).map( (integration) => integration.app - ), - ...Object.entries(BENCHMARK_HUB_INTEGRATION_META) - .filter(([, entry]) => entry.meta) - .map(([app]) => app) - ]) + ) + ) return Response.json(apps.map((name) => ({ name, documented: documented.has(name) }))) } if (path.startsWith('/api/scripts/hub/get_full/')) { diff --git a/ai_evals/adapters/frontend/mockBackendApi.test.ts b/ai_evals/adapters/frontend/mockBackendApi.test.ts deleted file mode 100644 index b3829e56da..0000000000 --- a/ai_evals/adapters/frontend/mockBackendApi.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { describe, expect, it } from 'bun:test' -import { handleBenchmarkApiFetch, hasBenchmarkApiHandler } from './mockBackend' - -// `list_workers`'s client call is not faked, so its request really does leave as a relative -// `/api/...` url that node's fetch cannot resolve. Without this route the tool throws instead -// of answering. -describe('benchmark API fetch handlers', () => { - it('lists workers, the way list_workers reaches them', async () => { - const url = '/api/workers/list?per_page=100' - - expect(hasBenchmarkApiHandler(url)).toBe(true) - const body = await handleBenchmarkApiFetch(url).json() - - // The tool counts the list and maps over it, so it needs a bare array, not an envelope. - expect(Array.isArray(body)).toBe(true) - expect(body[0]).toMatchObject({ worker: expect.any(String), worker_group: expect.any(String) }) - }) -}) - -// A benchmark whose list calls an integration undocumented while its metadata endpoint -// hands back authored notes teaches the model the flag means nothing. -describe('benchmark hub integration list', () => { - it('flags exactly the integrations whose metadata carries authored notes', async () => { - const listed = (await handleBenchmarkApiFetch('/api/integrations/hub/list').json()) as Array<{ - name: string - documented: boolean - }> - expect(listed.length).toBeGreaterThan(0) - - for (const { name, documented } of listed) { - const res = handleBenchmarkApiFetch(`/api/integrations/hub/${name}/meta`) - const authored = res.status === 200 && !!((await res.json()) as { meta?: unknown }).meta - expect(authored).toBe(documented) - } - }) -}) diff --git a/ai_evals/adapters/frontend/mockBackendDatatables.test.ts b/ai_evals/adapters/frontend/mockBackendDatatables.test.ts deleted file mode 100644 index 5d12ebb661..0000000000 --- a/ai_evals/adapters/frontend/mockBackendDatatables.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'bun:test' -import { - getBenchmarkCompletedJobResultMaybe, - getBenchmarkDatatableSchema, - listBenchmarkDatatables, - registerBenchmarkWorkspaceRunnables, - resetBenchmarkMockBackend, - runBenchmarkDatatableSql, - type BenchmarkWorkspaceRunnables -} from './mockBackend' - -const WORKSPACE = 'benchmark-datatable-ws' - -// Mirrors the production `isDatatableNotConfiguredError` regex in -// datatableTools.ts. The schema mock's "not configured" message MUST match it, -// otherwise the not-configured mapping in get_datatable_table_schema is silently -// untested. -const NOT_CONFIGURED_RE = /datatable\s+\S+\s+not found/i - -const SEED: BenchmarkWorkspaceRunnables = { - datatables: [ - { - datatable_name: 'main', - schemas: { - public: { - orders: { - columns: { id: 'int', total: 'numeric' }, - rows: [ - { id: 1, total: 10 }, - { id: 2, total: 20 } - ] - }, - customers: { - columns: { id: 'int', name: 'text' }, - rows: [{ id: 1, name: 'alice' }] - } - } - } - } - ] -} - -beforeEach(() => resetBenchmarkMockBackend()) -afterEach(() => resetBenchmarkMockBackend()) - -describe('listBenchmarkDatatables', () => { - it('returns null for a non-benchmark workspace (caller falls through to real backend)', () => { - expect(listBenchmarkDatatables('unregistered')).toBeNull() - }) - - it('returns [] for a registered workspace with no datatables seed', () => { - registerBenchmarkWorkspaceRunnables(WORKSPACE, {}) - expect(listBenchmarkDatatables(WORKSPACE)).toEqual([]) - }) - - it('projects seeded datatables to schema -> table names only (no columns)', () => { - registerBenchmarkWorkspaceRunnables(WORKSPACE, SEED) - expect(listBenchmarkDatatables(WORKSPACE)).toEqual([ - { datatable_name: 'main', schemas: { public: ['orders', 'customers'] } } - ]) - }) -}) - -describe('getBenchmarkDatatableSchema', () => { - beforeEach(() => registerBenchmarkWorkspaceRunnables(WORKSPACE, SEED)) - - it('returns the columns for a seeded table', () => { - expect( - getBenchmarkDatatableSchema({ - workspace: WORKSPACE, - datatableName: 'main', - schemaName: 'public', - tableName: 'orders' - }) - ).toEqual({ - datatable_name: 'main', - schema_name: 'public', - table_name: 'orders', - columns: { id: 'int', total: 'numeric' } - }) - }) - - it('throws a not-configured error matching the production regex for an unknown datatable', () => { - let error: Error | undefined - try { - getBenchmarkDatatableSchema({ - workspace: WORKSPACE, - datatableName: 'ghost', - schemaName: 'public', - tableName: 'orders' - }) - } catch (e) { - error = e as Error - } - expect(error).toBeDefined() - expect(error!.message).toMatch(NOT_CONFIGURED_RE) - }) - - it('throws a table-not-found error that does NOT match the datatable-not-configured regex', () => { - // The datatable IS configured; only the table is missing. Production maps - // this to a generic "error getting schema", not the blocking message. - let error: Error | undefined - try { - getBenchmarkDatatableSchema({ - workspace: WORKSPACE, - datatableName: 'main', - schemaName: 'public', - tableName: 'ghost' - }) - } catch (e) { - error = e as Error - } - expect(error).toBeDefined() - expect(error!.message).not.toMatch(NOT_CONFIGURED_RE) - }) -}) - -describe('runBenchmarkDatatableSql + getBenchmarkCompletedJobResultMaybe', () => { - beforeEach(() => registerBenchmarkWorkspaceRunnables(WORKSPACE, SEED)) - - function exec(sql: string): { success: boolean; completed: boolean; result: unknown } { - const jobId = runBenchmarkDatatableSql({ workspace: WORKSPACE, datatableName: 'main', sql }) - return getBenchmarkCompletedJobResultMaybe({ workspace: WORKSPACE, id: jobId }) - } - - it('returns the canned rows of the table named in a SELECT FROM clause', () => { - expect(exec('SELECT * FROM customers')).toEqual({ - success: true, - completed: true, - result: [{ id: 1, name: 'alice' }] - }) - }) - - it('falls back to the first seeded table when the SELECT references no known table', () => { - expect(exec('select 1').result).toEqual([ - { id: 1, total: 10 }, - { id: 2, total: 20 } - ]) - }) - - it('returns [] success for DDL and DML statements without RETURNING', () => { - expect(exec('CREATE TABLE foo (id int)').result).toEqual([]) - expect(exec('INSERT INTO orders VALUES (3, 30)').result).toEqual([]) - expect(exec('update orders set total = 0').result).toEqual([]) - }) - - it('reflects a write in a later SELECT, isolated from the shared seed', () => { - exec('UPDATE orders SET total = 999 WHERE id = 1') - expect((exec('SELECT * FROM orders').result as Record[])).toContainEqual({ - id: 1, - total: 999 - }) - // Registration deep-clones the seed, so the shared SEED const stays pristine. - expect(SEED.datatables![0].schemas.public.orders.rows).toContainEqual({ id: 1, total: 10 }) - }) - - it('reflects a CREATE in list_datatables and get_datatable_table_schema', () => { - exec('CREATE TABLE public.refunds (order_id int4, amount numeric)') - expect(listBenchmarkDatatables(WORKSPACE)?.[0].schemas.public).toContain('refunds') - expect( - getBenchmarkDatatableSchema({ - workspace: WORKSPACE, - datatableName: 'main', - schemaName: 'public', - tableName: 'refunds' - }).columns - ).toEqual({ order_id: 'int4', amount: 'numeric' }) - }) - - it('throws for an unknown job id', () => { - expect(() => - getBenchmarkCompletedJobResultMaybe({ workspace: WORKSPACE, id: 'does-not-exist' }) - ).toThrow() - }) -}) diff --git a/ai_evals/adapters/frontend/mockBackendDrafts.test.ts b/ai_evals/adapters/frontend/mockBackendDrafts.test.ts deleted file mode 100644 index 0ab79d216e..0000000000 --- a/ai_evals/adapters/frontend/mockBackendDrafts.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'bun:test' -import { - clearBenchmarkDrafts, - getBenchmarkDraftForUser, - getBenchmarkOwnDraft, - listBenchmarkDrafts, - resetBenchmarkMockBackend, - seedBenchmarkDraft, - updateBenchmarkDraft -} from './mockBackend' - -const WORKSPACE = 'benchmark-drafts-ws' - -// Drives the in-memory stand-in for the per-user draft backend (`DraftService`) -// that the global AI-chat eval round-trips its drafts through. Mirrors the -// production-unit-test mock in -// `frontend/src/lib/components/copilot/chat/global/core.test.ts`. -describe('mockBackend drafts', () => { - beforeEach(() => resetBenchmarkMockBackend()) - afterEach(() => resetBenchmarkMockBackend()) - - it('round-trips a saved draft through update / get / list', () => { - const value = { summary: 'Greet a user', content: 'export async function main() {}' } - const res = updateBenchmarkDraft({ - workspace: WORKSPACE, - kind: 'script', - path: 'f/evals/greet', - requestBody: { value } - }) - expect(res.status).toBe('saved') - - expect(getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/greet' }).value).toEqual( - value - ) - - const rows = listBenchmarkDrafts(WORKSPACE) - expect(rows).toHaveLength(1) - expect(rows[0]).toMatchObject({ kind: 'script', path: 'f/evals/greet', summary: 'Greet a user', draft_only: true }) - }) - - it('treats a null value as a delete', () => { - updateBenchmarkDraft({ - workspace: WORKSPACE, - kind: 'variable', - path: 'f/evals/token', - requestBody: { value: { summary: 'token' } } - }) - updateBenchmarkDraft({ - workspace: WORKSPACE, - kind: 'variable', - path: 'f/evals/token', - requestBody: { value: null } - }) - - expect(listBenchmarkDrafts(WORKSPACE)).toHaveLength(0) - expect(() => getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'variable', path: 'f/evals/token' })).toThrow() - }) - - it('returns null from getOwnDraft when no draft exists', () => { - expect( - getBenchmarkOwnDraft({ workspace: WORKSPACE, kind: 'trigger_schedule', path: 'u/evals/missing' }) - ).toBeNull() - }) - - // The global chat hydrates drawer-kind drafts (schedule/trigger/resource/variable) - // through getOwnDraft — getDraftForUser rejects those kinds as private. - it('hydrates a saved drawer-kind draft through getOwnDraft', () => { - const value = { path: 'u/evals/nightly', schedule: '0 0 9 * * *' } - updateBenchmarkDraft({ - workspace: WORKSPACE, - kind: 'trigger_schedule', - path: 'u/evals/nightly', - requestBody: { value } - }) - expect( - getBenchmarkOwnDraft({ workspace: WORKSPACE, kind: 'trigger_schedule', path: 'u/evals/nightly' })?.value - ).toEqual(value) - }) - - it('throws a 404-shaped error when no draft exists', () => { - try { - getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/missing' }) - throw new Error('expected a throw') - } catch (e) { - expect((e as { status?: number }).status).toBe(404) - } - }) - - it('seeds a draft as a backend row that a later edit overwrites', () => { - seedBenchmarkDraft(WORKSPACE, 'script', 'f/evals/current', { content: 'seed' }) - expect(getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/current' }).value).toEqual({ - content: 'seed' - }) - - // A model edit persists the same path and must win over the seed. - updateBenchmarkDraft({ - workspace: WORKSPACE, - kind: 'script', - path: 'f/evals/current', - requestBody: { value: { content: 'edited' } } - }) - expect(getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/current' }).value).toEqual({ - content: 'edited' - }) - }) - - it('clears only the targeted workspace', () => { - seedBenchmarkDraft(WORKSPACE, 'script', 'f/a', { content: 'a' }) - seedBenchmarkDraft('other-ws', 'script', 'f/b', { content: 'b' }) - - clearBenchmarkDrafts(WORKSPACE) - - expect(listBenchmarkDrafts(WORKSPACE)).toHaveLength(0) - expect(listBenchmarkDrafts('other-ws')).toHaveLength(1) - }) -}) diff --git a/ai_evals/adapters/frontend/vitestAdapter.test.ts b/ai_evals/adapters/frontend/vitestAdapter.test.ts index 754de224ac..b7529dc0d2 100644 --- a/ai_evals/adapters/frontend/vitestAdapter.test.ts +++ b/ai_evals/adapters/frontend/vitestAdapter.test.ts @@ -8,6 +8,7 @@ import { fileURLToPath } from 'url' import { handleBenchmarkApiFetch, hasBenchmarkApiHandler } from './mockBackend' import { resolveWindmillBackendSettings } from '../../core/windmillBackendSettings' import { WindmillBackendClient } from './windmillBackend' +import { realWorkspaceRoute } from './core/global/realWorkspace' const FRONTEND_DIR = fileURLToPath(new URL('../../../frontend/', import.meta.url)) @@ -30,6 +31,13 @@ globalThis.fetch = (async (input: unknown, init?: RequestInit) => { if (typeof url === 'string' && hasBenchmarkApiHandler(url)) { return handleBenchmarkApiFetch(url, init) } + // A global-mode case runs against a real workspace: send its calls there, as its user. + const real = typeof url === 'string' ? realWorkspaceRoute(url) : undefined + if (real) { + const headers = new Headers(init?.headers) + headers.set('Authorization', `Bearer ${real.token}`) + return ORIGINAL_FETCH(real.url, { ...init, headers }) + } // The docs tools read the documentation bundled into the backend: hand them to the // benchmark's real backend, logged in like the AI proxy calls. if (typeof url === 'string' && url.startsWith('/api/docs/')) { @@ -119,60 +127,21 @@ vi.mock('$lib/components/apps/components/display/dbtable/metadata', async () => vi.mock('$lib/gen', async () => { const actual = await vi.importActual('$lib/gen') const { - getBenchmarkAppByPath, - getBenchmarkJob, - getBenchmarkCompletedJobResultMaybe, - listBenchmarkWorkers, - listBenchmarkSchedules, - getBenchmarkSchedule, - listBenchmarkFolders, - getBenchmarkFolder, - getBenchmarkGroup, - listBenchmarkGroups, - getBenchmarkWorkspaceSettingsDocument, - applyBenchmarkWorkspaceSettingsDocument, - getBenchmarkDatatableSchema, - getBenchmarkDatatableMigrationsStatus, - createBenchmarkDatatableMigration, - upsertBenchmarkDatatableMigration, - runBenchmarkDatatableMigrations, - rollbackBenchmarkDatatableMigration, - getBenchmarkDraftForUser, + getBenchmarkCompletedJob, getBenchmarkFlowByPath, - getBenchmarkFlowAllResults, - getBenchmarkJobLogs, - getBenchmarkOwnDraft, getBenchmarkScriptByHash, getBenchmarkScriptByPath, - getBenchmarkAiConfig, - getBenchmarkResourceValue, - getBenchmarkVariableByPath, hasBenchmarkWorkspace, - getBenchmarkResource, - listBenchmarkAiProviderResources, - listBenchmarkPlainResources, listBenchmarkResourceTypeNames, queryBenchmarkResourceTypes, - createBenchmarkResourceType, - listBenchmarkApps, - listBenchmarkDatatables, - listBenchmarkDataMetrics, - listBenchmarkDrafts, - listBenchmarkDucklakes, listBenchmarkFlows, - listBenchmarkJobs, listBenchmarkScripts, - listBenchmarkVariables, - createBenchmarkFolder, createBenchmarkHttpTrigger, createBenchmarkSchedule, previewBenchmarkSchedule, - runBenchmarkDatatableSql, runBenchmarkFlowByPath, runBenchmarkFlowPreview, - runBenchmarkScriptByPath, - runBenchmarkScriptPreview, - updateBenchmarkDraft + runBenchmarkScriptPreview } = await import('./mockBackend') function wrapService(target: T, overrides: Record): T { @@ -188,104 +157,23 @@ vi.mock('$lib/gen', async () => { return { ...actual, - DraftService: wrapService(actual.DraftService, { - updateDraft: async (data: { - workspace: string - kind: any - path: string - requestBody?: { value?: unknown } - }) => - hasBenchmarkWorkspace(data.workspace) - ? updateBenchmarkDraft(data) - : actual.DraftService.updateDraft(data), - getDraftForUser: async (data: { workspace: string; kind: any; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? getBenchmarkDraftForUser(data) - : actual.DraftService.getDraftForUser(data), - getOwnDraft: async (data: { workspace: string; kind: any; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? getBenchmarkOwnDraft(data) - : actual.DraftService.getOwnDraft(data), - listDrafts: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? listBenchmarkDrafts(data.workspace) - : actual.DraftService.listDrafts(data) - }), - FolderService: wrapService(actual.FolderService, { - createFolder: async (data: { workspace: string; requestBody: { name: string } }) => - hasBenchmarkWorkspace(data.workspace) - ? createBenchmarkFolder(data.workspace, data.requestBody.name) - : 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 }) => hasBenchmarkWorkspace(data.workspace) ? (listBenchmarkScripts(data.workspace) ?? []) : actual.ScriptService.listScripts(data), - existsScriptByPath: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? Boolean(getBenchmarkScriptByPath(data.workspace, data.path)) - : actual.ScriptService.existsScriptByPath(data), - getScriptByPath: async (data: { workspace: string; path: string; getDraft?: boolean }) => { + getScriptByPath: async (data: { workspace: string; path: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { const script = getBenchmarkScriptByPath(data.workspace, data.path) - // `getDraft` mirrors production's overlay: the row plus the caller's - // draft and a `no_deployed` marker (draft-only item). The diff tool - // reads through this shape — without it every draft looks absent. - const draft = data.getDraft - ? getBenchmarkOwnDraft({ workspace: data.workspace, kind: 'script', path: data.path }) - : null if (!script) { - if (data.getDraft && draft) { - return { - ...(draft.value as Record), - path: data.path, - draft: draft.value, - no_deployed: true - } - } throw Object.assign( new Error(`Script "${data.path}" not found in benchmark workspace`), { status: 404 } ) } - return data.getDraft - ? { ...script, draft: draft?.value ?? undefined, no_deployed: false } - : script - } - return actual.ScriptService.getScriptByPath(data) - }, - getScriptByPathWithDraft: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - const script = getBenchmarkScriptByPath(data.workspace, data.path) - if (!script) { - throw new Error(`Script "${data.path}" not found in benchmark workspace`) - } return script } - return actual.ScriptService.getScriptByPathWithDraft(data) + return actual.ScriptService.getScriptByPath(data) }, getScriptByHash: async (data: { workspace: string; hash: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { @@ -303,56 +191,18 @@ vi.mock('$lib/gen', async () => { hasBenchmarkWorkspace(data.workspace) ? (listBenchmarkFlows(data.workspace) ?? []) : actual.FlowService.listFlows(data), - existsFlowByPath: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? Boolean(getBenchmarkFlowByPath(data.workspace, data.path)) - : actual.FlowService.existsFlowByPath(data), - getFlowByPath: async (data: { workspace: string; path: string; getDraft?: boolean }) => { + getFlowByPath: async (data: { workspace: string; path: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { const flow = getBenchmarkFlowByPath(data.workspace, data.path) - // Mirror production's `getDraft` overlay (see getScriptByPath above). - const draft = data.getDraft - ? getBenchmarkOwnDraft({ workspace: data.workspace, kind: 'flow', path: data.path }) - : null if (!flow) { - if (data.getDraft && draft) { - return { - ...(draft.value as Record), - path: data.path, - draft: draft.value, - no_deployed: true - } - } throw Object.assign( new Error(`Flow "${data.path}" not found in benchmark workspace`), { status: 404 } ) } - return data.getDraft - ? { ...flow, draft: draft?.value ?? undefined, no_deployed: false } - : flow - } - return actual.FlowService.getFlowByPath(data) - }, - getFlowByPathWithDraft: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - const flow = getBenchmarkFlowByPath(data.workspace, data.path) - if (!flow) { - throw new Error(`Flow "${data.path}" not found in benchmark workspace`) - } return flow } - return actual.FlowService.getFlowByPathWithDraft(data) - }, - getFlowLatestVersion: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - const flow = getBenchmarkFlowByPath(data.workspace, data.path) - if (!flow) { - throw new Error(`Flow "${data.path}" not found in benchmark workspace`) - } - return { id: 1 } - } - return actual.FlowService.getFlowLatestVersion(data) + return actual.FlowService.getFlowByPath(data) } }), JobService: wrapService(actual.JobService, { @@ -364,43 +214,16 @@ vi.mock('$lib/gen', async () => { args?: Record path?: string } - }) => { - if (!hasBenchmarkWorkspace(data.workspace)) { - return actual.JobService.runScriptPreview(data) - } - const requestBody = data.requestBody ?? {} - const database = requestBody.args?.database - // Datatable SQL runs as a `postgresql` preview against `datatable://`. - // Execute it through the canned-SQL mock instead of linting it as a script. - if ( - requestBody.language === 'postgresql' && - typeof database === 'string' && - database.startsWith('datatable://') - ) { - return runBenchmarkDatatableSql({ - workspace: data.workspace, - datatableName: database.slice('datatable://'.length), - sql: requestBody.content ?? '' - }) - } - return runBenchmarkScriptPreview({ workspace: data.workspace, requestBody }) - }, - runScriptByPath: async (data: { - workspace: string - path: string - requestBody?: Record }) => hasBenchmarkWorkspace(data.workspace) - ? runBenchmarkScriptByPath({ + ? runBenchmarkScriptPreview({ workspace: data.workspace, - path: data.path, - args: data.requestBody + requestBody: data.requestBody ?? {} }) - : actual.JobService.runScriptByPath(data), + : actual.JobService.runScriptPreview(data), runFlowPreview: async (data: { workspace: string - memoryId?: string - requestBody?: { path?: string; value?: { chat_input_enabled?: boolean }; args?: unknown } + requestBody?: { path?: string; args?: unknown } }) => hasBenchmarkWorkspace(data.workspace) ? runBenchmarkFlowPreview(data) @@ -426,24 +249,10 @@ vi.mock('$lib/gen', async () => { return job } return actual.JobService.getJob(data) - }, - getCompletedJobResultMaybe: async (data: { workspace: string; id: string }) => - hasBenchmarkWorkspace(data.workspace) - ? getBenchmarkCompletedJobResultMaybe({ workspace: data.workspace, id: data.id }) - : actual.JobService.getCompletedJobResultMaybe(data), - listJobs: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? (listBenchmarkJobs(data.workspace) ?? []) - : actual.JobService.listJobs(data), - getJobLogs: async (data: { workspace: string; id: string }) => - hasBenchmarkWorkspace(data.workspace) - ? getBenchmarkJobLogs(data.workspace, data.id) - : actual.JobService.getJobLogs(data), - getFlowAllResults: async (data: { workspace: string; id: string }) => - hasBenchmarkWorkspace(data.workspace) - ? getBenchmarkFlowAllResults(data.workspace, data.id) - : actual.JobService.getFlowAllResults(data) + } }), + // A benchmark workspace holds no resources and no AI settings: answer as an empty + // workspace would, rather than send its temp-directory id to the real backend. WorkspaceService: wrapService(actual.WorkspaceService, { getWorkspaceSettingsDocument: async (data: { workspace: string }) => hasBenchmarkWorkspace(data.workspace) @@ -454,77 +263,13 @@ vi.mock('$lib/gen', async () => { ? applyBenchmarkWorkspaceSettingsDocument(data) : actual.WorkspaceService.applyWorkspaceSettingsDocument(data), getCopilotInfo: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? (getBenchmarkAiConfig(data.workspace) ?? {}) - : actual.WorkspaceService.getCopilotInfo(data), - listDataTableTables: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? (listBenchmarkDatatables(data.workspace) ?? []) - : actual.WorkspaceService.listDataTableTables(data), - listDucklakes: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? (listBenchmarkDucklakes(data.workspace) ?? []) - : actual.WorkspaceService.listDucklakes(data), - getDataTableTableSchema: async (data: { - workspace: string - datatableName: string - schemaName: string - tableName: string - }) => - hasBenchmarkWorkspace(data.workspace) - ? getBenchmarkDatatableSchema({ - workspace: data.workspace, - datatableName: data.datatableName, - schemaName: data.schemaName, - tableName: data.tableName - }) - : actual.WorkspaceService.getDataTableTableSchema(data), - getDatatableMigrationsStatus: async (data: any) => - hasBenchmarkWorkspace(data.workspace) - ? getBenchmarkDatatableMigrationsStatus(data) - : actual.WorkspaceService.getDatatableMigrationsStatus(data), - createDatatableMigration: async (data: any) => - hasBenchmarkWorkspace(data.workspace) - ? createBenchmarkDatatableMigration(data) - : actual.WorkspaceService.createDatatableMigration(data), - upsertDatatableMigration: async (data: any) => - hasBenchmarkWorkspace(data.workspace) - ? upsertBenchmarkDatatableMigration(data) - : actual.WorkspaceService.upsertDatatableMigration(data), - runDatatableMigrations: async (data: any) => - hasBenchmarkWorkspace(data.workspace) - ? runBenchmarkDatatableMigrations(data) - : actual.WorkspaceService.runDatatableMigrations(data), - rollbackDatatableMigrations: async (data: any) => - hasBenchmarkWorkspace(data.workspace) - ? rollbackBenchmarkDatatableMigration(data) - : actual.WorkspaceService.rollbackDatatableMigrations(data) - }), - DataMetricService: wrapService(actual.DataMetricService, { - listDataMetrics: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? { metrics: listBenchmarkDataMetrics(data.workspace) ?? [] } - : actual.DataMetricService.listDataMetrics(data) + hasBenchmarkWorkspace(data.workspace) ? {} : actual.WorkspaceService.getCopilotInfo(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) - ? 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) - }, previewSchedule: async (data: { requestBody?: Record }) => previewBenchmarkSchedule(data), createSchedule: async (data: { workspace: string; requestBody: Record }) => @@ -533,254 +278,27 @@ vi.mock('$lib/gen', async () => { : actual.ScheduleService.createSchedule(data) }), ResourceService: wrapService(actual.ResourceService, { - existsResource: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? Boolean(getBenchmarkResourceValue(data.workspace, data.path)) - : actual.ResourceService.existsResource(data), - listResource: async (data: { workspace: string; resourceType?: string }) => { - if (!hasBenchmarkWorkspace(data.workspace)) { - return actual.ResourceService.listResource(data) - } - const seeded = [ - ...(listBenchmarkAiProviderResources(data.workspace) ?? []), - ...(listBenchmarkPlainResources(data.workspace) ?? []) - ] - const wanted = data.resourceType?.split(',') - return wanted ? seeded.filter((r) => wanted.includes(r.resource_type)) : seeded - }, + listResource: async (data: { workspace: string }) => + hasBenchmarkWorkspace(data.workspace) ? [] : actual.ResourceService.listResource(data), getResource: async (data: { workspace: string; path: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { - const resource = getBenchmarkResource(data.workspace, data.path) - if (!resource) { - throw new Error(`Resource "${data.path}" not found in benchmark workspace`) - } - return resource + throw new Error(`Resource "${data.path}" not found in benchmark workspace`) } return actual.ResourceService.getResource(data) }, - getResourceValue: async (data: { workspace: string; path: string }) => { - if (!hasBenchmarkWorkspace(data.workspace)) { - return actual.ResourceService.getResourceValue(data) - } - const value = getBenchmarkResourceValue(data.workspace, data.path) - if (!value) { - throw new Error(`Resource "${data.path}" not found in benchmark workspace`) - } - return value - }, queryResourceTypes: async (data: { workspace: string; text: string; limit?: number }) => hasBenchmarkWorkspace(data.workspace) - ? queryBenchmarkResourceTypes(data.workspace, data.text, data.limit) + ? queryBenchmarkResourceTypes(data.text, data.limit) : actual.ResourceService.queryResourceTypes(data), listResourceTypeNames: async (data: { workspace: string }) => listBenchmarkResourceTypeNames(data.workspace) ?? - actual.ResourceService.listResourceTypeNames(data), - createResourceType: async (data: { - workspace: string - requestBody: { name: string; schema?: unknown; description?: string } - }) => { - if (!hasBenchmarkWorkspace(data.workspace)) { - return actual.ResourceService.createResourceType(data) - } - createBenchmarkResourceType(data.workspace, data.requestBody) - return `resource_type ${data.requestBody.name} created` - } - }), - VariableService: wrapService(actual.VariableService, { - existsVariable: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? Boolean(getBenchmarkVariableByPath(data.workspace, data.path)) - : actual.VariableService.existsVariable(data), - listVariable: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? (listBenchmarkVariables(data.workspace) ?? []) - : actual.VariableService.listVariable(data), - getVariable: async (data: { - workspace: string - path: string - decryptSecret?: boolean - }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - const variable = getBenchmarkVariableByPath( - data.workspace, - data.path, - data.decryptSecret ?? true - ) - if (!variable) { - throw new Error(`Variable "${data.path}" not found in benchmark workspace`) - } - return variable - } - return actual.VariableService.getVariable(data) - } - }), - AppService: wrapService(actual.AppService, { - existsApp: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? Boolean(getBenchmarkAppByPath(data.workspace, data.path)) - : actual.AppService.existsApp(data), - listApps: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? (listBenchmarkApps(data.workspace) ?? []) - : actual.AppService.listApps(data), - getAppByPath: async (data: { - workspace: string - path: string - getDraft?: boolean - rawApp?: boolean - }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - const app = getBenchmarkAppByPath(data.workspace, data.path) - // Mirror production's `getDraft` overlay (see getScriptByPath above). - // Benchmark app drafts live under the raw_app kind. - const draft = data.getDraft - ? getBenchmarkOwnDraft({ workspace: data.workspace, kind: 'raw_app', path: data.path }) - : null - if (!app) { - if (data.getDraft && draft) { - return { - ...(draft.value as Record), - path: data.path, - raw_app: true, - draft: draft.value, - no_deployed: true - } - } - throw Object.assign( - new Error(`App "${data.path}" not found in benchmark workspace`), - { status: 404 } - ) - } - return data.getDraft - ? { ...app, draft: draft?.value ?? undefined, no_deployed: false } - : app - } - return actual.AppService.getAppByPath(data) - } + actual.ResourceService.listResourceTypeNames(data) }), HttpTriggerService: wrapService(actual.HttpTriggerService, { - existsHttpTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) ? false : actual.HttpTriggerService.existsHttpTrigger(data), - listHttpTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.HttpTriggerService.listHttpTriggers(data), - getHttpTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`HTTP trigger "${data.path}" not found in benchmark workspace`) - } - return actual.HttpTriggerService.getHttpTrigger(data) - }, createHttpTrigger: async (data: { workspace: string; requestBody: Record }) => hasBenchmarkWorkspace(data.workspace) ? createBenchmarkHttpTrigger(data) : actual.HttpTriggerService.createHttpTrigger(data) - }), - WebsocketTriggerService: wrapService(actual.WebsocketTriggerService, { - existsWebsocketTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? false - : actual.WebsocketTriggerService.existsWebsocketTrigger(data), - listWebsocketTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? [] - : actual.WebsocketTriggerService.listWebsocketTriggers(data), - getWebsocketTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`Websocket trigger "${data.path}" not found in benchmark workspace`) - } - return actual.WebsocketTriggerService.getWebsocketTrigger(data) - } - }), - KafkaTriggerService: wrapService(actual.KafkaTriggerService, { - existsKafkaTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? false - : actual.KafkaTriggerService.existsKafkaTrigger(data), - listKafkaTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.KafkaTriggerService.listKafkaTriggers(data), - getKafkaTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`Kafka trigger "${data.path}" not found in benchmark workspace`) - } - return actual.KafkaTriggerService.getKafkaTrigger(data) - } - }), - NatsTriggerService: wrapService(actual.NatsTriggerService, { - existsNatsTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) ? false : actual.NatsTriggerService.existsNatsTrigger(data), - listNatsTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.NatsTriggerService.listNatsTriggers(data), - getNatsTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`NATS trigger "${data.path}" not found in benchmark workspace`) - } - return actual.NatsTriggerService.getNatsTrigger(data) - } - }), - PostgresTriggerService: wrapService(actual.PostgresTriggerService, { - existsPostgresTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? false - : actual.PostgresTriggerService.existsPostgresTrigger(data), - listPostgresTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) - ? [] - : actual.PostgresTriggerService.listPostgresTriggers(data), - getPostgresTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`Postgres trigger "${data.path}" not found in benchmark workspace`) - } - return actual.PostgresTriggerService.getPostgresTrigger(data) - } - }), - MqttTriggerService: wrapService(actual.MqttTriggerService, { - existsMqttTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) ? false : actual.MqttTriggerService.existsMqttTrigger(data), - listMqttTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.MqttTriggerService.listMqttTriggers(data), - getMqttTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`MQTT trigger "${data.path}" not found in benchmark workspace`) - } - return actual.MqttTriggerService.getMqttTrigger(data) - } - }), - SqsTriggerService: wrapService(actual.SqsTriggerService, { - existsSqsTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) ? false : actual.SqsTriggerService.existsSqsTrigger(data), - listSqsTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.SqsTriggerService.listSqsTriggers(data), - getSqsTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`SQS trigger "${data.path}" not found in benchmark workspace`) - } - return actual.SqsTriggerService.getSqsTrigger(data) - } - }), - GcpTriggerService: wrapService(actual.GcpTriggerService, { - existsGcpTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) ? false : actual.GcpTriggerService.existsGcpTrigger(data), - listGcpTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.GcpTriggerService.listGcpTriggers(data), - getGcpTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`GCP trigger "${data.path}" not found in benchmark workspace`) - } - return actual.GcpTriggerService.getGcpTrigger(data) - } - }), - AzureTriggerService: wrapService(actual.AzureTriggerService, { - existsAzureTrigger: async (data: { workspace: string; path: string }) => - hasBenchmarkWorkspace(data.workspace) - ? false - : actual.AzureTriggerService.existsAzureTrigger(data), - listAzureTriggers: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.AzureTriggerService.listAzureTriggers(data), - getAzureTrigger: async (data: { workspace: string; path: string }) => { - if (hasBenchmarkWorkspace(data.workspace)) { - throw new Error(`Azure trigger "${data.path}" not found in benchmark workspace`) - } - return actual.AzureTriggerService.getAzureTrigger(data) - } }) } }) diff --git a/ai_evals/cases/global.yaml b/ai_evals/cases/global.yaml index f0df4ae6e3..b258c3822a 100644 --- a/ai_evals/cases/global.yaml +++ b/ai_evals/cases/global.yaml @@ -1989,6 +1989,153 @@ - does not misuse `-- materialize` for the S3 Parquet export (materialize is DuckLake-only; the S3 output is written by the script body, e.g. a DuckDB COPY or an SDK write) - leaves all three nodes as AI drafts without deploying or saving +- id: global-pipeline-run-orders-daily + prompt: |- + Our raw order exports land as CSV files under `raw/orders/` in the workspace + object storage. Build a data pipeline in the `shop` folder: one step that loads + all of them into a DuckLake table called `orders`, and a second step that builds + an `orders_daily` table with the number of orders and the total revenue for each + day. The daily table should rebuild by itself whenever `orders` is refreshed. + Keep everything as drafts, don't deploy. + initial: ai_evals/fixtures/frontend/global/initial/pipeline_orders_storage.json + runtime: + maxTurns: 16 + validate: + draftCountAtLeast: 2 + forbiddenDrafts: + - type: flow + pathStartsWith: f/shop/ + # The harness deploys the drafted nodes, runs the ones nothing upstream feeds, and lets + # the asset triggers run the rest: the rollup only fills if its `on` wiring is right. + pipelineRun: + folder: shop + # Only the ingest starts the pipeline; the rollup has to be reached by its trigger. + maxRoots: 1 + queries: + - name: orders holds every exported order + sql: SELECT count(*) AS n, sum(amount) AS revenue FROM dl.orders + includesValues: [6, 97.5] + - name: orders_daily has one row per day with its count and revenue + sql: SELECT * FROM dl.orders_daily + rowCount: 3 + includesValues: [2, 25, 3, 32.5, 1, 40] + toolExpect: + requiredToolsUsed: + - write_script + forbiddenToolsUsed: + - write_flow + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + # Pipeline nodes are declarative: `-- on ` binds inputs/triggers and + # `-- materialize ducklake://
` is a managed write whose body is a bare SELECT. + # A read of a DuckLake table inside a pipeline node also derives its trigger, so an + # explicit `-- on ducklake://main/orders` is good practice but not required. + - builds the pipeline as two pipeline-annotated scripts in f/shop (not a flow) + - the first step reads the CSV files under raw/orders/ from the workspace's default storage and materializes them into the DuckLake table `orders` + - the second step reads `orders` and materializes `orders_daily` with a per-day order count and revenue total + - the second step is wired to run when `orders` is produced + - leaves both as drafts without deploying + +- id: global-pipeline-run-tables-named-after-steps + prompt: |- + Our raw order exports land as CSV files under `raw/orders/` in the workspace + object storage. Build a data pipeline in the `shop` folder with two steps: + `orders`, which loads all of them into a DuckLake table, and `orders_daily`, + which turns that into the number of orders and the total revenue for each day. + Each table should just be named after the step that builds it, and the daily + one should rebuild by itself whenever orders are refreshed. Keep everything as + drafts, don't deploy. + initial: ai_evals/fixtures/frontend/global/initial/pipeline_orders_storage.json + runtime: + maxTurns: 16 + validate: + draftCountAtLeast: 2 + requiredDrafts: + - type: script + path: f/shop/orders + - type: script + path: f/shop/orders_daily + forbiddenDrafts: + - type: flow + pathStartsWith: f/shop/ + # A `materialize` naming no table writes the table named after its script, so + # `f/shop/orders` writes `ducklake://main/orders` whichever form the node uses. + pipelineRun: + folder: shop + maxRoots: 1 + queries: + - name: orders holds every exported order + sql: SELECT count(*) AS n, sum(amount) AS revenue FROM dl.orders + includesValues: [6, 97.5] + - name: orders_daily has one row per day with its count and revenue + sql: SELECT * FROM dl.orders_daily + rowCount: 3 + includesValues: [2, 25, 3, 32.5, 1, 40] + toolExpect: + requiredToolsUsed: + - write_script + forbiddenToolsUsed: + - write_flow + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + # A `-- materialize` that names no table writes `ducklake://main/\n\n{#snippet header(step: number, title: string, description: string)}\n
\n {step}\n
\n

{title}

\n

{description}

\n
\n
\n{/snippet}\n\n
\n
\n Windmill app{ctx.workspace ? ' · ' + ctx.workspace : ''}\n

{firstName ? 'Welcome, ' + firstName : 'Welcome'}

\n

\n Turn the scripts and flows deployed in this workspace into a tool anyone can use. Edit\n App.svelte to make it yours.\n

\n
\n\n

What you can build

\n
\n {#each uses as use (use.title)}\n
\n

{use.title}

\n

{use.text}

\n
\n {/each}\n
\n

{\"Your app can only run scripts and flows already deployed in this workspace, and it runs isolated from each viewer’s session.\"}

\n\n

How it works

\n
\n {#each steps as step, i (step.title)}\n
\n {@render header(i + 1, step.title, step.description)}\n
\n {#if step.path}\n
\n {#each step.path as label, j (label)}\n {#if j > 0}→{/if}\n {label}\n {/each}\n
\n {/if}\n {step.note}\n
\n {#if step.code}\n
{step.code}
\n {/if}\n
\n {/each}\n\n
\n {@render header(steps.length + 1, 'Know who is viewing', 'Windmill passes the workspace and the viewer to the app.')}\n
\n
Workspace {ctx.workspace}
\n
\n Viewer \n {viewer ? viewer.name || viewer.username : 'Anonymous visitor'}\n
\n
\n
{contextCode}
\n
\n
\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", diff --git a/backend/windmill-api/src/ai_session_tools/gen/display_words.json b/backend/windmill-api/src/ai_session_tools/gen/display_words.json new file mode 100644 index 0000000000..acce6e4065 --- /dev/null +++ b/backend/windmill-api/src/ai_session_tools/gen/display_words.json @@ -0,0 +1,99 @@ +{ + "ai": "AI", + "ai21": "AI21", + "amqp": "AMQP", + "api": "API", + "aws": "AWS", + "cms": "CMS", + "crm": "CRM", + "db": "DB", + "ftp": "FTP", + "gcp": "GCP", + "gpg": "GPG", + "hr": "HR", + "http": "HTTP", + "id": "ID", + "ifs": "IFS", + "json": "JSON", + "jwt": "JWT", + "ldap": "LDAP", + "mcp": "MCP", + "mqtt": "MQTT", + "ms": "Microsoft", + "nats": "NATS", + "oauth": "OAuth", + "odk": "ODK", + "oidc": "OIDC", + "rss": "RSS", + "s3": "S3", + "sdk": "SDK", + "smtp": "SMTP", + "sql": "SQL", + "ssh": "SSH", + "url": "URL", + "ynab": "YNAB", + "abstractapi": "AbstractAPI", + "arcgis": "ArcGIS", + "assemblyai": "AssemblyAI", + "bigquery": "BigQuery", + "chromadb": "ChromaDB", + "circleci": "CircleCI", + "clickhouse": "ClickHouse", + "clickup": "ClickUp", + "cockroachdb": "CockroachDB", + "comapeo": "CoMapeo", + "convertkit": "ConvertKit", + "currencyapi": "CurrencyAPI", + "customai": "CustomAI", + "datocms": "DatoCMS", + "dbt": "dbt", + "deepl": "DeepL", + "deepseek": "DeepSeek", + "digitalocean": "DigitalOcean", + "docspring": "DocSpring", + "docusign": "DocuSign", + "edgedb": "EdgeDB", + "faunadb": "FaunaDB", + "gcloud": "Google Cloud", + "ghostcms": "Ghost CMS", + "gitbook": "GitBook", + "github": "GitHub", + "gitlab": "GitLab", + "googleai": "GoogleAI", + "graphql": "GraphQL", + "groqai": "GroqAI", + "hubspot": "HubSpot", + "ipinfo": "IPinfo", + "kobotoolbox": "KoboToolbox", + "leonardoai": "LeonardoAI", + "linkedin": "LinkedIn", + "lumaai": "LumaAI", + "mailerlite": "MailerLite", + "mongodb": "MongoDB", + "mysql": "MySQL", + "netbox": "NetBox", + "netsuite": "NetSuite", + "newsapi": "NewsAPI", + "neondb": "NeonDB", + "nocodb": "NocoDB", + "openai": "OpenAI", + "openrouter": "OpenRouter", + "oracledb": "OracleDB", + "pagerduty": "PagerDuty", + "pandadoc": "PandaDoc", + "paypal": "PayPal", + "planetscale": "PlanetScale", + "postgresql": "PostgreSQL", + "readme": "ReadMe", + "rest": "REST", + "quickbooks": "QuickBooks", + "sendgrid": "SendGrid", + "servicenow": "ServiceNow", + "signoz": "SigNoz", + "surrealdb": "SurrealDB", + "togetherai": "TogetherAI", + "webscrapingai": "WebScrapingAI", + "weatherapi": "WeatherAPI", + "whatsapp": "WhatsApp", + "woocommerce": "WooCommerce" +} diff --git a/backend/windmill-api/src/mcp/session/gen/instructions.json b/backend/windmill-api/src/ai_session_tools/gen/instructions.json similarity index 99% rename from backend/windmill-api/src/mcp/session/gen/instructions.json rename to backend/windmill-api/src/ai_session_tools/gen/instructions.json index f197f795ce..0118abaa24 100644 --- a/backend/windmill-api/src/mcp/session/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -260,7 +260,7 @@ "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 `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch(\n params?: FetchParams // The union is for auto-completion\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit, \"resultCollection\">\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit, \"resultCollection\">\n ): Promise;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n (strings: TemplateStringsArray, ...values: any[]): SqlStatement;\n query(sql: string, ...params: any[]): SqlStatement;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n", "datatable.python3": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "datatable.go": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch(\n params?: FetchParams // The union is for auto-completion\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit, \"resultCollection\">\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit, \"resultCollection\">\n ): Promise;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n (strings: TemplateStringsArray, ...values: any[]): SqlStatement;\n query(sql: string, ...params: any[]): SqlStatement;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", - "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake:///
` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO
SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/
`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `wmill.ducklake(\"\")` targets a non-default catalog; `wmill.datatable(\"\")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on ` — declares an execution-DAG **input** (what triggers/feeds this node). `` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $ (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize `.\n- Optional badges: `// partitioned `, `// freshness ` (e.g. `1h`), `// tag `, `// retry [delay]`, `// data_test ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure = [where ]` and `// dimension = ` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3:///` (**double** slash, non-empty first segment) = a **named secondary** storage called `` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"\"), data)` (or the import-free dict `{\"s3\": \"\"}`), TS `wmill.writeS3File({ s3: \"\" }, data)`. That records the default-storage asset `/`, which a downstream `s3:///` reader connects to (same key both sides). A bare `write_s3_file(\"\", ...)` records **no** asset and produces **no** edge. Add `storage=\"\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake:///
`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see \"Ingesting from Python / TypeScript\") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes.\n\nA managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.) Write strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize append` → INSERT-append rows (incremental);\n- `// materialize key=` → merge/upsert on ``.\n\n`// materialize manual ` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned ` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition() = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure = [where ]` names the canonical way to aggregate that table (e.g. `// measure revenue = sum(amount) where not is_refund`), and `// dimension = ` names a way to slice it (e.g. `// dimension region = region`, `// dimension month = date_trunc('month', ordered_at)`). They execute nothing: they are catalogued at deploy so the editor and other agents reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as ` FILTER (WHERE )`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f//`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. 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", + "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake:///
` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO
SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/
`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `wmill.ducklake(\"\")` targets a non-default catalog; `wmill.datatable(\"\")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on ` — declares an execution-DAG **input** (what triggers/feeds this node). `` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $ (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize `.\n- Optional badges: `// partitioned `, `// freshness ` (e.g. `1h`), `// tag `, `// retry [delay]`, `// data_test ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure = [where ]` and `// dimension = ` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3:///` (**double** slash, non-empty first segment) = a **named secondary** storage called `` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"\"), data)` (or the import-free dict `{\"s3\": \"\"}`), TS `wmill.writeS3File({ s3: \"\" }, data)`. That records the default-storage asset `/`, which a downstream `s3:///` reader connects to (same key both sides). A bare `write_s3_file(\"\", ...)` records **no** asset and produces **no** edge. Add `storage=\"\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake:///
`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see \"Ingesting from Python / TypeScript\") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes.\n\nA managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.)\n\nA target that names no table — `// materialize`, `// materialize ducklake://`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read.\n\nWrite strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize append` → INSERT-append rows (incremental);\n- `// materialize key=` → merge/upsert on ``.\n\n`// materialize manual ` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned ` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition() = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure = [where ]` names the canonical way to aggregate that table (e.g. `// measure revenue = sum(amount) where not is_refund`), and `// dimension = ` names a way to slice it (e.g. `// dimension region = region`, `// dimension month = date_trunc('month', ordered_at)`). They execute nothing: they are catalogued at deploy so the editor and other agents reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as ` FILTER (WHERE )`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f//`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there.\n6. Don't deploy nodes unless the user asks to. A pipeline only \"runs\" once its scripts are deployed and their triggers exist.\n\n## Example (DuckDB → DuckLake, scheduled ingest + downstream transform)\n\nNode `f/sales/orders_ingest` (runs on a schedule, materializes a DuckLake table):\n\n```sql\n-- pipeline\n-- on schedule\n-- materialize ducklake://main/orders\nSELECT * FROM read_csv('s3:///raw/orders/*.csv')\n```\n\nNode `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup):\n\n```sql\n-- pipeline\n-- on ducklake://main/orders\n-- materialize ducklake://main/orders_daily\nATTACH 'ducklake://main' AS lake;\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM lake.orders GROUP BY 1\n```\n\nA node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://' AS lake;`, then `lake.
`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.
` does not resolve.\n", "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`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/` or `flow/`. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `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_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n" } } diff --git a/backend/windmill-api/src/mcp/session/gen/prompt.json b/backend/windmill-api/src/ai_session_tools/gen/prompt.json similarity index 100% rename from backend/windmill-api/src/mcp/session/gen/prompt.json rename to backend/windmill-api/src/ai_session_tools/gen/prompt.json diff --git a/backend/windmill-api/src/mcp/session/gen/schemas.json b/backend/windmill-api/src/ai_session_tools/gen/schemas.json similarity index 100% rename from backend/windmill-api/src/mcp/session/gen/schemas.json rename to backend/windmill-api/src/ai_session_tools/gen/schemas.json diff --git a/backend/windmill-api/src/mcp/session/gen/tools.json b/backend/windmill-api/src/ai_session_tools/gen/tools.json similarity index 100% rename from backend/windmill-api/src/mcp/session/gen/tools.json rename to backend/windmill-api/src/ai_session_tools/gen/tools.json diff --git a/backend/windmill-api/src/mcp/session/guidance.rs b/backend/windmill-api/src/ai_session_tools/guidance.rs similarity index 79% rename from backend/windmill-api/src/mcp/session/guidance.rs rename to backend/windmill-api/src/ai_session_tools/guidance.rs index 385aaa5c2a..669b02943e 100644 --- a/backend/windmill-api/src/mcp/session/guidance.rs +++ b/backend/windmill-api/src/ai_session_tools/guidance.rs @@ -6,7 +6,8 @@ use std::sync::LazyLock; use serde::Deserialize; use serde_json::Value; -use super::{opt_str_arg, str_arg, Ctx, ToolResult}; +use super::workspace::api_message; +use super::{opt_str_arg, str_arg, Ctx, Surface, ToolResult}; pub(super) const TOOLS: &[&str] = &["get_instructions", "read_skill"]; @@ -57,6 +58,8 @@ const TRUNCATED: &str = "… [truncated]"; pub(super) struct Skill { pub path: String, + /// Listed in the MCP instructions; the chat builds its own prompt. + #[cfg_attr(not(feature = "mcp"), allow(dead_code))] pub description: String, } @@ -103,11 +106,19 @@ async fn read_skill(ctx: &Ctx<'_>, args: &Value) -> ToolResult { // 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)), + Err(e) => return Ok(read_failed(ctx, path, api_message(&e))), }; - if !listed { + // The chat's user can switch a skill off for that chat, a setting their browser holds. + let switched_off = ctx + .chat + .is_some_and(|chat| !chat.skill_enabled.unwrap_or(true)); + if !listed || switched_off { + let (available, listing) = match ctx.surface { + Surface::Chat => ("available to this chat", "the system prompt"), + Surface::Mcp => ("available here", "the instructions"), + }; return Ok(format!( - "\"{path}\" is not one of the skills available here. Only the paths listed under \"Skills\" in the instructions can be read." + "\"{path}\" is not one of the skills {available}. Only the paths listed under \"Skills\" in {listing} can be read." )); } let value = match ctx @@ -115,10 +126,11 @@ async fn read_skill(ctx: &Ctx<'_>, args: &Value) -> ToolResult { .await { Ok(value) => value, - Err(e) => return Ok(read_failed(path, &e)), + Err(e) => return Ok(read_failed(ctx, path, api_message(&e))), }; let Some(body) = value.get("content").and_then(Value::as_str) else { return Ok(read_failed( + ctx, path, &format!("resource {path} has no string \"content\" — is it an {SKILL_RESOURCE_TYPE}?"), )); @@ -135,8 +147,12 @@ async fn read_skill(ctx: &Ctx<'_>, args: &Value) -> ToolResult { Ok(format!("Skill: {path}\n\nInstructions:\n{body}")) } -fn read_failed(path: &str, message: &str) -> String { +fn read_failed(ctx: &Ctx<'_>, path: &str, message: &str) -> String { + let listing = match ctx.surface { + Surface::Chat => "the system prompt", + Surface::Mcp => "the instructions", + }; format!( - "Failed to read skill \"{path}\": {message}. Check the path against the Skills list in the instructions." + "Failed to read skill \"{path}\": {message}. Check the path against the Skills list in {listing}." ) } diff --git a/backend/windmill-api/src/mcp/session/instructions.rs b/backend/windmill-api/src/ai_session_tools/instructions.rs similarity index 96% rename from backend/windmill-api/src/mcp/session/instructions.rs rename to backend/windmill-api/src/ai_session_tools/instructions.rs index f5c15c6e17..9b12293506 100644 --- a/backend/windmill-api/src/mcp/session/instructions.rs +++ b/backend/windmill-api/src/ai_session_tools/instructions.rs @@ -121,7 +121,7 @@ async fn appendix(ctx: &Ctx<'_>) -> String { } /// The whole prompt, for a connection that reaches one workspace. -pub(in crate::mcp) async fn session_instructions(ctx: &Ctx<'_>) -> String { +pub(crate) async fn session_instructions(ctx: &Ctx<'_>) -> String { let mut prompt = PARTS .base .replace("{{folder_guidance}}", &folder_guidance(ctx.auth)) @@ -132,7 +132,7 @@ pub(in crate::mcp) async fn session_instructions(ctx: &Ctx<'_>) -> String { /// The prompt without anything specific to a workspace, for a connection that reaches /// several: usernames are per workspace, so paths read `u//...`. -pub(in crate::mcp) fn generic_session_instructions() -> String { +pub(crate) fn generic_session_instructions() -> String { PARTS .base .replace("{{folder_guidance}}", "") @@ -140,7 +140,7 @@ pub(in crate::mcp) fn generic_session_instructions() -> String { } /// What `generic_session_instructions` leaves out, for one workspace. -pub(in crate::mcp) async fn workspace_context(ctx: &Ctx<'_>) -> String { +pub(crate) async fn workspace_context(ctx: &Ctx<'_>) -> String { let username = ctx.auth.username(); format!( "Workspace `{}`. Your username here is \"{username}\", so your personal paths are \ diff --git a/backend/windmill-api/src/mcp/session/items.rs b/backend/windmill-api/src/ai_session_tools/items.rs similarity index 99% rename from backend/windmill-api/src/mcp/session/items.rs rename to backend/windmill-api/src/ai_session_tools/items.rs index c075586a40..7ca0d7f8e3 100644 --- a/backend/windmill-api/src/mcp/session/items.rs +++ b/backend/windmill-api/src/ai_session_tools/items.rs @@ -44,7 +44,7 @@ static SCHEDULE_SCHEMA: LazyLock = 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"); + properties.shift_remove("advanced"); if let Some(advanced) = advanced.get("properties").and_then(Value::as_object) { properties.extend(advanced.clone()); } @@ -282,7 +282,7 @@ fn into_object(value: Option) -> Map { fn merge_config(base: Option, config: Value, path: &str) -> Map { let mut draft = into_object(base); for key in ["workspace_id", "edited_by", "edited_at", "email", "error"] { - draft.remove(key); + draft.shift_remove(key); } draft.extend(into_object(Some(config))); draft.insert("path".into(), json!(path)); @@ -454,6 +454,7 @@ async fn write_draft( from_deployed: impl FnOnce(Value) -> Value, build: impl FnOnce(Option) -> Result, ) -> ToolResult { + ctx.saving_draft(item_type, path); let base = write_base(ctx, item_type, path, trigger_kind).await?; let existed = base.base.is_some(); let from_draft = base.from_draft; @@ -480,7 +481,7 @@ async fn write_draft( fn take_override(parsed: &mut Value) -> bool { parsed .as_object_mut() - .and_then(|o| o.remove("override")) + .and_then(|o| o.shift_remove("override")) .and_then(|v| v.as_bool()) .unwrap_or(false) } diff --git a/backend/windmill-api/src/mcp/session/misc.rs b/backend/windmill-api/src/ai_session_tools/misc.rs similarity index 71% rename from backend/windmill-api/src/mcp/session/misc.rs rename to backend/windmill-api/src/ai_session_tools/misc.rs index d613b89f92..f45eb93d6d 100644 --- a/backend/windmill-api/src/mcp/session/misc.rs +++ b/backend/windmill-api/src/ai_session_tools/misc.rs @@ -1,13 +1,17 @@ //! Lookups that touch no draft: hub, docs, npm, resource types, workers, folders. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; +use std::sync::LazyLock; use futures::future::join_all; use serde_json::{json, Map, Value}; use windmill_common::utils::HTTP_CLIENT; +use super::chat::Effect; +use super::workspace::api_message; use super::{ - array, enc, is_not_found, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult, SCHEMAS, + array, enc, is_not_found, js_head, js_len, opt_str_arg, pretty, str_arg, truthy, Ctx, + ToolResult, SCHEMAS, }; pub(super) const TOOLS: &[&str] = &[ @@ -28,7 +32,7 @@ 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_npm_packages" => search_npm_packages(ctx, 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, @@ -90,12 +94,37 @@ async fn hub_integrations(ctx: &Ctx<'_>) -> Vec { } } +/// The frontend's `RESOURCE_TYPE_WORDS`: how a slug word reads where capitalizing gets it +/// wrong, some into several words (`gcloud` -> `Google Cloud`). +static DISPLAY_WORDS: LazyLock> = LazyLock::new(|| { + serde_json::from_str(include_str!("gen/display_words.json")) + .expect("gen/display_words.json is valid") +}); + +/// What the frontend's `integrationDisplayName` calls a slug the hub names nothing. +fn slug_display_name(slug: &str) -> String { + slug.split(['_', '-']) + .filter(|w| !w.is_empty()) + .map(|w| { + DISPLAY_WORDS + .get(&w.to_ascii_lowercase()) + .cloned() + .unwrap_or_else(|| w.to_string()) + }) + .collect::>() + .join(" ") +} + /// 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 = [name, display_name] + let display_name = integration + .get("display_name") + .and_then(Value::as_str) + .map(str::to_string) + .or_else(|| name.map(slug_display_name)); + let words: Vec = [name, display_name.as_deref()] .into_iter() .flatten() .flat_map(words) @@ -254,8 +283,9 @@ async fn get_hub_integration(ctx: &Ctx<'_>, args: &Value) -> ToolResult { 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) { + // way would teach the model that a real integration does not exist. No slug holds + // a `/`, and the route refuses one as malformed rather than absent. + let error = if is_not_found(&e) || integration.contains('/') { 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.") @@ -347,49 +377,183 @@ async fn get_hub_integration(ctx: &Ctx<'_>, args: &Value) -> ToolResult { // 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). +/// The registry's best match is kept, and the runner-up only when it scores this share of it: +/// the scores have no fixed scale (a descriptive query's right answer can score a few hundred, +/// a package's own name thousands), so a match is judged against the best one. +const NPM_RUNNER_UP_SHARE: f64 = 0.6; +/// A package's readme and types are each capped at 1% of the model's context window. An MCP +/// client's model is unknown, so this is 1% of the window assumed 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 { 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 { - 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}")) +/// Where a package's files come from: the public CDN, or the workspace's npm proxy, which +/// is the authoritative source once the instance names a registry of its own. Each falls +/// back to the other. +struct NpmSources<'a> { + ctx: &'a Ctx<'a>, + proxy_first: bool, } -async fn npm_search(query: &str) -> Result, String> { +impl NpmSources<'_> { + async fn new<'a>(ctx: &'a Ctx<'a>) -> NpmSources<'a> { + let proxy_first = ctx + .get(&ctx.ws("npm_proxy/config")) + .await + .is_ok_and(|config| truthy(config.get("registry_configured"))); + NpmSources { ctx, proxy_first } + } + + async fn json(&self, cdn: String, proxy: String) -> Option { + let via_cdn = || async { + let response = fetch(&cdn).await.ok()?.error_for_status().ok()?; + response.json::().await.ok() + }; + let via_proxy = || async { self.ctx.get(&self.ctx.ws(&proxy)).await.ok() }; + if self.proxy_first { + match via_proxy().await { + Some(v) => Some(v), + None => via_cdn().await, + } + } else { + match via_cdn().await { + Some(v) => Some(v), + None => via_proxy().await, + } + } + } + + async fn text(&self, cdn: String, proxy: String) -> Option { + let via_cdn = || async { + let response = fetch(&cdn).await.ok()?.error_for_status().ok()?; + response.text().await.ok() + }; + let via_proxy = || async { + self.ctx + .request("GET", &self.ctx.ws(&proxy), None) + .await + .ok() + }; + if self.proxy_first { + match via_proxy().await { + Some(v) => Some(v), + None => via_cdn().await, + } + } else { + match via_cdn().await { + Some(v) => Some(v), + None => via_proxy().await, + } + } + } + + /// `tag` as an exact version; one with two dots already is one. + async fn version(&self, module: &str, tag: &str) -> Option { + if tag.split('.').count() >= 3 { + return Some(tag.to_string()); + } + let resolved = self + .json( + format!("https://data.jsdelivr.com/v1/package/resolve/npm/{module}@{tag}"), + format!("npm_proxy/resolve/{}?tag={}", enc(module), enc(tag)), + ) + .await?; + resolved.get("version")?.as_str().map(String::from) + } + + /// The `.d.ts` files of `module` at `version`, in the order its file tree lists them. + async fn dts_files(&self, module: &str, version: &str) -> Option> { + let tree = self + .json( + format!("https://data.jsdelivr.com/v1/package/npm/{module}@{version}/flat"), + format!("npm_proxy/filetree/{}/{}", enc(module), enc(version)), + ) + .await?; + Some( + array(tree.get("files")) + .iter() + .filter_map(|f| f.get("name")?.as_str()) + .filter(|name| name.ends_with(".d.ts")) + .map(String::from) + .collect(), + ) + } +} + +/// `@bla/foo` → `bla__foo`, the DefinitelyTyped name of a scoped package. +fn dt_name(name: &str) -> String { + match name.strip_prefix('@') { + Some(scoped) if scoped.contains('/') => scoped.replacen('/', "__", 1), + _ => name.to_string(), + } +} + +/// Every declaration file of the package, or of its `@types` package when it ships none, +/// each headed by the path it would have under `node_modules`. +/// Files fetched at once, as the browser's type acquisition did. +const NPM_TYPES_CONCURRENCY: usize = 6; + +/// The package's declarations joined in order, fetched only until they reach `limit` +/// characters: only that head is returned, and `@types/lodash` alone has hundreds of files. +async fn npm_package_types( + sources: &NpmSources<'_>, + name: &str, + version: &str, + limit: usize, +) -> String { + let mut module = name.to_string(); + let mut prefix = format!("/node_modules/{name}"); + let mut version = match sources.version(name, version).await { + Some(version) => version, + None => return String::new(), + }; + let mut files = sources.dts_files(name, &version).await.unwrap_or_default(); + if files.is_empty() { + module = format!("@types/{}", dt_name(name)); + prefix = format!("/node_modules/@types/{}", dt_name(name)); + let Some(dt_version) = sources.version(&module, "latest").await else { + return String::new(); + }; + version = dt_version; + files = sources + .dts_files(&module, &version) + .await + .unwrap_or_default(); + } + let mut parts: Vec = Vec::new(); + for batch in files.chunks(NPM_TYPES_CONCURRENCY) { + let contents = join_all(batch.iter().map(|file| { + sources.text( + format!("https://cdn.jsdelivr.net/npm/{module}@{version}{file}"), + format!("npm_proxy/file/{}/{}{file}", enc(&module), enc(&version)), + ) + })) + .await; + parts.extend( + batch + .iter() + .zip(contents) + .filter_map(|(file, code)| Some(format!("// {prefix}{file}\n{}", code?))), + ); + if js_len(&parts.join("\n\n")) >= limit { + break; + } + } + parts.join("\n\n") +} + +fn confident_npm_matches(objects: &[Value]) -> Vec<&Value> { + let score = |o: &Value| o.get("searchScore").and_then(Value::as_f64).unwrap_or(0.0); + let best = objects.iter().map(score).fold(0.0, f64::max); + objects + .iter() + .filter(|o| score(o) >= best * NPM_RUNNER_UP_SHARE) + .collect() +} + +async fn npm_search(ctx: &Ctx<'_>, query: &str, limit: usize) -> Result, String> { let data: Value = fetch(&format!( "https://registry.npmjs.org/-/v1/search?text={}&size=2", enc(query) @@ -399,41 +563,36 @@ async fn npm_search(query: &str) -> Result, String> { .json() .await .map_err(|e| e.to_string())?; - let packages = data + let objects = 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_or("no `objects` in the registry answer")?; + let packages = confident_npm_matches(objects).into_iter().filter_map(|o| { + let package = o.get("package")?; + Some(( + package.get("name")?.as_str()?, + package.get("version").and_then(Value::as_str), + )) + }); + let sources = &NpmSources::new(ctx).await; 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(); + let types = npm_package_types(sources, name, version.unwrap_or("latest"), limit).await; json!({ "package": name, - "documentation": take_chars(&documentation, NPM_TEXT_LIMIT), - "types": take_chars(&types, NPM_TEXT_LIMIT), + "documentation": js_head(&documentation, limit), + "types": js_head(&types, limit), }) })) .await) } -async fn search_npm_packages(args: &Value) -> ToolResult { +async fn search_npm_packages(ctx: &Ctx<'_>, args: &Value) -> ToolResult { let query = str_arg(args, "query")?; - Ok(match npm_search(query).await { + Ok(match npm_search(ctx, query, NPM_TEXT_LIMIT).await { Ok(results) => Value::Array(results).to_string(), Err(e) => { tracing::warn!("npm package search failed: {e}"); @@ -454,7 +613,10 @@ fn docs_text(result: Result, action: &str) -> String { .and_then(Value::as_str) .unwrap_or_default() .to_string(), - Err(e) => format!("Failed to {action}: {e}, pursuing with the user request..."), + Err(e) => format!( + "Failed to {action}: {}, pursuing with the user request...", + api_message(&e) + ), } } @@ -466,6 +628,14 @@ async fn search_docs(ctx: &Ctx<'_>, args: &Value) -> ToolResult { ); } let result = ctx.get(&format!("/docs/search?query={}", enc(query))).await; + if let Ok(response) = &result { + let mut facts = Map::new(); + facts.insert( + "result_count".into(), + array(response.get("results")).len().into(), + ); + ctx.effect(Effect::Facts(facts)); + } Ok(docs_text(result, "search documentation")) } @@ -661,7 +831,7 @@ async fn create_folder(ctx: &Ctx<'_>, args: &Value) -> ToolResult { "success": true, "message": format!("Created folder `f/{name}`. You can now write items to `f/{name}/`.") }), - Err(error) => json!({ "success": false, "error": error }), + Err(error) => json!({ "success": false, "error": api_message(&error) }), } .to_string(), ) @@ -671,6 +841,25 @@ async fn create_folder(ctx: &Ctx<'_>, args: &Value) -> ToolResult { mod tests { use super::*; + #[test] + fn npm_matches_are_judged_against_the_best_one() { + let names = |scores: &[f64]| { + let objects: Vec = scores + .iter() + .enumerate() + .map(|(i, s)| json!({ "searchScore": s, "package": { "name": i.to_string() } })) + .collect(); + confident_npm_matches(&objects) + .iter() + .map(|o| o["package"]["name"].as_str().unwrap().to_string()) + .collect::>() + }; + // A descriptive query's right answer scores a few hundred; a weak runner-up is dropped. + assert_eq!(names(&[815.0, 454.0]), ["0"]); + assert_eq!(names(&[419.0, 384.0]), ["0", "1"]); + assert!(names(&[]).is_empty()); + } + #[test] fn suggestions_rank_by_matched_words() { let integrations = vec![ @@ -690,6 +879,12 @@ mod tests { ["salesforce"] ); assert_eq!(suggest_hub_integrations(&integrations, "s3 bucket"), ["s3"]); + // With no display name from the hub, the slug reads as the frontend labels it. + let unnamed = vec![json!({ "name": "gcloud", "display_name": null })]; + assert_eq!( + suggest_hub_integrations(&unnamed, "deploy to google cloud"), + ["gcloud"] + ); } #[test] diff --git a/backend/windmill-api/src/mcp/session/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs similarity index 72% rename from backend/windmill-api/src/mcp/session/mod.rs rename to backend/windmill-api/src/ai_session_tools/mod.rs index 6992c46221..6928545039 100644 --- a/backend/windmill-api/src/mcp/session/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -1,30 +1,46 @@ -//! The Windmill MCP server's toolset (`/api/mcp`, tokens with `mcp:all`): an AI session's toolset, for a client -//! outside the Windmill UI. +//! The AI session's GLOBAL toolset, run on the server for both of its callers: the +//! in-app chat (`POST /w/{workspace}/ai_session_tools/{name}`) and the Windmill MCP +//! server (`/api/mcp`, tokens with `mcp:all`). //! //! 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. +//! *does* is written here once; the chat keeps only what needs a browser (cards, +//! confirmations, the run form, the open editor). //! -//! 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. +//! A tool acts through the API as the caller, 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::{json, Map, Value}; -use windmill_mcp::server::{ - BackendResult, CallToolResult, ContentBlock, ErrorData, MetaObject, SessionAccess, Tool, - ToolAnnotations, -}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use windmill_common::auth::create_jwt_token; use crate::db::ApiAuthed; -use super::utils::{mint_caller_jwt, send_as_caller}; +pub(crate) mod chat; + +/// What a caller may do with the toolset. An MCP token sets it from its scopes; the chat +/// is always `Full`, its own gating running before a tool is called. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(feature = "mcp"), allow(dead_code))] +pub(crate) enum SessionAccess { + ReadOnly, + ReadAndRun, + Full, +} + +/// Which caller a tool runs for, at the few spots where the two genuinely differ. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Surface { + Mcp, + Chat, +} + +/// The largest tool result the MCP runner passes on whole; it truncates beyond it. +pub(crate) const MAX_TOOL_RESULT_BYTES: usize = 87_500; /// 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, @@ -42,11 +58,13 @@ pub(crate) fn register_router(base_internal_url: &str, router: Option, read_only: bool, @@ -108,6 +128,7 @@ const EDITOR_ONLY: &[&str] = &[ /// live datatable, run code, cancel a job, delete work, or replace a draft's content, which /// discarding the draft does not restore. Stands in for the session's confirmation card. The /// ChatGPT and Claude directories reject such a tool without this hint. +#[cfg(any(test, feature = "mcp"))] const DESTRUCTIVE: &[&str] = &[ "write_script", "edit_script", @@ -144,15 +165,11 @@ const DESTRUCTIVE: &[&str] = &[ "delete_app_runnable", ]; -/// The destructive tools a card may call, each from a button the user presses. Every -/// other destructive tool is hidden from cards: a card acts as the user with no one -/// confirming. -const CARD_ACTIONS: &[&str] = &["deploy_workspace_item", "cancel_job"]; - /// Tools that reach a system outside Windmill on the workspace's behalf: running code can /// reach any system the workspace can, and `get_db_schema` connects to a resource's /// database, and `search_npm_packages` queries the npm registry, which Windmill does not /// control. Reading Windmill's own hub and docs does not count. +#[cfg(any(test, feature = "mcp"))] const OPEN_WORLD: &[&str] = &[ "search_npm_packages", "run_script", @@ -166,23 +183,6 @@ const OPEN_WORLD: &[&str] = &[ "get_db_schema", ]; -/// A tool's display name, which Claude shows in its tool list and approval prompts. -fn tool_title(name: &str) -> String { - let words: Vec = name - .split('_') - .map(|word| match word { - "db" | "sql" | "json" => word.to_uppercase(), - _ => word.to_string(), - }) - .collect(); - let title = words.join(" "); - let mut chars = title.chars(); - chars - .next() - .map(|first| first.to_uppercase().chain(chars).collect()) - .unwrap_or_default() -} - /// 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"]; @@ -202,6 +202,7 @@ fn allowed(def: &ToolDef, access: SessionAccess) -> bool { /// Each group's tools and its dispatcher, tried in order. macro_rules! groups { ($($group:ident),*) => { + #[cfg(any(test, feature = "mcp"))] fn implemented() -> impl Iterator { std::iter::empty()$(.chain($group::TOOLS.iter().copied()))* } @@ -216,92 +217,53 @@ macro_rules! groups { } 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) +/// A tool as a client lists it. +#[cfg(feature = "mcp")] +pub(crate) struct ToolInfo { + pub name: &'static str, + pub description: &'static str, + pub parameters: &'static Map, + pub read_only: bool, + pub destructive: bool, + pub open_world: bool, } -/// The MCP Apps view a client that renders them draws these tools' results in. It draws -/// what the tool put in its result's `_meta` (`Ctx::view`), and acts by calling tools. -/// Hosts cache a view by its URI: bump the version when a change breaks the `_meta` shape -/// the deployed card reads. -pub(super) const CARD_URI: &str = "ui://windmill/card-v1"; -const CARD_HTML: &str = include_str!("card.html"); - -/// The `ui://` views the session's tools render in, as `(uri, html)`. -pub(super) fn session_views() -> &'static [(&'static str, &'static str)] { - &[(CARD_URI, CARD_HTML)] -} - -pub(super) fn session_tools(access: SessionAccess) -> Vec { +/// The tools implemented here that `access` may call. +#[cfg(feature = "mcp")] +pub(crate) fn session_tools(access: SessionAccess) -> impl Iterator { TOOL_DEFS .iter() .filter(|def| implemented().any(|name| name == def.name)) - .filter(|def| allowed(def, access)) + .filter(move |def| allowed(def, access)) .map(|def| { let name = def.name.as_str(); - let mut meta = result_size_meta(); - let destructive = DESTRUCTIVE.contains(&name); - if destructive && !CARD_ACTIONS.contains(&name) { - meta.0 - .insert("ui".into(), json!({ "visibility": ["model"] })); + ToolInfo { + name, + description: &def.description, + parameters: &def.parameters, + read_only: def.read_only && !RUNS_A_JOB.contains(&name), + destructive: DESTRUCTIVE.contains(&name), + open_world: OPEN_WORLD.contains(&name), } - let title = tool_title(name); - Tool::new( - def.name.clone(), - def.description.clone(), - def.parameters.clone(), - ) - .with_title(title.clone()) - .with_annotations( - ToolAnnotations::with_title(title) - .read_only(def.read_only && !RUNS_A_JOB.contains(&name)) - .destructive(destructive) - .open_world(OPEN_WORLD.contains(&name)), - ) - .with_meta(meta) }) - .chain( - views::definitions() - .into_iter() - .filter(|(name, ..)| views::allowed(name, access)) - .map(|(name, description, schema)| { - let mut meta = result_size_meta(); - meta.0 - .insert("ui".into(), json!({ "resourceUri": CARD_URI })); - let Value::Object(schema) = schema else { - unreachable!("a view tool's schema is an object") - }; - let title = tool_title(name); - Tool::new(name, description, schema) - .with_title(title.clone()) - .with_annotations( - ToolAnnotations::with_title(title) - .read_only(true) - .destructive(false) - .open_world(false), - ) - .with_meta(meta) - }), - ) - .collect() } /// What a tool hands back: the text the model reads, or the message of a failed call. pub(super) type ToolResult = Result; /// The caller, and the API reached as them. -pub(super) struct Ctx<'a> { +pub(crate) 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>, + pub surface: Surface, + /// What the chat sends beside a call; `None` for MCP. + pub chat: Option<&'a chat::ChatContext>, + /// What the call changed that the chat has to apply: its editors, cards and drafts. + pub effects: std::sync::Mutex>, /// 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, @@ -310,6 +272,38 @@ pub(super) struct Ctx<'a> { pub view: std::sync::Mutex>, } +impl<'a> Ctx<'a> { + pub(crate) fn new( + auth: &'a ApiAuthed, + w_id: &'a str, + base_internal_url: &'a str, + access: SessionAccess, + ) -> Self { + Ctx { + auth, + w_id, + base_internal_url, + access, + origin: None, + surface: Surface::Mcp, + chat: None, + effects: Default::default(), + jwt: Default::default(), + view: Default::default(), + } + } + + /// Hand the chat something to apply. A no-op for MCP, which has no editor. + pub(super) fn effect(&self, effect: chat::Effect) { + if self.surface == Surface::Chat { + self.effects.lock().unwrap().push(effect); + } + } +} + +/// The total timeout of the HTTP client the in-process router replaces. +const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + impl Ctx<'_> { /// Set what the card draws of this call, replacing what an inner step set. pub fn set_view(&self, key: &'static str, value: Value) { @@ -318,6 +312,20 @@ 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) -> ToolResult { + self.request_within(method, path, body, REQUEST_TIMEOUT) + .await + } + + /// `request` for a route that waits on jobs of its own, like the datatable migration + /// routes: each job is bounded server-side, so the default budget would cut a long one + /// off midway. + pub async fn request_within( + &self, + method: &str, + path: &str, + body: Option, + timeout: std::time::Duration, + ) -> 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 @@ -337,17 +345,18 @@ impl Ctx<'_> { .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())?) + Some(router) => { + self.call_router(router, method, &url, body, scopes, timeout) + .await? } + None => self.call_http(method, &url, body, scopes, timeout).await?, }; if status.is_success() { Ok(text) + } else if text.trim().is_empty() { + // What a browser's request reports for an answer with no body. + let reason = status.canonical_reason().unwrap_or_default(); + Err(format!("{}: {reason}", status.as_u16())) } else { Err(format!("{}: {}", status.as_u16(), text)) } @@ -362,6 +371,7 @@ impl Ctx<'_> { url: &str, body: Option, scopes: Option>, + timeout: std::time::Duration, ) -> Result<(http::StatusCode, String), String> { use tower::ServiceExt; let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?; @@ -376,7 +386,7 @@ impl Ctx<'_> { .jwt .get_or_try_init(|| mint_caller_jwt(self.w_id, self.auth, scopes)) .await - .map_err(|e| e.message.to_string())?; + .map_err(|e| e.to_string())?; let mut request = http::Request::builder() .method(method) .uri(uri) @@ -389,8 +399,7 @@ impl Ctx<'_> { 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 { + tokio::time::timeout(timeout, 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) @@ -402,6 +411,36 @@ impl Ctx<'_> { .map_err(|_| format!("Failed to execute request: {method} {url} timed out"))? } + /// `request` over HTTP, for a server whose router is not registered. + async fn call_http( + &self, + method: &str, + url: &str, + body: Option, + scopes: Option>, + timeout: std::time::Duration, + ) -> Result<(http::StatusCode, String), String> { + let method = http::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?; + let token = self + .jwt + .get_or_try_init(|| mint_caller_jwt(self.w_id, self.auth, scopes)) + .await + .map_err(|e| e.to_string())?; + let mut request = crate::HTTP_CLIENT + .request(method, url) + .header("Authorization", format!("Bearer {token}")) + .timeout(timeout); + if let Some(body) = body { + request = request.json(&body); + } + let response = request + .send() + .await + .map_err(|e| format!("Failed to execute request: {e}"))?; + let status = response.status(); + Ok((status, response.text().await.map_err(|e| e.to_string())?)) + } + pub async fn get(&self, path: &str) -> Result { let text = self.request("GET", path, None).await?; serde_json::from_str(&text).map_err(|e| format!("unexpected response from {path}: {e}")) @@ -424,6 +463,12 @@ impl Ctx<'_> { format!("/w/{}/{}", self.w_id, rest) } + /// `page_url` for an MCP client only: the chat shows what a tool made or ran in its own + /// cards and panel instead. + pub fn link(&self, page: &str) -> Option { + (self.surface == Surface::Mcp).then(|| self.page_url(page)) + } + /// 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 { @@ -637,57 +682,92 @@ pub(super) fn matches_glob(subject: &str, glob: &str) -> bool { regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(subject)) } -/// A generated session tool, refused when the token's access does not cover it. -async fn call_generated_tool(ctx: &Ctx<'_>, name: &str, args: &Value) -> BackendResult { +/// 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>, +) -> windmill_common::error::Result { + // 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. + // A browser caller stays a session: runs, trigger history and schedules attribute a + // session's actions to the UI, and anything else to the API (`webhook`). + create_jwt_token( + windmill_common::db::Authed::from(api_authed.clone()), + workspace_id, + 3600, + api_authed.job_id, + api_authed.is_session_token.then(|| "session".to_string()), + None, + scopes, + ) + .await +} + +/// Why a call was refused before the tool ran. +pub(crate) enum CallRefused { + UnknownTool(String), + NotAllowed(String), + NotAvailable(String), +} + +/// What the model reads, and whether the call failed. +#[derive(Serialize)] +pub(crate) struct ToolOutcome { + pub text: String, + pub is_error: bool, +} + +/// The card tools only MCP Apps clients draw; the chat draws its own cards. +#[cfg(feature = "mcp")] +pub(crate) use views::{allowed as view_allowed, definitions as view_definitions}; + +pub(crate) async fn call_session_tool( + ctx: &Ctx<'_>, + name: &str, + args: Value, +) -> Result { + if ctx.surface == Surface::Mcp && views::TOOLS.contains(&name) { + return Ok(outcome(views::call(ctx, name, &args).await)); + } + let result = call_generated_tool(ctx, name, &args).await?; + Ok(outcome(result)) +} + +/// A generated session tool, refused when the caller's access does not cover it. +async fn call_generated_tool( + ctx: &Ctx<'_>, + name: &str, + args: &Value, +) -> Result { let Some(def) = TOOL_DEFS.iter().find(|def| def.name == name) else { - return Err(ErrorData::invalid_params( - format!("Unknown tool '{name}'"), - None, - )); + return Err(CallRefused::UnknownTool(format!("Unknown tool '{name}'"))); }; 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, - )); + return Err(CallRefused::NotAllowed(format!( + "Tool '{name}' changes or runs something, and this token {token}" + ))); } - let Some(result) = dispatch(ctx, name, args).await else { - return Err(ErrorData::invalid_params( - format!("Tool '{name}' is not available on this server"), - None, - )); - }; - Ok(result) + dispatch(ctx, name, args).await.ok_or_else(|| { + CallRefused::NotAvailable(format!("Tool '{name}' is not available on this server")) + }) } -pub(super) async fn call_session_tool( - ctx: &Ctx<'_>, - name: &str, - args: Value, -) -> BackendResult { - let result = if views::TOOLS.contains(&name) { - views::call(ctx, name, &args).await - } else { - call_generated_tool(ctx, name, &args).await? - }; - windmill_common::feature_usage::log_feature_usage("mcp_workspace", "tool_call", name); - let mut result = match result { - Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]), +fn outcome(result: ToolResult) -> ToolOutcome { + match result { + Ok(text) => ToolOutcome { text, is_error: false }, // 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())]) + ToolOutcome { text: text.to_string(), is_error: true } } - }; - if let Some((key, view)) = ctx.view.lock().unwrap().take() { - result.meta = Some(MetaObject(Map::from_iter([(key.to_string(), view)]))); } - Ok(result) } #[cfg(test)] @@ -728,38 +808,6 @@ mod tests { assert!(url("POST", "/w/ws/variables/create", ReadOnly).is_err()); } - #[test] - fn no_card_can_call_a_destructive_tool_but_deploy_and_cancel() { - for tool in session_tools(SessionAccess::Full) { - let name = tool.name.as_ref(); - if DESTRUCTIVE.contains(&name) { - let ui = tool.meta.as_ref().and_then(|m| m.0.get("ui")); - let model_only = ui == Some(&json!({ "visibility": ["model"] })); - assert_eq!( - model_only, - !matches!(name, "deploy_workspace_item" | "cancel_job"), - "{name}" - ); - } - } - } - - /// The ChatGPT directory wants every hint explicit, and Claude's a title on every tool. - #[test] - fn every_session_tool_has_a_title_and_explicit_hints() { - for tool in session_tools(SessionAccess::Full) { - let a = tool.annotations.as_ref().expect("annotations"); - assert!(tool.title.is_some() && a.title.is_some(), "{}", tool.name); - assert!( - a.read_only_hint.is_some() - && a.destructive_hint.is_some() - && a.open_world_hint.is_some(), - "{}", - tool.name - ); - } - } - #[test] fn every_session_tool_is_implemented_or_editor_only() { let implemented: Vec<&str> = implemented().collect(); diff --git a/backend/windmill-api/src/ai_session_tools/run_args_cases.json b/backend/windmill-api/src/ai_session_tools/run_args_cases.json new file mode 100644 index 0000000000..35a850b4b7 --- /dev/null +++ b/backend/windmill-api/src/ai_session_tools/run_args_cases.json @@ -0,0 +1,120 @@ +{ + "//": "How a run's arguments are settled, which the chat does in the browser ($lib/components/job_args.ts, secretArgUtils.ts) and MCP on the server (runs.rs). Both test suites read this file, so a change on one side only fails. Each expectation applies its step to `args` alone. A minted variable is named .", + "cases": [ + { + "name": "undeclared arguments are dropped and named", + "schema": { "properties": { "a": { "type": "string" } } }, + "args": { "a": "x", "b": 1, "constructor": 2 }, + "declared": { "args": { "a": "x" }, "undeclared": ["b", "constructor"] } + }, + { + "name": "a schema without properties declares nothing", + "schema": {}, + "args": { "a": "x" }, + "declared": { "args": {}, "undeclared": ["a"] } + }, + { + "name": "a disabled field takes its default, reported only when a different value was proposed", + "schema": { + "properties": { + "locked": { "type": "string", "disabled": true, "default": "fixed" }, + "same": { "type": "object", "disabled": true, "default": { "k": [1, 2] } }, + "absent": { "type": "number", "disabled": true, "default": 3 }, + "no_default": { "type": "string", "disabled": true }, + "free": { "type": "string", "default": "d" } + } + }, + "args": { "locked": "mine", "same": { "k": [1, 2] }, "no_default": "kept", "free": "mine" }, + "disabled_defaults": { + "args": { + "locked": "fixed", + "same": { "k": [1, 2] }, + "absent": 3, + "no_default": "kept", + "free": "mine" + }, + "reset": ["locked"] + } + }, + { + "name": "secrets are minted at every depth, and references and empty fields are left alone", + "schema": { + "properties": { + "token": { "type": "string", "password": true }, + "creds": { "type": "object", "password": true, "properties": { "user": { "type": "string" } } }, + "nested": { "type": "object", "properties": { "inner": { "type": "string", "password": true } } }, + "rows": { + "type": "array", + "items": { "type": "object", "properties": { "key": { "type": "string", "password": true } } } + }, + "variant": { + "type": "object", + "oneOf": [ + { "properties": { "label": { "type": "string" } } }, + { "properties": { "pin": { "type": "string", "password": true } } } + ] + }, + "named": { "type": "string", "password": true }, + "named_object": { "type": "object", "password": true }, + "blank": { "type": "string", "password": true }, + "nothing": { "type": "string", "password": true }, + "plain": { "type": "string" } + } + }, + "args": { + "token": "hunter2", + "creds": { "user": "ada" }, + "nested": { "inner": "deep" }, + "rows": [{ "key": "k1" }, { "key": "$var:f/team/k2" }], + "variant": { "pin": "1234" }, + "named": "$var:f/team/api_token", + "named_object": "$var:f/team/creds", + "blank": "", + "nothing": null, + "plain": "kept" + }, + "secrets": { + "args": { + "token": "$var:", + "creds": "$jsonvar:", + "nested": { "inner": "$var:" }, + "rows": [{ "key": "$var:" }, { "key": "$var:f/team/k2" }], + "variant": { "pin": "$var:" }, + "named": "$var:f/team/api_token", + "named_object": "$jsonvar:f/team/creds", + "blank": "", + "nothing": null, + "plain": "kept" + }, + "stored": ["1234", "deep", "hunter2", "k1", "{\"user\":\"ada\"}"] + }, + "redacted": { + "token": "", + "creds": "", + "nested": { "inner": "" }, + "rows": [{ "key": "" }, { "key": "$var:f/team/k2" }], + "variant": { "pin": "" }, + "named": "$var:f/team/api_token", + "named_object": "$var:f/team/creds", + "blank": "", + "plain": "kept" + } + }, + { + "name": "file bytes are replaced by their size", + "schema": { + "properties": { + "doc": { "type": "string", "contentEncoding": "base64" }, + "docs": { "type": "array", "items": { "type": "string", "contentEncoding": "base64" } }, + "name": { "type": "string" } + } + }, + "args": { + "doc": "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", + "docs": ["QUJD", "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg=="], + "name": "report.pdf" + }, + "redacted": { "doc": "", "docs": ["", ""], "name": "report.pdf" } + } + ] +} diff --git a/backend/windmill-api/src/mcp/session/runs.rs b/backend/windmill-api/src/ai_session_tools/runs.rs similarity index 78% rename from backend/windmill-api/src/mcp/session/runs.rs rename to backend/windmill-api/src/ai_session_tools/runs.rs index 273a273199..99b6a653ec 100644 --- a/backend/windmill-api/src/mcp/session/runs.rs +++ b/backend/windmill-api/src/ai_session_tools/runs.rs @@ -3,9 +3,10 @@ use std::collections::HashMap; use std::time::Duration; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; +use super::chat::{Effect, RunPhase}; use super::workspace::{ api_message, get_draft, infer_script_schema, load_flow, load_script, path_enc, }; @@ -200,7 +201,10 @@ pub(super) async fn finish_run( 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 run_page = ctx + .link(&format!("/run/{id}")) + .map(|url| format!("\n\nRun page: {url}")) + .unwrap_or_default(); let Some(job) = wait_job(ctx, &id, wait_budget(tool_args), true).await else { return Ok(format!("{}{run_page}", backgrounded_summary(&id, label))); }; @@ -346,8 +350,37 @@ async fn process_secret_args( 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 mut minted: HashMap = HashMap::new(); + for (key, prefix, value) in secrets_to_mint(&args, schema) { + let variable = format!( + "u/{username}/secret_arg/{}", + windmill_common::utils::rd_string(12) + ); + 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_text(prefix, &value), + "is_secret": true, + "path": variable, + "description": "Ephemeral secret variable", + "expires_at": expires_at, + }), + ) + .await?; + minted.insert(key, format!("{prefix}{variable}")); + } + Ok(substitute_secrets(&args, schema, &minted)) +} + +/// The sensitive literals to mint, each keyed by its path, with the reference it becomes. +fn secrets_to_mint( + args: &Map, + schema: &Value, +) -> Vec<(String, &'static str, Value)> { + let mut pending = 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(( @@ -358,51 +391,37 @@ async fn process_secret_args( } Some(value.clone()) }); + pending +} - let mut minted: HashMap = 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}")); +/// What the secret variable stores: the text for `$var:`, the JSON for `$jsonvar:`. +fn secret_text(prefix: &str, value: &Value) -> String { + match value { + Value::String(text) if prefix == "$var:" => text.clone(), + other => other.to_string(), } +} - 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()); +/// The arguments with each minted literal replaced by its reference, keyed as +/// `secrets_to_mint` keys them. +fn substitute_secrets( + args: &Map, + schema: &Value, + minted: &HashMap, +) -> Map { + 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()) } - // 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()), - } - }, - )) + _ => Some(value.clone()), + } + }) } fn file_marker(base64: &str) -> String { @@ -602,66 +621,412 @@ async fn conclude( // 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( +/// What a run tool runs, resolved once and queued later with the final arguments: the +/// chat shows its argument form in between, and the run has to be the version the form +/// was shown for. +#[derive(Serialize, Deserialize, Clone)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(crate) enum RunTarget { + ScriptPreview { + path: Option, + language: String, + content: String, + /// A flow's preprocessor, which takes the arguments of its own entrypoint. + preprocessor: bool, + }, + ScriptByPath { + path: String, + }, + FlowByPath { + path: String, + /// A chat-enabled flow is refused without a conversation, and a run is its own. + chat_enabled: bool, + }, + FlowPreview { + path: String, + value: Value, + /// The conversation the caller named. + memory_id: Option, + /// Without one, a chat-enabled flow's test run is a conversation of its own. + fresh_conversation: bool, + }, + /// A saved AI agent, as its own page runs it. + Agent { + path: String, + memory_id: Option, + }, + /// An AI agent or AI decision step, run alone as a one-step flow preview of `flow_path`. + Step { + flow_path: String, + step: Value, + }, + AppRunnable { + app_path: String, + key: String, + runnable: Value, + }, + DatatableSql { + datatable: String, + sql: String, + role: Option, + }, +} + +/// Queue `target` with `args` and answer the job id, or the server's own message. +pub(super) async fn start_run( + ctx: &Ctx<'_>, + target: &RunTarget, + args: Map, + form_keys: &[String], +) -> Result { + let message = |e: String| api_message(&e).to_string(); + match target { + RunTarget::ScriptPreview { path, language, content, preprocessor } => { + let mut with_entrypoint = Map::new(); + if *preprocessor { + with_entrypoint.insert("_ENTRYPOINT_OVERRIDE".into(), "preprocessor".into()); + } + with_entrypoint.extend(args); + run_script_preview( + ctx, + path.as_deref(), + language, + content, + Value::Object(with_entrypoint), + ) + .await + .map_err(message) + } + // The arguments fill the main input schema; a preprocessor would take them for a + // trigger event. + RunTarget::ScriptByPath { path } => ctx + .post( + &ctx.ws(&format!( + "jobs/run/p/{}?skip_preprocessor=true", + path_enc(path) + )), + Value::Object(args), + ) + .await + .map(job_id) + .map_err(message), + RunTarget::FlowByPath { path, chat_enabled } => { + let memory_id = if *chat_enabled { + format!("&memory_id={}", uuid::Uuid::new_v4()) + } else { + String::new() + }; + ctx.post( + &ctx.ws(&format!( + "jobs/run/f/{}?skip_preprocessor=true{memory_id}", + path_enc(path) + )), + Value::Object(args), + ) + .await + .map(job_id) + .map_err(message) + } + RunTarget::FlowPreview { path, value, memory_id, fresh_conversation } => { + let memory_id = memory_id.clone().or_else(|| { + (*fresh_conversation && truthy(value.get("chat_input_enabled"))) + .then(|| uuid::Uuid::new_v4().to_string()) + }); + run_flow_preview( + ctx, + Some(path), + value, + Value::Object(args), + memory_id.as_deref(), + ) + .await + .map_err(message) + } + RunTarget::Agent { path, memory_id } => { + let query = memory_id + .as_ref() + .map(|id| format!("?memory_id={}", enc(id))) + .unwrap_or_default(); + ctx.post( + &ctx.ws(&format!("jobs/run/agent/{}{query}", path_enc(path))), + Value::Object(args), + ) + .await + .map(job_id) + .map_err(message) + } + RunTarget::Step { flow_path, step } => { + let mut step = step.clone(); + let value = &mut step["value"]; + if value["type"] == "aiagent" { + *value = migrated_agent_value(value); + value["input_transforms"] = Value::Object(agent_test_transforms( + value.get("input_transforms"), + &args, + form_keys, + )); + // After the inputs are wired: a linked agent's draft brings its own brain + // and tools, and the step's run inputs stay on top. + with_agent_drafts(ctx, &mut step).await?; + } else { + // The inputs given here override the step's own, so a state that reads an + // earlier step can be passed directly. + let mut transforms = value["input_transforms"] + .as_object() + .cloned() + .unwrap_or_default(); + for key in args.keys() { + transforms.insert( + key.clone(), + json!({ "type": "javascript", "expr": format!("flow_input.{key}") }), + ); + } + value["input_transforms"] = Value::Object(transforms); + } + let preview = json!({ "modules": [step] }); + run_flow_preview(ctx, Some(flow_path), &preview, Value::Object(args), None) + .await + .map_err(message) + } + RunTarget::AppRunnable { app_path, key, runnable } => { + let body = + super::apps::execute_component_body(app_path, key, runnable, &Value::Object(args)); + ctx.request( + "POST", + &ctx.ws(&format!("apps_u/execute_component/{}", path_enc(app_path))), + Some(body), + ) + .await + .map(|id| id.trim().trim_matches('"').to_string()) + .map_err(message) + } + RunTarget::DatatableSql { datatable, sql, role } => { + let database = match role { + None => format!("datatable://{datatable}"), + // A stored name holding a `?` is read whole by the server, so a role + // cannot follow it. + Some(role) if datatable.contains('?') => { + return Err(format!("Data table '{datatable}' 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://{datatable}?role={role}"), + }; + run_script_preview( + ctx, + None, + "postgresql", + sql, + json!({ "database": database }), + ) + .await + .map_err(message) + } + } +} + +/// A run tool's target, and what its argument form shows for it. +#[derive(Serialize)] +pub(super) struct Resolved { + pub target: RunTarget, + /// The input schema stored with what will run; `None` when it has none. The chat + /// infers a missing one with the editor's parsers, MCP with the backend's. + pub schema: Option, + pub code: Option, + pub lang: Option, + pub summary: Option, + /// `script` or `flow`: the kind of job the run queues. + pub runnable_kind: &'static str, + pub start_message: String, + /// The item's deployed page is a conversation rather than a run form. + pub conversational: bool, + /// For a step: the module, whose form an agent step builds from its own inputs. + pub module: Option, +} + +/// A run tool called by the chat, in its phases; by MCP, resolved and run here. +pub(super) async fn run_tool( + ctx: &Ctx<'_>, + tool_args: &Value, + resolved: impl std::future::Future>, + mcp: impl AsyncFnOnce(Resolved) -> ToolResult, +) -> ToolResult { + match ctx.chat.and_then(|chat| chat.run.as_ref()) { + Some(RunPhase::Prepare) => Ok(serde_json::to_string(&resolved.await?).unwrap_or_default()), + Some(RunPhase::Start { target, args, form_keys }) => { + let target = match target { + Some(target) => target.clone(), + None => resolved.await?.target, + }; + let args = if target_takes_tool_args(&target) && args.is_empty() { + proposed_args(tool_args) + } else { + args.clone() + }; + start_run(ctx, &target, args, form_keys).await + } + None => mcp(resolved.await?).await, + } +} + +/// A run with no argument form takes the tool's own `args`. +fn target_takes_tool_args(target: &RunTarget) -> bool { + matches!( + target, + RunTarget::AppRunnable { .. } | RunTarget::DatatableSql { .. } + ) +} + +/// MCP's run of a resolved target: arguments conformed and secrets minted here, as no +/// form stands in front of them, then the job awaited within the tool's budget. +async fn run_resolved( + ctx: &Ctx<'_>, + tool_args: &Value, + path: &str, + resolved: Resolved, + schema_noun: &str, + label: &str, + action: &str, +) -> ToolResult { + let proposed = proposed_args(tool_args); + run_resolved_with( ctx, - Some(path), - &script.language, - &script.content, - Value::Object(prepared.args), + tool_args, + path, + resolved, + proposed, + schema_noun, + label, + action, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn run_resolved_with( + ctx: &Ctx<'_>, + tool_args: &Value, + path: &str, + resolved: Resolved, + proposed: Map, + schema_noun: &str, + label: &str, + action: &str, +) -> ToolResult { + let schema = resolved.schema; + let prepared = match prepare_args(ctx, path, proposed, schema.as_ref(), schema_noun).await { + Ok(prepared) => prepared, + Err(message) => return Ok(message), + }; + let started = start_run( + ctx, + &resolved.target, + prepared.args, + &form_keys(schema.as_ref()), ) .await; - conclude(ctx, args, prepared.notes, started, path, false, "test").await + conclude( + ctx, + tool_args, + prepared.notes, + started, + label, + resolved.runnable_kind == "flow", + action, + ) + .await +} + +fn form_keys(schema: Option<&Value>) -> Vec { + schema + .and_then(|s| s["properties"].as_object()) + .map(|p| p.keys().cloned().collect()) + .unwrap_or_default() +} + +async fn resolve_test_script(ctx: &Ctx<'_>, path: &str) -> Result { + let script = load_script(ctx, path).await?; + Ok(Resolved { + schema: script.schema, + code: Some(script.content.clone()), + lang: Some(script.language.clone()), + summary: script.summary, + runnable_kind: "script", + start_message: format!("Running test for script \"{path}\"..."), + conversational: false, + module: None, + target: RunTarget::ScriptPreview { + path: Some(path.to_string()), + language: script.language, + content: script.content, + preprocessor: false, + }, + }) +} + +async fn test_run_script(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + run_tool( + ctx, + args, + resolve_test_script(ctx, path), + async |mut resolved: Resolved| { + let (code, lang) = (resolved.code.clone(), resolved.lang.clone()); + resolved.schema = schema_for_test_run( + &lang.unwrap_or_default(), + &code.unwrap_or_default(), + resolved.schema, + None, + ); + run_resolved(ctx, args, path, resolved, "script", path, "test").await + }, + ) + .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") +async fn resolve_deployed(ctx: &Ctx<'_>, path: &str, is_flow: bool) -> Result { + let get = if is_flow { + "flows/get" } else { - ("scripts/get/p", "jobs/run/p") + "scripts/get/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 + let chat_enabled = is_flow && truthy(item["value"].get("chat_input_enabled")); + Ok(Resolved { + schema: Some( + item.get("schema") + .filter(|s| !s.is_null()) + .cloned() + .unwrap_or_else(|| json!({})), + ), + code: None, + lang: None, + summary: item + .get("summary") + .and_then(Value::as_str) + .map(String::from), + runnable_kind: if is_flow { "flow" } else { "script" }, + start_message: format!("Running \"{path}\"..."), + conversational: chat_enabled, + module: None, + target: if is_flow { + RunTarget::FlowByPath { path: path.to_string(), chat_enabled } + } else { + RunTarget::ScriptByPath { path: path.to_string() } + }, + }) +} + +async fn run_deployed(ctx: &Ctx<'_>, args: &Value, is_flow: bool) -> ToolResult { + let path = str_arg(args, "path")?; + run_tool( + ctx, + args, + resolve_deployed(ctx, path, is_flow), + async |resolved| run_resolved(ctx, args, path, resolved, "deployed", path, "run").await, + ) + .await } /// The flow value a preview runs, from a loaded `{value, schema, groups}`. @@ -669,7 +1034,7 @@ 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"); + map.shift_remove("groups"); } else { map.insert("groups".into(), groups.clone()); } @@ -677,38 +1042,51 @@ fn flow_preview_value(flow: &Value) -> Value { 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"); +async fn resolve_test_flow( + ctx: &Ctx<'_>, + path: &str, + memory_id: Option<&str>, +) -> Result { 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( + Ok(Resolved { + schema: Some( + flow.flow + .get("schema") + .filter(|s| !s.is_null()) + .cloned() + .unwrap_or_else(|| json!({})), + ), + code: None, + lang: None, + summary: flow.summary.clone(), + runnable_kind: "flow", + start_message: format!("Starting flow test run for \"{path}\"..."), + conversational: false, + module: None, + // 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. + target: RunTarget::FlowPreview { + path: path.to_string(), + value: flow_preview_value(&flow.flow), + memory_id: memory_id.map(String::from), + fresh_conversation: true, + }, + }) +} + +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"); + run_tool( ctx, - Some(path), - &value, - Value::Object(prepared.args), - memory_id.as_deref(), + args, + resolve_test_flow(ctx, path, memory_id), + async |resolved| run_resolved(ctx, args, path, resolved, "flow", path, "test").await, ) - .await; - conclude(ctx, args, prepared.notes, started, path, true, "test").await + .await } // ============================================================================ @@ -739,24 +1117,26 @@ fn agent_memory_id(args: &Value) -> Result, String> { Ok(memory_id) } -/// The agent's configuration a test runs: the user's draft when there is one, else the deployed -/// resource. Refuses a path holding some other kind of resource. -async fn load_agent_for_test(ctx: &Ctx<'_>, path: &str) -> Result { +/// The agent a test runs, as `(configuration, description)`: the user's draft when there is +/// one, else the deployed resource. Refuses a path holding some other kind of resource. +async fn load_agent_for_test(ctx: &Ctx<'_>, path: &str) -> Result<(Value, Value), String> { let draft = get_draft(ctx, "resource", path).await?.map(|d| d.value); // A draft records its type only when nothing is deployed at its path. - let (resource_type, config) = match draft { - Some(draft) if draft.get("resource_type").is_some() => { - (draft["resource_type"].clone(), draft["args"].clone()) - } + let (resource_type, config, description) = match draft { + Some(draft) if draft.get("resource_type").is_some() => ( + draft["resource_type"].clone(), + draft["args"].clone(), + draft["description"].clone(), + ), draft => { let deployed = ctx .get(&ctx.ws(&format!("resources/get/{}", path_enc(path)))) .await?; - let config = match draft { - Some(draft) => draft["args"].clone(), - None => deployed["value"].clone(), + let (config, description) = match draft { + Some(draft) => (draft["args"].clone(), draft["description"].clone()), + None => (deployed["value"].clone(), deployed["description"].clone()), }; - (deployed["resource_type"].clone(), config) + (deployed["resource_type"].clone(), config, description) } }; let resource_type = resource_type.as_str().unwrap_or_default(); @@ -765,13 +1145,34 @@ async fn load_agent_for_test(ctx: &Ctx<'_>, path: &str) -> Result "\"{path}\" is a {resource_type} resource, not an AI agent." )); } - Ok(config) + Ok((config, description)) } -async fn test_run_agent(ctx: &Ctx<'_>, args: &Value) -> ToolResult { - let path = str_arg(args, "path")?; - let memory_id = agent_memory_id(args)?; - let mut config = load_agent_for_test(ctx, path).await?; +fn agent_resolved( + target: RunTarget, + description: &Value, + start_message: String, + conversational: bool, +) -> Resolved { + Resolved { + target, + schema: Some(agent_run_schema()), + code: None, + lang: None, + summary: description.as_str().map(String::from), + runnable_kind: "flow", + start_message, + conversational, + module: None, + } +} + +async fn resolve_test_agent( + ctx: &Ctx<'_>, + path: &str, + memory_id: Option<&str>, +) -> Result { + let (mut config, description) = load_agent_for_test(ctx, path).await?; // Who the agent runs as and who may ask it in Slack, not inputs: a test runs as its caller. if let Some(map) = config.as_object_mut() { for key in ["on_behalf_of", "run_on_behalf_of", "slack_anyone"] { @@ -790,48 +1191,72 @@ async fn test_run_agent(ctx: &Ctx<'_>, args: &Value) -> ToolResult { ) }) .map_err(|e| e.to_string())?; - let flow = serde_json::to_value(flow).map_err(|e| e.to_string())?; - let schema = agent_run_schema(); - let prepared = match prepare_args(ctx, path, proposed_args(args), Some(&schema), "agent").await - { - Ok(prepared) => prepared, - Err(message) => return Ok(message), + let target = RunTarget::FlowPreview { + // Filed where the agent editor's chat files its conversations. + path: format!("{path}.chat"), + value: serde_json::to_value(flow).map_err(|e| e.to_string())?, + memory_id: Some( + memory_id + .map(String::from) + .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()), + ), + fresh_conversation: false, }; - let memory_id = memory_id - .map(String::from) - .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); - // Filed where the agent editor's chat files its conversations. - let started = run_flow_preview( + Ok(agent_resolved( + target, + &description, + format!("Starting agent test run for \"{path}\"..."), + false, + )) +} + +async fn test_run_agent(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let memory_id = agent_memory_id(args)?; + run_tool( ctx, - Some(&format!("{path}.chat")), - &flow, - Value::Object(prepared.args), - Some(&memory_id), + args, + resolve_test_agent(ctx, path, memory_id), + async |resolved| run_resolved(ctx, args, path, resolved, "agent", path, "test").await, ) - .await; - conclude(ctx, args, prepared.notes, started, path, true, "test").await + .await +} + +async fn resolve_agent( + ctx: &Ctx<'_>, + path: &str, + memory_id: Option<&str>, +) -> Result { + let agent = ctx + .get(&ctx.ws(&format!("resources/get/{}", path_enc(path)))) + .await?; + let resource_type = agent["resource_type"].as_str().unwrap_or_default(); + if resource_type != "ai_agent" { + return Err(format!( + "\"{path}\" is a {resource_type} resource, not an AI agent." + )); + } + let target = + RunTarget::Agent { path: path.to_string(), memory_id: memory_id.map(String::from) }; + // A turn of a conversation stays on the card: the agent's page starts one of its own. + Ok(agent_resolved( + target, + &agent["description"], + format!("Running agent \"{path}\"..."), + memory_id.is_some(), + )) } async fn run_agent(ctx: &Ctx<'_>, args: &Value) -> ToolResult { let path = str_arg(args, "path")?; let memory_id = agent_memory_id(args)?; - let schema = agent_run_schema(); - let prepared = match prepare_args(ctx, path, proposed_args(args), Some(&schema), "agent").await - { - Ok(prepared) => prepared, - Err(message) => return Ok(message), - }; - let query = memory_id - .map(|id| format!("?memory_id={}", enc(id))) - .unwrap_or_default(); - let started = ctx - .post( - &ctx.ws(&format!("jobs/run/agent/{}{query}", path_enc(path))), - Value::Object(prepared.args), - ) - .await - .map(job_id); - conclude(ctx, args, prepared.notes, started, path, true, "run").await + run_tool( + ctx, + args, + resolve_agent(ctx, path, memory_id), + async |resolved| run_resolved(ctx, args, path, resolved, "agent", path, "run").await, + ) + .await } // ============================================================================ @@ -937,7 +1362,7 @@ 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) { if !transforms.contains_key("user_attachments") { - if let Some(images) = transforms.remove("user_images") { + if let Some(images) = transforms.shift_remove("user_images") { transforms.insert("user_attachments".into(), images); } } @@ -967,7 +1392,7 @@ fn migrate_agent_transforms(transforms: &mut Map) { } _ => {} } - transforms.remove("messages_context_length"); + transforms.shift_remove("messages_context_length"); } /// The inputs a test run of an agent step takes, in the agent form's order, and the @@ -1090,7 +1515,7 @@ fn inline_agent_draft(module: &mut Value, drafts: &HashMap) { .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"); + map.shift_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()) { @@ -1150,11 +1575,21 @@ async fn with_agent_drafts(ctx: &Ctx<'_>, module: &mut Value) -> Result<(), Stri Ok(()) } -async fn test_run_step(ctx: &Ctx<'_>, args: &Value) -> ToolResult { - let path = str_arg(args, "path")?; - let step_id = str_arg(args, "stepId")?; +async fn resolve_step(ctx: &Ctx<'_>, path: &str, step_id: &str) -> Result { let flow_value = flow_preview_value(&load_flow(ctx, path).await?.flow); - let Some(module) = find_module(&flow_value, step_id) else { + let Some(module) = find_module(&flow_value, step_id).cloned() else { + let mut patch = Map::new(); + patch.insert( + "content".into(), + json!(format!("Step \"{step_id}\" not found in flow")), + ); + patch.insert( + "error".into(), + json!(format!( + "Step with id \"{step_id}\" does not exist in the current flow" + )), + ); + ctx.effect(Effect::Status(patch)); return Err(format!( "Step with id \"{step_id}\" not found in flow. Available steps: {}", available_step_ids(&flow_value) @@ -1163,39 +1598,37 @@ async fn test_run_step(ctx: &Ctx<'_>, args: &Value) -> ToolResult { 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 = - 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" - )); - } + let preprocessor = module["id"] == "preprocessor"; + let step = |runnable_kind, start_message: String, schema, code, lang, target| Resolved { + schema, + code, + lang, + summary: None, + runnable_kind, + start_message, + conversational: false, + module: Some(module.clone()), + target, }; - - // 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 { + Ok(match module_type { + "rawscript" => step( + "script", + format!("Starting test run of step \"{step_id}\"..."), + None, + Some(text("content")), + Some(text("language")), + RunTarget::ScriptPreview { + path: None, + language: text("language"), + content: text("content"), + preprocessor, + }, + ), "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 { + let (content, language, schema) = 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)))) @@ -1214,143 +1647,120 @@ async fn test_run_step(ctx: &Ctx<'_>, args: &Value) -> ToolResult { (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 + step( + "script", + format!("Starting test run of script step \"{step_id}\"..."), + schema, + Some(content.clone()), + Some(language.clone()), + RunTarget::ScriptPreview { path: Some(target), language, content, preprocessor }, + ) } "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| { - 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 = 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)), + let subflow = load_flow(ctx, &target).await?; + let schema = subflow.flow.get("schema").filter(|s| !s.is_null()).cloned(); + if subflow.is_draft { + step( + "flow", + format!("Starting test run of draft flow step \"{step_id}\"..."), + schema, None, + None, + RunTarget::FlowPreview { + path: target, + value: flow_preview_value(&subflow.flow), + memory_id: None, + fresh_conversation: false, + }, ) - .await, - true, - ) + } else { + step( + "flow", + format!("Starting test run of flow step \"{step_id}\"..."), + schema, + None, + None, + RunTarget::FlowByPath { path: target, chat_enabled: false }, + ) + } } - }; - conclude(ctx, args, prepared.notes, started, &label, is_flow, "test").await + "aiagent" | "aidecision" => step( + "flow", + if module_type == "aiagent" { + format!("Starting test run of agent step \"{step_id}\"...") + } else { + format!("Starting test run of AI decision step \"{step_id}\"...") + }, + None, + None, + None, + RunTarget::Step { + flow_path: path.to_string(), + step: json!({ "id": module["id"], "value": value }), + }, + ), + other => { + let mut patch = Map::new(); + patch.insert( + "content".into(), + json!(format!("Step type \"{other}\" not supported for testing")), + ); + patch.insert( + "error".into(), + json!(format!("Cannot test step of type \"{other}\"")), + ); + ctx.effect(Effect::Status(patch)); + return Err(format!( + "Cannot test step of type \"{other}\". Supported types: rawscript, script, flow, aiagent, aidecision" + )); + } + }) +} + +async fn test_run_step(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + let path = str_arg(args, "path")?; + let step_id = str_arg(args, "stepId")?; + run_tool( + ctx, + args, + resolve_step(ctx, path, step_id), + async |mut resolved: Resolved| { + let module = resolved.module.clone().unwrap_or_default(); + let value = &module["value"]; + // A preprocessor takes the arguments of its own entrypoint, which no schema declares. + let entrypoint = (module["id"] == "preprocessor").then_some("preprocessor"); + let mut proposed = proposed_args(args); + match value["type"].as_str().unwrap_or_default() { + "rawscript" | "script" => { + let (code, lang) = (resolved.code.clone(), resolved.lang.clone()); + resolved.schema = schema_for_test_run( + &lang.unwrap_or_default(), + &code.unwrap_or_default(), + resolved.schema.filter(|_| value["type"] == "script"), + entrypoint, + ); + } + "aiagent" => { + let (keys, form_args) = + agent_step_form(&migrated_agent_value(value), &proposed); + let properties: Map = + keys.into_iter().map(|key| (key, json!({}))).collect(); + resolved.schema = Some(json!({ "properties": properties })); + proposed = form_args; + } + // What a run supplies is the state; the provider and questions are the step's own. + "aidecision" => resolved.schema = Some(json!({ "properties": { "state": {} } })), + // The subflow's own schema, which a deployed one may lack: then nothing conforms. + _ => {} + } + let label = format!("step {step_id}"); + run_resolved_with(ctx, args, path, resolved, proposed, "step", &label, "test").await + }, + ) + .await } fn migrated_agent_value(value: &Value) -> Value { @@ -1721,7 +2131,7 @@ impl<'a> RunTree<'a> { run_overrides: &Map, ) -> Value { let mut run = self.shape_step(0, heads, None); - let steps = run.remove("steps"); + let steps = run.shift_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" { @@ -1730,8 +2140,8 @@ impl<'a> RunTree<'a> { // 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"); + run.shift_remove("result"); + run.shift_remove("result_total_chars"); } for (key, value) in run_overrides { run.insert(key.clone(), value.clone()); @@ -1839,7 +2249,11 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult { results_route(STEP_RESULT_MAX_CHARS), enc(step) ); - return Ok(step_result(&ctx.get(&route).await?, step)); + let response = ctx.get(&route).await?; + if let Some(job_id) = finished_step_job(&response) { + ctx.effect(Effect::InspectedRun { job_id: job_id.to_string() }); + } + return Ok(step_result(&response, step)); } // Only the job read is load-bearing: logs and the step tree each answer part of @@ -1913,11 +2327,12 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult { None => report_run(ctx, id, Some(job), details), } } - Ok(format!( - "{}\n\nRun page: {}", - shape_run(id, &job?, logs, &results), - ctx.page_url(&format!("/run/{}", enc(id))) - )) + let run = shape_run(id, &job?, logs, &results); + ctx.effect(Effect::InspectedRun { job_id: id.to_string() }); + Ok(match ctx.link(&format!("/run/{}", enc(id))) { + Some(url) => format!("{run}\n\nRun page: {url}"), + None => run, + }) } /// The job read swaps a result past ~90 KB for a marker, so an image under the card's cap @@ -2478,7 +2893,7 @@ fn run_card(id: &str, job: Option<&Value>) -> Map { /// empty log. fn shape_run(id: &str, job: &Value, logs: Result, results: &Value) -> String { let mut run = summarize_run(job); - run.remove("id"); + run.shift_remove("id"); // Why a run ended badly. for (key, source) in [ ("canceled_by", "canceled_by"), @@ -2524,6 +2939,22 @@ fn shape_run(id: &str, job: &Value, logs: Result, results: &Valu shape_flow_run_tree(results, &run) } +/// The job a step address resolved to, once it finished: what the card renders. +fn finished_step_job(response: &Value) -> Option<&str> { + if response["step_error"] + .as_str() + .is_some_and(|e| !e.is_empty()) + { + return None; + } + let entry = response["entries"].get(0)?; + let status = entry["status"].as_str().unwrap_or_default(); + if matches!(status, "running" | "queued" | "suspended") { + return None; + } + entry["job_id"].as_str() +} + /// 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()) { @@ -2559,6 +2990,51 @@ fn step_result(response: &Value, step: &str) -> String { mod tests { use super::*; + // The chat settles a run's arguments in the browser with `job_args.ts`, read against the + // same cases by `runArgsCases.test.ts`. + #[test] + fn run_args_match_the_shared_cases() { + let cases: Value = serde_json::from_str(include_str!("run_args_cases.json")).unwrap(); + for case in cases["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let schema = &case["schema"]; + let args = case["args"].as_object().cloned().unwrap(); + if let Some(expected) = case.get("declared") { + let (kept, undeclared) = drop_undeclared_args(args.clone(), schema); + assert_eq!(Value::Object(kept), expected["args"], "{name}"); + assert_eq!(json!(undeclared), expected["undeclared"], "{name}"); + } + if let Some(expected) = case.get("disabled_defaults") { + let mut settled = args.clone(); + let reset = enforce_disabled_defaults(&mut settled, schema); + assert_eq!(Value::Object(settled), expected["args"], "{name}"); + assert_eq!(json!(reset), expected["reset"], "{name}"); + } + if let Some(expected) = case.get("secrets") { + let pending = secrets_to_mint(&args, schema); + let mut stored: Vec = pending + .iter() + .map(|(_, prefix, value)| secret_text(prefix, value)) + .collect(); + stored.sort(); + assert_eq!(json!(stored), expected["stored"], "{name}"); + let minted = pending + .into_iter() + .map(|(key, prefix, _)| (key, format!("{prefix}"))) + .collect(); + let out = substitute_secrets(&args, schema, &minted); + assert_eq!(Value::Object(out), expected["args"], "{name}"); + } + if let Some(expected) = case.get("redacted") { + assert_eq!( + Value::Object(redact_args(&args, schema)), + *expected, + "{name}" + ); + } + } + } + fn entry(overrides: Value) -> Value { let mut entry = json!({ "job_id": "j", diff --git a/backend/windmill-api/src/mcp/session/settings.rs b/backend/windmill-api/src/ai_session_tools/settings.rs similarity index 58% rename from backend/windmill-api/src/mcp/session/settings.rs rename to backend/windmill-api/src/ai_session_tools/settings.rs index 3548dada4b..6e3e70d1f1 100644 --- a/backend/windmill-api/src/mcp/session/settings.rs +++ b/backend/windmill-api/src/ai_session_tools/settings.rs @@ -2,8 +2,9 @@ use serde_json::{json, Map, Value}; +use super::chat::Effect; use super::workspace::api_message; -use super::{array, js_head, js_len, js_str, str_arg, Ctx, ToolResult}; +use super::{array, js_head, js_len, js_str, str_arg, Ctx, Surface, ToolResult}; pub(super) const TOOLS: &[&str] = &["get_workspace_settings", "set_workspace_settings"]; @@ -65,37 +66,73 @@ fn parse_settings_yaml(text: &str) -> Result { } } -/// The dry run stands in for the session's confirmation card: it reports a no-op or an -/// invalid document before anything is written. +/// The dry run reports a no-op or an invalid document before anything is written: for MCP +/// it stands in for the session's confirmation card, and the chat runs it alone, as a +/// check-only call, before showing that card. async fn set_workspace_settings(ctx: &Ctx<'_>, args: &Value) -> ToolResult { let route = ctx.ws("workspaces/settings_document"); + let refuse = |label: String, text: String| { + ctx.facts(json!({ "refused": label })); + Ok(text) + }; let document = match parse_settings_yaml(str_arg(args, "yaml")?) { Ok(document) => document, - Err(e) => return Ok(format!("Nothing was changed: {e}")), + Err(e) if ctx.surface == Surface::Chat && !ctx.check_only() => return Err(e), + Err(e) => { + return refuse( + format!("Invalid settings: {e}"), + 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 = array(dry_run.get("warnings")).iter().map(js_str).collect(); - let warnings = if warnings.is_empty() { - String::new() - } else { - format!(" Warnings: {}", warnings.join(" ")) + // The chat's own check ran before its card, and the user confirmed what it showed. + if ctx.surface == Surface::Mcp || ctx.check_only() { + 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) => { + let e = api_message(&e); + return refuse( + format!("Invalid settings: {e}"), + format!("Nothing was changed: {e}"), + ); + } }; - return Ok(format!( - "The settings already hold these values: nothing to change.{warnings}" - )); + if array(dry_run.get("changes")).is_empty() { + let warnings: Vec = array(dry_run.get("warnings")).iter().map(js_str).collect(); + let warnings = if warnings.is_empty() { + String::new() + } else { + format!(" Warnings: {}", warnings.join(" ")) + }; + return refuse( + "No settings change".to_string(), + format!("The settings already hold these values: nothing to change.{warnings}"), + ); + } + if ctx.check_only() { + ctx.facts(json!({ "changes": dry_run["changes"] })); + return Ok(String::new()); + } } 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()), + Err(e) => { + let error = api_message(&e); + let mut failed = Map::new(); + failed.insert( + "content".into(), + json!("Failed to change workspace settings"), + ); + failed.insert("error".into(), json!(error)); + ctx.effect(Effect::Status(failed)); + return Ok(json!({ "success": false, "error": error }).to_string()); + } }; + ctx.facts(json!({ "changes": applied["changes"] })); let keys: Vec = array(applied.get("changes")) .iter() .map(|c| js_str(c.get("key").unwrap_or(&Value::Null))) @@ -105,7 +142,11 @@ async fn set_workspace_settings(ctx: &Ctx<'_>, args: &Value) -> ToolResult { out.insert( "message".into(), json!(format!( - "These settings are now applied: {}.", + "{} now applied: {}.", + match ctx.surface { + Surface::Chat => "The user approved and these settings are", + Surface::Mcp => "These settings are", + }, keys.join(", ") )), ); diff --git a/backend/windmill-api/src/mcp/session/views.rs b/backend/windmill-api/src/ai_session_tools/views.rs similarity index 96% rename from backend/windmill-api/src/mcp/session/views.rs rename to backend/windmill-api/src/ai_session_tools/views.rs index 474171c2ee..9ecf77d493 100644 --- a/backend/windmill-api/src/mcp/session/views.rs +++ b/backend/windmill-api/src/ai_session_tools/views.rs @@ -3,7 +3,9 @@ //! the other tools, which draw nothing, and calls one of these when it means the user to //! see a result: a host draws a card for every call of a tool that has one. -use serde_json::{json, Value}; +#[cfg(feature = "mcp")] +use serde_json::json; +use serde_json::Value; use super::{deploy, runs, workspace, Ctx, SessionAccess, ToolResult}; @@ -11,7 +13,7 @@ pub(super) const TOOLS: &[&str] = &["show_run", "show_runs", "show_deploy_review /// The review card's one action deploys, which only a full token may do: such a token is /// neither offered the tool nor answered when it calls it by name. -pub(super) fn allowed(name: &str, access: SessionAccess) -> bool { +pub(crate) fn allowed(name: &str, access: SessionAccess) -> bool { name != "show_deploy_review" || access == SessionAccess::Full } @@ -32,7 +34,8 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult /// Each tool as `(name, description, input schema)`. All only read: the review card's /// Deploy button calls `deploy_workspace_item`, which the token's own access gates. -pub(super) fn definitions() -> [(&'static str, &'static str, Value); 4] { +#[cfg(feature = "mcp")] +pub(crate) fn definitions() -> [(&'static str, &'static str, Value); 4] { [ ( "show_run", diff --git a/backend/windmill-api/src/mcp/session/workspace.rs b/backend/windmill-api/src/ai_session_tools/workspace.rs similarity index 87% rename from backend/windmill-api/src/mcp/session/workspace.rs rename to backend/windmill-api/src/ai_session_tools/workspace.rs index 2eed15c464..80e5da2041 100644 --- a/backend/windmill-api/src/mcp/session/workspace.rs +++ b/backend/windmill-api/src/ai_session_tools/workspace.rs @@ -4,9 +4,10 @@ use std::collections::HashMap; use serde_json::{json, Map, Value}; +use super::chat::Effect; 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, + str_arg, truthy, Ctx, Surface, ToolResult, }; pub(super) const TOOLS: &[&str] = &[ @@ -294,11 +295,17 @@ pub(super) struct Draft { pub created_at: Option, } +/// The caller's own draft named `path`. For the chat, a cell the browser holds is newer +/// than the server's row and wins, the way the editor reads it. pub(super) async fn get_draft( ctx: &Ctx<'_>, kind: &str, path: &str, ) -> Result, String> { + let path = ctx.storage_path(kind, path); + if let Some(value) = ctx.chat.and_then(|chat| chat.cell(kind, path)) { + return Ok(Some(Draft { value: value.clone(), created_at: None })); + } let row = ctx .get(&ctx.ws(&format!("drafts/get_own/{kind}/{}", path_enc(path)))) .await?; @@ -312,6 +319,9 @@ pub(super) async fn get_draft( Ok(Some(Draft { value, created_at })) } +/// Save the caller's draft, or delete it with `None`. False on a conflict with a newer +/// row. The chat saves through its editor's own draft store instead, after the call: it +/// gets the write as an effect, and reports a conflict or failure itself. pub(super) async fn save_draft( ctx: &Ctx<'_>, kind: &str, @@ -320,6 +330,25 @@ pub(super) async fn save_draft( last_sync: Option<&str>, force: bool, ) -> Result { + if ctx.surface == Surface::Chat { + let storage_path = ctx.storage_path(kind, path).to_string(); + ctx.effect(match value { + Some(value) => Effect::DraftWrite { + kind: kind.to_string(), + storage_path, + value: value.clone(), + last_sync: last_sync.map(String::from), + force, + }, + None => Effect::DraftDelete { + kind: kind.to_string(), + storage_path, + last_sync: last_sync.map(String::from), + keep_live_editor: false, + }, + }); + return Ok(true); + } let mut body = Map::new(); body.insert("value".into(), value.cloned().unwrap_or(Value::Null)); if !force { @@ -335,12 +364,24 @@ pub(super) async fn save_draft( Ok(response.get("status").and_then(Value::as_str) != Some("conflict")) } +/// Delete the caller's draft. `keep_live_editor` leaves an editor open on it with its +/// copy, detached from the row, as a deploy does. pub(super) async fn delete_draft( ctx: &Ctx<'_>, kind: &str, path: &str, last_sync: Option<&str>, + keep_live_editor: bool, ) -> Result<(), String> { + if ctx.surface == Surface::Chat { + ctx.effect(Effect::DraftDelete { + kind: kind.to_string(), + storage_path: ctx.storage_path(kind, path).to_string(), + last_sync: last_sync.map(String::from), + keep_live_editor, + }); + return Ok(()); + } match save_draft(ctx, kind, path, None, last_sync, false).await { Ok(true) => Ok(()), Ok(false) => Err(format!( @@ -364,6 +405,7 @@ pub(super) async fn list_drafts(ctx: &Ctx<'_>) -> Result, String> { let Some((item_type, trigger_kind)) = item_type_of_kind(kind) else { continue; }; + let (path, live) = ctx.display_path(kind, path); let mut item = Map::new(); item.insert("type".into(), json!(item_type)); item.insert("path".into(), json!(path)); @@ -380,8 +422,31 @@ pub(super) async fn list_drafts(ctx: &Ctx<'_>) -> Result, String> { if kind == "raw_app" { item.insert("rawApp".into(), json!(true)); } + if live { + item.insert("isLiveDraft".into(), json!(true)); + } drafts.insert(item_key(item_type, path, trigger_kind), Value::Object(item)); } + // The browser's cells carry edits the rows may not have yet, and win. + for cell in ctx + .chat + .map(|chat| chat.cells.as_slice()) + .unwrap_or_default() + { + let Some(Value::Object(mut item)) = + shown_draft_item(ctx, &cell.kind, &cell.storage_path, &cell.value) + else { + continue; + }; + item.shift_remove("value"); + item.shift_remove("schema"); + let text = |key: &str| item.get(key).and_then(Value::as_str).map(String::from); + let (Some(item_type), Some(path)) = (text("type"), text("path")) else { + continue; + }; + let key = item_key(&item_type, &path, text("triggerKind").as_deref()); + drafts.insert(key, Value::Object(item)); + } Ok(drafts.into_iter().map(|(_, item)| item).collect()) } @@ -540,7 +605,24 @@ pub(super) async fn get_draft_item( let Some(draft) = get_draft(ctx, &kind, path).await? else { return Ok(None); }; - Ok(draft_item(&kind, path, &draft.value).map(|item| (item, draft))) + Ok(shown_draft_item(ctx, &kind, path, &draft.value).map(|item| (item, draft))) +} + +/// `draft_item` under the path the user sees: an open editor's own name for its draft, +/// flagged as live. +pub(super) fn shown_draft_item( + ctx: &Ctx<'_>, + kind: &str, + path: &str, + draft: &Value, +) -> Option { + let (shown, live) = ctx.display_path(kind, ctx.storage_path(kind, path)); + let mut item = draft_item(kind, shown, draft)?; + if live { + item.as_object_mut()? + .insert("isLiveDraft".into(), json!(true)); + } + Some(item) } fn stash_inline_script( @@ -766,6 +848,7 @@ pub(super) fn summarize_app_value(value: &Value) -> Value { _ if !by_path => "inline", Some("flow") => "flow", Some("hubscript") => "hubscript", + Some("agent") => "agent", _ => "script", }; out.insert("type".into(), json!(run_type)); @@ -869,7 +952,7 @@ pub(super) fn serialize_for_read(item: &Value, execution_mode: Option) -> 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"); + value.shift_remove("groups"); } else { value.insert("groups".into(), groups.clone()); } @@ -1013,7 +1096,7 @@ pub(super) async fn persist_draft( ) -> Result { let kind = draft_kind(item_type, trigger_kind) .ok_or_else(|| format!("Unsupported draft type \"{item_type}\"."))?; - let item = draft_item(&kind, path, value) + let item = shown_draft_item(ctx, &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)), @@ -1057,8 +1140,9 @@ pub(super) fn finish_draft_write(ctx: &Ctx<'_>, item: &Value, existed: bool) -> 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); + // The chat opens the draft in its own panel; an MCP client only has the link. if let Some(page) = draft_page(item_type, path, value) { - out.insert("url".into(), json!(ctx.page_url(&page))); + put(&mut out, "url", ctx.link(&page).map(Value::from)); } // A flow is not echoed back: the model just sent it. A variable comes back redacted. match item_type { @@ -1246,7 +1330,13 @@ pub(super) fn unified_patch( 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, + "triggerKind", + trigger_kind + .filter(|_| item_type == "trigger") + .map(Value::from), + ); put(&mut item, "path", row.get("path").cloned()); let mut is_draft = false; match item_type { @@ -1313,8 +1403,29 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { 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"); + // Scoped, the session's folders are the default, one listing each; an explicit + // path_prefix, "" included, overrides them. + let scope_roots: &[String] = match prefix { + None => ctx + .chat + .and_then(|chat| chat.scope_roots.as_deref()) + .unwrap_or_default(), + Some(_) => &[], + }; + let prefixes: Vec> = if scope_roots.is_empty() { + vec![prefix.filter(|p| !p.is_empty()).map(str::to_string)] + } else { + scope_roots.iter().map(|root| Some(format!("{root}/"))).collect() + }; + let per_page = limit.min(MAX_LIST_LIMIT); + let page_number = page.unwrap_or(1).max(1); + // Several folders read as one listing, folder after folder, so `limit` stays one cap per + // type (per trigger kind for triggers): page N is rows (N-1)*limit..N*limit of each + // concatenation, which takes every folder's first N*limit rows. + let window = (prefixes.len() > 1) + .then(|| (page_number - 1) * per_page..page_number * per_page); - let mut query = format!("per_page={}", limit.min(MAX_LIST_LIMIT)); + let mut query = format!("per_page={per_page}"); if let Some(page) = page { query.push_str(&format!("&page={page}")); } @@ -1338,40 +1449,54 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { } } - 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> = 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), + // Each type's index into its concatenation across folders, per trigger kind for triggers. + let mut index_by_kind: HashMap = HashMap::new(); + for prefix in &prefixes { + for item_type in ITEM_TYPES.iter().filter(|t| types.contains(t)) { + let kinds: Vec> = if *item_type == "trigger" { + TRIGGER_KINDS.iter().map(|kind| Some(*kind)).collect() + } else { + vec![None] }; - 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), - ); + let extra = if matches!(*item_type, "script" | "flow") { + "&include_draft_only=true&without_description=true" + } else { + "" + }; + for trigger_kind in kinds { + let mut query = match &window { + Some(window) => format!("per_page={}", window.end), + None => query.clone(), + }; + if let Some(prefix) = prefix { + query.push_str(&format!("&path_start={}", enc(prefix))); + } + 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), + }; + let index = index_by_kind + .entry(format!("{item_type}:{}", trigger_kind.unwrap_or_default())) + .or_default(); + for row in array(Some(&rows)) { + *index += 1; + if window.as_ref().is_some_and(|w| !w.contains(&(*index - 1))) { + continue; + } + 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), + ); + } } } } @@ -1380,6 +1505,7 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { // pages never repeat a page-1 item as its draft twin. if page.unwrap_or(1) == 1 { let mut count_by_type: HashMap = HashMap::new(); + let narrowing: Vec<&str> = prefixes.iter().flatten().map(String::as_str).collect(); for draft in list_drafts(ctx).await? { let text = |key: &str| draft.get(key).and_then(Value::as_str); let (item_type, path) = ( @@ -1391,11 +1517,13 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { } // 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 staged = text("draftPath"); + if !narrowing.is_empty() + && !narrowing.iter().any(|prefix| { + path.starts_with(prefix) || staged.is_some_and(|p| p.starts_with(prefix)) + }) + { + continue; } let count = count_by_type.entry(item_type.to_string()).or_default(); if *count >= limit { @@ -1425,7 +1553,15 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { }) }) .collect(); - Ok(pretty(&Value::Array(results))) + let listed = pretty(&Value::Array(results)); + if scope_roots.is_empty() { + return Ok(listed); + } + let folders: Vec<&str> = prefixes.iter().flatten().map(String::as_str).collect(); + Ok(format!( + "Items under {}, where this session works. Pass path_prefix \"\" for the whole workspace.\n{listed}", + folders.join(", ") + )) } /// The card of one workspace item: what `read_workspace_item` returns, under a one-line @@ -1663,8 +1799,28 @@ async fn write_script_draft( content: &str, force: bool, ) -> ToolResult { + // A session builds pipeline nodes into the folder's pipeline draft; a script draft + // written here never reaches the pipeline graph, and saving the pipeline drops it. + if ctx.in_session() && windmill_common::assets::parse_pipeline_annotations(content).in_pipeline + { + let folder = path + .strip_prefix("f/") + .and_then(|rest| rest.split_once('/')) + .map_or("", |(folder, _)| folder); + return Err(format!( + "\"{path}\" is a data pipeline node (its source starts with the pipeline annotation). In a session, pipeline nodes are not script drafts: call open_preview(kind=\"pipeline\", path=\"{folder}\") if that folder's pipeline editor is not open yet, then use build_pipeline_node (new node) or edit_pipeline_node (existing node). Nothing was written." + )); + } + ctx.saving_draft("script", path); let base = write_base(ctx, "script", path, None).await?; let existed = base.base.is_some(); + let before = base + .base + .as_ref() + .and_then(|b| b.get("content")) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); let mut draft = match base.base { Some(Value::Object(mut script)) => { if !base.from_draft { @@ -1697,17 +1853,21 @@ async fn write_script_draft( }; // 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); + // parse keeps the schema as it was. The chat infers with the editor's own parsers + // before saving, so its schema matches what the editor shows. + if ctx.surface == Surface::Mcp { + 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); + } + ctx.code_diff(&before, content, Some(language)); let persisted = persist_draft( ctx, "script", @@ -1755,7 +1915,11 @@ async fn discard_local_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult { 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?; + delete_draft(ctx, &kind, path, draft.created_at.as_deref(), false).await?; + ctx.status_after_save( + format!("Discarded {item_type} \"{path}\" draft"), + Some("Draft discarded"), + ); let mut out = Map::new(); out.insert("success".into(), json!(true)); out.insert( @@ -1826,18 +1990,18 @@ async fn rebase_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult { .as_ref() .map_or_else(|| "undefined".to_string(), js_str); if base.is_some() && base == head { + let message = format!( + "Draft \"{path}\" is already based on the latest deployed version ({head_text})." + ); + ctx.status(message.clone()); 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})." - )), - ); + out.insert("message".into(), json!(message)); return Ok(Value::Object(out).to_string()); } + ctx.status(format!("Rebasing draft \"{path}\" onto latest...")); // 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 @@ -1928,7 +2092,7 @@ async fn rebase_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult { 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 { + if ctx.surface == Surface::Mcp && result.len() > super::MAX_TOOL_RESULT_BYTES { let editor = match item_type { "script" => "/scripts/edit", "flow" => "/flows/edit", @@ -1940,7 +2104,8 @@ async fn rebase_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult { )); } let kind = draft_kind(item_type, None).ok_or_else(no_draft)?; - delete_draft(ctx, &kind, path, draft.created_at.as_deref()).await?; + delete_draft(ctx, &kind, path, draft.created_at.as_deref(), false).await?; + ctx.status_after_save(format!("Discarded stale draft \"{path}\""), Some("Rebased")); Ok(result) } diff --git a/backend/windmill-api/src/csrf.rs b/backend/windmill-api/src/csrf.rs index 4b2915f791..e92fb3a070 100644 --- a/backend/windmill-api/src/csrf.rs +++ b/backend/windmill-api/src/csrf.rs @@ -40,8 +40,11 @@ use crate::triggers::trigger_helpers::RunnableId; pub struct CrossSiteGetGuard(Option); impl CrossSiteGetGuard { - pub fn script_runnable(&self, script_path: &str) -> windmill_common::error::Result { - let runnable_id = RunnableId::from_script_path(script_path); + pub fn script_runnable( + &self, + script: &windmill_common::runnable_ref::RunnableRef, + ) -> windmill_common::error::Result { + let runnable_id = RunnableId::from_script_path(script.path()); let (Some(signal), RunnableId::HubScript(_)) = (&self.0, &runnable_id) else { return Ok(runnable_id); }; diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 1aa5340b67..c1934accb8 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -121,6 +121,7 @@ use windmill_common::{ }, oauth2::HmacSha256, query_builders, + runnable_ref::RunnableRef, scripts::{ScriptHash, ScriptLang}, users::username_to_permissioned_as, utils::{ @@ -297,6 +298,10 @@ pub fn workspaced_service() -> Router { .route("/run/dynamic_select", post(run_dynamic_select)) .route("/list", get(list_jobs)) .route("/oldest", get(get_oldest_job)) + .route( + "/recent_runs", + get(crate::jobs_recent_runs::list_recent_runs), + ) .route("/asset_dispatch_edges", get(list_asset_dispatch_edges)) .route( "/list_selected_job_groups", @@ -7185,10 +7190,11 @@ pub async fn run_flow_by_path( Query(run_query): Query, args: RawWebhookArgs, ) -> error::Result<(StatusCode, String)> { + let flow = RunnableRef::from_path(&flow_path.0, true)?; let (args, trigger_metadata) = match get_args_and_trigger_metadata( &db, &authed, - RunnableId::from_flow_path(flow_path.to_path()), + RunnableId::from_flow_path(flow.path()), &run_query, &w_id, args, @@ -7209,7 +7215,7 @@ pub async fn run_flow_by_path( None, user_db, w_id, - flow_path, + StripPath(flow.path().to_string()), run_query, args, trigger_metadata, @@ -7638,10 +7644,11 @@ pub async fn run_script_by_path( Query(run_query): Query, args: RawWebhookArgs, ) -> error::Result<(StatusCode, String)> { + let script = RunnableRef::from_path(&script_path.0, false)?; let (args, trigger_metadata) = match get_args_and_trigger_metadata( &db, &authed, - RunnableId::from_script_path(script_path.to_path()), + RunnableId::from_script_path(script.path()), &run_query, &w_id, args, @@ -7660,7 +7667,7 @@ pub async fn run_script_by_path( None, user_db, w_id, - script_path, + StripPath(script.path().to_string()), run_query, args, trigger_metadata, @@ -8178,8 +8185,9 @@ pub async fn run_wait_result_job_by_path_get( #[cfg(feature = "enterprise")] check_license_key_valid().await?; - let script_path = script_path.to_path(); - let runnable_id = cross_site.script_runnable(script_path)?; + let script = RunnableRef::from_path(&script_path.0, false)?; + let script_path = script.path(); + let runnable_id = cross_site.script_runnable(&script)?; check_scopes(&authed, || format!("jobs:run:scripts:{script_path}"))?; if method == http::Method::HEAD { @@ -8286,7 +8294,8 @@ pub async fn run_wait_result_flow_by_path_get( #[cfg(feature = "enterprise")] check_license_key_valid().await?; - let path = flow_path.to_path(); + let flow = RunnableRef::from_path(&flow_path.0, true)?; + let path = flow.path(); check_scopes(&authed, || format!("jobs:run:flows:{path}"))?; if method == http::Method::HEAD { @@ -8306,8 +8315,7 @@ pub async fn run_wait_result_flow_by_path_get( ) .await?; - run_wait_result_flow_by_path_internal(db, run_query, flow_path, authed, user_db, args, w_id) - .await + run_wait_result_flow_by_path_internal(db, run_query, &flow, authed, user_db, args, w_id).await } pub async fn run_wait_result_script_by_path( @@ -8321,7 +8329,8 @@ pub async fn run_wait_result_script_by_path( #[cfg(feature = "enterprise")] check_license_key_valid().await?; - let path = script_path.to_path(); + let script = RunnableRef::from_path(&script_path.0, false)?; + let path = script.path(); check_scopes(&authed, || format!("jobs:run:scripts:{path}"))?; let args = args @@ -8334,14 +8343,14 @@ pub async fn run_wait_result_script_by_path( ) .await?; - run_wait_result_script_by_path_internal(db, run_query, script_path, authed, user_db, w_id, args) + run_wait_result_script_by_path_internal(db, run_query, &script, authed, user_db, w_id, args) .await } pub async fn run_wait_result_script_by_path_internal( db: sqlx::Pool, run_query: RunJobQuery, - script_path: StripPath, + script: &RunnableRef, authed: ApiAuthed, user_db: UserDB, w_id: String, @@ -8352,7 +8361,7 @@ pub async fn run_wait_result_script_by_path_internal( let db_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; let (job_payload, tag, delete_after_use, delete_after_secs, timeout, on_behalf_of) = script_path_to_payload( - script_path.to_path(), + script.path(), Some(db_authed), db.clone(), &w_id, @@ -8569,7 +8578,8 @@ pub async fn run_wait_result_flow_by_path( #[cfg(feature = "enterprise")] check_license_key_valid().await?; - let path = flow_path.to_path(); + let flow = RunnableRef::from_path(&flow_path.0, true)?; + let path = flow.path(); check_scopes(&authed, || format!("jobs:run:flows:{path}"))?; let args = args @@ -8582,8 +8592,7 @@ pub async fn run_wait_result_flow_by_path( ) .await?; - run_wait_result_flow_by_path_internal(db, run_query, flow_path, authed, user_db, args, w_id) - .await + run_wait_result_flow_by_path_internal(db, run_query, &flow, authed, user_db, args, w_id).await } pub async fn stream_flow_by_path( @@ -8600,7 +8609,7 @@ pub async fn stream_flow_by_path( db, user_db, w_id, - RunnableId::from_flow_path(flow_path.to_path()), + RunnableId::from_flow_path(RunnableRef::from_path(&flow_path.0, true)?.path()), args, run_query, method == http::Method::GET, @@ -8640,7 +8649,8 @@ pub async fn stream_script_by_path( method: hyper::http::Method, args: RawWebhookArgs, ) -> error::Result { - let runnable_id = cross_site.script_runnable(script_path.to_path())?; + let runnable_id = + cross_site.script_runnable(&RunnableRef::from_path(&script_path.0, false)?)?; stream_job( authed, db, @@ -8821,7 +8831,7 @@ pub async fn stream_job( pub async fn run_wait_result_flow_by_path_internal( db: sqlx::Pool, run_query: RunJobQuery, - flow_path: StripPath, + flow: &RunnableRef, authed: ApiAuthed, user_db: UserDB, args: PushArgsOwned, @@ -8829,7 +8839,7 @@ pub async fn run_wait_result_flow_by_path_internal( ) -> error::Result { check_queue_too_long(&db, run_query.queue_limit).await?; - let flow_path = flow_path.to_path(); + let flow_path = flow.path(); let userdb_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; @@ -9344,15 +9354,15 @@ async fn run_inline_script_by_path( Path((w_id, script_path)): Path<(String, StripPath)>, Json(body): Json, ) -> error::Result { - let script_path_str = script_path.to_path(); - check_scopes(&authed, || format!("jobs:run:scripts:{script_path_str}"))?; + let script = RunnableRef::from_path(&script_path.0, false)?; + check_scopes(&authed, || format!("jobs:run:scripts:{}", script.path()))?; run_inline_script_inner( authed, token, db, w_id, // Resolved to a version by `run_inline_script_inner`. - InlineScriptTarget::Path { path: script_path.to_path().to_string(), hash: 0 }, + InlineScriptTarget::Path { path: script.path().to_string(), hash: 0 }, body.args, Some(user_db), ) @@ -10082,6 +10092,7 @@ async fn add_batch_jobs( ) = match batch_info.kind.as_str() { "script" => { if let Some(path) = batch_info.path { + let path = RunnableRef::from_path(&path, false)?.path().to_string(); let db_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; let ScriptHashInfo { @@ -10141,6 +10152,7 @@ async fn add_batch_jobs( let (mut value, job_kind, path) = if let Some(value) = batch_info.flow_value { (value, JobKind::FlowPreview, None) } else if let Some(path) = batch_info.path { + let path = RunnableRef::from_path(&path, true)?.path().to_string(); let mut tx = user_db.clone().begin(&authed).await?; let value_json = sqlx::query!( "SELECT coalesce(flow_version_lite.value, flow_version.value) as \"value!: sqlx::types::Json>\", flow.job_token_scopes FROM flow @@ -10565,7 +10577,7 @@ async fn run_dynamic_select( None, user_db.clone(), w_id.clone(), - StripPath(path), + StripPath(RunnableRef::from_path(&path, false)?.path().to_string()), run_query.clone(), push_args, None, @@ -10577,6 +10589,7 @@ async fn run_dynamic_select( RunnableKind::Flow => { // Runs the deployed flow's dynamic-select code. Path-scoped so a token not // scoped to this flow cannot trigger its code through dynamic select. + let path = RunnableRef::from_path(&path, true)?.path().to_string(); check_scopes(&authed, || format!("jobs:run:flows:{path}"))?; let mut conn = user_db.clone().begin(&authed).await?; diff --git a/backend/windmill-api/src/jobs_recent_runs.rs b/backend/windmill-api/src/jobs_recent_runs.rs new file mode 100644 index 0000000000..6136f2ea7d --- /dev/null +++ b/backend/windmill-api/src/jobs_recent_runs.rs @@ -0,0 +1,250 @@ +//! What ran recently in a workspace, one entry per runnable: the workspace home's "Recently run" +//! panel. Statuses and counts are settled here so the page only displays them. + +use std::collections::HashMap; + +use axum::{ + extract::{Path, Query}, + Extension, Json, +}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use windmill_common::{db::UserDB, error::JsonResult}; + +use crate::{db::ApiAuthed, users::get_scope_tags}; + +const WINDOW_HOURS: i32 = 24; +/// Newest root runs read from the window. A workspace running more than this in the window +/// gets counts over these runs only, and `capped` says so. +const SCAN_LIMIT: i64 = 5000; +/// Newest completions examined, flow steps included, to find those root runs. Each costs a +/// `v2_job` lookup, so this bounds a read where steps outnumber root runs; the counts then cover +/// a shorter span than the window, and `capped` says so. +const EXAMINE_LIMIT: i64 = 50_000; +const MAX_ITEMS: usize = 50; +const RUNS_PER_ITEM: usize = 10; + +/// The root runs the panel lists, on `j` (`v2_job`). An agent's run is filed under the agent's +/// path as a raw flow; an editor's flow preview also carries a path, so only a raw flow whose +/// path names a saved agent counts. +const LISTED_ROOT_RUN: &str = "j.workspace_id = $1 + AND j.parent_job IS NULL + AND j.runnable_path IS NOT NULL + AND ($3::text IS NULL OR starts_with(j.runnable_path, $3)) + AND ($5::text[] IS NULL OR j.tag = ANY($5)) + AND (j.kind IN ('script', 'singlestepflow', 'flow') + OR (j.kind = 'flowpreview' AND EXISTS ( + SELECT 1 FROM resource res + WHERE res.workspace_id = j.workspace_id AND res.path = j.runnable_path + AND res.resource_type = 'ai_agent')))"; + +#[derive(Deserialize)] +pub(crate) struct RecentRunsQuery { + folder: Option, + /// With `failed_ids_path`: list that item's unresolved failures in `failed_run_ids`. Only on + /// request, since a constantly failing item would put thousands of ids in every poll. + failed_ids_kind: Option, + failed_ids_path: Option, +} + +#[derive(Serialize)] +pub(crate) struct RecentRuns { + window_hours: i32, + capped: bool, + total_runs: i64, + failed_runs: i64, + failing_items: i64, + running_items: i64, + items: Vec, +} + +#[derive(Serialize)] +pub(crate) struct RecentRunItem { + path: String, + kind: String, + summary: Option, + /// The status of the item's newest run. + status: String, + /// Unresolved failures over the whole window, not only the runs listed. + failed_runs: i64, + /// Their ids, for the item named by the query's `failed_ids_*` only. + #[serde(skip_serializing_if = "Option::is_none")] + failed_run_ids: Option>, + /// Newest first. + runs: Vec, +} + +#[derive(Serialize, sqlx::FromRow)] +pub(crate) struct RecentRun { + id: uuid::Uuid, + #[serde(skip)] + path: String, + #[serde(skip)] + kind: String, + status: String, + /// When the run started, or was created for one that has not reported a start. + ran_at: DateTime, + duration_ms: Option, + #[serde(skip)] + examine_capped: bool, +} + +pub(crate) async fn list_recent_runs( + authed: ApiAuthed, + Extension(user_db): Extension, + Path(w_id): Path, + Query(q): Query, +) -> JsonResult { + let folder = q + .folder + .filter(|f| !f.is_empty()) + .map(|f| format!("f/{f}/")); + let failed_ids_of = q.failed_ids_kind.zip(q.failed_ids_path); + let mut tx = user_db.begin(&authed).await?; + + // A run counts when it completed in the window or is running now, whenever it was queued: + // a schedule is queued a full period ahead of its run. The completed side walks the + // (workspace_id, completed_at) index newest first, no further back than the EXAMINE_LIMIT-th + // completion (`since`, read index-only). Its root check is a per-row `v2_job` lookup: + // `OFFSET 0` keeps the planner from turning it into a join over every root run the + // workspace ever had, which grows with its history rather than with the window. + // A `singlestepflow` wraps a script or a flow. + let scope_tags = + get_scope_tags(&authed).map(|v| v.into_iter().map(str::to_string).collect::>()); + let runs = sqlx::query_as::<_, RecentRun>(&format!( + "WITH bound AS ( + SELECT (SELECT c.completed_at FROM v2_job_completed c + WHERE c.workspace_id = $1 + AND c.completed_at > now() - make_interval(hours => $2) + ORDER BY c.completed_at DESC + OFFSET $6 - 1 LIMIT 1) AS since + ), ran AS ( + (SELECT c.id, c.status::text AS status, c.started_at, + c.duration_ms::bigint AS duration_ms, c.completed_at + FROM v2_job_completed c + CROSS JOIN LATERAL (SELECT FROM v2_job j + WHERE j.id = c.id AND {LISTED_ROOT_RUN} OFFSET 0) root + WHERE c.workspace_id = $1 AND c.completed_at > now() - make_interval(hours => $2) + AND c.completed_at >= COALESCE((SELECT since FROM bound), '-infinity') + ORDER BY c.completed_at DESC + LIMIT $4) + UNION ALL + (SELECT q.id, NULL, q.started_at, NULL, NULL + FROM v2_job_queue q + JOIN v2_job j ON j.id = q.id + WHERE q.workspace_id = $1 AND q.running AND {LISTED_ROOT_RUN} + AND NOT EXISTS (SELECT 1 FROM v2_job_completed c WHERE c.id = q.id)) + ) + SELECT j.id, j.runnable_path AS path, + CASE WHEN j.kind = 'flow' THEN 'flow' + WHEN j.kind = 'flowpreview' THEN 'agent' + WHEN j.kind = 'singlestepflow' AND COALESCE( + (SELECT m->'value'->>'type' + FROM jsonb_array_elements(j.raw_flow->'modules') m + WHERE m->>'id' IN ('a', 'main') + LIMIT 1), + 'script') = 'flow' THEN 'flow' + ELSE 'script' END AS kind, + CASE WHEN r.status IS NULL THEN 'running' + WHEN r.status IN ('success', 'skipped') THEN 'success' + WHEN r.status = 'canceled' THEN 'canceled' + WHEN EXISTS (SELECT 1 FROM job_resolution jr WHERE jr.job_id = r.id) THEN 'resolved' + ELSE 'failure' END AS status, + COALESCE(r.started_at, j.created_at) AS ran_at, + r.duration_ms, + (SELECT since FROM bound) IS NOT NULL AS examine_capped + FROM ran r + JOIN v2_job j ON j.id = r.id + ORDER BY r.completed_at DESC NULLS FIRST, ran_at DESC + LIMIT $4" + )) + .bind(&w_id) + .bind(WINDOW_HOURS) + .bind(&folder) + .bind(SCAN_LIMIT) + .bind(&scope_tags) + .bind(EXAMINE_LIMIT) + .fetch_all(&mut *tx) + .await?; + + let capped = runs.len() as i64 == SCAN_LIMIT || runs.first().is_some_and(|r| r.examine_capped); + let total_runs = runs.len() as i64; + let failed_runs = runs.iter().filter(|r| r.status == "failure").count() as i64; + + // A script and a flow can share a path: they are two items. + let mut items: Vec = vec![]; + let mut index: HashMap<(String, String), usize> = HashMap::new(); + for run in runs { + let failed = run.status == "failure"; + let wanted = failed_ids_of + .as_ref() + .is_some_and(|(k, p)| *k == run.kind && *p == run.path); + match index.get(&(run.kind.clone(), run.path.clone())) { + Some(&i) => { + items[i].failed_runs += failed as i64; + if failed && wanted { + items[i].failed_run_ids.get_or_insert_with(Vec::new).push(run.id); + } + if items[i].runs.len() < RUNS_PER_ITEM { + items[i].runs.push(run); + } + } + None => { + index.insert((run.kind.clone(), run.path.clone()), items.len()); + items.push(RecentRunItem { + path: run.path.clone(), + kind: run.kind.clone(), + summary: None, + status: run.status.clone(), + failed_runs: failed as i64, + failed_run_ids: wanted.then(|| if failed { vec![run.id] } else { vec![] }), + runs: vec![run], + }); + } + } + } + let failing_items = items.iter().filter(|i| i.status == "failure").count() as i64; + let running_items = items.iter().filter(|i| i.status == "running").count() as i64; + items.truncate(MAX_ITEMS); + + let kinds: Vec = items.iter().map(|i| i.kind.clone()).collect(); + let paths: Vec = items.iter().map(|i| i.path.clone()).collect(); + let summaries: HashMap<(String, String), String> = + sqlx::query_as::<_, (String, String, Option)>( + "SELECT p.kind, p.path, CASE p.kind + WHEN 'script' THEN (SELECT NULLIF(s.summary, '') FROM script s + WHERE s.workspace_id = $1 AND s.path = p.path AND NOT s.archived + ORDER BY s.created_at DESC LIMIT 1) + WHEN 'flow' THEN (SELECT NULLIF(f.summary, '') FROM flow f + WHERE f.workspace_id = $1 AND f.path = p.path) + ELSE (SELECT NULLIF(r.description, '') FROM resource r + WHERE r.workspace_id = $1 AND r.path = p.path AND r.resource_type = 'ai_agent') + END + FROM unnest($2::text[], $3::text[]) AS p(kind, path)", + ) + .bind(&w_id) + .bind(&kinds) + .bind(&paths) + .fetch_all(&mut *tx) + .await? + .into_iter() + .filter_map(|(k, p, s)| s.map(|s| ((k, p), s))) + .collect(); + tx.commit().await?; + + for item in items.iter_mut() { + item.summary = summaries + .get(&(item.kind.clone(), item.path.clone())) + .cloned(); + } + + Ok(Json(RecentRuns { + window_hours: WINDOW_HOURS, + capped, + total_runs, + failed_runs, + failing_items, + running_items, + items, + })) +} diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 5e88107d1b..b47a644131 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -141,6 +141,7 @@ mod job_helpers_oss; pub mod job_metrics; pub mod jobs; pub mod jobs_export; +mod jobs_recent_runs; #[cfg(all(feature = "oauth2", feature = "private"))] pub mod oauth2_ee; #[cfg(feature = "oauth2")] @@ -159,6 +160,7 @@ mod saml_oss; #[cfg(feature = "private")] pub mod scim_ee; mod scim_oss; +mod session_hint; mod scripts; mod secret_backend_ext; mod service_logs; @@ -207,12 +209,13 @@ mod variables; pub mod volumes_ee; mod volumes_oss; pub mod webhook_util; +mod workspace_settings_document; mod workspaces; #[cfg(feature = "private")] pub mod workspaces_ee; mod workspaces_export; -mod workspace_settings_document; +mod ai_session_tools; #[cfg(feature = "mcp")] mod mcp_tools; @@ -448,6 +451,7 @@ pub async fn run_server( .layer(Extension(job_index_reader)) .layer(Extension(log_index_reader)) // .layer(Extension(index_writer)) + .layer(axum::middleware::from_fn(session_hint::mirror_session_cookie)) .layer(CookieManagerLayer::new()) .layer(Extension(WebhookShared::new( killpill_rx.resubscribe(), @@ -780,6 +784,10 @@ pub async fn run_server( Router::new() }) .nest("/ai", ai::workspaced_service()) + .nest( + "/ai_session_tools", + ai_session_tools::chat::workspaced_service(_base_internal_url.clone()), + ) .nest("/npm_proxy", windmill_api_npm_proxy::workspaced_service()) .nest( "/path_autocomplete", @@ -1287,8 +1295,7 @@ 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())); + ai_session_tools::register_router(&_base_internal_url, Some(app.clone())); let listener = listener.tap_io(move |tcp_stream| { let _ = tcp_stream.set_nodelay(!server_mode); @@ -1328,8 +1335,7 @@ pub async fn run_server( }); let served = server.await; - #[cfg(feature = "mcp")] - mcp::register_router(&_base_internal_url, None); + ai_session_tools::register_router(&_base_internal_url, None); served?; let forks = &windmill_api_workspaces::workspaces::BACKGROUND_FORKS; forks.close(); diff --git a/backend/windmill-api/src/mcp/session/card.html b/backend/windmill-api/src/mcp/card.html similarity index 100% rename from backend/windmill-api/src/mcp/session/card.html rename to backend/windmill-api/src/mcp/card.html diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 32bfe1d26a..7055aada3d 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -6,7 +6,7 @@ use async_trait::async_trait; use serde_json::Value; use std::collections::HashMap; -use windmill_common::{db::UserDB, utils::StripPath, DB}; +use windmill_common::{db::UserDB, runnable_ref::RunnableRef, DB}; use windmill_mcp::common::schema::enrich_resource_schemas; use windmill_mcp::common::transform::transform_property_keys; use windmill_mcp::common::types::{ @@ -83,15 +83,7 @@ impl WindmillBackend { 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(), - view: Default::default(), - } + session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access)) } pub fn new( @@ -283,14 +275,16 @@ impl McpBackend for WindmillBackend { 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) + let script = RunnableRef::from_path(path, false) + .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; + let push_args = prepare_push_args(&self.db, workspace_id, &script, args, request) .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; let result = run_wait_result_script_by_path_internal( self.db.clone(), RunJobQuery::default(), - StripPath(path.to_string()), + &script, auth.clone(), self.user_db.clone(), workspace_id.to_string(), @@ -311,14 +305,16 @@ impl McpBackend for WindmillBackend { 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) + let flow = RunnableRef::from_path(path, true) + .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; + let push_args = prepare_push_args(&self.db, workspace_id, &flow, args, request) .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; let result = run_wait_result_flow_by_path_internal( self.db.clone(), RunJobQuery::default(), - StripPath(path.to_string()), + &flow, auth.clone(), self.user_db.clone(), push_args, @@ -503,7 +499,8 @@ impl McpBackend for WindmillBackend { access: SessionAccess, origin: Option<&str>, ) -> BackendResult { - let ctx = session::Ctx { origin, ..self.session_ctx_with(auth, workspace_id, access) }; + let mut ctx = self.session_ctx_with(auth, workspace_id, access); + ctx.origin = origin; session::call_session_tool(&ctx, name, args).await } } diff --git a/backend/windmill-api/src/mcp/mod.rs b/backend/windmill-api/src/mcp/mod.rs index 05449d1b93..6052e4d60f 100644 --- a/backend/windmill-api/src/mcp/mod.rs +++ b/backend/windmill-api/src/mcp/mod.rs @@ -16,4 +16,3 @@ pub use core::{ extract_and_store_workspace_id, extract_workspace_from_token, list_tools_service, reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint, }; -pub(crate) use session::register_router; diff --git a/backend/windmill-api/src/mcp/session.rs b/backend/windmill-api/src/mcp/session.rs new file mode 100644 index 0000000000..0d1ee40b9f --- /dev/null +++ b/backend/windmill-api/src/mcp/session.rs @@ -0,0 +1,175 @@ +//! The AI session's toolset (`crate::ai_session_tools`) as MCP serves it. + +use serde_json::{json, Map, Value}; +use windmill_mcp::server::{ + BackendResult, CallToolResult, ContentBlock, ErrorData, MetaObject, SessionAccess, Tool, + ToolAnnotations, +}; + +use crate::ai_session_tools::{self as tools, CallRefused}; + +pub(super) use tools::{ + generic_session_instructions, session_instructions, workspace_context, Ctx, +}; + +pub(super) fn access(access: SessionAccess) -> tools::SessionAccess { + match access { + SessionAccess::ReadOnly => tools::SessionAccess::ReadOnly, + SessionAccess::ReadAndRun => tools::SessionAccess::ReadAndRun, + SessionAccess::Full => tools::SessionAccess::Full, + } +} + +/// 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) +} + +/// The destructive tools a card may call, each from a button the user presses. Every +/// other destructive tool is hidden from cards: a card acts as the user with no one +/// confirming. +const CARD_ACTIONS: &[&str] = &["deploy_workspace_item", "cancel_job"]; + +/// A tool's display name, which Claude shows in its tool list and approval prompts. +fn tool_title(name: &str) -> String { + let words: Vec = name + .split('_') + .map(|word| match word { + "db" | "sql" | "json" => word.to_uppercase(), + _ => word.to_string(), + }) + .collect(); + let title = words.join(" "); + let mut chars = title.chars(); + chars + .next() + .map(|first| first.to_uppercase().chain(chars).collect()) + .unwrap_or_default() +} + +/// The MCP Apps view a client that renders them draws these tools' results in. It draws +/// what the tool put in its result's `_meta` (`Ctx::view`), and acts by calling tools. +/// Hosts cache a view by its URI: bump the version when a change breaks the `_meta` shape +/// the deployed card reads. +pub(super) const CARD_URI: &str = "ui://windmill/card-v1"; +const CARD_HTML: &str = include_str!("card.html"); + +/// The `ui://` views the session's tools render in, as `(uri, html)`. +pub(super) fn session_views() -> &'static [(&'static str, &'static str)] { + &[(CARD_URI, CARD_HTML)] +} + +pub(super) fn session_tools(session_access: SessionAccess) -> Vec { + let access = access(session_access); + tools::session_tools(access) + .map(|tool| { + let mut meta = result_size_meta(); + if tool.destructive && !CARD_ACTIONS.contains(&tool.name) { + meta.0 + .insert("ui".into(), json!({ "visibility": ["model"] })); + } + let title = tool_title(tool.name); + Tool::new(tool.name, tool.description, tool.parameters.clone()) + .with_title(title.clone()) + .with_annotations( + ToolAnnotations::with_title(title) + .read_only(tool.read_only) + .destructive(tool.destructive) + .open_world(tool.open_world), + ) + .with_meta(meta) + }) + .chain( + tools::view_definitions() + .into_iter() + .filter(|(name, ..)| tools::view_allowed(name, access)) + .map(|(name, description, schema)| { + let mut meta = result_size_meta(); + meta.0 + .insert("ui".into(), json!({ "resourceUri": CARD_URI })); + let Value::Object(schema) = schema else { + unreachable!("a view tool's schema is an object") + }; + let title = tool_title(name); + Tool::new(name, description, schema) + .with_title(title.clone()) + .with_annotations( + ToolAnnotations::with_title(title) + .read_only(true) + .destructive(false) + .open_world(false), + ) + .with_meta(meta) + }), + ) + .collect() +} + +pub(super) async fn call_session_tool( + ctx: &Ctx<'_>, + name: &str, + args: Value, +) -> BackendResult { + let outcome = + tools::call_session_tool(ctx, name, args) + .await + .map_err(|refused| match refused { + CallRefused::NotAllowed(message) => ErrorData::invalid_request(message, None), + CallRefused::UnknownTool(message) | CallRefused::NotAvailable(message) => { + ErrorData::invalid_params(message, None) + } + })?; + windmill_common::feature_usage::log_feature_usage("mcp_workspace", "tool_call", name); + let content = vec![ContentBlock::text(outcome.text)]; + let mut result = if outcome.is_error { + CallToolResult::error(content) + } else { + CallToolResult::success(content) + }; + if let Some((key, view)) = ctx.view.lock().unwrap().take() { + result.meta = Some(MetaObject(Map::from_iter([(key.to_string(), view)]))); + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_card_can_call_a_destructive_tool_but_deploy_and_cancel() { + for tool in session_tools(SessionAccess::Full) { + let name = tool.name.as_ref(); + let destructive = tool.annotations.as_ref().and_then(|a| a.destructive_hint); + if destructive == Some(true) { + let ui = tool.meta.as_ref().and_then(|m| m.0.get("ui")); + let model_only = ui == Some(&json!({ "visibility": ["model"] })); + assert_eq!( + model_only, + !matches!(name, "deploy_workspace_item" | "cancel_job"), + "{name}" + ); + } + } + } + + /// The ChatGPT directory wants every hint explicit, and Claude's a title on every tool. + #[test] + fn every_session_tool_has_a_title_and_explicit_hints() { + for tool in session_tools(SessionAccess::Full) { + let a = tool.annotations.as_ref().expect("annotations"); + assert!(tool.title.is_some() && a.title.is_some(), "{}", tool.name); + assert!( + a.read_only_hint.is_some() + && a.destructive_hint.is_some() + && a.open_world_hint.is_some(), + "{}", + tool.name + ); + } + } +} diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index 9decf6993b..ba13efdb70 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -9,9 +9,9 @@ use axum::body::{to_bytes, Body}; use axum::response::Response; use serde_json::Value; use sql_builder::prelude::*; -use windmill_common::auth::create_jwt_token; -use windmill_common::db::{Authed, UserDB}; +use windmill_common::db::UserDB; use windmill_common::error::Error; +use windmill_common::runnable_ref::RunnableRef; use windmill_common::scripts::{get_full_hub_script_by_path, Schema}; use windmill_common::triggers::{RunnableFormat, RunnableFormatVersion, TriggerKind}; use windmill_common::utils::{query_elems_from_hub, StripPath}; @@ -213,9 +213,7 @@ fn items_query( } else { let conds: Vec = segments .iter() - .map(|s| { - "o.path LIKE ? ESCAPE '\\'".bind(&format!("%/{}", escape_like(s))) - }) + .map(|s| "o.path LIKE ? ESCAPE '\\'".bind(&format!("%/{}", escape_like(s)))) .collect(); sqlb.and_where(format!("({})", conds.join(" OR "))); } @@ -710,28 +708,6 @@ pub async fn create_http_request( 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>, -) -> BackendResult { - // 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( @@ -757,7 +733,9 @@ pub async fn send_as_caller( } }; - let token = mint_caller_jwt(workspace_id, api_authed, scopes).await?; + let token = crate::ai_session_tools::mint_caller_jwt(workspace_id, api_authed, scopes) + .await + .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; request_builder = request_builder.header("Authorization", format!("Bearer {}", token)); // Add body if present @@ -815,8 +793,7 @@ fn preprocessor_headers( pub async fn prepare_push_args( db: &DB, w_id: &str, - path: &str, - is_flow: bool, + runnable: &RunnableRef, args: Value, request: &McpRequest<'_>, ) -> Result { @@ -827,11 +804,11 @@ pub async fn prepare_push_args( } } - let runnable_id = if is_flow { - RunnableId::from_flow_path(path) + let runnable_id = if runnable.is_flow() { + RunnableId::from_flow_path(runnable.path()) } else { // Resolves a `hub/` path to the hub script on its own. - RunnableId::from_script_path(path) + RunnableId::from_script_path(runnable.path()) }; // MCP is not one of the `TRIGGER_KIND` enum values and does not need to be: diff --git a/backend/windmill-api/src/session_hint.rs b/backend/windmill-api/src/session_hint.rs new file mode 100644 index 0000000000..db6b78842c --- /dev/null +++ b/backend/windmill-api/src/session_hint.rs @@ -0,0 +1,102 @@ +//! A readable companion to the HttpOnly session cookie, so the frontend can tell whether the +//! session it rendered for last is still the one the browser holds before `whoami` answers. +//! It is derived from the token and cannot be turned back into it, so it grants nothing. +//! +//! Mirrored from the `Set-Cookie` headers rather than set beside each `token` cookie: every +//! site that sets or clears the session, EE ones included, must move the hint with it, or the +//! frontend would render one user's cached data under another's session. + +use axum::{extract::Request, middleware::Next, response::Response}; +use http::{header::SET_COOKIE, HeaderValue}; +use sha2::{Digest, Sha256}; +use tower_cookies::Cookie; +use windmill_common::users::COOKIE_NAME; + +pub(crate) const SESSION_HINT_COOKIE: &str = "wm_session"; + +fn session_hint(token: &str) -> String { + let digest = Sha256::new() + .chain_update(b"windmill-session-hint\0") + .chain_update(token.as_bytes()) + .finalize(); + hex::encode(&digest[..12]) +} + +/// The hint cookie for a `token` cookie being set (or cleared, when its value is empty), with +/// the same scope and lifetime. +fn hint_for(session: &Cookie) -> Cookie<'static> { + let value = if session.value().is_empty() { + String::new() + } else { + session_hint(session.value()) + }; + let mut hint = Cookie::new(SESSION_HINT_COOKIE, value); + if let Some(path) = session.path() { + hint.set_path(path.to_string()); + } + if let Some(domain) = session.domain() { + hint.set_domain(domain.to_string()); + } + if let Some(expires) = session.expires() { + hint.set_expires(expires); + } + if let Some(max_age) = session.max_age() { + hint.set_max_age(max_age); + } + if let Some(secure) = session.secure() { + hint.set_secure(secure); + } + if let Some(same_site) = session.same_site() { + hint.set_same_site(same_site); + } + hint.set_http_only(false); + hint +} + +/// Must wrap `CookieManagerLayer`, which writes the `Set-Cookie` headers this reads. +pub(crate) async fn mirror_session_cookie(req: Request, next: Next) -> Response { + let mut res = next.run(req).await; + let hints: Vec = res + .headers() + .get_all(SET_COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .filter_map(|s| Cookie::parse(s.to_owned()).ok()) + .filter(|c| c.name() == COOKIE_NAME) + .filter_map(|c| HeaderValue::from_str(&hint_for(&c).to_string()).ok()) + .collect(); + for hint in hints { + res.headers_mut().append(SET_COOKIE, hint); + } + res +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hint_follows_the_session_cookie_and_hides_the_token() { + let set = Cookie::parse( + "token=secret_token_value; Path=/; Domain=example.com; Secure; HttpOnly; \ + SameSite=Lax; Expires=Wed, 21 Oct 2037 07:28:00 GMT", + ) + .unwrap(); + let hint = hint_for(&set); + assert_eq!(hint.name(), SESSION_HINT_COOKIE); + assert!(!hint.value().contains("secret_token_value")); + assert_eq!(hint.value(), session_hint("secret_token_value")); + assert_ne!(hint.value(), session_hint("another_token")); + assert_eq!(hint.http_only(), Some(false)); + assert_eq!(hint.path(), Some("/")); + assert_eq!(hint.domain(), Some("example.com")); + assert_eq!(hint.expires(), set.expires()); + assert_eq!(hint.secure(), Some(true)); + + // A logout clears the session: the hint goes with it. + let cleared = Cookie::parse("token=; Path=/; Max-Age=0").unwrap(); + let hint = hint_for(&cleared); + assert_eq!(hint.value(), ""); + assert_eq!(hint.max_age(), cleared.max_age()); + } +} diff --git a/backend/windmill-common/src/data_metrics.rs b/backend/windmill-common/src/data_metrics.rs index 41eaeae9c3..6a955505e9 100644 --- a/backend/windmill-common/src/data_metrics.rs +++ b/backend/windmill-common/src/data_metrics.rs @@ -85,7 +85,7 @@ pub async fn sync_metric_catalog( .execute(&mut *db) .await?; - let ann = parse_pipeline_annotations(content); + let ann = parse_pipeline_annotations(content).for_script(script_path); let Some(spec) = ann .materialize .filter(|m| m.target_kind == AssetKind::Ducklake) diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index fac05d1fea..8f1e1da8ec 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -130,6 +130,7 @@ pub mod queue_metrics; pub mod result_stream; pub mod roles; pub mod runnable_job_stats; +pub mod runnable_ref; pub mod runnable_settings; pub mod runnables; pub mod schedule; diff --git a/backend/windmill-common/src/runnable_ref.rs b/backend/windmill-common/src/runnable_ref.rs new file mode 100644 index 0000000000..20dd9d1464 --- /dev/null +++ b/backend/windmill-common/src/runnable_ref.rs @@ -0,0 +1,97 @@ +//! The one parser for a script or flow named by path. A check and the resolution after it read +//! this value, so they cannot disagree on what a string means. Save-time guards that only refuse +//! a spelling may read the raw value: they can refuse more, never run something the parse did not +//! name. + +use crate::error::{Error, Result}; +use crate::utils::{parse_hub_id, RunnableKind}; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct RunnableRef { + kind: RunnableKind, + path: String, +} + +impl RunnableRef { + /// A bare path with a separate flag, as the run routes take it. + /// One leading `/` is tolerated, as the run routes have always stripped it. A second one is + /// refused: a stored path normalized once and stripped again when read must not change meaning. + /// A Hub path (`hub//…`, `hub/flows//…` for a flow) must carry a positive numeric id. + pub fn from_path(path: &str, is_flow: bool) -> Result { + let kind = if is_flow { + RunnableKind::Flow + } else { + RunnableKind::Script + }; + let canonical = path.strip_prefix('/').unwrap_or(path); + if canonical.is_empty() || canonical.starts_with('/') { + return Err(Error::BadRequest(format!( + "invalid {kind} path '{path}': expected a workspace or hub path" + ))); + } + let hub_prefix = match kind { + RunnableKind::Script => "hub/", + RunnableKind::Flow => "hub/flows/", + }; + if canonical.starts_with(hub_prefix) { + parse_hub_id(canonical, hub_prefix)?; + } + Ok(Self { kind, path: canonical.to_string() }) + } + + pub fn is_flow(&self) -> bool { + self.kind == RunnableKind::Flow + } + + /// The path without its leading `/`. + pub fn path(&self) -> &str { + &self.path + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_every_spelling() { + let bare = |s: &str, f: bool| RunnableRef::from_path(s, f); + for (name, got, is_flow, path) in [ + ("script", bare("u/me/x", false), false, "u/me/x"), + ("flow", bare("f/a/b", true), true, "f/a/b"), + ("one slash", bare("/u/me/x", false), false, "u/me/x"), + ("hub script", bare("hub/12/x", false), false, "hub/12/x"), + ("/hub script", bare("/hub/9/x", false), false, "hub/9/x"), + ( + "hub flow", + bare("hub/flows/76/x", true), + true, + "hub/flows/76/x", + ), + // A flow's Hub prefix is `hub/flows/`: `hub/abc` is a workspace flow path. + ( + "hub/ flow not flows/", + bare("hub/abc", true), + true, + "hub/abc", + ), + ] { + let got = got.unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!((got.is_flow(), got.path()), (is_flow, path), "{name}"); + } + + for (name, got) in [ + ("empty", bare("", false)), + ("only a slash", bare("/", false)), + ("two slashes", bare("//u/me/x", false)), + ("two slashes hub", bare("//hub/1/x", false)), + ("hub non-numeric", bare("hub/abc", false)), + ("hub zero", bare("hub/0/x", false)), + ("hub flow path as a script", bare("hub/flows/1/x", false)), + ("hub flow non-numeric", bare("hub/flows/abc", true)), + ("hub flow zero", bare("hub/flows/0", true)), + ] { + assert!(got.is_err(), "{name}: {got:?}"); + } + } +} diff --git a/backend/windmill-common/src/schema_contracts.rs b/backend/windmill-common/src/schema_contracts.rs index 7d941040bc..2485b47657 100644 --- a/backend/windmill-common/src/schema_contracts.rs +++ b/backend/windmill-common/src/schema_contracts.rs @@ -545,11 +545,10 @@ pub async fn check_schema_contracts( let producer_specs: HashMap> = producer_rows .into_iter() .map(|r| { - ( - r.path, - windmill_parser::asset_parser::parse_pipeline_annotations(&r.content) - .materialize, - ) + let spec = windmill_parser::asset_parser::parse_pipeline_annotations(&r.content) + .for_script(&r.path) + .materialize; + (r.path, spec) }) .collect(); diff --git a/backend/windmill-worker/src/duckdb_executor.rs b/backend/windmill-worker/src/duckdb_executor.rs index 8c3bab10ed..8f85b347d4 100644 --- a/backend/windmill-worker/src/duckdb_executor.rs +++ b/backend/windmill-worker/src/duckdb_executor.rs @@ -6,11 +6,12 @@ use serde_json::value::RawValue; use serde_json::{json, Value}; use uuid::Uuid; use windmill_common::error::{to_anyhow, Error, Result}; +use windmill_common::jobs::JobKind; use windmill_common::utils::sanitize_string_from_password; use windmill_common::worker::{get_memory, to_raw_value, Connection, SqlResultCollectionStrategy}; use windmill_common::workspaces::{ - get_datatable_resource_from_db, get_ducklake_from_db_unchecked, - sql_literal_len, strip_fork_reserved_attach_args, strip_sql_comments, DatatableAccess, DatatableConnectAs, + get_datatable_resource_from_db, get_ducklake_from_db_unchecked, sql_literal_len, + strip_fork_reserved_attach_args, strip_sql_comments, DatatableAccess, DatatableConnectAs, DucklakeCatalogResourceType, }; use windmill_common::PgDatabase; @@ -115,6 +116,8 @@ async fn fetch_custom_test_body(conn: &Connection, w_id: &str, path: &str) -> Re // `record_declared_warehouse_write`). fn build_materialized_query( query: &str, + // Names the table of a target that names none; a run without a path has to name it. + script_path: Option<&str>, partition_value: Option<&str>, // Custom (`// data_test `) test bodies, pre-fetched by the caller // (`fetch_custom_test_bodies`) so this stays pure/sync and unit-testable — @@ -129,6 +132,10 @@ fn build_materialized_query( }; let ann = parse_pipeline_annotations(query); + let ann = match script_path { + Some(path) => ann.for_script(path), + None => ann, + }; let has_tests = !ann.data_tests.is_empty(); let Some(m) = ann.materialize else { // Data tests run *against the materialized asset*; without a @@ -211,7 +218,8 @@ fn build_materialized_query( } if table.is_empty() { return Err(Error::ExecutionErr(format!( - "materialize: target `ducklake://{}` has no table (use ducklake:///
)", + "materialize: target `ducklake://{}` has no table, and this run has no script path to \ + name it after (use ducklake:///
)", m.target_path ))); } @@ -1343,7 +1351,30 @@ pub async fn do_duckdb( // itself stays pure/sync. let custom_test_bodies = fetch_custom_test_bodies(query, conn, &job.workspace_id).await?; - build_materialized_query(query, partition_value.as_deref(), &custom_test_bodies)? + // A deployed script, run directly or from a flow, names an untabled target after + // its own path. An inline flow step's path is `/`, which would name + // one shared table per step id across every flow, so it has to name its table. + // A flow editor's "Test this step" (marked by `_FLOW_PATH`) previews an inline step + // under that same `/` path. A step referencing a deployed script + // sends that script's hash and previews under its own path, which names its table + // as the script's own run does, wherever the script sits relative to the flow. + let inline_step_preview = job.runnable_id.is_none() + && job + .args + .as_ref() + .is_some_and(|a| a.0.contains_key("_FLOW_PATH")); + let script_path = (job.kind == JobKind::Script + || (job.kind == JobKind::Preview + && job.flow_step_id.is_none() + && !inline_step_preview)) + .then(|| job.runnable_path.as_deref()) + .flatten(); + build_materialized_query( + query, + script_path, + partition_value.as_deref(), + &custom_test_bodies, + )? } else { None }; @@ -3592,7 +3623,7 @@ mod tests { // The wrapped query still references `$file`, so the parsed sig binds it. // No custom data tests here, so no fetched bodies are needed. let (rewritten, _) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("managed mode rewrites the query"); @@ -3626,6 +3657,7 @@ mod tests { // binds them at run time. let (rewritten, _) = build_materialized_query( script, + None, Some("2026-07-02"), &std::collections::HashMap::new(), ) @@ -3648,7 +3680,7 @@ mod tests { let script = "-- materialize ducklake://main/dim key=id history track=name\n\ SELECT id, name FROM dl.src"; let (rewritten, _) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("scd2 is managed — must rewrite"); @@ -3679,7 +3711,7 @@ mod tests { let script = "-- materialize ducklake://main/dim key=id history deletes=close\n\ SELECT id, name FROM dl.src"; let (rewritten, _) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("scd2 is managed — must rewrite"); @@ -3692,10 +3724,11 @@ mod tests { #[test] fn materialize_scd2_requires_key() { let script = "-- materialize scd2 ducklake://main/dim\nSELECT id, name FROM dl.src"; - let err = match build_materialized_query(script, None, &std::collections::HashMap::new()) { - Err(e) => e, - Ok(_) => panic!("scd2 without key must error"), - }; + let err = + match build_materialized_query(script, None, None, &std::collections::HashMap::new()) { + Err(e) => e, + Ok(_) => panic!("scd2 without key must error"), + }; assert!( format!("{err}").contains("requires a natural key"), "got: {err}" @@ -3708,6 +3741,7 @@ mod tests { -- materialize scd2 ducklake://main/dim key=id\nSELECT id, name FROM dl.src"; let err = match build_materialized_query( script, + None, Some("2026-07-01"), &std::collections::HashMap::new(), ) { @@ -3733,7 +3767,7 @@ mod tests { -- data_test not_null id\n\ SELECT id FROM dl.src"; let (rewritten, meta) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("managed mode rewrites the query"); @@ -3758,7 +3792,7 @@ mod tests { let script = "-- materialize ducklake://main/dim key=id on_schema_change=fail\n\ SELECT id, name FROM dl.src"; let (rewritten, meta) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("managed mode rewrites the query"); @@ -3777,7 +3811,7 @@ mod tests { let script = "-- materialize ducklake://main/dim key=id on_schema_change=sync\n\ SELECT id, name FROM dl.src"; let (rewritten, meta) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("managed mode rewrites the query"); @@ -3810,7 +3844,7 @@ mod tests { let script = "-- materialize ducklake://main/dim key=id\n\ SELECT id, name FROM dl.src"; let (rewritten, meta) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("managed mode rewrites the query"); @@ -3834,7 +3868,7 @@ mod tests { let script = "-- materialize ducklake://main/t on_schema_change=fail\n\ SELECT a, b FROM dl.src"; let (rewritten, meta) = - build_materialized_query(script, None, &std::collections::HashMap::new()) + build_materialized_query(script, None, None, &std::collections::HashMap::new()) .expect("materialize builds") .expect("materialize present"); let rewritten = rewritten.expect("managed mode rewrites the query"); diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 553528fb66..a42a503324 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.856.0"; +export const VERSION = "v1.858.0"; export async function login(email: string, password: string): Promise { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 792b6b3144..cc4cddb5f5 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.856.0", + "version": "1.858.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.856.0", + "version": "1.858.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 fdf26bc3a0..8c26e318fb 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.856.0", + "version": "1.858.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/commands/pipeline/localGraph.ts b/cli/src/commands/pipeline/localGraph.ts index f6173a28bb..e5a228f95d 100644 --- a/cli/src/commands/pipeline/localGraph.ts +++ b/cli/src/commands/pipeline/localGraph.ts @@ -173,7 +173,7 @@ export type ParseAssetsRaw = { | { kind: string } )[]; // `// materialize [manual] …` — managed-materialize target (emitted by - // the wasm asset parser). The body (a bare trailing SELECT) writes nothing + // the wasm asset parser, which does not know the script path: see `withDefaultTable`). The body (a bare trailing SELECT) writes nothing // inferable, so the producer's output edge comes from here, not from `assets`. materialize?: { target_kind: string; @@ -195,6 +195,19 @@ export type ParseAssetsRaw = { column_lineage?: unknown[]; }; +type ParsedMaterialize = NonNullable; + +/** Mirrors Rust `MaterializeSpec::resolve_table`: a DuckLake target naming no table writes + * `/ %sveltekit.head% + -
+
@@ -259,6 +353,55 @@
+ %sveltekit.body% diff --git a/frontend/src/lib/assets/app.css b/frontend/src/lib/assets/app.css index 1236cdd50e..8f19f626ca 100644 --- a/frontend/src/lib/assets/app.css +++ b/frontend/src/lib/assets/app.css @@ -448,6 +448,25 @@ input[type='time']::-webkit-calendar-picker-indicator { } } +/* Content arriving, rather than being there: Home's page and the page header's actions, which + appear only once the header has measured them and so land after what is around them. */ +@keyframes wm-page-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} +.wm-page-in { + animation: wm-page-in 500ms ease-out both; +} +@media (prefers-reduced-motion: reduce) { + .wm-page-in { + animation: none; + } +} + .svelte-flow__edges { z-index: -10; } diff --git a/frontend/src/lib/components/AppConnectDrawer.svelte b/frontend/src/lib/components/AppConnectDrawer.svelte index 6cdfdc2998..ca6cb05300 100644 --- a/frontend/src/lib/components/AppConnectDrawer.svelte +++ b/frontend/src/lib/components/AppConnectDrawer.svelte @@ -14,16 +14,10 @@ interface Props { expressOAuthSetup?: boolean workspace?: string - disableChatOffset?: boolean native?: NativeConnect } - let { - expressOAuthSetup = false, - workspace = undefined, - disableChatOffset = false, - native = undefined - }: Props = $props() + let { expressOAuthSetup = false, workspace = undefined, native = undefined }: Props = $props() /** Set by `open(rt, fillPath)`, not by the parent: which resource this run fills is a * property of the click, and a prop would go stale between two different rows. */ @@ -82,7 +76,6 @@ dispatch('close') }} size="700px" - {disableChatOffset} > 1 ? resourceType : undefined)} diff --git a/frontend/src/lib/components/DraftBadge.svelte b/frontend/src/lib/components/DraftBadge.svelte index a52b09c411..8ea0b6e044 100644 --- a/frontend/src/lib/components/DraftBadge.svelte +++ b/frontend/src/lib/components/DraftBadge.svelte @@ -1,3 +1,10 @@ + + {#if trialRender} - +
{#if light}
Trial version
{/if} @@ -91,7 +96,7 @@ liveEditorDraftStoragePath={draftStoragePath || undefined} /> {/if} - +
{:else}
void | Promise /** Edit a folder of this workspace rather than the active one. */ workspace?: string @@ -101,7 +99,6 @@ { // Escape and click-away close the drawer before asking. Reopening in the same // tick is how the flow's script editor drawer handles this too: the close diff --git a/frontend/src/lib/components/ForkWorkspaceBanner.svelte b/frontend/src/lib/components/ForkWorkspaceBanner.svelte index 1736520eed..c27e2e9693 100644 --- a/frontend/src/lib/components/ForkWorkspaceBanner.svelte +++ b/frontend/src/lib/components/ForkWorkspaceBanner.svelte @@ -1,6 +1,5 @@ -{#if showBanner} +{#if showBanner && !homeActionsGathered()} @@ -213,81 +244,96 @@ {#snippet forkAction()} {@const total = comparison?.summary.total_diffs ?? 0} {@const conflicts = comparison?.summary.conflicts ?? 0} + {@const status = loading + ? 'loading' + : error + ? 'error' + : showDraftsOnly + ? 'drafts' + : total > 0 + ? 'drift' + : undefined} - {#if loading} - Checking for changes… - {:else if error} - Comparison failed - {:else if showDraftsOnly} - - {draftCount} draft{draftCount !== 1 ? 's' : ''} - - {:else if total > 0} - - - {#if changesAhead > 0} - openCompareDir('deploy_to')} - title="{changesAhead} ahead of {parentWorkspaceId} — review what this {currentNoun} has to give" - > - - {changesAhead}{compactCounts ? '' : ' ahead'} - - {/if} - {#if changesBehind > 0} - openCompareDir('update')} - title="{changesBehind} behind {parentWorkspaceId} — review what this {currentNoun} has yet to take" - > - - {changesBehind}{compactCounts ? '' : ' behind'} - - {/if} - {#if conflicts > 0} - - openCompareDir('deploy_to')} - title="{conflicts} conflicting item{conflicts !== 1 ? 's' : ''} — review them" - > - - {conflicts}{compactCounts ? '' : ` conflict${conflicts !== 1 ? 's' : ''}`} - - {/if} - - {#if draftCount > 0} - - - {draftCount}{compactCounts ? '' : ` draft${draftCount !== 1 ? 's' : ''}`} - - {/if} - {/if} + + {#key status} + + {#if loading} + Checking for changes… + {:else if error} + Comparison failed + {:else if showDraftsOnly} + + {draftCount} draft{draftCount !== 1 ? 's' : ''} + + {:else if total > 0} + + + {#if changesAhead > 0} + openCompareDir('deploy_to')} + title="{changesAhead} ahead of {parentWorkspaceId} — review what this {currentNoun} has to give" + > + + {changesAhead}{compactCounts ? '' : ' ahead'} + + {/if} + {#if changesBehind > 0} + openCompareDir('update')} + title="{changesBehind} behind {parentWorkspaceId} — review what this {currentNoun} has yet to take" + > + + {changesBehind}{compactCounts ? '' : ' behind'} + + {/if} + {#if conflicts > 0} + + openCompareDir('deploy_to')} + title="{conflicts} conflicting item{conflicts !== 1 ? 's' : ''} — review them" + > + + {conflicts}{compactCounts ? '' : ` conflict${conflicts !== 1 ? 's' : ''}`} + + {/if} + + {#if draftCount > 0} + + + {draftCount}{compactCounts ? '' : ` draft${draftCount !== 1 ? 's' : ''}`} + + {/if} + {/if} + + {/key} {#if showDraftsOnly} {:else} - - {draftCount} draft{draftCount !== 1 ? 's' : ''} - - + + + + {draftCount} draft{draftCount !== 1 ? 's' : ''} + + + {/if} {/snippet} diff --git a/frontend/src/lib/components/WorkspaceItemDrillPicker.svelte b/frontend/src/lib/components/WorkspaceItemDrillPicker.svelte index ec285ce4dd..67db2f3a1b 100644 --- a/frontend/src/lib/components/WorkspaceItemDrillPicker.svelte +++ b/frontend/src/lib/components/WorkspaceItemDrillPicker.svelte @@ -8,10 +8,7 @@ don't need to know about the generic tree model underneath. Surfaces the session's drafts (via `listGlobalDrafts`: backend draft rows overlaid with live editor cells) as extra items alongside the backend-loaded list, so drafts the listing does not show yet (unsaved cells, a rename typed -in a live editor) are still navigable. Gated on -`isGlobalAiEnabled()` — without sessions, the only UserDrafts present are -standalone editor autosaves and surfacing those in the breadcrumb picker -would be surprising. +in a live editor) are still navigable. --> @@ -48,7 +47,6 @@ The menu adding a pipeline script downstream of an asset: opened from the asset' pick.language as ScriptLang, pick.path, (pick.outputKind ?? 'none') as PipelineOutputKind, - pick.aiPrompt, { outputAsset: pick.outputAsset } ) } diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte index 87b085593c..5927bf65bd 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte @@ -85,15 +85,11 @@ language: import('$lib/gen').ScriptLang, scriptPath: string, outputKind: import('./pipelineTemplates').PipelineOutputKind, - aiPrompt?: string, options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void // Pipeline-wide + node shown at the top of the graph. Picking any // kind from the menu invokes this one callback with the chosen // trigger source — the page uses it to seed the draft's annotation. - // `aiPrompt` is set when the user filled the optional prompt field - // on the path stage; the page is expected to bootstrap the body via - // AI instead of using the seeded template. onAddPipelineScript?: ( language: import('$lib/gen').ScriptLang, path: string, @@ -102,7 +98,6 @@ path: string | undefined }, outputKind: import('./pipelineTemplates').PipelineOutputKind, - aiPrompt?: string, options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void // Folder-scoped prefix shown as a read-only chip in the insert menu diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte index 4577a11915..e1daf45704 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte @@ -925,7 +925,12 @@ sendUserToast(`Saved ${script.path}`) // Authoritative save-time schema-contract check (pipelines gap #2b): // warn-only, post-commit. Fire-and-forget — must never gate the save. - notifyContractWarnings(workspace, script.language as ScriptLang, script.content) + notifyContractWarnings( + workspace, + script.language as ScriptLang, + script.content, + script.path + ) if (isDraft) { onDraftSaved?.(script.path) } else { diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte index d0835b2880..d913d4b314 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte @@ -124,7 +124,6 @@ language: ScriptLang, scriptPath: string, outputKind: PipelineOutputKind, - aiPrompt?: string, options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void pathPrefix?: string diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte index 364c4c6221..ce618fab63 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte @@ -181,7 +181,6 @@ language: ScriptLang, scriptPath: string, outputKind: PipelineOutputKind, - aiPrompt?: string, options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void onAddPipelineScript?: ( @@ -189,7 +188,6 @@ path: string, source: { kind: NativeTriggerKind; path: string | undefined }, outputKind: PipelineOutputKind, - aiPrompt?: string, options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void onRunnableMenuRemove?: (...args: any[]) => void diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte index c1b64b59a2..f93826d98f 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte @@ -21,11 +21,6 @@ // Picked output asset kind. Optional because some menu instances // (those without `pickOutputKind`) skip that stage entirely. outputKind?: string - // Optional natural-language prompt entered on the path stage. - // When set, the caller is expected to bootstrap the script body - // from this prompt via AI (using language + outputKind + the - // upstream input as context) instead of using the seeded template. - aiPrompt?: string // Set by the schedule step when the picked kind is `schedule`. schedule?: PipelineInsertSchedule // Set by the asset step for the table output kinds, replacing the @@ -43,7 +38,6 @@ @@ -207,12 +201,6 @@ transition: opacity var(--duration) ease; } - .drawer.respect-global-chat.global-chat-open > .overlay { - width: 100%; - right: var(--adjusted-offset); - left: auto; - } - .drawer.open > .overlay { opacity: 1; } @@ -246,11 +234,6 @@ transform: translate(100%, 0); } - .drawer.respect-global-chat.global-chat-open > .panel.right { - right: var(--adjusted-offset); - width: calc(100vw - var(--adjusted-offset)); - } - .panel.top { top: 0; transform: translate(0, -100%); @@ -292,10 +275,6 @@ transform var(--duration) ease; } - .drawer.respect-global-chat.global-chat-open > .panel.center { - right: calc(var(--adjusted-offset) + 2rem); - } - .drawer.open > .panel.center { opacity: 1; transform: scale(1); diff --git a/frontend/src/lib/components/common/modal/Modal.svelte b/frontend/src/lib/components/common/modal/Modal.svelte index 1f5ca26a98..4932349787 100644 --- a/frontend/src/lib/components/common/modal/Modal.svelte +++ b/frontend/src/lib/components/common/modal/Modal.svelte @@ -25,8 +25,6 @@ import CloseButton from '../CloseButton.svelte' import Disposable from '../drawer/Disposable.svelte' import ConditionalPortal from '../drawer/ConditionalPortal.svelte' - import { zIndexes } from '$lib/zIndexes' - import { chatState } from '$lib/components/copilot/chat/sharedChatState.svelte' interface Props { title: string @@ -94,7 +92,7 @@ fitHeight = false, paginated = false, enterConfirms = true, - minZIndex: minZIndexProp = undefined, + minZIndex = undefined, titleBadge, levelBadge, settings, @@ -122,11 +120,6 @@ let disposable: Disposable | undefined = $state(undefined) - // An explicit override wins; otherwise only elevate above the AI chat panel - // when it's actually open — when chat is closed there's nothing at z-index - // 1200 to stack above. - const minZIndex = $derived(minZIndexProp ?? (chatState.size > 0 ? zIndexes.aiChat + 1 : 0)) - // So content in the body can tell a key meant for this dialog from one meant for whatever was // opened over it. Read lazily: `disposable` is bound after this runs. setTopmostSurface(() => disposable?.isTopmost() ?? true) diff --git a/frontend/src/lib/components/common/modal/Modal2.svelte b/frontend/src/lib/components/common/modal/Modal2.svelte index 6d7c8fdd0f..4c76c4f935 100644 --- a/frontend/src/lib/components/common/modal/Modal2.svelte +++ b/frontend/src/lib/components/common/modal/Modal2.svelte @@ -8,8 +8,6 @@ import { X } from 'lucide-svelte' import List from '$lib/components/common/layout/List.svelte' import { fade } from 'svelte/transition' - import { zIndexes } from '$lib/zIndexes' - import { chatState } from '$lib/components/copilot/chat/sharedChatState.svelte' import Disposable from '../drawer/Disposable.svelte' import { overlayHostActive, setTopmostSurface } from '../overlayHost.svelte' import { untrack } from 'svelte' @@ -125,9 +123,6 @@ function fadeFast(node: HTMLElement) { return fade(node, { duration: 200 }) } - - // Elevate above the AI chat panel while chat is open so the dialog isn't hidden behind it. - const minZIndex = $derived(chatState.size > 0 ? zIndexes.aiChat + 1 : 0) - + {#snippet children({ zIndex })} {#if isOpen} diff --git a/frontend/src/lib/components/common/table/Row.svelte b/frontend/src/lib/components/common/table/Row.svelte index 4054f61c9b..4f53d5504a 100644 --- a/frontend/src/lib/components/common/table/Row.svelte +++ b/frontend/src/lib/components/common/table/Row.svelte @@ -182,8 +182,10 @@ bind:this={rowEl} data-row-selection-key={rowSelection?.key} data-row-keyboard-selected={keyboardSelected ? 'true' : undefined} + data-row-path={path} + data-row-kind={kind} class={twMerge( - 'group/row w-full inline-flex items-center gap-4 px-4 py-3', + 'group/row w-full inline-flex items-center gap-4 px-4 py-3 transition-shadow duration-300 data-[revealed]:ring-2 data-[revealed]:ring-inset data-[revealed]:ring-accent', 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', diff --git a/frontend/src/lib/components/copilot/AIFormAssistant.svelte b/frontend/src/lib/components/copilot/AIFormAssistant.svelte index 8b5daefa9d..c6accd4c64 100644 --- a/frontend/src/lib/components/copilot/AIFormAssistant.svelte +++ b/frontend/src/lib/components/copilot/AIFormAssistant.svelte @@ -1,10 +1,8 @@ {#snippet aiButton(unifiedSize: 'sm' | 'md')} - - - {#snippet fallback()} - - {/snippet} - + {/snippet} {#if $copilotInfo.workspaceDisabled} diff --git a/frontend/src/lib/components/copilot/AskAiButton.svelte b/frontend/src/lib/components/copilot/AskAiButton.svelte index 4b40c021a5..1736fd6089 100644 --- a/frontend/src/lib/components/copilot/AskAiButton.svelte +++ b/frontend/src/lib/components/copilot/AskAiButton.svelte @@ -1,11 +1,8 @@ @@ -46,7 +26,7 @@ }} unifiedSize="md" btnClasses={AIBtnClasses('default')} - title={handsOffToSession ? 'Ask this in a new AI session' : 'Ask this in the AI chat'} + title="Ask this in a new AI session" on:click={onClick} > {label} diff --git a/frontend/src/lib/components/copilot/CustomAIPrompts.svelte b/frontend/src/lib/components/copilot/CustomAIPrompts.svelte index 4c7cfbe47b..4289f82717 100644 --- a/frontend/src/lib/components/copilot/CustomAIPrompts.svelte +++ b/frontend/src/lib/components/copilot/CustomAIPrompts.svelte @@ -1,5 +1,5 @@
diff --git a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte index 45df865c11..b16f23bf00 100644 --- a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte +++ b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte @@ -1,12 +1,5 @@ -{#snippet button(onClick?: () => void)} - -
- {/snippet} - {#snippet content()} -
-
-

Enable Windmill AI in the workspace settings

-
- {/snippet} - - {/snippet} -
+ /> {/if} {/if} diff --git a/frontend/src/lib/components/copilot/aiClientWorkspace.ts b/frontend/src/lib/components/copilot/aiClientWorkspace.ts new file mode 100644 index 0000000000..27d3b07744 --- /dev/null +++ b/frontend/src/lib/components/copilot/aiClientWorkspace.ts @@ -0,0 +1,14 @@ +// The workspace the AI clients go through (their proxy URL names it). Kept apart from +// `./lib`, which holds the provider SDKs: what switches workspace runs in the app shell, and +// the clients are built on their first use rather than on every switch. +let current: string | undefined +let generation = 0 + +export function setAiClientWorkspace(workspace: string): void { + current = workspace + generation++ +} + +export function aiClientWorkspace(): { workspace: string | undefined; generation: number } { + return { workspace: current, generation } +} diff --git a/frontend/src/lib/components/copilot/aiProviders.ts b/frontend/src/lib/components/copilot/aiProviders.ts new file mode 100644 index 0000000000..5b2abbf040 --- /dev/null +++ b/frontend/src/lib/components/copilot/aiProviders.ts @@ -0,0 +1,144 @@ +// The provider catalog, apart from `./lib` and its SDKs so that what only names providers or +// picks a default model loads neither. +import type { AIProvider } from '$lib/gen' + +export interface AIProviderDetails { + label: string + defaultModels: string[] +} + +// The first entry is what a new workspace is created with (see +// CreateWorkspaceInner), so each list leads with the balanced tier rather than +// the frontier model. The gpt-5 family is deprecated (retires 2026-12-11) but +// still served, so it stays in the list below the 5.6 models. +const OPENAI_MODELS = [ + 'gpt-6.1-sol', + 'gpt-6-sol', + 'gpt-6-astra', + 'gpt-6-luna', + 'gpt-5.6-terra', + 'gpt-5.6-sol', + 'gpt-5.6-luna', + 'gpt-5', + 'gpt-5-mini', + 'gpt-4o', + 'gpt-4o-mini', + 'o4-mini', + 'o3' +] + +/** The providers that chat. Every surface picking a model to talk to (the copilot, flow chat, an + * agent's text or image output, eval judges) offers exactly these. */ +export type ChatAIProvider = Exclude + +export const AI_PROVIDERS: Record = { + openai: { + label: 'OpenAI', + defaultModels: OPENAI_MODELS + }, + anthropic: { + label: 'Anthropic', + defaultModels: [ + 'claude-sonnet-5-5', + 'claude-opus-5-5', + 'claude-sonnet-5', + 'claude-opus-5', + 'claude-opus-4-8', + 'claude-haiku-4-5' + ] + }, + googleai: { + label: 'Google AI', + defaultModels: [ + 'gemini-3.6-flash', + 'gemini-3.5-flash', + 'gemini-3.1-pro-preview', + 'gemini-3.5-flash-lite', + 'gemini-3.1-flash-lite', + 'gemini-2.5-pro', + 'gemini-2.5-flash' + ] + }, + azure_openai: { + label: 'Azure OpenAI', + defaultModels: OPENAI_MODELS + }, + azure_foundry: { + label: 'Azure AI Foundry', + defaultModels: [ + 'gpt-5.6-terra', + 'gpt-5.6-sol', + 'claude-sonnet-5', + 'claude-opus-5', + 'DeepSeek-V4-Pro', + 'Llama-3.3-70B-Instruct', + 'Phi-4' + ] + }, + mistral: { + label: 'Mistral', + defaultModels: ['mistral-medium-latest', 'codestral-latest'] + }, + deepseek: { + label: 'DeepSeek', + defaultModels: ['deepseek-v4-pro', 'deepseek-flash'] + }, + groq: { + label: 'Groq', + defaultModels: ['openai/gpt-oss-120b', 'openai/gpt-oss-20b'] + }, + openrouter: { + label: 'OpenRouter', + defaultModels: ['meta-llama/llama-3.2-3b-instruct:free'] + }, + togetherai: { + label: 'Together AI', + defaultModels: ['meta-llama/Llama-3.3-70B-Instruct-Turbo'] + }, + aws_bedrock: { + label: 'AWS Bedrock', + defaultModels: [ + 'global.anthropic.claude-sonnet-5', + 'global.anthropic.claude-opus-5', + 'global.anthropic.claude-haiku-4-5-20251001-v1:0' + ] + }, + customai: { + label: 'Custom AI', + defaultModels: [] + } +} + +/** Decision models answer typed questions instead of messages, so only an AI decision offers + * them: TypeSafe's Jev, Cloudflare's Jev-compatible Clef, and the model of OpenAI's Decisions + * API, which an OpenAI resource serves next to its chat models. The pinned Jev version is there + * for flows tuned against its probabilities. */ +export const DECISION_AI_PROVIDERS: Record< + Exclude | 'openai', + AIProviderDetails +> = { + openai: { + label: 'OpenAI', + defaultModels: ['gpt-6-luna'] + }, + typesafe: { + label: 'TypeSafe', + defaultModels: ['jev-latest', 'jev-1.13.0'] + }, + cloudflare: { + label: 'Cloudflare', + defaultModels: ['clef', 'clef-flash'] + } +} + +/** Label and default models of any provider kind, chat or decision. A kind in neither list (a flow + * written by hand or by a newer version) is named as it is and offers no models. */ +export function aiProviderDetails(provider: AIProvider): AIProviderDetails { + return ( + (AI_PROVIDERS as Record)[provider] ?? + (DECISION_AI_PROVIDERS as Record)[provider] ?? { + label: provider, + defaultModels: [] + } + ) +} diff --git a/frontend/src/lib/components/copilot/chat/AIChat.svelte b/frontend/src/lib/components/copilot/chat/AIChat.svelte index 1ff6830ba3..d59254f02f 100644 --- a/frontend/src/lib/components/copilot/chat/AIChat.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChat.svelte @@ -7,7 +7,6 @@ import { getAiChatManager } from './aiChatManagerContext' const aiChatManager = getAiChatManager() - import 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' @@ -103,10 +102,6 @@ 'How do I schedule a recurring job?' ] - export async function generateStep(moduleId: string, lang: ScriptLang, instructions: string) { - aiChatManager.generateStep(moduleId, lang, instructions) - } - export async function sendRequest( options: { removeDiff?: boolean @@ -135,6 +130,10 @@ aiChatDisplay?.openAssistantSettings(section, root) } + export function prefill(text: string) { + aiChatDisplay?.prefill(text) + } + export async function attachContext(element: import('./context').ContextElement) { await aiChatDisplay?.attachContext(element) } @@ -160,23 +159,11 @@ onkeydown={(e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'l') { e.preventDefault() - aiChatManager.toggleOpen() aiChatDisplay?.focusInput() } }} /> -{#snippet headerLeft()} -
\` means the runtime writes the node's output table FOR you — write the body as a single SELECT and the runtime wraps it in the create/replace, so do NOT also write your own CREATE TABLE / INSERT. The \`dbt://\` target below is the opposite: the node writes its own DDL and none of the write strategies apply to it. IMPORTANT: a MANAGED \`// materialize\` is **DuckDB-only** and its target MUST be a DuckLake table (\`ducklake:///
\`) — deploy rejects a \`ducklake://\` target on any other language. For a \`python3\`/\`bun\`/\`postgresql\` node writing the lake, do NOT use \`// materialize\`; write the table straight into DuckLake with \`wmill.ducklake()\` (or a data table with \`wmill.datatable()\`), or a \`CREATE TABLE\` in postgresql and let the output be inferred. Reach for \`duckdb\` when a node should materialize a DuckLake table. The one target any language BUT DBT'S OWN may declare (a dbt project's writes come from its manifest, so \`// materialize\` on a dbt script is rejected at deploy) is a WAREHOUSE RELATION: \`// materialize manual dbt:////\`, with \`\` a warehouse the workspace configures under Settings → dbt. \`manual\` is its only mode — nothing generates warehouse DDL, so the node issues its own write and the annotation records the outcome. Use it on an ingestion node a dbt project reads as a \`source\`: the declared relation and the dbt model become ONE graph node, and a downstream \`// on dbt:////\` fires when that node completes. Write strategy: with no option it REPLACES the whole table each run (full refresh; the only mode whose output columns may change); \`// materialize append\` INSERT-appends rows (incremental); \`// materialize key=\` merges/upserts on \`\`. \`// materialize manual \` opts OUT of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage. \`materialize\` is paired with partitioning for incremental pipelines: a \`// partitioned \` node runs once per partition (append/merge into a fixed-schema table), and the \`{partition}\` token — usable in any asset URI AND in the body SQL — is substituted with the current partition's IDENTITY string at run time. To filter the source to the active slice on a time grain, use the runtime-injected macro: \`WHERE wm_partition() = {partition}\`. \`wm_partition(ts)\` buckets a timestamp with the exact identity format the runtime used (daily/hourly/weekly/monthly), so it always matches and you never hand-write a \`strftime\` format. Do NOT write \`= TIMESTAMP {partition}\`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at runtime. For \`dynamic\` partitioning the identity is your caller-supplied key (not a timestamp, no macro), so filter on it directly: \`WHERE = {partition}\`. \`materialize\` is an output DECLARATION on the node — it is not a command; there is no "materialize run". -- \`measure\` / \`dimension\` (declared metrics): on a node that materializes a DuckLake table, \`// measure = [where ]\` names the canonical way to aggregate that table (e.g. \`// measure revenue = sum(amount) where not is_refund\`), and \`// dimension = \` names a way to slice it (e.g. \`// dimension region = region\`, \`// dimension month = date_trunc('month', ordered_at)\`). They execute nothing: they are catalogued at deploy so the editor and other agents can reuse the definition instead of re-deriving it and silently disagreeing. Keep the predicate in the \`where\` clause rather than folding it into the aggregate: it is rendered as \` FILTER (WHERE )\`, which is what lets two measures with different predicates sit under one GROUP BY. DuckLake-only, and only meaningful next to \`// materialize\`. Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures, an obvious \`count(*)\` earns nothing. To USE a metric another node declares, read that node with read_pipeline_node and reuse its exact expression rather than guessing it. +- Each node declares itself in top-of-file annotation comments, written in its own comment syntax (\`--\` for SQL, \`#\` for python3/bash, \`//\` for bun/TS): \`pipeline\` makes it a node, \`on \` says what starts it, and \`materialize \` names the DuckLake table the runtime writes from its SELECT (a target naming no table writes the one named after the script). - Use get_pipeline_graph to see the current nodes/assets/triggers, and read_pipeline_node before editing one. - ${pathLine}${ canWriteDraft ? ` +- How to write a node (the \`pipeline\` / \`on\` / \`materialize\` annotations, write strategies, partitioning, declared metrics, reading a DuckLake table) is in get_instructions with subject "pipeline": read it before building the first node, unless this conversation already did. +- To reuse a metric another node declares, read that node with read_pipeline_node and reuse its exact expression rather than guessing it. - Build new nodes with build_pipeline_node and edit existing ones with edit_pipeline_node. Give every node a succinct \`summary\` (a few words saying what it does, e.g. "Ingest Stripe charges"), and update it when an edit changes what the node does. These apply directly as unsaved drafts on the canvas (like the flow/script editor applies AI edits) — they DO NOT deploy. There is no separate Accept/Reject step. Prefer these over the generic write_script/edit_script draft tools while a pipeline is open. - Reuse existing asset paths from the graph when wiring a downstream node to an upstream one (read the upstream's write asset, then \`// on\` that same URI). - TRIGGERS: an ingestion node (one with no upstream asset to react to) must declare how it starts, e.g. \`// on schedule\`, and every \`on \` line needs its trigger: pass it in build_pipeline_node's \`triggers\` (or call set_pipeline_trigger) in the same step you build the node. A schedule needs a 6-field cron and an IANA timezone — pick a sensible cadence from the request (e.g. daily at 06:00 UTC for a daily sync) rather than leaving it empty; for the other kinds call get_trigger_schema(kind) for the config fields and ask the user for any connection/resource you cannot find. Never leave a declared trigger without one: the node would deploy with nothing to start it. \`webhook\` and \`data_upload\` need no trigger. diff --git a/frontend/src/lib/components/copilot/chat/script/core.ts b/frontend/src/lib/components/copilot/chat/script/core.ts index 93ad12ff67..e7053ce141 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.ts @@ -32,8 +32,10 @@ import { getDbSchemas } from '$lib/components/apps/components/display/dbtable/me import { scriptLangToEditorLang } from '$lib/scripts' import { getScriptPrompt, getWorkflowAsCodePrompt } from '$system_prompts' -// Score threshold for npm packages search filtering -const SCORE_THRESHOLD = 1000 +// The registry's best match is kept, and the runner-up only when it scores this share of it: +// the scores have no fixed scale (a descriptive query's right answer can score a few hundred, a +// package's own name thousands), so a match is judged against the best one. +const NPM_RUNNER_UP_SHARE = 0.6 // percentage of the context window for documentation of npm packages const DOCS_CONTEXT_PERCENTAGE = 1 // percentage of the context window for types of npm packages @@ -612,8 +614,9 @@ export async function searchExternalIntegrationResources(args: { query: string } `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(args.query)}&size=2` ) const data = await result.json() + const best = Math.max(0, ...data.objects.map((r: PackageSearchQuery) => r.searchScore)) const filtered = data.objects.filter( - (r: PackageSearchQuery) => r.searchScore >= SCORE_THRESHOLD + (r: PackageSearchQuery) => r.searchScore >= best * NPM_RUNNER_UP_SHARE ) const model = getCurrentModel() diff --git a/frontend/src/lib/components/copilot/chat/shared.test.ts b/frontend/src/lib/components/copilot/chat/shared.test.ts index 88a5efb7c5..12b0912796 100644 --- a/frontend/src/lib/components/copilot/chat/shared.test.ts +++ b/frontend/src/lib/components/copilot/chat/shared.test.ts @@ -2251,152 +2251,6 @@ describe('getHubIntegrationTool', () => { expect(getHubIntegrationTool.planModeSafe).toBe(true) expect(createSearchHubScriptsTool().planModeSafe).toBe(true) }) - - const doc = { - app: 'confluence', - display_name: 'Confluence', - // Authored knowledge, but nobody has asserted whether the script set was pruned. - curated: null, - metadata_source: 'curated', - meta: { gotchas: ['Auth is Basic with an API token, not the password'] }, - derived: { - api_hosts: [{ host: 'api.atlassian.com', count: 12 }], - style: 'fetch', - languages: { bun: 14 }, - script_counts: { total: 14, by_kind: { script: 13 } }, - top_scripts: [ - { path: 'hub/1/confluence/create_page', summary: 'Create page', language: 'bun' } - ] - }, - resource_types: [{ name: 'confluence', schema: { type: 'object' } }] - } - - // Hand-validated provider knowledge and facts inferred from script bodies must - // stay under separate keys, or the model will report guesses as verified. - it('keeps authored notes apart from what was inferred from the scripts', async () => { - const { IntegrationService } = await import('$lib/gen') - Object.assign(IntegrationService, { getHubIntegrationMeta: vi.fn(async () => doc) }) - - const { getHubIntegrationTool } = await import('./shared') - const parsed = JSON.parse( - await getHubIntegrationTool.fn({ - args: { integration: 'confluence' }, - toolId: 't1', - toolCallbacks: { setToolStatus: vi.fn() } - } as any) - ) - - expect(parsed.verified_provider_notes).toEqual(doc.meta) - expect(parsed.scripts_note).toBeUndefined() - expect(parsed.observed_from_scripts).toEqual({ - api_hosts: ['api.atlassian.com'], - style: 'fetch', - languages: ['bun'], - script_counts: { total: 14, by_kind: { script: 13 } } - }) - }) - - // The hub repo owns this payload, so a hub older than this client can send a - // subset. Reading it must degrade to less content, never to a tool error. - it('returns what an older hub sent instead of failing on the missing sections', async () => { - const { IntegrationService } = await import('$lib/gen') - Object.assign(IntegrationService, { - getHubIntegrationMeta: vi.fn(async () => ({ - app: 'stripe', - display_name: 'Stripe', - curated: false - })) - }) - - const { getHubIntegrationTool } = await import('./shared') - const parsed = JSON.parse( - await getHubIntegrationTool.fn({ - args: { integration: 'stripe' }, - toolId: 't1', - toolCallbacks: { setToolStatus: vi.fn() } - } as any) - ) - - expect(parsed.integration).toBe('stripe') - expect(parsed.observed_from_scripts).toBeUndefined() - expect(parsed.resource_types).toEqual([]) - expect(parsed.example_scripts).toEqual([]) - }) - - // `curated` has three states and only `true` is a licence to call the scripts good - // examples. `false` and the unassessed `null` must both stay silent, or the 212 - // integrations nobody has looked at get characterised anyway. - it.each([ - [true, true], - [false, false], - [null, false] - ])('speaks about the script set only when curated is true (%s)', async (curated, expected) => { - const { IntegrationService } = await import('$lib/gen') - Object.assign(IntegrationService, { - getHubIntegrationMeta: vi.fn(async () => ({ ...doc, curated })) - }) - - const { getHubIntegrationTool } = await import('./shared') - const parsed = JSON.parse( - await getHubIntegrationTool.fn({ - args: { integration: 'confluence' }, - toolId: 't1', - toolCallbacks: { setToolStatus: vi.fn() } - } as any) - ) - - expect(!!parsed.scripts_note).toBe(expected) - }) - - // A hub that times out has said nothing about whether the integration exists, and - // reporting it as absent would stick for the rest of the conversation. - it('does not report a transient hub failure as a missing integration', async () => { - const { IntegrationService } = await import('$lib/gen') - Object.assign(IntegrationService, { - getHubIntegrationMeta: vi.fn(async () => { - throw Object.assign(new Error('Service Unavailable'), { status: 503 }) - }), - listHubIntegrations: vi.fn(async () => [{ name: 'confluence' }]) - }) - - const { getHubIntegrationTool, clearHubIntegrationsCache } = await import('./shared') - clearHubIntegrationsCache() - const parsed = JSON.parse( - await getHubIntegrationTool.fn({ - args: { integration: 'confluence' }, - toolId: 't1', - toolCallbacks: { setToolStatus: vi.fn() } - } as any) - ) - - expect(parsed.error).toContain('Could not reach the hub') - expect(parsed.error).not.toContain('No hub metadata') - }) - - // A hub with no such integration and one too old to serve the endpoint both 404; - // neither may surface as a tool error, since the model can still read scripts. - it('suggests real slugs instead of failing when the integration is unknown', async () => { - const { IntegrationService } = await import('$lib/gen') - Object.assign(IntegrationService, { - getHubIntegrationMeta: vi.fn(async () => { - throw Object.assign(new Error('Not Found'), { status: 404 }) - }), - listHubIntegrations: vi.fn(async () => [{ name: 'stripe' }, { name: 'slack' }]) - }) - - const { getHubIntegrationTool, clearHubIntegrationsCache } = await import('./shared') - clearHubIntegrationsCache() - const parsed = JSON.parse( - await getHubIntegrationTool.fn({ - args: { integration: 'stripe_billing' }, - toolId: 't1', - toolCallbacks: { setToolStatus: vi.fn() } - } as any) - ) - - expect(parsed.error).toContain('stripe_billing') - expect(parsed.suggested_integrations).toEqual(['stripe']) - }) }) describe('processToolCall confirmation hooks', () => { diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index 55c63f3718..0e9fd516a6 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -78,6 +78,7 @@ import { import type { editor as meditor } from 'monaco-editor' import { pendingFolderInstructions, type FolderInstructionsContext } from './folderInstructions' import type { WebSearchSource } from './webSearchResult' +import { runOnServer } from './global/backendSessionTools' // Prettify function for code arguments - extracts and formats code from JSON function prettifyCodeArguments(content: string): string { @@ -471,6 +472,11 @@ export function buildContextString(selectedContext: ContextElement[]): string { workspaceItemsContext = 'SELECTED WORKSPACE ITEMS:\n' } workspaceItemsContext += `- type: ${isUserContextPath(context.path) ? 'user' : 'folder'}, path: ${context.path}\n` + } else if (context.type === 'workspace_run') { + if (!workspaceItemsContext) { + workspaceItemsContext = 'SELECTED WORKSPACE ITEMS:\n' + } + workspaceItemsContext += `- type: run, id: ${context.id}, of: ${context.path}\n` } } @@ -1699,7 +1705,7 @@ function hasOptionalProperties(schema: Record | undefined): boolean return false } -const searchHubScriptsSchema = z.object({ +export const searchHubScriptsSchema = z.object({ query: z .string() .optional() @@ -1856,41 +1862,6 @@ const getHubIntegrationToolDef = createToolDef( '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.' ) -/** Enough to show the integration's idiom; search_hub_scripts is the way to find - * a specific one. */ -const MAX_INTEGRATION_EXAMPLES = 5 - -/** How the authored notes were checked — method, per-surface confidence, the instance - * used — is provenance for a human reviewing the hub, and up to a third of the - * document. The verdict and any fields it flags as shaky are the parts a caller can - * act on, so those stay. */ -function withoutProvenance(meta: unknown): unknown { - if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) { - return meta - } - const { validation, ...rest } = meta as Record - const kept = Object.fromEntries( - Object.entries((validation as Record | undefined) ?? {}).filter( - ([key]) => key === 'status' || key === 'low_confidence_fields' - ) - ) - return Object.keys(kept).length ? { ...rest, validation: kept } : rest -} - -/** The hub keeps a resource type's schema in a text column and hands it back as a - * JSON string, so parse it rather than passing an escaped blob to the model. - * Anything already structured goes through untouched. */ -function parseResourceTypeSchema(schema: unknown): unknown { - if (typeof schema !== 'string') { - return schema - } - try { - return JSON.parse(schema) - } catch { - return schema - } -} - export const HUB_SYNC_INSTRUCTIONS = 'Tell the user: no resource of a missing type can be created until a superadmin syncs resource types from the hub, with "Sync resource types with Hub" in the Add resource dialog of the Resources page.' @@ -1899,76 +1870,20 @@ export const getHubIntegrationTool = { def: getHubIntegrationToolDef, // Reads one hub document over a GET and writes nothing, so planning may use it. planModeSafe: true, - fn: async ({ args, toolId, toolCallbacks }) => { + fn: async ({ args, workspace, toolId, toolCallbacks }) => { const { integration } = getHubIntegrationSchema.parse(args) toolCallbacks.setToolStatus(toolId, { content: `Reading the ${integration} integration...` }) - - let doc: Awaited> - try { - doc = await IntegrationService.getHubIntegrationMeta({ app: integration }) - } catch (err) { - // Only a 404 means the integration is absent — an unknown slug, or a hub - // predating the endpoint. Reporting a timeout the same way would teach the - // model that a real integration does not exist for the rest of the chat. - const absent = (err as { status?: number } | undefined)?.status === 404 - const label = absent - ? `No hub integration named ${integration}` - : `Could not reach the hub for ${integration}` - toolCallbacks.setToolStatus(toolId, { content: label }) - const suggested = await suggestHubIntegrations(integration) - return JSON.stringify({ - error: absent - ? `No hub metadata for "${integration}".` - : `Could not reach the hub for "${integration}"; it may still exist. Read its scripts instead, or try again.`, - suggested_integrations: suggested - }) - } - - toolCallbacks.setToolStatus(toolId, { content: `Read the ${doc.display_name} integration` }) - // The hub owns this response's shape and can be older than this client, so - // every section is read as optional: a hub that sends less should return less, - // not fail the call. - const derived = doc.derived - return JSON.stringify({ - integration: doc.app, - display_name: doc.display_name, - ...(doc.description ? { description: doc.description } : {}), - ...(doc.docs_url ? { docs_url: doc.docs_url } : {}), - // Authored provider knowledge and facts inferred from the scripts stay - // separate: only the former was checked against the live API. - ...(doc.meta ? { verified_provider_notes: withoutProvenance(doc.meta) } : {}), - ...(derived - ? { - observed_from_scripts: { - api_hosts: derived.api_hosts?.map((h) => h.host) ?? [], - style: derived.style, - languages: Object.keys(derived.languages ?? {}), - script_counts: derived.script_counts - } - } - : {}), - // `curated` is three-state: only an integration's own meta.json asserts it, and - // anything else means nobody has assessed the script set. Speak only for a - // positive assertion, so an unassessed integration is never characterised - // either way; `script_counts` below is the factual signal for the rest. - ...(doc.curated === true - ? { - scripts_note: - 'These scripts were pruned to idiomatic actions rather than generated one per API endpoint, so they are worth following as style examples.' - } - : {}), - resource_types: (doc.resource_types ?? []).map((rt) => ({ - name: rt.name, - ...(rt.description ? { description: rt.description } : {}), - schema: parseResourceTypeSchema(rt.schema) - })), - example_scripts: (derived?.top_scripts ?? []).slice(0, MAX_INTEGRATION_EXAMPLES).map((s) => ({ - path: s.path, - summary: s.summary, - ...(s.description ? { description: s.description } : {}), - ...(s.language ? { language: s.language } : {}) - })) + const { text } = await runOnServer('get_hub_integration', workspace, args) + const doc = JSON.parse(text) + toolCallbacks.setToolStatus(toolId, { + content: + doc.error === undefined + ? `Read the ${doc.display_name} integration` + : doc.error.startsWith('No hub metadata') + ? `No hub integration named ${integration}` + : `Could not reach the hub for ${integration}` }) + return text } } satisfies SessionTool<{}> @@ -2687,6 +2602,18 @@ async function loadDeployedScriptForFlowStep( } } +/** What a test run of an AI decision step supplies: the state. The provider and questions + * are the step's own. */ +export function decisionStepRunSchema(): Record { + return { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties: { state: AI_DECISION_SCHEMA.properties.state }, + required: ['state'], + order: ['state'] + } +} + export async function resolveFlowStepRun({ flowValue, stepId, @@ -2828,14 +2755,7 @@ export async function resolveFlowStepRun({ // Run alone as a one-step flow preview, as the editor's step test does: the inputs given here // override the step's own, so a state that reads an earlier step can be passed directly. runnableKind: 'flow', - // What a run supplies: the state. The provider and questions are the step's own. - schema: { - $schema: 'https://json-schema.org/draft/2020-12/schema', - type: 'object', - properties: { state: AI_DECISION_SCHEMA.properties.state }, - required: ['state'], - order: ['state'] - }, + schema: decisionStepRunSchema(), startMessage: `Starting test run of AI decision step "${stepId}"...`, startJob: async (args) => JobService.runFlowPreview({ diff --git a/frontend/src/lib/components/copilot/chat/sharedChatState.svelte.ts b/frontend/src/lib/components/copilot/chat/sharedChatState.svelte.ts index 330ee95c7d..0e68b6178d 100644 --- a/frontend/src/lib/components/copilot/chat/sharedChatState.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/sharedChatState.svelte.ts @@ -1,5 +1,3 @@ -import { BROWSER } from 'esm-env' - export const triggerablesByAi = $state({}) export type TriggerablesMap = Record< @@ -9,19 +7,3 @@ export type TriggerablesMap = Record< onTrigger: ((value?: string) => void) | undefined } > -export const DEFAULT_SIZE = 22 - -type ChatState = { - size: number - // Whether a docked chat pane is mounted (set by AiChatLayout). False in AI - // Sessions mode, where the root layout renders no pane: aiChatManager.openChat() - // only writes `size`, so a button that opens the pane without checking this is a - // silent no-op. Entry points that can't fall back to a session must hide instead. - dockedChatAvailable: boolean -} - -// we first check BROWSER before localStorage to avoid SSR issues when using Drawer in a SvelteKit app (chatState is imported in Drawer.svelte) -export const chatState = $state({ - size: BROWSER && localStorage.getItem('ai-chat-open') === 'true' ? DEFAULT_SIZE : 0, - dockedChatAvailable: false -}) diff --git a/frontend/src/lib/components/copilot/lib.ts b/frontend/src/lib/components/copilot/lib.ts index 299765605e..9f9fd460ba 100644 --- a/frontend/src/lib/components/copilot/lib.ts +++ b/frontend/src/lib/components/copilot/lib.ts @@ -60,149 +60,18 @@ import { getReasoningContentDelta } from './chat/openaiReasoning' import { parseFimCompletionChoice } from './fim' +import { aiClientWorkspace, setAiClientWorkspace } from './aiClientWorkspace' +import { AI_PROVIDERS, DECISION_AI_PROVIDERS, type ChatAIProvider } from './aiProviders' export const SUPPORTED_LANGUAGES = new Set(Object.keys(GEN_CONFIG.prompts)) -interface AIProviderDetails { - label: string - defaultModels: string[] -} - -// The first entry is what a new workspace is created with (see -// CreateWorkspaceInner), so each list leads with the balanced tier rather than -// the frontier model. The gpt-5 family is deprecated (retires 2026-12-11) but -// still served, so it stays in the list below the 5.6 models. -const OPENAI_MODELS = [ - 'gpt-6.1-sol', - 'gpt-6-sol', - 'gpt-6-astra', - 'gpt-6-luna', - 'gpt-5.6-terra', - 'gpt-5.6-sol', - 'gpt-5.6-luna', - 'gpt-5', - 'gpt-5-mini', - 'gpt-4o', - 'gpt-4o-mini', - 'o4-mini', - 'o3' -] - -/** The providers that chat. Every surface picking a model to talk to (the copilot, flow chat, an - * agent's text or image output, eval judges) offers exactly these. */ -export type ChatAIProvider = Exclude - -export const AI_PROVIDERS: Record = { - openai: { - label: 'OpenAI', - defaultModels: OPENAI_MODELS - }, - anthropic: { - label: 'Anthropic', - defaultModels: [ - 'claude-sonnet-5-5', - 'claude-opus-5-5', - 'claude-sonnet-5', - 'claude-opus-5', - 'claude-opus-4-8', - 'claude-haiku-4-5' - ] - }, - googleai: { - label: 'Google AI', - defaultModels: [ - 'gemini-3.6-flash', - 'gemini-3.5-flash', - 'gemini-3.1-pro-preview', - 'gemini-3.5-flash-lite', - 'gemini-3.1-flash-lite', - 'gemini-2.5-pro', - 'gemini-2.5-flash' - ] - }, - azure_openai: { - label: 'Azure OpenAI', - defaultModels: OPENAI_MODELS - }, - azure_foundry: { - label: 'Azure AI Foundry', - defaultModels: [ - 'gpt-5.6-terra', - 'gpt-5.6-sol', - 'claude-sonnet-5', - 'claude-opus-5', - 'DeepSeek-V4-Pro', - 'Llama-3.3-70B-Instruct', - 'Phi-4' - ] - }, - mistral: { - label: 'Mistral', - defaultModels: ['mistral-medium-latest', 'codestral-latest'] - }, - deepseek: { - label: 'DeepSeek', - defaultModels: ['deepseek-v4-pro', 'deepseek-flash'] - }, - groq: { - label: 'Groq', - defaultModels: ['openai/gpt-oss-120b', 'openai/gpt-oss-20b'] - }, - openrouter: { - label: 'OpenRouter', - defaultModels: ['meta-llama/llama-3.2-3b-instruct:free'] - }, - togetherai: { - label: 'Together AI', - defaultModels: ['meta-llama/Llama-3.3-70B-Instruct-Turbo'] - }, - aws_bedrock: { - label: 'AWS Bedrock', - defaultModels: [ - 'global.anthropic.claude-sonnet-5', - 'global.anthropic.claude-opus-5', - 'global.anthropic.claude-haiku-4-5-20251001-v1:0' - ] - }, - customai: { - label: 'Custom AI', - defaultModels: [] - } -} - -/** Decision models answer typed questions instead of messages, so only an AI decision offers - * them: TypeSafe's Jev, Cloudflare's Jev-compatible Clef, and the model of OpenAI's Decisions - * API, which an OpenAI resource serves next to its chat models. The pinned Jev version is there - * for flows tuned against its probabilities. */ -export const DECISION_AI_PROVIDERS: Record< - Exclude | 'openai', - AIProviderDetails -> = { - openai: { - label: 'OpenAI', - defaultModels: ['gpt-6-luna'] - }, - typesafe: { - label: 'TypeSafe', - defaultModels: ['jev-latest', 'jev-1.13.0'] - }, - cloudflare: { - label: 'Cloudflare', - defaultModels: ['clef', 'clef-flash'] - } -} - -/** Label and default models of any provider kind, chat or decision. A kind in neither list (a flow - * written by hand or by a newer version) is named as it is and offers no models. */ -export function aiProviderDetails(provider: AIProvider): AIProviderDetails { - return ( - (AI_PROVIDERS as Record)[provider] ?? - (DECISION_AI_PROVIDERS as Record)[provider] ?? { - label: provider, - defaultModels: [] - } - ) -} +export { + AI_PROVIDERS, + DECISION_AI_PROVIDERS, + aiProviderDetails, + type AIProviderDetails, + type ChatAIProvider +} from './aiProviders' export interface ModelResponse { id: string @@ -595,12 +464,11 @@ export function createAnthropicProxyClient(baseURL: string): Anthropic { } class WorkspacedAIClients { - private openaiClient: OpenAI | undefined - private anthropicClient: Anthropic | undefined + private openaiClient: { client: OpenAI; generation: number } | undefined + private anthropicClient: { client: Anthropic; generation: number } | undefined init(workspace: string) { - this.openaiClient = this.createOpenaiClient(workspace) - this.anthropicClient = this.createAnthropicClient(workspace) + setAiClientWorkspace(workspace) } createOpenaiClient(workspace: string): OpenAI { @@ -611,18 +479,26 @@ class WorkspacedAIClients { return createAnthropicProxyClient(getAiProxyBaseURL(workspace)) } - getOpenaiClient() { - if (!this.openaiClient) { + getOpenaiClient(): OpenAI { + const { workspace, generation } = aiClientWorkspace() + if (!workspace) { throw new Error('OpenAI not initialized') } - return this.openaiClient + if (this.openaiClient?.generation !== generation) { + this.openaiClient = { client: this.createOpenaiClient(workspace), generation } + } + return this.openaiClient.client } - getAnthropicClient() { - if (!this.anthropicClient) { + getAnthropicClient(): Anthropic { + const { workspace, generation } = aiClientWorkspace() + if (!workspace) { throw new Error('Anthropic not initialized') } - return this.anthropicClient + if (this.anthropicClient?.generation !== generation) { + this.anthropicClient = { client: this.createAnthropicClient(workspace), generation } + } + return this.anthropicClient.client } } diff --git a/frontend/src/lib/components/copilot/loadCopilot.test.ts b/frontend/src/lib/components/copilot/loadCopilot.test.ts index f255295afc..5bfcf1f547 100644 --- a/frontend/src/lib/components/copilot/loadCopilot.test.ts +++ b/frontend/src/lib/components/copilot/loadCopilot.test.ts @@ -1,10 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { get } from 'svelte/store' -vi.mock('./lib', () => ({ - workspaceAIClients: { init: () => {} } -})) - let requests: { workspace: string; resolve: (config: any) => void }[] = [] vi.mock('$lib/gen', () => ({ diff --git a/frontend/src/lib/components/copilot/loadCopilot.ts b/frontend/src/lib/components/copilot/loadCopilot.ts index 496fb89fdc..4b1e53a686 100644 --- a/frontend/src/lib/components/copilot/loadCopilot.ts +++ b/frontend/src/lib/components/copilot/loadCopilot.ts @@ -1,6 +1,6 @@ import { WorkspaceService } from '$lib/gen' import { copilotWorkspace, setCopilotInfo } from '$lib/aiStore' -import { workspaceAIClients } from './lib' +import { setAiClientWorkspace } from './aiClientWorkspace' import { writable } from 'svelte/store' // The workspace of the most recent loadCopilot *request*, set synchronously before the @@ -42,7 +42,7 @@ export function loadCopilot(workspace: string): Promise { } async function fetchAndApply(workspace: string, token: number) { - workspaceAIClients.init(workspace) + setAiClientWorkspace(workspace) try { const info = await WorkspaceService.getCopilotInfo({ workspace }) if (token !== loadCopilotToken) return diff --git a/frontend/src/lib/components/debug/debugUtils.ts b/frontend/src/lib/components/debug/debugUtils.ts index d58fb23983..b9b9c9b174 100644 --- a/frontend/src/lib/components/debug/debugUtils.ts +++ b/frontend/src/lib/components/debug/debugUtils.ts @@ -80,11 +80,26 @@ export async function signDebugRequest( * multiplayer server will verify before accepting the WebSocket connection. */ export async function signMultiplayerRequest(workspace: string): Promise { + return signSessionRequest(workspace, 'sign_multiplayer') +} + +/** + * Sign a language server session request. Returns a short-lived JWT token that + * the windmill_extra gateway verifies before accepting the WebSocket connection. + */ +export async function signLspRequest(workspace: string): Promise { + return signSessionRequest(workspace, 'sign_lsp') +} + +async function signSessionRequest( + workspace: string, + endpoint: 'sign_multiplayer' | 'sign_lsp' +): Promise { if (!workspace) { throw new Error('No workspace selected') } - const response = await fetch(`/api/w/${workspace}/debug/sign_multiplayer`, { + const response = await fetch(`/api/w/${workspace}/debug/${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) @@ -92,7 +107,7 @@ export async function signMultiplayerRequest(workspace: string): Promise if (!response.ok) { const errorText = await response.text() - throw new Error(errorText || 'Failed to sign multiplayer session') + throw new Error(errorText || `Failed to sign session (${endpoint})`) } const data: { token: string } = await response.json() diff --git a/frontend/src/lib/components/flows/FlowEditor.svelte b/frontend/src/lib/components/flows/FlowEditor.svelte index f735d1579b..39c99f38cb 100644 --- a/frontend/src/lib/components/flows/FlowEditor.svelte +++ b/frontend/src/lib/components/flows/FlowEditor.svelte @@ -38,13 +38,10 @@ import { Button } from '../common' import { MousePointerClick, X } from 'lucide-svelte' import FlowPanelPlacementPicker from './common/FlowPanelPlacementPicker.svelte' - import { prefersSessionHandoff } from '../copilot/chat/global/gate' import { openSourceInSession } from '$lib/components/sessions/sessionSwitch.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() - const roleCaps = useRoleCapabilities() const { flowStore, selectionManager, pathStore, opWorkspace } = getContext('FlowEditorContext') // Flow paths repeat across workspaces, and a session keeps every tab it has visited alive, so two @@ -76,9 +73,7 @@ onEditInput?: ((moduleId: string, key: string) => void) | undefined forceTestTab?: Record highlightArg?: Record - aiChatOpen?: boolean showFlowAiButton?: boolean - toggleAiChat?: () => void sessionOpen?: OpenInSessionSource localModuleStates?: Record testModuleStates?: ModulesTestStates @@ -117,9 +112,7 @@ highlightArg, localModuleStates = {}, testModuleStates = undefined, - aiChatOpen, showFlowAiButton, - toggleAiChat, sessionOpen, isOwner, onTestFlow, @@ -301,8 +294,8 @@ aiChatManager.flowOptions = options }) - // The step exists but is empty, so name it: a GLOBAL-mode request carries no - // implicit "current step" the way the old SCRIPT-mode generateStep did. + // The step exists but is empty, so name it: a GLOBAL-mode request carries no implicit + // "current step". function stepInstructionsPrompt(moduleId: string, instructions: string): string { return `Write the code for step \`${moduleId}\` of the flow open in the editor:\n\n${instructions}` } @@ -402,10 +395,9 @@ on:reload on:generateStep={({ detail }) => { // The step is already inserted; the prompt describes what it should - // contain. Hand it to a session opened on that step rather than the - // docked chat, which sessions leave unmounted. Sent on arrival: the + // contain. Hand it to a session opened on that step. Sent on arrival: the // user already said what they wanted in the description field. - if (!sessionScopedManager && sessionOpen && prefersSessionHandoff(!$roleCaps.code)) { + if (!sessionScopedManager && sessionOpen) { void openSourceInSession(sessionOpen, { previewParams: { selected: detail.moduleId }, seedPrompt: stepInstructionsPrompt(detail.moduleId, detail.instructions), @@ -417,24 +409,15 @@ // Not `generateStep` — that forces the request into SCRIPT mode, and // changeMode is persistent, so it would strand the session outside // GLOBAL. Global mode writes step code through set_flow_module_code. - if (sessionScopedManager) { - sessionScopedManager.sendOrQueue( - stepInstructionsPrompt(detail.moduleId, detail.instructions) - ) - return - } - if (!aiChatManager.open) { - aiChatManager.openChat() - } - aiChatManager.generateStep(detail.moduleId, detail.lang, detail.instructions) + sessionScopedManager?.sendOrQueue( + stepInstructionsPrompt(detail.moduleId, detail.instructions) + ) }} {onTestUpTo} {onEditInput} {localModuleStates} {testModuleStates} - {aiChatOpen} {showFlowAiButton} - {toggleAiChat} {sessionOpen} {isOwner} {onTestFlow} diff --git a/frontend/src/lib/components/flows/linkedAgentDrafts.ts b/frontend/src/lib/components/flows/linkedAgentDrafts.ts index 1a5b7ac7f1..0031353098 100644 --- a/frontend/src/lib/components/flows/linkedAgentDrafts.ts +++ b/frontend/src/lib/components/flows/linkedAgentDrafts.ts @@ -78,17 +78,15 @@ export function agentDraftState( export class AgentDraftUnavailable extends Error {} /** - * An agent's resource together with the draft a run of it would use. + * Land the agent editor's pending save of `path`, or refuse: a read of the stored draft would + * otherwise be older than the edit still held in the browser. * - * The flush is what makes the answer current. Autosave is debounced by 1.5s (10s ceiling), and + * The flush is what makes the stored row current. Autosave is debounced by 1.5s (10s ceiling), and * closing the agent editor releases the in-memory cell without cancelling that pending POST — so * testing or deploying right after closing would otherwise read a row the last edits have not * reached yet. `flush` replays the parked save and is a no-op when there is none. */ -export async function fetchAgentWithDraft( - path: string, - workspace: string -): Promise<{ response: Resource; draft: AgentResourceState | undefined }> { +export async function settleAgentDraft(path: string, workspace: string): Promise { const query = { workspace, itemKind: 'resource' as const, path } await UserDraftDbSyncer.flush(query) // `flush` resolves whether or not the save actually landed: `postSave` catches network and @@ -106,6 +104,14 @@ export async function fetchAgentWithDraft( `The unsaved changes to ${path} could not be saved because it was edited elsewhere. Open the agent to resolve it.` ) } +} + +/** An agent's resource together with the draft a run of it would use, its pending save landed. */ +export async function fetchAgentWithDraft( + path: string, + workspace: string +): Promise<{ response: Resource; draft: AgentResourceState | undefined }> { + await settleAgentDraft(path, workspace) const response = await ResourceService.getResource({ workspace, path, getDraft: true }) return { response, draft: agentDraftState(response, path, workspace) } } diff --git a/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte b/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte index fbf8879c53..d1e3e0f6f9 100644 --- a/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte +++ b/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte @@ -64,9 +64,7 @@ onEditInput?: (moduleId: string, key: string) => void localModuleStates?: Record testModuleStates?: ModulesTestStates - aiChatOpen?: boolean showFlowAiButton?: boolean - toggleAiChat?: () => void sessionOpen?: OpenInSessionSource isOwner?: boolean onTestFlow?: () => void @@ -94,9 +92,7 @@ onEditInput, localModuleStates = {}, testModuleStates = new ModulesTestStates(), - aiChatOpen, showFlowAiButton, - toggleAiChat, sessionOpen, isOwner, onTestFlow, @@ -503,8 +499,6 @@ {disableStaticInputs} {smallErrorHandler} on:generateStep - {aiChatOpen} - {toggleAiChat} {sessionOpen} {noteMode} {toggleNoteMode} diff --git a/frontend/src/lib/components/flows/map/FlowStickyNode.svelte b/frontend/src/lib/components/flows/map/FlowStickyNode.svelte index 1d5c1d2fe1..9ba1105232 100644 --- a/frontend/src/lib/components/flows/map/FlowStickyNode.svelte +++ b/frontend/src/lib/components/flows/map/FlowStickyNode.svelte @@ -5,10 +5,8 @@ import { Badge } from '$lib/components/common' import { DollarSign, Settings, StickyNote } from 'lucide-svelte' import FlowErrorHandlerItem from './FlowErrorHandlerItem.svelte' - import AIButton from '$lib/components/copilot/chat/AIButton.svelte' import Popover from '$lib/components/Popover.svelte' import Button from '$lib/components/common/button/Button.svelte' - import { AIBtnClasses } from '$lib/components/copilot/chat/AIButtonStyle' import OpenInSessionButton, { type OpenInSessionSource } from '$lib/components/sessions/OpenInSessionButton.svelte' @@ -17,9 +15,7 @@ disableSettings?: boolean disableStaticInputs?: boolean smallErrorHandler: boolean - aiChatOpen?: boolean showFlowAiButton?: boolean - toggleAiChat?: () => void sessionOpen?: OpenInSessionSource noteMode?: boolean toggleNoteMode?: () => void @@ -32,9 +28,7 @@ disableSettings, disableStaticInputs, smallErrorHandler, - aiChatOpen, showFlowAiButton, - toggleAiChat, sessionOpen, noteMode, toggleNoteMode, @@ -101,17 +95,7 @@ {/if} {#if showFlowAiButton} - - {#snippet fallback()} - { - toggleAiChat?.() - }} - btnClasses={AIBtnClasses(aiChatOpen ? 'selected' : 'default')} - /> - {/snippet} - + {/if} @@ -134,7 +146,7 @@ {/if} - {#if !sideTripsInBar || homeQuickAccessSettings.hidden} + {#if !sideTripsInBar || homeQuickAccessSettings.hidden || gatheredItems.length > 0} @@ -151,6 +163,7 @@ size="sm" customWidth={240} items={[ + ...gatheredItems, ...(homeQuickAccessSettings.hidden ? [ { @@ -164,7 +177,7 @@ : [ { displayName: 'CLI / MCP', - action: () => homeConnectDrawer?.openDrawer?.() + action: () => void openConnectDrawer() }, ...(hubOffered ? [ diff --git a/frontend/src/lib/components/home/HomeQuickAccess.svelte b/frontend/src/lib/components/home/HomeQuickAccess.svelte index 5bba8d1112..2604a282f2 100644 --- a/frontend/src/lib/components/home/HomeQuickAccess.svelte +++ b/frontend/src/lib/components/home/HomeQuickAccess.svelte @@ -1,3 +1,9 @@ + + + + + +
{ + if (e.key === 'Enter' && e.target === e.currentTarget) open() + }} +> + + {#if item.status === 'running'} + + {:else if failing} + + {:else if item.status === 'resolved'} + + {:else if item.status === 'canceled'} + + {:else} + + {/if} + + + + + {#if prefix}{prefix} / {/if}{title} + + + {item.path} + + {#if item.failed_runs > 0} + {item.failed_runs} failed + {#if onResolve && $roleCaps.code} + + + {/if} + {/if} + {#if failing && canAskAI() && latest} + + {/if} + + + + {#if canAskAI() && latest} + + + {/if} + + {#if strip} + + {#each slots as run, i (run?.id ?? `empty-${i}`)} + {#if run} + e.stopPropagation()} + > + {:else} + + {/if} + {/each} + + {/if} + + + + {latest ? shortAge(latest, now) : ''} + + {#if latest} + e.stopPropagation()} + > + Run ↗ + + {/if} + +
diff --git a/frontend/src/lib/components/home/RecentRunsHeaderStatus.svelte b/frontend/src/lib/components/home/RecentRunsHeaderStatus.svelte new file mode 100644 index 0000000000..c2f24df00b --- /dev/null +++ b/frontend/src/lib/components/home/RecentRunsHeaderStatus.svelte @@ -0,0 +1,188 @@ + + + +{#if data || onShowPanel} +
+ + {#snippet trigger()} + {#if compact} + + + {#if data} + + {/if} + + {:else} + {data ? totalLabel(data) : 'Recent runs'} + {#if !data && runs.loading} + + {/if} + {#if data && data.failed_runs > 0} + + + {data.failed_runs} failed + + {:else if data} + + + all good + + {/if} + {#if data && data.running_items > 0} + + + {data.running_items} running + + {/if} + + {/if} + {/snippet} + {#snippet content()} +
+ {#if data} +
+ + {windowLabel(data.window_hours)} + + + {totalLabel(data)} · + 0 ? 'text-red-600 dark:text-red-400' : ''}> + {data.failed_runs} failed + + + {#if canAskAI() && failing.length > 0} + + {/if} +
+ + + {#each data.items.slice(0, MAX_ITEMS) as item (itemKey(item))} + { + isOpen = false + onFocusItem(item) + })} + /> + {:else} +

+ Runs show up here once something runs. +

+ {/each} + {#if data.items.length > MAX_ITEMS} + + {data.items.length - MAX_ITEMS} more + + {/if} + {:else if runs.loading} + + {:else if runs.failed} +

+ Could not load recent runs. + +

+ {/if} + +
+ + All runs + + + {#if onShowPanel} +
+ +
+ {/if} +
+
+ {/snippet} +
+
+{/if} diff --git a/frontend/src/lib/components/home/RecentRunsPanel.svelte b/frontend/src/lib/components/home/RecentRunsPanel.svelte new file mode 100644 index 0000000000..270be61085 --- /dev/null +++ b/frontend/src/lib/components/home/RecentRunsPanel.svelte @@ -0,0 +1,117 @@ + + +
+
+

+ Recently run + {#if folder} + in {folder} + {/if} + {#if data} + + {#if data.failed_runs > 0} + + {data.failed_runs} failed + {#if canAskAI() && failing.length > 0} + + {/if} + + {:else} + {totalLabel(data)} + {/if} + + · {windowText} + + {/if} +

+ + All runs + + +
+ +
+ {#if !data && runs.loading} + + {:else if !data && runs.failed} +

+ Could not load recent runs. + +

+ {:else if data && data.items.length === 0} +

Runs show up here once something runs.

+ {:else if data} + +
+ {#each data.items as item (itemKey(item))} + + {/each} +
+ {/if} +
+
diff --git a/frontend/src/lib/components/home/homeHeaderMenu.svelte.ts b/frontend/src/lib/components/home/homeHeaderMenu.svelte.ts new file mode 100644 index 0000000000..80b23eda76 --- /dev/null +++ b/frontend/src/lib/components/home/homeHeaderMenu.svelte.ts @@ -0,0 +1,64 @@ +import type { Item } from '$lib/utils' +import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' + +/** Home's header actions fold through two levels once the breadcrumb has given all it can: at + * the first the runs status shrinks to an icon, at the second every action joins the ⋮ menu. */ +export const HOME_ACTION_FOLDS = 2 + +/** Bar width from which the fork badges say what they count. Below it they keep the icon and the + * number, which is the part a reader scans for; the tooltip names them either way. */ +const BAR_FITS_COUNT_LABELS = 1280 +/** Bar width from which CLI / MCP and the hub stand in the bar rather than in the ⋮ menu. Home's + * trail is ~250px and the rest of its actions ~400, so this leaves room for both labelled + * buttons without the trail starting to truncate. */ +const BAR_FITS_SIDE_TRIPS = 1024 + +export function homeCountLabels(): boolean { + return pageHeader.barWidth >= BAR_FITS_COUNT_LABELS +} + +export function homeSideTripsInBar(): boolean { + return pageHeader.barWidth >= BAR_FITS_SIDE_TRIPS && !homeActionsGathered() +} + +/** The actions change width at these two widths on their own, not through a fold: the bar has to + * measure its fold levels afresh when one flips, or it keeps folding by the wider row. */ +export function homeActionsVersion(): string { + return `${homeCountLabels()}:${pageHeader.barWidth >= BAR_FITS_SIDE_TRIPS}:${renderers > 0}` +} + +export function homeActionsCompact(): boolean { + return pageHeader.actionFold >= 1 +} + +/** Only while the ⋮ menu (HomeAIChat) is mounted to hold them: without it, gathered actions would + * be nowhere on the page. */ +export function homeActionsGathered(): boolean { + return pageHeader.actionFold >= 2 && renderers > 0 +} + +let providers = $state<{ id: number; order: number; get: () => Item[] }[]>([]) +let nextId = 0 +let renderers = $state(0) + +/** The rows each of Home's header actions puts in the ⋮ menu once they are gathered there. */ +export const homeHeaderMenu = { + get items(): Item[] { + return [...providers].sort((a, b) => a.order - b.order).flatMap((p) => p.get()) + }, + /** Registers on mount and returns the id to release on destroy. `order` is the action's own + * `actionsOrder`, so the menu lists them as the bar does. */ + register(order: number, get: () => Item[]): number { + const id = nextId++ + providers = [...providers, { id, order, get }] + return id + }, + release(id: number) { + providers = providers.filter((p) => p.id !== id) + }, + /** Called by the menu that lists `items`, on mount; returns its release for destroy. */ + mountRenderer(): () => void { + renderers++ + return () => renderers-- + } +} diff --git a/frontend/src/lib/components/home/recentRuns.svelte.ts b/frontend/src/lib/components/home/recentRuns.svelte.ts new file mode 100644 index 0000000000..2e03e299da --- /dev/null +++ b/frontend/src/lib/components/home/recentRuns.svelte.ts @@ -0,0 +1,190 @@ +import { JobService, type ListRecentRunsResponse } from '$lib/gen' +import { getLocalSetting, MAX_RESOLUTION_BATCH, storeLocalSetting } from '$lib/utils' +import { sendUserToast } from '$lib/toast' +import { IsDocumentVisible, useInterval } from 'runed' +import { persistedResource } from '$lib/persistedResource.svelte' +import { homeComposerContext } from '$lib/components/sessions/homeComposerContext.svelte' +import { runContextElement } from '$lib/components/copilot/chat/context' + +export type RecentRuns = ListRecentRunsResponse +export type RecentRunItem = RecentRuns['items'][number] +export type RecentRun = RecentRunItem['runs'][number] +export type RecentRunStatus = RecentRun['status'] + +/** Home stays open in many tabs and each read can examine tens of thousands of completions, while + * the panel only shows ages to the minute: a tighter rate multiplies that load for nothing. */ +const REFRESH_MS = 30000 + +/** + * What ran recently in the workspace, read from `listRecentRuns`. The side panel and the header + * status read the same instance: the counts they show must never disagree. Nothing is read while + * `enabled` is false: each read scans the window's runs. + */ +export function useRecentRuns( + args: () => { workspace: string | undefined; folder?: string; enabled: boolean } +) { + // A refresh that fails (a backend restart) throws, which keeps what is on screen rather than + // surfacing an error every few seconds; a failed first load shows the cached runs, or nothing. + const runs = persistedResource( + args, + async ({ workspace, folder, enabled }) => + workspace && enabled ? await JobService.listRecentRuns({ workspace, folder }) : undefined, + { + name: 'recent_runs', + version: 2, + scope: ({ workspace, folder, enabled }) => + workspace && enabled ? { workspace, args: { folder } } : undefined + } + ) + // The rows' ages ("3m") are read against this, so they move on with each refresh. + let now = $state(Date.now()) + const visible = new IsDocumentVisible() + useInterval(REFRESH_MS, { + callback: () => { + if (!visible.current || !args().enabled) return + now = Date.now() + if (!runs.loading) runs.refetch() + } + }) + return { + get current() { + return runs.current + }, + /** A read is in flight; with no `current` yet, nothing is known about the window. */ + get loading() { + return runs.loading + }, + /** The latest read failed: with no `current`, the panel would otherwise read as empty. */ + get failed() { + return runs.error !== undefined + }, + retry() { + if (!runs.loading) runs.refetch() + }, + get now() { + return now + }, + /** Marks every unresolved failure of `item` in the window as resolved. */ + async resolveFailures(item: RecentRunItem) { + const { workspace, folder } = args() + if (!workspace) return + let resolved = 0 + try { + // Read on click, for this item only: the endpoint files each run under its item the + // way the row counts it, which a job listing cannot (a `singlestepflow` wraps a script + // or a flow). + const read = await JobService.listRecentRuns({ + workspace, + folder, + failedIdsKind: item.kind, + failedIdsPath: item.path + }) + const ids = + read.items.find((i) => i.kind === item.kind && i.path === item.path)?.failed_run_ids ?? [] + for (let i = 0; i < ids.length; i += MAX_RESOLUTION_BATCH) { + const affected = await JobService.resolveCompletedJobs({ + workspace, + requestBody: { job_ids: ids.slice(i, i + MAX_RESOLUTION_BATCH) } + }) + resolved += affected.length + } + sendUserToast(`Resolved ${resolved} failed run${resolved === 1 ? '' : 's'}`) + } catch (e) { + sendUserToast(`Could not resolve the failed runs: ${e}`, true) + } + runs.refetch() + } + } +} + +export type RecentRunsState = ReturnType + +const PANEL_OPEN_SETTING = 'wm-home-runs-open' + +export function usePanelOpen() { + let open = $state(getLocalSetting(PANEL_OPEN_SETTING) !== 'false') + return { + get val() { + return open + }, + set val(v: boolean) { + open = v + try { + storeLocalSetting(PANEL_OPEN_SETTING, v ? undefined : 'false') + } catch {} + } + } +} + +export function itemHref(item: Pick) { + const base = item.kind === 'flow' ? 'flows' : item.kind === 'agent' ? 'agents' : 'scripts' + return `/${base}/get/${item.path}` +} + +export function runHref(id: string, workspace: string | undefined) { + return `/run/${id}?workspace=${workspace ?? ''}` +} + +export function allRunsHref(folder: string | undefined) { + return folder ? `/runs?folder=${encodeURIComponent(folder)}` : '/runs' +} + +export function windowLabel(hours: number) { + return hours > 24 && hours % 24 === 0 ? `last ${hours / 24}d` : `last ${hours}h` +} + +/** `now`, `3m`, `2h`, `4d`; `running` while the newest run has not finished. */ +export function shortAge(run: RecentRun, now: number) { + if (run.status === 'running') return 'running' + const s = Math.max(0, (now - new Date(run.ran_at).getTime()) / 1000) + if (s < 60) return 'now' + if (s < 3600) return `${Math.floor(s / 60)}m` + if (s < 86400) return `${Math.floor(s / 3600)}h` + return `${Math.floor(s / 86400)}d` +} + +/** A script and a flow can share a path: an item is both. */ +export function itemKey(item: Pick) { + return `${item.kind}:${item.path}` +} + +export function itemTitle(item: Pick) { + return item.summary || item.path.split('/').pop() || item.path +} + +/** The folder (or user) to show before a title another listed item also carries. */ +export function collisionPrefixes(items: RecentRunItem[]): Map { + const byTitle = new Map() + for (const item of items) byTitle.set(itemTitle(item), (byTitle.get(itemTitle(item)) ?? 0) + 1) + const prefixes = new Map() + for (const item of items) { + if ((byTitle.get(itemTitle(item)) ?? 0) > 1) + prefixes.set(itemKey(item), item.path.split('/')[1]) + } + return prefixes +} + +export function totalLabel(runs: RecentRuns) { + return `${runs.total_runs}${runs.capped ? '+' : ''} runs` +} + +export type AskAIContext = + | { kind: 'failing'; items: RecentRunItem[] } + | { kind: 'run'; path: string; jobId: string } + +/** Whether Home's composer is there to take a run: it registers only once mounted. */ +export function canAskAI(): boolean { + return homeComposerContext.available +} + +/** Each run into Home's composer as context, `draft` before them: a failing item hands over its + * latest run, which is the one that failed. */ +export async function askAI(context: AskAIContext, draft?: string) { + const runs = + context.kind === 'run' + ? [{ path: context.path, jobId: context.jobId }] + : context.items.flatMap((i) => (i.runs[0] ? [{ path: i.path, jobId: i.runs[0].id }] : [])) + // Mentions land at the caret, so they go in first; `prefill` then puts the question ahead of them. + for (const run of runs) await homeComposerContext.attach(runContextElement(run.jobId, run.path)) + if (draft) homeComposerContext.prefill(`${draft} `) +} diff --git a/frontend/src/lib/components/icons/AristaIcon.svelte b/frontend/src/lib/components/icons/AristaIcon.svelte new file mode 100644 index 0000000000..9edd09de74 --- /dev/null +++ b/frontend/src/lib/components/icons/AristaIcon.svelte @@ -0,0 +1,24 @@ + + + + + + diff --git a/frontend/src/lib/components/icons/index.ts b/frontend/src/lib/components/icons/index.ts index 152ecd334e..a51aaee7fc 100644 --- a/frontend/src/lib/components/icons/index.ts +++ b/frontend/src/lib/components/icons/index.ts @@ -242,6 +242,7 @@ import SalesflareIcon from './SalesflareIcon.svelte' import PaylocityIcon from './PaylocityIcon.svelte' import KustomerIcon from './KustomerIcon.svelte' import NetBoxIcon from './NetBoxIcon.svelte' +import AristaIcon from './AristaIcon.svelte' import VmwareIcon from './VmwareIcon.svelte' import AbstractApiIcon from './AbstractApiIcon.svelte' import AcumbamailIcon from './AcumbamailIcon.svelte' @@ -621,6 +622,7 @@ export const APP_TO_ICON_COMPONENT = { paylocity: PaylocityIcon, kustomer: KustomerIcon, netbox: NetBoxIcon, + arista_eos: AristaIcon, vmware_vsphere: VmwareIcon, abstractapi: AbstractApiIcon, acumbamail: AcumbamailIcon, @@ -958,6 +960,7 @@ export { PaylocityIcon, KustomerIcon, NetBoxIcon, + AristaIcon, VmwareIcon, AbstractApiIcon, AcumbamailIcon, diff --git a/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte b/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte index 2f2145da9b..b65b7a6872 100644 --- a/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte +++ b/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte @@ -11,15 +11,10 @@ interface Props { hasUnsavedChanges?: boolean - disableChatOffset?: boolean showHubSync?: boolean } - let { - hasUnsavedChanges = $bindable(false), - disableChatOffset = false, - showHubSync = false - }: Props = $props() + let { hasUnsavedChanges = $bindable(false), showHubSync = false }: Props = $props() let initialConfig: AIConfig | undefined = $state(undefined) let loaded = $state(false) @@ -129,7 +124,6 @@ bind:hasUnsavedChanges {initialConfig} workspace="admins" - {disableChatOffset} title="Windmill AI" description="Windmill AI integrates with your favorite AI providers and models. Set your AI settings at the instance level to be able to use them on all your workspaces. Workspace-level settings can override these." link="https://www.windmill.dev/docs/core_concepts/ai_generation" diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 95ae18f9f4..148b476211 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -83,7 +83,6 @@ 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, @@ -2174,14 +2173,11 @@ addEventListener('message', function (e) { 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. + // Outside a session there is no 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) | undefined = $derived( - onInlinePrompt ?? - (!onInspectorSelect && sessionOpen && prefersSessionHandoff(!$roleCaps.code) - ? sendPickToNewSession - : undefined) + onInlinePrompt ?? (!onInspectorSelect && sessionOpen ? sendPickToNewSession : undefined) ) const inlinePromptSelector = $derived( inlinePrompt && previewSelectors.length > 0 diff --git a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte index 73e9bd1187..1a5b426378 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte @@ -34,8 +34,7 @@ Redo, Settings, Undo, - UserPlus, - WandSparkles + UserPlus } from 'lucide-svelte' import ShareDialog from '$lib/components/itemSettings/ShareDialog.svelte' import { showAppLinks } from '$lib/components/itemSettings/AppLinksModal.svelte' @@ -72,7 +71,6 @@ import { updateRawAppPolicy } from './rawAppPolicy' import { withoutSharedPolicySettings } from '../apps/editor/appDraftSettings' import { saveRawAppFork } from './forkRawApp.svelte' - import { aiChatManager } from '../copilot/chat/AIChatManager.svelte' import { getContext } from 'svelte' // Forward-looking hook for the upcoming session-pane feature: that PR will @@ -90,7 +88,6 @@ // session-side equivalent is RawAppEditorView's `onDeploy` → // `runtime.itemDeployed`, which discards the fork draft + reloads // the preview to the deployed version. - import { AIBtnClasses } from '../copilot/chat/AIButtonStyle' import { stripRawAppDiffNoise } from './utils' import type { RawAppData } from './dataTableRefUtils' import { editInForkAllowed, editInForkLabel, openEditInFork } from '$lib/utils/editInFork' @@ -378,11 +375,9 @@ ownsPageHeader ? pageHeader.actionFold >= 1 : topbarWidth > 0 && topbarWidth < 720 ) // 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. + // The second fold keeps the trail, the file sidebar's toggle and Deploy; Diff joins the menu, + // while Jobs and the export are already in it, 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. @@ -1329,24 +1324,8 @@ - - - {#snippet fallback()} - {#if !phoneTopbar} - - {/if} - {/snippet} - + + {#if offersSharing && !phoneTopbar} @@ -282,11 +281,8 @@ } }) - // 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 && (!composeOnlyApps || prefersSessionHandoff(!$roleCaps.code)) - ) + // With AI turned off for the workspace there is nothing to choose between. + const aiOffered = $derived(!$copilotInfo.workspaceDisabled) const canStart = $derived( !!templates[selectedTemplateIndex] && !newSchemaAlreadyExists && rolesSettled && accessSettled diff --git a/frontend/src/lib/components/resourceTypeDisplay.ts b/frontend/src/lib/components/resourceTypeDisplay.ts index ad01c05bb9..5fdd47b1a1 100644 --- a/frontend/src/lib/components/resourceTypeDisplay.ts +++ b/frontend/src/lib/components/resourceTypeDisplay.ts @@ -81,7 +81,7 @@ export function sortResourceTypesByMatch( * that carry a capital inside the word. Anything absent is capitalized, which is right for * the great majority of types (`stripe` -> `Stripe`). */ -const RESOURCE_TYPE_WORDS: Record = { +export const RESOURCE_TYPE_WORDS: Record = { ai: 'AI', ai21: 'AI21', amqp: 'AMQP', diff --git a/frontend/src/lib/components/runArgsCases.test.ts b/frontend/src/lib/components/runArgsCases.test.ts new file mode 100644 index 0000000000..2cbd3aab4e --- /dev/null +++ b/frontend/src/lib/components/runArgsCases.test.ts @@ -0,0 +1,67 @@ +// The MCP server settles a run's arguments in Rust (`ai_session_tools/runs.rs`), read against +// the same cases by `run_args_match_the_shared_cases`. +import { readFileSync } from 'node:fs' +import { describe, expect, it, vi } from 'vitest' + +const stored: string[] = [] + +vi.mock('$lib/gen', () => ({ + VariableService: { + createVariable: vi.fn(async ({ requestBody }: any) => { + stored.push(requestBody.value) + return requestBody.path + }) + } +})) + +vi.mock('$lib/stores', async () => { + const { writable } = await import('svelte/store') + return { workspaceStore: writable('test-ws'), userStore: writable({ username: 'ada' }) } +}) + +import { + dropUndeclaredArgs, + enforceDisabledDefaults, + redactFileArgs, + redactSecretArgs +} from './job_args' +import { processSecretArgs } from './secretArgUtils' + +const { cases } = JSON.parse( + readFileSync( + new URL( + '../../../../backend/windmill-api/src/ai_session_tools/run_args_cases.json', + import.meta.url + ), + 'utf8' + ) +) + +describe('run arguments, against the cases the server shares', () => { + for (const c of cases) { + it(c.name, async () => { + if (c.declared) { + const { args, undeclaredKeys } = dropUndeclaredArgs(c.args, c.schema) + expect(args).toEqual(c.declared.args) + expect(undeclaredKeys).toEqual(c.declared.undeclared) + } + if (c.disabled_defaults) { + const { args, resetKeys } = enforceDisabledDefaults(c.args, c.schema) + expect(args).toEqual(c.disabled_defaults.args) + expect(resetKeys).toEqual(c.disabled_defaults.reset) + } + if (c.secrets) { + stored.length = 0 + const out = await processSecretArgs(c.args, c.schema, 'test-ws') + const named = JSON.parse( + JSON.stringify(out).replace(/u\/ada\/secret_arg\/[A-Za-z0-9]+/g, '') + ) + expect(named).toEqual(c.secrets.args) + expect([...stored].sort()).toEqual(c.secrets.stored) + } + if (c.redacted) { + expect(redactFileArgs(redactSecretArgs(c.args, c.schema), c.schema)).toEqual(c.redacted) + } + }) + } +}) diff --git a/frontend/src/lib/components/runs/JobDetailHeader.svelte b/frontend/src/lib/components/runs/JobDetailHeader.svelte index e676bf609b..a2b19a54bf 100644 --- a/frontend/src/lib/components/runs/JobDetailHeader.svelte +++ b/frontend/src/lib/components/runs/JobDetailHeader.svelte @@ -14,7 +14,16 @@ import TimeAgo from '$lib/components/TimeAgo.svelte' import { enterpriseLicense, userStore } from '$lib/stores' import Tooltip from '$lib/components/meltComponents/Tooltip.svelte' - import { ExternalLink, ListFilter, ChevronDown, Share2, Link, Copy } from 'lucide-svelte' + import { + ExternalLink, + ListFilter, + ChevronDown, + Share2, + Link, + Copy, + CircleCheck, + Undo2 + } from 'lucide-svelte' import JobStatus from '$lib/components/JobStatus.svelte' import JobStatusIcon from '$lib/components/runs/JobStatusIcon.svelte' import RunBadges from '$lib/components/runs/RunBadges.svelte' @@ -459,7 +468,9 @@ > {#if job} - {/if} diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte index 95e4e4000a..dd0d052471 100644 --- a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -91,6 +91,7 @@ }, focus: () => aiChat?.focusInput(), flash: () => aiChat?.flashComposer(), + prefill: (text) => aiChat?.prefill(text), openSettings: (section, root) => aiChat?.openAssistantSettings(section, root), runtime }) diff --git a/frontend/src/lib/components/sessions/OpenInSessionButton.svelte b/frontend/src/lib/components/sessions/OpenInSessionButton.svelte index 2ea4bdbf61..93fd9bb9c3 100644 --- a/frontend/src/lib/components/sessions/OpenInSessionButton.svelte +++ b/frontend/src/lib/components/sessions/OpenInSessionButton.svelte @@ -42,18 +42,14 @@ {#if $copilotInfo.workspaceDisabled} - + {:else if show} -{:else if !inSessionPanel && !handoff} - {@render fallback?.()} {/if} diff --git a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte index e8c6da3016..8c29bd9286 100644 --- a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte +++ b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte @@ -39,7 +39,6 @@ section or the flat layout. getGlobalDraftStoragePath, listGlobalDrafts } from '$lib/components/copilot/chat/global/userDraftAdapter' - import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate' import type { PersistedArtifact } from '$lib/components/copilot/chat/artifacts/artifactsDB' import { PREVIEW_PAGES, @@ -130,8 +129,8 @@ section or the flat layout. // chat-scaffolded items are navigable (see WorkspaceItemDrillPicker). const KIND_TO_DRAFT_TYPE = { flow: 'flow', script: 'script', app: 'app' } as const const globalDraftsResource = resource( - () => ({ ws: effectiveWorkspace, enabled: isGlobalAiEnabled() }), - async ({ ws, enabled }) => (enabled && ws ? await listGlobalDrafts(ws) : []) + () => effectiveWorkspace, + async (ws) => (ws ? await listGlobalDrafts(ws) : []) ) function aiDraftsForKind(k: Kind): WorkspaceItem[] { const targetType = KIND_TO_DRAFT_TYPE[k] diff --git a/frontend/src/lib/components/sessions/SessionPicker.svelte b/frontend/src/lib/components/sessions/SessionPicker.svelte index 68e01d0c8b..091ca6435d 100644 --- a/frontend/src/lib/components/sessions/SessionPicker.svelte +++ b/frontend/src/lib/components/sessions/SessionPicker.svelte @@ -52,7 +52,7 @@ getSessionChatPeek, getSessionChatStatus, removeSession - } from './sessionRuntime.svelte' + } from './sessionRuntimeRegistry.svelte' import SessionStatusDot from './SessionStatusDot.svelte' import UnreadCountBadge from '$lib/components/common/badge/UnreadCountBadge.svelte' import { buildWorkspaceHierarchy } from '$lib/utils/workspaceHierarchy' @@ -60,7 +60,6 @@ import { Menu, Menubar, MenuItem } from '$lib/components/meltComponents' import MenuButton, { sidebarClasses } from '$lib/components/sidebar/MenuButton.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' - import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate' import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' import { workspaceIsFork } from '$lib/utils/workspaceHierarchy' import { WorkspaceService } from '$lib/gen' @@ -103,10 +102,6 @@ return !!rt && rt.manager.instructions.trim().length > 0 } - // Sessions share the beta opt-out gate with the global AI chat — when the - // user opted out, the sidebar section is hidden entirely. - const globalEnabled = isGlobalAiEnabled() - // The activity cutoff and the date buckets are wall-clock reads, which Svelte // cannot track: without this the list would keep a session past its cutoff, and // keep yesterday's header on today's rows, until some unrelated write forced a @@ -670,12 +665,7 @@ ) -{#if !globalEnabled} - -{:else if isCollapsed} +{#if isCollapsed}
{#snippet children({ createMenu })} diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index f1eb987588..d6af084258 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -368,8 +368,8 @@
Session not found
{:else} + at the bottom, where it stays once the transcript shows, rather than the chat's default + keyboard-shortcut hint, which means nothing here. --> {#snippet sessionEmptyHint()}
{/snippet} {#snippet inputPreface()} diff --git a/frontend/src/lib/components/sessions/SessionsBetaBanner.svelte b/frontend/src/lib/components/sessions/SessionsBetaBanner.svelte deleted file mode 100644 index 255a3955b5..0000000000 --- a/frontend/src/lib/components/sessions/SessionsBetaBanner.svelte +++ /dev/null @@ -1,23 +0,0 @@ - - - -
-
- - Try AI Sessions (beta) - · - -
-
diff --git a/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts index a37858f288..08a89e9023 100644 --- a/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts +++ b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts @@ -33,6 +33,8 @@ type Registration = { focus: () => void /** The box's accent outline, for a composer the user is sent to without it moving. */ flash: () => void + /** Text put before the draft, for an entry point that comes with a question. */ + prefill: (text: string) => void /** Assistant settings on `section`, focused on `root`'s folder. */ openSettings: (section: 'instructions' | 'skills' | 'mcp', root: string) => void runtime: SessionRuntime @@ -68,6 +70,9 @@ export const homeComposerContext = { flash(): void { registered?.flash() }, + prefill(text: string): void { + registered?.prefill(text) + }, openSettings(section: 'instructions' | 'skills' | 'mcp', root: string): void { registered?.openSettings(section, root) }, diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index e1d1e41bac..22dc68e1d3 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -1,4 +1,3 @@ -import { SvelteMap } from 'svelte/reactivity' import type { PendingRun } from '$lib/components/details/pendingRun' import { get } from 'svelte/store' import { invalidate as invalidateWorkspaceItems } from '$lib/components/workspacePicker' @@ -43,27 +42,18 @@ import { random_adj } from '$lib/components/random_positive_adjetive' import { copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' import { emptySchema, userPathPrefix, type StateStore } from '$lib/utils' -import { - localRunEnded, - localRunStarted, - onRemoteTurnEnd, - runHeldElsewhere -} from './sessionSync.svelte' +import { localRunEnded, localRunStarted, runHeldElsewhere } from './sessionSync.svelte' import { commitSessionWorkspace, - deleteSession as deleteSessionState, getEffectiveWorkspaceId, markSessionStateChanged, materializeTransient, - noteRemoteStateChange, sessionState, setGeneratedSessionSummary, setSessionChatId, setSessionPreviewCollapsed, setSessionPreviewSize, setSessionTabs, - setDraftsDiscardedHandler, - setSendUnderWayCheck, setSessionWorkMode, setSessionWorkingIn, type Session @@ -127,13 +117,24 @@ import type { RawAppDomResult } from '$lib/components/raw_apps/rawAppDom' import { getNonStreamingMetadataCompletion } from '$lib/components/copilot/lib' +import { pendingUserAction, type DisplayMessage } from '$lib/components/copilot/chat/shared' import { - pendingUserAction, - type ChatJob, - type DisplayMessage -} from '$lib/components/copilot/chat/shared' -import { readStoredChat } from '$lib/components/copilot/chat/HistoryManager.svelte' -import { getCurrentUserEmail } from '$lib/userScopedStorage' + getRuntime, + runtimeRoots, + runtimes, + setPendingUserActionResolver +} from './sessionRuntimeRegistry.svelte' +export { + disposeRuntime, + ensureSessionChatPeek, + getRuntime, + getSessionChatPeek, + getSessionChatStatus, + listRuntimes, + removeSession, + type SessionChatPeek, + type SessionChatStatus +} from './sessionRuntimeRegistry.svelte' import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs' // Per-kind load state for a session's editor target. Pure state container the @@ -315,8 +316,7 @@ export interface SessionRuntime { ): void } -const runtimes = new SvelteMap() -const runtimeRoots = new Map void>() +setPendingUserActionResolver(pendingUserAction) function emptyFlow(): Flow { return { @@ -1396,23 +1396,6 @@ export function getOrCreateRuntime(session: Session): SessionRuntime { return runtime } -export function disposeRuntime(sessionId: string) { - const runtime = runtimes.get(sessionId) - if (!runtime) return - 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) -} - -export function listRuntimes(): SessionRuntime[] { - return Array.from(runtimes.values()) -} - /** A pipeline deleted outside the session: every live session on its workspace * drops what it holds of it. Its in-memory drafts would otherwise keep showing the * pipeline in the preview, and autosave would write the deleted draft back. */ @@ -1425,76 +1408,6 @@ export function forgetDeletedPipeline(workspace: string, folder: string): void { } } -export function getRuntime(sessionId: string): SessionRuntime | undefined { - return runtimes.get(sessionId) -} - -// --------------------------------------------------------------------------- -// Cross-tab catch-up -// --------------------------------------------------------------------------- - -// Chained per session so two turn-ends close together (a turn plus its queued -// follow-up) re-read sequentially: the later read starts after the earlier -// one's loadPastChat, so the newest record is what ends up on screen. -const catchUps = new Map>() - -onRemoteTurnEnd((sessionId, chatId) => { - noteRemoteStateChange(sessionId) - const next = (catchUps.get(sessionId) ?? Promise.resolve()) - .then(() => applyRemoteTurnEnd(sessionId, chatId)) - .catch((e) => console.error('Failed to catch up on a turn from another tab', e)) - catchUps.set(sessionId, next) - void next.finally(() => { - if (catchUps.get(sessionId) === next) catchUps.delete(sessionId) - }) - // Awaited by the caller: the composer unlock rides on this settling. - return next -}) - -async function applyRemoteTurnEnd(sessionId: string, chatId: string): Promise { - const runtime = runtimes.get(sessionId) - if (!runtime) { - // The driving tab may have rotated to a new chat; follow it, or the next - // read and a later runtime would open the old one. - setSessionChatId(sessionId, chatId) - refreshSessionChatPeek(sessionId) - return - } - const m = runtime.manager - // Two transient states get a short retry rather than a skip, because the - // composer unlocks when this promise settles and a skip would unlock it on - // stale history: a send of this tab's own still in preflight (it may yet be - // refused, leaving no turn to converge on), and a store that failed to - // open. A turn actually running here owns the transcript instead — its own - // end converges — and the pruner caps the whole hold at STALE_MS anyway. - for (let attempt = 0; ; attempt++) { - if (m.loading) return - if (!m.sendInFlight) { - const res = await m.historyManager.reloadChat(chatId) - if (res === 'missing') return - if (res === 'loaded') break - } - if (attempt >= 7) return - await new Promise((r) => setTimeout(r, 500)) - if (runtimes.get(sessionId) !== runtime) return - } - // Disposed (session deleted, teardown) while the read was in flight. - if (runtimes.get(sessionId) !== runtime) return - // Adopts the driver's chat unconditionally, current view included: watching - // a session means following where its activity is, and it is also how tabs - // converge after an unsynced /clear rotation. A watcher browsing an older - // conversation is pulled along — deliberate, and the price of not syncing - // rotation as its own message. - // - // preserveQueue: this reload is a catch-up, not a conversation switch — a - // draft queued here (a refused send's kept message, a failed turn's card) - // is unsent user input the re-read must not destroy. - await m.loadPastChat(chatId, { preserveQueue: true }) - // loadPastChat's own artifact sync no-ops for an unchanged session id, so - // artifacts the driver wrote during the turn need this forced re-read. - await m.artifacts.resyncFromStore() -} - // Point a session's preview at a single seed tab. For re-pointing an existing // draft session at a new destination ("Open in AI session" / new-session-from- // page on a reused transient): its previous tabs — persisted with the draft @@ -1517,31 +1430,6 @@ export function resetSessionPreviewTabs(sessionId: string, seedUrl: string): voi } } -export type SessionChatStatus = - | 'idle' - | 'streaming' - // The assistant's turn ended and the user has yet to reply — passive, unlike - // 'awaiting-answer'/'needs-confirmation', where a running loop is blocked. - | 'awaiting-user' - | 'awaiting-answer' - | 'needs-confirmation' - | 'draft' - | 'error' - -// Full session teardown: dispose the runtime and remove from sessionState in one -// call. Callers (sidebar / header dropdowns) just invoke this; navigation away -// from a deleted active session is the caller's responsibility. -export function removeSession(sessionId: string): void { - disposeRuntime(sessionId) - deleteSessionState(sessionId) -} - -setDraftsDiscardedHandler((ids) => ids.forEach(disposeRuntime)) -setSendUnderWayCheck((id) => { - const m = runtimes.get(id)?.manager - return !!m && (m.loading || m.sendInFlight || m.sendPending) -}) - // The chat calls a new item by its chosen name while its draft is stored at // `draft_`; resolve the name the way the chat's write tools do. function draftStoragePath( @@ -1877,103 +1765,3 @@ setScreenshotHandler(async ({ sessionId: callerSessionId }) => { } } }) - -export function getSessionChatStatus(runtime: SessionRuntime): SessionChatStatus { - const m = runtime.manager - const last = m.displayMessages[m.displayMessages.length - 1] - // A loop parked on the user still reports `loading`, so these must be tested - // before `streaming` — otherwise "answer me" renders as "the AI is typing" - // and a session that needs the user looks like one that doesn't. - const pending = pendingUserAction(m.displayMessages) - if (pending === 'question') return 'awaiting-answer' - if (pending === 'confirmation') return 'needs-confirmation' - if (m.loading) return 'streaming' - if (m.instructions.trim().length > 0) return 'draft' - if (last?.role === 'user' && last.error) return 'error' - if (last && (last.role === 'assistant' || last.role === 'tool')) return 'awaiting-user' - return 'idle' -} - -// --------------------------------------------------------------------------- -// Sessions without a runtime -// --------------------------------------------------------------------------- - -// A runtime costs a chat manager and its loaded transcript, and lives until its -// session is deleted, so the sidebar does not create one per listed session. It -// reads the session's one stored chat instead, once. Without a runtime nothing -// runs in this tab, so only two facts of that chat can matter: its length (for -// the unread count) and whether its last message failed. Every other status is -// a live one. -export interface SessionChatPeek { - status: 'error' | 'idle' - messageCount: number -} - -const peeks = new SvelteMap() -const peeksInFlight = new Set() -const peeksPendingRefresh = new Set() - -// Not gated on `detached`: a chat saved mid-wait stores its job undetached, and -// loadPastChat resumes polling every unfinished job either way. -function isLiveJob(j: ChatJob): boolean { - return ( - j.status === 'queued' || - j.status === 'running' || - j.status === 'suspended' || - j.status === 'scheduled' - ) -} - -function sessionById(sessionId: string): Session | undefined { - return sessionState.sessions.find((s) => s.id === sessionId) -} - -function refreshSessionChatPeek(sessionId: string): void { - peeks.delete(sessionId) - if (peeksInFlight.has(sessionId)) { - peeksPendingRefresh.add(sessionId) - return - } - const session = sessionById(sessionId) - if (session) void ensureSessionChatPeek(session) -} - -export function getSessionChatPeek(sessionId: string): SessionChatPeek | undefined { - return peeks.get(sessionId) -} - -/** Read the stored chat of a session that has no runtime. A chat with a detached - * job still running gets its runtime instead: only a runtime polls the job and - * resumes the conversation when it finishes. */ -export async function ensureSessionChatPeek(session: Session): Promise { - const id = session.id - const chatId = session.chatId - if (runtimes.has(id) || peeks.has(id) || peeksInFlight.has(id) || !chatId) return - const email = getCurrentUserEmail() - if (!email) return - peeksInFlight.add(id) - try { - const chat = await readStoredChat(chatId, email) - if (sessionById(id)?.chatId !== chatId) { - refreshSessionChatPeek(id) - return - } - if (!chat || runtimes.has(id)) return - if (chat.backgroundJobs?.some(isLiveJob)) { - getOrCreateRuntime(session) - return - } - const last = chat.displayMessages[chat.displayMessages.length - 1] - peeks.set(id, { - status: last?.role === 'user' && last.error ? 'error' : 'idle', - messageCount: chat.displayMessages.length - }) - } catch (e) { - console.error('Failed to read session chat', e) - } finally { - peeksInFlight.delete(id) - if (peeksPendingRefresh.delete(id)) { - refreshSessionChatPeek(id) - } - } -} diff --git a/frontend/src/lib/components/sessions/sessionRuntimeRegistry.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntimeRegistry.svelte.ts new file mode 100644 index 0000000000..828659cc76 --- /dev/null +++ b/frontend/src/lib/components/sessions/sessionRuntimeRegistry.svelte.ts @@ -0,0 +1,247 @@ +// The live session runtimes, and what the sidebar reads of a session without one. Apart from +// `./sessionRuntime.svelte`, which builds runtimes and reaches the whole chat engine: the +// sidebar lists sessions on every page, and only opening one needs the engine. +import { SvelteMap } from 'svelte/reactivity' +import type { + ChatJob, + DisplayMessage, + PendingUserAction +} from '$lib/components/copilot/chat/shared' +import { readStoredChat } from '$lib/components/copilot/chat/HistoryManager.svelte' +import { getCurrentUserEmail } from '$lib/userScopedStorage' +import { onRemoteTurnEnd } from './sessionSync.svelte' +import { + deleteSession as deleteSessionState, + noteRemoteStateChange, + sessionState, + setDraftsDiscardedHandler, + setSendUnderWayCheck, + setSessionChatId, + type Session +} from './sessionState.svelte' +import type { SessionRuntime } from './sessionRuntime.svelte' + +export const runtimes = new SvelteMap() +export const runtimeRoots = new Map void>() + +// Only ever asked of a runtime, and every runtime is built by `./sessionRuntime.svelte`, which +// sets this when it loads. +let pendingActionOf: (messages: DisplayMessage[]) => PendingUserAction | undefined = () => undefined +export function setPendingUserActionResolver( + fn: (messages: DisplayMessage[]) => PendingUserAction | undefined +): void { + pendingActionOf = fn +} + +export function disposeRuntime(sessionId: string) { + const runtime = runtimes.get(sessionId) + if (!runtime) return + 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) +} + +export function listRuntimes(): SessionRuntime[] { + return Array.from(runtimes.values()) +} + +export function getRuntime(sessionId: string): SessionRuntime | undefined { + return runtimes.get(sessionId) +} + +// --------------------------------------------------------------------------- +// Cross-tab catch-up +// --------------------------------------------------------------------------- + +// Chained per session so two turn-ends close together (a turn plus its queued +// follow-up) re-read sequentially: the later read starts after the earlier +// one's loadPastChat, so the newest record is what ends up on screen. +const catchUps = new Map>() + +onRemoteTurnEnd((sessionId, chatId) => { + noteRemoteStateChange(sessionId) + const next = (catchUps.get(sessionId) ?? Promise.resolve()) + .then(() => applyRemoteTurnEnd(sessionId, chatId)) + .catch((e) => console.error('Failed to catch up on a turn from another tab', e)) + catchUps.set(sessionId, next) + void next.finally(() => { + if (catchUps.get(sessionId) === next) catchUps.delete(sessionId) + }) + // Awaited by the caller: the composer unlock rides on this settling. + return next +}) + +async function applyRemoteTurnEnd(sessionId: string, chatId: string): Promise { + const runtime = runtimes.get(sessionId) + if (!runtime) { + // The driving tab may have rotated to a new chat; follow it, or the next + // read and a later runtime would open the old one. + setSessionChatId(sessionId, chatId) + refreshSessionChatPeek(sessionId) + return + } + const m = runtime.manager + // Two transient states get a short retry rather than a skip, because the + // composer unlocks when this promise settles and a skip would unlock it on + // stale history: a send of this tab's own still in preflight (it may yet be + // refused, leaving no turn to converge on), and a store that failed to + // open. A turn actually running here owns the transcript instead — its own + // end converges — and the pruner caps the whole hold at STALE_MS anyway. + for (let attempt = 0; ; attempt++) { + if (m.loading) return + if (!m.sendInFlight) { + const res = await m.historyManager.reloadChat(chatId) + if (res === 'missing') return + if (res === 'loaded') break + } + if (attempt >= 7) return + await new Promise((r) => setTimeout(r, 500)) + if (runtimes.get(sessionId) !== runtime) return + } + // Disposed (session deleted, teardown) while the read was in flight. + if (runtimes.get(sessionId) !== runtime) return + // Adopts the driver's chat unconditionally, current view included: watching + // a session means following where its activity is, and it is also how tabs + // converge after an unsynced /clear rotation. A watcher browsing an older + // conversation is pulled along — deliberate, and the price of not syncing + // rotation as its own message. + // + // preserveQueue: this reload is a catch-up, not a conversation switch — a + // draft queued here (a refused send's kept message, a failed turn's card) + // is unsent user input the re-read must not destroy. + await m.loadPastChat(chatId, { preserveQueue: true }) + // loadPastChat's own artifact sync no-ops for an unchanged session id, so + // artifacts the driver wrote during the turn need this forced re-read. + await m.artifacts.resyncFromStore() +} + +export type SessionChatStatus = + | 'idle' + | 'streaming' + // The assistant's turn ended and the user has yet to reply — passive, unlike + // 'awaiting-answer'/'needs-confirmation', where a running loop is blocked. + | 'awaiting-user' + | 'awaiting-answer' + | 'needs-confirmation' + | 'draft' + | 'error' + +// Full session teardown: dispose the runtime and remove from sessionState in one +// call. Callers (sidebar / header dropdowns) just invoke this; navigation away +// from a deleted active session is the caller's responsibility. +export function removeSession(sessionId: string): void { + disposeRuntime(sessionId) + deleteSessionState(sessionId) +} + +setDraftsDiscardedHandler((ids) => ids.forEach(disposeRuntime)) +setSendUnderWayCheck((id) => { + const m = runtimes.get(id)?.manager + return !!m && (m.loading || m.sendInFlight || m.sendPending) +}) + +export function getSessionChatStatus(runtime: SessionRuntime): SessionChatStatus { + const m = runtime.manager + const last = m.displayMessages[m.displayMessages.length - 1] + // A loop parked on the user still reports `loading`, so these must be tested + // before `streaming` — otherwise "answer me" renders as "the AI is typing" + // and a session that needs the user looks like one that doesn't. + const pending = pendingActionOf(m.displayMessages) + if (pending === 'question') return 'awaiting-answer' + if (pending === 'confirmation') return 'needs-confirmation' + if (m.loading) return 'streaming' + if (m.instructions.trim().length > 0) return 'draft' + if (last?.role === 'user' && last.error) return 'error' + if (last && (last.role === 'assistant' || last.role === 'tool')) return 'awaiting-user' + return 'idle' +} + +// --------------------------------------------------------------------------- +// Sessions without a runtime +// --------------------------------------------------------------------------- + +// A runtime costs a chat manager and its loaded transcript, and lives until its +// session is deleted, so the sidebar does not create one per listed session. It +// reads the session's one stored chat instead, once. Without a runtime nothing +// runs in this tab, so only two facts of that chat can matter: its length (for +// the unread count) and whether its last message failed. Every other status is +// a live one. +export interface SessionChatPeek { + status: 'error' | 'idle' + messageCount: number +} + +const peeks = new SvelteMap() +const peeksInFlight = new Set() +const peeksPendingRefresh = new Set() + +// Not gated on `detached`: a chat saved mid-wait stores its job undetached, and +// loadPastChat resumes polling every unfinished job either way. +function isLiveJob(j: ChatJob): boolean { + return ( + j.status === 'queued' || + j.status === 'running' || + j.status === 'suspended' || + j.status === 'scheduled' + ) +} + +function sessionById(sessionId: string): Session | undefined { + return sessionState.sessions.find((s) => s.id === sessionId) +} + +function refreshSessionChatPeek(sessionId: string): void { + peeks.delete(sessionId) + if (peeksInFlight.has(sessionId)) { + peeksPendingRefresh.add(sessionId) + return + } + const session = sessionById(sessionId) + if (session) void ensureSessionChatPeek(session) +} + +export function getSessionChatPeek(sessionId: string): SessionChatPeek | undefined { + return peeks.get(sessionId) +} + +/** Read the stored chat of a session that has no runtime. A chat with a detached + * job still running gets its runtime instead: only a runtime polls the job and + * resumes the conversation when it finishes. */ +export async function ensureSessionChatPeek(session: Session): Promise { + const id = session.id + const chatId = session.chatId + if (runtimes.has(id) || peeks.has(id) || peeksInFlight.has(id) || !chatId) return + const email = getCurrentUserEmail() + if (!email) return + peeksInFlight.add(id) + try { + const chat = await readStoredChat(chatId, email) + if (sessionById(id)?.chatId !== chatId) { + refreshSessionChatPeek(id) + return + } + if (!chat || runtimes.has(id)) return + if (chat.backgroundJobs?.some(isLiveJob)) { + const { getOrCreateRuntime } = await import('./sessionRuntime.svelte') + getOrCreateRuntime(session) + return + } + const last = chat.displayMessages[chat.displayMessages.length - 1] + peeks.set(id, { + status: last?.role === 'user' && last.error ? 'error' : 'idle', + messageCount: chat.displayMessages.length + }) + } catch (e) { + console.error('Failed to read session chat', e) + } finally { + peeksInFlight.delete(id) + if (peeksPendingRefresh.delete(id)) { + refreshSessionChatPeek(id) + } + } +} diff --git a/frontend/src/lib/components/sessions/sidebarList.svelte.ts b/frontend/src/lib/components/sessions/sidebarList.svelte.ts index ceb213988b..13a5a32ee2 100644 --- a/frontend/src/lib/components/sessions/sidebarList.svelte.ts +++ b/frontend/src/lib/components/sessions/sidebarList.svelte.ts @@ -1,30 +1,13 @@ import { BROWSER } from 'esm-env' import { fromStore } from 'svelte/store' -import { roleCapabilities } from '$lib/stores' import { copilotInfo } from '$lib/aiStore' -import { - clearSessionsBetaOptOut, - isGlobalAiEnabled, - sessionsAllowedFor -} from '$lib/components/copilot/chat/global/gate' -const capabilities = fromStore(roleCapabilities) const copilot = fromStore(copilotInfo) // Listing sessions from within a session's preview frame would nest the whole experience. const embedded = BROWSER && window.self !== window.top -/** Whether the sidebar lists AI sessions. Not in a browser that opted out of them, for a role - * /sessions refuses, in a workspace that hid the assistant, nor inside a preview frame. */ +/** Whether the sidebar lists AI sessions. Not in a workspace that hid the assistant, nor inside a + * preview frame. */ export function sidebarSessionsShown(): boolean { - return ( - !embedded && - isGlobalAiEnabled() && - sessionsAllowedFor(!capabilities.current.code) && - !copilot.current.workspaceDisabled - ) -} - -/** Turning AI Sessions back on: Home, with the sessions listed in the sidebar. */ -export function activateAiSessions(): void { - clearSessionsBetaOptOut('/') + return !embedded && !copilot.current.workspaceDisabled } diff --git a/frontend/src/lib/components/sessions/workModeLock.svelte.ts b/frontend/src/lib/components/sessions/workModeLock.svelte.ts index 837a319ff3..6d55b8c781 100644 --- a/frontend/src/lib/components/sessions/workModeLock.svelte.ts +++ b/frontend/src/lib/components/sessions/workModeLock.svelte.ts @@ -4,7 +4,7 @@ import { switchWorkspace } from '$lib/storeUtils' import { useEditRights } from '$lib/operatorWriteRights' import { buildsAnything } from '$lib/editRights' import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy' -import { workspaceAIClients } from '$lib/components/copilot/lib' +import { setAiClientWorkspace } from '$lib/components/copilot/aiClientWorkspace' import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl' import type { WorkModeLock } from '../copilot/chat/workMode' import { useSessionReadOnly } from './sessionPermissions.svelte' @@ -20,7 +20,7 @@ import { openNewSession } from './sessionSwitch.svelte' function moveUnsentSession(sessionId: string, id: string, switchesWorkspace: boolean) { setSessionPendingWorkspace(sessionId, id) if (!switchesWorkspace || get(workspaceStore) === id) return - workspaceAIClients.init(id) + setAiClientWorkspace(id) switchWorkspace(id) void fixupUrlAfterWorkspaceSwitch(id) } diff --git a/frontend/src/lib/components/settings/AIPromptsModal.svelte b/frontend/src/lib/components/settings/AIPromptsModal.svelte index 91b73318a0..74e0531bd5 100644 --- a/frontend/src/lib/components/settings/AIPromptsModal.svelte +++ b/frontend/src/lib/components/settings/AIPromptsModal.svelte @@ -3,7 +3,7 @@ import Button from '../common/button/Button.svelte' import Label from '../Label.svelte' import TextInput from '../text_input/TextInput.svelte' - import { AIMode, getVisibleAIModes } from '../copilot/chat/AIChatManager.svelte' + import { AIMode } from '../copilot/chat/AIChatManager.svelte' import { ExternalLink } from 'lucide-svelte' import { Alert } from '../common' @@ -66,7 +66,7 @@ [AIMode.ASK]: 'Ask Mode' } - let visibleModes = $derived(modes ?? getVisibleAIModes()) + let visibleModes = $derived(modes ?? Object.values(AIMode)) // In read-only mode, only show modes that actually have a prompt configured let displayModes = $derived( readOnly diff --git a/frontend/src/lib/components/sidebar/MultiplayerMenu.svelte b/frontend/src/lib/components/sidebar/MultiplayerMenu.svelte index b85c602407..7b4f012342 100644 --- a/frontend/src/lib/components/sidebar/MultiplayerMenu.svelte +++ b/frontend/src/lib/components/sidebar/MultiplayerMenu.svelte @@ -4,16 +4,14 @@ import { enterpriseLicense, userStore, workspaceStore, awarenessStore } from '$lib/stores' - import { WebsocketProvider } from 'y-websocket' import * as Y from 'yjs' import type { Awareness } from 'y-protocols/awareness' import { page } from '$app/stores' import { slide } from 'svelte/transition' - import { buildWsUrl } from '$lib/wsUrl' - import { signMultiplayerRequest } from '$lib/components/debug/debugUtils' + import { MultiplayerConnection } from '$lib/multiplayerConnection' let awareness: Awareness | undefined = $state(undefined) - let wsProvider: WebsocketProvider | undefined = undefined + let connection: MultiplayerConnection | undefined = undefined let connected = $state(false) @@ -24,34 +22,39 @@ url: $page.url.pathname }) } + // Bumped on every disconnect, so a connection that finishes opening after the + // workspace changed or the menu unmounted is dropped instead of reconnecting forever. + let connectGeneration = 0 function disconnectWorkspace() { - if (wsProvider) { - wsProvider.destroy() - wsProvider = undefined + connectGeneration++ + if (connection) { + connection.destroy() + connection = undefined } connected = false awareness = undefined } async function connectWorkspace(workspace: string) { disconnectWorkspace() + const generation = connectGeneration - let token: string | undefined + let opened: MultiplayerConnection try { - token = await signMultiplayerRequest(workspace) + opened = await MultiplayerConnection.open(workspace, workspace, new Y.Doc()) } catch (e) { console.error('Failed to sign multiplayer request:', e) return } - - const ydoc = new Y.Doc() - wsProvider = new WebsocketProvider(buildWsUrl('/ws_mp/'), workspace, ydoc, { - params: { token } - }) - wsProvider.on('sync', (isSynced: boolean) => { + if (generation !== connectGeneration) { + opened.destroy() + return + } + connection = opened + opened.provider.on('sync', (isSynced: boolean) => { connected = true }) - awareness = wsProvider.awareness + awareness = opened.provider.awareness updateLocalState() diff --git a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte index 7178e6b4b2..b2357beece 100644 --- a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte +++ b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte @@ -1,3 +1,10 @@ + + `).exec(appHtml) + if (!m) throw new Error(`no script #${id} in app.html`) + return m[1].replace('%sveltekit.version%', version) +} +// Node's own experimental `localStorage` global shadows jsdom's, and is unset without a file. +function memoryStorage(): Storage { + const m = new Map() + return { + getItem: (k) => m.get(k) ?? null, + setItem: (k, v) => void m.set(k, String(v)), + removeItem: (k) => void m.delete(k), + clear: () => m.clear(), + key: (i) => [...m.keys()][i] ?? null, + get length() { + return m.size + } + } +} +for (const name of ['localStorage', 'sessionStorage'] as const) + Object.defineProperty(globalThis, name, { value: memoryStorage(), configurable: true }) + +const headScript = inlineScript('wm-home-snapshot-head') +const bodyScript = inlineScript('wm-home-snapshot-body') + +const user = { email: 'a@x.dev', username: 'a', workspace_id: 'demo' } as unknown as UserExt +const setHint = (v: string | undefined) => { + for (const c of document.cookie.split(/;\s*/)) { + const name = c.split('=')[0] + if (name) document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT` + } + if (v) document.cookie = `${__WM_SESSION_HINT__}=${v}` +} + +function renderHome() { + document.documentElement.removeAttribute('data-wm-home-snapshot') + document.head.innerHTML = '' + document.body.innerHTML = `
+ f/ax +
draft
+
menu
i
` +} + +/** Runs app.html's scripts as a load of `url` would; what it painted, if anything. */ +function boot(url: string): { painted: HTMLElement | null; written: string } { + history.replaceState(null, '', url) + ;(window as any).__wmHomeSnapshot = undefined + document.documentElement.removeAttribute('data-wm-home-snapshot') + document.head.innerHTML = '' + document.body.innerHTML = '
' + let written = '' + document.write = (s: string) => { + written += s + document.head.insertAdjacentHTML('beforeend', s) + } + new Function(headScript)() + new Function(bodyScript)() + return { painted: document.getElementById('wm-home-snapshot'), written } +} + +function stored(): HomeSnapshot | null { + const raw = localStorage.getItem(HOME_SNAPSHOT_KEY) + return raw ? JSON.parse(raw) : null +} + +beforeEach(() => { + localStorage.clear() + sessionStorage.clear() + forgetLastSession() + window.matchMedia = vi.fn(() => ({ matches: false })) as any + history.replaceState(null, '', '/?workspace=demo') + setHint('h1') + rememberUser(user, 'h1') + renderHome() +}) + +describe('home snapshot', () => { + it('paints what was saved, without values, handlers or anything open', () => { + saveHomeSnapshot('demo', 'demo') + const { painted, written } = boot('/?workspace=demo') + expect(painted).not.toBeNull() + expect(written).toContain('href="/_app/immutable/assets/app.css"') + const html = painted!.innerHTML + expect(html).toContain('f/a') + expect(html).not.toMatch(/typed|draft|menu|onclick|javascript:|id="content"/) + expect(html).toContain('id="g1"') + // The workspace disc draws its icon in a foreignObject. + expect(html).toContain('class="icon"') + }) + + it('hands over to the live page, which keeps the stylesheets', () => { + saveHomeSnapshot('demo', 'demo') + boot('/?workspace=demo') + releaseHomeSnapshot() + expect(document.getElementById('wm-home-snapshot')).toBeNull() + expect(document.documentElement.isConnected).toBe(true) + expect(document.documentElement.hasAttribute('data-wm-home-snapshot')).toBe(false) + expect(document.getElementById('svelte-global-loader')).not.toBeNull() + expect(document.querySelector('link[href="/_app/immutable/assets/app.css"]')).not.toBeNull() + }) + + it('shows what a part draws while the app boots, in its place', () => { + document + .getElementById('content')! + .insertAdjacentHTML( + 'beforeend', + '

starter

' + + '
' + ) + saveHomeSnapshot('demo', 'demo') + const html = boot('/?workspace=demo').painted!.innerHTML + expect(html).toContain('skeleton') + expect(html).not.toMatch(/starter|\shidden=/) + expect(html).toMatch(/visibility: hidden;"[^>]*>
- {:else if !sessionsAllowedFor(!$roleCapabilities.code)} - -
-

AI Sessions are not available for your role

-

Use the Ask AI chat instead.

- -
- {:else if !globalEnabled} - -
-

AI Sessions are deactivated

-

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

- -
{:else if !sessionState.hydrated} - + diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte index bc3d9f09cb..ab16f2d6a0 100644 --- a/frontend/src/routes/+layout.svelte +++ b/frontend/src/routes/+layout.svelte @@ -13,6 +13,8 @@ import { page } from '$app/state' import { installDevPollingDormancy } from '$lib/utils/devPollingDormancy' + import { noteClientNavigation, releaseHomeSnapshot } from '$lib/homeSnapshot' + import { onNavigate } from '$app/navigation' interface Props { children?: import('svelte').Snippet } @@ -33,6 +35,13 @@ document.getElementById('svelte-global-loader')?.remove() + // Home replaces the snapshot `app.html` painted when it mounts; a load that lands elsewhere + // (a redirect to login, to the workspace picker) replaces it here. + $effect(() => { + if (page.route.id !== '/(root)/(logged)') releaseHomeSnapshot() + }) + onNavigate(noteClientNavigation) + installDevPollingDormancy() // Prevent scrolling over number inputs from changing their value diff --git a/frontend/static/_headers b/frontend/static/_headers new file mode 100644 index 0000000000..9a5afacaa0 --- /dev/null +++ b/frontend/static/_headers @@ -0,0 +1,5 @@ +# Read by Cloudflare Pages, which hosts the PR previews; the backend sets the same headers +# itself (static_assets.rs). Without this, Pages serves every chunk with max-age=0 and a reload +# revalidates all of them over the network. +/_app/immutable/* + Cache-Control: public, max-age=31536000, immutable diff --git a/frontend/vite.config.js b/frontend/vite.config.js index a07034d2c1..b65276dc14 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -20,6 +20,65 @@ const uiBuilderStaticPresent = existsSync( fileURLToPath(new URL('static/ui_builder/app-preview.html', import.meta.url)) ) +/** + * Vite's preload helper (`__vitePreload`) checks every dependency of a dynamic import against + * every `` in the document before adding its own: with relative paths it walks + * `document.getElementsByTagName('link')` reading each `href`. A route node here preloads + * hundreds of chunks, so loading Home made that walk quadratic, ~40ms of a warm reload. + * + * The walk only has to catch links the helper did not add itself (its own are deduped by its + * `seen` map), which are the ones already in the document when it first runs: those are + * snapshotted once into a set. Patched in `renderChunk`, before the chunk's hash is taken, so + * a cached copy of the unpatched helper is never served under the same name. Fails the build + * when the helper no longer has the expected shape, so a Vite upgrade cannot silently bring + * the walk back. + */ +function preloadWithoutLinkScan() { + // Matches Vite's source and its minified form alike. + const scan = + /for\s*\(\s*let\s+(\w+)\s*=\s*(\w+)\.length\s*-\s*1\s*;\s*\1\s*>=\s*0\s*;\s*\1--\s*\)\s*\{\s*(?:const|let)\s+(\w+)\s*=\s*\2\[\1\]\s*;?\s*if\s*\(\s*\3\.href\s*===\s*(\w+)\s*&&\s*\(\s*!(\w+)\s*\|\|\s*\3\.rel\s*===\s*(["'`])stylesheet\6\s*\)\s*\)\s*return\s*;?\s*\}/ + const present = `function __wmLinkPresent(links, href, css) { + const s = (__wmLinkPresent.s ??= (() => { + const all = new Set(), sheets = new Set() + for (const l of links) { + all.add(l.href) + if (l.rel === 'stylesheet') sheets.add(l.href) + } + return { all, sheets } + })()) + return (css ? s.sheets : s.all).has(href) +} +` + // The server pass has no preload helper to patch. + let ssr = false + let patched = 0 + return { + name: 'wm-preload-without-link-scan', + apply: 'build', + configResolved(config) { + ssr = !!config.build.ssr + }, + renderChunk(code, chunk) { + if (ssr || !code.includes('vite:preloadError')) return null + if (!scan.test(code)) { + this.error( + `wm-preload-without-link-scan: ${chunk.fileName} holds Vite's preload helper, but not the link scan this plugin replaces. Check what the new helper does before dropping the plugin.` + ) + } + patched++ + return { + code: present + code.replace(scan, 'if (__wmLinkPresent($2, $4, $5)) return;'), + map: null + } + }, + generateBundle() { + if (!ssr && patched === 0) { + this.error("wm-preload-without-link-scan: no chunk holds Vite's preload helper") + } + } + } +} + /** * Fail the build if the emitted chunks import each other in a cycle. * @@ -168,6 +227,38 @@ function assertMonacoFreeAppShell() { } } +/** + * Fail the build if the app shell or the home page statically loads the AI chat engine or the + * provider SDKs. + * + * Everything those entries import statically loads and evaluates before the first page renders, + * and the engine alone is over a megabyte. The shell reaches it only from a click: through + * `sessionRuntimeRegistry` and `aiClientWorkspace`, which stand in for the modules that would pull + * it in. + */ +function assertAiEngineFreeAppShell() { + const entries = [ + '/src/routes/+layout.svelte', + '/src/routes/(root)/+layout.svelte', + '/src/routes/(root)/(logged)/+layout.svelte', + '/src/routes/(root)/(logged)/+page.svelte' + ] + const forbidden = [ + '/src/lib/components/copilot/chat/AIChatManager.svelte.ts', + '/node_modules/openai/', + '/node_modules/@anthropic-ai/sdk/' + ] + return { + name: 'wm-assert-ai-engine-free-app-shell', + generateBundle(_options, bundle) { + if (!isClientBuild(bundle)) return + for (const entry of entries) { + assertStaticClosureExcludes(this, bundle, entry, forbidden, 'sessionRuntimeRegistry.svelte.ts') + } + } + } +} + const remoteUrl = process.env.REMOTE ?? (process.env.BACKEND_PORT @@ -184,6 +275,9 @@ const authCookie = `token_${new URL(remoteUrl).host.replace(/\W/g, '_')}` // Isolated cookies are host-only: `Domain=localhost` is rejected when the dev server is // reached as 127.0.0.1 or over the network. const cookieDomain = isolateDevAuth ? '' : 'localhost' +// The readable hint the backend mirrors from the session cookie (session_hint.rs), renamed +// with it so that one worktree's login does not stand for another's session. +const sessionHintCookie = isolateDevAuth ? `${authCookie}_hint` : 'wm_session' function isolateAuthCookie(proxy) { if (!isolateDevAuth) return @@ -201,7 +295,9 @@ function isolateAuthCookie(proxy) { proxy.on('proxyRes', (proxyRes) => { const setCookie = proxyRes.headers['set-cookie'] if (setCookie) { - proxyRes.headers['set-cookie'] = setCookie.map((c) => c.replace(/^token=/, `${authCookie}=`)) + proxyRes.headers['set-cookie'] = setCookie.map((c) => + c.replace(/^token=/, `${authCookie}=`).replace(/^wm_session=/, `${sessionHintCookie}=`) + ) } }) } @@ -346,12 +442,25 @@ const config = { }, preview: { port: 3001 }, plugins: [ + // Only the dev proxy renames the hint: a build reads the name the backend sets. + { + name: 'wm-session-hint-cookie', + config: (_, { command }) => ({ + define: { + __WM_SESSION_HINT__: JSON.stringify( + command === 'serve' ? sessionHintCookie : 'wm_session' + ) + } + }) + }, sveltekit(), ...(process.env.HTTPS === 'true' ? [mkcert()] : []), plugin, assertAcyclicChunks(), + preloadWithoutLinkScan(), assertLeanPublicAppRoutes(), - assertMonacoFreeAppShell() + assertMonacoFreeAppShell(), + assertAiEngineFreeAppShell() ], define: { '__pkg__.version': JSON.stringify(version) }, optimizeDeps: { diff --git a/functions/api/[[path]].ts b/functions/api/[[path]].ts index e6f00292a8..c9c378ee03 100644 --- a/functions/api/[[path]].ts +++ b/functions/api/[[path]].ts @@ -30,18 +30,15 @@ export async function onRequest(context) { }); const newResponse = new Response(res.body, res); - // Extract domain from target hostname for cookie domain replacement - const targetDomain = targetHostname.split(".").slice(-2).join("."); - - newResponse.headers.set( - "set-cookie", - "token" + - (newResponse.headers - .get("set-cookie") - ?.replace(`Domain=${targetDomain};`, "") - ?.split("token") - ?.pop() ?? "") - ); + // Each cookie is passed on by itself, without its Domain: the backend's (e.g. + // `windmill.dev`) does not match this host, and a browser drops a cookie whose Domain + // does not match. Reading them joined (`headers.get`) would merge the session cookie with + // the `wm_session` hint set beside it, Domain included. + const setCookies = res.headers.getSetCookie(); + newResponse.headers.delete("set-cookie"); + for (const c of setCookies) { + newResponse.headers.append("set-cookie", c.replace(/;\s*Domain=[^;]*/gi, "")); + } newResponse.headers.set("Cross-Origin-Resource-Policy", "cross-origin"); return newResponse; diff --git a/lsp/Pipfile b/lsp/Pipfile index 88ab7642b8..0f7d52a7a5 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.856.0" +wmill = ">=1.858.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/lsp/pyls_launcher.py b/lsp/pyls_launcher.py index b3fbe7fd9a..b1b01b8fdc 100644 --- a/lsp/pyls_launcher.py +++ b/lsp/pyls_launcher.py @@ -371,9 +371,6 @@ class ShellcheckLS(websocket.WebSocketHandler): class RuffLS(LanguageServerWebSocketHandler): procargs = ["ruff", "server"] -class DenoLS(LanguageServerWebSocketHandler): - procargs = ["deno", "lsp"] - class GoLS(LanguageServerWebSocketHandler): procargs = ["gopls", "serve"] @@ -407,11 +404,6 @@ if __name__ == "__main__": monaco_path = "/tmp/monaco" os.makedirs(monaco_path, exist_ok=True) print("The monaco directory is created!") - go_mod_path = os.path.join(monaco_path, "go.mod") - if not os.path.exists(go_mod_path): - f = open(go_mod_path, "w") - f.write("module mymod\ngo 1.27") - f.close() # Sync instance-level ruff config into /tmp/monaco/ruff.toml so every # spawned `ruff server` picks it up. @@ -426,7 +418,6 @@ if __name__ == "__main__": (r"/ws/pyright", PyrightLS), (r"/ws/diagnostic", ShellcheckLS), (r"/ws/ruff", RuffLS), - (r"/ws/deno", DenoLS), (r"/ws/go", GoLS), (r"/ws/ping", PingHandler), (r"/ws/health", HealthHandler), @@ -434,5 +425,6 @@ if __name__ == "__main__": (r"/health", HealthHandler), ] ) - app.listen(port, address="0.0.0.0") + # The entrypoint sets 127.0.0.1 when the gateway, which checks the tokens, is in front. + app.listen(port, address=os.environ.get("LSP_HOST", "0.0.0.0")) ioloop.IOLoop.current().start() diff --git a/multiplayer/gateway.mjs b/multiplayer/gateway.mjs index 4749e61688..4bb48122bc 100644 --- a/multiplayer/gateway.mjs +++ b/multiplayer/gateway.mjs @@ -14,9 +14,14 @@ * clean paths (e.g. /ws_mp/room-name → /room-name on port 3002). * * Handles both HTTP and WebSocket upgrades. + * + * Requests for the language servers carry a backend-signed `?token=` (purpose + * "lsp"), checked here since the LSP launcher has no verifier of its own. Set + * REQUIRE_SIGNED_LSP_REQUESTS=false to turn the check off. */ import http from 'http' +import { getPublicKey, verifySignedToken } from './jwt.mjs' const PORT = parseInt(process.env.PORT || process.env.GATEWAY_PORT || '3000') const HOST = process.env.GATEWAY_HOST || '0.0.0.0' @@ -24,6 +29,12 @@ const HOST = process.env.GATEWAY_HOST || '0.0.0.0' const LSP_PORT = parseInt(process.env.LSP_PORT || '3001') const MULTIPLAYER_PORT = parseInt(process.env.MULTIPLAYER_PORT || '3002') const DEBUGGER_PORT = parseInt(process.env.DEBUGGER_PORT || '3003') +const REQUIRE_SIGNED_LSP_REQUESTS = process.env.REQUIRE_SIGNED_LSP_REQUESTS !== 'false' + +// The only LSP paths served without a token: health probes and the editor's +// connectivity check. Everything else that reaches the LSP port, the fallback +// route included, needs one. +const LSP_OPEN_PATHS = new Set(['/', '/health', '/ws/health', '/ws/ping']) const ROUTES = [ { prefix: '/ws_mp/', target: MULTIPLAYER_PORT, strip: '/ws_mp' }, @@ -45,11 +56,30 @@ function resolve (url) { return { port: LSP_PORT, path: url } } +/** Returns null when the request may be forwarded, or why it may not. */ +async function lspRequestRefusal (port, url) { + if (port !== LSP_PORT || !REQUIRE_SIGNED_LSP_REQUESTS) return null + const [pathname, query = ''] = url.split('?', 2) + if (LSP_OPEN_PATHS.has(pathname)) return null + const token = new URLSearchParams(query).get('token') + if (!token) return 'no token' + const { error } = await verifySignedToken(token, 'lsp') + return error ?? null +} + // ---- HTTP proxy ---- -const server = http.createServer((clientReq, clientRes) => { +const server = http.createServer(async (clientReq, clientRes) => { const { port, path } = resolve(clientReq.url) + const refusal = await lspRequestRefusal(port, clientReq.url) + if (refusal) { + console.warn(`[gateway] REJECTED ${clientReq.url.split('?')[0]}: ${refusal}`) + clientRes.writeHead(401, { 'Content-Type': 'text/plain' }) + clientRes.end('Unauthorized') + return + } + const opts = { hostname: '127.0.0.1', port, @@ -76,9 +106,17 @@ const server = http.createServer((clientReq, clientRes) => { // ---- WebSocket proxy (upgrade) ---- -server.on('upgrade', (clientReq, clientSocket, head) => { +server.on('upgrade', async (clientReq, clientSocket, head) => { const { port, path } = resolve(clientReq.url) + clientSocket.on('error', () => clientSocket.destroy()) + const refusal = await lspRequestRefusal(port, clientReq.url) + if (refusal) { + console.warn(`[gateway] REJECTED ${clientReq.url.split('?')[0]}: ${refusal}`) + clientSocket.end('HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n') + return + } + const opts = { hostname: '127.0.0.1', port, @@ -119,10 +157,25 @@ server.on('upgrade', (clientReq, clientSocket, head) => { proxy.end() }) +// The port the language servers were served on before the gateway, still targeted by +// proxies set up then; served by the same handlers, so with the same checks. +const LEGACY_LSP_PORT = parseInt(process.env.GATEWAY_LEGACY_LSP_PORT || '') +if (LEGACY_LSP_PORT && LEGACY_LSP_PORT !== PORT) { + const legacy = http.createServer() + legacy.on('request', (...args) => server.emit('request', ...args)) + legacy.on('upgrade', (...args) => server.emit('upgrade', ...args)) + legacy.listen(LEGACY_LSP_PORT, HOST, () => console.log(`[gateway] also listening on ${HOST}:${LEGACY_LSP_PORT}`)) +} + server.listen(PORT, HOST, () => { console.log(`[gateway] listening on ${HOST}:${PORT}`) console.log(`[gateway] /ws/* → :${LSP_PORT}`) console.log(`[gateway] /ws_mp/* → :${MULTIPLAYER_PORT}`) console.log(`[gateway] /ws_debug/* → :${DEBUGGER_PORT}`) console.log(`[gateway] (fallback) → :${LSP_PORT}`) + console.log(`[gateway] Signed LSP requests ${REQUIRE_SIGNED_LSP_REQUESTS ? 'REQUIRED (set REQUIRE_SIGNED_LSP_REQUESTS=false to disable)' : 'DISABLED'}`) + if (REQUIRE_SIGNED_LSP_REQUESTS) { + // Warm the JWKS cache so the first editor does not wait on it. + getPublicKey() + } }) diff --git a/multiplayer/jwt.mjs b/multiplayer/jwt.mjs new file mode 100644 index 0000000000..00db5a13e7 --- /dev/null +++ b/multiplayer/jwt.mjs @@ -0,0 +1,129 @@ +/** + * Verification of the Ed25519 JWTs the Windmill backend signs for the extra + * services (multiplayer, language servers), against the key it publishes at + * /api/debug/jwks. + */ + +import crypto from 'node:crypto' + +const WINDMILL_BASE_URL = process.env.WINDMILL_BASE_URL || process.env.BASE_INTERNAL_URL + +let cachedPublicKey = null +let publicKeyFetchPromise = null +// The backend re-derives its key when the instance's JWT secret changes, so a +// signature the cached key rejects triggers a refetch, at most this often. +const KEY_REFRESH_INTERVAL_MS = 60_000 +let lastKeyRefresh = 0 + +function base64urlDecode(str) { + const padding = '='.repeat((4 - str.length % 4) % 4) + const base64 = str.replace(/-/g, '+').replace(/_/g, '/') + padding + const binary = atob(base64) + return Uint8Array.from(binary, c => c.charCodeAt(0)) +} + +export async function getPublicKey() { + if (cachedPublicKey) return cachedPublicKey + if (publicKeyFetchPromise) return publicKeyFetchPromise + + if (!WINDMILL_BASE_URL) { + console.warn(`[${new Date().toISOString()}] WINDMILL_BASE_URL not set - cannot fetch public key`) + return null + } + + publicKeyFetchPromise = (async () => { + try { + const jwksUrl = `${WINDMILL_BASE_URL.replace(/\/$/, '')}/api/debug/jwks` + console.log(`[${new Date().toISOString()}] Fetching JWKS from ${jwksUrl}`) + const response = await fetch(jwksUrl) + if (!response.ok) { + throw new Error(`Failed to fetch JWKS: ${response.status} ${response.statusText}`) + } + + const jwks = await response.json() + if (!jwks.keys || jwks.keys.length === 0) { + throw new Error('No keys in JWKS') + } + + const jwk = jwks.keys[0] + if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') { + throw new Error(`Unsupported key type: ${jwk.kty}/${jwk.crv}`) + } + + const publicKeyBytes = base64urlDecode(jwk.x) + const key = await crypto.subtle.importKey( + 'raw', + publicKeyBytes, + { name: 'Ed25519' }, + true, + ['verify'] + ) + + cachedPublicKey = key + console.log(`[${new Date().toISOString()}] Successfully loaded Ed25519 public key from JWKS`) + return key + } catch (error) { + console.error(`[${new Date().toISOString()}] Failed to fetch/parse JWKS: ${error}`) + return null + } finally { + publicKeyFetchPromise = null + } + })() + + return publicKeyFetchPromise +} + +/** + * Verify the signature, expiry and purpose of a token. + * Returns `{ claims }` when valid, otherwise `{ error }`, with `noKey` set when + * the failure is only that the public key could not be obtained. + */ +export async function verifySignedToken(token, purpose, refreshed = false) { + const publicKey = await getPublicKey() + if (!publicKey) { + return { error: 'Public key not available but signed requests are required. Set WINDMILL_BASE_URL.', noKey: true } + } + + const parts = token.split('.') + if (parts.length !== 3) { + return { error: 'Invalid JWT format' } + } + + const [headerB64, claimsB64, signatureB64] = parts + + try { + const message = new TextEncoder().encode(`${headerB64}.${claimsB64}`) + const signature = base64urlDecode(signatureB64) + + const isValid = await crypto.subtle.verify( + { name: 'Ed25519' }, + publicKey, + signature, + message + ) + + if (!isValid) { + if (!refreshed && Date.now() - lastKeyRefresh > KEY_REFRESH_INTERVAL_MS) { + lastKeyRefresh = Date.now() + cachedPublicKey = null + return verifySignedToken(token, purpose, true) + } + return { error: 'Invalid JWT signature' } + } + + const claims = JSON.parse(new TextDecoder().decode(base64urlDecode(claimsB64))) + + const now = Math.floor(Date.now() / 1000) + if (!(now <= claims.exp)) { + return { error: `Token expired: ${now - claims.exp} seconds ago` } + } + + if (claims.purpose !== purpose) { + return { error: `Invalid token purpose: ${claims.purpose}` } + } + + return { claims } + } catch (error) { + return { error: `JWT verification error: ${error}` } + } +} diff --git a/multiplayer/server.mjs b/multiplayer/server.mjs index 87b20bd66e..195aab1e98 100644 --- a/multiplayer/server.mjs +++ b/multiplayer/server.mjs @@ -5,7 +5,7 @@ */ import http from 'http' -import crypto from 'node:crypto' +import { getPublicKey, verifySignedToken } from './jwt.mjs' import { WebSocketServer } from 'ws' import * as Y from 'yjs' import * as syncProtocol from 'y-protocols/sync' @@ -29,128 +29,28 @@ const MAX_PREAUTH_BYTES = 1024 * 1024 // --- JWT verification --- -let cachedPublicKey = null -let publicKeyFetchPromise = null - -function base64urlDecode(str) { - const padding = '='.repeat((4 - str.length % 4) % 4) - const base64 = str.replace(/-/g, '+').replace(/_/g, '/') + padding - const binary = atob(base64) - return Uint8Array.from(binary, c => c.charCodeAt(0)) -} - -async function getPublicKey() { - if (cachedPublicKey) return cachedPublicKey - if (publicKeyFetchPromise) return publicKeyFetchPromise - - if (!WINDMILL_BASE_URL) { - console.warn(`[${new Date().toISOString()}] WINDMILL_BASE_URL not set - cannot fetch public key`) - return null - } - - publicKeyFetchPromise = (async () => { - try { - const jwksUrl = `${WINDMILL_BASE_URL.replace(/\/$/, '')}/api/debug/jwks` - console.log(`[${new Date().toISOString()}] Fetching JWKS from ${jwksUrl}`) - const response = await fetch(jwksUrl) - if (!response.ok) { - throw new Error(`Failed to fetch JWKS: ${response.status} ${response.statusText}`) - } - - const jwks = await response.json() - if (!jwks.keys || jwks.keys.length === 0) { - throw new Error('No keys in JWKS') - } - - const jwk = jwks.keys[0] - if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') { - throw new Error(`Unsupported key type: ${jwk.kty}/${jwk.crv}`) - } - - const publicKeyBytes = base64urlDecode(jwk.x) - const key = await crypto.subtle.importKey( - 'raw', - publicKeyBytes, - { name: 'Ed25519' }, - true, - ['verify'] - ) - - cachedPublicKey = key - console.log(`[${new Date().toISOString()}] Successfully loaded Ed25519 public key from JWKS`) - return key - } catch (error) { - console.error(`[${new Date().toISOString()}] Failed to fetch/parse JWKS: ${error}`) - return null - } finally { - publicKeyFetchPromise = null - } - })() - - return publicKeyFetchPromise -} - /** * Verify a JWT multiplayer token. * Returns null if valid, or an error message if invalid. */ async function verifyToken(token, docName) { - const publicKey = await getPublicKey() + const { claims, error, noKey } = await verifySignedToken(token, 'multiplayer') - if (!publicKey) { - if (REQUIRE_SIGNED_REQUESTS) { - return 'Public key not available but signed requests are required. Set WINDMILL_BASE_URL.' - } + if (noKey && !REQUIRE_SIGNED_REQUESTS) { console.warn(`[${new Date().toISOString()}] Public key not available - signature verification disabled`) return null } - - const parts = token.split('.') - if (parts.length !== 3) { - return 'Invalid JWT format' + if (error) { + return error } - const [headerB64, claimsB64, signatureB64] = parts - - try { - const message = new TextEncoder().encode(`${headerB64}.${claimsB64}`) - const signature = base64urlDecode(signatureB64) - - const isValid = await crypto.subtle.verify( - { name: 'Ed25519' }, - publicKey, - signature, - message - ) - - if (!isValid) { - return 'Invalid JWT signature' - } - - const claimsJson = new TextDecoder().decode(base64urlDecode(claimsB64)) - const claims = JSON.parse(claimsJson) - - // Check expiration - const now = Math.floor(Date.now() / 1000) - if (now > claims.exp) { - return `Token expired: ${now - claims.exp} seconds ago` - } - - // Check purpose - if (claims.purpose !== 'multiplayer') { - return `Invalid token purpose: ${claims.purpose}` - } - - // Check workspace matches the doc room (format: "{workspace}/{path}") - const docWorkspace = docName.split('/')[0] - if (docWorkspace && claims.workspace_id !== docWorkspace) { - return `Token workspace "${claims.workspace_id}" does not match room workspace "${docWorkspace}"` - } - - return null - } catch (error) { - return `JWT verification error: ${error}` + // Check workspace matches the doc room (format: "{workspace}/{path}") + const docWorkspace = docName.split('/')[0] + if (docWorkspace && claims.workspace_id !== docWorkspace) { + return `Token workspace "${claims.workspace_id}" does not match room workspace "${docWorkspace}"` } + + return null } // --- Y.js document management --- diff --git a/multiplayer/test/gateway.test.mjs b/multiplayer/test/gateway.test.mjs new file mode 100644 index 0000000000..d0b5b79e8d --- /dev/null +++ b/multiplayer/test/gateway.test.mjs @@ -0,0 +1,120 @@ +/** + * The gateway forwards a connection to the language servers only with a + * backend-signed "lsp" token, except on the health and connectivity paths. + */ + +import assert from 'node:assert/strict' +import test from 'node:test' +import http from 'node:http' +import path from 'node:path' +import { spawn } from 'node:child_process' +import { fileURLToPath } from 'node:url' + +import { freePort, mintToken, startJwksServer, waitFor } from './helpers.mjs' + +const GATEWAY_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'gateway.mjs') + +/** Stands in for the LSP launcher: accepts every upgrade and records its path. */ +async function startFakeLsp() { + const upgraded = [] + const server = http.createServer((_req, res) => res.end('ok')) + server.on('upgrade', (req, socket) => { + upgraded.push(req.url) + socket.end('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n') + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { port: server.address().port, upgraded, close: () => new Promise((r) => server.close(r)) } +} + +/** Resolves to the status the gateway answers a plain request with. */ +function httpStatus(port, url) { + return new Promise((resolve, reject) => { + http.get({ hostname: '127.0.0.1', port, path: url }, (res) => { + res.resume() + resolve(res.statusCode) + }).on('error', reject) + }) +} + +/** Resolves to the status the gateway answers an upgrade request with. */ +function upgradeStatus(port, url) { + return new Promise((resolve, reject) => { + const req = http.request({ + hostname: '127.0.0.1', + port, + path: url, + headers: { Connection: 'Upgrade', Upgrade: 'websocket' } + }) + req.on('upgrade', (res, socket) => { + socket.destroy() + resolve(res.statusCode) + }) + req.on('response', (res) => { + res.resume() + resolve(res.statusCode) + }) + req.on('error', reject) + req.end() + }) +} + +test('language server upgrades need a signed lsp token', { timeout: 30000 }, async (t) => { + const jwks = await startJwksServer() + const lsp = await startFakeLsp() + const port = await freePort() + const legacyPort = await freePort() + let output = '' + const gateway = spawn(process.execPath, [GATEWAY_PATH], { + env: { + ...process.env, + PORT: String(port), + GATEWAY_HOST: '127.0.0.1', + LSP_PORT: String(lsp.port), + GATEWAY_LEGACY_LSP_PORT: String(legacyPort), + WINDMILL_BASE_URL: jwks.baseUrl, + BASE_INTERNAL_URL: '', + REQUIRE_SIGNED_LSP_REQUESTS: 'true' + }, + stdio: ['ignore', 'pipe', 'pipe'] + }) + gateway.stdout.on('data', (c) => { output += c }) + gateway.stderr.on('data', (c) => { output += c }) + t.after(async () => { + gateway.kill('SIGKILL') + await lsp.close() + await jwks.close() + }) + await waitFor(() => output.includes(`listening on 127.0.0.1:${port}`) && output.includes(`${legacyPort}`), { + message: 'the gateway to listen' + }) + + const lspToken = mintToken(jwks.privateKey, { workspaceId: 'ws', purpose: 'lsp' }) + const multiplayerToken = mintToken(jwks.privateKey, { workspaceId: 'ws' }) + const expired = mintToken(jwks.privateKey, { workspaceId: 'ws', purpose: 'lsp', ttlSecs: -1 }) + + assert.equal(await upgradeStatus(port, '/ws/pyright'), 401) + assert.equal(await upgradeStatus(port, `/ws/pyright?token=${multiplayerToken}`), 401) + assert.equal(await upgradeStatus(port, `/ws/pyright?token=${expired}`), 401) + // The fallback route reaches the launcher too. + assert.equal(await upgradeStatus(port, '/somewhere'), 401) + assert.deepEqual(lsp.upgraded, []) + + assert.equal(await upgradeStatus(port, `/ws/pyright?token=${lspToken}`), 101) + assert.equal(await upgradeStatus(port, '/ws/ping'), 101) + assert.deepEqual(lsp.upgraded, [`/ws/pyright?token=${lspToken}`, '/ws/ping']) + + assert.equal(await httpStatus(port, '/ws/pyright'), 401) + assert.equal(await httpStatus(port, '/health'), 200) + + // The pre-gateway LSP port applies the same checks. + assert.equal(await upgradeStatus(legacyPort, '/ws/pyright'), 401) + assert.equal(await upgradeStatus(legacyPort, `/ws/pyright?token=${lspToken}`), 101) + + // A token signed after the backend's key changed is accepted without a restart. + jwks.rotate() + const rotated = mintToken(jwks.privateKey, { workspaceId: 'ws', purpose: 'lsp' }) + assert.equal(await upgradeStatus(port, `/ws/go?token=${rotated}`), 101) + // A signature no key verifies is refused, with no second refetch within the interval. + assert.equal(await upgradeStatus(port, `/ws/pyright?token=${lspToken}`), 401) + assert.equal(jwks.requests, 2) +}) diff --git a/multiplayer/test/helpers.mjs b/multiplayer/test/helpers.mjs index 371123d864..7d71a13d54 100644 --- a/multiplayer/test/helpers.mjs +++ b/multiplayer/test/helpers.mjs @@ -21,7 +21,7 @@ export function base64url(buffer) { * the port up and the server.mjs child binding it, so `startMultiplayerServer` * retries on EADDRINUSE; servers started in-process bind port 0 directly instead. */ -async function freePort() { +export async function freePort() { return new Promise((resolve, reject) => { const probe = net.createServer() probe.on('error', reject) @@ -37,7 +37,7 @@ async function freePort() { * `sign_multiplayer` (backend/windmill-api-debug/src/lib.rs): an EdDSA JWT with * claims workspace_id, email, iat, exp, purpose. */ -export function mintToken(privateKey, { workspaceId, email = 'test@windmill.dev', ttlSecs = 300 } = {}) { +export function mintToken(privateKey, { workspaceId, email = 'test@windmill.dev', ttlSecs = 300, purpose = 'multiplayer' } = {}) { const now = Math.floor(Date.now() / 1000) const header = base64url(JSON.stringify({ alg: 'EdDSA', typ: 'JWT' })) const claims = base64url( @@ -46,7 +46,7 @@ export function mintToken(privateKey, { workspaceId, email = 'test@windmill.dev' email, iat: now, exp: now + ttlSecs, - purpose: 'multiplayer' + purpose }) ) const message = `${header}.${claims}` @@ -65,11 +65,14 @@ export function mintToken(privateKey, { workspaceId, email = 'test@windmill.dev' * could overrun. */ export async function startJwksServer({ hold = false } = {}) { - const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519') - const jwk = publicKey.export({ format: 'jwk' }) - const body = JSON.stringify({ - keys: [{ kty: jwk.kty, crv: jwk.crv, x: jwk.x, kid: 'test', use: 'sig', alg: 'EdDSA' }] - }) + let { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519') + const jwksBody = (key) => { + const jwk = key.export({ format: 'jwk' }) + return JSON.stringify({ + keys: [{ kty: jwk.kty, crv: jwk.crv, x: jwk.x, kid: 'test', use: 'sig', alg: 'EdDSA' }] + }) + } + let body = jwksBody(publicKey) let requests = 0 let released = !hold const held = new Set() @@ -100,7 +103,14 @@ export async function startJwksServer({ hold = false } = {}) { const { port } = server.address() return { - privateKey, + get privateKey() { + return privateKey + }, + /** Serve a new key pair from now on, as the backend does when its JWT secret changes. */ + rotate() { + ;({ publicKey, privateKey } = crypto.generateKeyPairSync('ed25519')) + body = jwksBody(publicKey) + }, baseUrl: `http://127.0.0.1:${port}`, get requests() { return requests diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 0c674ba689..f88323094f 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.856.0 + version: 1.858.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 3fc0c56a1f..0db271db30 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.856.0' + ModuleVersion = '1.858.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index a2690dba92..a1105ca17e 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.856.0" +version = "1.858.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/system_prompts/README.md b/system_prompts/README.md index 32c0c521c4..14a940ea0f 100644 --- a/system_prompts/README.md +++ b/system_prompts/README.md @@ -10,7 +10,7 @@ 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 +The workspace MCP server (`backend/windmill-api/src/ai_session_tools/`) 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`. diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 3ee03a96f8..68178f8365 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1465,7 +1465,11 @@ The key must be a **string literal** — the graph parser is static and cannot f > > The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: \`// materialize manual dbt:////\`, where \`\` is a warehouse the workspace configures under Settings → dbt. \`manual\` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql \`CREATE TABLE\` / \`INSERT\`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a \`source\`: the declared relation and the dbt model land on ONE graph node, and a downstream \`// on dbt:////\` fires when the ingestion node completes. -A managed \`// materialize ducklake:///
\` tells the runtime to write the node's output table **for you**: write the body as a single \`SELECT\` and the runtime wraps it in the create/replace — do **not** also write your own \`CREATE TABLE\` / \`INSERT\`. (The opposite holds for the \`dbt://\` target above: there the node writes its own DDL and the strategies below do not apply.) Write strategy: +A managed \`// materialize ducklake:///
\` tells the runtime to write the node's output table **for you**: write the body as a single \`SELECT\` and the runtime wraps it in the create/replace — do **not** also write your own \`CREATE TABLE\` / \`INSERT\`. (The opposite holds for the \`dbt://\` target above: there the node writes its own DDL and the strategies below do not apply.) + +A target that names no table — \`// materialize\`, \`// materialize ducklake://\`, or options alone such as \`// materialize key=id\` — writes the table named after the script: node \`f/shop/orders_daily\` materializes \`ducklake://main/orders_daily\` (characters other than letters, digits and \`_\` become \`_\`, and a name starting with a digit gets a leading \`_\`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream \`// on\` and read. + +Write strategy: - no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change); - \`// materialize append\` → INSERT-append rows (incremental); @@ -1496,7 +1500,8 @@ On a node that materializes a DuckLake table, \`// measure = 2. 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. 3. Start each body with \`// pipeline\`, then the \`// on\` input declarations, then the transform that writes the output. 4. **Chain nodes by asset URI**: read an upstream node's output asset, then \`// on \` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones. -5. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist. +5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as \`DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')\` or \`ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders\`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there. +6. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist. ## Example (DuckDB → DuckLake, scheduled ingest + downstream transform) @@ -1515,9 +1520,12 @@ Node \`f/sales/orders_daily\` (runs when \`orders\` is produced, writes a rollup -- pipeline -- on ducklake://main/orders -- materialize ducklake://main/orders_daily +ATTACH 'ducklake://main' AS lake; SELECT date_trunc('day', ts) AS day, count(*) AS n -FROM ducklake.main.orders GROUP BY 1 +FROM lake.orders GROUP BY 1 \`\`\` + +A node reads a DuckLake table only through a lake it attaches itself (\`ATTACH 'ducklake://' AS lake;\`, then \`lake.
\`); the materialize target is attached by the runtime under a name of its own, so \`ducklake.main.
\` does not resolve. `; export const DATATABLE_BASE = `# Data tables: schema changes, migrations and permissions diff --git a/system_prompts/auto-generated/skills/write-pipeline/SKILL.md b/system_prompts/auto-generated/skills/write-pipeline/SKILL.md index 4c339e6222..084e0cda63 100644 --- a/system_prompts/auto-generated/skills/write-pipeline/SKILL.md +++ b/system_prompts/auto-generated/skills/write-pipeline/SKILL.md @@ -101,7 +101,11 @@ The key must be a **string literal** — the graph parser is static and cannot f > > The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes. -A managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.) Write strategy: +A managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.) + +A target that names no table — `// materialize`, `// materialize ducklake://`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read. + +Write strategy: - no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change); - `// materialize append` → INSERT-append rows (incremental); @@ -132,7 +136,8 @@ On a node that materializes a DuckLake table, `// measure = [ 2. 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. 3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output. 4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones. -5. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist. +5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there. +6. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist. Locally: @@ -158,6 +163,9 @@ Node `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup): -- pipeline -- on ducklake://main/orders -- materialize ducklake://main/orders_daily +ATTACH 'ducklake://main' AS lake; SELECT date_trunc('day', ts) AS day, count(*) AS n -FROM ducklake.main.orders GROUP BY 1 +FROM lake.orders GROUP BY 1 ``` + +A node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://' AS lake;`, then `lake.
`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.
` does not resolve. diff --git a/system_prompts/base/pipeline-base.md b/system_prompts/base/pipeline-base.md index 59924faf41..3a27b54a5a 100644 --- a/system_prompts/base/pipeline-base.md +++ b/system_prompts/base/pipeline-base.md @@ -98,7 +98,11 @@ The key must be a **string literal** — the graph parser is static and cannot f > > The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes. -A managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.) Write strategy: +A managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.) + +A target that names no table — `// materialize`, `// materialize ducklake://`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read. + +Write strategy: - no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change); - `// materialize append` → INSERT-append rows (incremental); @@ -129,7 +133,8 @@ On a node that materializes a DuckLake table, `// measure = [ 2. 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. 3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output. 4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones. -5. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist. +5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there. +6. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist. Locally: @@ -157,6 +162,9 @@ Node `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup): -- pipeline -- on ducklake://main/orders -- materialize ducklake://main/orders_daily +ATTACH 'ducklake://main' AS lake; SELECT date_trunc('day', ts) AS day, count(*) AS n -FROM ducklake.main.orders GROUP BY 1 +FROM lake.orders GROUP BY 1 ``` + +A node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://' AS lake;`, then `lake.
`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.
` does not resolve. diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 743dd8a87e..58ec4c1e1a 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.856.0", + "version": "1.858.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 26bbd282cc..f9d671deed 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.856.0", + "version": "1.858.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 1c44102738..985fe358d9 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.856.0 +1.858.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 642c0ed651..5f7b62a377 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.856.0", + "version": "1.858.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.856.0", + "version": "1.858.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 902dc70b3c..d93720f0bf 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.856.0", + "version": "1.858.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts",