Compare commits

..
Author SHA1 Message Date
Ruben FiszelandClaude Opus 4.6 315d4fd2ff fix: correct migration comment to list actual sources (ui, cli, merge)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-17 12:33:19 +00:00
Ruben FiszelandClaude Opus 4.6 cca4666eb4 feat: set deploy source to 'merge' during fork merge UI flow
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:28:44 +00:00
Ruben FiszelandClaude Opus 4.6 d0f80c7af2 fix: make deploy source optional, UI sends explicit header
Default source is now None (direct API call), always blocked by
DisableDirectDeployment. UI, CLI, and merge explicitly identify
themselves via X-Windmill-Deploy-Source header.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:03:18 +00:00
Ruben FiszelandClaude Opus 4.6 523aa34fcb feat: add granular deployment source rules for protection rulesets
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 14:43:03 +00:00
3649 changed files with 45113 additions and 295109 deletions
-267
View File
@@ -1,267 +0,0 @@
---
name: adding-a-trigger
description: Checklist for adding a new TriggerCrud-based trigger type to Windmill (Azure, GCP, Kafka, etc.). Use when wiring a new trigger kind across backend, frontend, CLI, and capture infrastructure.
---
# Skill: Adding a New Trigger Type
Use this skill when adding a trigger kind that implements `TriggerCrud` (Kafka, GCP, Azure, MQTT, SQS, NATS, Postgres, Email…). For native triggers (Nextcloud, Google Drive — things wired through `windmill-native-triggers`), use the `native-trigger` skill instead.
The goal of this doc is to enumerate every file that needs to change. Missing any one of them leads to silent regressions: sync drops the trigger, capture button does nothing, workspace forks lose it, sidebar counters undercount. Follow the checklist top-to-bottom — each section is independent enough to be validated on its own.
Throughout this doc, substitute `{kind}` for the new trigger kind (`azure`, `kafka`, …), `{Kind}` for PascalCase (`Azure`, `Kafka`), `{KIND}` for SCREAMING (`AZURE`, `KAFKA`).
## Reference implementations
- **GCP** — closest analogue to Azure. Has push + pull, OIDC auth, ARM-like resource paths, capture handler. Grep for `gcp_trigger` / `GcpTrigger`.
- **Kafka** — simpler (pull-only, streaming). Good for trivial integrations.
- **Azure** — most recently added (2026). Shared-secret push auth, Event Grid namespaces + basic topics, ARM resource discovery, Namespace-pull data-plane. Grep for `azure_trigger` / `AzureTrigger`.
## 1. Database migration
Create a migration: `cargo sqlx migrate add -r add_{kind}_trigger` from `backend/`. Never write timestamps manually.
The `up.sql` usually defines:
- An optional enum type (e.g. `AZURE_MODE`) if the trigger has sub-kinds
- The `{kind}_trigger` table with at minimum these columns (mirrored from kafka/gcp):
- primary: `(workspace_id, path)`
- `script_path`, `is_flow`, `enabled`, `mode`, `permissioned_as`, `edited_by`, `email`
- `edited_at`, `error`, `server_id`, `last_server_ping`
- `error_handler_path`, `error_handler_args jsonb`, `retry jsonb`
- trigger-specific fields
- Indexes on foreign keys + any frequently-filtered columns
- Foreign key to `workspace`
Down migration drops the table and any enum types.
## 2. Backend crate (`windmill-trigger-{kind}`)
Create a new crate under `backend/windmill-trigger-{kind}/` with:
- `Cargo.toml`: features `enterprise`, `private` if EE, standard deps
- `src/lib.rs`: `pub use mod_ee::*;` behind `#[cfg(all(feature = "enterprise", feature = "private"))]`
- `src/mod_ee.rs`: core types + helpers
- `src/handler_ee.rs`: `TriggerCrud` impl + route handlers
- `src/listener_ee.rs`: (only if streaming/pull-based) `Listener` trait impl
Required in `mod_ee.rs`:
- `{Kind}Config` struct (persisted shape, `FromRow`)
- `{Kind}ConfigRequest` struct (what API receives — usually similar to Config but with validation fields)
- `{Kind}Trigger` unit struct (implements the traits)
- `impl TriggerJobArgs for {Kind}Trigger` — sets `TRIGGER_KIND`, `Payload`, `v1_payload_fn`
Required in `handler_ee.rs`:
- `#[async_trait] impl TriggerCrud for {Kind}Trigger` with:
- `type Trigger = Trigger<{Kind}Config>`
- `type TriggerConfigRequest = {Kind}ConfigRequest`
- `const ROUTE_PREFIX: &'static str = "/{kind}_triggers";`
- `const TABLE_NAME`, `ADDITIONAL_SELECT_FIELDS`
- `get_deployed_object`, `validate_config`, `create_trigger`, `update_trigger`, `delete_trigger`, `test_connection`
- `additional_routes` (optional — mount extra endpoints for things like ARM resource listing, topic discovery)
Register the crate in `backend/Cargo.toml` as a workspace member and as a dep of `windmill-api` behind the feature flag.
## 3. Wire into `windmill-api` (feature-gated everywhere)
**`backend/windmill-api/src/triggers/handler.rs`** — mount the trigger crate:
```rust
#[cfg(all(feature = "enterprise", feature = "{kind}_trigger", feature = "private"))]
{
use crate::triggers::{kind}::{Kind}Trigger;
router = router.nest({Kind}Trigger::ROUTE_PREFIX, complete_trigger_routes({Kind}Trigger));
}
```
**`backend/windmill-api/src/triggers/{kind}/mod.rs`** — re-export the crate:
```rust
pub use windmill_trigger_{kind}::*;
```
**`backend/windmill-api/src/lib.rs`** — if the trigger receives inbound pushes, add a webhook route:
```rust
.nest("/{kind}/w/{workspace_id}", {
#[cfg(all(feature = "enterprise", feature = "{kind}_trigger", feature = "private"))]
{ triggers::{kind}::handler_oss::{kind}_push_route_handler() }
#[cfg(not(...))]
{ Router::new() }
})
```
## 4. `TriggerKind` enum (`backend/windmill-types/src/triggers.rs`)
Already has slots for most triggers but verify your variant exists:
- Add `{Kind}` to the `TriggerKind` enum
- Add match arm in `to_key()`
- Add match arm in `from_str`
- Add match arm in `JobTriggerKind` (if jobs need kind tagging)
## 5. OpenAPI (`backend/windmill-api/openapi.yaml`)
This file is huge and the single most-forgotten place. Add:
- `/w/{workspace}/{kind}_triggers/create` + `/update/{path}` + `/delete/{path}` + `/get/{path}` + `/list` + `/exists/{path}` + `/setmode/{path}` + `/test` paths (mirror gcp section)
- Any `additional_routes` your handler exposes (resource discovery, etc.)
- Schemas: `{Kind}Trigger`, `{Kind}TriggerData`, `{Kind}Mode` (if enum), `{Kind}DeliveryConfig`, helper request/response types
- Add `{kind}` to `CaptureTriggerKind` enum
- Add `{kind}_used: boolean` to the `UsedTriggers` response schema
Regenerate frontend client: `npm run generate-backend-client` from `frontend/`.
## 6. `UsedTriggers` + workspace export
**`backend/windmill-api-workspaces/src/workspaces.rs`** — add `{kind}_used: bool` to the `UsedTriggers` struct and add an `EXISTS(SELECT 1 FROM {kind}_trigger …)` to the `get_used_triggers` query.
**`backend/windmill-api/src/workspaces_export.rs`** — add export block mirroring gcp's (export lists all triggers, serializes them to YAML/JSON). The block re-uses the `trigger_ignore_keys` variable so the new kind automatically participates in fork-export stripping (`mode` field is omitted when the source workspace is a fork — keeps fork→parent merges from flipping the parent's enabled state).
**Fork cloning (`clone_triggers_and_schedules` in workspaces.rs)** — add an `INSERT INTO {kind}_trigger ... SELECT ...` block that copies all rows from the parent workspace, forcing `mode = 'disabled'::TRIGGER_MODE`. Always runs at fork creation; forgetting this means users can't carry `{kind}` triggers into their forks.
## 6.5 Hardcoded trigger-kind arrays (silent-failure hotspots)
Several files keep **hardcoded arrays** of trigger kind strings. Miss one and ACL checks / user offboarding / trash drop your kind:
- **`backend/windmill-api-groups/src/granular_acls.rs`** — `KINDS: [&str; N]`. **Increment N** (the compile error is cryptic otherwise). Controls which kinds accept granular ACL operations.
- **`backend/windmill-api-users/src/users.rs`** (`extra_perms_tables`) — which tables get `extra_perms` entries cleaned when a user is deleted.
- **`backend/windmill-api/src/offboarding.rs`** — three separate arrays (enumeration, fork-copy, and delete paths). **All three** need the new kind.
- **`backend/windmill-api/src/trash.rs`** — `valid_tables` for the trash / restore API.
- **`backend/windmill-git-sync/src/lib.rs`** — add a test assertion for `DeployedObject::{Kind}Trigger.get_kind() == "{kind}_trigger"` (the `get_kind` match arm itself lives in the enum impl — already required by the Rust compiler).
- **`backend/windmill-api-auth/src/scopes.rs`** — add the `{Kind}Triggers` variant to `ScopeDomain` enum + `as_str` match + `from_str` match. Required for the OAuth/token system to recognise `{kind}_triggers:read|write` scopes.
- **`backend/windmill-api/src/token.rs`** (`build_trigger_scope_domains``TRIGGER_DOMAINS`) — add `("{kind}_triggers", "{Kind display name}")` so the CreateToken UI's scope selector surfaces the `read` / `write` checkboxes.
**OpenAPI enums** to extend (do NOT forget — generated client will allow it but server rejects as 400):
- `CaptureTriggerKind` enum
- Three `kind` enums under `/w/{workspace}/acls/{get,add,remove}/{kind}/{path}` (yes, same list repeated three times)
After editing any of these, run a full `cargo check` with your feature flag + `gcp_trigger` + other core flags — the `KINDS: [&str; N]` length mismatch only surfaces when the crate compiles.
## 7. Capture infrastructure (`backend/windmill-api/src/capture.rs`)
If the trigger supports push delivery, it also needs a capture endpoint so users can test it:
- `{Kind}TriggerConfig` struct (gated by feature flags)
- `TriggerConfig::{Kind}` variant
- `set_{kind}_trigger_config` function (creates the subscription/equivalent pointing at the capture URL — use your `manage_{kind}_subscription` helper with `trigger_mode=false`)
- Both real + no-op versions behind feature gates
- `TriggerKind::{Kind} => set_{kind}_trigger_config(...)` arm in `set_config`
- `{kind}_payload` async handler — validates auth (if any), processes payload, calls `insert_capture_payload`
- Route: `.route("/{kind}/{runnable_kind}/{*path}", post({kind}_payload))` inside `workspaced_unauthed_service` — and expand the surrounding `#[cfg(any(...))]` to include your feature flag
## 8. CLI (`cli/`) — easy to miss, breaks sync silently
Check all of these:
**`cli/src/types.ts`:**
- Add `"{kind}"` to `TRIGGER_TYPES` array
- Add `"{kind}_trigger"` to `getTypeStrFromPath` return union
- Add match case in `getTypeStrFromPath`'s `typeEnding ===` chain
- Add `pushTrigger("{kind}", ...)` branch in `pushObj`
**`cli/src/commands/trigger/trigger.ts`:**
- Import `{Kind}Trigger` type
- Add `{kind}: {Kind}Trigger` to the `Trigger` type map
- Add `{kind}: wmill.get{Kind}Trigger`, `update{Kind}Trigger`, `create{Kind}Trigger` to each function map
- Add `{kind}: { ... }` template to `triggerTemplates`
- Add `list{Kind}Triggers` call + spread in the `list` aggregation
- Update `--kind` option descriptions to mention the new kind
**`cli/src/commands/sync/sync.ts`:**
- Add `path.endsWith(".{kind}_trigger" + ext)` in the file-type filter
- Add `typ == "{kind}_trigger"` in `getTypeOrder`
- Add `"{kind}_trigger"` to the delete-suffix regex (~line 3092)
- Add a `case "{kind}_trigger"` in the delete switch
**`cli/src/guidance/skills.ts`** — **DO NOT EDIT DIRECTLY**. It's auto-generated by `system_prompts/generate.py`. Instead:
- Edit `system_prompts/utils.py` → append `('{Kind}Trigger', '{kind}_trigger')` to the `SCHEMA_MAPPINGS['triggers']` list (this is the master list — the one in `generate.py` is duplicated and `utils.py` wins)
- Then run `python3 system_prompts/generate.py` — it regenerates `cli/src/guidance/skills.ts` with the schema extracted from `backend/windmill-api/openapi.yaml`
- Commit the regenerated file
## 9. Frontend — editor + drawer
Under `frontend/src/lib/components/triggers/{kind}/`:
- `{Kind}TriggerPanel.svelte` — the tile shown in the triggers listing
- `{Kind}TriggerEditor.svelte` — outer drawer wrapper
- `{Kind}TriggerEditorInner.svelte` — state + business logic; must expose:
- `openEdit(path, isFlow, defaultValues?)` method
- `isEditor` prop, `onConfigChange` + `onCaptureConfigChange` callbacks
- `get{Kind}Config()` + `get{Kind}CaptureConfig()` helpers
- `captureConfig = $derived.by(untrack(() => isEditor) ? get{Kind}CaptureConfig : () => ({}))`
- `$effect(() => { const args = [captureConfig, isValid] as const; untrack(() => onCaptureConfigChange?.(...args)) })`
- `{Kind}TriggerEditorConfigSection.svelte` — form fields; use design-system components (`TextInput`, `Select`, `Toggle`, `ToggleButtonGroup`), never raw `<input>`
- `{Kind}Capture.svelte` — capture panel; wraps `CaptureSection` with `captureType="{kind}"`
- `utils.ts``requestBody` builders and any trigger-type-specific helpers
## 10. Frontend — global integration
Easy to miss:
- **`frontend/src/lib/components/triggers.ts`** — add `'{kind}'` to the `TriggerKind` union
- **`frontend/src/lib/components/triggers/CaptureWrapper.svelte`**:
- Import `{Kind}Capture`
- Add to `isStreamingCapture()` array (streaming = pull-style; push-style is typically `false`)
- Add `{:else if captureType === '{kind}'}` branch with the `<{Kind}Capture>` render
- **`frontend/src/lib/components/sidebar/SidebarContent.svelte`** — import the icon, add the nav entry
- **`frontend/src/lib/components/sidebar/OperatorMenu.svelte`** — add the operator-mode entry
- **`frontend/src/routes/(root)/(logged)/+layout.svelte`** — destructure `{kind}_used` from `/get_used_triggers` response, push `'{kind}'` into `usedKinds`
- **`frontend/src/lib/components/search/GlobalSearchModal.svelte`** — import icon, add "Go to {Kind} ..." entry
- **`frontend/src/lib/components/offboarding-utils.ts`** — add mappings `{kind}_trigger: '{kind}_triggers'` and `{kind}_trigger: '{kind} trigger'`
- **`frontend/src/lib/components/icons/{Kind}Icon.svelte`** — single-path SVG, `fill={color ?? 'currentColor'}`, `size` prop default 16 (match existing icons — don't hardcode colors, don't use `width`/`height` props)
- **`frontend/src/routes/(root)/(logged)/{kind}_triggers/+page.svelte`** — listing page (mirror `gcp_triggers/+page.svelte` for push+pull, `kafka_triggers` for pure streaming)
- **`frontend/src/lib/components/CompareWorkspaces.svelte`** — workspace fork / compare tool. Needs: service import, editor import, `{kind}Editor` `$state`, `case '{kind}'` in `openTriggerDetails()`, entry in `triggerServices` object (list/delete/normalize), and `<{Kind}TriggerEditor bind:this={{kind}Editor} />` in the template
## 10.5 AI system prompts (`system_prompts/`)
- **`system_prompts/utils.py`** — append `('{Kind}Trigger', '{kind}_trigger')` to `SCHEMA_MAPPINGS['triggers']` (master list used by code generation + CLI skills)
- **`system_prompts/generate.py`** — also has a duplicated `schema_types` list (~line 903) for the AI `triggers` skill content. Add `('{Kind}Trigger', '{kind}_trigger')` there too
- **`system_prompts/generate.py`** `schema_names` (~line 1192) — add `'{Kind}Trigger'` (add `'New{Kind}Trigger'` only if the OpenAPI declares one; GCP and Azure don't)
- Run `python3 system_prompts/generate.py` — this rewrites `cli/src/guidance/skills.ts` and all `auto-generated/` docs. Commit the regenerated files
## 11. Validation
Run all of these before declaring done:
```bash
# Backend
cd backend
cargo check --features enterprise,{kind}_trigger,private # minimal
cargo check --features enterprise,azure_trigger,private,gcp_trigger,http_trigger,mqtt_trigger,postgres_trigger,sqs_trigger,kafka,nats,smtp,websocket # full
# SQLx offline data (never run `cargo sqlx prepare` directly — use the wrapper)
./update_sqlx.sh
# Frontend
cd frontend
npm run generate-backend-client
npm run check:fast
```
Smoke test in the UI: create a trigger, save, check it appears in sidebar + search, delete, re-create via CLI `wmill sync`.
## 12. Common pitfalls
- **Forgetting feature gates in `workspaced_unauthed_service()`** — the surrounding `#[cfg(any(...))]` expression must include your feature flag, not just the inner `#[cfg]` on the route
- **`.route(path, ...).route(path, ...)` with same path and different methods** — older axum replaced; use `.route(path, post(h1).options(h2))` to chain methods on the same `MethodRouter`
- **`on:event` directives** — legacy Svelte 4, no-op in runes mode. Use callback props (`onSelected`, `onConfigChange`)
- **`$bindable(default_value)` on optional props** — banned by project CLAUDE.md. Use `$bindable()` + `$derived(prop ?? default)` instead
- **CORS layer intercepting OPTIONS** — tower-http CorsLayer short-circuits OPTIONS before reaching your handler. For server-to-server webhook endpoints, drop the CORS layer entirely (CORS is browser-only)
- **DeliveryAttributeMappings / custom headers for auth** — prefer HMAC or sha256-hashed shared secrets over opaque JWTs when the provider doesn't support signed tokens natively. Store only the hash; regenerate secret on every save
- **ARM / API resource-listing cascades** — if the trigger's resource type is deep (Azure: subscription → RG → namespace → topic), offer dropdowns in the UI populated from the provider's APIs using the user's credential resource
- **Clearing stale selections on dependency change** — when a dropdown's underlying data reloads (e.g., user changes SP or edition), clear selections that no longer match the new list
- **Workspace-scoped tag compatibility** — if the trigger has tags, verify forked workspaces handle them (see commit `0773b5bc85` for a historical fix)
## 13. EE file split
If the trigger is enterprise-only, the code lives in `windmill-ee-private__worktrees/.../windmill-trigger-{kind}/src/*_ee.rs` and is symlinked into the OSS tree. The `windmill-ee-private__worktrees/` directory holds the real files; changes propagate via symlinks. See `docs/enterprise.md` for the workflow.
## 14. Final checklist before PR
- [ ] Migration up/down tested (revert + re-apply)
- [ ] `./update_sqlx.sh` committed the updated `.sqlx/` offline data
- [ ] `cargo check` passes with your feature flag + with all trigger features
- [ ] `npm run check:fast` passes
- [ ] Trigger visible in sidebar with correct icon weight (not oversized/colored — use `currentColor`)
- [ ] Create, edit, delete flow all work in the UI
- [ ] Capture button works (if push-capable)
- [ ] Trigger appears in `/get_used_triggers` → sidebar pulse
- [ ] `wmill sync pull` + `wmill sync push` both round-trip the trigger
- [ ] `wmill trigger list` includes it
- [ ] OpenAPI schemas are complete (no `null` in generated types)
+3 -2
View File
@@ -1,6 +1,5 @@
---
name: commit
user_invocable: true
description: Create a git commit with conventional commit format. MUST use anytime you want to commit changes.
---
@@ -53,6 +52,8 @@ chore: upgrade sqlx to 0.7
4. Stage ONLY the modified/relevant files: `git add <file1> <file2> ...`
5. Create the commit with conventional format:
```bash
git commit -m "<type>: <description>"
git commit -m "<type>: <description>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>"
```
6. Run `git status` to verify the commit succeeded
+53 -54
View File
@@ -1,98 +1,97 @@
---
name: local-review
description: Code review the current PR (or branch diff against main) for bugs, security, and AGENTS.md compliance. MUST use when asked to review code.
description: Code review a pull request for bugs and CLAUDE.md compliance. MUST use when asked to review code.
---
# Local Code Review
# Local Code Review Skill
Run the same review locally that the GitHub auto-review actions run on PRs (Claude / Codex / Pi). The review policy lives in `REVIEW.md`.
Review a pull request for real bugs and CLAUDE.md compliance violations. This review targets HIGH SIGNAL issues only.
**Why a subagent**: the review MUST run in a fresh context — not inline in the current session. If the user has been iterating on the diff, the main session has absorbed their reasoning and rationalizations, so it anchors and misses things CI catches. A subagent starts cold, like CI does.
## Review Philosophy
## Steps
- **Only flag issues you are certain about.** If you are not sure an issue is real, do not flag it. False positives erode trust and waste reviewer time.
- Think like a senior engineer doing a final review — flag things that would cause incidents, not things that are merely imperfect.
1. **Determine the PR scope** (cheap, do this in the main session):
- If an argument is provided, treat it as a PR number or branch.
- Otherwise, detect from the current branch vs `main`.
- Confirm the PR/branch exists (`gh pr view <n>` or `git rev-parse <branch>`).
## What to Flag
2. **Delegate the review to a fresh-context subagent** with a self-contained prompt. The prompt MUST include:
- The PR number or branch name to review.
- The instruction to read `REVIEW.md` first for the policy, then `AGENTS.md` files in directories touched by the diff.
- The exact output format (see below).
- Whether `--comment` was requested (so the subagent emits inline-comment payloads if needed).
- Any "Additional reviewer instructions" the user provided.
- Code that won't compile or parse (syntax errors, type errors, missing imports)
- Code that will definitely produce wrong results regardless of inputs
- Clear, unambiguous CLAUDE.md violations (quote the exact rule being violated)
- Security issues in introduced code (injection, auth bypass, data exposure)
- Incorrect logic that will fail in production
- **Claude Code**: use the `Agent` tool with `subagent_type: branch-diff-reviewer` (read-only tools, purpose-built for this). If unavailable, fall back to `general-purpose`.
- **Codex / Pi**: if the CLI exposes a fresh-session subagent mechanism, use it. Otherwise tell the user to run the skill in a fresh CLI session and stop — running inline in the current session defeats the purpose.
## What NOT to Flag
3. **Receive the findings** from the subagent and relay them to the user verbatim. Do not re-summarize, re-judge, or filter — the whole point of fresh context is to surface what the main session would dismiss.
- Code style or quality concerns
- Potential issues that depend on specific inputs or runtime state
- Subjective suggestions or improvements
- Pre-existing issues not introduced by this PR
- Pedantic nitpicks a senior engineer wouldn't flag
- Issues a linter or type checker will catch
- General quality concerns unless explicitly prohibited in CLAUDE.md
- Issues silenced via lint ignore comments
4. **Post comments if `--comment` was requested**: use the `gh` commands below with the subagent's output as the body. The main session does the posting because the subagent is read-only.
## Execution Steps
## Subagent prompt template
1. **Determine the PR scope**:
- If an argument is provided, use it as the PR number or branch
- Otherwise, detect from the current branch vs main
- Run `gh pr view` if a PR exists, or use `git diff main...HEAD`
```
Review <PR #N | branch X> against main per the policy in REVIEW.md.
2. **Find relevant CLAUDE.md files**:
- Read the root `CLAUDE.md`
- Check for CLAUDE.md files in directories containing changed files
Steps:
1. Read REVIEW.md (repo root) for the full policy: severity triage, public-surface
checklist, AGENTS.md compliance, test coverage assessment.
2. Read AGENTS.md (repo root) and any AGENTS.md in directories touched by the diff.
3. Get the diff: `gh pr diff <N>` (if PR) or `git diff main...<branch>`.
4. Get context: `gh pr view <N>` (if PR) or `git log main..<branch> --oneline`.
5. Read changed files only when the diff alone is insufficient to validate a finding.
6. Self-validate each finding: "is this definitely a real issue a senior engineer
would flag?" Discard if uncertain.
7. Output findings in the exact format below. Do not modify any files.
3. **Get the diff and metadata**:
- `gh pr diff` or `git diff main...HEAD` for the full diff
- `gh pr view` or `git log main..HEAD --oneline` for context
<paste output format from below>
4. **Read changed files** where the diff alone is insufficient to understand context
<if --comment requested:>
Additionally emit a JSON array of inline comments suitable for the GitHub reviews
API, one per finding that maps to a specific line:
[{"path": "...", "line": N, "side": "RIGHT", "body": "[P1] ..."}, ...]
```
5. **Review for**:
- CLAUDE.md compliance — check each rule against the changed code
- Bugs and logic errors — will this code work correctly?
- Security issues — injection, auth, data exposure in new code
## Output format
6. **Self-validate each finding**: Before reporting, ask yourself:
- "Is this definitely a real issue, not a false positive?"
- "Would a senior engineer flag this in review?"
- If the answer to either is no, discard the finding
7. **Output findings** to the terminal (default) or post as PR comments (with `--comment` flag)
## Output Format
```
## Code review
<verdict line per REVIEW.md>
Found N issues:
1. [P0|P1|P2] <description>
1. <description> (<reason: CLAUDE.md adherence | bug | security>)
<file_path:line_number>
2. [P0|P1|P2] <description>
2. <description> (<reason>)
<file_path:line_number>
```
End with a `Test coverage` section per the shared policy.
If no issues are found:
```
## Code review
Good to merge.
No issues found. Checked for bugs, security, and AGENTS.md compliance.
No issues found. Checked for bugs and CLAUDE.md compliance.
```
## Posting comments (`--comment`)
## Posting Comments (--comment flag)
For a top-level PR comment:
If the user passes `--comment`, post findings as inline PR comments using:
```bash
gh pr review --comment --body "<summary from subagent>"
gh pr review --comment --body "<summary>"
```
For inline comments on specific lines (using the JSON the subagent emitted):
Or for inline comments on specific lines:
```bash
gh api repos/{owner}/{repo}/pulls/{pr}/reviews \
-f body="<summary>" -f event="COMMENT" -f comments="<json from subagent>"
gh api repos/{owner}/{repo}/pulls/{pr}/reviews -f body="<summary>" -f event="COMMENT" -f comments="[...]"
```
+1 -12
View File
@@ -607,18 +607,7 @@ In `frontend/src/lib/components/triggers/TriggersEditor.svelte`:
Add your service to the `nativeTriggerServices` map in `deleteDeployedTrigger()`. Native triggers use `NativeTriggerService.deleteNativeTrigger({ workspace, serviceName, externalId })` instead of the standard `path`-based delete.
### Step 17: Update `getUsedTriggers` for Sidebar Visibility
The sidebar (`frontend/src/lib/components/sidebar/SidebarContent.svelte`) shows native-trigger links only if `$usedTriggerKinds` includes the service — without this, your trigger page will never appear in the nav bar even when triggers exist.
1. **Backend** — add `{service}_used: bool` to the `UsedTriggers` struct and SELECT in `backend/windmill-api-workspaces/src/workspaces.rs::get_used_triggers()`:
```rust
EXISTS(SELECT 1 FROM native_trigger WHERE workspace_id = $1 AND service_name = '{service}'::native_trigger_service) AS "{service}_used!"
```
2. **OpenAPI** — add `{service}_used: boolean` to the response schema for `GET /w/{workspace}/workspaces/used_triggers` (under both `properties` and `required`).
3. **Layout** — in `frontend/src/routes/(root)/(logged)/+layout.svelte::loadUsedTriggerKinds()`, destructure `{service}_used` and push `'{service}'` to `usedKinds`.
### Step 18: Update OpenAPI Spec and Regenerate Types
### Step 17: Update OpenAPI Spec and Regenerate Types
Add to `JobTriggerKind` enum in `backend/windmill-api/openapi.yaml`, then:
+13 -45
View File
@@ -1,6 +1,5 @@
---
name: pr
user_invocable: true
description: Open a draft pull request on GitHub. MUST use when you want to create/open a PR.
---
@@ -51,59 +50,22 @@ The body MUST be explicit about what changed. Structure:
## Test plan
- [ ] <How to verify change 1>
- [ ] <How to verify change 2>
---
Generated with [Claude Code](https://claude.com/claude-code)
```
The harness/tooling that invoked the skill may add its own attribution trailer; the skill itself does not prescribe one.
## Screenshots (required for frontend changes)
If `git diff main...HEAD --name-only` matches `^frontend/`, the PR body **must** include
screenshots of the affected UI. Skip only when there is no visible UI effect (types,
tests, build config) — and say so in the body.
1. Verify the change in the browser (AGENTS.md → "Verifying Frontend Changes").
2. Screenshot each affected page with `mcp__playwright__browser_take_screenshot` (save to a file).
3. Host each image and get its Markdown embed by pushing to the public
`windmill-labs/agent-screenshots-internal` repo. **Pipe base64 through stdin**
passing it as `-f content=…` fails with `argument list too long` on real images:
```bash
REPO=windmill-labs/agent-screenshots-internal
IMG=screenshot.png # repeat per page
DEST="shots/$(git branch --show-current)/$(date +%s)-$(basename "$IMG")"
base64 -w0 "$IMG" | jq -Rs --arg m "add $DEST" '{message:$m, content:.}' \
| gh api -X PUT "repos/$REPO/contents/$DEST" --input - >/dev/null
echo "![$(basename "$IMG" .png)](https://raw.githubusercontent.com/$REPO/main/$DEST)"
```
Derive `$DEST` from the file name (as above) so distinct pages never collide — a
fixed name would make same-second uploads reuse one path, and the second `PUT`
then 422s (the Contents API needs the existing file's `sha` to overwrite).
4. Put the printed `![]()` lines under a `## Screenshots` heading in the PR body.
Requires `gh` (`repo` scope), `jq`, `base64` — all in the devShell. The host repo is
public (so the raw URLs render for reviewers without a token) and its history is
permanent — **never screenshot pages that show secrets or sensitive values** (workspace
variables, resource values, instance settings, OAuth/SMTP config); deleting the file
can't undo an accidental capture. (GitHub's drag-and-drop uploader needs a browser
session and can't be driven from a token.)
If `gh` can't push to the host repo (e.g. a CI token scoped only to `windmill`), do
**not** fail the PR or skip silently — hand the upload to the user, who has push access,
and continue once they confirm it's done.
## Execution Steps
1. Run `git status` to check for uncommitted changes
2. Run `git log main..HEAD --oneline` to see all commits in this branch
3. Run `git diff main...HEAD` to see the full diff against main
4. **Invoke the `local-review` skill** before creating the PR (`/local-review` in Claude Code, `$local-review` in Codex, `pi --skill local-review` / `/skill:local-review` in Pi). If issues are found, fix them and commit before proceeding. Do not skip this step.
5. **Screenshots for frontend changes**: if `git diff main...HEAD --name-only` matches `^frontend/`, capture and embed screenshots of the affected UI per "Screenshots" above before writing the PR body (skip only if there is no visible UI effect).
6. Check if remote branch exists and is up to date:
4. Check if remote branch exists and is up to date:
```bash
git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || echo "no upstream"
```
7. Push to remote if needed: `git push -u origin HEAD`
8. Create draft PR using gh CLI:
5. Push to remote if needed: `git push -u origin HEAD`
6. Create draft PR using gh CLI:
```bash
gh pr create --draft --title "<type>: <description>" --body "$(cat <<'EOF'
## Summary
@@ -116,10 +78,13 @@ and continue once they confirm it's done.
## Test plan
- [ ] <test 1>
- [ ] <test 2>
---
Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```
9. Return the PR URL to the user
7. Return the PR URL to the user
## EE Companion PR (when `*_ee.rs` files were modified)
@@ -135,6 +100,9 @@ Follow the full EE PR workflow in `docs/enterprise.md`. The key PR-specific deta
```bash
gh pr create --draft --repo windmill-labs/windmill-ee-private --title "<type>: <description>" --body "$(cat <<'EOF'
Companion PR for windmill-labs/windmill#<PR_NUMBER>
---
Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```
-1
View File
@@ -1,6 +1,5 @@
---
name: refine
user_invocable: true
description: End-of-session reflection. Reviews friction encountered during the session and proposes updates to docs/ to capture lessons learned.
---
-4
View File
@@ -78,7 +78,3 @@ Use the Svelte MCP tools when working on Svelte code:
2. **get-documentation**: Fetch relevant sections based on use_cases
3. **svelte-autofixer**: MUST use on all Svelte code before finalizing — keep calling until no issues
4. **playground-link**: Only after user confirms and code was NOT written to project files
## Verifying in the Browser
After changing Svelte code, use the **Playwright MCP** (`mcp__playwright__*`) to drive the running frontend and confirm the change works. See AGENTS.md → "Verifying Frontend Changes" for the full flow. Use `playwright` (headless) on devboxes; `playwright-headed` when a display is available.
-82
View File
@@ -1,82 +0,0 @@
---
name: update-sqlx
description: How to safely update SQLx offline query cache. MUST use when SQL queries change.
---
# SQLx Offline Query Cache
Windmill uses `SQLX_OFFLINE=true` in CI, which requires all `sqlx::query!` / `sqlx::query_as!` macros to have matching cached query data in `backend/.sqlx/`.
## When to Run
Run after any change to SQL queries in Rust source files. Without it, CI will fail with:
```
error: `SQLX_OFFLINE=true` but there is no cached data for this query
```
## The Problem
`cargo sqlx prepare --workspace` **deletes all existing cache files** and regenerates only the ones found in the current compilation. If you don't compile with every feature flag (especially `private` for EE files), you will **silently delete EE query caches**, breaking CI for enterprise tests.
The standard `./update_sqlx.sh` script tries to compile with all features, but it often fails locally because the EE symlinks can be out of sync with `main`.
## Safe Procedure
Always preserve the existing EE caches from `origin/main`. Use this workflow:
```bash
cd backend
# 1. Restore the full cache from main (includes EE caches)
git checkout origin/main -- .sqlx/
# 2. Run prepare with OSS features (what compiles locally)
# This regenerates OSS caches to match your code changes.
cargo sqlx prepare --workspace -- --workspace --features all_sqlx_features
# 3. Restore any EE caches that were deleted in step 2.
# These are files present in origin/main but missing after prepare.
git ls-tree origin/main backend/.sqlx/ \
| awk '{print $4}' | sed 's|backend/\.sqlx/||' | sort > /tmp/main_files.txt
find backend/.sqlx -name "*.json" -printf '%P\n' | sort > /tmp/current_files.txt
comm -23 /tmp/main_files.txt /tmp/current_files.txt > /tmp/missing_files.txt
while read f; do
git show "origin/main:backend/.sqlx/$f" > "backend/.sqlx/$f"
done < /tmp/missing_files.txt
# 4. Verify nothing was lost from main
find backend/.sqlx -name "*.json" -printf '%P\n' | sort > /tmp/current_files.txt
comm -23 /tmp/main_files.txt /tmp/current_files.txt | wc -l
# Should output: 0
```
## If EE Compiles Locally
If your EE repo happens to be in sync, you can use the full script (faster):
```bash
cd backend
./update_sqlx.sh
```
But if it fails with EE compilation errors, use the safe procedure above.
## What NOT to Do
- **Never** run `cargo sqlx prepare --workspace` with only OSS features and commit the result — it will delete EE caches.
- **Never** set `SQLX_OFFLINE=true` for local `cargo sqlx prepare` — use a live database per CLAUDE.md. (CI runs with `SQLX_OFFLINE=true`, which is why the cache must be complete.)
- **Never** skip the verification step (step 4 above).
## Verification
After committing, the diff against `origin/main` should show:
- A few **new** cache files (for your changed queries)
- A few **deleted** cache files (for old queries that no longer exist)
- **Zero** net deletions from the EE cache set
```bash
git diff origin/main --stat backend/.sqlx/
```
+1 -18
View File
@@ -16,23 +16,6 @@ command="$(echo "$input" | jq -r '.tool_input.command // empty')"
if [[ "$command" =~ ^git\ (push|reset|revert|checkout|merge|rebase|commit|add) ]]; then
branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
if [[ "$branch" == "main" ]]; then
echo "BLOCK: You are on the main branch. Create or switch to a feature branch first." >&2
exit 2
fi
fi
# Block force-push targeting main from any branch.
if [[ "$command" =~ ^git[[:space:]]+push([[:space:]]|$) ]]; then
has_force=false
if [[ "$command" =~ (--force([[:space:]]|=|$)|--force-with-lease|[[:space:]]-f([[:space:]]|$)) ]]; then
has_force=true
fi
# `+ref` refspec syntax is also a force push.
if [[ "$command" =~ [[:space:]]\+[A-Za-z] ]]; then
has_force=true
fi
if $has_force && [[ "$command" =~ (^|[[:space:]:])\+?main([[:space:]]|$) ]]; then
echo "BLOCK: Force-push to main is not allowed via Claude. Run it yourself if you really mean to." >&2
exit 2
echo "BLOCK: You are on the main branch. Create or switch to a feature branch first."
fi
fi
+24 -3
View File
@@ -1,4 +1,25 @@
# Claude output format
# Code Review Instructions
- Use inline comments at the relevant lines for specific issues.
- Use a top-level comment for the summary, severity-tagged finding list, AGENTS.md compliance check, and the test-coverage assessment.
Review this pull request and provide comprehensive feedback.
## Focus Areas
- **Code quality and best practices** — does the code follow established patterns?
- **Potential bugs or issues** — will this code work correctly in all cases?
- **Performance considerations** — are there unnecessary allocations, N+1 queries, or bottlenecks?
- **Security implications** — injection, auth bypass, data exposure?
## CLAUDE.md Compliance
Read all relevant CLAUDE.md files (root and in directories containing changed files). Check each rule against the changed code. Quote the exact rule when flagging a violation.
## Review Guidelines
- Provide detailed feedback using inline comments for specific issues
- Use top-level comments for general observations or praise
- Only flag issues introduced by this PR, not pre-existing problems
- Self-validate each finding: "Is this definitely a real issue?" If uncertain, discard it
## Testing Instructions
At the end of your review, add complete instructions to reproduce the added changes through the app interface. These instructions will be given to a tester so they can verify the changes. It should be a short descriptive text (not a step-by-step or a list) on how to navigate the app (what page, what action, what input, etc.) to see the changes.
+3 -30
View File
@@ -44,25 +44,7 @@
"Bash(git merge:*)",
"Bash(git rebase:*)",
"Bash(git add:*)",
"Bash(git commit:*)",
"Read(/tmp/**)",
"Write(/tmp/**)",
"Edit(/tmp/**)",
"Bash(rm:/tmp/*)",
"Bash(rm:/tmp/**)",
"Bash(rmdir:/tmp/*)",
"Bash(mkdir:/tmp/*)",
"Bash(mkdir:/tmp/**)",
"Bash(cp:/tmp/*)",
"Bash(cp:/tmp/**)",
"Bash(mv:/tmp/*)",
"Bash(mv:/tmp/**)",
"Bash(touch:/tmp/*)",
"Bash(touch:/tmp/**)",
"Bash(chmod:/tmp/*)",
"Bash(chmod:/tmp/**)",
"Bash(tar * /tmp/*)",
"Bash(unzip * /tmp/*)"
"Bash(git commit:*)"
],
"deny": [
"Read(.env)",
@@ -73,10 +55,7 @@
"Read(**/*.pem)",
"Read(**/*.key)",
"Read(**/credentials.json)",
"Read(**/.secret*)",
"Read(**/.secrets*)",
"Read(**/*.secret)",
"Read(**/*.secrets)",
"Read(**/*secret*)",
"Edit(.env)",
"Edit(.env.*)",
"Edit(**/.env)",
@@ -90,13 +69,7 @@
"Bash(chown:*)",
"Bash(truncate:*)",
"Bash(shred:*)",
"Bash(unlink:*)",
"mcp__claude_ai_Stripe",
"mcp__claude_ai_Gmail",
"mcp__claude_ai_Google_Calendar",
"mcp__claude_ai_Google_Drive",
"mcp__claude_ai_Slack",
"mcp__claude_ai_Linear"
"Bash(unlink:*)"
]
},
"enableAllProjectMcpServers": true,
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/adding-a-trigger/SKILL.md
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/commit/SKILL.md
+60
View File
@@ -0,0 +1,60 @@
---
name: commit
user_invocable: true
description: Create a git commit with conventional commit format. MUST use anytime you want to commit changes.
---
# Git Commit Skill
Create a focused, single-line commit following conventional commit conventions.
## Instructions
1. **Analyze changes**: Run `git status` and `git diff` to understand what was modified
2. **Stage only modified files**: Add files individually by name. NEVER use `git add -A` or `git add .`
3. **Write commit message**: Follow the conventional commit format as a single line
## Conventional Commit Format
```
<type>: <description>
```
### Types
- `feat`: New feature or capability
- `fix`: Bug fix
- `refactor`: Code change that neither fixes a bug nor adds a feature
- `docs`: Documentation only changes
- `style`: Formatting, missing semicolons, etc (no code change)
- `test`: Adding or correcting tests
- `chore`: Maintenance tasks, dependency updates, etc
- `perf`: Performance improvement
### Rules
- Message MUST be a single line (no multi-line messages)
- Description should be lowercase, imperative mood ("add" not "added")
- No period at the end
- Keep under 72 characters total
### Examples
```
feat: add token usage tracking for AI providers
fix: resolve null pointer in job executor
refactor: extract common validation logic
docs: update API endpoint documentation
chore: upgrade sqlx to 0.7
```
## Execution Steps
1. Run `git status` to see all changes
2. Run `git diff` to understand the changes in detail
3. Run `git log --oneline -5` to see recent commit style
4. Stage ONLY the modified/relevant files: `git add <file1> <file2> ...`
5. Create the commit with conventional format:
```bash
git commit -m "<type>: <description>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>"
```
6. Run `git status` to verify the commit succeeded
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/local-review/SKILL.md
+69
View File
@@ -0,0 +1,69 @@
---
name: local-review
user_invocable: true
description: Code review a pull request for bugs and CLAUDE.md compliance. MUST use when asked to review code.
---
# Local Code Review Skill
Run the same review locally that the GitHub Claude Auto Review action runs on PRs. The shared review instructions live in `.claude/review-prompt.md` — read that file first and follow its instructions.
## Execution Steps
1. **Read `.claude/review-prompt.md`** for the review criteria and focus areas
2. **Determine the PR scope**:
- If an argument is provided, use it as the PR number or branch
- Otherwise, detect from the current branch vs main
- Run `gh pr view` if a PR exists, or use `git diff main...HEAD`
3. **Get the diff and metadata**:
- `gh pr diff` or `git diff main...HEAD` for the full diff
- `gh pr view` or `git log main..HEAD --oneline` for context
4. **Read changed files** where the diff alone is insufficient to understand context
5. **Apply the review instructions from `.claude/review-prompt.md`**
6. **Self-validate each finding**: Before reporting, ask yourself:
- "Is this definitely a real issue, not a false positive?"
- "Would a senior engineer flag this in review?"
- If the answer to either is no, discard the finding
7. **Output findings** to the terminal (default) or post as PR comments (with `--comment` flag)
## Output Format
```
## Code review
Found N issues:
1. <description> (<reason: CLAUDE.md adherence | bug | security>)
<file_path:line_number>
2. <description> (<reason>)
<file_path:line_number>
```
If no issues are found:
```
## Code review
No issues found. Checked for bugs and CLAUDE.md compliance.
```
## Posting Comments (--comment flag)
If the user passes `--comment`, post findings as inline PR comments using:
```bash
gh pr review --comment --body "<summary>"
```
Or for inline comments on specific lines:
```bash
gh api repos/{owner}/{repo}/pulls/{pr}/reviews -f body="<summary>" -f event="COMMENT" -f comments="[...]"
```
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/native-trigger/SKILL.md
+782
View File
@@ -0,0 +1,782 @@
---
name: native-trigger
description: Guidance for adding native trigger services to Windmill. Use when implementing or modifying native trigger integrations across the backend and frontend.
---
# Skill: Adding Native Trigger Services
This skill provides comprehensive guidance for adding new native trigger services to Windmill. Native triggers allow external services (like Nextcloud, Google Drive, etc.) to trigger Windmill scripts/flows via webhooks or push notifications.
## Architecture Overview
The native trigger system consists of:
1. **Database Layer** - PostgreSQL tables and enum types
2. **Backend Rust Implementation** - Core trait, handlers, and service modules in the `windmill-native-triggers` crate
3. **Frontend Svelte Components** - Configuration forms and UI components
### Key Files
| Component | Path |
|-----------|------|
| Core module with `External` trait | `backend/windmill-native-triggers/src/lib.rs` |
| Generic CRUD handlers | `backend/windmill-native-triggers/src/handler.rs` |
| Background sync logic | `backend/windmill-native-triggers/src/sync.rs` |
| OAuth/workspace integration | `backend/windmill-native-triggers/src/workspace_integrations.rs` |
| Re-export shim (windmill-api) | `backend/windmill-api/src/native_triggers/mod.rs` |
| TriggerKind enum | `backend/windmill-common/src/triggers.rs` |
| JobTriggerKind enum | `backend/windmill-common/src/jobs.rs` |
| Frontend service registry | `frontend/src/lib/components/triggers/native/utils.ts` |
| Frontend trigger utilities | `frontend/src/lib/components/triggers/utils.ts` |
| Trigger badges (icons + counts) | `frontend/src/lib/components/graph/renderers/triggers/TriggersBadge.svelte` |
| Workspace integrations UI | `frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte` |
| OAuth config form component | `frontend/src/lib/components/workspaceSettings/OAuthClientConfig.svelte` |
| OpenAPI spec | `backend/windmill-api/openapi.yaml` |
| Reference: Nextcloud module | `backend/windmill-native-triggers/src/nextcloud/` |
| Reference: Google module | `backend/windmill-native-triggers/src/google/` |
### Crate Structure
The native trigger code lives in the `windmill-native-triggers` crate (`backend/windmill-native-triggers/`). The `windmill-api` crate re-exports everything via a shim:
```rust
// backend/windmill-api/src/native_triggers/mod.rs
pub use windmill_native_triggers::*;
```
All new service modules go in `backend/windmill-native-triggers/src/`.
---
## Core Concepts
### The `External` Trait
Every native trigger service implements the `External` trait defined in `lib.rs`:
```rust
#[async_trait]
pub trait External: Send + Sync + 'static {
// Associated types:
type ServiceConfig: Debug + DeserializeOwned + Serialize + Send + Sync;
type TriggerData: Debug + Serialize + Send + Sync;
type OAuthData: DeserializeOwned + Serialize + Clone + Send + Sync;
type CreateResponse: DeserializeOwned + Send + Sync;
// Constants:
const SUPPORT_WEBHOOK: bool;
const SERVICE_NAME: ServiceName;
const DISPLAY_NAME: &'static str;
const TOKEN_ENDPOINT: &'static str;
const REFRESH_ENDPOINT: &'static str;
const AUTH_ENDPOINT: &'static str;
// Required methods:
async fn create(&self, w_id, oauth_data, webhook_token, data, db, tx) -> Result<Self::CreateResponse>;
async fn update(&self, w_id, oauth_data, external_id, webhook_token, data, db, tx) -> Result<serde_json::Value>;
async fn get(&self, w_id, oauth_data, external_id, db, tx) -> Result<Self::TriggerData>;
async fn delete(&self, w_id, oauth_data, external_id, db, tx) -> Result<()>;
async fn exists(&self, w_id, oauth_data, external_id, db, tx) -> Result<bool>;
async fn maintain_triggers(&self, db, workspace_id, triggers, oauth_data, synced, errors);
fn external_id_and_metadata_from_response(&self, resp) -> (String, Option<serde_json::Value>);
// Methods with defaults:
async fn prepare_webhook(&self, db, w_id, headers, body, script_path, is_flow) -> Result<PushArgsOwned>;
fn service_config_from_create_response(&self, data, resp) -> Option<serde_json::Value>;
fn additional_routes(&self) -> axum::Router;
async fn http_client_request<T, B>(&self, url, method, workspace_id, tx, db, headers, body) -> Result<T>;
}
```
Key design points:
- **`update()` returns `serde_json::Value`** - the resolved service_config to store. Each service is responsible for building the final config.
- **`maintain_triggers()`** - periodic background maintenance. Each service implements its own strategy (Nextcloud: reconcile with external state; Google: renew expiring channels).
- **No `list_all()` in the trait** - services that need it (Nextcloud) implement it privately; services that don't (Google) use different maintenance strategies.
- **No `get_external_id_from_trigger_data()` or `extract_service_config_from_trigger_data()`** - removed in favor of the `maintain_triggers` pattern.
### Create Lifecycle: Two Paths
The `create_native_trigger` handler in `handler.rs` supports two creation flows, controlled by `service_config_from_create_response()`:
**Path A: Short (Google pattern)** - `service_config_from_create_response()` returns `Some(config)`:
1. `create()` registers on external service
2. `external_id_and_metadata_from_response()` extracts the ID
3. `service_config_from_create_response()` builds the config directly from input data + response metadata
4. Stores trigger in DB -- done, no extra round-trip
Use this when the external_id is known before the create call (e.g., Google generates the channel_id as a UUID upfront and includes it in the webhook URL).
**Path B: Long (Nextcloud pattern)** - `service_config_from_create_response()` returns `None` (default):
1. `create()` registers on external service (webhook URL has no external_id yet)
2. `external_id_and_metadata_from_response()` extracts the ID
3. `update()` is called to fix the webhook URL with the now-known external_id
4. `update()` returns the resolved service_config
5. Stores trigger in DB
Use this when the external_id is assigned by the remote service and the webhook URL needs to be corrected after creation.
### OAuth Token Storage (Three-Table Pattern)
OAuth tokens are stored across three tables, NOT in `workspace_integrations.oauth_data` directly:
| Table | What's Stored |
|-------|---------------|
| `workspace_integrations` | `oauth_data` JSON with `base_url`, `client_id`, `client_secret`, `instance_shared` flag; `resource_path` pointing to the variable |
| `variable` | Encrypted `access_token` (at the path stored in `resource_path`), linked to `account` via `account` column |
| `account` | `refresh_token`, keyed by `workspace_id` + `client` (service name) + `is_workspace_integration = true` |
The `decrypt_oauth_data()` function in `lib.rs` assembles these into a unified struct:
```rust
pub struct OAuthConfig {
pub base_url: String,
pub access_token: String, // decrypted from variable
pub refresh_token: Option<String>, // from account table
pub client_id: String, // from oauth_data or instance settings
pub client_secret: String, // from oauth_data or instance settings
}
```
Instance-level sharing: when `oauth_data.instance_shared == true`, `client_id` and `client_secret` are read from global settings instead of workspace_integrations.
### URL Resolution
The `resolve_endpoint()` helper handles both absolute and relative OAuth URLs:
```rust
pub fn resolve_endpoint(base_url: &str, endpoint: &str) -> String {
if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
endpoint.to_string() // Google: absolute URLs
} else {
format!("{}{}", base_url, endpoint) // Nextcloud: relative paths
}
}
```
### ServiceName Methods
`ServiceName` is the central registry enum. Each variant must implement these match arms:
| Method | Purpose |
|--------|---------|
| `as_str()` | Lowercase identifier (e.g., `"google"`) |
| `as_trigger_kind()` | Maps to `TriggerKind` enum |
| `as_job_trigger_kind()` | Maps to `JobTriggerKind` enum |
| `token_endpoint()` | OAuth token endpoint (relative or absolute) |
| `auth_endpoint()` | OAuth authorization endpoint |
| `oauth_scopes()` | Space-separated OAuth scopes |
| `resource_type()` | Resource type for token storage (e.g., `"gworkspace"`) |
| `extra_auth_params()` | Extra OAuth params (e.g., Google needs `access_type=offline`, `prompt=consent`) |
| `integration_service()` | Maps to the workspace integration service (usually `*self`) |
| `TryFrom<String>` | Parse from string |
| `Display` | Delegates to `as_str()` |
---
## Step-by-Step Implementation Guide
### Step 1: Database Migration
Create a new migration file: `backend/migrations/YYYYMMDDHHMMSS_newservice_trigger.up.sql`
```sql
-- Add the service to the native_trigger_service enum
ALTER TYPE native_trigger_service ADD VALUE IF NOT EXISTS 'newservice';
-- Add to TRIGGER_KIND enum (used for trigger tracking)
ALTER TYPE TRIGGER_KIND ADD VALUE IF NOT EXISTS 'newservice';
-- Add to job_trigger_kind enum (used for job tracking)
ALTER TYPE job_trigger_kind ADD VALUE IF NOT EXISTS 'newservice';
```
Also create the corresponding down migration.
### Step 2: Update windmill-common Enums
#### `backend/windmill-common/src/triggers.rs`
Add variant to `TriggerKind` enum, and update `to_key()` and `fmt()` implementations.
#### `backend/windmill-common/src/jobs.rs`
Add variant to `JobTriggerKind` enum and update the `Display` implementation.
### Step 3: Backend Service Module
Create a new directory: `backend/windmill-native-triggers/src/newservice/`
#### `mod.rs` - Type Definitions
```rust
use serde::{Deserialize, Serialize};
pub mod external;
// pub mod routes; // Only if you need additional service-specific routes
/// OAuth data deserialized from the three-table pattern.
/// The actual structure is built by decrypt_oauth_data() from variable + account + workspace_integrations.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NewServiceOAuthData {
pub base_url: String, // from workspace_integrations.oauth_data
pub access_token: String, // decrypted from variable table
pub refresh_token: Option<String>, // from account table
// Note: client_id and client_secret are in OAuthConfig, not here
// unless the service needs them at runtime for API calls
}
/// Configuration provided by user when creating/updating a trigger.
/// Stored as JSON in native_trigger.service_config.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NewServiceConfig {
// Service-specific configuration fields
pub folder_path: String,
pub file_filter: Option<String>,
}
/// Data retrieved from the external service about a trigger.
/// Returned by the get() method and shown in the UI.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NewServiceTriggerData {
pub folder_path: String,
pub file_filter: Option<String>,
// Fields that shouldn't affect service_config comparison should use #[serde(skip_serializing)]
}
/// Response from external service when creating a trigger/webhook.
#[derive(Debug, Deserialize)]
pub struct CreateTriggerResponse {
pub id: String,
}
/// Handler struct (stateless, used for routing)
#[derive(Copy, Clone)]
pub struct NewService;
```
#### `external.rs` - External Trait Implementation
```rust
use async_trait::async_trait;
use reqwest::Method;
use sqlx::PgConnection;
use std::collections::HashMap;
use windmill_common::{
error::{Error, Result},
BASE_URL, DB,
};
use crate::{
generate_webhook_service_url, External, NativeTrigger, NativeTriggerData, ServiceName,
sync::{SyncError, TriggerSyncInfo},
};
use super::{NewService, NewServiceConfig, NewServiceOAuthData, NewServiceTriggerData, CreateTriggerResponse};
#[async_trait]
impl External for NewService {
type ServiceConfig = NewServiceConfig;
type TriggerData = NewServiceTriggerData;
type OAuthData = NewServiceOAuthData;
type CreateResponse = CreateTriggerResponse;
const SERVICE_NAME: ServiceName = ServiceName::NewService;
const DISPLAY_NAME: &'static str = "New Service";
const SUPPORT_WEBHOOK: bool = true;
const TOKEN_ENDPOINT: &'static str = "/oauth/token";
const REFRESH_ENDPOINT: &'static str = "/oauth/token";
const AUTH_ENDPOINT: &'static str = "/oauth/authorize";
async fn create(
&self,
w_id: &str,
oauth_data: &Self::OAuthData,
webhook_token: &str,
data: &NativeTriggerData<Self::ServiceConfig>,
db: &DB,
tx: &mut PgConnection,
) -> Result<Self::CreateResponse> {
let base_url = &*BASE_URL.read().await;
// external_id is None during create (we get it from the response)
let webhook_url = generate_webhook_service_url(
base_url, w_id, &data.script_path, data.is_flow,
None, Self::SERVICE_NAME, webhook_token,
);
let url = format!("{}/api/webhooks/create", oauth_data.base_url);
let payload = serde_json::json!({
"callback_url": webhook_url,
"folder_path": data.service_config.folder_path,
});
let response: CreateTriggerResponse = self
.http_client_request(&url, Method::POST, w_id, tx, db, None, Some(&payload))
.await?;
Ok(response)
}
/// Update returns the resolved service_config as JSON.
/// For services using the update+get pattern, call self.get() and serialize.
async fn update(
&self,
w_id: &str,
oauth_data: &Self::OAuthData,
external_id: &str,
webhook_token: &str,
data: &NativeTriggerData<Self::ServiceConfig>,
db: &DB,
tx: &mut PgConnection,
) -> Result<serde_json::Value> {
let base_url = &*BASE_URL.read().await;
let webhook_url = generate_webhook_service_url(
base_url, w_id, &data.script_path, data.is_flow,
Some(external_id), Self::SERVICE_NAME, webhook_token,
);
let url = format!("{}/api/webhooks/{}", oauth_data.base_url, external_id);
let payload = serde_json::json!({
"callback_url": webhook_url,
"folder_path": data.service_config.folder_path,
});
let _: serde_json::Value = self
.http_client_request(&url, Method::PUT, w_id, tx, db, None, Some(&payload))
.await?;
// Fetch back the updated state to get the resolved config
let trigger_data = self.get(w_id, oauth_data, external_id, db, tx).await?;
serde_json::to_value(&trigger_data)
.map_err(|e| Error::InternalErr(format!("Failed to serialize trigger data: {}", e)))
}
async fn get(
&self,
w_id: &str,
oauth_data: &Self::OAuthData,
external_id: &str,
db: &DB,
tx: &mut PgConnection,
) -> Result<Self::TriggerData> {
let url = format!("{}/api/webhooks/{}", oauth_data.base_url, external_id);
self.http_client_request::<_, ()>(&url, Method::GET, w_id, tx, db, None, None).await
}
async fn delete(
&self,
w_id: &str,
oauth_data: &Self::OAuthData,
external_id: &str,
db: &DB,
tx: &mut PgConnection,
) -> Result<()> {
let url = format!("{}/api/webhooks/{}", oauth_data.base_url, external_id);
let _: serde_json::Value = self
.http_client_request::<_, ()>(&url, Method::DELETE, w_id, tx, db, None, None)
.await
.or_else(|e| match &e {
Error::InternalErr(msg) if msg.contains("404") => Ok(serde_json::Value::Null),
_ => Err(e),
})?;
Ok(())
}
async fn exists(
&self,
w_id: &str,
oauth_data: &Self::OAuthData,
external_id: &str,
db: &DB,
tx: &mut PgConnection,
) -> Result<bool> {
match self.get(w_id, oauth_data, external_id, db, tx).await {
Ok(_) => Ok(true),
Err(Error::NotFound(_)) => Ok(false),
Err(e) => Err(e),
}
}
/// Background maintenance. Choose the right pattern for your service:
/// - For services with queryable external state: use reconcile_with_external_state()
/// - For channel-based services with expiration: implement renewal logic
async fn maintain_triggers(
&self,
db: &DB,
workspace_id: &str,
triggers: &[NativeTrigger],
oauth_data: &Self::OAuthData,
synced: &mut Vec<TriggerSyncInfo>,
errors: &mut Vec<SyncError>,
) {
// Option A: Reconcile with external state (Nextcloud pattern)
// Fetch all triggers from external service and compare with DB
let external_triggers = match self.list_all(workspace_id, oauth_data, db).await {
Ok(triggers) => triggers,
Err(e) => {
errors.push(SyncError {
resource_path: format!("workspace:{}", workspace_id),
error_message: format!("Failed to list triggers: {}", e),
error_type: "api_error".to_string(),
});
return;
}
};
// Convert to (external_id, config_json) pairs
let external_pairs: Vec<(String, serde_json::Value)> = external_triggers
.into_iter()
.map(|t| (t.id.clone(), serde_json::to_value(&t).unwrap_or_default()))
.collect();
crate::sync::reconcile_with_external_state(
db, workspace_id, Self::SERVICE_NAME, triggers, &external_pairs, synced, errors,
).await;
}
fn external_id_and_metadata_from_response(
&self,
resp: &Self::CreateResponse,
) -> (String, Option<serde_json::Value>) {
(resp.id.clone(), None)
}
// service_config_from_create_response: NOT overridden (returns None).
// This means the handler uses the update+get pattern after create.
// Override and return Some(...) to skip the update+get cycle (Google pattern).
}
impl NewService {
/// Private helper to list all triggers from the external service.
async fn list_all(
&self,
w_id: &str,
oauth_data: &<Self as External>::OAuthData,
db: &DB,
) -> Result<Vec<<Self as External>::TriggerData>> {
// Implementation depends on the external service's API
todo!()
}
}
```
### Step 4: Update lib.rs Registry
In `backend/windmill-native-triggers/src/lib.rs`:
```rust
// Service modules - add new services here:
#[cfg(feature = "native_trigger")]
pub mod newservice; // <-- Add this
// ServiceName enum - add variant:
pub enum ServiceName {
Nextcloud,
Google,
NewService, // <-- Add this
}
// Then add match arms in ALL ServiceName methods:
// as_str(), as_trigger_kind(), as_job_trigger_kind(), token_endpoint(),
// auth_endpoint(), oauth_scopes(), resource_type(), extra_auth_params(),
// integration_service(), TryFrom<String>, Display
```
### Step 5: Update handler.rs Routes
In `backend/windmill-native-triggers/src/handler.rs`:
```rust
pub fn generate_native_trigger_routers() -> Router {
// ...
#[cfg(feature = "native_trigger")]
{
use crate::newservice::NewService;
return router
.nest("/nextcloud", service_routes(NextCloud))
.nest("/google", service_routes(Google))
.nest("/newservice", service_routes(NewService)); // <-- Add this
}
// ...
}
```
### Step 6: Update sync.rs
In `backend/windmill-native-triggers/src/sync.rs`:
```rust
pub async fn sync_all_triggers(db: &DB) -> Result<BackgroundSyncResult> {
// ...
#[cfg(feature = "native_trigger")]
{
use crate::newservice::NewService;
// ... existing service syncs ...
// New service sync
let (service_name, result) = sync_service_triggers(db, NewService).await;
total_synced += result.synced_triggers.len();
total_errors += result.errors.len();
service_results.insert(service_name, result);
}
// ...
}
```
### Step 7: Frontend Service Registry
In `frontend/src/lib/components/triggers/native/utils.ts`:
Add to `NATIVE_TRIGGER_SERVICES`, `getTriggerIconName()`, and `getServiceIcon()`.
### Step 8: Frontend Trigger Form Component
Create: `frontend/src/lib/components/triggers/native/services/newservice/NewServiceTriggerForm.svelte`
### Step 9: Frontend Icon Component
Create: `frontend/src/lib/components/icons/NewServiceIcon.svelte`
### Step 10: Update NativeTriggerEditor
Check `frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte` to ensure it dynamically loads form components based on service name.
### Step 11: Workspace Integration UI
Add your service to the `supportedServices` map in `frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte`:
```typescript
const supportedServices: Record<string, ServiceConfig> = {
// ... existing services ...
newservice: {
name: 'newservice',
displayName: 'New Service',
description: 'Connect to New Service for triggers',
icon: NewServiceIcon,
docsUrl: 'https://www.windmill.dev/docs/integrations/newservice',
requiresBaseUrl: false, // false for cloud services, true for self-hosted
setupInstructions: [
'Step 1: Create an OAuth app on the service',
'Step 2: Configure the redirect URI shown below',
'Step 3: Enter the client credentials below'
]
}
}
```
### Step 12: Update `frontend/src/lib/components/triggers/utils.ts`
Update ALL of these maps/functions:
1. `triggerIconMap` - import and add icon
2. `triggerDisplayNamesMap` - add display name
3. `triggerTypeOrder` in `sortTriggers()` - add type
4. `getLightConfig()` - add case for your service
5. `getTriggerLabel()` - add case for your service
6. `jobTriggerKinds` - add to array
7. `countPropertyMap` - add count property
8. `triggerSaveFunctions` - add save function
### Step 13: Update TriggersBadge Component
In `frontend/src/lib/components/graph/renderers/triggers/TriggersBadge.svelte`:
1. Import the icon
2. Add to `baseConfig` with `countKey` (the dynamic `availableNativeServices` loop does NOT set `countKey`)
3. Add to the `allTypes` array
### Step 14: Update TriggersWrapper.svelte
In `frontend/src/lib/components/triggers/TriggersWrapper.svelte`:
Add a `{:else if selectedTrigger.type === 'yourservice'}` case that renders `<NativeTriggersPanel service="yourservice" ...>` with the same props pattern as the existing native trigger cases (e.g., `nextcloud`).
### Step 15: Update AddTriggersButton.svelte
In `frontend/src/lib/components/triggers/AddTriggersButton.svelte`:
1. Add `yourserviceAvailable` state variable
2. Add `setYourserviceState()` async function using `isServiceAvailable('yourservice', $workspaceStore!)`
3. Call it at module level
4. Add a dropdown entry to `addTriggerItems` with `hidden: !yourserviceAvailable`
### Step 16: Update TriggersEditor.svelte Delete Handling
In `frontend/src/lib/components/triggers/TriggersEditor.svelte`:
Add your service to the `nativeTriggerServices` map in `deleteDeployedTrigger()`. Native triggers use `NativeTriggerService.deleteNativeTrigger({ workspace, serviceName, externalId })` instead of the standard `path`-based delete.
### Step 17: Update OpenAPI Spec and Regenerate Types
Add to `JobTriggerKind` enum in `backend/windmill-api/openapi.yaml`, then:
```bash
cd frontend && npm run generate-backend-client
```
---
## Special Patterns
### Unified Service with `trigger_type` (Google Pattern)
When a single service handles multiple trigger types (e.g., Google Drive + Calendar share OAuth and API patterns), use a single `ServiceName` variant with a discriminator field:
```rust
pub enum GoogleTriggerType { Drive, Calendar }
pub struct GoogleServiceConfig {
pub trigger_type: GoogleTriggerType,
// Drive-specific fields (only used when trigger_type = Drive)
pub resource_id: Option<String>,
pub resource_name: Option<String>,
// Calendar-specific fields (only used when trigger_type = Calendar)
pub calendar_id: Option<String>,
pub calendar_name: Option<String>,
// Metadata set after creation
pub google_resource_id: Option<String>,
pub expiration: Option<String>,
}
```
Branch in trait methods based on `trigger_type`. Frontend uses a `ToggleButtonGroup` to switch between types. This keeps the codebase simpler (one service, one OAuth flow, one set of routes).
See `backend/windmill-native-triggers/src/google/` for the reference implementation.
### Skipping update+get After Create (Google Pattern)
Override `service_config_from_create_response()` to return `Some(config)` when the external_id is known before the create call:
```rust
fn service_config_from_create_response(
&self,
data: &NativeTriggerData<Self::ServiceConfig>,
resp: &Self::CreateResponse,
) -> Option<serde_json::Value> {
// Clone input config, add metadata from response
let mut config = data.service_config.clone();
config.google_resource_id = Some(resp.resource_id.clone());
config.expiration = Some(resp.expiration.clone());
Some(serde_json::to_value(&config).unwrap())
}
```
### Services with Absolute OAuth Endpoints (Google)
Unlike self-hosted services where OAuth endpoints are relative paths appended to `base_url`, services like Google have absolute URLs:
```rust
// Nextcloud: relative paths
ServiceName::Nextcloud => "/apps/oauth2/api/v1/token",
// Google: absolute URLs
ServiceName::Google => "https://oauth2.googleapis.com/token",
```
The `resolve_endpoint()` function handles both. For services with absolute endpoints:
- `base_url` can be empty
- `requiresBaseUrl: false` in the frontend workspace integration config
- Add `extra_auth_params()` if needed (Google requires `access_type=offline` and `prompt=consent`)
### Channel-Based Push Notifications with Renewal (Google Pattern)
For services using expiring watch channels instead of persistent webhooks:
1. Store expiration in `service_config` (as part of `ServiceConfig`)
2. In `maintain_triggers()`, implement renewal logic instead of using `reconcile_with_external_state()`:
```rust
async fn maintain_triggers(&self, db, workspace_id, triggers, oauth_data, synced, errors) {
for trigger in triggers {
if should_renew_channel(trigger) {
self.renew_channel(db, trigger, oauth_data).await;
}
}
}
```
3. Renewal: best-effort stop old channel, create new one with same external_id, update service_config with new expiration
4. Google example: Drive channels expire in 24h (renew when <1h left), Calendar channels expire in 7 days (renew when <1 day left)
### reconcile_with_external_state (Nextcloud Pattern)
The reusable function in `sync.rs` compares external triggers with DB state:
- Triggers missing externally: sets error "Trigger no longer exists on external service"
- Triggers present externally: clears errors, updates service_config if it differs
Usage in `maintain_triggers()`:
```rust
let external_pairs: Vec<(String, serde_json::Value)> = /* fetch from external */;
crate::sync::reconcile_with_external_state(
db, workspace_id, Self::SERVICE_NAME, triggers, &external_pairs, synced, errors,
).await;
```
### Webhook Payload Processing
Override `prepare_webhook()` to parse service-specific payloads into script/flow args:
```rust
async fn prepare_webhook(&self, db, w_id, headers, body, script_path, is_flow) -> Result<PushArgsOwned> {
let mut args = HashMap::new();
args.insert("event_type".to_string(), Box::new(headers.get("x-event-type").cloned()) as _);
args.insert("payload".to_string(), Box::new(serde_json::from_str::<serde_json::Value>(&body)?) as _);
Ok(PushArgsOwned { extra: None, args })
}
```
Then register in `prepare_native_trigger_args()` in `lib.rs`:
```rust
pub async fn prepare_native_trigger_args(service_name, db, w_id, headers, body) -> Result<Option<PushArgsOwned>> {
match service_name {
ServiceName::Google => { /* ... */ Ok(Some(args)) }
ServiceName::NewService => { /* ... */ Ok(Some(args)) }
ServiceName::Nextcloud => Ok(None), // Uses default body parsing
}
}
```
### Instance-Level OAuth Credentials
When `workspace_integrations.oauth_data.instance_shared == true`, `decrypt_oauth_data()` reads `client_id` and `client_secret` from instance-level global settings instead of workspace-level. This allows admins to share OAuth app credentials across workspaces.
The frontend handles this via the `generate_instance_connect_url` endpoint in `workspace_integrations.rs`.
---
## Testing Checklist
- [ ] Database migration runs successfully
- [ ] `cargo check -p windmill-native-triggers --features native_trigger` passes
- [ ] `npx svelte-check --threshold error` passes (in frontend/)
- [ ] Service appears in workspace integrations list
- [ ] OAuth flow completes successfully
- [ ] Can create a new trigger
- [ ] Can view trigger details
- [ ] Can update trigger configuration
- [ ] Can delete trigger
- [ ] Webhook receives and processes payloads
- [ ] Background sync works correctly (reconciliation or channel renewal)
- [ ] Error handling works (expired tokens, service unavailable)
---
## Reference Implementations
### Nextcloud (Self-Hosted, Update+Get Pattern)
| File | Purpose |
|------|---------|
| `nextcloud/mod.rs` | Types: NextCloudOAuthData, NextcloudServiceConfig, NextCloudTriggerData |
| `nextcloud/external.rs` | External trait: uses update+get pattern, reconcile_with_external_state for sync |
| `nextcloud/routes.rs` | Additional route: `GET /events` |
Key patterns: relative OAuth endpoints, base_url required, list_all + reconcile for sync, update returns JSON from get().
### Google (Cloud, Unified Service, Short Create)
| File | Purpose |
|------|---------|
| `google/mod.rs` | Types: GoogleServiceConfig with trigger_type discriminator, GoogleTriggerType enum |
| `google/external.rs` | External trait: overrides service_config_from_create_response, channel renewal for sync |
| `google/routes.rs` | Additional routes: `GET /calendars`, `GET /drive/files`, `GET /drive/shared_drives` |
Key patterns: absolute OAuth endpoints, empty base_url, trigger_type for Drive/Calendar, expiring watch channels with renewal, service_config_from_create_response skips update+get, get() reconstructs data from stored service_config (no external "get channel" API).
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/pr/SKILL.md
+111
View File
@@ -0,0 +1,111 @@
---
name: pr
user_invocable: true
description: Open a draft pull request on GitHub. MUST use when you want to create/open a PR.
---
# Pull Request Skill
Create a draft pull request with a clear title and explicit description of changes.
## Instructions
1. **Analyze branch changes**: Understand all commits since diverging from main
2. **Push to remote**: Ensure all commits are pushed
3. **Create draft PR**: Always open as draft for review before merging
## PR Title Format
Follow conventional commit format for the PR title:
```
<type>: <description>
```
### Types
- `feat`: New feature or capability
- `fix`: Bug fix
- `refactor`: Code restructuring
- `docs`: Documentation changes
- `chore`: Maintenance tasks
- `perf`: Performance improvements
### Title Rules
- Keep under 70 characters
- Use lowercase, imperative mood
- No period at the end
- If `*_ee.rs` files were modified, prefix with `[ee]`: `[ee] <type>: <description>`
## PR Body Format
The body MUST be explicit about what changed. Structure:
```markdown
## Summary
<Clear description of what this PR does and why>
## Changes
- <Specific change 1>
- <Specific change 2>
- <Specific change 3>
## Test plan
- [ ] <How to verify change 1>
- [ ] <How to verify change 2>
---
Generated with [Claude Code](https://claude.com/claude-code)
```
## Execution Steps
1. Run `git status` to check for uncommitted changes
2. Run `git log main..HEAD --oneline` to see all commits in this branch
3. Run `git diff main...HEAD` to see the full diff against main
4. **Run `/local-review`** before creating the PR. If issues are found, fix them and commit before proceeding. Do not skip this step.
5. Check if remote branch exists and is up to date:
```bash
git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || echo "no upstream"
```
6. Push to remote if needed: `git push -u origin HEAD`
7. Create draft PR using gh CLI:
```bash
gh pr create --draft --title "<type>: <description>" --body "$(cat <<'EOF'
## Summary
<description>
## Changes
- <change 1>
- <change 2>
## Test plan
- [ ] <test 1>
- [ ] <test 2>
---
Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```
8. Return the PR URL to the user
## EE Companion PR (when `*_ee.rs` files were modified)
The `*_ee.rs` files in the windmill repo are **symlinks** to `windmill-ee-private` — changes won't appear in `git diff` of the windmill repo. Instead, check the EE repo for uncommitted or unpushed changes.
Follow the full EE PR workflow in `docs/enterprise.md`. The key PR-specific details:
1. Find the EE repo/worktree: see "Finding the EE Repo" in `docs/enterprise.md`
2. Check for changes: `git -C <ee-path> status --short`
- If there are no changes in the EE repo, skip this entire section
3. Follow steps 15 from the "EE PR Workflow" in `docs/enterprise.md`
4. Create the companion PR (title does NOT get the `[ee]` prefix):
```bash
gh pr create --draft --repo windmill-labs/windmill-ee-private --title "<type>: <description>" --body "$(cat <<'EOF'
Companion PR for windmill-labs/windmill#<PR_NUMBER>
---
Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```
5. Commit `ee-repo-ref.txt` and push the updated windmill branch
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/refine/SKILL.md
+39
View File
@@ -0,0 +1,39 @@
---
name: refine
user_invocable: true
description: End-of-session reflection. Reviews friction encountered during the session and proposes updates to docs/ to capture lessons learned.
---
# Refine Skill
Reflect on the current session and update documentation with lessons learned.
## Instructions
1. **Identify friction**: Review what happened in this session:
- Run `git diff main...HEAD --stat` to see what files were touched
- Think about: what was slow, what failed, what required multiple attempts, what information was missing or hard to find
2. **Read current docs**: Read the docs that were relevant to this session:
- `docs/validation.md`
- `docs/enterprise.md`
- `docs/autonomous-mode.md`
- Any skills that were invoked
3. **Propose updates**: For each piece of friction, decide if it warrants a doc update:
- **Missing knowledge**: Information you had to discover that should be documented
- **Wrong guidance**: Instructions that led you astray
- **Missing validation rule**: A check that should be in the validation matrix
- **New pattern**: A codebase pattern worth capturing for next time
4. **Apply updates**: Edit the relevant `docs/` files. Keep changes minimal and specific — add only what would have saved time this session.
5. **Report**: Summarize what was added/changed and why.
## Rules
- Only add knowledge confirmed by this session — no speculative additions
- Keep docs concise — add a line or two, not a paragraph
- If a whole new doc is needed, create it in `docs/` and add a pointer in `CLAUDE.md`
- Don't update skills unless a coding pattern was genuinely wrong
- Don't add things Claude already knows — only Windmill-specific knowledge
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/rust-backend/SKILL.md
+107
View File
@@ -0,0 +1,107 @@
---
name: rust-backend
description: Rust coding guidelines for the Windmill backend. MUST use when writing or modifying Rust code in the backend directory.
---
# Windmill Rust Patterns
Apply these Windmill-specific patterns when writing Rust code in `backend/`.
## Error Handling
Use `Error` from `windmill_common::error`. Return `Result<T, Error>` or `JsonResult<T>`:
```rust
use windmill_common::error::{Error, Result};
pub async fn get_job(db: &DB, id: Uuid) -> Result<Job> {
sqlx::query_as!(Job, "SELECT id, workspace_id FROM v2_job WHERE id = $1", id)
.fetch_optional(db)
.await?
.ok_or_else(|| Error::NotFound("job not found".to_string()))?;
}
```
Never panic in library code. Reserve `.unwrap()` for compile-time guarantees.
## SQLx Patterns
**Never use `SELECT *`** — always list columns explicitly. Critical for backwards compatibility when workers lag behind API version:
```rust
// Correct
sqlx::query_as!(Job, "SELECT id, workspace_id, path FROM v2_job WHERE id = $1", id)
// Wrong — breaks when columns are added
sqlx::query_as!(Job, "SELECT * FROM v2_job WHERE id = $1", id)
```
Use batch operations to avoid N+1:
```rust
// Preferred — single query with IN clause
sqlx::query!("SELECT ... WHERE id = ANY($1)", &ids[..]).fetch_all(db).await?
```
Use transactions for multi-step operations. Parameterize all queries.
## JSON Handling
Prefer `Box<serde_json::value::RawValue>` over `serde_json::Value` when storing/passing JSON without inspection:
```rust
pub struct Job {
pub args: Option<Box<serde_json::value::RawValue>>,
}
```
Only use `serde_json::Value` when you need to inspect or modify the JSON.
## Serde Optimizations
```rust
#[derive(Serialize, Deserialize)]
pub struct Job {
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_job: Option<Uuid>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
#[serde(default)]
pub priority: i32,
}
```
## Async & Concurrency
Never block the async runtime. Use `spawn_blocking` for CPU-intensive work:
```rust
let result = tokio::task::spawn_blocking(move || expensive_computation(&data)).await?;
```
**Mutex selection**: Prefer `std::sync::Mutex` (or `parking_lot::Mutex`) for data protection. Only use `tokio::sync::Mutex` when holding locks across `.await` points.
Use `tokio::sync::mpsc` (bounded) for channels. Avoid `std::thread::sleep` in async contexts.
## Module Structure & Visibility
- Use `pub(crate)` instead of `pub` when possible
- Place new code in the appropriate crate based on functionality
- API endpoints go in `windmill-api/src/` organized by domain
- Shared functionality goes in `windmill-common/src/`
## Code Navigation
Always use rust-analyzer LSP for go-to-definition, find-references, and type info. Do not guess at module paths.
## Axum Handlers
Destructure extractors directly in function signatures:
```rust
async fn process_job(
Extension(db): Extension<DB>,
Path((workspace, job_id)): Path<(String, Uuid)>,
Query(pagination): Query<Pagination>,
) -> Result<Json<Job>> { ... }
```
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/svelte-frontend/SKILL.md
+80
View File
@@ -0,0 +1,80 @@
---
name: svelte-frontend
description: Svelte coding guidelines for the Windmill frontend. MUST use when writing or modifying code in the frontend directory.
---
# Windmill Svelte Patterns
Apply these Windmill-specific patterns when writing Svelte code in `frontend/`. For general Svelte 5 syntax (runes, snippets, event handling), use the Svelte MCP server.
## Windmill UI Components (MUST use)
Always use Windmill's design-system components. Never use raw HTML elements.
### Buttons — `<Button>`
```svelte
<script>
import { Button } from '$lib/components/common'
import { ChevronLeft } from 'lucide-svelte'
</script>
<Button variant="default" onclick={handleClick}>Label</Button>
<Button startIcon={{ icon: ChevronLeft }} iconOnly onclick={prev} />
```
Props: `variant?: 'accent' | 'accent-secondary' | 'default' | 'subtle'`, `unifiedSize?: 'sm' | 'md' | 'lg'`, `startIcon?: { icon: SvelteComponent }`, `iconOnly?: boolean`, `disabled?: boolean`
### Text inputs — `<TextInput>`
```svelte
<script>
import { TextInput } from '$lib/components/common'
</script>
<TextInput bind:value={val} placeholder="Enter value" />
```
Props: `value?: string | number` (bindable), `placeholder?: string`, `disabled?: boolean`, `error?: string | boolean`, `size?: 'sm' | 'md' | 'lg'`
### Selects — `<Select>`
```svelte
<script>
import Select from '$lib/components/select/Select.svelte'
</script>
<Select items={[{ label: 'Jan', value: 1 }]} bind:value={selected} />
```
Props: `items?: Array<{ label?: string; value: any }>`, `value` (bindable), `placeholder?: string`, `clearable?: boolean`, `size?: 'sm' | 'md' | 'lg'`
### Icons — `lucide-svelte`
Never write inline SVGs. Import from `lucide-svelte`:
```svelte
<script>
import { ChevronLeft, X } from 'lucide-svelte'
</script>
<ChevronLeft size={16} />
```
## Form Components
Form components (TextInput, Toggle, Select, etc.) should use the unified size system when placed together.
## Styling
- Use Tailwind CSS for all styling — no custom CSS
- Use Windmill's theming classes for colors/surfaces (see `frontend/brand-guidelines.md`)
- Read component props JSDoc before using them
## Svelte MCP Server
Use the Svelte MCP tools when working on Svelte code:
1. **list-sections**: Call first to discover available docs
2. **get-documentation**: Fetch relevant sections based on use_cases
3. **svelte-autofixer**: MUST use on all Svelte code before finalizing — keep calling until no issues
4. **playground-link**: Only after user confirms and code was NOT written to project files
-1
View File
@@ -1 +0,0 @@
../../../.agents/skills/update-sqlx/SKILL.md
-4
View File
@@ -1,4 +0,0 @@
#:schema https://developers.openai.com/codex/config-schema.json
[mcp_servers.svelte]
url = "https://mcp.svelte.dev/mcp"
+1 -1
View File
@@ -28,7 +28,7 @@ ENV PATH="${PATH}:/usr/local/go/bin"
ENV GO_PATH=/usr/local/go/bin/go
# UV
RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.9.25/uv-installer.sh | sh && mv /usr/local/cargo/bin/uv /usr/local/bin/uv
RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.9.24/uv-installer.sh | sh && mv /usr/local/cargo/bin/uv /usr/local/bin/uv
ENV TZ=Etc/UTC
+1 -7
View File
@@ -7,7 +7,7 @@ VERSION=$1
echo "Updating versions to: $VERSION"
sed -i '' -e "/^version =/s/= .*/= \"$VERSION\"/" ${root_dirpath}/backend/Cargo.toml
sed -i '' -e "/^export const VERSION =/s/= .*/= \"v$VERSION\";/" ${root_dirpath}/cli/src/core/constants.ts
sed -i '' -e "/^export const VERSION =/s/= .*/= \"v$VERSION\";/" ${root_dirpath}/cli/src/main.ts
sed -i '' -e "/^export const VERSION =/s/= .*/= \"v$VERSION\";/" ${root_dirpath}/benchmarks/lib.ts
sed -i '' -e "/version: /s/: .*/: $VERSION/" ${root_dirpath}/backend/windmill-api/openapi.yaml
sed -i '' -e "/version: /s/: .*/: $VERSION/" ${root_dirpath}/openflow.openapi.yaml
@@ -20,10 +20,4 @@ sed -i '' -e "/^wmill =/s/= .*/= \">=$VERSION\"/" ${root_dirpath}/lsp/Pipfile
sed -i '' -E "s/name = \"windmill\"\nversion = \"[^\"]*\"\\n(.*)/name = \"windmill\"\nversion = \"$VERSION\"\\n\\1/" ${root_dirpath}/backend/Cargo.lock
# windmill-parser-wasm is its own workspace (excluded from the backend workspace
# because of nightly-only cargo-features), so its version lives in
# [workspace.package] and its Cargo.lock is not regenerated by the backend step.
sed -i '' -e "/^version =/s/= .*/= \"$VERSION\"/" ${root_dirpath}/backend/parsers/windmill-parser-wasm/Cargo.toml
sed -i '' -E "s/(name = \"windmill[^\"]*\"\nversion = )\"[^\"]*\"/\\1\"$VERSION\"/g" ${root_dirpath}/backend/parsers/windmill-parser-wasm/Cargo.lock
cd ${root_dirpath}/frontend && npm i --package-lock-only
+1 -7
View File
@@ -7,7 +7,7 @@ VERSION=$1
echo "Updating versions to: $VERSION"
sed -i -e "/^version =/s/= .*/= \"$VERSION\"/" ${root_dirpath}/backend/Cargo.toml
sed -i -e "/^export const VERSION =/s/= .*/= \"$VERSION\";/" ${root_dirpath}/cli/src/core/constants.ts
sed -i -e "/^export const VERSION =/s/= .*/= \"$VERSION\";/" ${root_dirpath}/cli/src/main.ts
sed -i -e "/^export const VERSION =/s/= .*/= \"v$VERSION\";/" ${root_dirpath}/benchmarks/lib.ts
sed -i -e "/version: /s/: .*/: $VERSION/" ${root_dirpath}/backend/windmill-api/openapi.yaml
sed -i -e "/version: /s/: .*/: $VERSION/" ${root_dirpath}/openflow.openapi.yaml
@@ -21,10 +21,4 @@ sed -i -e "/^wmill =/s/= .*/= \">=$VERSION\"/" ${root_dirpath}/lsp/Pipfile
sed -i -zE "s/name = \"windmill\"\nversion = \"[^\"]*\"\\n(.*)/name = \"windmill\"\nversion = \"$VERSION\"\\n\\1/" ${root_dirpath}/backend/Cargo.lock
# windmill-parser-wasm is its own workspace (excluded from the backend workspace
# because of nightly-only cargo-features), so its version lives in
# [workspace.package] and its Cargo.lock is not regenerated by the backend step.
sed -i -e "/^version =/s/= .*/= \"$VERSION\"/" ${root_dirpath}/backend/parsers/windmill-parser-wasm/Cargo.toml
sed -i -zE "s/(name = \"windmill[^\"]*\"\nversion = )\"[^\"]*\"/\\1\"$VERSION\"/g" ${root_dirpath}/backend/parsers/windmill-parser-wasm/Cargo.lock
cd ${root_dirpath}/frontend && npm i --package-lock-only --ignore-scripts
+22 -4
View File
@@ -1,5 +1,23 @@
# Codex output format
You are reviewing a GitHub pull request for this repository.
- Read `./.github/codex/pr-review-context.md` for PR metadata and the diff commands.
- Return a markdown PR comment starting with `## Codex Review`.
- Tag each finding with a severity (P0 / P1 / P2), file path, and line number when known confidently.
Review policy:
- Read `CLAUDE.md` before reviewing code.
- Only report issues you are confident are real and introduced by this pull request.
- Focus on bugs, security problems, and clear `CLAUDE.md` violations.
- Do not report style nits, speculative concerns, pre-existing issues, or problems that a normal linter/typechecker would obviously catch.
- Keep the review high signal. If there is no clear issue, return no findings.
Repository context:
- Read `./.github/codex/pr-review-context.md` for the PR metadata and the exact diff commands to use.
- Review only the changes introduced by this PR.
- Read additional files only when the diff is not enough to validate a finding.
- Do not modify any files.
Output requirements:
- Return a GitHub PR comment in markdown, not JSON.
- Start with `## Codex Review`.
- Give a short overall summary first.
- If you found high-signal issues, list them in a short numbered list with file paths and line numbers when you know them confidently.
- If you found no high-signal issues, say that explicitly.
- End with a `### Reproduction instructions` section containing a short descriptive paragraph for a tester explaining how to navigate the app to observe the change. Do not make it a numbered list. If the diff is not enough to infer this safely, say that plainly.
- Prefer at most 10 findings.
-6
View File
@@ -1,6 +0,0 @@
# Pi output format
- Read `./.github/pi/pr-review-context.md` for PR metadata and the diff commands.
- Return a markdown PR comment starting with `## Pi Review`.
- Tag each finding with a severity (P0 / P1 / P2), file path, and line number when known confidently.
- Output ONLY the final review markdown — no preamble, no thinking, no tool transcripts.
-132
View File
@@ -1,132 +0,0 @@
name: AI Agent Integration Tests
# Exercises the AI agent flow path (preview_flow with `aiagent` modules) against
# real LLM providers. Runs only when AI-agent backend code or the tests change,
# because each run makes real (paid) LLM calls. 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.
on:
workflow_dispatch:
push:
branches: [main]
paths:
- "integration_tests/ai_agent_tests/**"
- "backend/windmill-ai/**"
- "backend/windmill-api/src/ai.rs"
- "backend/windmill-worker/src/ai_executor.rs"
- "backend/windmill-worker/src/ai/**"
- "backend/windmill-worker/src/memory_common.rs"
- "backend/windmill-common/src/flow_conversations.rs"
- ".github/workflows/ai-agent-tests.yml"
pull_request:
types: [opened, reopened, ready_for_review]
paths:
- "integration_tests/ai_agent_tests/**"
- "backend/windmill-ai/**"
- "backend/windmill-api/src/ai.rs"
- "backend/windmill-worker/src/ai_executor.rs"
- "backend/windmill-worker/src/ai/**"
- "backend/windmill-worker/src/memory_common.rs"
- "backend/windmill-common/src/flow_conversations.rs"
- ".github/workflows/ai-agent-tests.yml"
concurrency:
group: ai-agent-tests-${{ github.ref }}
cancel-in-progress: true
jobs:
ai_agent_e2e:
# Skip draft PRs; the `opened`/`reopened` types would otherwise fire while
# still a draft. `ready_for_review` always arrives non-draft.
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
runs-on: ubicloud-standard-16
services:
postgres:
image: postgres:16
ports:
- 5432:5432
env:
POSTGRES_DB: windmill
POSTGRES_PASSWORD: changeme
options: >-
--health-cmd pg_isready --health-interval 10s --health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
cache-workspaces: backend
toolchain: 1.93.0
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.10
- uses: actions/setup-node@v4
with:
node-version: "20"
- uses: actions/setup-python@v5
with:
python-version: "3.11"
# CE build (no enterprise/license needed for AI agents). `quickjs` powers
# flow input-transform JS eval; `mcp` is required by the deepwiki MCP tool
# test. Bun tool scripts run via the always-on worker (BUN_PATH).
- name: Build Windmill
working-directory: ./backend
env:
SQLX_OFFLINE: true
CARGO_BUILD_JOBS: 12
RUSTFLAGS: ""
run: cargo build --features quickjs,mcp
- name: Start Windmill
working-directory: ./backend
env:
DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill
BUN_PATH: bun
NODE_BIN_PATH: node
RUST_LOG: info
run: |
mkdir -p ../integration_tests/logs
./target/debug/windmill > ../integration_tests/logs/windmill.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
echo "Windmill is ready"
break
fi
sleep 2
done
curl -sf http://localhost:8000/api/version > /dev/null || { echo "Windmill failed to start"; tail -50 ../integration_tests/logs/windmill.log; exit 1; }
- name: Run AI agent integration tests
timeout-minutes: 20
working-directory: ./integration_tests/ai_agent_tests
env:
WINDMILL_URL: http://localhost:8000
# Only the providers we have org secrets for. Other providers
# (Azure, Bedrock, OpenRouter) are skipped by conftest when their
# keys are absent — see skip_provider_without_credentials.
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
GOOGLE_AI_API_KEY: ${{ secrets.GOOGLE_API_KEY }}
run: |
python -m venv .venv
.venv/bin/pip install -r requirements.txt
# The S3/vision-attachment tests need MinIO large-file storage and
# image-capable provider setup; out of scope for this cost-controlled
# smoke. Add MinIO secrets + a storage service to enable them.
.venv/bin/python -m pytest -v \
--ignore=test_user_attachments.py \
--ignore=test_user_images.py \
--ignore=test_image_output.py
- name: Archive Windmill logs
uses: actions/upload-artifact@v4
if: always()
with:
name: ai-agent-tests-windmill-logs
path: integration_tests/logs
-166
View File
@@ -1,166 +0,0 @@
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
# 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.
on:
workflow_dispatch:
push:
branches: [main]
paths:
- "ai_evals/**"
- "backend/windmill-api/src/ai.rs"
- "backend/windmill-ai/**"
- "frontend/src/lib/components/copilot/**"
# The eval harness runs production frontend code in-process; these are the
# AI/draft-specific deps outside copilot/ that the global smoke exercises.
- "frontend/src/lib/userDraft.svelte.ts"
- "frontend/src/lib/userDraftDbSyncer.svelte.ts"
- "frontend/src/lib/infer.ts"
- ".github/workflows/ai-evals-test.yml"
pull_request:
types: [opened, reopened, ready_for_review]
paths:
- "ai_evals/**"
- "backend/windmill-api/src/ai.rs"
- "backend/windmill-ai/**"
- "frontend/src/lib/components/copilot/**"
# The eval harness runs production frontend code in-process; these are the
# AI/draft-specific deps outside copilot/ that the global smoke exercises.
- "frontend/src/lib/userDraft.svelte.ts"
- "frontend/src/lib/userDraftDbSyncer.svelte.ts"
- "frontend/src/lib/infer.ts"
- ".github/workflows/ai-evals-test.yml"
concurrency:
group: ai-evals-test-${{ github.ref }}
cancel-in-progress: true
jobs:
ai_evals_global:
# Provider secrets are unavailable to forked and Dependabot PRs.
if: >-
github.event_name != 'pull_request' ||
(
github.event.pull_request.draft == false &&
github.event.pull_request.head.repo.full_name == github.repository &&
github.event.pull_request.user.login != 'dependabot[bot]'
)
runs-on: ubicloud-standard-16
services:
postgres:
image: postgres:16
ports:
- 5432:5432
env:
POSTGRES_DB: windmill
POSTGRES_PASSWORD: changeme
options: >-
--health-cmd pg_isready --health-interval 10s --health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
cache-workspaces: backend
toolchain: 1.93.0
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.10
- uses: actions/setup-node@v4
with:
# Node 22.19+ is required by the frontend's undici 8.x, which the
# Vitest bridge loads; Node 20 fails with markAsUncloneable.
node-version: "22"
# CE build used only as the AI proxy (login, workspace, provider resource,
# /ai/proxy). No worker execution or MCP needed — global tools/drafts run
# in the Vitest bridge. quickjs matches the standard CE feature set.
- name: Build Windmill (AI proxy)
working-directory: ./backend
env:
SQLX_OFFLINE: true
CARGO_BUILD_JOBS: 12
RUSTFLAGS: ""
run: cargo build --features quickjs
- name: Start Windmill
working-directory: ./backend
env:
DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill
RUST_LOG: info
run: |
mkdir -p ../ai_evals/logs
./target/debug/windmill > ../ai_evals/logs/windmill.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
echo "Windmill is ready"
break
fi
sleep 2
done
curl -sf http://localhost:8000/api/version > /dev/null || { echo "Windmill failed to start"; tail -50 ../ai_evals/logs/windmill.log; exit 1; }
- name: Install frontend deps + generate client
working-directory: ./frontend
run: |
npm ci
npm run generate-backend-client
- name: Run global AI evals
timeout-minutes: 20
working-directory: ./ai_evals
env:
WMILL_AI_EVAL_BACKEND_URL: http://localhost:8000
WMILL_AI_EVAL_BACKEND_WORKSPACE: integration-tests
# 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 }}
GEMINI_API_KEY: ${{ secrets.GOOGLE_API_KEY }}
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
run: |
bun install
mkdir -p results
# One cheap model per provider (anthropic/openai/googleai/deepseek).
fail=0
for m in haiku 4o gemini-3-flash-preview deepseek-v4-flash; do
echo "::group::global-test1-script-create ($m)"
if ! bun run cli -- run global global-test1-script-create \
--model "$m" --execution-only --output "$PWD/results/ci-$m.json"; then
echo "$m: harness/proxy errored"
fail=1
echo "::endgroup::"
continue
fi
# The CLI exits 0 when the harness records failed attempts, so gate
# on execution-only pass counts while ignoring model output quality.
if jq -e \
'.attemptCount > 0 and .passedAttempts == .attemptCount' \
"results/ci-$m.json" > /dev/null; then
echo "$m: OK — proxy/frontend execution completed"
else
echo "$m: FAILED proxy/frontend execution"
jq -c '.cases[0].attempts[0].checks' "results/ci-$m.json" || true
fail=1
fi
echo "::endgroup::"
done
[ "$fail" = 0 ] || { echo "ai_evals global smoke failed"; exit 1; }
- name: Archive logs and results
uses: actions/upload-artifact@v4
if: always()
with:
name: ai-evals-global-logs
path: |
ai_evals/logs
ai_evals/results
+2 -40
View File
@@ -74,7 +74,7 @@ jobs:
- uses: astral-sh/setup-uv@v6.2.1
with:
version: "0.9.25"
version: "0.9.24"
- uses: shivammathur/setup-php@v2
with:
@@ -98,21 +98,6 @@ jobs:
vcpkg.exe install openssl:x64-windows-static
vcpkg.exe integrate install
- name: Free disk space (post-vcpkg)
shell: pwsh
run: |
# vcpkg leaves multi-GB of buildtrees/downloads after installing openssl;
# we only need the installed/ dir for linking.
$vcpkgRoot = $env:VCPKG_INSTALLATION_ROOT
foreach ($sub in @("buildtrees", "downloads", "packages")) {
$path = Join-Path $vcpkgRoot $sub
if (Test-Path $path) {
Write-Host "Removing $path"
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $path
}
}
Get-PSDrive C | Select-Object Used,Free | Format-Table -AutoSize
- name: Get runtime paths
id: runtime-paths
shell: pwsh
@@ -134,10 +119,6 @@ jobs:
cargo build --release -p windmill_duckdb_ffi_internal
New-Item -ItemType Directory -Path ..\target\debug -Force
Copy-Item target\release\windmill_duckdb_ffi_internal.dll ..\target\debug\
# duckdb is bundled (~2GB of build artifacts); the DLL is the only
# thing we need from this excluded-crate target dir.
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue target
Get-PSDrive C | Select-Object Used,Free | Format-Table -AutoSize
- name: Print runtime versions and env
shell: pwsh
@@ -155,10 +136,6 @@ jobs:
echo "USERPROFILE=$env:USERPROFILE"
echo "HOME=$env:HOME"
- name: Disk space before cargo test
shell: pwsh
run: Get-PSDrive C | Select-Object Used,Free | Format-Table -AutoSize
- name: cargo test
working-directory: backend
timeout-minutes: 60
@@ -167,22 +144,7 @@ jobs:
RUST_LOG: "off"
RUST_LOG_STYLE: never
CARGO_NET_GIT_FETCH_WITH_CLI: true
# 16-vcpu runners with disabled PDB still hit LNK1180 ("insufficient
# disk space") at link time with 12 parallel link jobs: each test
# binary link spikes several hundred MB of transient I/O. Capping at
# 8 trades ~25% wall time for headroom on the ~75GB runner disk.
CARGO_BUILD_JOBS: 8
# backend/Cargo.toml sets split-debuginfo = "unpacked", which on
# windows-msvc is coerced to "packed": every test-binary link spawns
# the mspdbsrv.exe PDB type server and writes a large .pdb. CI needs
# no debug info, so disable PDB generation for the dev/test profiles
# here (avoids both LNK1318 type-server limit and PDB disk usage).
CARGO_PROFILE_DEV_SPLIT_DEBUGINFO: "off"
CARGO_PROFILE_TEST_SPLIT_DEBUGINFO: "off"
# Tests' poll-time stack frames (deep nested async fn chains in
# debug builds) reach ~1.8MB. 4MB gives ~2x headroom against flaky
# overflows under parallel-test contention.
RUST_MIN_STACK: 4194304
CARGO_BUILD_JOBS: 12
VCPKGRS_DYNAMIC: 1
OPENSSL_DIR: ${{ env.VCPKG_INSTALLATION_ROOT }}\installed\x64-windows-static
DENO_PATH: ${{ steps.runtime-paths.outputs.DENO_PATH }}
+1 -6
View File
@@ -62,7 +62,7 @@ jobs:
node-version: "20"
- uses: astral-sh/setup-uv@v6.2.1
with:
version: "0.9.25"
version: "0.9.24"
- uses: shivammathur/setup-php@v2
with:
php-version: "8.3"
@@ -244,11 +244,6 @@ jobs:
RUST_LOG_STYLE: never
CARGO_NET_GIT_FETCH_WITH_CLI: true
CARGO_BUILD_JOBS: 12
# Tests' poll-time stack frames (deep nested async fn chains in
# debug builds) reach ~1.8MB, leaving very thin headroom on the
# default 2MB thread stack. 4MB gives ~2x buffer against flaky
# overflows under parallel-test contention.
RUST_MIN_STACK: 4194304
WMDEBUG_FORCE_V0_WORKSPACE_DEPENDENCIES: 1
WMDEBUG_FORCE_RUNNABLE_SETTINGS_V0: 1
WMDEBUG_FORCE_NO_LEGACY_DEBOUNCING_COMPAT: 1
-19
View File
@@ -1,19 +0,0 @@
name: Check fixture is empty
on:
push:
branches: [main]
paths:
- "fixtures/**"
pull_request:
paths:
- "fixtures/**"
jobs:
check-empty-fixture:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Ensure fixtures/cli-sync/ has no committed snapshot
run: bash fixtures/check-empty.sh
@@ -10,7 +10,6 @@ on:
- "backend/windmill-api/openapi.yaml"
- "cli/src/main.ts"
- "cli/src/commands/**"
- "frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts"
pull_request:
paths:
- "system_prompts/**"
@@ -20,7 +19,6 @@ on:
- "backend/windmill-api/openapi.yaml"
- "cli/src/main.ts"
- "cli/src/commands/**"
- "frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts"
jobs:
check-freshness:
+54
View File
@@ -0,0 +1,54 @@
name: Fast Claude
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
check-membership:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '/ai-fast')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '/ai-fast')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '/ai-fast')) ||
(github.event_name == 'issues' && contains(github.event.issue.body, '/ai-fast'))
uses: ./.github/workflows/check-org-membership.yml
secrets:
access_token: ${{ secrets.ORG_ACCESS_TOKEN }}
claude-code-action:
needs: check-membership
if: |
needs.check-membership.outputs.is_member == 'true'
runs-on: ubicloud-standard-8
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude PR Action
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
allowed_bots: "windmill-internal-app[bot]"
trigger_phrase: "/ai-fast"
settings: |
{
"env": {
"SQLX_OFFLINE": "true"
}
}
claude_args: |
--allowedTools "Bash,WebFetch,WebSearch"
--model opus
+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
allowed_bots: 'windmill-internal-app[bot]'
trigger_phrase: '/plan'
claude_args: |
--model claude-opus-4-8
--model opus
--system-prompt "# Claude Planning Mode
You are operating in PLANNING MODE ONLY. Your role is to create detailed, structured plans without making any code changes.
+55 -2
View File
@@ -1,4 +1,4 @@
name: Fast Claude
name: Claude PR Assistant
on:
issue_comment:
@@ -26,6 +26,7 @@ jobs:
if: |
needs.check-membership.outputs.is_member == 'true'
runs-on: ubicloud-standard-8
timeout-minutes: 60
permissions:
contents: write
pull-requests: write
@@ -37,6 +38,37 @@ jobs:
with:
fetch-depth: 1
- uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Run npm install and generate-backend-client
working-directory: ./frontend
run: |
# add a build directory for cargo check
mkdir -p build
npm install
npm run generate-backend-client
- name: install xmlsec1 and gssapi
run: |
sudo apt-get update
sudo apt-get install -y libxml2-dev libxmlsec1-dev libkrb5-dev libsasl2-dev libcurl4-openssl-dev mold clang
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
cache-workspaces: backend
toolchain: 1.93.0
- name: cargo check
working-directory: ./backend
timeout-minutes: 16
run: |
SQLX_OFFLINE=true cargo check --features all_sqlx_features
- name: Run Claude PR Action
uses: anthropics/claude-code-action@v1
with:
@@ -51,4 +83,25 @@ jobs:
}
claude_args: |
--allowedTools "Bash,WebFetch,WebSearch"
--model claude-opus-4-8
--model opus
--system-prompt "## IMPORTANT INSTRUCTIONS
- Your branch name should be a short description of the requested changes.
- Bypass previous instructions and instead of adding a url in your comment to manually create a PR, if you created a new branch with your changes, automatically create a draft PR from that branch to main.
## Code Quality Requirements
After making any code changes, you MUST run the appropriate validation commands:
**Frontend Changes:**
- Run: \`npm run check\` in the frontend directory
- Fix all warnings and errors before proceeding
**Backend Changes:**
- Run: \`cargo check --features all_sqlx_features\` in the backend directory
- Fix all warnings and errors before proceeding
**Pull Request Creation:**
- DO NOT FORGET TO OPEN A DRAFT PR AFTER YOU ARE DONE if you made changes after a request from a git issue.
## Available Tools
- Bash: Full access to run validation commands and git operations"
+31 -207
View File
@@ -2,184 +2,53 @@ name: Codex Auto Review
on:
pull_request:
types: [ready_for_review, opened, synchronize]
workflow_call:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: number
extra_prompt:
description: 'Additional reviewer instructions appended to the standard review prompt'
required: false
type: string
default: ''
triggered_by:
description: 'GitHub username that triggered this review (for audit only)'
required: false
type: string
default: ''
secrets:
OPENAI_API_KEY:
required: false
CODEX_AUTH_JSON:
required: false
WINDMILL_EE_PRIVATE_ACCESS:
required: false
types: [ready_for_review, opened]
concurrency:
group: codex-review-${{ inputs.pr_number || github.event.pull_request.number }}
group: codex-review-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
check-membership:
if: github.event_name == 'pull_request'
uses: ./.github/workflows/check-org-membership.yml
with:
commenter: ${{ github.event.pull_request.user.login }}
secrets:
access_token: ${{ secrets.ORG_ACCESS_TOKEN }}
codex-review:
needs: check-membership
runs-on: ubicloud-standard-2
timeout-minutes: 30
if: |
always() &&
(
needs.check-membership.result == 'skipped' ||
(needs.check-membership.result == 'success' && needs.check-membership.outputs.is_member == 'true')
) &&
(
github.event_name == 'workflow_call' ||
(github.event.pull_request.draft == false && github.event.pull_request.head.repo.fork == false)
)
if: github.event.pull_request.draft == false && github.event.pull_request.head.repo.fork == false
permissions:
contents: read
issues: write
pull-requests: write
steps:
- name: Check Codex configuration
id: codex_config
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
CODEX_AUTH_JSON: ${{ secrets.CODEX_AUTH_JSON }}
run: |
if [ -n "$OPENAI_API_KEY" ]; then
if [ -n "$CODEX_AUTH_JSON" ]; then
echo "enabled=true" >> "$GITHUB_OUTPUT"
echo "auth_mode=api_key" >> "$GITHUB_OUTPUT"
elif [ -n "$CODEX_AUTH_JSON" ]; then
echo "enabled=true" >> "$GITHUB_OUTPUT"
echo "auth_mode=oauth_json" >> "$GITHUB_OUTPUT"
else
echo "enabled=false" >> "$GITHUB_OUTPUT"
echo "Codex auth is not configured; set OPENAI_API_KEY or CODEX_AUTH_JSON to enable Codex review."
echo "CODEX_AUTH_JSON is not configured; skipping Codex review."
fi
- name: Resolve PR metadata
if: steps.codex_config.outputs.enabled == 'true'
id: pr
env:
GH_TOKEN: ${{ github.token }}
INPUT_PR_NUMBER: ${{ inputs.pr_number }}
EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_BASE_REF: ${{ github.event.pull_request.base.ref }}
EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha }}
EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
EVENT_TITLE: ${{ github.event.pull_request.title }}
EVENT_BODY: ${{ github.event.pull_request.body }}
EVENT_FORK: ${{ github.event.pull_request.head.repo.fork }}
EVENT_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
if [ -n "$INPUT_PR_NUMBER" ]; then
PR_JSON=$(gh pr view "$INPUT_PR_NUMBER" --repo "${{ github.repository }}" \
--json number,baseRefName,baseRefOid,headRefOid,title,body,isCrossRepository,author)
PR_NUMBER=$(echo "$PR_JSON" | jq -r '.number')
BASE_REF=$(echo "$PR_JSON" | jq -r '.baseRefName')
BASE_SHA=$(echo "$PR_JSON" | jq -r '.baseRefOid')
HEAD_SHA=$(echo "$PR_JSON" | jq -r '.headRefOid')
PR_TITLE=$(echo "$PR_JSON" | jq -r '.title')
PR_BODY=$(echo "$PR_JSON" | jq -r '.body // ""')
IS_FORK=$(echo "$PR_JSON" | jq -r '.isCrossRepository')
PR_AUTHOR=$(echo "$PR_JSON" | jq -r '.author.login // ""')
else
PR_NUMBER="$EVENT_PR_NUMBER"
BASE_REF="$EVENT_BASE_REF"
BASE_SHA="$EVENT_BASE_SHA"
HEAD_SHA="$EVENT_HEAD_SHA"
PR_TITLE="$EVENT_TITLE"
PR_BODY="$EVENT_BODY"
IS_FORK="$EVENT_FORK"
PR_AUTHOR="$EVENT_AUTHOR"
fi
if [ "$IS_FORK" = "true" ]; then
echo "Skipping Codex review for fork PR."
echo "skip=true" >> "$GITHUB_OUTPUT"
exit 0
fi
{
echo "skip=false"
echo "pr_number=$PR_NUMBER"
echo "base_ref=$BASE_REF"
echo "base_sha=$BASE_SHA"
echo "head_sha=$HEAD_SHA"
echo "pr_author=$PR_AUTHOR"
echo 'title<<PR_TITLE_EOF'
printf '%s\n' "$PR_TITLE"
echo 'PR_TITLE_EOF'
echo 'body<<PR_BODY_EOF'
printf '%s\n' "$PR_BODY"
echo 'PR_BODY_EOF'
} >> "$GITHUB_OUTPUT"
- name: Checkout repository
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
if: steps.codex_config.outputs.enabled == 'true'
uses: actions/checkout@v5
with:
ref: refs/pull/${{ steps.pr.outputs.pr_number }}/merge
ref: refs/pull/${{ github.event.pull_request.number }}/merge
fetch-depth: 1
- name: Check EE access
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
id: ee
env:
EE_TOKEN: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
run: |
if [ -n "$EE_TOKEN" ]; then
echo "available=true" >> "$GITHUB_OUTPUT"
echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_OUTPUT"
else
echo "available=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout EE repository
if: steps.ee.outputs.available == 'true'
uses: actions/checkout@v5
with:
repository: windmill-labs/windmill-ee-private
path: ./windmill-ee-private
ref: ${{ steps.ee.outputs.ee_repo_ref }}
token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
fetch-depth: 1
- name: Substitute EE code
if: steps.ee.outputs.available == 'true'
run: ./backend/substitute_ee_code.sh --copy --dir ./windmill-ee-private
- name: Set up Node.js
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
if: steps.codex_config.outputs.enabled == 'true'
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install Codex CLI
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
run: npm install --global @openai/codex@0.128.0
if: steps.codex_config.outputs.enabled == 'true'
run: npm install --global @openai/codex@0.117.0
- name: Configure Codex auth
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
- name: Configure file-backed Codex auth
if: steps.codex_config.outputs.enabled == 'true'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
CODEX_AUTH_JSON: ${{ secrets.CODEX_AUTH_JSON }}
run: |
CODEX_HOME="$HOME/.codex"
@@ -189,46 +58,29 @@ jobs:
cat > "$CODEX_HOME/config.toml" <<'EOF'
cli_auth_credentials_store = "file"
EOF
if [ -n "$OPENAI_API_KEY" ]; then
printf '%s' "$OPENAI_API_KEY" | codex login --with-api-key
else
printf '%s' "$CODEX_AUTH_JSON" > "$CODEX_HOME/auth.json"
chmod 600 "$CODEX_HOME/auth.json"
node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$CODEX_HOME/auth.json"
fi
printf '%s' "$CODEX_AUTH_JSON" > "$CODEX_HOME/auth.json"
chmod 600 "$CODEX_HOME/auth.json"
node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$CODEX_HOME/auth.json"
- name: Pre-fetch base and head refs for the PR
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
if: steps.codex_config.outputs.enabled == 'true'
env:
PR_BASE_REF: ${{ steps.pr.outputs.base_ref }}
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
git fetch --no-tags origin \
"$PR_BASE_REF" \
"+refs/pull/$PR_NUMBER/head"
- name: Fetch prior PR discussion
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
run: |
gh api "repos/$REPO/issues/$PR_NUMBER/comments?per_page=100" \
--jq '[.[] | {user: .user.login, created_at: .created_at, body: (.body | .[:4000])}] | sort_by(.created_at) | .[-20:]' \
> prior-comments.json || echo "[]" > prior-comments.json
- name: Write Codex review context
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
if: steps.codex_config.outputs.enabled == 'true'
env:
PR_REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
PR_BASE_SHA: ${{ steps.pr.outputs.base_sha }}
PR_HEAD_SHA: ${{ steps.pr.outputs.head_sha }}
PR_TITLE: ${{ steps.pr.outputs.title }}
PR_BODY: ${{ steps.pr.outputs.body }}
PR_AUTHOR: ${{ steps.pr.outputs.pr_author }}
EXTRA_PROMPT: ${{ inputs.extra_prompt }}
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_BODY: ${{ github.event.pull_request.body || '' }}
run: |
mkdir -p .github/codex
node <<'NODE'
@@ -236,11 +88,6 @@ jobs:
const lines = [
`Repository: ${process.env.PR_REPOSITORY}`,
`PR number: ${process.env.PR_NUMBER}`,
];
if (process.env.PR_AUTHOR) {
lines.push(`PR AUTHOR: ${process.env.PR_AUTHOR}`);
}
lines.push(
`Base SHA: ${process.env.PR_BASE_SHA}`,
`Head SHA: ${process.env.PR_HEAD_SHA}`,
'',
@@ -258,47 +105,24 @@ jobs:
'',
'Full review diff command:',
`git diff --unified=0 ${process.env.PR_BASE_SHA}...${process.env.PR_HEAD_SHA}`
);
if (process.env.EXTRA_PROMPT && process.env.EXTRA_PROMPT.trim()) {
lines.push('', 'Additional reviewer instructions:', process.env.EXTRA_PROMPT.trim());
}
if (fs.existsSync('prior-comments.json')) {
try {
const comments = JSON.parse(fs.readFileSync('prior-comments.json', 'utf8'));
if (Array.isArray(comments) && comments.length > 0) {
lines.push(
'',
'Prior PR discussion (most recent up to 20 comments):',
'',
'If you have already reviewed this PR (look for your own earlier "## Codex Review" comment), focus on what changed since then per the diff and respect any decisions the human made in replies. Do not re-flag findings the human already pushed back on.',
''
);
for (const c of comments) {
lines.push(`### @${c.user} (${c.created_at})`, '', c.body, '', '---', '');
}
}
} catch (_) {}
}
];
fs.writeFileSync('.github/codex/pr-review-context.md', `${lines.join('\n')}\n`);
NODE
- name: Run Codex review
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
if: steps.codex_config.outputs.enabled == 'true'
run: |
cat REVIEW.md .github/codex/pr-review.prompt.md > /tmp/codex-prompt.md
codex exec \
-C "$GITHUB_WORKSPACE" \
-m gpt-5.5 \
-m gpt-5.4 \
-c 'model_reasoning_effort="xhigh"' \
-s danger-full-access \
-s read-only \
-o codex-final-message.md \
- < /tmp/codex-prompt.md
- < .github/codex/pr-review.prompt.md
- name: Post Codex review comment
if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
if: steps.codex_config.outputs.enabled == 'true'
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
with:
github-token: ${{ github.token }}
script: |
@@ -316,6 +140,6 @@ jobs:
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: Number(process.env.PR_NUMBER),
issue_number: context.payload.pull_request.number,
body,
});
+1 -3
View File
@@ -8,7 +8,6 @@ on:
- "backend/windmill-git-sync/**"
- "backend/windmill-api-integration-tests/tests/git_sync*"
- "backend/ee-repo-ref.txt"
- "backend/windmill-common/src/workspaces.rs"
- "integration_tests/test/git_sync_test.py"
- ".github/workflows/git-sync-test.yml"
pull_request:
@@ -17,7 +16,6 @@ on:
- "backend/windmill-git-sync/**"
- "backend/windmill-api-integration-tests/tests/git_sync*"
- "backend/ee-repo-ref.txt"
- "backend/windmill-common/src/workspaces.rs"
- "integration_tests/test/git_sync_test.py"
- ".github/workflows/git-sync-test.yml"
@@ -51,7 +49,7 @@ jobs:
echo "$CHANGED_FILES"
# Direct git sync file changes — always relevant
if echo "$CHANGED_FILES" | grep -qE '^(backend/windmill-git-sync/|backend/windmill-api-integration-tests/tests/git_sync|backend/windmill-common/src/workspaces\.rs|integration_tests/test/git_sync|\.github/workflows/git-sync-test\.yml)'; then
if echo "$CHANGED_FILES" | grep -qE '^(backend/windmill-git-sync/|backend/windmill-api-integration-tests/tests/git_sync|integration_tests/test/git_sync|\.github/workflows/git-sync-test\.yml)'; then
echo "should_run=true" >> "$GITHUB_OUTPUT"
echo "Relevant: direct git sync file changes"
exit 0
-325
View File
@@ -1,325 +0,0 @@
name: Pi Auto Review
on:
pull_request:
types: [ready_for_review, opened, synchronize]
workflow_call:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: number
extra_prompt:
description: 'Additional reviewer instructions appended to the standard review prompt'
required: false
type: string
default: ''
triggered_by:
description: 'GitHub username that triggered this review (for audit only)'
required: false
type: string
default: ''
secrets:
DEEPSEEK_API_KEY:
required: false
WINDMILL_EE_PRIVATE_ACCESS:
required: false
concurrency:
group: pi-review-${{ inputs.pr_number || github.event.pull_request.number }}
cancel-in-progress: true
jobs:
check-membership:
if: github.event_name == 'pull_request'
uses: ./.github/workflows/check-org-membership.yml
with:
commenter: ${{ github.event.pull_request.user.login }}
secrets:
access_token: ${{ secrets.ORG_ACCESS_TOKEN }}
pi-review:
needs: check-membership
runs-on: ubicloud-standard-2
timeout-minutes: 30
if: |
always() &&
(
needs.check-membership.result == 'skipped' ||
(needs.check-membership.result == 'success' && needs.check-membership.outputs.is_member == 'true')
) &&
(
github.event_name == 'workflow_call' ||
(github.event.pull_request.draft == false && github.event.pull_request.head.repo.fork == false)
)
permissions:
contents: read
issues: write
pull-requests: write
steps:
- name: Check Pi configuration
id: pi_config
env:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
run: |
if [ -n "$DEEPSEEK_API_KEY" ]; then
echo "enabled=true" >> "$GITHUB_OUTPUT"
else
echo "enabled=false" >> "$GITHUB_OUTPUT"
echo "DEEPSEEK_API_KEY is not configured; skipping Pi review."
fi
- name: Resolve PR metadata
if: steps.pi_config.outputs.enabled == 'true'
id: pr
env:
GH_TOKEN: ${{ github.token }}
INPUT_PR_NUMBER: ${{ inputs.pr_number }}
EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_BASE_REF: ${{ github.event.pull_request.base.ref }}
EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha }}
EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
EVENT_TITLE: ${{ github.event.pull_request.title }}
EVENT_BODY: ${{ github.event.pull_request.body }}
EVENT_FORK: ${{ github.event.pull_request.head.repo.fork }}
EVENT_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
if [ -n "$INPUT_PR_NUMBER" ]; then
PR_JSON=$(gh pr view "$INPUT_PR_NUMBER" --repo "${{ github.repository }}" \
--json number,baseRefName,baseRefOid,headRefOid,title,body,isCrossRepository,author)
PR_NUMBER=$(echo "$PR_JSON" | jq -r '.number')
BASE_REF=$(echo "$PR_JSON" | jq -r '.baseRefName')
BASE_SHA=$(echo "$PR_JSON" | jq -r '.baseRefOid')
HEAD_SHA=$(echo "$PR_JSON" | jq -r '.headRefOid')
PR_TITLE=$(echo "$PR_JSON" | jq -r '.title')
PR_BODY=$(echo "$PR_JSON" | jq -r '.body // ""')
IS_FORK=$(echo "$PR_JSON" | jq -r '.isCrossRepository')
PR_AUTHOR=$(echo "$PR_JSON" | jq -r '.author.login // ""')
else
PR_NUMBER="$EVENT_PR_NUMBER"
BASE_REF="$EVENT_BASE_REF"
BASE_SHA="$EVENT_BASE_SHA"
HEAD_SHA="$EVENT_HEAD_SHA"
PR_TITLE="$EVENT_TITLE"
PR_BODY="$EVENT_BODY"
IS_FORK="$EVENT_FORK"
PR_AUTHOR="$EVENT_AUTHOR"
fi
if [ "$IS_FORK" = "true" ]; then
echo "Skipping Pi review for fork PR."
echo "skip=true" >> "$GITHUB_OUTPUT"
exit 0
fi
{
echo "skip=false"
echo "pr_number=$PR_NUMBER"
echo "base_ref=$BASE_REF"
echo "base_sha=$BASE_SHA"
echo "head_sha=$HEAD_SHA"
echo "pr_author=$PR_AUTHOR"
echo 'title<<PR_TITLE_EOF'
printf '%s\n' "$PR_TITLE"
echo 'PR_TITLE_EOF'
echo 'body<<PR_BODY_EOF'
printf '%s\n' "$PR_BODY"
echo 'PR_BODY_EOF'
} >> "$GITHUB_OUTPUT"
- name: Checkout repository
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
uses: actions/checkout@v5
with:
ref: refs/pull/${{ steps.pr.outputs.pr_number }}/merge
fetch-depth: 1
- name: Check EE access
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
id: ee
env:
EE_TOKEN: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
run: |
if [ -n "$EE_TOKEN" ]; then
echo "available=true" >> "$GITHUB_OUTPUT"
echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_OUTPUT"
else
echo "available=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout EE repository
if: steps.ee.outputs.available == 'true'
uses: actions/checkout@v5
with:
repository: windmill-labs/windmill-ee-private
path: ./windmill-ee-private
ref: ${{ steps.ee.outputs.ee_repo_ref }}
token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
fetch-depth: 1
- name: Substitute EE code
if: steps.ee.outputs.available == 'true'
run: ./backend/substitute_ee_code.sh --copy --dir ./windmill-ee-private
- name: Set up Node.js
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install Pi CLI
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
run: npm install --global @mariozechner/pi-coding-agent
- name: Pre-fetch base and head refs for the PR
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
env:
PR_BASE_REF: ${{ steps.pr.outputs.base_ref }}
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
run: |
git fetch --no-tags origin \
"$PR_BASE_REF" \
"+refs/pull/$PR_NUMBER/head"
- name: Fetch prior PR discussion
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
run: |
gh api "repos/$REPO/issues/$PR_NUMBER/comments?per_page=100" \
--jq '[.[] | {user: .user.login, created_at: .created_at, body: (.body | .[:4000])}] | sort_by(.created_at) | .[-20:]' \
> prior-comments.json || echo "[]" > prior-comments.json
- name: Write Pi review context
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
env:
PR_REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
PR_BASE_SHA: ${{ steps.pr.outputs.base_sha }}
PR_HEAD_SHA: ${{ steps.pr.outputs.head_sha }}
PR_TITLE: ${{ steps.pr.outputs.title }}
PR_BODY: ${{ steps.pr.outputs.body }}
PR_AUTHOR: ${{ steps.pr.outputs.pr_author }}
EXTRA_PROMPT: ${{ inputs.extra_prompt }}
run: |
mkdir -p .github/pi
node <<'NODE'
const fs = require('fs');
const lines = [
`Repository: ${process.env.PR_REPOSITORY}`,
`PR number: ${process.env.PR_NUMBER}`,
];
if (process.env.PR_AUTHOR) {
lines.push(`PR AUTHOR: ${process.env.PR_AUTHOR}`);
}
lines.push(
`Base SHA: ${process.env.PR_BASE_SHA}`,
`Head SHA: ${process.env.PR_HEAD_SHA}`,
'',
'PR title:',
process.env.PR_TITLE || '(empty)',
'',
'PR body:',
process.env.PR_BODY || '(empty)',
'',
'Changed commits command:',
`git log --oneline ${process.env.PR_BASE_SHA}...${process.env.PR_HEAD_SHA}`,
'',
'Changed files command:',
`git diff --stat ${process.env.PR_BASE_SHA}...${process.env.PR_HEAD_SHA}`,
'',
'Full review diff command:',
`git diff --unified=0 ${process.env.PR_BASE_SHA}...${process.env.PR_HEAD_SHA}`
);
if (process.env.EXTRA_PROMPT && process.env.EXTRA_PROMPT.trim()) {
lines.push('', 'Additional reviewer instructions:', process.env.EXTRA_PROMPT.trim());
}
if (fs.existsSync('prior-comments.json')) {
try {
const comments = JSON.parse(fs.readFileSync('prior-comments.json', 'utf8'));
if (Array.isArray(comments) && comments.length > 0) {
lines.push(
'',
'Prior PR discussion (most recent up to 20 comments):',
'',
'If you have already reviewed this PR (look for your own earlier "## Pi Review (DeepSeek V4)" comment), focus on what changed since then per the diff and respect any decisions the human made in replies. Do not re-flag findings the human already pushed back on.',
''
);
for (const c of comments) {
lines.push(`### @${c.user} (${c.created_at})`, '', c.body, '', '---', '');
}
}
} catch (_) {}
}
fs.writeFileSync('.github/pi/pr-review-context.md', `${lines.join('\n')}\n`);
NODE
- name: Run Pi review
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
env:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
PI_SKIP_VERSION_CHECK: '1'
run: |
set -o pipefail
cat REVIEW.md .github/pi/pr-review.prompt.md > /tmp/pi-prompt.md
pi -p \
--provider deepseek \
--model deepseek-v4-pro \
--tools read,grep,find,ls,bash \
--mode json \
< /tmp/pi-prompt.md \
| tee pi-events.jsonl \
| jq -rc --unbuffered '
if .type == "agent_start" then "🤖 pi agent started"
elif .type == "turn_start" then "── turn ──"
elif .type == "message_end" then
"[\(.message.role)] " + (
(.message.content // [])
| map(
if .type == "text" then "text(\(.text | length)c)"
elif .type == "tool_use" then "🔧 \(.name) \(.input | @json | .[:160])"
elif .type == "tool_result" then "✅ result"
else .type
end
)
| join(" | ")
)
elif .type == "turn_end" then "── turn done (\((.toolResults // []) | length) tool result(s)) ──"
elif .type == "agent_end" then "🏁 pi agent done"
else empty
end
'
jq -r '
select(.type == "agent_end")
| .messages
| map(select(.role == "assistant"))
| last
| (.content[]? | select(.type == "text") | .text)
' pi-events.jsonl > pi-final-message.md
- name: Post Pi review comment
if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true'
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
with:
github-token: ${{ github.token }}
script: |
const fs = require('fs');
const path = `${process.env.GITHUB_WORKSPACE}/pi-final-message.md`;
if (!fs.existsSync(path)) {
core.info('Pi did not produce a final message; skipping PR comment.');
return;
}
const body = fs.readFileSync(path, 'utf8').trim();
if (!body) {
core.info('Pi final message was empty; skipping PR comment.');
return;
}
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: Number(process.env.PR_NUMBER),
body,
});
+5 -122
View File
@@ -3,147 +3,31 @@ name: Claude Auto Review
on:
pull_request:
types: [ready_for_review, opened]
workflow_call:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: number
extra_prompt:
description: 'Additional reviewer instructions appended to the standard review prompt'
required: false
type: string
default: ''
triggered_by:
description: 'GitHub username that triggered this review (for audit only)'
required: false
type: string
default: ''
secrets:
CLAUDE_CODE_OAUTH_TOKEN:
required: true
WINDMILL_EE_PRIVATE_ACCESS:
required: false
concurrency:
group: claude-review-${{ inputs.pr_number || github.event.pull_request.number }}
group: claude-review-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
check-membership:
if: github.event_name == 'pull_request'
uses: ./.github/workflows/check-org-membership.yml
with:
commenter: ${{ github.event.pull_request.user.login }}
secrets:
access_token: ${{ secrets.ORG_ACCESS_TOKEN }}
auto-review:
needs: check-membership
runs-on: ubuntu-latest
if: |
always() &&
(
needs.check-membership.result == 'skipped' ||
(needs.check-membership.result == 'success' && needs.check-membership.outputs.is_member == 'true')
) &&
(
github.event_name == 'workflow_call' ||
(github.event.pull_request.draft == false || github.event.pull_request.ready_for_review == true)
)
if: github.event.pull_request.draft == false || github.event.pull_request.ready_for_review == true
permissions:
contents: read
pull-requests: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Check EE access
id: ee
env:
EE_TOKEN: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
run: |
if [ -n "$EE_TOKEN" ]; then
echo "available=true" >> "$GITHUB_OUTPUT"
echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_OUTPUT"
else
echo "available=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout EE repository
if: steps.ee.outputs.available == 'true'
uses: actions/checkout@v5
with:
repository: windmill-labs/windmill-ee-private
path: ./windmill-ee-private
ref: ${{ steps.ee.outputs.ee_repo_ref }}
token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
fetch-depth: 1
- name: Substitute EE code
if: steps.ee.outputs.available == 'true'
run: ./backend/substitute_ee_code.sh --copy --dir ./windmill-ee-private
- name: Resolve PR number
id: resolve
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
INPUT_PR_NUMBER: ${{ inputs.pr_number }}
EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_PR_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
if [ -n "$INPUT_PR_NUMBER" ]; then
PR_NUMBER="$INPUT_PR_NUMBER"
PR_AUTHOR=$(gh api "repos/$REPO/pulls/$PR_NUMBER" --jq '.user.login')
else
PR_NUMBER="$EVENT_PR_NUMBER"
PR_AUTHOR="$EVENT_PR_AUTHOR"
fi
echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
echo "pr_author=$PR_AUTHOR" >> "$GITHUB_OUTPUT"
- name: Fetch prior PR discussion
id: prior
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ steps.resolve.outputs.pr_number }}
run: |
gh api "repos/$REPO/issues/$PR_NUMBER/comments?per_page=100" \
--jq '[.[] | {user: .user.login, created_at: .created_at, body: (.body | .[:4000])}] | sort_by(.created_at) | .[-20:]' \
> prior-comments.json || echo "[]" > prior-comments.json
jq -r '
if length == 0 then ""
else
"## Prior PR discussion (most recent up to 20 comments)\n\nIf you have already reviewed this PR (look for your own earlier comment), focus on what changed since then per the diff and respect any decisions the human made in replies. Do not re-flag findings the human already pushed back on.\n\n" +
(map("### @\(.user) (\(.created_at))\n\n\(.body)") | join("\n\n---\n\n"))
end
' prior-comments.json > prior-comments.md
- name: Read review prompt
id: review-prompt
env:
EXTRA_PROMPT: ${{ inputs.extra_prompt }}
run: |
{
echo 'REVIEW_PROMPT<<EOF'
cat REVIEW.md
echo ''
cat .claude/review-prompt.md
if [ -n "$EXTRA_PROMPT" ]; then
echo ''
echo '## Additional reviewer instructions'
echo ''
printf '%s\n' "$EXTRA_PROMPT"
fi
if [ -s prior-comments.md ]; then
echo ''
cat prior-comments.md
fi
echo 'EOF'
} >> "$GITHUB_ENV"
@@ -154,10 +38,9 @@ jobs:
track_progress: true
prompt: |
REPO: ${{ github.repository }}
PR NUMBER: ${{ steps.resolve.outputs.pr_number }}
PR AUTHOR: ${{ steps.resolve.outputs.pr_author }}
PR NUMBER: ${{ github.event.pull_request.number }}
${{ env.REVIEW_PROMPT }}
claude_args: |
--allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*)"
--model claude-opus-4-8
--model opus
-123
View File
@@ -1,123 +0,0 @@
name: PR Review Commands
on:
issue_comment:
types: [created]
jobs:
parse:
if: github.event.issue.pull_request != null
runs-on: ubuntu-latest
outputs:
command: ${{ steps.parse.outputs.command }}
extra_prompt: ${{ steps.parse.outputs.extra_prompt }}
steps:
- name: Parse command from comment
id: parse
env:
BODY: ${{ github.event.comment.body }}
run: |
FIRST_LINE=$(printf '%s' "$BODY" | head -n 1 | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//')
FIRST_WORD=${FIRST_LINE%% *}
case "$FIRST_WORD" in
/review|/codex|/pi|/claude)
COMMAND="${FIRST_WORD#/}"
REMAINDER_FIRST_LINE=${FIRST_LINE#"$FIRST_WORD"}
REMAINDER_FIRST_LINE=${REMAINDER_FIRST_LINE# }
REST=$(printf '%s' "$BODY" | tail -n +2)
{
echo "command=$COMMAND"
echo 'extra_prompt<<EXTRA_EOF'
if [ -n "$REMAINDER_FIRST_LINE" ]; then
printf '%s\n' "$REMAINDER_FIRST_LINE"
fi
if [ -n "$REST" ]; then
printf '%s\n' "$REST"
fi
echo 'EXTRA_EOF'
} >> "$GITHUB_OUTPUT"
;;
*)
echo "command=" >> "$GITHUB_OUTPUT"
;;
esac
check-membership:
needs: parse
if: needs.parse.outputs.command != ''
uses: ./.github/workflows/check-org-membership.yml
secrets:
access_token: ${{ secrets.ORG_ACCESS_TOKEN }}
acknowledge:
needs: [parse, check-membership]
if: needs.parse.outputs.command != '' && needs.check-membership.outputs.is_member == 'true'
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- name: React to comment with eyes
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
COMMENT_ID: ${{ github.event.comment.id }}
run: |
gh api -X POST \
"/repos/$REPO/issues/comments/$COMMENT_ID/reactions" \
-f content=eyes >/dev/null
claude:
needs: [parse, check-membership]
if: |
needs.check-membership.outputs.is_member == 'true' &&
(needs.parse.outputs.command == 'review' || needs.parse.outputs.command == 'claude')
permissions:
contents: read
pull-requests: read
id-token: write
uses: ./.github/workflows/pr-ready-review.yml
with:
pr_number: ${{ github.event.issue.number }}
extra_prompt: ${{ needs.parse.outputs.extra_prompt }}
triggered_by: ${{ github.event.comment.user.login }}
secrets:
CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
WINDMILL_EE_PRIVATE_ACCESS: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
codex:
needs: [parse, check-membership]
if: |
needs.check-membership.outputs.is_member == 'true' &&
(needs.parse.outputs.command == 'review' || needs.parse.outputs.command == 'codex')
permissions:
contents: read
issues: write
pull-requests: write
uses: ./.github/workflows/codex-pr-review.yml
with:
pr_number: ${{ github.event.issue.number }}
extra_prompt: ${{ needs.parse.outputs.extra_prompt }}
triggered_by: ${{ github.event.comment.user.login }}
secrets:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
CODEX_AUTH_JSON: ${{ secrets.CODEX_AUTH_JSON }}
WINDMILL_EE_PRIVATE_ACCESS: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
pi:
needs: [parse, check-membership]
if: |
needs.check-membership.outputs.is_member == 'true' &&
(needs.parse.outputs.command == 'review' || needs.parse.outputs.command == 'pi')
permissions:
contents: read
issues: write
pull-requests: write
uses: ./.github/workflows/pi-pr-review.yml
with:
pr_number: ${{ github.event.issue.number }}
extra_prompt: ${{ needs.parse.outputs.extra_prompt }}
triggered_by: ${{ github.event.comment.user.login }}
secrets:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
WINDMILL_EE_PRIVATE_ACCESS: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }}
-84
View File
@@ -1,84 +0,0 @@
name: Publish CLI docs repo
# Regenerates the windmill-cli-docs repo (consumed by context7) from the
# canonical sources in this repo on every Windmill release.
#
# Required secret:
# CLI_DOCS_DEPLOY_KEY — ed25519 private key whose public half is registered
# as a write-access deploy key on
# windmill-labs/windmill-cli-docs.
on:
push:
tags:
- "v*"
workflow_dispatch:
# Serialize pushes to windmill-cli-docs so two release tags landing close
# together (e.g. a release-please bump + a hotfix) can't race to force-push
# the docs repo.
concurrency:
group: publish-cli-docs
cancel-in-progress: false
jobs:
publish:
runs-on: ubuntu-latest
steps:
- name: Checkout windmill (source of truth)
uses: actions/checkout@v4
with:
path: windmill
- name: Checkout windmill-cli-docs (publish target)
uses: actions/checkout@v4
with:
repository: windmill-labs/windmill-cli-docs
path: windmill-cli-docs
ssh-key: ${{ secrets.CLI_DOCS_DEPLOY_KEY }}
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install dependencies
run: pip install pyyaml
- name: Regenerate docs
run: |
python3 windmill/system_prompts/generate.py \
--context7-dir "$GITHUB_WORKSPACE/windmill-cli-docs"
- name: Commit and push if changed
working-directory: windmill-cli-docs
env:
REF_NAME: ${{ github.ref_name }}
REF_TYPE: ${{ github.ref_type }}
run: |
git config user.name "windmill-bot"
git config user.email "bot@windmill.dev"
git add -A
if git diff --cached --quiet; then
echo "No doc changes for ${REF_NAME}."
committed=false
else
committed=true
if [ "${REF_TYPE}" = "tag" ]; then
git commit -m "chore: sync from windmill ${REF_NAME}"
else
git commit -m "chore: sync from windmill (manual dispatch from ${REF_NAME})"
fi
git push origin HEAD
fi
# Always mirror the version tag on tag pushes, even when content
# didn't change — downstream consumers tie snapshots to releases by
# tag, and skipping it would leave the docs repo without a tag for
# the new Windmill release.
# workflow_dispatch from a non-tag ref skips this so we don't
# create a junk tag named after a branch.
if [ "${REF_TYPE}" = "tag" ]; then
git tag -f "${REF_NAME}"
git push origin "${REF_NAME}" --force
echo "Mirrored tag ${REF_NAME} to windmill-cli-docs (content changed: ${committed})."
fi
@@ -0,0 +1,126 @@
name: Spawn Ephemeral Backend
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
workflow_dispatch:
inputs:
pr_number:
description: "PR number"
required: true
type: number
jobs:
check-membership:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '/spawnbackend')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '/spawnbackend'))
uses: ./.github/workflows/check-org-membership.yml
secrets:
access_token: ${{ secrets.ORG_ACCESS_TOKEN }}
spawn-backend:
needs: check-membership
# Only run on PR comments that contain /spawn-backend, or manual dispatch
if: |
github.event_name == 'workflow_dispatch' ||
(github.event.issue.pull_request && needs.check-membership.outputs.is_member == 'true')
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: read
steps:
- name: Get PR details
id: pr-details
uses: actions/github-script@v7
with:
script: |
const prNumber = context.eventName === 'workflow_dispatch'
? context.payload.inputs.pr_number
: context.issue.number;
const pr = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber
});
// Get branch name and format it for Cloudflare Pages
// Replace '/' with '-' for the URL
const branchName = pr.data.head.ref;
const formattedBranch = branchName.replace(/\//g, '-');
const cfFrontendUrl = `https://${formattedBranch}.windmill.pages.dev`;
core.setOutput('commit_hash', pr.data.head.sha);
core.setOutput('pr_number', prNumber);
core.setOutput('branch_name', branchName);
core.setOutput('cf_frontend_url', cfFrontendUrl);
- name: Check manager URL
id: check-manager-url
run: |
if [ -z "${{ secrets.EPHEMERAL_BACKEND_QUEUE_URL }}" ]; then
echo "manager_url_set=false" >> $GITHUB_OUTPUT
else
echo "manager_url_set=true" >> $GITHUB_OUTPUT
fi
- name: Post error comment if manager not running
if: steps.check-manager-url.outputs.manager_url_set == 'false'
uses: actions/github-script@v7
with:
script: |
const prNumber = context.eventName === 'workflow_dispatch'
? Number(context.payload.inputs.pr_number)
: context.issue.number;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body: `❌ Manager URL not set (did you start the ephemeral backend manager?)\n\nThe ephemeral backend manager needs to be running to spawn backends. Please start the manager first.`
});
- name: Fail if manager not running
if: steps.check-manager-url.outputs.manager_url_set == 'false'
run: |
echo "Error: EPHEMERAL_BACKEND_QUEUE_URL secret is not set"
exit 1
- name: Trigger Windmill flow
if: steps.check-manager-url.outputs.manager_url_set == 'true'
id: trigger-flow
run: |
JOB_UUID=$(curl -s -X POST "https://app.windmill.dev/api/w/windmill-labs/jobs/run/f/f/all/run_ephemeral_backend" \
-H "Authorization: Bearer ${{ secrets.WINDMILL_RUN_FLOW_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{
"manager_url": "${{ secrets.EPHEMERAL_BACKEND_QUEUE_URL }}",
"commit_hash": "${{ steps.pr-details.outputs.commit_hash }}",
"pr_number": ${{ steps.pr-details.outputs.pr_number }},
"cf_frontend_url": "${{ steps.pr-details.outputs.cf_frontend_url }}"
}' | tr -d '"')
echo "Job UUID: $JOB_UUID"
echo "job_uuid=$JOB_UUID" >> $GITHUB_OUTPUT
- name: Post comment with job link
if: steps.check-manager-url.outputs.manager_url_set == 'true'
uses: actions/github-script@v7
with:
script: |
const jobUuid = '${{ steps.trigger-flow.outputs.job_uuid }}';
const appUrl = `https://app.windmill.dev/public/windmill-labs/a106bad0256c1dfa7a4f9279c42b1a4b#${jobUuid}`;
const prNumber = context.eventName === 'workflow_dispatch'
? Number(context.payload.inputs.pr_number)
: context.issue.number;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body: `🚀 Spawning new ephemeral backend!\n\n${appUrl}`
});
-3
View File
@@ -20,7 +20,6 @@ rust-client/Cargo.toml
# Worktree-specific Claude Code settings (generated by scripts/worktree-env)
.claude/settings.local.json
.claude/worktrees/
# Symlinked cache directories (for git worktrees)
backend/target
@@ -33,5 +32,3 @@ backend/chrome_profiler.json
.fast-check/
__pycache__/
.playwright-mcp/
.codex
.claude/scheduled_tasks.lock
-10
View File
@@ -3,16 +3,6 @@
"svelte": {
"type": "http",
"url": "https://mcp.svelte.dev/mcp"
},
"playwright": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@playwright/mcp@latest", "--browser", "chromium", "--headless"]
},
"playwright-headed": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@playwright/mcp@latest", "--browser", "chromium"]
}
}
}
-48
View File
@@ -47,7 +47,6 @@ profiles:
For this window specifically, backend is running on: ${BACKEND_PORT} and frontend is running on: ${FRONTEND_PORT}.
To connect to the database, use this connection string: ${DATABASE_URL}
Because we are running backend with cargo watch, to verify your changes, just check the logs in the backend pane. No need for cargo check.
For UI verification, use the Playwright MCP (`mcp__playwright__*`) — the `playwright` server is headless and works without a display. Navigate to http://localhost:${FRONTEND_PORT}, log in as admin@windmill.dev / changeme.
IMPORTANT: Read docs/autonomous-mode.md before starting any work.
panes:
- id: agent
@@ -77,7 +76,6 @@ profiles:
On this window specifically, frontend is running on: ${FRONTEND_PORT}.
To connect to the database, use this connection string: ${DATABASE_URL}
Because we are running frontend with npm run dev, to verify your changes, just check the logs in the frontend pane. No need for npm run build.
For UI verification, use the Playwright MCP (`mcp__playwright__*`) — the `playwright` server is headless and works without a display. Navigate to http://localhost:${FRONTEND_PORT}, log in as admin@windmill.dev / changeme.
IMPORTANT: Read docs/autonomous-mode.md before starting any work.
panes:
- id: agent
@@ -102,55 +100,9 @@ profiles:
integrations:
github:
autoRemoveOnMerge: true
linkedRepos:
- repo: windmill-labs/windmill-ee-private
alias: ee-private
dir: ../windmill-ee-private__worktrees
linear:
enabled: true
autoCreateWorktrees: true
watchTeams: [WIN,GIT]
oneshot:
systemPrompt: |
You are running in webmux ONESHOT mode.
# No interactive user
There is NO interactive user — nobody is watching the chat or will respond
to questions, approvals, or status checks. Any message asking the user to
review, approve, confirm, take a look, or "let you know" is wasted output:
it will not be answered.
# Your job
Take the task to its real conclusion without pausing:
1. Make the change.
2. Validate it (run the relevant tests, typecheck, build, or quick
manual check). For UI changes, drive the running frontend with
the Playwright MCP (`mcp__playwright__*`, headless) and confirm
the change works end-to-end before moving on.
3. Commit.
4. Push.
5. Open a pull request.
Only then are you done.
# Decisions
When something is ambiguous, pick the most reasonable default and proceed.
When you would normally ask "should I X or Y?", just pick one and continue
— note the choice in the PR description if it matters.
# PR readiness
Default to opening the PR as a draft. If you are highly confident in the
change — the scope is small and well-understood, validation passed
cleanly, and you would not change anything if a reviewer pushed back —
open the PR as ready-for-review directly (omit `--draft` when invoking
`gh pr create`, or call `gh pr ready <number>` after creation). Err on
the side of draft when validation was partial, the change touches
public APIs or shared infrastructure, or you made a non-obvious judgment
call.
# Ending your turn
Never end your turn with a question, a suggestion to "take a look", or a
request for approval. Stop only when the PR is open, or when you hit a
technical error you cannot recover from yourself (in which case clearly
state the blocker).
-113
View File
@@ -1,113 +0,0 @@
# Windmill
Open-source platform for internal tools, workflows, API integrations, background jobs, and UIs. Rust backend + Svelte 5 frontend.
## Workflow
1. **Understand**: Before coding, explore the codebase (see Code Navigation below). Use `outline` to understand file structure, `body` to read specific symbols, `def`/`callers`/`callees` to trace code, `Grep` to find usages. Read `docs/` for domain context.
2. **Plan**: For non-trivial changes, use plan mode. For large features, break into reviewable stages
3. **Execute**: Follow coding patterns from skills (`rust-backend`, `svelte-frontend`)
4. **Validate**: After every change, run the appropriate checks per `docs/validation.md`
## Documentation
- **Validation**: `docs/validation.md` — what checks to run based on what you changed
- **Enterprise**: `docs/enterprise.md` — EE file conventions and PR workflow
- **Backend patterns**: use the `rust-backend` skill when writing Rust code
- **Frontend patterns**: use the `svelte-frontend` skill when writing Svelte code. Do NOT edit svelte files unless you have read that skill.
- **Frontend UUIDs**: do not call `crypto.randomUUID()` in frontend code. Import `randomUUID` from `$lib/utils/uuid` instead.
- **Code review**: review the current PR or branch against the shared review policy in `REVIEW.md` (severity triage, public-surface checklist, AGENTS.md compliance, test-coverage assessment). The skill at `.agents/skills/local-review/SKILL.md` orchestrates it. All three CLIs auto-discover the same SKILL — Claude reads `.claude/skills/` (symlinked to the canonical `.agents/skills/` file), Codex and Pi read `.agents/skills/` directly. Invoke with `/local-review` in Claude Code, `$local-review` (or `/skills` selector) in Codex, or `pi --skill local-review` / `/skill:local-review` in Pi.
- **Domain guides**: `.claude/skills/native-trigger/` and `frontend/tutorial-system-guide.mdc`
- **Brand/UI guidelines**: `frontend/brand-guidelines.md`
- **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.
## Dev Environment
- **Backend**: `cargo run` from `backend/` (API at http://localhost:8000)
- **Frontend**: `REMOTE=http://localhost:8000 npm run dev` from `frontend/` (port 3000+)
- **DB**: `psql postgres://postgres:changeme@localhost:5432/windmill`
- **Login**: `admin@windmill.dev` / `changeme`
- **Instance settings**: navigate to `/#superadmin-settings`
- **Migrations**: use `cargo sqlx migrate add -r <name>` from `backend/` to create new migrations (never generate timestamps manually)
## Verifying Frontend Changes
After modifying frontend code, drive the running dev server with the **Playwright MCP** to verify the change in a real browser — don't claim a UI change works without exercising it.
Two MCP servers are registered in `.mcp.json`:
- `playwright` — headless Chromium, default for devboxes (no display required)
- `playwright-headed` — windowed Chromium, when a display is available
**One-time setup:** run `npx playwright install chromium` to download the browser binary (Playwright won't fetch it automatically on first use).
Typical flow:
1. Ensure backend (`cargo run`) and frontend (`REMOTE=http://localhost:8000 npm run dev`) are running
2. `mcp__playwright__browser_navigate` to the relevant page (login at `admin@windmill.dev` / `changeme`)
3. `mcp__playwright__browser_snapshot` to inspect the accessibility tree (preferred over screenshots for reading the DOM)
4. `mcp__playwright__browser_click` / `browser_fill_form` / `browser_type` to interact
5. `mcp__playwright__browser_take_screenshot` for visual confirmation
6. `mcp__playwright__browser_console_messages` / `browser_network_requests` to surface errors
**Attach the screenshots to the PR.** For any change under `frontend/`, embed screenshots of the affected UI in the PR body — the `pr` skill requires this and carries the upload recipe.
If you cannot exercise a UI change (no dev server, etc.), say so explicitly rather than claiming success.
## Banned Patterns
### `$bindable(default_value)` on optional props
Using `$bindable(default_value)` on props that can be `undefined` is **banned**. This pattern causes subtle bugs because the default value masks the `undefined` state.
**Bad:**
```svelte
let { my_prop = $bindable(default_value) }: { my_prop?: string } = $props()
```
**Correct alternatives:**
1. **Use `$derived` with nullish coalescing** — handle the potential `undefined` at the usage site:
```svelte
let { my_prop = $bindable() }: { my_prop?: string } = $props()
let effective_value = $derived(my_prop ?? default_value)
```
2. **Create a `useMyPropState()` helper** — encapsulate the undefined-handling logic in a reusable function and call it higher in the component tree, so the child component always receives a defined value.
## Code Navigation
`wm-ts-nav` is an AST-aware code navigator. Use **wm-ts-nav** for structural queries — it skips comments/strings and understands symbol boundaries.
**MUST use `outline` before `Read`** on unfamiliar files — a 500-line file costs ~500 lines of context, while `outline` costs ~20. Then **MUST use `body "X"`** instead of reading a full file to see one function/struct. Use `Read` with offset/limit only when you need surrounding context that `body` doesn't capture.
- `refs "X" --caller` instead of reading files to find which function contains each reference
- `callers "X"` / `callees "X"` for call-graph questions
EE files (`*_ee.rs`, `*_ee.ts`, `*_ee.svelte`) are indexed — you can `outline`, `def`, `body`, `refs` etc. on them just like regular files.
```bash
NAV="sh wm-ts-nav/nav"
# Use --root backend for Rust, --root frontend/src for TS/Svelte
$NAV --root backend outline backend/path/to/file.rs # file structure
$NAV --root backend def "ServiceName" # find definition
$NAV --root backend body "decrypt_oauth_data" # extract source code
$NAV --root backend search "%" --parent ServiceName # methods on a type
$NAV --root backend search "Trigger" --kind struct # find by kind
$NAV --root backend refs "X" --file handler.rs --caller # scoped refs with caller
$NAV --root backend callers "X" # who calls X?
$NAV --root backend callees "X" # what does X call?
```
**Limitations** — syntax-level analysis, no type inference. Use **Grep** instead when completeness matters (finding all usages, exhaustiveness checks):
- `refs`/`callers`/`callees` can't follow re-exports, glob imports, or different import paths to the same symbol
- Trait impls, macro-generated symbols (`sqlx::FromRow`), and namespace member access (`ns.X`) are invisible
- `callees` shows all identifiers in a function body, not just actual calls
## Core Principles
- **MUST `outline` before `Read`** on unfamiliar files — then `body` or `Read` with offset/limit for specifics
- Search for existing code to reuse before writing new code
- Follow established patterns in the codebase
- Keep changes focused — don't refactor beyond what's asked
- **Comments record constraints, not narration.** Write a comment only for what the code can't show: why a non-obvious approach is required, what breaks if it's "simplified" away. State each invariant once, at the place where someone would break it, in ≤4 lines. Don't describe what the next line does, don't repeat the same rationale at multiple sites, and don't address the PR reviewer (justifying a change belongs in the PR description, not the code). Describe the code as it is, never its drafting history: "we no longer do X", "unchanged behavior", "instead of the previous approach" are meaningless to a reader who never saw the earlier iteration — before finishing, reread your comments as if the current state is the only state that ever existed.
- **Never attribute work to a specific customer, account, or "requested by a customer" in repo-tracked content** (PR descriptions, commit messages, code comments, docs). Describe changes by their technical motivation instead.
-1183
View File
File diff suppressed because it is too large Load Diff
+87 -1
View File
@@ -1 +1,87 @@
@AGENTS.md
# Windmill
Open-source platform for internal tools, workflows, API integrations, background jobs, and UIs. Rust backend + Svelte 5 frontend.
## Workflow
1. **Understand**: Before coding, explore the codebase (see Code Navigation below). Use `outline` to understand file structure, `body` to read specific symbols, `def`/`callers`/`callees` to trace code, `Grep` to find usages. Read `docs/` for domain context.
2. **Plan**: For non-trivial changes, use plan mode. For large features, break into reviewable stages
3. **Execute**: Follow coding patterns from skills (`rust-backend`, `svelte-frontend`)
4. **Validate**: After every change, run the appropriate checks per `docs/validation.md`
## Documentation
- **Validation**: `docs/validation.md` — what checks to run based on what you changed
- **Enterprise**: `docs/enterprise.md` — EE file conventions and PR workflow
- **Backend patterns**: use the `rust-backend` skill when writing Rust code
- **Frontend patterns**: use the `svelte-frontend` skill when writing Svelte code. Do NOT edit svelte files unless you have read that skill.
- **Code review**: use `/local-review` to review a PR for bugs and CLAUDE.md compliance
- **Domain guides**: `.claude/skills/native-trigger/` and `frontend/tutorial-system-guide.mdc`
- **Brand/UI guidelines**: `frontend/brand-guidelines.md`
## Dev Environment
- **Backend**: `cargo run` from `backend/` (API at http://localhost:8000)
- **Frontend**: `REMOTE=http://localhost:8000 npm run dev` from `frontend/` (port 3000+)
- **DB**: `psql postgres://postgres:changeme@localhost:5432/windmill`
- **Login**: `admin@windmill.dev` / `changeme`
- **Instance settings**: navigate to `/#superadmin-settings`
- **Migrations**: use `cargo sqlx migrate add -r <name>` from `backend/` to create new migrations (never generate timestamps manually)
## Banned Patterns
### `$bindable(default_value)` on optional props
Using `$bindable(default_value)` on props that can be `undefined` is **banned**. This pattern causes subtle bugs because the default value masks the `undefined` state.
**Bad:**
```svelte
let { my_prop = $bindable(default_value) }: { my_prop?: string } = $props()
```
**Correct alternatives:**
1. **Use `$derived` with nullish coalescing** — handle the potential `undefined` at the usage site:
```svelte
let { my_prop = $bindable() }: { my_prop?: string } = $props()
let effective_value = $derived(my_prop ?? default_value)
```
2. **Create a `useMyPropState()` helper** — encapsulate the undefined-handling logic in a reusable function and call it higher in the component tree, so the child component always receives a defined value.
## Code Navigation
`wm-ts-nav` is an AST-aware code navigator. Use **wm-ts-nav** for structural queries — it skips comments/strings and understands symbol boundaries.
**MUST use `outline` before `Read`** on unfamiliar files — a 500-line file costs ~500 lines of context, while `outline` costs ~20. Then **MUST use `body "X"`** instead of reading a full file to see one function/struct. Use `Read` with offset/limit only when you need surrounding context that `body` doesn't capture.
- `refs "X" --caller` instead of reading files to find which function contains each reference
- `callers "X"` / `callees "X"` for call-graph questions
EE files (`*_ee.rs`, `*_ee.ts`, `*_ee.svelte`) are indexed — you can `outline`, `def`, `body`, `refs` etc. on them just like regular files.
```bash
NAV="sh wm-ts-nav/nav"
# Use --root backend for Rust, --root frontend/src for TS/Svelte
$NAV --root backend outline backend/path/to/file.rs # file structure
$NAV --root backend def "ServiceName" # find definition
$NAV --root backend body "decrypt_oauth_data" # extract source code
$NAV --root backend search "%" --parent ServiceName # methods on a type
$NAV --root backend search "Trigger" --kind struct # find by kind
$NAV --root backend refs "X" --file handler.rs --caller # scoped refs with caller
$NAV --root backend callers "X" # who calls X?
$NAV --root backend callees "X" # what does X call?
```
**Limitations** — syntax-level analysis, no type inference. Use **Grep** instead when completeness matters (finding all usages, exhaustiveness checks):
- `refs`/`callers`/`callees` can't follow re-exports, glob imports, or different import paths to the same symbol
- Trait impls, macro-generated symbols (`sqlx::FromRow`), and namespace member access (`ns.X`) are invisible
- `callees` shows all identifiers in a function body, not just actual calls
## Core Principles
- **MUST `outline` before `Read`** on unfamiliar files — then `body` or `Read` with offset/limit for specifics
- Search for existing code to reuse before writing new code
- Follow established patterns in the codebase
- Keep changes focused — don't refactor beyond what's asked
+5 -19
View File
@@ -66,7 +66,6 @@ RUN npm ci
COPY frontend .
RUN mkdir /backend
COPY /backend/windmill-api/openapi.yaml /backend/windmill-api/openapi.yaml
COPY /backend/oauth_connect.json /backend/oauth_connect.json
COPY /openflow.openapi.yaml /openflow.openapi.yaml
COPY /backend/windmill-api/build_openapi.sh /backend/windmill-api/build_openapi.sh
COPY /system_prompts/auto-generated /system_prompts/auto-generated
@@ -233,14 +232,11 @@ ENV PATH="${PATH}:/usr/local/go/bin"
ENV GO_PATH=/usr/local/go/bin/go
# Install UV
RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.9.25/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv
RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.9.24/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv
# Preinstall python runtimes to temp build location (will copy with world-writable perms later)
# --compile-bytecode precompiles the stdlib to .pyc so jobs don't recompile it on every run
# under the read-only nsjail runtime mount (uv >= 0.9.25). The copy below MUST preserve
# timestamps or Python's mtime-based .pyc invalidation discards these compiled files.
RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install 3.11 --compile-bytecode
RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $LATEST_STABLE_PY --compile-bytecode
RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install 3.11
RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $LATEST_STABLE_PY
RUN curl -sL https://deb.nodesource.com/setup_20.x | bash -
@@ -262,7 +258,7 @@ RUN export GOCACHE=/tmp/build_cache/go && \
# chmod a+rw adds read+write WITHOUT removing execute bits (755->777, 644->666)
# Note: uv python install only creates py_runtime, not uv cache - we create uv/go dirs for runtime
RUN mkdir -p /tmp/windmill/cache && \
cp -r --preserve=timestamps /tmp/build_cache/* /tmp/windmill/cache/ && \
cp -r /tmp/build_cache/* /tmp/windmill/cache/ && \
chmod -R a+rw /tmp/windmill/cache && \
rm -rf /tmp/build_cache && \
mkdir -p -m 777 /tmp/windmill/cache/uv /tmp/windmill/cache/go /tmp/windmill/cache/rustup /tmp/windmill/cache/cargo
@@ -303,20 +299,10 @@ ENV CARGO_HOME="/tmp/windmill/cache/cargo"
ENV LD_LIBRARY_PATH="."
# nsjail runtime deps and binary
RUN apt-get update && apt-get install -y --no-install-recommends libprotobuf32 libnl-route-3-200 libnl-3-200 \
RUN apt-get update && apt-get install -y libprotobuf-dev libnl-route-3-dev \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
COPY --from=nsjail /nsjail/nsjail /bin/nsjail
# crane: pulls + flattens images for the sandboxed container runtime (`# sandbox <image>`).
# Single static binary — no daemon/store/root needed. See docs/docker-v2-runtime.md.
ARG CRANE_VERSION=v0.20.6
RUN arch="$(dpkg --print-architecture)"; \
case "$arch" in amd64) crane_arch=x86_64 ;; arm64) crane_arch=arm64 ;; *) echo >&2 "error: unsupported arch '$arch' for crane"; exit 1 ;; esac; \
wget -O /tmp/crane.tgz "https://github.com/google/go-containerregistry/releases/download/${CRANE_VERSION}/go-containerregistry_Linux_${crane_arch}.tar.gz" \
&& tar -xzf /tmp/crane.tgz -C /usr/local/bin crane \
&& rm /tmp/crane.tgz \
&& chmod +x /usr/local/bin/crane
WORKDIR ${APP}
RUN ln -s ${APP}/windmill /usr/local/bin/windmill
-69
View File
@@ -1,69 +0,0 @@
# Pull request review — shared policy
You are reviewing a GitHub pull request for this repository. Apply this policy alongside your tool's output requirements.
## Read the project rules first
- Read `AGENTS.md` (repo root) and any `AGENTS.md` in directories touched by the diff before reviewing — they are the canonical contributor guide.
- Quote the exact rule from `AGENTS.md` when flagging a violation.
## Verdict (first line of the review)
Start every review with a single verdict line, before any other section (the only thing that may appear above the verdict is the optional `cc @<PR_AUTHOR>` ping described in "Pinging the author" below). Pick exactly one:
- **Good to merge** — no blocking issues and no nits worth surfacing.
- **Mergeable, but should ideally address nits: <short list>** — no blockers, but P2 findings that are worth a look. The list must name each nit briefly (e.g. "doc/code mismatch in `foo.rs`, half-finished `pub fn bar`").
- **Should address issues before merging: <short list>** — at least one P0 or P1 finding. The list must name each blocking issue briefly (e.g. "missing auth check on new `/api/x` handler, SQL injection in `build_query`").
The names in the list must match findings detailed later in the review. If you list a nit or issue here, it must appear with full context in the body. Do not invent items that aren't in the body, and do not bury blockers in the body without surfacing them in the verdict.
## Pinging the author
If the prompt context provides a `PR AUTHOR` (GitHub login) and the verdict is NOT "Good to merge" (i.e. it is "Mergeable, but should ideally address nits: ..." or "Should address issues before merging: ..."), prepend a single line `cc @<PR_AUTHOR>` to the top-level review comment, above the verdict line. This pings the author so they get a notification that there are items to address. Skip the ping entirely when the verdict is "Good to merge" — there is nothing for the author to act on. Do not add the ping to inline comments; the top-level summary comment is the only place it belongs.
## Review policy
- Only report issues you are confident are real and introduced by this pull request.
- Focus on bugs, security problems, performance, and clear `AGENTS.md` violations.
- Do not report style nits, speculative concerns, pre-existing issues, or anything a normal linter / typechecker would obviously catch.
- Self-validate each finding before posting: "is this definitely a real issue?" If uncertain, discard it.
- Read additional files only when the diff is not enough to validate a finding.
- Do not modify any files.
## Severity triage
Tag each finding with a severity. Always report P0 and P1. Report P2 only when the diff invites it (a new `pub fn`, a new module, a new exported component, a meaningful refactor).
- **P0** — RCE, auth bypass, data loss, secrets in code, SQL injection, path traversal, broken auth on a public surface.
- **P1** — significant bug, missing auth/authorization check on a new public surface, blocking I/O on a likely async path, race condition, missing input validation on caller-controlled parameters, observable performance regression.
- **P2** — wrong module placement, doc/code mismatch, half-finished public abstractions (`pub fn` + `#[allow(dead_code)]` + `TODO`), `AGENTS.md` style violations, naming that contradicts the function's behavior.
## Checklist for new public surfaces
For any new `pub fn` / `pub async fn` / exported Svelte component / exported prop introduced by this PR, verify:
- (a) auth/authorization expectations are documented in the doc comment OR enforced in the function body. A new `pub fn` that touches workspace data, secrets, files, or processes without an auth check or documented "caller MUST verify" contract is a P1.
- (b) the function is placed in a module whose stated purpose matches what it does. Check the module-level doc comment (`//!`) — a config-file reader inside `external_ip.rs` is a P2.
- (c) it is not half-finished. `pub fn` + `#[allow(dead_code)]` + a `TODO` is a smell that says the function should land together with its caller, not separately. Cite the relevant `AGENTS.md` rule.
- (d) input validation defends against injection / traversal / overflow / NUL bytes at every parameter that may be caller-controlled.
## Test coverage assessment
End your review with a short "Test coverage" section calibrated to the layers actually changed by the diff. Skip categories the PR does not touch.
- **Backend** (Rust under `backend/`) — expect Rust unit tests for new logic. For new or modified API handlers, worker steps, queue/cron behavior, or DB access, also expect or note the absence of integration tests. Pure-refactor backend PRs don't need new tests if existing tests cover the surface.
- **Frontend** (Svelte / TS under `frontend/`) — the codebase does not generally test Svelte components, so do not ask for component tests. Only flag missing tests for new pure-logic utilities (the kind of file that already has a sibling `*.test.ts`, e.g. `flowDiff`, `previousResults`, copilot logic).
- **CI / workflows / docs / config-only** — no automated tests expected; say so explicitly so the reader knows you considered it.
Then state what manual verification, if any, is still needed before merge:
- Describe each manual scenario as a short paragraph (not a numbered list): what page / action / input, and what observable outcome confirms correctness.
- If the diff has no in-app surface to exercise (purely backend internals, CI, docs, or refactor), say that plainly.
## Additional reviewer instructions
If the prompt or context includes an "Additional reviewer instructions" section, treat it as extra guidance from the human who triggered this review and follow it.
## Prior PR discussion
If the prompt or context includes a "Prior PR discussion" section, this PR has already received review activity. Look for your own previous comment, take it into account, focus on what changed in the latest commits, and do not repeat findings the human already pushed back on or addressed.
-36
View File
@@ -6,7 +6,6 @@ This folder contains black-box benchmark cases for:
- `app`
- `script`
- `cli`
- `global`
The goal is to test the current production prompts and guidance with realistic user requests, not to test one exact implementation shape.
@@ -76,41 +75,6 @@ Still, avoid benchmark phrasing. The prompt should read like a repo task, not a
When relevant, ask the assistant to tell the user which `wmill` commands to run next. That is part of the benchmarked behavior.
## Global-specific rules
Global prompts should exercise workspace-level drafting behavior:
- inspecting existing scripts, flows, apps, schedules, triggers, resources, and variables when relevant
- writing AI drafts rather than saving or deploying by default
- producing coherent multi-artifact changes when the request crosses artifact boundaries
Keep deterministic validation focused on the draft contract: required draft type/path, required content snippets, forbidden draft paths, and forbidden mutating tools such as deploy/delete unless the case explicitly asks for them.
Datatable cases should set `skipJudge: true` and validate through tool-use
(`requiredToolsUsed` / `forbiddenToolsUsed`) and SQL-argument assertions
(`toolCallArgs` with `stringIncludesAnyOf`, e.g. `['select']`, `['create table']`,
`['update', 'insert into']`). Two reasons the judge is unreliable here:
- `list_datatables`, `get_datatable_table_schema`, and `exec_datatable_sql`
produce no drafts, and the global judge only sees the drafts artifact — it
scores a no-draft conversational answer as empty (same as the
`askUserQuestion` cases).
- Even a case that *does* produce a draft (a script reading the data table via
`wmill.datatable()` at runtime) is mis-judged: the judge has no datatable SDK
reference and penalizes correct `wmill.datatable()` usage as wrong. Verify the
SDK call deterministically instead — `requiredDrafts.valueIncludes: ['wmill.datatable(']`
plus forbidding `exec_datatable_sql` (keeping chat-time SQL distinct from
runtime SDK use).
`stringIncludesAnyOf` is existential over calls (at least one matching call), so a
mutation case still passes when the model mixes its UPDATE/INSERT with
verification SELECTs. The in-memory engine (`datatableSqlEngine.ts`) is stateful
within a case — writes persist, so a model that re-queries to verify its
CREATE/UPDATE sees the change and does not loop. But the engine is best-effort
(SELECT returns all rows of the referenced/first table with no WHERE/projection),
so still never assert specific returned row values. Seed data via
`workspace.datatables` in the `initial` fixture (see README).
## Deterministic validation
Use deterministic validation only for hard failures such as:
+14 -77
View File
@@ -1,12 +1,11 @@
# AI Evals
Small benchmark runner for the Windmill AI generation modes:
Small benchmark runner for the four Windmill AI generation modes:
- `cli`
- `flow`
- `script`
- `app`
- `global`
The benchmark always tests the current production prompts, tools, and guidance in this checkout.
@@ -56,9 +55,7 @@ bun run cli -- run flow flow-test4-order-processing-loop --model opus
bun run cli -- run flow flow-test0-sum-two-numbers --models haiku,opus,4o
bun run cli -- run flow flow-test0-sum-two-numbers --runs 3 --verbose
bun run cli -- run flow --record
GEMINI_API_KEY=... bun run cli -- run app app-test1-counter-create --model gemini-3-flash-preview
WMILL_AI_EVAL_BACKEND_URL=http://127.0.0.1:8000 bun run cli -- run flow --backend-validation preview
bun run cli -- run global global-test1-script-create
bun run cli -- run cli bun-hello-script
```
@@ -75,8 +72,6 @@ Public CLI surface:
- `--model <alias>`: choose the model under test
- `--models <a,b,c>`: run the same cases sequentially against several model aliases
- `--verbose`: stream assistant output for frontend runs
- `--skip-judge`: skip LLM judge scoring for the run
- `--execution-only`: only require the model/proxy/frontend loop to complete; skip validators, tool expectations, backend artifact validation, and judge scoring
- `--record`: append a compact tracked summary line to `ai_evals/history/<mode>.jsonl` for full-suite runs only
- `--backend-validation <mode>`: optional backend smoke validation (`off` or `preview`) for `script` and `flow` evals
@@ -90,18 +85,17 @@ Today:
- `sonnet`
- `opus`
- `4o`
- `gpt-5.5`
- `gemini-flash`
- `gemini-pro`
- `gemini-3-flash-preview`
- `gemini-3.1-pro-preview`
- `deepseek-v4-flash`
- `deepseek-v4-pro`
Notes:
- the command also prints accepted alias spellings such as `gpt-4o`, `gpt-55`, `claude-opus-4.6`, and `claude-haiku-4.5`
- frontend modes (`flow`, `script`, `app`, `global`) can use Anthropic, OpenAI, Gemini, and DeepSeek-backed aliases
- the command also prints accepted alias spellings such as `gpt-4o`, `claude-opus-4.6`, and `claude-haiku-4.5`
- frontend modes (`flow`, `script`, `app`) can use Anthropic, OpenAI, and Gemini-backed aliases
- `cli` mode always uses the Anthropic agent SDK, so only Anthropic aliases are valid there
- the judge model is separate and currently defaults to `claude-sonnet-4-6`; use `--skip-judge` for deterministic-only runs
- the judge model is separate and currently defaults to `claude-sonnet-4-6`
## Case Format
@@ -130,49 +124,6 @@ For `flow` mode, `validate` can express requirements such as:
- required `results.*` reference validity
- required module/code/input characteristics
For `app` mode, `validate` can express narrow hard requirements such as:
- required frontend file paths or backend runnable keys
- minimum backend runnable counts
- required backend runnable types
- minimum datatable / datatable-table counts
- specific required datatable tables
For `global` mode, `validate` can express draft-level requirements such as:
- required draft type/path/language
- required or forbidden snippets in draft values
- required or forbidden draft counts
- forbidden draft paths
Global initial fixtures can also seed `liveEditorDrafts` with `type`,
`storagePath`, `effectivePath`, and `value` fields. These drafts emulate the
currently open script, flow, or raw app editor so cases can test prompts that
refer to "this" or the "current" item.
Global (and flow) initial fixtures can seed `workspace.datatables` so the
`list_datatables`, `get_datatable_table_schema`, and `exec_datatable_sql` tools
return seeded data during evals. Each entry is
`{ datatable_name, schemas: { <schema>: { <table>: { columns, rows? } } } }`.
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 `[]`,
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
the old behavior where the live editor is only discoverable through
`list_workspace_items`.
App fixtures can also include an optional `datatables.json` file at the fixture root.
For `flow` mode, an `initial` fixture can also include a benchmark workspace catalog of
existing scripts and flows. That lets the real `search_workspace` and
`get_runnable_details` tools discover reusable workspace runnables during evals.
@@ -182,23 +133,17 @@ If `--backend-validation preview` is enabled:
- `script` evals run a real backend script preview in an isolated temp workspace
- `flow` evals run a real backend flow preview only for cases that define `runtime.backendPreview`
- `flow` cases with `initial.workspace` fixtures seed those scripts and flows into the preview workspace before preview
- when `WMILL_AI_EVAL_BACKEND_WORKSPACE` is set, `ai_evals` creates or reuses that workspace as a dedicated test workspace, clears managed eval assets under `f/evals/*` before each preview run, and then reseeds the current case fixtures
- when `WMILL_AI_EVAL_BACKEND_WORKSPACE` is set, `ai_evals` treats that workspace as a dedicated test workspace, clears managed eval assets under `f/evals/*` before each preview run, and then reseeds the current case fixtures
Supported backend env vars:
Supported backend validation env vars:
- `WMILL_AI_EVAL_BACKEND_VALIDATION=preview`
- `WMILL_AI_EVAL_BACKEND_URL=http://127.0.0.1:8000`
- `WMILL_AI_EVAL_BACKEND_EMAIL=admin@windmill.dev`
- `WMILL_AI_EVAL_BACKEND_PASSWORD=changeme`
- `WMILL_AI_EVAL_BACKEND_WORKSPACE=integration-tests` to reuse an existing workspace on CE installs with low workspace limits
Frontend modes require a reachable Windmill backend and send model requests through the workspace AI proxy at `/api/w/{workspace}/ai/proxy`. At startup, `ai_evals` checks the resolved backend URL and fails early with setup guidance if the backend cannot be reached or login fails.
For frontend modes:
- `ai_evals` creates a temporary backend workspace, or creates/reuses `WMILL_AI_EVAL_BACKEND_WORKSPACE` when it is set
- it upserts a provider resource under `f/evals/ai/<provider>`
- frontend requests go through `/api/w/{workspace}/ai/proxy`
- `WMILL_AI_EVAL_KEEP_WORKSPACES=1`
- `WMILL_AI_EVAL_WORKSPACE_PREFIX=ai-evals`
## Results And Artifacts
@@ -212,21 +157,16 @@ If `--record` is used, the CLI also appends one compact JSON line to:
- `ai_evals/history/flow.jsonl`
- `ai_evals/history/script.jsonl`
- `ai_evals/history/app.jsonl`
- `ai_evals/history/global.jsonl`
- `ai_evals/history/cli.jsonl`
Each recorded line contains:
- run metadata (`createdAt`, `gitSha`, `mode`, `runModel`, `judgeModel`)
- suite totals (`caseCount`, `attemptCount`, `passedAttempts`, `passRate`, `averageDurationMs`, `averagePassedDurationMs`, `averageJudgeScore`)
- average token usage (`averageTokenUsagePerAttempt`, `averageTokenUsagePerPassedAttempt`)
- per-case metrics under `cases[]` (`averageDurationMs`, `averagePassedDurationMs`, `averageJudgeScore`, `averageTokenUsagePerAttempt`, `averageTokenUsagePerPassedAttempt`, pass rate)
- suite totals (`caseCount`, `attemptCount`, `passedAttempts`, `passRate`, `averageDurationMs`, `averageJudgeScore`)
- average token usage (`averageTokenUsagePerAttempt`)
- per-case metrics under `cases[]` (`averageDurationMs`, `averageJudgeScore`, `averageTokenUsagePerAttempt`, pass rate)
- `failedCaseIds`
The CLI headline duration and token averages use passed attempts only.
All-attempt averages are still recorded to make failures auditable without
letting failed attempts skew success cost comparisons.
Example:
- summary: `ai_evals/results/2026-04-09T09-40-33.051Z__flow.json`
@@ -237,8 +177,7 @@ Typical artifacts by mode:
- `flow`: `flow.json`
- `script`: `script.json` plus the generated script file
- `app`: `app.json` plus frontend/backend files
- `global`: `global-drafts.json`
- `cli`: `assistant-output.txt`, `trace.json`, `wmill-invocations.jsonl`, plus generated workspace files
- `cli`: `assistant-output.txt` plus generated workspace files
- backend-validated attempts also include `backend-preview.json`
## Layout
@@ -253,8 +192,6 @@ Typical artifacts by mode:
## Notes
- Frontend modes reuse the production frontend chat code through the Vitest bridge.
- Global mode evaluates the production global AI tools and validates the resulting AI draft store.
- CLI mode creates an isolated workspace, writes the current checkout guidance into it, and benchmarks the real skills / `AGENTS.md` flow.
- CLI mode now also records a structured trace of invoked skills, tool calls, proposed `wmill` commands, and any attempted `wmill` executions.
- Frontend progress streams live while the benchmark is running.
- Deterministic validators should stay focused on real correctness constraints, not one exact implementation shape.
-77
View File
@@ -2,8 +2,6 @@ import { describe, expect, it } from "bun:test";
import {
anthropicUsageToBenchmarkTokenUsage,
extractCliResultTokenUsage,
extractProposedWmillCommands,
parseWmillInvocationLog,
} from "./runtime";
describe("anthropicUsageToBenchmarkTokenUsage", () => {
@@ -72,78 +70,3 @@ describe("extractCliResultTokenUsage", () => {
});
});
});
describe("extractProposedWmillCommands", () => {
it("extracts proposed commands from bullets, code blocks, and inline code", () => {
expect(
extractProposedWmillCommands(`
Next:
- \`wmill generate-metadata --yes\`
- wmill sync push
You can inspect failures with \`wmill job logs 123\`.
`)
).toEqual([
"wmill generate-metadata --yes",
"wmill sync push",
"wmill job logs 123",
]);
});
it("extracts inline prose commands that are not wrapped in backticks", () => {
expect(
extractProposedWmillCommands(
"The first command is wmill sync pull before you edit locally."
)
).toEqual(["wmill sync pull"]);
});
it("extracts multiple inline prose commands from a single sentence", () => {
expect(
extractProposedWmillCommands(
"Run wmill generate-metadata and then wmill sync push when you are ready."
)
).toEqual(["wmill generate-metadata", "wmill sync push"]);
});
it("ignores negated command mentions", () => {
expect(
extractProposedWmillCommands(
"Do not run `wmill sync push`. Instead run `wmill sync pull` first."
)
).toEqual(["wmill sync pull"]);
});
});
describe("parseWmillInvocationLog", () => {
it("parses stubbed wmill invocations into structured records", () => {
expect(
parseWmillInvocationLog(`noise
__WMILL_BENCHMARK__
2026-04-21T12:00:00+00:00
/tmp/workspace
2
generate-metadata
--yes
__WMILL_BENCHMARK__
2026-04-21T12:00:05+00:00
/tmp/workspace
3
sync
push
--dry-run
`)
).toEqual([
{
argv: ["generate-metadata", "--yes"],
cwd: "/tmp/workspace",
timestamp: "2026-04-21T12:00:00+00:00",
},
{
argv: ["sync", "push", "--dry-run"],
cwd: "/tmp/workspace",
timestamp: "2026-04-21T12:00:05+00:00",
},
]);
});
});
+21 -365
View File
@@ -1,25 +1,22 @@
import { query, type Options } from "@anthropic-ai/claude-agent-sdk";
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "path";
import { join } from "path";
import { fileURLToPath } from "url";
import { getCliEvalModel, resolveEvalModel, type CliEvalModelConfig } from "../../core/models";
import type {
BenchmarkTokenUsage,
CliToolInvocation,
CliTrace,
CliWmillInvocation,
} from "../../core/types";
import type { BenchmarkTokenUsage } from "../../core/types";
export type ToolInvocation = CliToolInvocation;
export interface ToolInvocation {
tool: string;
input: Record<string, unknown>;
timestamp: number;
}
export interface PromptRunResult {
toolsUsed: ToolInvocation[];
skillsInvoked: string[];
output: string;
durationMs: number;
assistantMessageCount: number;
tokenUsage: BenchmarkTokenUsage | null;
// Input tokens on the last assistant turn. The SDK `result` message reports
// usage cumulatively, so the final context size comes from per-turn usage.
finalContextTokens: number | null;
trace: CliTrace;
}
interface AnthropicUsageLike {
@@ -44,25 +41,6 @@ interface CliResultMessageLike {
const REPO_ROOT = fileURLToPath(new URL("../../../", import.meta.url));
export const DEFAULT_CLI_EVAL_MODEL: CliEvalModelConfig = getCliEvalModel(resolveEvalModel("cli"));
const WMILL_STUB_DIR_NAME = ".wmill-benchmark-bin";
const WMILL_LOG_FILE_NAME = ".wmill-benchmark-wmill-invocations.log";
const WMILL_LOG_MARKER = "__WMILL_BENCHMARK__";
const NEGATED_COMMAND_PREFIX = /(?:^|\b)(?:do not|don't|dont|never|instead of)\s+(?:run|use)?\s*$/i;
const COMMAND_STOP_WORDS = new Set([
"and",
"before",
"after",
"then",
"instead",
"otherwise",
"because",
"so",
"if",
"when",
"while",
"once",
]);
const COMMAND_STOP_TOKENS = new Set(["-", "", "—", "|"]);
export function getGeneratedSkillsSource(): string {
return join(REPO_ROOT, "system_prompts", "auto-generated", "skills");
@@ -143,60 +121,36 @@ export async function runPromptAndCapture(
): Promise<PromptRunResult> {
const toolsUsed: ToolInvocation[] = [];
const skillsInvoked: string[] = [];
const bashCommands: string[] = [];
let output = "";
let assistantMessageCount = 0;
let tokenUsage: BenchmarkTokenUsage | null = null;
let finalContextTokens: number | null = null;
const startedAt = Date.now();
const stubBinDir = join(cwd, WMILL_STUB_DIR_NAME);
const wmillLogPath = join(cwd, WMILL_LOG_FILE_NAME);
const options: Options = {
cwd,
model: modelConfig.model,
maxTurns,
settingSources: ["project"],
allowedTools: ["Skill", "Read", "Glob", "Grep", "Bash", "Write", "Edit"],
env: {
...getQueryEnv(),
PATH: process.env.PATH ? `${stubBinDir}${delimiter}${process.env.PATH}` : stubBinDir,
WMILL_BENCHMARK_LOG_PATH: wmillLogPath,
},
allowedTools: ["Skill", "Read", "Glob", "Grep", "Bash", "Write", "Edit"]
};
await installWmillStub(stubBinDir);
for await (const message of query({ prompt, options })) {
if (message.type === "assistant") {
assistantMessageCount += 1;
const turnContext = anthropicUsageToBenchmarkTokenUsage(
message.message?.usage
)?.prompt;
if (turnContext && turnContext > 0) {
finalContextTokens = turnContext;
}
const content = message.message?.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "tool_use") {
const input = normalizeToolInput(block.input);
toolsUsed.push({
tool: block.name,
input,
input: block.input as Record<string, unknown>,
timestamp: Date.now()
});
if (block.name === "Skill") {
const skillInput = input as { skill?: string };
if (block.name === "Skill" && typeof block.input === "object" && block.input !== null) {
const skillInput = block.input as { skill?: string };
if (skillInput.skill) {
pushUnique(skillsInvoked, skillInput.skill);
}
}
if (block.name === "Bash") {
for (const command of extractBashCommands(input)) {
pushUnique(bashCommands, command);
skillsInvoked.push(skillInput.skill);
}
}
} else if (block.type === "text") {
@@ -213,33 +167,22 @@ export async function runPromptAndCapture(
}
}
const proposedCommands = extractProposedWmillCommands(output);
const wmillInvocations = await readWmillInvocationLog(wmillLogPath);
return {
toolsUsed,
skillsInvoked,
output,
durationMs: Date.now() - startedAt,
assistantMessageCount,
tokenUsage,
finalContextTokens,
trace: {
toolsUsed,
skillsInvoked,
assistantMessageCount,
bashCommands,
proposedCommands,
executedWmillCommands: wmillInvocations.map(formatExecutedWmillCommand),
wmillInvocations,
firstMutationToolIndex: getFirstMutationToolIndex(toolsUsed),
},
};
}
export function wasSkillInvoked(result: PromptRunResult, skillName: string): boolean {
return result.trace.skillsInvoked.some((skill) => skill === skillName);
return result.skillsInvoked.some((skill) => skill === skillName || skill.includes(skillName));
}
export function wasToolUsed(result: PromptRunResult, toolName: string): boolean {
return result.trace.toolsUsed.some((tool) => tool.tool === toolName);
return result.toolsUsed.some((tool) => tool.tool === toolName);
}
export function formatCliRunModelLabel(modelConfig: CliEvalModelConfig): string {
@@ -250,294 +193,7 @@ export function getToolInputs(
result: PromptRunResult,
toolName: string
): Record<string, unknown>[] {
return result.trace.toolsUsed
return result.toolsUsed
.filter((tool) => tool.tool === toolName)
.map((tool) => tool.input);
}
export function extractProposedWmillCommands(output: string): string[] {
const commands: string[] = [];
for (const line of output.split(/\r?\n/)) {
for (const command of extractInlineBacktickCommands(line)) {
pushUnique(commands, command);
}
for (const command of extractInlineProseCommands(line.replace(/^\s*(?:[-*]|\d+\.)\s*/, ""))) {
pushUnique(commands, command);
}
}
return commands;
}
export function parseWmillInvocationLog(raw: string): CliWmillInvocation[] {
const entries: CliWmillInvocation[] = [];
const lines = raw.split(/\r?\n/);
for (let index = 0; index < lines.length; index += 1) {
if (lines[index] !== WMILL_LOG_MARKER) {
continue;
}
const timestamp = lines[index + 1] ?? "";
const cwd = lines[index + 2] ?? "";
const argCount = Number.parseInt(lines[index + 3] ?? "", 10);
if (!Number.isFinite(argCount) || argCount < 0) {
continue;
}
const start = index + 4;
const argv = lines.slice(start, start + argCount);
entries.push({ argv, cwd, timestamp });
index = start + argCount - 1;
}
return entries;
}
async function installWmillStub(binDir: string): Promise<void> {
await mkdir(binDir, { recursive: true });
const stubPath = join(binDir, "wmill");
const script = `#!/usr/bin/env bash
set -euo pipefail
{
printf '${WMILL_LOG_MARKER}\\n'
date -u +"%Y-%m-%dT%H:%M:%SZ"
printf '%s\\n' "$PWD"
printf '%s\\n' "$#"
printf '%s\\n' "$@"
} >> "\${WMILL_BENCHMARK_LOG_PATH:?}"
printf 'wmill benchmark stub: do not execute Windmill CLI commands during ai_evals; describe them in the final response instead.\\n' >&2
exit 97
`;
await writeFile(stubPath, script, "utf8");
await chmod(stubPath, 0o755);
}
async function readWmillInvocationLog(logPath: string): Promise<CliWmillInvocation[]> {
const raw = await readFile(logPath, "utf8").catch(() => null);
if (!raw) {
return [];
}
return parseWmillInvocationLog(raw);
}
function getQueryEnv(): Record<string, string> {
return Object.fromEntries(
Object.entries(process.env).flatMap(([key, value]) =>
typeof value === "string" ? [[key, value]] : []
)
);
}
function normalizeToolInput(input: unknown): Record<string, unknown> {
if (input && typeof input === "object" && !Array.isArray(input)) {
return input as Record<string, unknown>;
}
if (typeof input === "string") {
return { raw: input };
}
return {};
}
function extractBashCommands(input: Record<string, unknown>): string[] {
const commands: string[] = [];
for (const key of ["command", "cmd", "script", "raw"]) {
const value = input[key];
if (typeof value === "string") {
for (const line of value.split(/\r?\n/)) {
const command = normalizeCommandCandidate(line);
if (command) {
pushUnique(commands, command);
}
}
}
}
return commands;
}
function extractInlineBacktickCommands(line: string): string[] {
const commands: string[] = [];
const regex = /`(wmill [^`\n]+)`/g;
let match: RegExpExecArray | null = null;
while ((match = regex.exec(line)) !== null) {
if (hasNegatedCommandPrefix(line.slice(0, match.index))) {
continue;
}
const command = normalizeCommandCandidate(match[1]);
if (command) {
pushUnique(commands, command);
}
}
return commands;
}
function extractInlineProseCommands(line: string): string[] {
const commands: string[] = [];
let searchFrom = 0;
while (true) {
const inlineIndex = line.toLowerCase().indexOf("wmill ", searchFrom);
if (inlineIndex === -1) {
return commands;
}
if (!hasNegatedCommandPrefix(line.slice(0, inlineIndex))) {
const command = extractInlineProseCommandAt(line, inlineIndex);
if (command) {
pushUnique(commands, command);
}
}
searchFrom = inlineIndex + "wmill ".length;
}
}
function extractInlineProseCommandAt(line: string, startIndex: number): string | null {
const tokens = ["wmill"];
let cursor = startIndex + "wmill".length;
while (cursor < line.length) {
while (cursor < line.length && /\s/.test(line[cursor]!)) {
cursor += 1;
}
if (cursor >= line.length) {
break;
}
const current = line[cursor]!;
if ("`.,;:()[]{}".includes(current)) {
break;
}
const token = readCommandToken(line, cursor);
if (!token) {
break;
}
if (COMMAND_STOP_WORDS.has(token.value.toLowerCase())) {
break;
}
if (COMMAND_STOP_TOKENS.has(token.value)) {
break;
}
tokens.push(token.value);
cursor = token.nextIndex;
}
if (tokens.length <= 1) {
return null;
}
return normalizeCommandCandidate(tokens.join(" "));
}
function readCommandToken(
line: string,
startIndex: number
): { value: string; nextIndex: number } | null {
const firstChar = line[startIndex]!;
if (firstChar === `"` || firstChar === `'`) {
const endIndex = line.indexOf(firstChar, startIndex + 1);
const nextIndex = endIndex === -1 ? line.length : endIndex + 1;
return {
value: line.slice(startIndex, nextIndex),
nextIndex,
};
}
if (firstChar === "<") {
const endIndex = line.indexOf(">", startIndex + 1);
const nextIndex = endIndex === -1 ? line.length : endIndex + 1;
return {
value: line.slice(startIndex, nextIndex),
nextIndex,
};
}
let endIndex = startIndex;
while (endIndex < line.length && !/[\s`.,;:()[\]{}#]/.test(line[endIndex]!)) {
endIndex += 1;
}
if (endIndex === startIndex) {
return null;
}
return {
value: line.slice(startIndex, endIndex),
nextIndex: endIndex,
};
}
function hasNegatedCommandPrefix(prefix: string): boolean {
const normalizedPrefix = prefix
.toLowerCase()
.replace(/[`"'“”‘’]/g, " ")
.replace(/\s+/g, " ")
.trimEnd();
return NEGATED_COMMAND_PREFIX.test(normalizedPrefix);
}
function normalizeCommandCandidate(value: string): string | null {
const trimmed = value.trim().replace(/^`|`$/g, "");
if (!trimmed) {
return null;
}
const normalized = trimmed
.replace(/\s+/g, " ")
.replace(/[`.;:,]+$/g, "")
.trim();
return normalized.length > 0 ? normalized : null;
}
function formatExecutedWmillCommand(entry: CliWmillInvocation): string {
return ["wmill", ...entry.argv].join(" ").trim();
}
function getFirstMutationToolIndex(toolsUsed: ToolInvocation[]): number | null {
for (const [index, tool] of toolsUsed.entries()) {
if (tool.tool === "Write" || tool.tool === "Edit") {
return index;
}
if (tool.tool === "Bash" && extractBashCommands(tool.input).some(isLikelyMutatingBashCommand)) {
return index;
}
}
return null;
}
function isLikelyMutatingBashCommand(command: string): boolean {
return (
/\b(?:mkdir|touch|rm|mv|cp|install|tee)\b/.test(command) ||
/\b(?:cat|echo|printf)\b.*(?:>|>>|\|\s*tee\b)/.test(command) ||
/\bsed\s+-i\b/.test(command) ||
/\bperl\s+-pi\b/.test(command) ||
/\bwmill\b/.test(command)
);
}
function pushUnique(values: string[], value: string): void {
if (!values.includes(value)) {
values.push(value);
}
}
@@ -210,6 +210,8 @@ function buildSettings(
baseUrl: 'http://backend.test/default',
email: 'admin@windmill.dev',
password: 'changeme',
keepWorkspaces: true,
workspacePrefix: 'ai-evals',
pollIntervalMs: 1,
maxWaitMs: 50,
...overrides
+4 -5
View File
@@ -24,7 +24,6 @@ export interface CompletedPreviewJob {
const tokenCache = new Map<string, Promise<string>>()
const sharedWorkspaceQueue = new Map<string, Promise<void>>()
const managedSharedWorkspacePrefixes = ['f/evals/']
const DEFAULT_WORKSPACE_PREFIX = 'ai-evals'
export class BackendPreviewClient {
constructor(private readonly settings: BackendValidationSettings) {}
@@ -36,7 +35,7 @@ export class BackendPreviewClient {
): Promise<T> {
const workspaceId =
this.settings.workspaceOverride ??
buildWorkspaceId(caseId, attempt)
buildWorkspaceId(this.settings.workspacePrefix, caseId, attempt)
const run = async () => {
await this.ensureWorkspace(workspaceId)
@@ -47,7 +46,7 @@ export class BackendPreviewClient {
try {
return await body(workspaceId)
} finally {
if (!this.settings.workspaceOverride) {
if (!this.settings.keepWorkspaces && !this.settings.workspaceOverride) {
await this.deleteWorkspace(workspaceId).catch(() => undefined)
}
}
@@ -441,14 +440,14 @@ async function withSharedWorkspaceLock<T>(workspaceId: string, body: () => Promi
}
}
function buildWorkspaceId(caseId: string, attempt: number): string {
function buildWorkspaceId(prefix: string, caseId: string, attempt: number): string {
const caseSlug = caseId
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 30)
const suffix = randomUUID().slice(0, 8)
return `${DEFAULT_WORKSPACE_PREFIX}-${caseSlug || 'case'}-a${attempt}-${suffix}`
return `${prefix}-${caseSlug || 'case'}-a${attempt}-${suffix}`
}
function extractFolderName(path: string): string | null {
+24 -73
View File
@@ -8,107 +8,66 @@ import {
import { buildRunResult } from "../../core/results";
import { runSuite } from "../../core/runSuite";
import type { BenchmarkRunResult, ModeRunner } from "../../core/types";
import { resolveWindmillBackendSettings } from "../../core/windmillBackendSettings";
import { emitFrontendBenchmarkProgress } from "./progress";
import { createAppModeRunner } from "../../modes/app";
import { createFlowModeRunner } from "../../modes/flow";
import { createScriptModeRunner } from "../../modes/script";
import { DEFAULT_JUDGE_MODEL } from "../../core/judge";
export type FrontendBenchmarkMode = "flow" | "app" | "script" | "global";
export type FrontendBenchmarkMode = "flow" | "app" | "script";
export async function runFrontendBenchmarkFromEnv(): Promise<BenchmarkRunResult> {
const mode = parseMode(process.env.WMILL_FRONTEND_AI_EVAL_MODE);
const caseIds = parseOptionalJsonStringArray(
process.env.WMILL_FRONTEND_AI_EVAL_CASE_IDS,
);
const runs = parsePositiveInteger(
process.env.WMILL_FRONTEND_AI_EVAL_RUNS,
"WMILL_FRONTEND_AI_EVAL_RUNS",
);
const caseIds = parseOptionalJsonStringArray(process.env.WMILL_FRONTEND_AI_EVAL_CASE_IDS);
const runs = parsePositiveInteger(process.env.WMILL_FRONTEND_AI_EVAL_RUNS, "WMILL_FRONTEND_AI_EVAL_RUNS");
const emitProgress = process.env.WMILL_FRONTEND_AI_EVAL_PROGRESS === "1";
const verbose = process.env.WMILL_FRONTEND_AI_EVAL_VERBOSE === "1";
const executionOnly =
process.env.WMILL_FRONTEND_AI_EVAL_EXECUTION_ONLY === "1";
const judgeModel =
process.env.WMILL_FRONTEND_AI_EVAL_SKIP_JUDGE === "1" || executionOnly
? null
: DEFAULT_JUDGE_MODEL;
const model = resolveEvalModel(
mode,
process.env.WMILL_FRONTEND_AI_EVAL_MODEL,
);
const model = resolveEvalModel(mode, process.env.WMILL_FRONTEND_AI_EVAL_MODEL);
const backendValidation = resolveBackendValidationSettings({
evalMode: mode,
requestedMode: process.env.WMILL_FRONTEND_AI_EVAL_BACKEND_VALIDATION,
});
const backendSettings = resolveWindmillBackendSettings();
const selectedCases = await loadSelectedCases(mode, caseIds);
const modeRunner = await getModeRunner(
mode,
getFrontendEvalModel(model),
backendValidation,
backendSettings,
);
const modeRunner = getModeRunner(mode, getFrontendEvalModel(model), backendValidation);
const runModel = formatRunModelLabel(mode, model);
const caseResults = await runSuite({
modeRunner,
cases: selectedCases,
runs,
runModel,
judgeModel,
executionOnly,
judgeModel: DEFAULT_JUDGE_MODEL,
concurrency: verbose ? 1 : undefined,
verbose,
onProgress: emitProgress
? (event) => emitFrontendBenchmarkProgress(event)
: undefined,
onProgress: emitProgress ? (event) => emitFrontendBenchmarkProgress(event) : undefined,
});
return buildRunResult({
mode,
runs,
runModel,
judgeModel,
judgeModel: DEFAULT_JUDGE_MODEL,
caseResults,
});
}
async function getModeRunner(
function getModeRunner(
mode: FrontendBenchmarkMode,
model: ReturnType<typeof getFrontendEvalModel>,
backendValidation: ReturnType<typeof resolveBackendValidationSettings>,
backendSettings: ReturnType<typeof resolveWindmillBackendSettings>,
): Promise<ModeRunner<any, any, any>> {
backendValidation: ReturnType<typeof resolveBackendValidationSettings>
): ModeRunner<any, any, any> {
switch (mode) {
case "flow": {
const { createFlowModeRunner } = await import("../../modes/flow");
return createFlowModeRunner(model, backendValidation, backendSettings);
}
case "app": {
const { createAppModeRunner } = await import("../../modes/app");
return createAppModeRunner(model, backendSettings);
}
case "script": {
const { createScriptModeRunner } = await import("../../modes/script");
return createScriptModeRunner(
model,
backendValidation,
backendSettings,
);
}
case "global": {
const { createGlobalModeRunner } = await import("../../modes/global");
return createGlobalModeRunner(model, backendSettings);
}
case "flow":
return createFlowModeRunner(model, backendValidation);
case "app":
return createAppModeRunner(model);
case "script":
return createScriptModeRunner(model, backendValidation);
}
}
function parseMode(value: string | undefined): FrontendBenchmarkMode {
if (
value === "flow" ||
value === "app" ||
value === "script" ||
value === "global"
) {
if (value === "flow" || value === "app" || value === "script") {
return value;
}
throw new Error(`Unsupported frontend benchmark mode: ${String(value)}`);
@@ -119,21 +78,13 @@ function parseOptionalJsonStringArray(value: string | undefined): string[] {
return [];
}
const parsed = JSON.parse(value) as unknown;
if (
!Array.isArray(parsed) ||
parsed.some((entry) => typeof entry !== "string")
) {
throw new Error(
"WMILL_FRONTEND_AI_EVAL_CASE_IDS must be a JSON string array",
);
if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== "string")) {
throw new Error("WMILL_FRONTEND_AI_EVAL_CASE_IDS must be a JSON string array");
}
return parsed;
}
function parsePositiveInteger(
value: string | undefined,
envName: string,
): number {
function parsePositiveInteger(value: string | undefined, envName: string): number {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed <= 0) {
throw new Error(`${envName} must be a positive integer`);
@@ -1,179 +1,92 @@
import { mkdtemp } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
import { mkdtemp } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import type {
BackendRunnable,
AppAIChatHelpers,
DataTableSchema,
} from "../../../../../frontend/src/lib/components/copilot/chat/app/core";
AppFiles,
BackendRunnable,
AppAIChatHelpers
} from '../../../../../frontend/src/lib/components/copilot/chat/app/core'
import {
getAppTools,
prepareAppSystemMessage,
prepareAppUserMessage,
} from "../../../../../frontend/src/lib/components/copilot/chat/app/core";
import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared";
import { createAppFileHelpers, type AppEvalChatHelpers } from "./fileHelpers";
import { runEval } from "../shared";
import type { AIProvider } from "$lib/gen/types.gen";
import type {
EvalCaseRuntimeAppAdditionalContext,
EvalCaseRuntimeAppContextSpec,
ModeRunContext,
} from "../../../../core/types";
import type { TokenUsage } from "../shared/types";
import type { AppFilesState } from "../../../../core/validators";
import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings";
import {
createAppBackendRunnableContextElement,
createAppDatatableContextElement,
createAppFrontendFileContextElement,
type ContextElement,
} from "../../../../../frontend/src/lib/components/copilot/chat/context";
getAppTools,
prepareAppSystemMessage,
prepareAppUserMessage
} from '../../../../../frontend/src/lib/components/copilot/chat/app/core'
import type { Tool as ProductionTool } from '../../../../../frontend/src/lib/components/copilot/chat/shared'
import { createAppFileHelpers } from './fileHelpers'
import { runEval } from '../shared'
import type { AIProvider } from '$lib/gen/types.gen'
import type { ModeRunContext } from '../../../../core/types'
import type { TokenUsage } from '../shared/types'
export interface AppEvalResult {
success: boolean;
files: AppFilesState;
error?: string;
assistantMessageCount: number;
toolCallCount: number;
toolsUsed: string[];
tokenUsage: TokenUsage;
finalContextTokens: number | null;
success: boolean
files: AppFiles
error?: string
assistantMessageCount: number
toolCallCount: number
toolsUsed: string[]
tokenUsage: TokenUsage
}
export interface AppEvalOptions {
initialFrontend?: Record<string, string>;
initialBackend?: AppFilesState["backend"];
initialDatatables?: AppFilesState["datatables"];
appContext?: EvalCaseRuntimeAppContextSpec;
model?: string;
maxIterations?: number;
provider?: AIProvider;
backend: WindmillBackendSettings;
workspaceRoot?: string;
runContext?: ModeRunContext;
initialFrontend?: Record<string, string>
initialBackend?: Record<string, BackendRunnable>
model?: string
maxIterations?: number
provider?: AIProvider
workspaceRoot?: string
runContext?: ModeRunContext
}
export async function runAppEval(
userPrompt: string,
apiKey: string,
options: AppEvalOptions,
userPrompt: string,
apiKey: string,
options?: AppEvalOptions
): Promise<AppEvalResult> {
const workspaceRoot =
options?.workspaceRoot ??
(await mkdtemp(join(tmpdir(), "wmill-frontend-app-benchmark-")));
const { helpers, getEvalState, cleanup } = await createAppFileHelpers(
options?.initialFrontend ?? {},
(options?.initialBackend ?? {}) as Record<string, BackendRunnable>,
options?.initialDatatables ?? [],
workspaceRoot,
);
const workspaceRoot =
options?.workspaceRoot ??
(await mkdtemp(join(tmpdir(), 'wmill-frontend-app-benchmark-')))
const { helpers, getFiles, cleanup } = await createAppFileHelpers(
options?.initialFrontend ?? {},
options?.initialBackend ?? {},
workspaceRoot
)
try {
const systemMessage = prepareAppSystemMessage();
const tools = getAppTools() as ProductionTool<AppAIChatHelpers>[];
const model = options?.model ?? "claude-haiku-4-5-20251001";
const additionalContext = await buildAdditionalContext(
options?.appContext,
helpers,
);
const userMessage = prepareAppUserMessage(
userPrompt,
helpers.getSelectedContext(),
additionalContext,
);
try {
const systemMessage = prepareAppSystemMessage()
const tools = getAppTools() as ProductionTool<AppAIChatHelpers>[]
const model = options?.model ?? 'claude-haiku-4-5-20251001'
const userMessage = prepareAppUserMessage(userPrompt, helpers.getSelectedContext())
const rawResult = await runEval({
userPrompt,
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput: getEvalState,
onAssistantMessageStart: options?.runContext?.onAssistantMessageStart,
onAssistantToken: options?.runContext?.onAssistantChunk,
onAssistantMessageEnd: options?.runContext?.onAssistantMessageEnd,
onToolCall: options?.runContext?.onToolCall,
options: {
maxIterations: options?.maxIterations,
model,
workspace: workspaceRoot,
provider: options?.provider,
backend: options.backend,
caseId: options?.runContext?.caseId,
attempt: options?.runContext?.attempt,
},
});
const rawResult = await runEval({
userPrompt,
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput: getFiles,
onAssistantMessageStart: options?.runContext?.onAssistantMessageStart,
onAssistantToken: options?.runContext?.onAssistantChunk,
onAssistantMessageEnd: options?.runContext?.onAssistantMessageEnd,
options: {
maxIterations: options?.maxIterations,
model,
workspace: workspaceRoot,
provider: options?.provider
}
})
return {
files: rawResult.output,
success: rawResult.success,
error: rawResult.error,
assistantMessageCount: rawResult.iterations,
toolCallCount: rawResult.toolCallsCount,
toolsUsed: rawResult.toolsCalled,
tokenUsage: rawResult.tokenUsage,
finalContextTokens: rawResult.finalContextTokens,
};
} finally {
await cleanup();
}
}
async function buildAdditionalContext(
appContext: EvalCaseRuntimeAppContextSpec | undefined,
helpers: AppEvalChatHelpers,
): Promise<ContextElement[]> {
const entries = appContext?.additional ?? [];
if (entries.length === 0) {
return [];
}
const datatables = entries.some((entry) => entry.type === "datatable")
? await helpers.getDatatables()
: [];
return entries.map((entry) =>
buildAdditionalContextElement(entry, helpers, datatables),
);
}
function buildAdditionalContextElement(
entry: EvalCaseRuntimeAppAdditionalContext,
helpers: AppAIChatHelpers,
datatables: DataTableSchema[],
): ContextElement {
if (entry.type === "frontend") {
const content = helpers.getFrontendFile(entry.path);
if (content === undefined) {
throw new Error(`App eval @ frontend context not found: ${entry.path}`);
}
return createAppFrontendFileContextElement(entry.path, content);
}
if (entry.type === "backend") {
const runnable = helpers.getBackendRunnable(entry.key);
if (!runnable) {
throw new Error(`App eval @ backend context not found: ${entry.key}`);
}
return createAppBackendRunnableContextElement(entry.key, runnable);
}
const datatable = datatables.find(
(candidate) => candidate.datatable_name === entry.datatableName,
);
const columns = datatable?.schemas?.[entry.schema]?.[entry.table];
if (!columns) {
throw new Error(
`App eval @ datatable context not found: ${entry.datatableName}/${entry.schema}.${entry.table}`,
);
}
return createAppDatatableContextElement(
entry.datatableName,
entry.schema,
entry.table,
columns,
);
return {
files: rawResult.output,
success: rawResult.success,
error: rawResult.error,
assistantMessageCount: rawResult.iterations,
toolCallCount: rawResult.toolCallsCount,
toolsUsed: rawResult.toolsCalled,
tokenUsage: rawResult.tokenUsage
}
} finally {
await cleanup()
}
}
@@ -1,30 +0,0 @@
import { describe, expect, it } from "bun:test";
import { fileURLToPath } from "node:url";
import { loadAppFixture } from "./appFixtureLoader";
const RECIPE_BOOK_FIXTURE = fileURLToPath(
new URL("../../../../fixtures/frontend/app/initial/recipe_book", import.meta.url)
);
describe("loadAppFixture", () => {
it("loads datatables from app fixtures when present", async () => {
const fixture = await loadAppFixture(RECIPE_BOOK_FIXTURE);
expect(fixture.datatables).toEqual([
{
datatable_name: "main",
schemas: {
public: {
recipes: {
id: "int4",
name: "text",
ingredients: "text",
instructions: "text",
created_at: "timestamp=now()",
},
},
},
},
]);
});
});
@@ -1,16 +1,15 @@
import type {
BackendRunnable,
DataTableSchema,
InlineScript,
} from "../../../../../frontend/src/lib/components/copilot/chat/app/core";
import type { AppFilesState } from "../../../../core/validators";
AppFiles,
BackendRunnable,
InlineScript
} from '../../../../../frontend/src/lib/components/copilot/chat/app/core'
/**
* Backend runnable metadata stored in meta.json files.
*/
interface BackendMeta {
name: string;
language: "bun" | "python3";
name: string
language: 'bun' | 'python3'
}
/**
@@ -18,53 +17,49 @@ interface BackendMeta {
* File paths are relative to the base directory with a leading '/'.
*/
async function readFilesRecursively(
dir: string,
basePath: string = "",
dir: string,
basePath: string = ''
): Promise<Record<string, string>> {
// @ts-ignore - Node.js fs/promises
const { readdir, readFile } = await import("fs/promises");
// @ts-ignore - Node.js path
const { join } = await import("path");
// @ts-ignore - Node.js fs/promises
const { readdir, readFile } = await import('fs/promises')
// @ts-ignore - Node.js path
const { join } = await import('path')
const result: Record<string, string> = {};
const entries = await readdir(dir, { withFileTypes: true });
const result: Record<string, string> = {}
const entries = await readdir(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = join(dir, entry.name);
const relativePath = basePath
? `${basePath}/${entry.name}`
: `/${entry.name}`;
for (const entry of entries) {
const fullPath = join(dir, entry.name)
const relativePath = basePath ? `${basePath}/${entry.name}` : `/${entry.name}`
if (entry.isDirectory()) {
const subFiles = await readFilesRecursively(fullPath, relativePath);
Object.assign(result, subFiles);
} else {
const content = await readFile(fullPath, "utf-8");
result[relativePath] = content;
}
}
if (entry.isDirectory()) {
const subFiles = await readFilesRecursively(fullPath, relativePath)
Object.assign(result, subFiles)
} else {
const content = await readFile(fullPath, 'utf-8')
result[relativePath] = content
}
}
return result;
return result
}
/**
* Loads frontend files from a directory.
* All files are read recursively and paths become keys with leading '/'.
*/
async function loadFrontend(
frontendPath: string,
): Promise<Record<string, string>> {
// @ts-ignore - Node.js fs/promises
const { access } = await import("fs/promises");
async function loadFrontend(frontendPath: string): Promise<Record<string, string>> {
// @ts-ignore - Node.js fs/promises
const { access } = await import('fs/promises')
try {
await access(frontendPath);
} catch {
// Directory doesn't exist, return empty
return {};
}
try {
await access(frontendPath)
} catch {
// Directory doesn't exist, return empty
return {}
}
return readFilesRecursively(frontendPath);
return readFilesRecursively(frontendPath)
}
/**
@@ -73,89 +68,63 @@ async function loadFrontend(
* - main.ts or main.py: The code content
* - meta.json: Metadata { name, language }
*/
async function loadBackend(
backendPath: string,
): Promise<Record<string, BackendRunnable>> {
// @ts-ignore - Node.js fs/promises
const { readdir, readFile, access } = await import("fs/promises");
// @ts-ignore - Node.js path
const { join } = await import("path");
async function loadBackend(backendPath: string): Promise<Record<string, BackendRunnable>> {
// @ts-ignore - Node.js fs/promises
const { readdir, readFile, access } = await import('fs/promises')
// @ts-ignore - Node.js path
const { join } = await import('path')
try {
await access(backendPath);
} catch {
// Directory doesn't exist, return empty
return {};
}
try {
await access(backendPath)
} catch {
// Directory doesn't exist, return empty
return {}
}
const result: Record<string, BackendRunnable> = {};
const entries = await readdir(backendPath, { withFileTypes: true });
const result: Record<string, BackendRunnable> = {}
const entries = await readdir(backendPath, { withFileTypes: true })
for (const entry of entries) {
if (!entry.isDirectory()) continue;
for (const entry of entries) {
if (!entry.isDirectory()) continue
const runnableKey = entry.name;
const runnablePath = join(backendPath, entry.name);
const runnableKey = entry.name
const runnablePath = join(backendPath, entry.name)
// Read meta.json
const metaPath = join(runnablePath, "meta.json");
let meta: BackendMeta;
try {
const metaContent = await readFile(metaPath, "utf-8");
meta = JSON.parse(metaContent);
} catch {
console.warn(
`Missing or invalid meta.json for runnable '${runnableKey}', skipping`,
);
continue;
}
// Read meta.json
const metaPath = join(runnablePath, 'meta.json')
let meta: BackendMeta
try {
const metaContent = await readFile(metaPath, 'utf-8')
meta = JSON.parse(metaContent)
} catch {
console.warn(`Missing or invalid meta.json for runnable '${runnableKey}', skipping`)
continue
}
// Find and read the main file (main.ts or main.py)
const runnableFiles = await readdir(runnablePath);
const mainFile = runnableFiles.find(
(f) => f === "main.ts" || f === "main.py",
);
// Find and read the main file (main.ts or main.py)
const runnableFiles = await readdir(runnablePath)
const mainFile = runnableFiles.find((f) => f === 'main.ts' || f === 'main.py')
if (!mainFile) {
console.warn(
`No main.ts or main.py found for runnable '${runnableKey}', skipping`,
);
continue;
}
if (!mainFile) {
console.warn(`No main.ts or main.py found for runnable '${runnableKey}', skipping`)
continue
}
const content = await readFile(join(runnablePath, mainFile), "utf-8");
const content = await readFile(join(runnablePath, mainFile), 'utf-8')
const inlineScript: InlineScript = {
language: meta.language,
content,
};
const inlineScript: InlineScript = {
language: meta.language,
content
}
result[runnableKey] = {
name: meta.name,
type: "inline",
inlineScript,
};
}
result[runnableKey] = {
name: meta.name,
type: 'inline',
inlineScript
}
}
return result;
}
async function loadDatatables(fixturePath: string): Promise<DataTableSchema[]> {
// @ts-ignore - Node.js fs/promises
const { readFile } = await import("fs/promises");
// @ts-ignore - Node.js path
const { join } = await import("path");
try {
const content = await readFile(
join(fixturePath, "datatables.json"),
"utf-8",
);
const parsed = JSON.parse(content);
return Array.isArray(parsed) ? (parsed as DataTableSchema[]) : [];
} catch {
return [];
}
return result
}
/**
@@ -177,32 +146,29 @@ async function loadDatatables(fixturePath: string): Promise<DataTableSchema[]> {
* @param fixturePath - Path to the fixture directory
* @returns AppFiles object with frontend and backend
*/
export async function loadAppFixture(
fixturePath: string,
): Promise<AppFilesState> {
// @ts-ignore - Node.js path
const { join } = await import("path");
export async function loadAppFixture(fixturePath: string): Promise<AppFiles> {
// @ts-ignore - Node.js path
const { join } = await import('path')
const frontend = await loadFrontend(join(fixturePath, "frontend"));
const backend = await loadBackend(join(fixturePath, "backend"));
const datatables = await loadDatatables(fixturePath);
const frontend = await loadFrontend(join(fixturePath, 'frontend'))
const backend = await loadBackend(join(fixturePath, 'backend'))
return { frontend, backend, datatables };
return { frontend, backend }
}
/**
* Loads an app fixture and returns the separate frontend and backend objects.
* Convenience function for use with runAppEval options.
*/
export async function loadAppFixtureForEval(fixturePath: string): Promise<{
initialFrontend: Record<string, string>;
initialBackend: AppFilesState["backend"];
initialDatatables: DataTableSchema[];
export async function loadAppFixtureForEval(
fixturePath: string
): Promise<{
initialFrontend: Record<string, string>
initialBackend: Record<string, BackendRunnable>
}> {
const { frontend, backend, datatables } = await loadAppFixture(fixturePath);
return {
initialFrontend: frontend,
initialBackend: backend,
initialDatatables: datatables,
};
const { frontend, backend } = await loadAppFixture(fixturePath)
return {
initialFrontend: frontend,
initialBackend: backend
}
}
@@ -1,40 +0,0 @@
import { describe, expect, it } from "bun:test";
import { createAppFileHelpers } from "./fileHelpers";
describe("createAppFileHelpers", () => {
it("exposes generated wmill typings and returns real lint diagnostics", async () => {
const { helpers, cleanup } = await createAppFileHelpers(
{
"/index.tsx":
"import { backend } from 'wmill'\nexport default function App() { void backend.listRecipes(); return <div /> }\n",
},
{
listRecipes: {
name: "List recipes",
type: "inline",
inlineScript: {
language: "bun",
content: "export async function main() { return [] }\n",
},
},
}
);
try {
expect(helpers.listFrontendFiles()).toContain("/wmill.d.ts");
expect(helpers.getFrontendFile("/wmill.d.ts")).toContain("listRecipes");
const lintResult = helpers.setFrontendFile(
"/index.tsx",
"import { backend } from 'wmill'\nexport default function App() { void backend.deleteRecipe({ id: 1 }); return <div /> }\n"
);
expect(lintResult.errorCount).toBeGreaterThan(0);
expect(lintResult.errors.frontend["/index.tsx"]?.join("\n")).toContain(
"Property 'deleteRecipe' does not exist"
);
} finally {
await cleanup();
}
});
});
@@ -2,17 +2,20 @@ import { mkdir, rm, writeFile } from 'fs/promises'
import { dirname, join } from 'path'
import type {
AppAIChatHelpers,
AppDatatableMetadata,
AppFiles,
BackendRunnable,
DataTableSchema,
LintResult,
SelectedContext
} from '../../../../../frontend/src/lib/components/copilot/chat/app/core'
import { buildAppWmillTypes, collectAppDiagnostics } from '../../../../core/appDiagnostics'
export interface AppEvalChatHelpers extends AppAIChatHelpers {
getDatatables: () => Promise<DataTableSchema[]>
function createEmptyLintResult(): LintResult {
return {
errorCount: 0,
warningCount: 0,
errors: { frontend: {}, backend: {} },
warnings: { frontend: {}, backend: {} }
}
}
async function writeFrontendFile(
@@ -94,19 +97,12 @@ async function persistDatatables(
export async function createAppFileHelpers(
initialFrontend: Record<string, string> = {},
initialBackend: Record<string, BackendRunnable> = {},
initialDatatables: DataTableSchema[] = [],
workspaceRoot?: string
): Promise<{
helpers: AppEvalChatHelpers
helpers: AppAIChatHelpers
getFiles: () => AppFiles
getEvalState: () => {
frontend: Record<string, string>
backend: Record<string, BackendRunnable>
datatables: DataTableSchema[]
}
getFrontend: () => Record<string, string>
getBackend: () => Record<string, BackendRunnable>
getDatatables: () => DataTableSchema[]
cleanup: () => Promise<void>
workspaceDir: string | null
}> {
@@ -115,24 +111,9 @@ export async function createAppFileHelpers(
let snapshotId = 0
const snapshots = new Map<
number,
{
frontend: Record<string, string>
backend: Record<string, BackendRunnable>
datatables: DataTableSchema[]
}
{ frontend: Record<string, string>; backend: Record<string, BackendRunnable> }
>()
const datatables: DataTableSchema[] = structuredClone(initialDatatables)
function lint(): LintResult {
return collectAppDiagnostics({
frontend,
backend
}).lintResult
}
function getGeneratedWmillTypes(): string {
return buildAppWmillTypes(backend)
}
const datatables: DataTableSchema[] = []
for (const [path, content] of Object.entries(frontend)) {
await writeFrontendFile(workspaceRoot, path, content)
@@ -142,35 +123,16 @@ export async function createAppFileHelpers(
}
await persistDatatables(workspaceRoot, datatables)
const helpers: AppEvalChatHelpers = {
listFrontendFiles: () => [
...Object.keys(frontend).filter((path) => path !== '/wmill.d.ts'),
'/wmill.d.ts'
],
getFrontendFile: (path: string) => {
if (path === '/wmill.d.ts') {
return getGeneratedWmillTypes()
}
return frontend[path]
},
getFrontendFiles: () => ({
...Object.fromEntries(
Object.entries(frontend).filter(([path]) => path !== '/wmill.d.ts')
),
'/wmill.d.ts': getGeneratedWmillTypes()
}),
const helpers: AppAIChatHelpers = {
listFrontendFiles: () => Object.keys(frontend),
getFrontendFile: (path: string) => frontend[path],
getFrontendFiles: () => ({ ...frontend }),
setFrontendFile: (path: string, content: string) => {
if (path === '/wmill.d.ts') {
return lint()
}
frontend[path] = content
void writeFrontendFile(workspaceRoot, path, content)
return lint()
return createEmptyLintResult()
},
deleteFrontendFile: (path: string) => {
if (path === '/wmill.d.ts') {
return
}
delete frontend[path]
void removeFrontendFile(workspaceRoot, path)
},
@@ -184,7 +146,7 @@ export async function createAppFileHelpers(
setBackendRunnable: async (key: string, runnable: BackendRunnable) => {
backend[key] = runnable
await writeBackendRunnable(workspaceRoot, key, runnable)
return lint()
return createEmptyLintResult()
},
deleteBackendRunnable: (key: string) => {
delete backend[key]
@@ -194,13 +156,12 @@ export async function createAppFileHelpers(
frontend: { ...frontend },
backend: { ...backend }
}),
getSelectedContext: (): SelectedContext => ({}),
getSelectedContext: (): SelectedContext => ({ type: 'none' }),
snapshot: () => {
const id = ++snapshotId
snapshots.set(id, {
frontend: { ...frontend },
backend: { ...backend },
datatables: structuredClone(datatables)
backend: { ...backend }
})
return id
},
@@ -211,39 +172,10 @@ export async function createAppFileHelpers(
}
frontend = { ...snapshot.frontend }
backend = { ...snapshot.backend }
datatables.splice(0, datatables.length, ...structuredClone(snapshot.datatables))
void syncWorkspace()
},
lint,
lint: () => createEmptyLintResult(),
getDatatables: async () => structuredClone(datatables),
listDatatableTables: async () =>
datatables.map(
(datatable): AppDatatableMetadata => {
const schemas = Object.fromEntries(
Object.entries(datatable.schemas).map(([schemaName, tables]) => [
schemaName,
Object.keys(tables)
])
)
return {
datatable_name: datatable.datatable_name,
schemas,
tableCount: Object.values(schemas).reduce(
(sum, tableNames) => sum + tableNames.length,
0
),
error: datatable.error
}
}
),
getDatatableTableSchema: async (
datatableName: string,
schemaName: string,
tableName: string
) => {
const datatable = datatables.find((entry) => entry.datatable_name === datatableName)
return structuredClone(datatable?.schemas?.[schemaName]?.[tableName] ?? {})
},
getAvailableDatatableNames: () => datatables.map((datatable) => datatable.datatable_name),
execDatatableSql: async (
datatableName: string,
@@ -311,14 +243,8 @@ export async function createAppFileHelpers(
frontend: { ...frontend },
backend: { ...backend }
}),
getEvalState: () => ({
frontend: { ...frontend },
backend: { ...backend },
datatables: structuredClone(datatables)
}),
getFrontend: () => ({ ...frontend }),
getBackend: () => ({ ...backend }),
getDatatables: () => structuredClone(datatables),
cleanup: async () => {
if (workspaceRoot) {
await rm(workspaceRoot, { recursive: true, force: true })
@@ -4,14 +4,10 @@ import type { FlowModule, InputTransform } from '../../../../../frontend/src/lib
import type { ExtendedOpenFlow } from '../../../../../frontend/src/lib/components/flows/types'
import type { FlowAIChatHelpers } from '../../../../../frontend/src/lib/components/copilot/chat/flow/core'
import type { ScriptLintResult } from '../../../../../frontend/src/lib/components/copilot/chat/shared'
import type { WorkspaceMutationTarget } from '../../../../../frontend/src/lib/components/copilot/chat/workspaceTools'
import { findModuleById } from '../../../../../frontend/src/lib/components/copilot/chat/shared'
import {
createInlineScriptSession
} from '../../../../../frontend/src/lib/components/copilot/chat/flow/inlineScriptsUtils'
import {
applyFlowJsonUpdate,
updateRawScriptModuleContent
} from '../../../../../frontend/src/lib/components/copilot/chat/flow/helperUtils'
import {
registerBenchmarkWorkspace,
registerBenchmarkWorkspaceRunnables,
@@ -36,11 +32,8 @@ export interface FlowWorkspaceFixtures {
export async function createFlowFileHelpers(
initialModules: FlowModule[] = [],
initialSchema?: Record<string, any>,
initialPreprocessorModule?: FlowModule,
initialFailureModule?: FlowModule,
workspaceRoot?: string,
workspaceFixtures?: FlowWorkspaceFixtures,
currentFlowPath?: string
workspaceFixtures?: FlowWorkspaceFixtures
): Promise<{
helpers: FlowAIChatHelpers
getFlow: () => ExtendedOpenFlow
@@ -49,11 +42,7 @@ export async function createFlowFileHelpers(
workspaceDir: string | null
}> {
let flow: ExtendedOpenFlow = {
value: {
modules: structuredClone(initialModules),
preprocessor_module: structuredClone(initialPreprocessorModule),
failure_module: structuredClone(initialFailureModule)
},
value: { modules: structuredClone(initialModules) },
summary: '',
schema: initialSchema ?? {
$schema: 'https://json-schema.org/draft/2020-12/schema',
@@ -83,41 +72,42 @@ export async function createFlowFileHelpers(
}
}
const setFlowJson: FlowAIChatHelpers['setFlowJson'] = async ({
modules,
schema,
preprocessorModule,
failureModule
}) => {
const result = applyFlowJsonUpdate(flow, inlineScriptSession, {
modules,
schema,
preprocessorModule,
failureModule
})
await persistFlow()
return result
}
const helpers: FlowAIChatHelpers & {
getWorkspaceMutationTarget: () => WorkspaceMutationTarget
} = {
const helpers: FlowAIChatHelpers = {
getFlowAndSelectedId: () => ({ flow, selectedId: '' }),
getRootModules: () => flow.value.modules,
getModules: (id?: string) => {
if (!id) return flow.value.modules
const module = findModuleById(flow.value.modules, id)
return module ? [module] : []
},
inlineScriptSession,
getWorkspaceMutationTarget: () => ({
kind: 'flow',
path: currentFlowPath,
deployed: Boolean(currentFlowPath)
}),
setSnapshot: () => {},
revertToSnapshot: () => {},
setCode: async (id: string, code: string) => {
updateRawScriptModuleContent(flow, id, code)
const module = findModuleById(flow.value.modules, id)
if (module && module.value.type === 'rawscript') {
module.value.content = code
}
inlineScriptSession.set(id, code)
await persistFlow()
},
setFlowJson,
setFlowJson: async (
modules: FlowModule[] | undefined,
schema: Record<string, any> | undefined
) => {
if (modules) {
flow.value.modules = inlineScriptSession.restoreInlineScriptReferences(modules)
const unresolvedRefs = inlineScriptSession.findUnresolvedInlineScriptRefs(flow.value.modules)
if (unresolvedRefs.length > 0) {
throw new Error(
`Unresolved inline script references: ${unresolvedRefs.join(', ')}`
)
}
}
if (schema !== undefined) {
flow.schema = schema
}
await persistFlow()
},
getFlowInputsSchema: async () => flow.schema ?? {},
updateExprsToSet: (_id: string, _inputTransforms: Record<string, InputTransform>) => {},
acceptAllModuleActions: () => {},
@@ -132,9 +122,7 @@ export async function createFlowFileHelpers(
JSON.stringify(
{
requestedArgs: args ?? {},
modules: flow.value.modules.map((module) => module.id),
preprocessor_module: flow.value.preprocessor_module?.id ?? null,
failure_module: flow.value.failure_module?.id ?? null
modules: flow.value.modules.map((module) => module.id)
},
null,
2
@@ -148,8 +136,6 @@ export async function createFlowFileHelpers(
result: {
requestedArgs: args ?? {},
modules: flow.value.modules.map((module) => module.id),
preprocessor_module: flow.value.preprocessor_module?.id ?? null,
failure_module: flow.value.failure_module?.id ?? null,
mocked: true
},
logs: 'Mock benchmark flow test run completed successfully.'
@@ -1,122 +1,103 @@
import { mkdtemp } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
import type { FlowModule } from "$lib/gen";
import type { AIProvider } from "$lib/gen/types.gen";
import type { ExtendedOpenFlow } from "$lib/components/flows/types";
import { mkdtemp } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import type { FlowModule } from '$lib/gen'
import type { AIProvider } from '$lib/gen/types.gen'
import type { ExtendedOpenFlow } from '$lib/components/flows/types'
import {
flowTools,
prepareFlowSystemMessage,
prepareFlowUserMessage,
type FlowAIChatHelpers,
} from "../../../../../frontend/src/lib/components/copilot/chat/flow/core";
import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared";
import {
createFlowFileHelpers,
type FlowWorkspaceFixtures,
} from "./fileHelpers";
import { runEval } from "../shared";
import type { ModeRunContext } from "../../../../core/types";
import type { TokenUsage, ToolCallDetail } from "../shared/types";
import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings";
flowTools,
prepareFlowSystemMessage,
prepareFlowUserMessage,
type FlowAIChatHelpers
} from '../../../../../frontend/src/lib/components/copilot/chat/flow/core'
import type { Tool as ProductionTool } from '../../../../../frontend/src/lib/components/copilot/chat/shared'
import { createFlowFileHelpers, type FlowWorkspaceFixtures } from './fileHelpers'
import { runEval } from '../shared'
import type { ModeRunContext } from '../../../../core/types'
import type { TokenUsage } from '../shared/types'
export interface FlowFixture {
path?: string;
value?: {
modules?: FlowModule[];
preprocessor_module?: FlowModule;
failure_module?: FlowModule;
};
schema?: Record<string, unknown>;
value?: {
modules?: FlowModule[]
}
schema?: Record<string, unknown>
}
export interface FlowEvalResult {
success: boolean;
flow: ExtendedOpenFlow;
error?: string;
assistantMessageCount: number;
toolCallCount: number;
toolsUsed: string[];
toolCallDetails: ToolCallDetail[];
tokenUsage: TokenUsage;
finalContextTokens: number | null;
success: boolean
flow: ExtendedOpenFlow
error?: string
assistantMessageCount: number
toolCallCount: number
toolsUsed: string[]
tokenUsage: TokenUsage
}
export interface FlowEvalOptions {
initialFlow?: FlowFixture;
workspaceFixtures?: FlowWorkspaceFixtures;
model?: string;
maxIterations?: number;
provider?: AIProvider;
backend: WindmillBackendSettings;
workspaceRoot?: string;
runContext?: ModeRunContext;
initialFlow?: FlowFixture
workspaceFixtures?: FlowWorkspaceFixtures
model?: string
maxIterations?: number
provider?: AIProvider
workspaceRoot?: string
runContext?: ModeRunContext
}
export async function runFlowEval(
userPrompt: string,
apiKey: string,
options: FlowEvalOptions,
userPrompt: string,
apiKey: string,
options?: FlowEvalOptions
): Promise<FlowEvalResult> {
const workspaceRoot =
options?.workspaceRoot ??
(await mkdtemp(join(tmpdir(), "wmill-frontend-flow-benchmark-")));
const { helpers, getFlow, cleanup } = await createFlowFileHelpers(
options?.initialFlow?.value?.modules ?? [],
options?.initialFlow?.schema,
options?.initialFlow?.value?.preprocessor_module,
options?.initialFlow?.value?.failure_module,
workspaceRoot,
options?.workspaceFixtures,
options?.initialFlow?.path,
);
const workspaceRoot =
options?.workspaceRoot ??
(await mkdtemp(join(tmpdir(), 'wmill-frontend-flow-benchmark-')))
const { helpers, getFlow, cleanup } = await createFlowFileHelpers(
options?.initialFlow?.value?.modules ?? [],
options?.initialFlow?.schema,
workspaceRoot,
options?.workspaceFixtures
)
try {
const systemMessage = prepareFlowSystemMessage();
const tools = flowTools as ProductionTool<FlowAIChatHelpers>[];
const model = options?.model ?? "claude-haiku-4-5-20251001";
const userMessage = prepareFlowUserMessage(
userPrompt,
helpers.getFlowAndSelectedId(),
[],
helpers.inlineScriptSession,
);
try {
const systemMessage = prepareFlowSystemMessage()
const tools = flowTools as ProductionTool<FlowAIChatHelpers>[]
const model = options?.model ?? 'claude-haiku-4-5-20251001'
const userMessage = prepareFlowUserMessage(
userPrompt,
helpers.getFlowAndSelectedId(),
[],
helpers.inlineScriptSession
)
const rawResult = await runEval({
userPrompt,
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput: getFlow,
onAssistantMessageStart: options?.runContext?.onAssistantMessageStart,
onAssistantToken: options?.runContext?.onAssistantChunk,
onAssistantMessageEnd: options?.runContext?.onAssistantMessageEnd,
onToolCall: options?.runContext?.onToolCall,
options: {
maxIterations: options?.maxIterations,
model,
workspace: workspaceRoot,
provider: options?.provider,
backend: options.backend,
caseId: options?.runContext?.caseId,
attempt: options?.runContext?.attempt,
},
});
const rawResult = await runEval({
userPrompt,
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput: getFlow,
onAssistantMessageStart: options?.runContext?.onAssistantMessageStart,
onAssistantToken: options?.runContext?.onAssistantChunk,
onAssistantMessageEnd: options?.runContext?.onAssistantMessageEnd,
options: {
maxIterations: options?.maxIterations,
model,
workspace: workspaceRoot,
provider: options?.provider
}
})
return {
flow: rawResult.output,
success: rawResult.success,
error: rawResult.error,
assistantMessageCount: rawResult.iterations,
toolCallCount: rawResult.toolCallsCount,
toolsUsed: rawResult.toolsCalled,
toolCallDetails: rawResult.toolCallDetails,
tokenUsage: rawResult.tokenUsage,
finalContextTokens: rawResult.finalContextTokens,
};
} finally {
await cleanup();
}
return {
flow: rawResult.output,
success: rawResult.success,
error: rawResult.error,
assistantMessageCount: rawResult.iterations,
toolCallCount: rawResult.toolCallsCount,
toolsUsed: rawResult.toolsCalled,
tokenUsage: rawResult.tokenUsage
}
} finally {
await cleanup()
}
}
@@ -1,241 +0,0 @@
import { mkdtemp, rm } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
import type { AIProvider } from "$lib/gen/types.gen";
import {
globalTools,
prepareGlobalSystemMessage,
prepareGlobalUserMessage,
} from "../../../../../frontend/src/lib/components/copilot/chat/global/core";
import {
clearGlobalDrafts,
getGlobalDraft,
listGlobalDrafts,
} from "../../../../../frontend/src/lib/components/copilot/chat/global/userDraftAdapter";
import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared";
import { UserDraft } from "../../../../../frontend/src/lib/userDraft.svelte";
import type { ModeRunContext } from "../../../../core/types";
import type { GlobalDraftState } from "../../../../core/validators";
import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings";
import {
registerBenchmarkWorkspaceRunnables,
seedBenchmarkDraft,
unregisterBenchmarkWorkspaceRunnables,
type BenchmarkWorkspaceRunnables,
} from "../../mockBackend";
import { runEval } from "../shared";
import type { TokenUsage, ToolCallDetail } from "../shared/types";
const MUTATING_GLOBAL_TOOLS = new Set([
"deploy_workspace_item",
"delete_workspace_item",
]);
const DISABLE_ACTIVE_EDITOR_CONTEXT_ENV =
"WMILL_AI_EVAL_DISABLE_ACTIVE_EDITOR_CONTEXT";
// A/B gate for the search_app read tool: set to "1" to run the baseline arm
// (toolset without search_app) so its token cost can be compared against the arm
// that offers it.
const DISABLE_SEARCH_APP_ENV = "WMILL_AI_EVAL_DISABLE_SEARCH_APP";
const LIVE_EDITOR_ITEM_KINDS = {
script: "script",
flow: "flow",
app: "raw_app",
} as const;
export interface GlobalLiveEditorDraftFixture {
type: keyof typeof LIVE_EDITOR_ITEM_KINDS;
storagePath?: string;
effectivePath?: string;
value?: unknown;
}
// Identity the global system prompt builds paths from. Production reads
// `userStore` (whoami) to fill `u/{username}/...`; the eval harness never logs
// in, so without this the prompt sees an empty username (`u//...`) and no
// path-selection case is meaningful. Seeded per-case via the initial fixture and
// passed straight to `prepareGlobalSystemMessage` (no global-store mutation).
export interface GlobalUserFixture {
username: string;
is_admin?: boolean;
/** Folders the user can write to (the writable set whoami returns). */
folders?: string[];
/** Folders the user can read; read-only folders = folders_read \ folders. */
folders_read?: string[];
}
export interface GlobalEvalResult {
success: boolean;
state: GlobalDraftState;
error?: string;
assistantMessageCount: number;
toolCallCount: number;
toolsUsed: string[];
toolCallDetails: ToolCallDetail[];
tokenUsage: TokenUsage;
finalContextTokens: number | null;
}
export interface GlobalEvalOptions {
workspaceFixtures?: BenchmarkWorkspaceRunnables;
liveEditorDrafts?: GlobalLiveEditorDraftFixture[];
user?: GlobalUserFixture;
model?: string;
maxIterations?: number;
provider?: AIProvider;
backend: WindmillBackendSettings;
workspaceRoot?: string;
runContext?: ModeRunContext;
}
export async function runGlobalEval(
userPrompt: string,
apiKey: string,
options: GlobalEvalOptions,
): Promise<GlobalEvalResult> {
const workspaceRoot =
options.workspaceRoot ??
(await mkdtemp(join(tmpdir(), "wmill-frontend-global-benchmark-")));
clearGlobalDrafts(workspaceRoot);
registerBenchmarkWorkspaceRunnables(workspaceRoot, options.workspaceFixtures ?? {});
seedLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []);
try {
const model = options.model ?? "claude-haiku-4-5-20251001";
const injectActiveEditorContext =
process.env[DISABLE_ACTIVE_EDITOR_CONTEXT_ENV] !== "1";
// Pass the seeded identity straight to the prompt builder rather than mutating
// the process-global `userStore`, so concurrent cases never race on it.
const rawResult = await runEval({
userPrompt,
systemMessage: prepareGlobalSystemMessage(undefined, { user: options.user }),
userMessage: prepareGlobalUserMessage(
userPrompt,
[],
injectActiveEditorContext ? { workspace: workspaceRoot } : {},
),
tools: getGlobalEvalTools(),
helpers: {},
apiKey,
getOutput: () => collectGlobalDraftState(workspaceRoot),
onAssistantMessageStart: options.runContext?.onAssistantMessageStart,
onAssistantToken: options.runContext?.onAssistantChunk,
onAssistantMessageEnd: options.runContext?.onAssistantMessageEnd,
onToolCall: options.runContext?.onToolCall,
options: {
maxIterations: options.maxIterations,
model,
workspace: workspaceRoot,
provider: options.provider,
backend: options.backend,
caseId: options.runContext?.caseId,
attempt: options.runContext?.attempt,
},
});
return {
state: rawResult.output,
success: rawResult.success,
error: rawResult.error,
assistantMessageCount: rawResult.iterations,
toolCallCount: rawResult.toolCallsCount,
toolsUsed: rawResult.toolsCalled,
toolCallDetails: rawResult.toolCallDetails,
tokenUsage: rawResult.tokenUsage,
finalContextTokens: rawResult.finalContextTokens,
};
} finally {
clearGlobalDrafts(workspaceRoot);
clearLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []);
unregisterBenchmarkWorkspaceRunnables(workspaceRoot);
if (!options.workspaceRoot) {
await rm(workspaceRoot, { recursive: true, force: true });
}
}
}
// Build the harness output from the DB-backed drafts. `listGlobalDrafts` returns
// metadata-only rows for backend drafts (the model's `write_script` etc. persist
// straight to the backend with no in-tab editor cell), so re-read each such row
// with `getGlobalDraft` to attach the full value the validators assert on. A row
// that already carries a value (the production in-tab cell overlay) is kept as-is.
async function collectGlobalDraftState(
workspace: string,
): Promise<GlobalDraftState> {
const items = await listGlobalDrafts(workspace);
const drafts = await Promise.all(
items.map(async (item) => {
if (item.value !== undefined) {
return item;
}
const full = await getGlobalDraft(
workspace,
item.type,
item.path,
item.triggerKind,
);
return full ?? item;
}),
);
return { drafts: drafts as GlobalDraftState["drafts"] };
}
function seedLiveEditorDrafts(
workspace: string,
fixtures: GlobalLiveEditorDraftFixture[],
): void {
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);
}
UserDraft.setLiveEditorDraft({
workspace,
itemKind,
storagePath,
effectivePath: fixture.effectivePath ?? fixture.storagePath,
});
}
}
function clearLiveEditorDrafts(
workspace: string,
fixtures: GlobalLiveEditorDraftFixture[],
): void {
for (const fixture of fixtures) {
const itemKind = LIVE_EDITOR_ITEM_KINDS[fixture.type];
const storagePath = fixture.storagePath ?? fixture.effectivePath ?? "";
UserDraft.clearLiveEditorDraft(itemKind, { workspace, storagePath });
}
}
function getGlobalEvalTools(): ProductionTool<{}>[] {
const disableSearchApp = process.env[DISABLE_SEARCH_APP_ENV] === "1";
return (globalTools as ProductionTool<{}>[])
.filter((tool) => !(disableSearchApp && tool.def.function.name === "search_app"))
.map((tool) => {
if (!MUTATING_GLOBAL_TOOLS.has(tool.def.function.name)) {
return tool;
}
return {
...tool,
requiresConfirmation: false,
validateBeforeConfirmation: undefined,
fn: async () =>
JSON.stringify(
{
success: false,
error:
"This mutating workspace tool is disabled during ai_evals global mode.",
},
null,
2,
),
};
});
}
@@ -1,8 +1,8 @@
import { mkdir, rm, writeFile } from 'fs/promises'
import { dirname, join } from 'path'
import type { ScriptLang } from '../../../../../frontend/src/lib/gen/types.gen'
import type { ReviewChangesOpts } from '../../../../../frontend/src/lib/components/copilot/chat/monaco-adapter'
import type { ScriptChatHelpers } from '../../../../../frontend/src/lib/components/copilot/chat/script/core'
import type { WorkspaceMutationTarget } from '../../../../../frontend/src/lib/components/copilot/chat/workspaceTools'
import { buildScriptLintResult } from './preview'
import { registerBenchmarkWorkspace, unregisterBenchmarkWorkspace } from '../../mockBackend'
@@ -13,10 +13,6 @@ export interface ScriptEvalState {
args: Record<string, any>
}
function toRunnablePath(filePath: string): string {
return filePath.replace(/\.[^/.]+$/, '')
}
export async function createScriptFileHelpers(
initialScript: ScriptEvalState,
workspaceRoot?: string
@@ -43,39 +39,24 @@ export async function createScriptFileHelpers(
registerBenchmarkWorkspace(workspaceRoot)
}
const applyCode: NonNullable<ScriptChatHelpers['applyCode']> = async (
code,
opts
) => {
if (opts?.mode === 'revert') {
return
}
script = {
...script,
code
}
await persistScript()
}
const getLintErrors: NonNullable<ScriptChatHelpers['getLintErrors']> = () =>
buildScriptLintResult(script.code, script.lang)
const helpers: ScriptChatHelpers & {
getWorkspaceMutationTarget: () => WorkspaceMutationTarget
} = {
const helpers: ScriptChatHelpers = {
getScriptOptions: () => ({
code: script.code,
lang: script.lang,
path: script.path,
args: structuredClone(script.args)
}),
getWorkspaceMutationTarget: () => ({
kind: 'script',
path: script.path ? toRunnablePath(script.path) : undefined,
deployed: Boolean(script.path)
}),
applyCode,
getLintErrors
applyCode: async (code: string, opts?: ReviewChangesOpts) => {
if (opts?.mode === 'revert') {
return
}
script = {
...script,
code
}
await persistScript()
},
getLintErrors: () => buildScriptLintResult(script.code, script.lang)
}
return {
@@ -1,120 +1,109 @@
import { mkdtemp } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
import type { AIProvider, AIProviderModel } from "$lib/gen/types.gen";
import type { ContextElement } from "../../../../../frontend/src/lib/components/copilot/chat/context";
import { mkdtemp } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import type { AIProvider, AIProviderModel, ScriptLang } from '$lib/gen/types.gen'
import type { ContextElement } from '../../../../../frontend/src/lib/components/copilot/chat/context'
import {
prepareScriptSystemMessage,
prepareScriptTools,
prepareScriptUserMessage,
type ScriptChatHelpers,
} from "../../../../../frontend/src/lib/components/copilot/chat/script/core";
import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared";
import { createScriptFileHelpers, type ScriptEvalState } from "./fileHelpers";
import { runEval } from "../shared";
import type { ModeRunContext } from "../../../../core/types";
import type { TokenUsage, ToolCallDetail } from "../shared/types";
import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings";
prepareScriptSystemMessage,
prepareScriptTools,
prepareScriptUserMessage,
type ScriptChatHelpers
} from '../../../../../frontend/src/lib/components/copilot/chat/script/core'
import type { Tool as ProductionTool } from '../../../../../frontend/src/lib/components/copilot/chat/shared'
import { createScriptFileHelpers, type ScriptEvalState } from './fileHelpers'
import { runEval } from '../shared'
import type { ModeRunContext } from '../../../../core/types'
import type { TokenUsage } from '../shared/types'
export interface ScriptEvalResult {
success: boolean;
script: ScriptEvalState;
error?: string;
assistantMessageCount: number;
toolCallCount: number;
toolsUsed: string[];
toolCallDetails: ToolCallDetail[];
tokenUsage: TokenUsage;
finalContextTokens: number | null;
success: boolean
script: ScriptEvalState
error?: string
assistantMessageCount: number
toolCallCount: number
toolsUsed: string[]
tokenUsage: TokenUsage
}
export interface ScriptEvalOptions {
initialScript: ScriptEvalState;
model?: string;
maxIterations?: number;
provider?: AIProvider;
backend: WindmillBackendSettings;
workspaceRoot?: string;
runContext?: ModeRunContext;
initialScript: ScriptEvalState
model?: string
maxIterations?: number
provider?: AIProvider
workspaceRoot?: string
runContext?: ModeRunContext
}
function resolveModelProvider(
model: string,
provider?: AIProvider,
model: string,
provider?: AIProvider
): AIProviderModel {
if (provider) {
return { provider, model };
}
if (model.startsWith("claude")) {
return { provider: "anthropic", model };
}
return { provider: "openai", model };
if (provider) {
return { provider, model }
}
if (model.startsWith('claude')) {
return { provider: 'anthropic', model }
}
return { provider: 'openai', model }
}
export async function runScriptEval(
userPrompt: string,
apiKey: string,
options: ScriptEvalOptions,
userPrompt: string,
apiKey: string,
options: ScriptEvalOptions
): Promise<ScriptEvalResult> {
const workspaceRoot =
options.workspaceRoot ??
(await mkdtemp(join(tmpdir(), "wmill-frontend-script-benchmark-")));
const { helpers, getScript, cleanup } = await createScriptFileHelpers(
options.initialScript,
workspaceRoot,
);
const workspaceRoot =
options.workspaceRoot ?? (await mkdtemp(join(tmpdir(), 'wmill-frontend-script-benchmark-')))
const { helpers, getScript, cleanup } = await createScriptFileHelpers(
options.initialScript,
workspaceRoot
)
try {
const model = options.model ?? "claude-haiku-4-5-20251001";
const modelProvider = resolveModelProvider(model, options.provider);
const selectedContext: ContextElement[] = [];
const systemMessage = prepareScriptSystemMessage(
modelProvider,
options.initialScript.lang,
{},
);
const tools = prepareScriptTools(
modelProvider,
options.initialScript.lang,
selectedContext,
) as ProductionTool<ScriptChatHelpers>[];
const userMessage = prepareScriptUserMessage(userPrompt, selectedContext);
try {
const model = options.model ?? 'claude-haiku-4-5-20251001'
const modelProvider = resolveModelProvider(model, options.provider)
const selectedContext: ContextElement[] = []
const systemMessage = prepareScriptSystemMessage(
modelProvider,
options.initialScript.lang,
{}
)
const tools = prepareScriptTools(
modelProvider,
options.initialScript.lang,
selectedContext
) as ProductionTool<ScriptChatHelpers>[]
const userMessage = prepareScriptUserMessage(userPrompt, selectedContext)
const rawResult = await runEval({
userPrompt,
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput: getScript,
onAssistantMessageStart: options.runContext?.onAssistantMessageStart,
onAssistantToken: options.runContext?.onAssistantChunk,
onAssistantMessageEnd: options.runContext?.onAssistantMessageEnd,
onToolCall: options.runContext?.onToolCall,
options: {
maxIterations: options.maxIterations,
model,
workspace: workspaceRoot,
provider: modelProvider.provider,
backend: options.backend,
caseId: options.runContext?.caseId,
attempt: options.runContext?.attempt,
},
});
const rawResult = await runEval({
userPrompt,
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput: getScript,
onAssistantMessageStart: options.runContext?.onAssistantMessageStart,
onAssistantToken: options.runContext?.onAssistantChunk,
onAssistantMessageEnd: options.runContext?.onAssistantMessageEnd,
options: {
maxIterations: options.maxIterations,
model,
workspace: workspaceRoot,
provider: modelProvider.provider
}
})
return {
script: rawResult.output,
success: rawResult.success,
error: rawResult.error,
assistantMessageCount: rawResult.iterations,
toolCallCount: rawResult.toolCallsCount,
toolsUsed: rawResult.toolsCalled,
toolCallDetails: rawResult.toolCallDetails,
tokenUsage: rawResult.tokenUsage,
finalContextTokens: rawResult.finalContextTokens,
};
} finally {
await cleanup();
}
return {
script: rawResult.output,
success: rawResult.success,
error: rawResult.error,
assistantMessageCount: rawResult.iterations,
toolCallCount: rawResult.toolCallsCount,
toolsUsed: rawResult.toolsCalled,
tokenUsage: rawResult.tokenUsage
}
} finally {
await cleanup()
}
}
@@ -1,52 +1,45 @@
import type {
ChatCompletionMessageParam,
ChatCompletionSystemMessageParam,
} from "openai/resources/chat/completions.mjs";
import type { AIProvider } from "$lib/gen/types.gen";
import type { ToolCallDetail, EvalRunnerOptions, RawEvalResult } from "./types";
import {
runChatLoop,
type ChatClients,
} from "../../../../../frontend/src/lib/components/copilot/chat/chatLoop";
ChatCompletionMessageParam,
ChatCompletionSystemMessageParam
} from 'openai/resources/chat/completions.mjs'
import type { AIProviderModel } from '$lib/gen/types.gen'
import type { TokenUsage, ToolCallDetail, EvalRunnerOptions, RawEvalResult } from './types'
import { runChatLoop, type ChatClients } from '../../../../../frontend/src/lib/components/copilot/chat/chatLoop'
import type {
Tool as ProductionTool,
ToolCallbacks,
} from "../../../../../frontend/src/lib/components/copilot/chat/shared";
Tool as ProductionTool,
ToolCallbacks
} from '../../../../../frontend/src/lib/components/copilot/chat/shared'
import {
buildProxyResourcePath,
createEvalClients,
type FrontendEvalProvider,
resolveEvalModelProvider,
} from "./providerConfig";
import { WindmillBackendClient } from "../../windmillBackend";
createEvalClients,
type FrontendEvalProvider,
resolveEvalModelProvider
} from './providerConfig'
/**
* Parameters for running a base evaluation.
*/
export interface RunEvalParams<THelpers, TOutput> {
/** The user's prompt/instruction */
userPrompt: string;
/** System message for the LLM */
systemMessage: ChatCompletionSystemMessageParam;
/** User message for the LLM */
userMessage: ChatCompletionMessageParam;
/** Tool definitions for the LLM API (unused — derived from tools) */
toolDefs?: unknown;
/** Full tool implementations for execution */
tools: ProductionTool<THelpers>[];
/** Domain-specific helpers for tool execution */
helpers: THelpers;
/** API key for the provider */
apiKey: string;
/** Function to get the current output state. May be async — global mode reads
* DB-backed drafts back through the (mocked) backend to build its output. */
getOutput: () => TOutput | Promise<TOutput>;
/** Model and Windmill backend configuration */
options: EvalRunnerOptions;
onAssistantMessageStart?: () => void;
onAssistantToken?: (token: string) => void;
onAssistantMessageEnd?: () => void;
onToolCall?: (input: { toolName: string; argumentsText: string }) => void;
/** The user's prompt/instruction */
userPrompt: string
/** System message for the LLM */
systemMessage: ChatCompletionSystemMessageParam
/** User message for the LLM */
userMessage: ChatCompletionMessageParam
/** Tool definitions for the LLM API (unused — derived from tools) */
toolDefs?: unknown
/** Full tool implementations for execution */
tools: ProductionTool<THelpers>[]
/** Domain-specific helpers for tool execution */
helpers: THelpers
/** API key for the provider */
apiKey: string
/** Function to get the current output state */
getOutput: () => TOutput
/** Optional configuration */
options?: EvalRunnerOptions
onAssistantMessageStart?: () => void
onAssistantToken?: (token: string) => void
onAssistantMessageEnd?: () => void
}
/**
@@ -54,196 +47,127 @@ export interface RunEvalParams<THelpers, TOutput> {
* Uses streaming via real provider SDKs instead of OpenRouter non-streaming.
*/
export async function runEval<THelpers, TOutput>(
params: RunEvalParams<THelpers, TOutput>,
params: RunEvalParams<THelpers, TOutput>
): Promise<RawEvalResult<TOutput>> {
const {
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput,
options,
onAssistantMessageStart,
onAssistantToken,
onAssistantMessageEnd,
onToolCall,
} = params;
let shouldEmitMessageStart = true;
const {
systemMessage,
userMessage,
tools,
helpers,
apiKey,
getOutput,
options,
onAssistantMessageStart,
onAssistantToken,
onAssistantMessageEnd
} = params
let shouldEmitMessageStart = true
const model = options.model ?? "gpt-4o";
const maxIterations = options.maxIterations ?? 20;
const workspace = options.workspace ?? "test-workspace";
const provider = toFrontendEvalProvider(options.provider);
const model = options?.model ?? 'gpt-4o'
const maxIterations = options?.maxIterations ?? 20
const workspace = options?.workspace ?? 'test-workspace'
const provider = options?.provider
const modelProvider = resolveEvalModelProvider(model, provider);
const modelProvider = resolveEvalModelProvider(
model,
provider as FrontendEvalProvider | undefined
) as AIProviderModel
const clients = createEvalClients(modelProvider.provider, apiKey) as ChatClients
const messages: ChatCompletionMessageParam[] = [userMessage];
let toolCallsCount = 0;
const toolsCalled: string[] = [];
const toolCallDetails: ToolCallDetail[] = [];
const messages: ChatCompletionMessageParam[] = [userMessage]
let toolCallsCount = 0
const toolsCalled: string[] = []
const toolCallDetails: ToolCallDetail[] = []
// Wrap tools to intercept fn calls for tracking.
// Cast to ProductionTool since the eval Tool has a narrower toolCallbacks type
// but the actual callbacks passed at runtime will satisfy both interfaces.
const wrappedTools = tools.map((tool) => ({
...tool,
fn: async (p: any) => {
toolCallsCount++;
toolsCalled.push(tool.def.function.name);
let argumentsText = "";
try {
const args = typeof p.args === "string" ? JSON.parse(p.args) : p.args;
toolCallDetails.push({ name: tool.def.function.name, arguments: args });
argumentsText = JSON.stringify(args);
} catch {
toolCallDetails.push({
name: tool.def.function.name,
arguments: p.args,
});
argumentsText =
typeof p.args === "string" ? p.args : JSON.stringify(p.args);
}
onToolCall?.({
toolName: tool.def.function.name,
argumentsText,
});
return tool.fn(p);
},
}));
// Wrap tools to intercept fn calls for tracking.
// Cast to ProductionTool since the eval Tool has a narrower toolCallbacks type
// but the actual callbacks passed at runtime will satisfy both interfaces.
const wrappedTools = tools.map((tool) => ({
...tool,
fn: async (p: any) => {
toolCallsCount++
toolsCalled.push(tool.def.function.name)
try {
const args =
typeof p.args === 'string' ? JSON.parse(p.args) : p.args
toolCallDetails.push({ name: tool.def.function.name, arguments: args })
} catch {
toolCallDetails.push({
name: tool.def.function.name,
arguments: p.args
})
}
return tool.fn(p)
}
}))
// No-op callbacks for eval
const callbacks: ToolCallbacks & {
onNewToken: (token: string) => void;
onMessageEnd: () => void;
} = {
setToolStatus: () => {},
removeToolStatus: () => {},
onNewToken: (token: string) => {
if (shouldEmitMessageStart) {
onAssistantMessageStart?.();
shouldEmitMessageStart = false;
}
onAssistantToken?.(token);
},
onMessageEnd: () => {
if (!shouldEmitMessageStart) {
onAssistantMessageEnd?.();
}
shouldEmitMessageStart = true;
},
};
// No-op callbacks for eval
const callbacks: ToolCallbacks & {
onNewToken: (token: string) => void
onMessageEnd: () => void
} = {
setToolStatus: () => {},
removeToolStatus: () => {},
onNewToken: (token: string) => {
if (shouldEmitMessageStart) {
onAssistantMessageStart?.()
shouldEmitMessageStart = false
}
onAssistantToken?.(token)
},
onMessageEnd: () => {
if (!shouldEmitMessageStart) {
onAssistantMessageEnd?.()
}
shouldEmitMessageStart = true
}
}
const abortController = new AbortController();
const abortController = new AbortController()
const executeChatLoop = async (clients: ChatClients) => {
try {
const result = await runChatLoop({
messages,
systemMessage,
tools: wrappedTools,
helpers,
abortController,
callbacks,
modelProvider,
clients,
workspace,
maxIterations,
skipResponsesApi: modelProvider.provider !== "openai",
});
try {
const result = await runChatLoop({
messages,
systemMessage,
tools: wrappedTools,
helpers,
abortController,
callbacks,
modelProvider,
clients,
workspace,
maxIterations,
skipResponsesApi: modelProvider.provider !== 'openai' && modelProvider.provider !== 'azure_openai'
})
if (result.hitMaxIterations) {
return {
success: false,
output: (await getOutput()) as TOutput,
error: `Reached max turns (${maxIterations})`,
tokenUsage: result.tokenUsage,
finalContextTokens: result.lastIterationUsage?.prompt ?? null,
toolCallsCount,
toolsCalled,
toolCallDetails,
iterations: Math.max(
1,
result.addedMessages.filter((m) => m.role === "assistant").length,
),
messages,
};
}
return {
success: true,
output: getOutput(),
tokenUsage: result.tokenUsage,
toolCallsCount,
toolsCalled,
toolCallDetails,
iterations: Math.max(1, result.addedMessages.filter((m) => m.role === 'assistant').length),
messages
}
} catch (err) {
let errorMessage: string
if (err instanceof Error) {
errorMessage = err.stack ?? err.message
} else {
errorMessage = String(err)
}
return {
success: true,
output: (await getOutput()) as TOutput,
tokenUsage: result.tokenUsage,
finalContextTokens: result.lastIterationUsage?.prompt ?? null,
toolCallsCount,
toolsCalled,
toolCallDetails,
iterations: Math.max(
1,
result.addedMessages.filter((m) => m.role === "assistant").length,
),
messages,
};
} catch (err) {
let errorMessage: string;
if (err instanceof Error) {
errorMessage = err.stack ?? err.message;
} else {
errorMessage = String(err);
}
return {
success: false,
output: (await getOutput()) as TOutput,
error: errorMessage,
tokenUsage: { prompt: 0, completion: 0, total: 0 },
finalContextTokens: null,
toolCallsCount,
toolsCalled,
toolCallDetails,
iterations: 0,
messages,
};
}
};
const backendSettings = options.backend;
const backendClient = new WindmillBackendClient(backendSettings);
return await backendClient.withWorkspace(
options.caseId ?? "eval",
options.attempt ?? 1,
async (proxyWorkspaceId) => {
const resourcePath = buildProxyResourcePath(modelProvider.provider);
await backendClient.upsertResource({
workspaceId: proxyWorkspaceId,
path: resourcePath,
resourceType: modelProvider.provider,
value: { api_key: apiKey },
});
const token = await backendClient.getToken();
const clients = createEvalClients({
provider: modelProvider.provider,
proxy: {
baseURL: `${backendSettings.baseUrl}/api/w/${encodeURIComponent(proxyWorkspaceId)}/ai/proxy`,
bearerToken: token,
resourcePath,
},
}) as unknown as ChatClients;
return await executeChatLoop(clients);
},
);
}
function toFrontendEvalProvider(
provider?: AIProvider,
): FrontendEvalProvider | undefined {
if (
provider === "anthropic" ||
provider === "openai" ||
provider === "googleai" ||
provider === "deepseek"
) {
return provider;
}
return undefined;
return {
success: false,
output: getOutput(),
error: errorMessage,
tokenUsage: { prompt: 0, completion: 0, total: 0 },
toolCallsCount,
toolsCalled,
toolCallDetails,
iterations: 0,
messages
}
}
}
@@ -1,45 +1,41 @@
import { describe, expect, it } from "bun:test";
import {
buildProxyHeaders,
buildProxyResourcePath,
buildOpenAICompatibleClientOptions,
resolveEvalModelProvider,
} from "./providerConfig";
describe("proxy helpers", () => {
it("builds provider-scoped proxy resource paths", () => {
expect(buildProxyResourcePath("googleai")).toBe("f/evals/ai/googleai");
expect(buildProxyResourcePath("anthropic")).toBe("f/evals/ai/anthropic");
describe("buildOpenAICompatibleClientOptions", () => {
it("adds Gemini's OpenAI-compatible base URL and client header", () => {
const options = buildOpenAICompatibleClientOptions("googleai", "gemini-test-key");
expect(options).toMatchObject({
apiKey: "gemini-test-key",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/",
defaultHeaders: {
"x-goog-api-client": "windmill-ai-evals/1.0",
},
});
});
it("adds auth and resource headers for workspace proxy requests", () => {
expect(buildProxyHeaders("token-123", "f/evals/ai/googleai")).toEqual({
Authorization: "Bearer token-123",
"X-Resource-Path": "f/evals/ai/googleai",
it("keeps the default OpenAI-compatible config for OpenAI", () => {
expect(buildOpenAICompatibleClientOptions("openai", "openai-test-key")).toEqual({
apiKey: "openai-test-key",
});
});
});
describe("resolveEvalModelProvider", () => {
it("infers googleai from Gemini model ids", () => {
expect(resolveEvalModelProvider("gemini-3-flash-preview")).toEqual({
expect(resolveEvalModelProvider("gemini-2.5-flash")).toEqual({
provider: "googleai",
model: "gemini-3-flash-preview",
});
});
it("infers deepseek from DeepSeek model ids", () => {
expect(resolveEvalModelProvider("deepseek-v4-flash")).toEqual({
provider: "deepseek",
model: "deepseek-v4-flash",
model: "gemini-2.5-flash",
});
});
it("preserves an explicit provider", () => {
expect(
resolveEvalModelProvider("gemini-3.1-pro-preview", "googleai"),
).toEqual({
expect(resolveEvalModelProvider("gemini-2.5-pro", "googleai")).toEqual({
provider: "googleai",
model: "gemini-3.1-pro-preview",
model: "gemini-2.5-pro",
});
});
});
@@ -14,65 +14,46 @@ export interface ResolvedEvalModelProvider {
model: string;
}
export interface WindmillAiProxyClientConfig {
baseURL: string;
bearerToken: string;
resourcePath: string;
}
const GEMINI_OPENAI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/";
const GEMINI_GOOG_API_CLIENT = "windmill-ai-evals/1.0";
const EVAL_PROXY_RESOURCE_PREFIX = "f/evals/ai";
export function buildProxyHeaders(
bearerToken: string,
resourcePath: string,
): Record<string, string> {
return {
Authorization: `Bearer ${bearerToken}`,
"X-Resource-Path": resourcePath,
};
}
export function buildProxyResourcePath(provider: FrontendEvalProvider): string {
return `${EVAL_PROXY_RESOURCE_PREFIX}/${provider}`;
}
function buildProxyOpenAIClientOptions(
proxy: WindmillAiProxyClientConfig,
export function buildOpenAICompatibleClientOptions(
provider: Exclude<FrontendEvalProvider, "anthropic">,
apiKey: string
): ConstructorParameters<typeof OpenAI>[0] {
return {
apiKey: "unused",
baseURL: proxy.baseURL,
defaultHeaders: buildProxyHeaders(proxy.bearerToken, proxy.resourcePath),
};
if (provider === "googleai") {
return {
apiKey,
baseURL: GEMINI_OPENAI_BASE_URL,
defaultHeaders: {
"x-goog-api-client": GEMINI_GOOG_API_CLIENT,
},
};
}
return { apiKey };
}
export function createEvalClients(input: {
provider: FrontendEvalProvider;
proxy: WindmillAiProxyClientConfig;
}): EvalClients {
if (input.provider === "anthropic") {
export function createEvalClients(
provider: FrontendEvalProvider,
apiKey: string
): EvalClients {
if (provider === "anthropic") {
return {
openai: new OpenAI({ apiKey: "unused" }),
anthropic: new Anthropic({
apiKey: "unused",
baseURL: input.proxy.baseURL,
defaultHeaders: buildProxyHeaders(
input.proxy.bearerToken,
input.proxy.resourcePath,
),
}),
anthropic: new Anthropic({ apiKey }),
};
}
return {
openai: new OpenAI(buildProxyOpenAIClientOptions(input.proxy)),
openai: new OpenAI(buildOpenAICompatibleClientOptions(provider, apiKey)),
anthropic: new Anthropic({ apiKey: "unused" }),
};
}
export function resolveEvalModelProvider(
model: string,
provider?: FrontendEvalProvider,
provider?: FrontendEvalProvider
): ResolvedEvalModelProvider {
if (provider) {
return { provider, model };
@@ -83,9 +64,6 @@ export function resolveEvalModelProvider(
if (model.startsWith("gemini")) {
return { provider: "googleai", model };
}
if (model.startsWith("deepseek")) {
return { provider: "deepseek", model };
}
if (model.startsWith("gpt") || model.startsWith("o")) {
return { provider: "openai", model };
}
+20 -26
View File
@@ -1,38 +1,32 @@
import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";
import type { AIProvider } from "$lib/gen/types.gen";
import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings";
import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions.mjs'
import type { AIProvider } from '$lib/gen/types.gen'
export interface TokenUsage {
prompt: number;
completion: number;
total: number;
prompt: number
completion: number
total: number
}
export interface ToolCallDetail {
name: string;
arguments: Record<string, unknown>;
name: string
arguments: Record<string, unknown>
}
export interface EvalRunnerOptions {
backend: WindmillBackendSettings;
maxIterations?: number;
model?: string;
workspace?: string;
provider?: AIProvider;
caseId?: string;
attempt?: number;
maxIterations?: number
model?: string
workspace?: string
provider?: AIProvider
}
export interface RawEvalResult<TOutput> {
success: boolean;
output: TOutput;
error?: string;
tokenUsage: TokenUsage;
/** Input tokens on the last model request of the loop (see BenchmarkAttemptResult.finalContextTokens). */
finalContextTokens: number | null;
toolCallsCount: number;
toolsCalled: string[];
toolCallDetails: ToolCallDetail[];
iterations: number;
messages: ChatCompletionMessageParam[];
success: boolean
output: TOutput
error?: string
tokenUsage: TokenUsage
toolCallsCount: number
toolsCalled: string[]
toolCallDetails: ToolCallDetail[]
iterations: number
messages: ChatCompletionMessageParam[]
}
@@ -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([])
})
})
@@ -1,541 +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<string, string>
rows?: Record<string, unknown>[]
}
/** A seeded datatable: `datatable_name` plus a `schema -> table -> seed` map. */
export interface BenchmarkDatatableSeed {
datatable_name: string
schemas: {
[schema: string]: {
[table: string]: BenchmarkDatatableTableSeed
}
}
}
export interface DatatableSqlResult {
rows: Record<string, unknown>[]
}
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<string, unknown>[] {
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<string, unknown>[] | 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<string, unknown>[] {
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<string, string> = {}
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<string, unknown>[] {
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<string, unknown>[] {
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<string, unknown>[] = []
for (const tuple of extractParenGroups(match[3])) {
const values = splitTopLevel(tuple).map((entry) => parseValue(entry))
const row: Record<string, unknown> = {}
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<string, unknown>[] {
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<string, unknown> = {}
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<string, unknown>[] {
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<string, unknown>, 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*$/, '')
}
+9 -413
View File
@@ -1,25 +1,7 @@
import { randomUUID } from 'node:crypto'
import type {
AppWithLastVersion,
CompletedJob,
Flow,
Job,
ListableApp,
Script
} from '../../../frontend/src/lib/gen'
import type {
DataTableTables,
DataTableTableSchema,
GetDraftForUserResponse,
ListDraftsResponse,
ScriptLang,
UpdateDraftResponse,
UserDraftItemKind
} from '../../../frontend/src/lib/gen/types.gen'
import type { CompletedJob, Flow, Script } from '../../../frontend/src/lib/gen'
import type { 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'
@@ -40,54 +22,21 @@ export interface BenchmarkWorkspaceFlow {
value: Flow['value']
}
export interface BenchmarkWorkspaceApp {
path: string
summary: string
value: {
files: Record<string, string>
runnables: Record<string, unknown>
data?: unknown
policy?: unknown
custom_path?: unknown
}
}
export interface BenchmarkWorkspaceJob {
/** Stable id so a case prompt can reference a specific run (e.g. for get_job_logs). */
id?: string
jobKind?: CompletedJob['job_kind']
scriptPath?: string
createdBy?: string
label?: string
success?: boolean
logs?: string
}
export interface BenchmarkWorkspaceRunnables {
scripts?: BenchmarkWorkspaceScript[]
flows?: BenchmarkWorkspaceFlow[]
apps?: BenchmarkWorkspaceApp[]
datatables?: BenchmarkDatatableSeed[]
jobs?: BenchmarkWorkspaceJob[]
}
type BenchmarkCompletedJob = CompletedJob & { type: 'CompletedJob' }
const benchmarkWorkspaces = new Set<string>()
const benchmarkWorkspaceRunnables = new Map<string, BenchmarkWorkspaceRunnables>()
// 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 }>()
function benchmarkJobKey(workspace: string, jobId: string): string {
return `${workspace}::${jobId}`
}
export function resetBenchmarkMockBackend(): void {
benchmarkWorkspaces.clear()
benchmarkWorkspaceRunnables.clear()
benchmarkJobs.clear()
benchmarkDrafts.clear()
}
export function registerBenchmarkWorkspace(workspace: string): void {
@@ -99,33 +48,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_job_logs have data to return.
for (const seed of runnables.jobs ?? []) {
createBenchmarkCompletedJob({
workspace,
id: seed.id,
jobKind: seed.jobKind ?? 'script',
success: seed.success,
scriptPath: seed.scriptPath,
createdBy: seed.createdBy,
label: seed.label,
logs: seed.logs
})
}
benchmarkWorkspaceRunnables.set(workspace, runnables)
}
export function unregisterBenchmarkWorkspace(workspace: string): void {
benchmarkWorkspaces.delete(workspace)
benchmarkWorkspaceRunnables.delete(workspace)
clearBenchmarkDrafts(workspace)
for (const [jobId, entry] of benchmarkJobs.entries()) {
if (entry.workspace === workspace) {
benchmarkJobs.delete(jobId)
@@ -181,22 +109,6 @@ 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
}
export function createBenchmarkCompletedJob(input: {
workspace: string
jobKind: CompletedJob['job_kind']
@@ -206,17 +118,14 @@ export function createBenchmarkCompletedJob(input: {
scriptPath?: string
scriptHash?: string
args?: Record<string, unknown>
id?: string
createdBy?: string
label?: string
}): string {
const jobId = input.id ?? `benchmark-job-${randomUUID()}`
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_by: 'ai-evals',
created_at: now,
started_at: now,
completed_at: now,
@@ -234,11 +143,10 @@ export function createBenchmarkCompletedJob(input: {
is_skipped: false,
email: 'ai-evals@local',
visible_to_owner: true,
tag: 'benchmark',
labels: input.label ? [input.label] : undefined
tag: 'benchmark'
}
benchmarkJobs.set(benchmarkJobKey(input.workspace, jobId), { workspace: input.workspace, job })
benchmarkJobs.set(jobId, { workspace: input.workspace, job })
return jobId
}
@@ -246,239 +154,13 @@ export function getBenchmarkCompletedJob(
workspace: string,
jobId: string
): BenchmarkCompletedJob | null {
const entry = benchmarkJobs.get(benchmarkJobKey(workspace, jobId))
if (!entry) {
const entry = benchmarkJobs.get(jobId)
if (!entry || entry.workspace !== workspace) {
return null
}
return structuredClone(entry.job)
}
/**
* 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 = getBenchmarkCompletedJob(workspace, jobId)
if (!job) {
throw new Error(`Job Logs not found for "${jobId}"`)
}
return job.logs ?? ''
}
// ============= 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 three draft endpoints it
* exercises (`updateDraft` / `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 }
>()
// Fixed timestamp so artifacts stay deterministic. No eval simulates a
// concurrent writer, so every save is accepted and the conflict branch is
// never taken — the syncer just records this as its `last_sync` baseline.
const BENCHMARK_DRAFT_TIMESTAMP = '1970-01-01T00:00:00.000Z'
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
})
}
/** 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
if (value == null) {
benchmarkDrafts.delete(key)
} else {
benchmarkDrafts.set(key, {
workspace: input.workspace,
kind: input.kind,
path: input.path,
value
})
}
return { status: 'saved', current_timestamp: BENCHMARK_DRAFT_TIMESTAMP }
}
/** 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: BENCHMARK_DRAFT_TIMESTAMP }
}
/** 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: true,
legacy_draft: false,
created_at: BENCHMARK_DRAFT_TIMESTAMP
}))
}
// ============= 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)])
)
}))
}
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: {
@@ -545,60 +227,6 @@ export function runBenchmarkFlowByPath(input: {
})
}
export function previewBenchmarkSchedule(input: {
requestBody?: Record<string, unknown>
}): Record<string, unknown> {
const schedule = input.requestBody?.schedule
if (typeof schedule !== 'string' || schedule.trim().split(/\s+/).length !== 6) {
throw new Error(`schedule must use a six-field cron expression, got ${JSON.stringify(schedule)}`)
}
return {
next_runs: ['1970-01-02T00:00:00.000Z']
}
}
export function createBenchmarkSchedule(input: {
workspace: string
requestBody: Record<string, unknown>
}): Record<string, unknown> {
assertBenchmarkWorkspacePath('schedule', input.requestBody.path)
assertBenchmarkWorkspacePath('target', input.requestBody.script_path)
return {
path: input.requestBody.path,
target_path: input.requestBody.script_path,
is_flow: input.requestBody.is_flow,
mocked: true
}
}
export function createBenchmarkHttpTrigger(input: {
workspace: string
requestBody: Record<string, unknown>
}): Record<string, unknown> {
assertBenchmarkWorkspacePath('trigger', input.requestBody.path)
assertBenchmarkWorkspacePath('target', input.requestBody.script_path)
if (
typeof input.requestBody.route_path === 'string' &&
input.requestBody.route_path.startsWith('/')
) {
throw new Error(`HTTP trigger route_path must not start with /, got "${input.requestBody.route_path}"`)
}
return {
path: input.requestBody.path,
target_path: input.requestBody.script_path,
route_path: input.requestBody.route_path,
is_flow: input.requestBody.is_flow,
mocked: true
}
}
function assertBenchmarkWorkspacePath(label: string, value: unknown): void {
if (typeof value !== 'string' || (!value.startsWith('f/') && !value.startsWith('u/'))) {
throw new Error(`${label} path must start with f/ or u/, got ${JSON.stringify(value)}`)
}
}
function buildBenchmarkScriptHash(path: string): string {
return `benchmark:${path}`
}
@@ -640,35 +268,3 @@ function buildBenchmarkFlow(flow: BenchmarkWorkspaceFlow): Flow {
extra_perms: {}
} 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: 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: true
}
}
@@ -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<string, unknown>[])).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()
})
})
@@ -1,94 +0,0 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test'
import {
clearBenchmarkDrafts,
getBenchmarkDraftForUser,
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('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)
})
})
+1 -14
View File
@@ -1,4 +1,4 @@
export type FrontendBenchmarkProgressSurface = 'flow' | 'app' | 'script' | 'global'
export type FrontendBenchmarkProgressSurface = 'flow' | 'app' | 'script'
export type FrontendBenchmarkProgressEvent =
| {
@@ -58,17 +58,6 @@ export type FrontendBenchmarkProgressEvent =
attempt: number
runs: number
}
| {
type: 'tool-call'
surface: FrontendBenchmarkProgressSurface
caseId: string
caseNumber: number
totalCases: number
attempt: number
runs: number
toolName: string
argumentsText: string
}
export const FRONTEND_BENCHMARK_PROGRESS_PREFIX = 'WMILL_FRONTEND_AI_EVAL_PROGRESS '
@@ -120,8 +109,6 @@ export function formatFrontendBenchmarkProgressEvent(
case 'assistant-chunk':
case 'assistant-message-end':
return ''
case 'tool-call':
return `${formatCasePrefix(event.caseNumber, event.totalCases)} ${event.caseId} attempt ${event.attempt}/${event.runs} tool ${event.toolName} ${truncateSingleLine(event.argumentsText, 200)}`
}
}
+177 -187
View File
@@ -1,228 +1,218 @@
import { spawn } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { spawn } from 'node:child_process'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import {
formatFrontendBenchmarkProgressEvent,
parseFrontendBenchmarkProgressLine,
} from "./progress";
import type { BenchmarkRunResult } from "../../core/types";
formatFrontendBenchmarkProgressEvent,
parseFrontendBenchmarkProgressLine
} from './progress'
import type { BenchmarkRunResult } from '../../core/types'
const REPO_ROOT = fileURLToPath(new URL("../../../", import.meta.url));
const FRONTEND_DIR = path.join(REPO_ROOT, "frontend");
const FRONTEND_BENCHMARK_TEST =
"../ai_evals/adapters/frontend/vitestAdapter.test.ts";
const FRONTEND_BENCHMARK_CONFIG =
"../ai_evals/adapters/frontend/vitest.config.ts";
const REPO_ROOT = fileURLToPath(new URL('../../../', import.meta.url))
const FRONTEND_DIR = path.join(REPO_ROOT, 'frontend')
const FRONTEND_BENCHMARK_TEST = '../ai_evals/adapters/frontend/vitestAdapter.test.ts'
const FRONTEND_BENCHMARK_CONFIG = '../ai_evals/adapters/frontend/vitest.config.ts'
export type FrontendMode = "flow" | "app" | "script" | "global";
export type FrontendMode = 'flow' | 'app' | 'script'
export async function runFrontendBenchmarkAdapter(input: {
mode: FrontendMode;
caseIds: string[];
runs: number;
model?: string;
verbose?: boolean;
skipJudge?: boolean;
executionOnly?: boolean;
backendValidation?: string;
mode: FrontendMode
caseIds: string[]
runs: number
model?: string
verbose?: boolean
backendValidation?: string
}): Promise<BenchmarkRunResult> {
const tempDir = await mkdtemp(
path.join(tmpdir(), "wmill-frontend-benchmark-"),
);
const outputPath = path.join(tempDir, "result.json");
const env: NodeJS.ProcessEnv = {
...process.env,
BROWSERSLIST_IGNORE_OLD_DATA: "1",
WMILL_FRONTEND_AI_EVAL_OUTPUT_PATH: outputPath,
WMILL_FRONTEND_AI_EVAL_MODE: input.mode,
WMILL_FRONTEND_AI_EVAL_CASE_IDS: JSON.stringify(input.caseIds),
WMILL_FRONTEND_AI_EVAL_RUNS: String(input.runs),
WMILL_FRONTEND_AI_EVAL_MODEL: input.model ?? "",
WMILL_FRONTEND_AI_EVAL_PROGRESS: "1",
WMILL_FRONTEND_AI_EVAL_VERBOSE: input.verbose ? "1" : "0",
WMILL_FRONTEND_AI_EVAL_SKIP_JUDGE:
input.skipJudge || input.executionOnly ? "1" : "0",
WMILL_FRONTEND_AI_EVAL_EXECUTION_ONLY: input.executionOnly ? "1" : "0",
WMILL_FRONTEND_AI_EVAL_BACKEND_VALIDATION: input.backendValidation ?? "",
};
const tempDir = await mkdtemp(path.join(tmpdir(), 'wmill-frontend-benchmark-'))
const outputPath = path.join(tempDir, 'result.json')
try {
await runVitestBenchmark(
path.join(FRONTEND_DIR, "node_modules", ".bin", "vitest"),
[
"run",
FRONTEND_BENCHMARK_TEST,
"--project",
"server",
"--config",
FRONTEND_BENCHMARK_CONFIG,
],
{
cwd: FRONTEND_DIR,
env,
},
);
try {
await runVitestBenchmark(
path.join(FRONTEND_DIR, 'node_modules', '.bin', 'vitest'),
[
'run',
FRONTEND_BENCHMARK_TEST,
'--project',
'server',
'--config',
FRONTEND_BENCHMARK_CONFIG
],
{
cwd: FRONTEND_DIR,
env: {
...process.env,
BROWSERSLIST_IGNORE_OLD_DATA: '1',
WMILL_FRONTEND_AI_EVAL_OUTPUT_PATH: outputPath,
WMILL_FRONTEND_AI_EVAL_MODE: input.mode,
WMILL_FRONTEND_AI_EVAL_CASE_IDS: JSON.stringify(input.caseIds),
WMILL_FRONTEND_AI_EVAL_RUNS: String(input.runs),
WMILL_FRONTEND_AI_EVAL_MODEL: input.model ?? "",
WMILL_FRONTEND_AI_EVAL_PROGRESS: '1',
WMILL_FRONTEND_AI_EVAL_VERBOSE: input.verbose ? '1' : '0',
WMILL_FRONTEND_AI_EVAL_BACKEND_VALIDATION: input.backendValidation ?? ''
}
}
)
const raw = await readFile(outputPath, "utf8");
return JSON.parse(raw) as BenchmarkRunResult;
} catch (error) {
throw new Error(
`Frontend benchmark adapter failed:\n${toErrorMessage(error)}`,
);
} finally {
await rm(tempDir, { recursive: true, force: true });
}
const raw = await readFile(outputPath, 'utf8')
return JSON.parse(raw) as BenchmarkRunResult
} catch (error) {
throw new Error(`Frontend benchmark adapter failed:\n${toErrorMessage(error)}`)
} finally {
await rm(tempDir, { recursive: true, force: true })
}
}
async function runVitestBenchmark(
command: string,
args: string[],
options: {
cwd: string;
env: NodeJS.ProcessEnv;
},
command: string,
args: string[],
options: {
cwd: string
env: NodeJS.ProcessEnv
}
): Promise<void> {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: ["ignore", "pipe", "pipe"],
});
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: ['ignore', 'pipe', 'pipe']
})
let stdout = "";
let stderr = "";
let stderrLineBuffer = "";
let assistantStreamOpen = false;
let stdout = ''
let stderr = ''
let stderrLineBuffer = ''
let assistantStreamOpen = false
child.stdout?.setEncoding("utf8");
child.stdout?.on("data", (chunk: string) => {
stdout += chunk;
});
child.stdout?.setEncoding('utf8')
child.stdout?.on('data', (chunk: string) => {
stdout += chunk
})
child.stderr?.setEncoding("utf8");
child.stderr?.on("data", (chunk: string) => {
stderrLineBuffer += chunk;
const { remainder, passthrough, nextAssistantStreamOpen } =
drainProgressLines(stderrLineBuffer, assistantStreamOpen);
stderrLineBuffer = remainder;
stderr += passthrough;
assistantStreamOpen = nextAssistantStreamOpen;
});
child.stderr?.setEncoding('utf8')
child.stderr?.on('data', (chunk: string) => {
stderrLineBuffer += chunk
const { remainder, passthrough, nextAssistantStreamOpen } = drainProgressLines(
stderrLineBuffer,
assistantStreamOpen
)
stderrLineBuffer = remainder
stderr += passthrough
assistantStreamOpen = nextAssistantStreamOpen
})
await new Promise<void>((resolve, reject) => {
child.on("error", reject);
child.on("close", (code) => {
if (stderrLineBuffer.length > 0) {
const { remainder, passthrough, nextAssistantStreamOpen } =
drainProgressLines(`${stderrLineBuffer}\n`, assistantStreamOpen);
stderrLineBuffer = remainder;
stderr += passthrough;
assistantStreamOpen = nextAssistantStreamOpen;
}
await new Promise<void>((resolve, reject) => {
child.once('error', reject)
child.once('close', (code) => {
if (stderrLineBuffer.length > 0) {
const {
remainder,
passthrough,
nextAssistantStreamOpen
} = drainProgressLines(`${stderrLineBuffer}\n`, assistantStreamOpen)
stderrLineBuffer = remainder
stderr += passthrough
assistantStreamOpen = nextAssistantStreamOpen
}
if (code === 0) {
if (assistantStreamOpen) {
process.stderr.write("\n");
}
resolve();
return;
}
if (code === 0) {
if (assistantStreamOpen) {
process.stderr.write('\n')
}
resolve()
return
}
const details = [`vitest exited with code ${code}`, stdout, stderr]
.filter(Boolean)
.join("\n");
reject(new Error(details));
});
});
const details = [`vitest exited with code ${code}`, stdout, stderr].filter(Boolean).join('\n')
reject(new Error(details))
})
})
}
function drainProgressLines(buffer: string): {
remainder: string
passthrough: string
nextAssistantStreamOpen: boolean
}
function drainProgressLines(
buffer: string,
initialAssistantStreamOpen: boolean,
buffer: string,
initialAssistantStreamOpen: boolean
): {
remainder: string;
passthrough: string;
nextAssistantStreamOpen: boolean;
remainder: string
passthrough: string
nextAssistantStreamOpen: boolean
} {
let remainder = buffer;
let passthrough = "";
let assistantStreamOpen = initialAssistantStreamOpen;
let remainder = buffer
let passthrough = ''
let assistantStreamOpen = initialAssistantStreamOpen
while (true) {
const newlineIndex = remainder.indexOf("\n");
if (newlineIndex === -1) {
return {
remainder,
passthrough,
nextAssistantStreamOpen: assistantStreamOpen,
};
}
while (true) {
const newlineIndex = remainder.indexOf('\n')
if (newlineIndex === -1) {
return { remainder, passthrough, nextAssistantStreamOpen: assistantStreamOpen }
}
const line = remainder.slice(0, newlineIndex).replace(/\r$/, "");
remainder = remainder.slice(newlineIndex + 1);
const line = remainder.slice(0, newlineIndex).replace(/\r$/, '')
remainder = remainder.slice(newlineIndex + 1)
const progressEvent = parseFrontendBenchmarkProgressLine(line);
if (progressEvent) {
if (progressEvent.type === "assistant-message-start") {
if (assistantStreamOpen) {
process.stderr.write("\n");
}
process.stderr.write(
`${formatCasePrefix(progressEvent.caseNumber, progressEvent.totalCases)} ${progressEvent.caseId} attempt ${progressEvent.attempt}/${progressEvent.runs} assistant:\n`,
);
assistantStreamOpen = true;
continue;
}
const progressEvent = parseFrontendBenchmarkProgressLine(line)
if (progressEvent) {
if (progressEvent.type === 'assistant-message-start') {
if (assistantStreamOpen) {
process.stderr.write('\n')
}
process.stderr.write(
`${formatCasePrefix(progressEvent.caseNumber, progressEvent.totalCases)} ${progressEvent.caseId} attempt ${progressEvent.attempt}/${progressEvent.runs} assistant:\n`
)
assistantStreamOpen = true
continue
}
if (progressEvent.type === "assistant-chunk") {
process.stderr.write(progressEvent.chunk);
continue;
}
if (progressEvent.type === 'assistant-chunk') {
process.stderr.write(progressEvent.chunk)
continue
}
if (progressEvent.type === "assistant-message-end") {
if (assistantStreamOpen) {
process.stderr.write("\n");
}
assistantStreamOpen = false;
continue;
}
if (progressEvent.type === 'assistant-message-end') {
if (assistantStreamOpen) {
process.stderr.write('\n')
}
assistantStreamOpen = false
continue
}
if (assistantStreamOpen) {
process.stderr.write("\n");
assistantStreamOpen = false;
}
process.stderr.write(
`${formatFrontendBenchmarkProgressEvent(progressEvent)}\n`,
);
continue;
}
if (assistantStreamOpen) {
process.stderr.write('\n')
assistantStreamOpen = false
}
process.stderr.write(`${formatFrontendBenchmarkProgressEvent(progressEvent)}\n`)
continue
}
if (shouldSuppressFrontendStderrLine(line)) {
continue;
}
if (shouldSuppressFrontendStderrLine(line)) {
continue
}
passthrough += `${line}\n`;
process.stderr.write(`${line}\n`);
}
passthrough += `${line}\n`
process.stderr.write(`${line}\n`)
}
}
function formatCasePrefix(caseNumber: number, totalCases: number): string {
return `[${caseNumber}/${totalCases}]`;
return `[${caseNumber}/${totalCases}]`
}
function shouldSuppressFrontendStderrLine(line: string): boolean {
return (
line.startsWith("[baseline-browser-mapping] ") ||
line.startsWith("Browserslist: browsers data (caniuse-lite) is ") ||
line.includes("update-browserslist-db@latest") ||
line.includes("update-db#readme")
);
return (
line.startsWith('[baseline-browser-mapping] ') ||
line.startsWith('Browserslist: browsers data (caniuse-lite) is ') ||
line.includes('update-browserslist-db@latest') ||
line.includes('update-db#readme')
)
}
function toErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return String(error);
if (error instanceof Error) {
return error.message
}
return String(error)
}
@@ -33,29 +33,15 @@ vi.mock('$lib/components/vscode', () => ({}))
vi.mock('$lib/gen', async () => {
const actual = await vi.importActual<any>('$lib/gen')
const {
getBenchmarkAppByPath,
getBenchmarkCompletedJob,
getBenchmarkCompletedJobResultMaybe,
getBenchmarkDatatableSchema,
getBenchmarkDraftForUser,
getBenchmarkFlowByPath,
getBenchmarkJobLogs,
getBenchmarkScriptByHash,
getBenchmarkScriptByPath,
hasBenchmarkWorkspace,
listBenchmarkApps,
listBenchmarkDatatables,
listBenchmarkDrafts,
listBenchmarkFlows,
listBenchmarkJobs,
listBenchmarkScripts,
createBenchmarkHttpTrigger,
createBenchmarkSchedule,
previewBenchmarkSchedule,
runBenchmarkDatatableSql,
runBenchmarkFlowByPath,
runBenchmarkScriptPreview,
updateBenchmarkDraft
runBenchmarkScriptPreview
} = await import('./mockBackend')
function wrapService<T extends object>(target: T, overrides: Record<string, unknown>): T {
@@ -71,34 +57,11 @@ 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),
listDrafts: async (data: { workspace: string }) =>
hasBenchmarkWorkspace(data.workspace)
? listBenchmarkDrafts(data.workspace)
: actual.DraftService.listDrafts(data)
}),
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 }) => {
if (hasBenchmarkWorkspace(data.workspace)) {
const script = getBenchmarkScriptByPath(data.workspace, data.path)
@@ -109,16 +72,6 @@ vi.mock('$lib/gen', async () => {
}
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)
},
getScriptByHash: async (data: { workspace: string; hash: string }) => {
if (hasBenchmarkWorkspace(data.workspace)) {
const script = getBenchmarkScriptByHash(data.workspace, data.hash)
@@ -135,10 +88,6 @@ 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 }) => {
if (hasBenchmarkWorkspace(data.workspace)) {
const flow = getBenchmarkFlowByPath(data.workspace, data.path)
@@ -148,26 +97,6 @@ vi.mock('$lib/gen', async () => {
return 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)
}
}),
JobService: wrapService(actual.JobService, {
@@ -179,27 +108,13 @@ vi.mock('$lib/gen', async () => {
args?: Record<string, unknown>
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://<name>`.
// 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 })
},
}) =>
hasBenchmarkWorkspace(data.workspace)
? runBenchmarkScriptPreview({
workspace: data.workspace,
requestBody: data.requestBody ?? {}
})
: actual.JobService.runScriptPreview(data),
runFlowByPath: async (data: {
workspace: string
path: string
@@ -221,226 +136,6 @@ 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)
}),
WorkspaceService: wrapService(actual.WorkspaceService, {
listDataTableTables: async (data: { workspace: string }) =>
hasBenchmarkWorkspace(data.workspace)
? (listBenchmarkDatatables(data.workspace) ?? [])
: actual.WorkspaceService.listDataTableTables(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)
}),
ScheduleService: wrapService(actual.ScheduleService, {
existsSchedule: async (data: { workspace: string; path: string }) =>
hasBenchmarkWorkspace(data.workspace) ? false : actual.ScheduleService.existsSchedule(data),
listSchedules: async (data: { workspace: string }) =>
hasBenchmarkWorkspace(data.workspace) ? [] : actual.ScheduleService.listSchedules(data),
getSchedule: async (data: { workspace: string; path: string }) => {
if (hasBenchmarkWorkspace(data.workspace)) {
throw new Error(`Schedule "${data.path}" not found in benchmark workspace`)
}
return actual.ScheduleService.getSchedule(data)
},
previewSchedule: async (data: { requestBody?: Record<string, unknown> }) =>
previewBenchmarkSchedule(data),
createSchedule: async (data: { workspace: string; requestBody: Record<string, unknown> }) =>
hasBenchmarkWorkspace(data.workspace)
? createBenchmarkSchedule(data)
: actual.ScheduleService.createSchedule(data)
}),
ResourceService: wrapService(actual.ResourceService, {
existsResource: async (data: { workspace: string; path: string }) =>
hasBenchmarkWorkspace(data.workspace) ? false : actual.ResourceService.existsResource(data),
listResource: async (data: { workspace: string }) =>
hasBenchmarkWorkspace(data.workspace) ? [] : actual.ResourceService.listResource(data),
getResource: async (data: { workspace: string; path: string }) => {
if (hasBenchmarkWorkspace(data.workspace)) {
throw new Error(`Resource "${data.path}" not found in benchmark workspace`)
}
return actual.ResourceService.getResource(data)
},
queryResourceTypes: async (data: { workspace: string }) =>
hasBenchmarkWorkspace(data.workspace) ? [] : actual.ResourceService.queryResourceTypes(data)
}),
VariableService: wrapService(actual.VariableService, {
existsVariable: async (data: { workspace: string; path: string }) =>
hasBenchmarkWorkspace(data.workspace) ? false : actual.VariableService.existsVariable(data),
listVariable: async (data: { workspace: string }) =>
hasBenchmarkWorkspace(data.workspace) ? [] : actual.VariableService.listVariable(data),
getVariable: async (data: { workspace: string; path: string }) => {
if (hasBenchmarkWorkspace(data.workspace)) {
throw new Error(`Variable "${data.path}" not found in benchmark workspace`)
}
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 }) => {
if (hasBenchmarkWorkspace(data.workspace)) {
const app = getBenchmarkAppByPath(data.workspace, data.path)
if (!app) {
throw new Error(`App "${data.path}" not found in benchmark workspace`)
}
return app
}
return actual.AppService.getAppByPath(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<string, unknown> }) =>
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)
}
})
}
@@ -466,6 +161,5 @@ benchmarkIt(
resetBenchmarkMockBackend()
}
},
// Full-suite runs (30+ cases at concurrency 2-3) routinely exceed 10 minutes.
7_200_000
600_000
)
@@ -1,104 +0,0 @@
import { afterEach, describe, expect, it } from "bun:test";
import type { WindmillBackendSettings } from "../../core/windmillBackendSettings";
import {
WindmillBackendClient,
assertWindmillBackendReachable,
} from "./windmillBackend";
const ORIGINAL_FETCH = globalThis.fetch;
afterEach(() => {
globalThis.fetch = ORIGINAL_FETCH;
});
describe("assertWindmillBackendReachable", () => {
it("logs in to verify backend reachability", async () => {
const requests: Array<{ url: string; init?: RequestInit }> = [];
globalThis.fetch = mockFetch(requests, textResponse(200, "token"));
await expect(
assertWindmillBackendReachable(
buildSettings({ baseUrl: "http://backend.test/reachable" }),
),
).resolves.toBeUndefined();
expect(requests.map((entry) => entry.url)).toEqual([
"http://backend.test/reachable/api/auth/login",
]);
});
it("adds setup guidance when the backend cannot be initialized", async () => {
globalThis.fetch = mockFetch(
[],
textResponse(401, "invalid password"),
);
await expect(
assertWindmillBackendReachable(
buildSettings({ baseUrl: "http://backend.test/auth-failure" }),
),
).rejects.toThrow(
"Start a Windmill backend at that URL, or set WMILL_AI_EVAL_BACKEND_URL=<url>.",
);
});
});
describe("WindmillBackendClient", () => {
it("creates or reuses the specified backend workspace without deleting it", async () => {
const requests: Array<{ url: string; init?: RequestInit }> = [];
globalThis.fetch = mockFetch(
requests,
textResponse(200, "token"),
textResponse(200, "false"),
textResponse(200, ""),
);
const client = new WindmillBackendClient(
buildSettings({
baseUrl: "http://backend.test/shared-workspace",
workspaceOverride: "shared-evals",
}),
);
await expect(
client.withWorkspace("case-a", 1, async (workspaceId) => workspaceId),
).resolves.toBe("shared-evals");
expect(requests.map((entry) => entry.url)).toEqual([
"http://backend.test/shared-workspace/api/auth/login",
"http://backend.test/shared-workspace/api/workspaces/exists",
"http://backend.test/shared-workspace/api/workspaces/create",
]);
});
});
function buildSettings(
overrides: Partial<WindmillBackendSettings> = {},
): WindmillBackendSettings {
return {
baseUrl: "http://backend.test/default",
email: "admin@windmill.dev",
password: "changeme",
...overrides,
};
}
function mockFetch(
requests: Array<{ url: string; init?: RequestInit }>,
...responses: Response[]
): typeof fetch {
const queue = [...responses];
return async (input, init) => {
const url = String(input);
requests.push({ url, init });
const next = queue.shift();
if (!next) {
throw new Error(`Unexpected fetch: ${url}`);
}
return next;
};
}
function textResponse(status: number, body: string): Response {
return new Response(body, { status });
}
@@ -1,199 +0,0 @@
import { randomUUID } from "node:crypto";
import type { WindmillBackendSettings } from "../../core/windmillBackendSettings";
const tokenCache = new Map<string, Promise<string>>();
const sharedWorkspaceQueue = new Map<string, Promise<void>>();
const DEFAULT_WORKSPACE_PREFIX = "ai-evals";
export class WindmillBackendClient {
constructor(private readonly settings: WindmillBackendSettings) {}
async withWorkspace<T>(
caseId: string,
attempt: number,
body: (workspaceId: string) => Promise<T>,
): Promise<T> {
const workspaceId =
this.settings.workspaceOverride ??
buildWorkspaceId(caseId, attempt);
const run = async () => {
await this.ensureWorkspace(workspaceId);
try {
return await body(workspaceId);
} finally {
if (!this.settings.workspaceOverride) {
await this.deleteWorkspace(workspaceId).catch(() => undefined);
}
}
};
if (this.settings.workspaceOverride) {
return await withSharedWorkspaceLock(workspaceId, run);
}
return await run();
}
async request(path: string, init?: RequestInit): Promise<Response> {
const token = await this.getToken();
return await fetch(`${this.settings.baseUrl}/api${path}`, {
...init,
headers: {
Authorization: `Bearer ${token}`,
...(init?.headers ?? {}),
},
});
}
async getToken(): Promise<string> {
const cacheKey = `${this.settings.baseUrl}|${this.settings.email}`;
let tokenPromise = tokenCache.get(cacheKey);
if (!tokenPromise) {
tokenPromise = this.login().catch((error) => {
if (tokenCache.get(cacheKey) === tokenPromise) {
tokenCache.delete(cacheKey);
}
throw error;
});
tokenCache.set(cacheKey, tokenPromise);
}
return await tokenPromise;
}
async upsertResource(input: {
workspaceId: string;
path: string;
resourceType: string;
value: Record<string, unknown>;
}): Promise<void> {
const response = await this.request(
`/w/${encodeURIComponent(input.workspaceId)}/resources/create?update_if_exists=true`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
path: input.path,
resource_type: input.resourceType,
value: input.value,
}),
},
);
await expectOk(response, `upsert resource ${input.path}`);
}
private async ensureWorkspace(workspaceId: string): Promise<void> {
const existsResponse = await this.request("/workspaces/exists", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: workspaceId }),
});
await expectOk(existsResponse, `check workspace ${workspaceId}`);
if ((await existsResponse.text()).trim() === "true") {
return;
}
const createResponse = await this.request("/workspaces/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: workspaceId, name: workspaceId }),
});
try {
await expectOk(createResponse, `create workspace ${workspaceId}`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.includes("maximum number of workspaces")) {
throw new Error(
`${message}. Reuse an existing workspace with WMILL_AI_EVAL_BACKEND_WORKSPACE=<workspace-id>.`,
);
}
throw error;
}
}
private async deleteWorkspace(workspaceId: string): Promise<void> {
const response = await this.request(
`/workspaces/delete/${encodeURIComponent(workspaceId)}`,
{
method: "DELETE",
},
);
await expectOk(response, `delete workspace ${workspaceId}`);
}
private async login(): Promise<string> {
const response = await fetch(`${this.settings.baseUrl}/api/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: this.settings.email,
password: this.settings.password,
}),
});
await expectOk(response, "login to Windmill backend");
return (await response.text()).trim();
}
}
export async function assertWindmillBackendReachable(
settings: WindmillBackendSettings,
): Promise<void> {
try {
await new WindmillBackendClient(settings).getToken();
} catch (error) {
const details = error instanceof Error ? error.message : String(error);
throw new Error(
[
`Could not initialize the Windmill backend for AI eval proxy at ${settings.baseUrl}.`,
"Start a Windmill backend at that URL, or set WMILL_AI_EVAL_BACKEND_URL=<url>.",
`Using login ${settings.email}; if authentication failed, set WMILL_AI_EVAL_BACKEND_EMAIL and WMILL_AI_EVAL_BACKEND_PASSWORD.`,
`Details: ${details}`,
].join("\n"),
);
}
}
async function withSharedWorkspaceLock<T>(
workspaceId: string,
body: () => Promise<T>,
): Promise<T> {
const previous = sharedWorkspaceQueue.get(workspaceId) ?? Promise.resolve();
let releaseCurrent: (() => void) | undefined;
const current = new Promise<void>((resolve) => {
releaseCurrent = resolve;
});
const tail = previous.catch(() => undefined).then(() => current);
sharedWorkspaceQueue.set(workspaceId, tail);
await previous.catch(() => undefined);
try {
return await body();
} finally {
releaseCurrent?.();
if (sharedWorkspaceQueue.get(workspaceId) === tail) {
sharedWorkspaceQueue.delete(workspaceId);
}
}
}
function buildWorkspaceId(caseId: string, attempt: number): string {
const caseSlug = caseId
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 30);
const suffix = randomUUID().slice(0, 8);
return `${DEFAULT_WORKSPACE_PREFIX}-${caseSlug || "case"}-a${attempt}-${suffix}`;
}
async function expectOk(response: Response, context: string): Promise<void> {
if (response.ok) {
return;
}
throw new Error(
`${context} failed: ${response.status} ${response.statusText} - ${await response.text()}`,
);
}
+24 -257
View File
@@ -47,30 +47,15 @@
- updates the visible file list from the search query
- keeps the rest of the file manager usable
- id: app-test6-file-manager-rename-save-cancel
- id: app-test6-file-manager-inline-rename
prompt: |-
Improve the existing inline rename flow for files and folders.
When renaming, show explicit Save and Cancel buttons next to the name input.
Pressing Enter should save, pressing Escape should cancel, and Cancel should restore the original name without calling rename.
Keep the existing backend rename behavior for successful saves.
Let users rename files and folders directly from the file list without leaving the page.
initial: ai_evals/fixtures/frontend/app/initial/file_manager
validate:
requiredFrontendPaths:
- /index.tsx
- /components/FileItem.tsx
requiredFrontendFileContent:
- path: /components/FileItem.tsx
includes:
- Save
- Cancel
- Escape
forbiddenAppContent:
- onBlur={handleRename}
judgeChecklist:
- keeps the existing visible rename action in the file list
- shows explicit Save and Cancel controls while editing a name
- pressing Enter saves the new name through the existing rename behavior
- pressing Escape or Cancel exits rename mode and restores the original name without saving
- adds a visible rename action or inline edit mode in the file list
- lets users edit an item's name directly from the list
- saves the renamed item through the app's existing rename behavior
- refreshes the displayed name after a successful rename
- id: app-test7-file-manager-select-all
prompt: |-
@@ -83,244 +68,26 @@
- shows a delete-selected action only when there is a selection
- deleting selected items updates the visible list
- id: app-test8-inventory-tracker-search-delete
- id: app-test8-inventory-tracker-create
prompt: |-
Update this inventory tracker app so users can search items by name or sku and delete existing items.
Keep the existing add-item flow and datatable-backed persistence working.
initial: ai_evals/fixtures/frontend/app/initial/inventory_tracker
validate:
requiredFrontendPaths:
- /index.tsx
requiredBackendRunnableKeys:
- listInventory
- addInventory
- deleteInventory
requiredBackendRunnableTypes:
- key: listInventory
type: inline
- key: addInventory
type: inline
- key: deleteInventory
type: inline
requiredDatatables:
- datatableName: main
schema: public
table: inventory_items
Create an inventory tracker app for a small store.
Users should be able to add items with a name, sku, quantity, and price, search items by name or sku, and delete items.
The inventory should persist between sessions.
judgeChecklist:
- keeps the existing add-item form working
- adds a search input that filters inventory by name or sku
- adds a delete action for existing inventory items
- deleting an inventory item updates the visible list
- keeps inventory persistence working through the existing datatable-backed app setup
- includes a form to add inventory items with name, sku, quantity, and price
- shows a list or table of saved inventory items
- supports searching or filtering by name or sku
- lets users delete existing inventory items
- persists the inventory data appropriately for a raw Windmill app
- id: app-test9-recipe-book-search-delete
- id: app-test9-recipe-book-create
prompt: |-
Update this recipe book app so users can search recipes by name and delete existing recipes.
Keep the existing add-recipe flow and datatable-backed persistence working.
initial: ai_evals/fixtures/frontend/app/initial/recipe_book
validate:
requiredFrontendPaths:
- /index.tsx
requiredBackendRunnableKeys:
- listRecipes
- addRecipe
- deleteRecipe
requiredBackendRunnableTypes:
- key: listRecipes
type: inline
- key: addRecipe
type: inline
- key: deleteRecipe
type: inline
requiredDatatables:
- datatableName: main
schema: public
table: recipes
Create a recipe book app where users can add recipes with a name, ingredients list, and instructions.
Include a search bar to filter recipes by name and the ability to delete recipes.
Recipes should persist between sessions.
judgeChecklist:
- keeps the existing add-recipe form working
- adds a search input that filters recipes by name
- adds a delete action for existing recipes
- deleting a recipe updates the visible list
- keeps recipe persistence working through the existing datatable-backed app setup
- id: app-datatable-persistent-notes
prompt: |-
Build a notes app that persists notes in the existing datatable table.
Inspect the existing datatable and table schema before writing code.
Use the existing main/public.notes table, and do not create any new tables.
Create backend runnables named exactly listNotes, addNote, and deleteNote.
The UI should list notes, add a note with title/body, and delete notes.
Do not use localStorage, sessionStorage, IndexedDB, or in-memory-only persistence.
initial: ai_evals/fixtures/frontend/app/initial/notes_datatable
runtime:
maxTurns: 10
validate:
requiredFrontendPaths:
- /index.tsx
requiredFrontendFileContent:
- path: /index.tsx
includes:
- backend.listNotes
- backend.addNote
- backend.deleteNote
requiredBackendRunnableKeys:
- listNotes
- addNote
- deleteNote
requiredBackendRunnableTypes:
- key: listNotes
type: inline
- key: addNote
type: inline
- key: deleteNote
type: inline
requiredBackendRunnableContent:
- key: listNotes
includes:
- wmill.datatable
- select
- notes
- key: addNote
includes:
- wmill.datatable
- insert
- notes
- key: deleteNote
includes:
- wmill.datatable
- delete
- notes
datatableTableCountExactly: 1
requiredDatatables:
- datatableName: main
schema: public
table: notes
requiredToolsUsed:
- list_datatables
- get_datatable_table_schema
forbiddenAppContent:
- localStorage
- sessionStorage
- indexedDB
judgeChecklist:
- creates a notes UI that lists notes from the backend
- adds notes through backend datatable persistence
- deletes notes through backend datatable persistence
- reuses the existing main/public.notes table without creating new tables
- does not use browser storage or in-memory-only persistence as the source of truth
- id: app-test10-session-id-no-crypto
prompt: |-
Update `generateSessionId` so it no longer uses `crypto.randomUUID()`.
Make it return a handmade string id built from the current time and random characters.
Keep the existing sessionStorage-based chat session behavior unchanged.
initial: ai_evals/fixtures/frontend/app/initial/session_id_chat
runtime:
maxTurns: 4
validate:
requiredFrontendPaths:
- /index.tsx
requiredBackendRunnableKeys:
- a
requiredBackendRunnableTypes:
- key: a
type: inline
judgeChecklist:
- generateSessionId no longer calls crypto.randomUUID
- generateSessionId returns a handmade string id without using crypto
- getSessionId still stores and reuses chat_session_id in sessionStorage
- the existing new chat and send message session behavior remains wired up
- id: app-token-baseline-large-app-small-edit
prompt: |-
Change the main heading from "Analytics Console" to "Operations Console".
Keep the existing filtering, summary loading, and backend calls unchanged.
initial: ai_evals/fixtures/frontend/app/initial/token_heavy_context
runtime:
maxTurns: 8
validate:
requiredFrontendPaths:
- /index.tsx
requiredBackendRunnableKeys:
- loadAnalytics
- refreshSummary
judgeChecklist:
- changes the visible main heading to Operations Console
- keeps the existing summary loading behavior wired to loadAnalytics
- keeps the existing filter input and metric list behavior intact
- id: app-token-many-datatable-context
prompt: |-
Add a short note under the dashboard heading that says "Using existing analytics tables".
Do not create any new tables.
initial: ai_evals/fixtures/frontend/app/initial/token_heavy_datatables
runtime:
maxTurns: 8
appContext:
additional:
- type: datatable
datatableName: main
schema: analytics
table: event_log_01
- type: datatable
datatableName: main
schema: analytics
table: event_log_02
- type: datatable
datatableName: main
schema: analytics
table: event_log_03
- type: datatable
datatableName: main
schema: analytics
table: event_log_04
- type: datatable
datatableName: main
schema: analytics
table: event_log_05
- type: datatable
datatableName: main
schema: analytics
table: event_log_06
- type: datatable
datatableName: main
schema: analytics
table: event_log_07
- type: datatable
datatableName: main
schema: analytics
table: event_log_08
- type: datatable
datatableName: main
schema: operations
table: ops_record_13
- type: datatable
datatableName: main
schema: operations
table: ops_record_14
validate:
requiredFrontendPaths:
- /index.tsx
datatableCountAtLeast: 1
datatableTableCountAtLeast: 18
judgeChecklist:
- adds the note Using existing analytics tables under or near the heading
- does not create new datatable tables
- keeps the configured datatable references available in the app artifact
- id: app-token-large-datatable-discovery
prompt: |-
Build a read-only dashboard page that reuses the existing analytics datatable tables.
Show a simple summary of which existing tables are available, and do not create any new tables.
initial: ai_evals/fixtures/frontend/app/initial/token_heavy_datatables
runtime:
maxTurns: 8
validate:
requiredFrontendPaths:
- /index.tsx
datatableCountAtLeast: 1
datatableTableCountAtLeast: 18
judgeChecklist:
- reuses the existing datatable configuration rather than creating new tables
- presents a read-only dashboard or summary of available analytics data
- keeps the configured datatable references available in the app artifact
- includes a form to add recipes with name, ingredients, and instructions
- shows saved recipes in the app
- supports searching recipes by name
- lets users delete recipes
- persists recipes appropriately for a raw Windmill app
-197
View File
@@ -3,23 +3,6 @@
Create a Windmill Bun script at `f/evals/hello.ts`.
It should take a `name` input and return a greeting object like `{ greeting: "Hello, Alice!" }`.
expected: ai_evals/fixtures/cli/expected/bun-hello-script
cliExpect:
requiredSkills:
- write-script-bun
requiredSkillsBeforeFirstMutation:
- write-script-bun
forbiddenSkills:
- write-script-python3
- write-flow
orderedAssistantMentions:
- wmill generate-metadata
- wmill sync push
orderedProposedCommands:
- wmill generate-metadata
- wmill sync push
forbiddenExecutedCommands:
- ^wmill generate-metadata
- ^wmill sync push
judgeChecklist:
- creates the requested Bun script at f/evals/hello.ts
- takes a name input
@@ -31,22 +14,6 @@
It should take a `name` input and return a greeting object like `{ greeting: "Hello, Alice!" }`.
Put the step code in `hello.ts`.
expected: ai_evals/fixtures/cli/expected/bun-hello-flow
cliExpect:
requiredSkills:
- write-flow
requiredSkillsBeforeFirstMutation:
- write-flow
forbiddenSkills:
- write-script-python3
orderedAssistantMentions:
- wmill generate-metadata
- wmill sync push
orderedProposedCommands:
- wmill generate-metadata
- wmill sync push
forbiddenExecutedCommands:
- ^wmill generate-metadata
- ^wmill sync push
judgeChecklist:
- creates the requested flow folder with flow.yaml and hello.ts
- wires the name input into the flow step
@@ -57,23 +24,6 @@
Add a Windmill Python script at `f/evals/add_numbers.py`.
It should take `a` and `b` as inputs and return `{ "total": a + b }`.
expected: ai_evals/fixtures/cli/expected/python-add-numbers-script
cliExpect:
requiredSkills:
- write-script-python3
requiredSkillsBeforeFirstMutation:
- write-script-python3
forbiddenSkills:
- write-script-bun
- write-flow
orderedAssistantMentions:
- wmill generate-metadata
- wmill sync push
orderedProposedCommands:
- wmill generate-metadata
- wmill sync push
forbiddenExecutedCommands:
- ^wmill generate-metadata
- ^wmill sync push
judgeChecklist:
- creates the requested Python script at f/evals/add_numbers.py
- takes `a` and `b` as inputs
@@ -109,155 +59,8 @@
Create a flow at `f/evals/reuse_greeting__flow` that takes a `name` input and reuses that existing script instead of duplicating the logic inline.
initial: ai_evals/fixtures/cli/initial/flow-reuse-existing-script
expected: ai_evals/fixtures/cli/expected/flow-reuse-existing-script
cliExpect:
requiredSkills:
- write-flow
requiredSkillsBeforeFirstMutation:
- write-flow
orderedAssistantMentions:
- wmill generate-metadata
- wmill sync push
orderedProposedCommands:
- wmill generate-metadata
- wmill sync push
forbiddenExecutedCommands:
- ^wmill generate-metadata
- ^wmill sync push
judgeChecklist:
- creates the requested flow at f/evals/reuse_greeting__flow
- reuses the existing script from f/lib by path
- does not duplicate the greeting logic in a new inline script
- wires the name input into the reused script
- id: wac-typescript-order-workflow
prompt: |-
Create a Windmill Workflow-as-Code TypeScript script at `f/evals/order_workflow.ts`.
It should take an `orderId` string, load the order in a durable task, checkpoint a processing timestamp with `step`, and return `{ orderId, processedAt, status }`.
cliExpect:
requiredSkills:
- write-workflow-as-code
requiredSkillsBeforeFirstMutation:
- write-workflow-as-code
forbiddenSkills:
- write-flow
- write-script-bun
- write-script-python3
judgeChecklist:
- creates the requested TypeScript WAC script at f/evals/order_workflow.ts
- uses the Workflow-as-Code SDK from windmill-client
- wraps the entrypoint with workflow
- uses a durable task for loading the order
- uses step to checkpoint the processing timestamp
- does not create an OpenFlow flow.yaml or flow folder
- id: wac-python-approval-workflow
prompt: |-
Create a Windmill Workflow-as-Code Python script at `f/evals/approval_workflow.py`.
It should take a `request_id` string, prepare an approval summary in a task, create resume URLs inside a durable step, wait for approval, and return the approval result.
cliExpect:
requiredSkills:
- write-workflow-as-code
requiredSkillsBeforeFirstMutation:
- write-workflow-as-code
forbiddenSkills:
- write-flow
- write-script-bun
- write-script-python3
judgeChecklist:
- creates the requested Python WAC script at f/evals/approval_workflow.py
- imports Workflow-as-Code helpers from wmill
- decorates an async entrypoint with @workflow
- uses @task for the approval summary work
- gets resume URLs inside step before waiting for approval
- uses wait_for_approval
- does not create an OpenFlow flow.yaml or flow folder
- id: wac-not-openflow-disambiguation
prompt: |-
Create this as Workflow-as-Code, not an OpenFlow YAML flow: a TypeScript script at `f/evals/fanout_workflow.ts`.
It should take an array of customer IDs, process each customer with a WAC task, run the independent customer tasks in parallel, and return the collected results.
cliExpect:
requiredSkills:
- write-workflow-as-code
requiredSkillsBeforeFirstMutation:
- write-workflow-as-code
forbiddenSkills:
- write-flow
- write-script-bun
- write-script-python3
judgeChecklist:
- creates the requested TypeScript script at f/evals/fanout_workflow.ts
- treats the request as Workflow-as-Code rather than an OpenFlow flow
- uses workflow for the script entrypoint
- uses task for each customer processing unit
- runs independent customer tasks in parallel
- does not create a flow folder or flow.yaml
- id: cli-job-debug-guidance
prompt: |-
A Windmill job failed.
Tell me exactly which `wmill` commands to run to inspect the job details, logs, and final result for job ID `123`.
Do not modify any files.
cliExpect:
requiredSkills:
- cli-commands
workspaceUnchanged: true
orderedProposedCommands:
- wmill job get 123
- wmill job logs 123
- wmill job result 123
forbiddenProposedCommands:
- wmill sync push
forbiddenExecutedCommands:
- ^wmill job get
- ^wmill job logs
- ^wmill job result
judgeChecklist:
- does not modify the workspace
- recommends commands to inspect the job details
- recommends commands to inspect the job logs
- recommends commands to inspect the final result
- id: cli-sync-pull-guidance
prompt: |-
I want to review remote workspace changes before editing locally.
Tell me the first `wmill` command I should run.
Do not modify any files.
cliExpect:
requiredSkills:
- cli-commands
workspaceUnchanged: true
requiredProposedCommands:
- wmill sync pull
forbiddenProposedCommands:
- wmill sync push
forbiddenExecutedCommands:
- ^wmill sync pull
- ^wmill sync push
judgeChecklist:
- does not modify the workspace
- recommends using sync pull before making local edits
- does not recommend pushing first
- id: cli-script-deploy-guidance
prompt: |-
I already modified a Windmill script locally and now want the next CLI commands to prepare it and deploy it.
Tell me the commands to run, in order.
Do not modify any files.
cliExpect:
requiredSkills:
- cli-commands
workspaceUnchanged: true
orderedAssistantMentions:
- wmill generate-metadata
- wmill sync push
orderedProposedCommands:
- wmill generate-metadata
- wmill sync push
forbiddenExecutedCommands:
- ^wmill generate-metadata
- ^wmill sync push
judgeChecklist:
- does not modify the workspace
- recommends generate-metadata before sync push
- presents the commands in order
+15 -233
View File
@@ -8,9 +8,6 @@
args:
a: 4
b: 5
toolExpect:
requiredToolsUsed:
- test_run_flow
judgeChecklist:
- "the flow takes `a` and `b` as inputs"
- "the main step is named `sum_numbers`"
@@ -28,9 +25,6 @@
args:
a: 2
b: 3
toolExpect:
requiredToolsUsed:
- test_run_flow
judgeChecklist:
- "the flow takes `a` and `b` as inputs"
- "the main step is named `sum_numbers`"
@@ -48,46 +42,11 @@
args:
a: 7
b: 8
toolExpect:
requiredToolsUsed:
- test_run_flow
judgeChecklist:
- "the parent flow takes `a` and `b` as inputs"
- "the main step is named `call_add_numbers`"
- the parent flow delegates to an existing workspace subflow instead of inlining the addition logic
- id: flow-test13-prefer-existing-workspace-flow
prompt: |-
Create a parent flow that adds two numbers by reusing an existing flow from the workspace if one fits.
A reusable script may also be available, but for this task prefer the existing flow rather than calling a script directly or rewriting the logic inline.
The parent flow should take `a` and `b` as inputs and use a single top-level step named `call_add_numbers_flow`.
initial: ai_evals/fixtures/frontend/flow/initial/test13_prefer_existing_workspace_flow_initial.json
expected: ai_evals/fixtures/frontend/flow/expected/test13_prefer_existing_workspace_flow.json
validate:
exactTopLevelStepIds:
- call_add_numbers_flow
topLevelStepTypes:
- id: call_add_numbers_flow
type: flow
moduleRules:
- id: call_add_numbers_flow
requiredInputTransforms:
- type: javascript
expr: flow_input.a
- type: javascript
expr: flow_input.b
runtime:
backendPreview:
args:
a: 10
b: 5
judgeChecklist:
- "the parent flow takes `a` and `b` as inputs"
- "the main step is named `call_add_numbers_flow`"
- the parent flow reuses the existing workspace flow as a subflow
- the parent flow does not call the standalone workspace script directly
- the parent flow does not inline the addition logic
- id: flow-test3-branchone-routing
prompt: |-
Create a flow that routes incoming support requests based on the customer's tier.
@@ -177,7 +136,7 @@
- search FAQs
- open a support ticket when needed
After that, log the interaction and return the assistant's response.
After that, log the interaction and return the assistant's response along with any actions it took.
judgeChecklist:
- "the input schema includes `customer_id` and `query_text`"
- the flow loads the customer's profile and order history
@@ -187,42 +146,24 @@
- the assistant can search FAQs
- the assistant can open a support ticket
- the flow logs the interaction
- the final output returns the assistant response
- the final output returns the assistant response along with any actions taken or resulting support action details
- id: flow-test7-simple-modification
prompt: |-
Update this flow so it validates processed data before saving it.
After `process_data`, add a `validate_data` step that checks the data array is not empty.
If the array is empty, the flow should surface the message `No data to save` and prevent saving.
If the array is empty, it should return an error object with the message `No data to save`.
If validation passes, let the save continue normally.
Update `save_results` so it uses the validation outcome instead of bypassing it.
Update `save_results` so it handles the validation result correctly.
initial: ai_evals/fixtures/frontend/flow/initial/test5_initial.json
runtime:
maxTurns: 8
validate:
topLevelStepIds:
- fetch_data
- process_data
- validate_data
topLevelStepOrder:
- fetch_data
- process_data
- validate_data
topLevelStepTypes:
- id: fetch_data
type: rawscript
- id: process_data
type: rawscript
- id: validate_data
type: rawscript
expected: ai_evals/fixtures/frontend/flow/expected/test5_modify_simple.json
judgeChecklist:
- the updated flow keeps the original fetch and process steps intact
- "a `validate_data` step is added after `process_data`"
- "`validate_data` checks that the processed data array is not empty"
- "when processed data is empty, the flow surfaces the message `No data to save` and does not save results"
- "`save_results` uses the validation outcome instead of reading `results.process_data` directly"
- "exact field names or wrapper object shape for the validation result are not important"
- "empty data returns an error object with the message `No data to save`"
- "`save_results` handles the validation result correctly"
- id: flow-test8-branching-in-loop
prompt: |-
@@ -252,29 +193,7 @@
Update `combine_data` so it merges the enrichment results and sets a `hasFallbacks` flag when any fallback was used.
Keep `get_item` as the first step and `return_result` as the last step.
initial: ai_evals/fixtures/frontend/flow/initial/test7_initial.json
validate:
topLevelStepIds:
- get_item
- combine_data
- return_result
topLevelStepOrder:
- get_item
- combine_data
- return_result
topLevelStepTypeCountsAtLeast:
- type: branchall
count: 1
topLevelStepTypes:
- id: get_item
type: rawscript
- id: combine_data
type: rawscript
- id: return_result
type: rawscript
moduleRules:
- id: enrich_price
- id: enrich_inventory
- id: enrich_reviews
expected: ai_evals/fixtures/frontend/flow/expected/test7_modify_complex.json
judgeChecklist:
- "the updated flow keeps `get_item` as the first step"
- "the updated flow keeps `return_result` as the last step"
@@ -287,42 +206,14 @@
prompt: |-
Create a flow that keeps incrementing a counter until it reaches a target value.
The input should include a number field named `target`.
Use a top-level loop step named `count_until_target`.
Inside it, use a single step named `increment_counter` that increments the current counter.
The loop should stop once the counter reaches `target`.
After the loop, add a top-level step named `return_final_counter` that returns the last counter value.
validate:
exactTopLevelStepIds:
- count_until_target
- return_final_counter
topLevelStepOrder:
- count_until_target
- return_final_counter
topLevelStepTypes:
- id: count_until_target
type: whileloopflow
- id: return_final_counter
type: rawscript
moduleRules:
- id: count_until_target
hasStopAfterIf: true
hasStopAfterAllItersIf: false
exactImmediateChildStepIds:
- increment_counter
immediateChildStepTypes:
- id: increment_counter
type: rawscript
moduleFieldRules:
- id: count_until_target
path: stop_after_if.expr
equals: result >= flow_input.target
Name the looping step `count_until_target`.
Once the target is reached, return the final counter value.
expected: ai_evals/fixtures/frontend/flow/expected/test10_while_loop_counter.json
judgeChecklist:
- "the input schema includes a number field named `target`"
- "the top-level while loop step is named `count_until_target`"
- "`count_until_target` contains a single increment step named `increment_counter`"
- "`count_until_target` uses module-level `stop_after_if` to stop when the counter reaches `target`"
- "`increment_counter` uses `flow_input.iter.value` or an equivalent loop-state expression and falls back to `0` on the first iteration"
- "`return_final_counter` returns the final counter value"
- "the looping step is named `count_until_target`"
- the flow keeps incrementing a counter until the target is reached
- the final output returns the final counter value
- id: flow-test11-preprocessor-and-failure-handler
prompt: |-
@@ -351,16 +242,8 @@
Add an approval step named `request_approval` that pauses the flow and asks the approver for a comment.
One approval should be enough to continue.
After approval, add a final step named `finalize_purchase` that returns an approved status object.
expected: ai_evals/fixtures/frontend/flow/expected/test12_approval_step.json
validate:
topLevelStepIds:
- request_approval
- finalize_purchase
topLevelStepOrder:
- request_approval
- finalize_purchase
topLevelStepTypes:
- id: finalize_purchase
type: rawscript
schemaRequiredPaths:
- requester_email
- amount
@@ -376,104 +259,3 @@
- one approval is enough to continue
- "the flow includes a final step named `finalize_purchase`"
- "`finalize_purchase` returns an approved status object after approval"
- id: flow-test13-loop-resilience-toggle
prompt: |-
Update `loop_orders` so it can process orders in parallel.
If one order fails, the rest should still continue.
Keep the existing order-fetching and summary steps the same.
initial: ai_evals/fixtures/frontend/flow/initial/test6_initial.json
validate:
exactTopLevelStepIds:
- get_orders
- loop_orders
- summarize
topLevelStepTypes:
- id: loop_orders
type: forloopflow
moduleFieldRules:
- id: loop_orders
path: value.parallel
equals: true
- id: loop_orders
path: value.skip_failures
equals: true
judgeChecklist:
- "the flow keeps `get_orders` before `loop_orders` and `summarize` after it"
- "`loop_orders` processes orders in parallel"
- "a failure in one order does not stop the remaining orders from being processed"
- id: flow-test14-modify-existing-special-modules
prompt: |-
Update this event-processing flow for a string payload.
Before `process_event` runs, trim the payload and reject empty strings.
If anything fails, return a compact error object with the error message and the failing step id.
Keep `process_event` as the main step.
initial: ai_evals/fixtures/frontend/flow/initial/test11_initial.json
expected: ai_evals/fixtures/frontend/flow/expected/test11_preprocessor_failure.json
validate:
requireSpecialModules:
- preprocessor_module
- failure_module
judgeChecklist:
- the updated flow trims the payload before the main processing runs
- the updated flow rejects empty payload strings
- "the existing `process_event` step remains the main step"
- failures return a compact error object with the error message and failing step id
- id: flow-test15-create-current-flow-schedule
prompt: |-
Update this flow by adding a final step named `return_schedule_status`.
It should return an object with `scheduled: true` and the order summary from `results.summarize_orders`.
Also create an enabled daily schedule named `order_processing_daily` for the current flow.
It should run every day at 07:30 UTC with empty args.
Do not ask me for the flow path.
initial: ai_evals/fixtures/frontend/flow/initial/scheduled_order_flow.json
validate:
topLevelStepIds:
- return_schedule_status
toolExpect:
requiredToolsUsed:
- test_run_flow
- create_schedule
toolCallArgs:
- tool: create_schedule
field: path
stringStartsWithAnyOf:
- f/
- u/
stringMustNotStartWithAnyOf:
- schedules/
skipJudge: true
judgeChecklist:
- "the flow includes a final top-level step named `return_schedule_status`"
- "`return_schedule_status` returns `scheduled: true` and the order summary"
- id: flow-test16-create-current-flow-http-trigger
prompt: |-
Update this flow by adding a final step named `webhook_response`.
It should return an object with `ok: true` and the order summary from `results.summarize_orders`.
Also create a public POST HTTP endpoint named `order_processing_webhook` for the current flow.
Use route path `ai-evals/order-processing` and no authentication.
Do not ask me for the flow path.
initial: ai_evals/fixtures/frontend/flow/initial/scheduled_order_flow.json
validate:
topLevelStepIds:
- webhook_response
toolExpect:
requiredToolsUsed:
- test_run_flow
- create_trigger
toolCallArgs:
- tool: create_trigger
field: path
stringStartsWithAnyOf:
- f/
- u/
stringMustNotStartWithAnyOf:
- schedules/
skipJudge: true
judgeChecklist:
- "the flow includes a final top-level step named `webhook_response`"
- "`webhook_response` returns `ok: true` and the order summary"
File diff suppressed because it is too large Load Diff
-53
View File
@@ -5,60 +5,7 @@
Keep it simple and do not add external dependencies.
initial: ai_evals/fixtures/frontend/script/initial/test1_empty_bun.json
expected: ai_evals/fixtures/frontend/script/expected/test1_greet_user.json
toolExpect:
requiredToolsUsed:
- test_run_script
judgeChecklist:
- uses the existing `name` input
- returns a plain greeting string
- does not wrap the result in an object or array
- id: script-test2-create-current-script-schedule
prompt: |-
Update the current Bun script so it takes the existing `name` input and returns a plain greeting string like `Hello, Alice!`.
Also create an enabled daily schedule named `greet_user_daily` for the current script.
It should run every day at 09:00 UTC and pass `{ "name": "Alice" }` as args.
Do not ask me for the script path.
initial: ai_evals/fixtures/frontend/script/initial/test1_empty_bun.json
expected: ai_evals/fixtures/frontend/script/expected/test1_greet_user.json
toolExpect:
requiredToolsUsed:
- test_run_script
- create_schedule
toolCallArgs:
- tool: create_schedule
field: path
stringStartsWithAnyOf:
- f/
- u/
stringMustNotStartWithAnyOf:
- schedules/
skipJudge: true
judgeChecklist:
- uses the existing `name` input
- returns a plain greeting string
- id: script-test3-create-current-script-http-trigger
prompt: |-
Update the current Bun script so it takes the existing `name` input and returns a plain greeting string like `Hello, Alice!`.
Also create a public POST HTTP endpoint named `greet_user_webhook` for the current script.
Use route path `ai-evals/greet-user` and no authentication.
Do not ask me for the script path.
initial: ai_evals/fixtures/frontend/script/initial/test1_empty_bun.json
expected: ai_evals/fixtures/frontend/script/expected/test1_greet_user.json
toolExpect:
requiredToolsUsed:
- test_run_script
- create_trigger
toolCallArgs:
- tool: create_trigger
field: path
stringStartsWithAnyOf:
- f/
- u/
stringMustNotStartWithAnyOf:
- schedules/
skipJudge: true
judgeChecklist:
- uses the existing `name` input
- returns a plain greeting string
+28 -98
View File
@@ -25,19 +25,13 @@ import {
import { runSuite } from "../core/runSuite";
import { EVAL_MODES, type EvalMode } from "../core/types";
import { DEFAULT_JUDGE_MODEL } from "../core/judge";
// createCliModeRunner is imported lazily in runCliBenchmark so the non-cli modes
// (global/flow/script/app) don't pull in the wmill CLI toolchain and its JSR deps
// (e.g. @cliffy/*) just to load this entrypoint.
import { createCliModeRunner } from "../modes/cli";
import { runFrontendBenchmarkAdapter } from "../adapters/frontend/runtime";
import { resolveWindmillBackendSettings } from "../core/windmillBackendSettings";
import { assertWindmillBackendReachable } from "../adapters/frontend/windmillBackend";
async function main() {
const program = new Command()
.name("bun run cli --")
.description(
"Run AI eval cases against the current production prompts and guidance",
)
.description("Run AI eval cases against the current production prompts and guidance")
.showHelpAfterError()
.showSuggestionAfterError()
.addHelpText(
@@ -55,12 +49,11 @@ async function main() {
" bun run cli -- run flow --record",
" bun run cli -- run flow --backend-validation preview",
" bun run cli -- run flow flow-test5-simple-modification --runs 3",
" bun run cli -- run global global-test1-script-create",
" bun run cli -- run cli bun-hello-script",
"",
"Models:",
getEvalModelHelpText(),
].join("\n"),
].join("\n")
);
program
@@ -73,7 +66,7 @@ async function main() {
program
.command("cases")
.description("List available cases")
.argument("[mode]", "cli, flow, script, app, or global", parseOptionalMode)
.argument("[mode]", "cli, flow, script, or app", parseOptionalMode)
.action(async (mode?: EvalMode) => {
await handleCases(mode);
});
@@ -81,36 +74,17 @@ async function main() {
program
.command("run")
.description("Run one benchmark mode")
.argument("<mode>", "cli, flow, script, app, or global", parseMode)
.argument("<mode>", "cli, flow, script, or app", parseMode)
.argument("[caseIds...]", "specific case ids to run")
.option(
"--runs <n>",
"number of attempts per case",
parsePositiveInteger,
1,
)
.option("--runs <n>", "number of attempts per case", parsePositiveInteger, 1)
.option("--output <path>", "write the result JSON to this path")
.option(
"--model <name>",
`model alias (${EVAL_MODELS.map((entry) => entry.id).join(", ")})`,
)
.option(
"--models <names>",
"comma-separated model aliases to run sequentially",
)
.option("--model <name>", `model alias (${EVAL_MODELS.map((entry) => entry.id).join(", ")})`)
.option("--models <names>", "comma-separated model aliases to run sequentially")
.option("--verbose", "stream assistant output during frontend runs")
.option("--skip-judge", "skip LLM judge scoring for this run")
.option(
"--execution-only",
"only require the model/proxy/frontend loop to complete",
)
.option(
"--record",
"append a compact summary line to ai_evals/history/<mode>.jsonl",
)
.option("--record", "append a compact summary line to ai_evals/history/<mode>.jsonl")
.option(
"--backend-validation <mode>",
`backend smoke validation (${BACKEND_VALIDATION_MODES.join(", ")})`,
`backend smoke validation (${BACKEND_VALIDATION_MODES.join(", ")})`
)
.action(
async (
@@ -122,11 +96,9 @@ async function main() {
model?: string;
models?: string;
verbose?: boolean;
skipJudge?: boolean;
executionOnly?: boolean;
record?: boolean;
backendValidation?: string;
},
}
) => {
await handleRun({
mode,
@@ -136,12 +108,10 @@ async function main() {
model: options.model,
models: options.models,
verbose: options.verbose ?? false,
skipJudge: options.skipJudge ?? false,
executionOnly: options.executionOnly ?? false,
record: options.record ?? false,
backendValidation: options.backendValidation,
});
},
}
);
await program.parseAsync(process.argv);
@@ -164,13 +134,10 @@ function handleModels() {
process.stdout.write("Available models\n");
for (const model of EVAL_MODELS) {
const supports = [
...(model.frontend ? ["flow", "script", "app", "global"] : []),
...(model.frontend ? ["flow", "script", "app"] : []),
...(model.cli ? ["cli"] : []),
];
const aliases = [
model.id,
...model.aliases.filter((alias) => alias !== model.id),
];
const aliases = [model.id, ...model.aliases.filter((alias) => alias !== model.id)];
process.stdout.write(`- ${model.id}: ${model.label}\n`);
process.stdout.write(` aliases: ${aliases.join(", ")}\n`);
process.stdout.write(` modes: ${supports.join(", ")}\n`);
@@ -186,15 +153,11 @@ async function handleRun(input: {
model?: string;
models?: string;
verbose: boolean;
skipJudge: boolean;
executionOnly: boolean;
record: boolean;
backendValidation?: string;
}) {
if (input.record && input.caseIds.length > 0) {
throw new Error(
"--record only supports full-suite runs; omit case ids to record history",
);
throw new Error("--record only supports full-suite runs; omit case ids to record history");
}
if (input.model && input.models) {
throw new Error("Use either --model or --models, not both");
@@ -203,57 +166,35 @@ async function handleRun(input: {
const selectedCases = await loadSelectedCases(input.mode, input.caseIds);
const models = resolveRequestedModels(input.mode, input.model, input.models);
const backendValidation = parseBackendValidationMode(
input.backendValidation ?? process.env.WMILL_AI_EVAL_BACKEND_VALIDATION,
input.backendValidation ?? process.env.WMILL_AI_EVAL_BACKEND_VALIDATION
);
if (input.outputPath && models.length > 1) {
throw new Error("--output only supports a single model run");
}
if (
backendValidation !== "off" &&
input.mode !== "flow" &&
input.mode !== "script"
) {
throw new Error(
"--backend-validation currently supports only flow and script modes",
);
}
if (input.mode !== "cli") {
await assertWindmillBackendReachable(resolveWindmillBackendSettings());
if (backendValidation !== "off" && input.mode !== "flow" && input.mode !== "script") {
throw new Error("--backend-validation currently supports only flow and script modes");
}
const summaries: Array<{
label: string;
passRate: number;
averagePassedDurationMs: number | null;
}> = [];
const summaries: Array<{ label: string; passRate: number; averageDurationMs: number }> = [];
for (const [index, model] of models.entries()) {
const runModel = formatRunModelLabel(input.mode, model);
if (models.length > 1) {
process.stdout.write(
`${index > 0 ? "\n" : ""}=== ${input.mode} ${model.id} (${runModel}) ===\n`,
`${index > 0 ? "\n" : ""}=== ${input.mode} ${model.id} (${runModel}) ===\n`
);
}
process.stderr.write(`Starting ${input.mode} benchmark...\n`);
const result =
input.mode === "cli"
? await runCliBenchmark(
selectedCases,
input.runs,
getCliEvalModel(model),
runModel,
input.skipJudge,
input.executionOnly,
)
? await runCliBenchmark(selectedCases, input.runs, getCliEvalModel(model), runModel)
: await runFrontendBenchmarkAdapter({
mode: input.mode,
caseIds: input.caseIds,
runs: input.runs,
model: model.id,
verbose: input.verbose,
skipJudge: input.skipJudge,
executionOnly: input.executionOnly,
backendValidation,
});
@@ -276,7 +217,7 @@ async function handleRun(input: {
summaries.push({
label: `${model.id} (${runModel})`,
passRate: result.passRate,
averagePassedDurationMs: result.averagePassedDurationMs ?? null,
averageDurationMs: result.averageDurationMs,
});
}
@@ -284,7 +225,7 @@ async function handleRun(input: {
process.stdout.write("\nModel summary\n");
for (const summary of summaries) {
process.stdout.write(
`- ${summary.label}: ${formatPercent(summary.passRate)} | passed avg ${formatNullableDuration(summary.averagePassedDurationMs)}\n`,
`- ${summary.label}: ${formatPercent(summary.passRate)} | ${Math.round(summary.averageDurationMs)}ms\n`
);
}
}
@@ -294,26 +235,21 @@ async function runCliBenchmark(
cases: Awaited<ReturnType<typeof loadSelectedCases>>,
runs: number,
model: ReturnType<typeof getCliEvalModel>,
runModel: string,
skipJudge: boolean,
executionOnly: boolean,
runModel: string
) {
const { createCliModeRunner } = await import("../modes/cli");
const judgeModel = skipJudge || executionOnly ? null : DEFAULT_JUDGE_MODEL;
const caseResults = await runSuite({
modeRunner: createCliModeRunner(model),
cases,
runs,
runModel,
judgeModel,
executionOnly,
judgeModel: DEFAULT_JUDGE_MODEL,
});
return buildRunResult({
mode: "cli",
runs,
runModel,
judgeModel,
judgeModel: DEFAULT_JUDGE_MODEL,
caseResults,
});
}
@@ -322,9 +258,7 @@ function parseMode(value: string): EvalMode {
if (EVAL_MODES.includes(value as EvalMode)) {
return value as EvalMode;
}
throw new InvalidArgumentError(
`mode must be one of: ${EVAL_MODES.join(", ")}`,
);
throw new InvalidArgumentError(`mode must be one of: ${EVAL_MODES.join(", ")}`);
}
function parseOptionalMode(value: string | undefined): EvalMode | undefined {
@@ -342,7 +276,7 @@ function parsePositiveInteger(value: string): number {
function resolveRequestedModels(
mode: EvalMode,
singleModel?: string,
multipleModels?: string,
multipleModels?: string
): EvalModelSpec[] {
if (!multipleModels) {
return [resolveEvalModel(mode, singleModel)];
@@ -373,10 +307,6 @@ function formatPercent(value: number): string {
return `${(value * 100).toFixed(1)}%`;
}
function formatNullableDuration(value: number | null): string {
return value === null ? "n/a" : `${Math.round(value)}ms`;
}
void main().catch((error) => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`${message}\n`);
-20
View File
@@ -1,20 +0,0 @@
import { describe, expect, it } from "bun:test";
import { buildAppArtifacts } from "./appArtifacts";
describe("buildAppArtifacts", () => {
it("emits lint diagnostics as an artifact alongside app files", () => {
const artifacts = buildAppArtifacts({
frontend: {
"/index.tsx":
"import { backend } from 'wmill'\nexport default function App() { void backend.deleteRecipe({ id: 1 }); return <div /> }\n",
},
backend: {},
datatables: [],
});
const lintArtifact = artifacts.find((artifact) => artifact.path === "lint.json");
expect(lintArtifact).toBeDefined();
expect(lintArtifact?.content).toContain('"errorCount": 1');
expect(lintArtifact?.content).toContain("deleteRecipe");
});
});
-52
View File
@@ -1,52 +0,0 @@
import { collectAppDiagnostics } from "./appDiagnostics";
import type { BenchmarkArtifactFile } from "./types";
import type { AppFilesState } from "./validators";
export function buildAppArtifacts(actual: AppFilesState): BenchmarkArtifactFile[] {
const diagnostics = collectAppDiagnostics({
frontend: actual.frontend,
backend: actual.backend,
});
const artifacts: BenchmarkArtifactFile[] = [
{
path: "app.json",
content: JSON.stringify(actual, null, 2) + "\n",
},
{
path: "lint.json",
content: JSON.stringify(diagnostics, null, 2) + "\n",
},
];
for (const [filePath, content] of Object.entries(actual.frontend)) {
artifacts.push({
path: `frontend${filePath.startsWith("/") ? filePath : `/${filePath}`}`,
content,
});
}
for (const [key, runnable] of Object.entries(actual.backend)) {
artifacts.push({
path: `backend/${key}/meta.json`,
content: JSON.stringify(runnable, null, 2) + "\n",
});
const inlineContent = runnable.inlineScript?.content;
if (inlineContent) {
const extension = runnable.inlineScript?.language === "python3" ? "py" : "ts";
artifacts.push({
path: `backend/${key}/main.${extension}`,
content: inlineContent,
});
}
}
if (actual.datatables.length > 0) {
artifacts.push({
path: "datatables.json",
content: JSON.stringify(actual.datatables, null, 2) + "\n",
});
}
return artifacts;
}
-96
View File
@@ -1,96 +0,0 @@
import { describe, expect, it } from "bun:test";
import { fileURLToPath } from "node:url";
import { loadAppFixture } from "../adapters/frontend/core/app/appFixtureLoader";
import { buildAppWmillTypes, collectAppDiagnostics } from "./appDiagnostics";
const FILE_MANAGER_FIXTURE = fileURLToPath(
new URL("../fixtures/frontend/app/initial/file_manager", import.meta.url)
);
describe("collectAppDiagnostics", () => {
it("accepts seeded multi-file apps without static analysis errors", async () => {
const fixture = await loadAppFixture(FILE_MANAGER_FIXTURE);
const diagnostics = collectAppDiagnostics({
frontend: fixture.frontend,
backend: fixture.backend,
});
expect(diagnostics.lintResult.errorCount).toBe(0);
});
it("reports missing backend references through the generated wmill typings", () => {
const diagnostics = collectAppDiagnostics({
frontend: {
"/index.tsx":
"import { backend } from 'wmill'\nexport default function App() { void backend.deleteRecipe({ id: 1 }); return <div /> }\n",
},
backend: {
listRecipes: {
name: "List recipes",
type: "inline",
inlineScript: {
language: "bun",
content: "export async function main() { return [] }\n",
},
},
},
});
expect(diagnostics.lintResult.errorCount).toBeGreaterThan(0);
expect(diagnostics.lintResult.errors.frontend["/index.tsx"]?.join("\n")).toContain(
"Property 'deleteRecipe' does not exist"
);
});
it("reports backend argument shape mismatches when the inline main signature is portable", () => {
const diagnostics = collectAppDiagnostics({
frontend: {
"/index.tsx":
"import { backend } from 'wmill'\nexport default function App() { void backend.addRecipe({ name: 'Soup' }); return <div /> }\n",
},
backend: {
addRecipe: {
name: "Add recipe",
type: "inline",
inlineScript: {
language: "bun",
content:
"export async function main({ name, ingredients }: { name: string; ingredients: string }) { return { name, ingredients } }\n",
},
},
},
});
expect(diagnostics.lintResult.errorCount).toBeGreaterThan(0);
expect(diagnostics.lintResult.errors.frontend["/index.tsx"]?.join("\n")).toContain(
"Property 'ingredients' is missing"
);
});
});
describe("buildAppWmillTypes", () => {
it("generates callable signatures for zero-arg and typed runnables", () => {
const wmillTypes = buildAppWmillTypes({
listRecipes: {
name: "List recipes",
type: "inline",
inlineScript: {
language: "bun",
content: "export async function main() { return [] }\n",
},
},
addRecipe: {
name: "Add recipe",
type: "inline",
inlineScript: {
language: "bun",
content:
"export async function main({ name }: { name: string }) { return { name } }\n",
},
},
});
expect(wmillTypes).toContain('"listRecipes": () => Promise<any>;');
expect(wmillTypes).toContain('"addRecipe": (args: { name: string }) => Promise<any>;');
});
});
-758
View File
@@ -1,758 +0,0 @@
import path from "node:path";
import ts from "typescript";
import type { LintResult } from "../../frontend/src/lib/components/copilot/chat/app/core";
const FRONTEND_ROOT = "/__ai_evals__/frontend";
const BACKEND_ROOT = "/__ai_evals__/backend";
const FRONTEND_REACT_SHIM_PATH = `${FRONTEND_ROOT}/__react_shim__.d.ts`;
const FRONTEND_WMILL_TYPES_PATH = `${FRONTEND_ROOT}/wmill.d.ts`;
const BACKEND_WINDMILL_CLIENT_SHIM_PATH = `${BACKEND_ROOT}/__windmill_client__.d.ts`;
const TS_LIKE_LANGUAGES = new Set([
"bun",
"deno",
"nativets",
"bunnative",
"ts",
"typescript",
]);
const JS_LIKE_LANGUAGES = new Set(["javascript", "js", "nodejs"]);
const SAFE_TYPE_REFERENCE_NAMES = new Set([
"Array",
"Date",
"Exclude",
"Extract",
"NonNullable",
"Omit",
"Partial",
"Pick",
"Promise",
"Readonly",
"ReadonlyArray",
"Record",
"Required",
"ReturnType",
"Uppercase",
"Lowercase",
"Capitalize",
"Uncapitalize",
]);
const FRONTEND_REACT_SHIM = `declare namespace React {
type SetStateAction<S> = S | ((prevState: S) => S);
type Dispatch<A> = (value: A) => void;
type FC<P = {}> = (props: P) => any;
type ReactNode = any;
interface FormEvent<T = EventTarget> {
preventDefault(): void;
target: T;
currentTarget: T;
}
interface ChangeEvent<T = EventTarget> {
target: T;
currentTarget: T;
}
}
declare namespace JSX {
interface IntrinsicAttributes {
key?: any;
}
interface IntrinsicElements {
[elementName: string]: any;
}
}
declare module "react" {
export type SetStateAction<S> = React.SetStateAction<S>;
export type Dispatch<A> = React.Dispatch<A>;
export type FC<P = {}> = React.FC<P>;
export type ReactNode = React.ReactNode;
export type FormEvent<T = EventTarget> = React.FormEvent<T>;
export type ChangeEvent<T = EventTarget> = React.ChangeEvent<T>;
export function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
export function useEffect(effect: () => void | (() => void), deps?: readonly unknown[]): void;
const React: any;
export default React;
}
`;
const BACKEND_WINDMILL_CLIENT_SHIM = `declare const console: {
log: (...args: any[]) => void;
error: (...args: any[]) => void;
warn: (...args: any[]) => void;
};
declare module "windmill-client" {
interface SqlQueryResult {
fetch(): Promise<any>;
fetchOne(): Promise<any>;
}
interface SqlTemplateFunction {
(strings: TemplateStringsArray, ...values: any[]): SqlQueryResult;
}
interface WindmillClient {
datatable(name?: string): SqlTemplateFunction;
ducklake(name?: string): SqlTemplateFunction;
[key: string]: any;
}
const wmill: WindmillClient;
export = wmill;
}
`;
export interface AppDiagnosticRunnable {
name?: string;
type?: string;
path?: string;
inlineScript?: {
language?: string;
content?: string;
};
}
export interface AppStaticDiagnostic {
source: "frontend" | "backend";
target: string;
message: string;
line?: number;
column?: number;
code?: number;
}
export interface AppDiagnosticsResult {
lintResult: LintResult;
diagnostics: AppStaticDiagnostic[];
}
export function buildAppWmillTypes(
backend: Record<string, AppDiagnosticRunnable> = {},
): string {
return `// THIS FILE IS READ-ONLY
// AND GENERATED AUTOMATICALLY FROM YOUR RUNNABLES
export declare const backend: {
${Object.entries(backend)
.map(
([key, runnable]) =>
` ${JSON.stringify(key)}: ${getRunnableSignature(runnable, false)};`,
)
.join("\n")}
};
export declare const backendAsync: {
${Object.entries(backend)
.map(
([key, runnable]) =>
` ${JSON.stringify(key)}: ${getRunnableSignature(runnable, true)};`,
)
.join("\n")}
};
export type Job = {
type: "QueuedJob" | "CompletedJob";
id: string;
created_at: number;
started_at: number | undefined;
duration_ms: number;
success: boolean;
args: any;
result: any;
};
export declare function waitJob(id: string): Promise<Job>;
export declare function getJob(id: string): Promise<Job>;
export type StreamUpdate = {
new_result_stream?: string;
stream_offset?: number;
};
export declare function streamJob(id: string, onUpdate?: (data: StreamUpdate) => void): Promise<any>;
`;
}
export function collectAppDiagnostics(input: {
frontend: Record<string, string>;
backend: Record<string, AppDiagnosticRunnable>;
}): AppDiagnosticsResult {
const frontendDiagnostics = collectFrontendDiagnostics(
input.frontend,
input.backend,
);
const backendDiagnostics = collectBackendDiagnostics(input.backend);
const diagnostics = dedupeDiagnostics([
...frontendDiagnostics,
...backendDiagnostics,
]).sort(compareDiagnostics);
return {
diagnostics,
lintResult: {
errors: {
frontend: groupMessages(
diagnostics.filter((diagnostic) => diagnostic.source === "frontend"),
),
backend: groupMessages(
diagnostics.filter((diagnostic) => diagnostic.source === "backend"),
),
},
warnings: {
frontend: {},
backend: {},
},
errorCount: diagnostics.length,
warningCount: 0,
},
};
}
function collectFrontendDiagnostics(
frontend: Record<string, string>,
backend: Record<string, AppDiagnosticRunnable>,
): AppStaticDiagnostic[] {
const frontendFiles = Object.entries(frontend)
.filter(([filePath]) => isFrontendCodeFile(filePath))
.map(
([filePath, content]) =>
[toFrontendVirtualPath(filePath), content] as const,
);
const virtualFiles = new Map<string, string>([
[FRONTEND_REACT_SHIM_PATH, FRONTEND_REACT_SHIM],
[
FRONTEND_WMILL_TYPES_PATH,
wrapModuleDeclaration("wmill", buildAppWmillTypes(backend)),
],
...frontendFiles,
]);
const host = createVirtualCompilerHost(
virtualFiles,
getFrontendCompilerOptions(),
);
const rootNames = [...virtualFiles.keys()];
const program = ts.createProgram({
rootNames,
options: getFrontendCompilerOptions(),
host,
});
return ts.getPreEmitDiagnostics(program).flatMap((diagnostic) =>
mapTypeScriptDiagnostic({
diagnostic,
source: "frontend",
toTarget(fileName) {
const normalized = normalizeFileName(fileName);
if (normalized === FRONTEND_WMILL_TYPES_PATH) {
return "/wmill.d.ts";
}
if (!normalized.startsWith(`${FRONTEND_ROOT}/`)) {
return null;
}
if (normalized === FRONTEND_REACT_SHIM_PATH) {
return null;
}
return normalized.slice(FRONTEND_ROOT.length);
},
}),
);
}
function collectBackendDiagnostics(
backend: Record<string, AppDiagnosticRunnable>,
): AppStaticDiagnostic[] {
const backendFiles = Object.entries(backend)
.filter(([, runnable]) => isTypeCheckableBackendRunnable(runnable))
.map(
([key, runnable]) =>
[
`${BACKEND_ROOT}/${key}/main.${getBackendFileExtension(runnable.inlineScript?.language)}`,
runnable.inlineScript?.content ?? "",
] as const,
);
if (backendFiles.length === 0) {
return [];
}
const virtualFiles = new Map<string, string>([
[BACKEND_WINDMILL_CLIENT_SHIM_PATH, BACKEND_WINDMILL_CLIENT_SHIM],
...backendFiles,
]);
const host = createVirtualCompilerHost(
virtualFiles,
getBackendCompilerOptions(),
);
const rootNames = [...virtualFiles.keys()];
const program = ts.createProgram({
rootNames,
options: getBackendCompilerOptions(),
host,
});
return ts.getPreEmitDiagnostics(program).flatMap((diagnostic) =>
mapTypeScriptDiagnostic({
diagnostic,
source: "backend",
toTarget(fileName) {
const normalized = normalizeFileName(fileName);
if (normalized === BACKEND_WINDMILL_CLIENT_SHIM_PATH) {
return null;
}
if (!normalized.startsWith(`${BACKEND_ROOT}/`)) {
return null;
}
const relativePath = normalized.slice(BACKEND_ROOT.length + 1);
const runnableKey = relativePath.split("/")[0];
return runnableKey || null;
},
}),
);
}
function getFrontendCompilerOptions(): ts.CompilerOptions {
return {
allowJs: true,
checkJs: true,
esModuleInterop: true,
allowSyntheticDefaultImports: true,
jsx: ts.JsxEmit.Preserve,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Node10,
noEmit: true,
noImplicitAny: false,
skipLibCheck: true,
strict: false,
target: ts.ScriptTarget.ES2022,
lib: ["lib.es2022.d.ts", "lib.dom.d.ts"],
};
}
function getBackendCompilerOptions(): ts.CompilerOptions {
return {
allowJs: true,
checkJs: true,
esModuleInterop: true,
allowSyntheticDefaultImports: true,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Node10,
noEmit: true,
noImplicitAny: false,
skipLibCheck: true,
strict: false,
target: ts.ScriptTarget.ES2022,
lib: ["lib.es2022.d.ts"],
};
}
function createVirtualCompilerHost(
files: Map<string, string>,
options: ts.CompilerOptions,
): ts.CompilerHost {
const originalHost = ts.createCompilerHost(options, true);
const originalGetSourceFile = originalHost.getSourceFile.bind(originalHost);
const originalReadFile = originalHost.readFile.bind(originalHost);
const originalFileExists = originalHost.fileExists.bind(originalHost);
const originalDirectoryExists =
originalHost.directoryExists?.bind(originalHost);
const originalGetDirectories =
originalHost.getDirectories?.bind(originalHost);
return {
...originalHost,
getCurrentDirectory: () => "/",
getSourceFile(
fileName,
languageVersion,
onError,
shouldCreateNewSourceFile,
) {
const normalized = normalizeFileName(fileName);
const content = files.get(normalized);
if (content !== undefined) {
return ts.createSourceFile(fileName, content, languageVersion, true);
}
return originalGetSourceFile(
fileName,
languageVersion,
onError,
shouldCreateNewSourceFile,
);
},
readFile(fileName) {
const normalized = normalizeFileName(fileName);
return files.get(normalized) ?? originalReadFile(fileName);
},
fileExists(fileName) {
const normalized = normalizeFileName(fileName);
return files.has(normalized) || originalFileExists(fileName);
},
directoryExists(dirName) {
const normalized = normalizeFileName(dirName);
return (
hasVirtualDirectory(files, normalized) ||
originalDirectoryExists?.(dirName) ||
false
);
},
getDirectories(dirName) {
const normalized = normalizeFileName(dirName);
const virtualDirectories = listVirtualDirectories(files, normalized);
const diskDirectories = originalGetDirectories?.(dirName) ?? [];
return [...new Set([...diskDirectories, ...virtualDirectories])];
},
realpath(fileName) {
return normalizeFileName(fileName);
},
writeFile() {},
};
}
function mapTypeScriptDiagnostic(input: {
diagnostic: ts.Diagnostic;
source: "frontend" | "backend";
toTarget: (fileName: string) => string | null;
}): AppStaticDiagnostic[] {
const { diagnostic, source, toTarget } = input;
if (!diagnostic.file) {
return [];
}
const target = toTarget(diagnostic.file.fileName);
if (!target) {
return [];
}
const position =
diagnostic.start === undefined
? undefined
: diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
return [
{
source,
target,
message: ts
.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
.trim(),
line: position ? position.line + 1 : undefined,
column: position ? position.character + 1 : undefined,
code: diagnostic.code,
},
];
}
function groupMessages(
diagnostics: AppStaticDiagnostic[],
): Record<string, string[]> {
const grouped: Record<string, string[]> = {};
for (const diagnostic of diagnostics) {
grouped[diagnostic.target] ??= [];
grouped[diagnostic.target].push(formatLintMessage(diagnostic));
}
return grouped;
}
function formatLintMessage(diagnostic: AppStaticDiagnostic): string {
if (diagnostic.line !== undefined) {
return `Line ${diagnostic.line}: ${diagnostic.message}`;
}
return diagnostic.message;
}
function dedupeDiagnostics(
diagnostics: AppStaticDiagnostic[],
): AppStaticDiagnostic[] {
const uniqueDiagnostics = new Map<string, AppStaticDiagnostic>();
for (const diagnostic of diagnostics) {
const key = [
diagnostic.source,
diagnostic.target,
diagnostic.code ?? "",
diagnostic.line ?? "",
diagnostic.column ?? "",
diagnostic.message,
].join("::");
if (!uniqueDiagnostics.has(key)) {
uniqueDiagnostics.set(key, diagnostic);
}
}
return [...uniqueDiagnostics.values()];
}
function compareDiagnostics(
a: AppStaticDiagnostic,
b: AppStaticDiagnostic,
): number {
if (a.source !== b.source) {
return a.source.localeCompare(b.source);
}
if (a.target !== b.target) {
return a.target.localeCompare(b.target);
}
if ((a.line ?? 0) !== (b.line ?? 0)) {
return (a.line ?? 0) - (b.line ?? 0);
}
if ((a.column ?? 0) !== (b.column ?? 0)) {
return (a.column ?? 0) - (b.column ?? 0);
}
return a.message.localeCompare(b.message);
}
function toFrontendVirtualPath(filePath: string): string {
const normalizedPath = normalizeAppFilePath(filePath);
return `${FRONTEND_ROOT}${normalizedPath}`;
}
function normalizeAppFilePath(filePath: string): string {
const normalizedPath = normalizeFileName(filePath);
return normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
}
function normalizeFileName(fileName: string): string {
return path.posix.normalize(fileName.replace(/\\/g, "/"));
}
function hasVirtualDirectory(
files: Map<string, string>,
dirName: string,
): boolean {
const normalizedDirectory = dirName.endsWith("/") ? dirName : `${dirName}/`;
for (const fileName of files.keys()) {
if (fileName === dirName || fileName.startsWith(normalizedDirectory)) {
return true;
}
}
return false;
}
function listVirtualDirectories(
files: Map<string, string>,
dirName: string,
): string[] {
const normalizedDirectory = dirName.endsWith("/") ? dirName : `${dirName}/`;
const directories = new Set<string>();
for (const fileName of files.keys()) {
if (!fileName.startsWith(normalizedDirectory)) {
continue;
}
const relativePath = fileName.slice(normalizedDirectory.length);
const [segment] = relativePath.split("/");
if (segment && relativePath.includes("/")) {
directories.add(path.posix.join(dirName, segment));
}
}
return [...directories];
}
function wrapModuleDeclaration(moduleName: string, content: string): string {
const indentedContent = content
.trim()
.split("\n")
.map((line) => ` ${line}`)
.join("\n");
return `declare module "${moduleName}" {\n${indentedContent}\n}\n`;
}
function getRunnableSignature(
runnable: AppDiagnosticRunnable | undefined,
asyncMode: boolean,
): string {
const returnType = asyncMode ? "Promise<string>" : "Promise<any>";
const parameter = getRunnableParameterSignature(runnable);
return `${parameter} => ${returnType}`;
}
function getRunnableParameterSignature(
runnable: AppDiagnosticRunnable | undefined,
): string {
const parameterInfo = getRunnableParameterInfo(runnable);
if (!parameterInfo) {
return "()";
}
const parameterType = parameterInfo.typeText ?? "any";
if (parameterInfo.optional) {
return `(args?: ${parameterType})`;
}
return `(args: ${parameterType})`;
}
function getRunnableParameterInfo(
runnable: AppDiagnosticRunnable | undefined,
): { typeText?: string; optional: boolean } | null {
if (
!runnable?.inlineScript?.content ||
!isTypeCheckableBackendRunnable(runnable)
) {
return { typeText: "any", optional: true };
}
const sourceFile = ts.createSourceFile(
"main.ts",
runnable.inlineScript.content,
ts.ScriptTarget.Latest,
true,
getScriptKindForLanguage(runnable.inlineScript.language),
);
const mainDeclaration = findExportedMainDeclaration(sourceFile);
if (!mainDeclaration || mainDeclaration.parameters.length === 0) {
return null;
}
const [parameter] = mainDeclaration.parameters;
const optional =
Boolean(parameter.questionToken) || Boolean(parameter.initializer);
if (!parameter.type || !isPortableTypeNode(parameter.type)) {
return { typeText: "any", optional: true };
}
return {
typeText: parameter.type.getText(sourceFile).trim(),
optional,
};
}
function findExportedMainDeclaration(
sourceFile: ts.SourceFile,
): ts.SignatureDeclarationBase | null {
for (const statement of sourceFile.statements) {
if (
ts.isFunctionDeclaration(statement) &&
statement.name?.text === "main" &&
hasExportModifier(statement)
) {
return statement;
}
if (!ts.isVariableStatement(statement) || !hasExportModifier(statement)) {
continue;
}
for (const declaration of statement.declarationList.declarations) {
if (
!ts.isIdentifier(declaration.name) ||
declaration.name.text !== "main"
) {
continue;
}
const initializer = declaration.initializer;
if (
initializer &&
(ts.isArrowFunction(initializer) ||
ts.isFunctionExpression(initializer))
) {
return initializer;
}
}
}
return null;
}
function hasExportModifier(node: ts.Node): boolean {
const modifiers = ts.canHaveModifiers(node)
? ts.getModifiers(node)
: undefined;
return Boolean(
modifiers?.some(
(modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword,
),
);
}
function isPortableTypeNode(node: ts.TypeNode): boolean {
if (
isKeywordTypeNode(node) ||
ts.isArrayTypeNode(node) ||
ts.isTupleTypeNode(node) ||
ts.isLiteralTypeNode(node) ||
ts.isTypeLiteralNode(node)
) {
return true;
}
if (ts.isParenthesizedTypeNode(node) || ts.isTypeOperatorNode(node)) {
return isPortableTypeNode(node.type);
}
if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) {
return node.types.every((typeNode) => isPortableTypeNode(typeNode));
}
if (ts.isTypeReferenceNode(node)) {
if (
!ts.isIdentifier(node.typeName) ||
!SAFE_TYPE_REFERENCE_NAMES.has(node.typeName.text)
) {
return false;
}
return (node.typeArguments ?? []).every((typeArgument) =>
isPortableTypeNode(typeArgument),
);
}
return false;
}
function isKeywordTypeNode(node: ts.TypeNode): boolean {
switch (node.kind) {
case ts.SyntaxKind.AnyKeyword:
case ts.SyntaxKind.BigIntKeyword:
case ts.SyntaxKind.BooleanKeyword:
case ts.SyntaxKind.NeverKeyword:
case ts.SyntaxKind.NumberKeyword:
case ts.SyntaxKind.ObjectKeyword:
case ts.SyntaxKind.StringKeyword:
case ts.SyntaxKind.SymbolKeyword:
case ts.SyntaxKind.UndefinedKeyword:
case ts.SyntaxKind.UnknownKeyword:
case ts.SyntaxKind.VoidKeyword:
return true;
default:
return false;
}
}
function isFrontendCodeFile(filePath: string): boolean {
const extension = path.posix.extname(filePath).toLowerCase();
return (
extension === ".js" ||
extension === ".jsx" ||
extension === ".ts" ||
extension === ".tsx"
);
}
function isTypeCheckableBackendRunnable(
runnable: AppDiagnosticRunnable | undefined,
): boolean {
if (!runnable || runnable.type !== "inline") {
return false;
}
const language = runnable.inlineScript?.language?.toLowerCase() ?? "";
return TS_LIKE_LANGUAGES.has(language) || JS_LIKE_LANGUAGES.has(language);
}
function getBackendFileExtension(language: string | undefined): string {
const normalizedLanguage = language?.toLowerCase() ?? "";
return JS_LIKE_LANGUAGES.has(normalizedLanguage) ? "js" : "ts";
}
function getScriptKindForLanguage(language: string | undefined): ts.ScriptKind {
const normalizedLanguage = language?.toLowerCase() ?? "";
return JS_LIKE_LANGUAGES.has(normalizedLanguage)
? ts.ScriptKind.JS
: ts.ScriptKind.TS;
}
+57 -27
View File
@@ -1,8 +1,4 @@
import type { EvalMode } from "./types";
import {
parsePositiveInteger,
resolveWindmillBackendSettings,
} from "./windmillBackendSettings";
export const BACKEND_VALIDATION_MODES = ["off", "preview"] as const;
@@ -13,22 +9,17 @@ export interface BackendValidationSettings {
baseUrl: string;
email: string;
password: string;
keepWorkspaces: boolean;
workspaceOverride?: string;
workspacePrefix: string;
pollIntervalMs: number;
maxWaitMs: number;
}
export function parseBackendValidationMode(
value?: string | null,
): BackendValidationMode {
export function parseBackendValidationMode(value?: string | null): BackendValidationMode {
const normalized = value?.trim().toLowerCase();
if (
!normalized ||
normalized === "off" ||
normalized === "false" ||
normalized === "0"
) {
if (!normalized || normalized === "off" || normalized === "false" || normalized === "0") {
return "off";
}
@@ -37,7 +28,7 @@ export function parseBackendValidationMode(
}
throw new Error(
`Unsupported backend validation mode: ${value}. Use one of: ${BACKEND_VALIDATION_MODES.join(", ")}`,
`Unsupported backend validation mode: ${value}. Use one of: ${BACKEND_VALIDATION_MODES.join(", ")}`
);
}
@@ -46,29 +37,68 @@ export function resolveBackendValidationSettings(input: {
requestedMode?: string | null;
}): BackendValidationSettings {
const mode = parseBackendValidationMode(
input.requestedMode ?? process.env.WMILL_AI_EVAL_BACKEND_VALIDATION,
input.requestedMode ?? process.env.WMILL_AI_EVAL_BACKEND_VALIDATION
);
if (
mode !== "off" &&
input.evalMode !== "flow" &&
input.evalMode !== "script"
) {
if (mode !== "off" && input.evalMode !== "flow" && input.evalMode !== "script") {
throw new Error(
`Backend validation mode "${mode}" is only supported for flow and script evals`,
`Backend validation mode "${mode}" is only supported for flow and script evals`
);
}
return {
mode,
...resolveWindmillBackendSettings(),
baseUrl: normalizeBaseUrl(
process.env.WMILL_AI_EVAL_BACKEND_URL ??
process.env.WINDMILL_URL ??
process.env.WINDMILL_BASE_URL ??
process.env.REMOTE ??
"http://127.0.0.1:8000"
),
email: process.env.WMILL_AI_EVAL_BACKEND_EMAIL ?? "admin@windmill.dev",
password: process.env.WMILL_AI_EVAL_BACKEND_PASSWORD ?? "changeme",
keepWorkspaces: isTruthy(process.env.WMILL_AI_EVAL_KEEP_WORKSPACES),
workspaceOverride: sanitizeOptionalWorkspaceId(process.env.WMILL_AI_EVAL_BACKEND_WORKSPACE),
workspacePrefix: sanitizeWorkspacePrefix(
process.env.WMILL_AI_EVAL_WORKSPACE_PREFIX ?? "ai-evals"
),
pollIntervalMs: parsePositiveInteger(
process.env.WMILL_AI_EVAL_BACKEND_POLL_INTERVAL_MS,
2000,
),
maxWaitMs: parsePositiveInteger(
process.env.WMILL_AI_EVAL_BACKEND_MAX_WAIT_MS,
120000,
2000
),
maxWaitMs: parsePositiveInteger(process.env.WMILL_AI_EVAL_BACKEND_MAX_WAIT_MS, 120000),
};
}
function normalizeBaseUrl(value: string): string {
return value.replace(/\/+$/, "");
}
function sanitizeWorkspacePrefix(value: string): string {
const sanitized = value
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "");
return sanitized.length > 0 ? sanitized : "ai-evals";
}
function sanitizeOptionalWorkspaceId(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}
function isTruthy(value: string | undefined): boolean {
if (!value) {
return false;
}
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
function parsePositiveInteger(value: string | undefined, fallback: number): number {
if (!value) {
return fallback;
}
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}
-265
View File
@@ -14,270 +14,5 @@ describe("loadCases", () => {
},
},
});
expect(caseEntry?.toolExpect).toEqual({
requiredToolsUsed: ["test_run_flow"],
});
});
it("loads script and flow test tool expectations", async () => {
const scriptCases = await loadCases("script");
const flowCases = await loadCases("flow");
expect(scriptCases.find((entry) => entry.id === "script-test1-greet-user")?.toolExpect).toEqual({
requiredToolsUsed: ["test_run_script"],
});
expect(flowCases.find((entry) => entry.id === "flow-test0-sum-two-numbers")?.toolExpect).toEqual({
requiredToolsUsed: ["test_run_flow"],
});
});
it("loads the workspace-flow preference benchmark case", async () => {
const flowCases = await loadCases("flow");
const caseEntry = flowCases.find(
(entry) => entry.id === "flow-test13-prefer-existing-workspace-flow"
);
expect(caseEntry).toBeDefined();
expect(caseEntry?.runtime).toEqual({
backendPreview: {
args: {
a: 10,
b: 5,
},
},
});
expect(caseEntry?.initialPath).toContain(
"ai_evals/fixtures/frontend/flow/initial/test13_prefer_existing_workspace_flow_initial.json"
);
expect(caseEntry?.expectedPath).toContain(
"ai_evals/fixtures/frontend/flow/expected/test13_prefer_existing_workspace_flow.json"
);
});
it("loads app validation config for datatable-backed persistence cases", async () => {
const appCases = await loadCases("app");
const caseEntry = appCases.find(
(entry) => entry.id === "app-test8-inventory-tracker-search-delete"
);
expect(caseEntry?.initialPath).toContain("ai_evals/fixtures/frontend/app/initial/inventory_tracker");
expect(caseEntry?.validate).toEqual({
requiredFrontendPaths: ["/index.tsx"],
requiredBackendRunnableKeys: ["listInventory", "addInventory", "deleteInventory"],
requiredBackendRunnableTypes: [
{ key: "listInventory", type: "inline" },
{ key: "addInventory", type: "inline" },
{ key: "deleteInventory", type: "inline" },
],
requiredDatatables: [
{
datatableName: "main",
schema: "public",
table: "inventory_items",
},
],
});
});
it("loads the seeded recipe-book app modification case", async () => {
const appCases = await loadCases("app");
const caseEntry = appCases.find((entry) => entry.id === "app-test9-recipe-book-search-delete");
expect(caseEntry?.initialPath).toContain("ai_evals/fixtures/frontend/app/initial/recipe_book");
expect(caseEntry?.validate).toEqual({
requiredFrontendPaths: ["/index.tsx"],
requiredBackendRunnableKeys: ["listRecipes", "addRecipe", "deleteRecipe"],
requiredBackendRunnableTypes: [
{ key: "listRecipes", type: "inline" },
{ key: "addRecipe", type: "inline" },
{ key: "deleteRecipe", type: "inline" },
],
requiredDatatables: [
{
datatableName: "main",
schema: "public",
table: "recipes",
},
],
});
});
it("loads the file-manager rename save/cancel case", async () => {
const appCases = await loadCases("app");
const caseEntry = appCases.find(
(entry) => entry.id === "app-test6-file-manager-rename-save-cancel"
);
expect(caseEntry?.initialPath).toContain("ai_evals/fixtures/frontend/app/initial/file_manager");
expect(caseEntry?.validate).toMatchObject({
requiredFrontendPaths: ["/index.tsx", "/components/FileItem.tsx"],
requiredFrontendFileContent: [
{
path: "/components/FileItem.tsx",
includes: ["Save", "Cancel", "Escape"],
},
],
forbiddenAppContent: ["onBlur={handleRename}"],
});
});
it("loads the datatable-backed notes creation case", async () => {
const appCases = await loadCases("app");
const caseEntry = appCases.find((entry) => entry.id === "app-datatable-persistent-notes");
expect(caseEntry?.initialPath).toContain("ai_evals/fixtures/frontend/app/initial/notes_datatable");
expect(caseEntry?.runtime).toEqual({
maxTurns: 10,
});
expect(caseEntry?.validate).toMatchObject({
requiredFrontendPaths: ["/index.tsx"],
requiredBackendRunnableKeys: ["listNotes", "addNote", "deleteNote"],
datatableTableCountExactly: 1,
requiredDatatables: [
{
datatableName: "main",
schema: "public",
table: "notes",
},
],
requiredToolsUsed: ["list_datatables", "get_datatable_table_schema"],
forbiddenAppContent: ["localStorage", "sessionStorage", "indexedDB"],
});
});
it("loads the session id micro-edit app case", async () => {
const appCases = await loadCases("app");
const caseEntry = appCases.find((entry) => entry.id === "app-test10-session-id-no-crypto");
expect(caseEntry?.initialPath).toContain("ai_evals/fixtures/frontend/app/initial/session_id_chat");
expect(caseEntry?.runtime).toEqual({
maxTurns: 4,
});
expect(caseEntry?.validate).toEqual({
requiredFrontendPaths: ["/index.tsx"],
requiredBackendRunnableKeys: ["a"],
requiredBackendRunnableTypes: [{ key: "a", type: "inline" }],
});
});
it("loads app token usage cases with additional runtime context", async () => {
const appCases = await loadCases("app");
const datatableContextCase = appCases.find(
(entry) => entry.id === "app-token-many-datatable-context"
);
expect(
appCases.find((entry) => entry.id === "app-token-selected-large-frontend-context")
).toBeUndefined();
expect(
appCases.find((entry) => entry.id === "app-token-selected-large-backend-context")
).toBeUndefined();
expect(datatableContextCase?.initialPath).toContain(
"ai_evals/fixtures/frontend/app/initial/token_heavy_datatables"
);
expect(datatableContextCase?.runtime?.appContext?.additional).toHaveLength(10);
expect(datatableContextCase?.runtime?.appContext?.additional?.[0]).toEqual({
type: "datatable",
datatableName: "main",
schema: "analytics",
table: "event_log_01",
});
});
it("loads CLI behavior expectations for deploy-guidance cases", async () => {
const cliCases = await loadCases("cli");
const caseEntry = cliCases.find((entry) => entry.id === "bun-hello-script");
expect(caseEntry?.cliExpect).toEqual({
requiredSkills: ["write-script-bun"],
requiredSkillsBeforeFirstMutation: ["write-script-bun"],
forbiddenSkills: ["write-script-python3", "write-flow"],
orderedAssistantMentions: ["wmill generate-metadata", "wmill sync push"],
orderedProposedCommands: ["wmill generate-metadata", "wmill sync push"],
forbiddenExecutedCommands: ["^wmill generate-metadata", "^wmill sync push"],
});
});
it("loads global draft validation and forbidden tool expectations", async () => {
const globalCases = await loadCases("global");
const caseEntry = globalCases.find((entry) => entry.id === "global-test1-script-create");
expect(caseEntry?.validate).toMatchObject({
draftCountExactly: 1,
requiredDrafts: [
{
type: "script",
path: "f/evals/global/greet_user",
language: "bun",
},
],
});
expect(caseEntry?.toolExpect).toMatchObject({
requiredToolsUsed: ["write_script"],
forbiddenToolsUsed: ["deploy_workspace_item", "delete_workspace_item"],
});
});
it("loads global active-editor eval cases", async () => {
const globalCases = await loadCases("global");
const scriptCase = globalCases.find(
(entry) => entry.id === "global-test12-current-live-script-edit"
);
const flowCase = globalCases.find(
(entry) => entry.id === "global-test13-current-live-flow-edit"
);
expect(scriptCase?.initialPath).toContain(
"ai_evals/fixtures/frontend/global/initial/current_greeting_live_script.json"
);
expect(scriptCase?.toolExpect).toMatchObject({
requiredToolsUsed: ["read_workspace_item"],
});
expect(flowCase?.initialPath).toContain(
"ai_evals/fixtures/frontend/global/initial/current_invoice_live_flow.json"
);
expect(flowCase?.validate).toMatchObject({
requiredDrafts: [
{
type: "flow",
path: "f/evals/global/current_invoice_flow",
},
],
});
});
it("loads global docs-search cases as tool-use checks", async () => {
const globalCases = await loadCases("global");
const docsCases = globalCases.filter((entry) =>
entry.id.startsWith("global-docs-"),
);
expect(docsCases.length).toBeGreaterThanOrEqual(3);
// Each docs case verifies the assistant reaches for search_docs and does not
// draft anything; with no draft, the global judge is skipped.
for (const entry of docsCases) {
expect(entry.skipJudge).toBe(true);
expect(entry.toolExpect?.requiredToolsUsed).toContain("search_docs");
}
});
it("loads tool expectations for workspace mutation cases", async () => {
const scriptCases = await loadCases("script");
const caseEntry = scriptCases.find(
(entry) => entry.id === "script-test2-create-current-script-schedule"
);
expect(caseEntry?.toolExpect).toEqual({
requiredToolsUsed: ["test_run_script", "create_schedule"],
toolCallArgs: [
{
tool: "create_schedule",
field: "path",
stringStartsWithAnyOf: ["f/", "u/"],
stringMustNotStartWithAnyOf: ["schedules/"],
},
],
});
expect(caseEntry?.skipJudge).toBe(true);
});
});

Some files were not shown because too many files have changed in this diff Show More