mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-29 16:07:43 +00:00
Merge origin/main into image-generation-script-two-issues
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
---
|
||||
name: demo-video
|
||||
description: Record a demo video of a feature, either a narrated browser walkthrough (mp4 with burned-in captions and text-to-speech audio) driven by Playwright, or a terminal session (a CLI or TUI such as Codex or Claude Code) recorded with vhs, optionally beside the browser it drives, with its idle waits cut. Use when the user asks for a demo video, a recorded walkthrough, a terminal or CLI recording, a video to check a feature, a video for a PR, or to cut the waiting out of a recording.
|
||||
---
|
||||
|
||||
# Demo video
|
||||
|
||||
One scenario file in, one mp4 out. Do not snapshot or screenshot the page while writing the
|
||||
scenario: write selectors from the code you just changed, run once, and fix only the step the
|
||||
script reports as failed.
|
||||
|
||||
Every script lives in `.agents/skills/demo-video/`; the commands below are written from the repo
|
||||
root. Scratch files (scenarios, tapes, recordings) go in the session scratchpad, never in the
|
||||
repo: `record.mjs` writes only the mp4 you name, beside the scenario by default.
|
||||
|
||||
For a terminal session (vhs, optionally beside a browser), for cutting the waits out of any
|
||||
silent recording, and for adding a voice-over to a cut, follow
|
||||
`.agents/skills/demo-video/terminal.md`. A browser take whose waits depend on an AI (a chat
|
||||
turn) goes the same way: record it silent with Playwright's `recordVideo`, cut, then narrate,
|
||||
rather than through `record.mjs`, whose narration cannot survive a cut.
|
||||
|
||||
## What it needs
|
||||
|
||||
| Tool | Used by | Without it |
|
||||
| --- | --- | --- |
|
||||
| Playwright: `npm ci --prefix .agents/skills/demo-video`, once per worktree | every script | the script stops with that command |
|
||||
| Playwright's Chromium: `npx --prefix .agents/skills/demo-video playwright install chromium`, once per machine | every script | the script stops with that command |
|
||||
| `ffmpeg` and `ffprobe` (`brew install ffmpeg`) | every script | the script stops before recording |
|
||||
| macOS `say` | narration in `record.mjs` and `narrate.mjs` | set `voice: false` in the scenario or pass `--voice=none`: captions only, no audio, each line on screen for its reading time |
|
||||
| `vhs` (`brew install vhs`, brings `ttyd`) | terminal recordings | no terminal recordings; browser demos still work |
|
||||
|
||||
Homebrew's `ffmpeg` has no text filters, so captions and notes are drawn by the browser and
|
||||
overlaid as images.
|
||||
|
||||
## Write the scenario
|
||||
|
||||
`<scratch>/demo.mjs`, against this worktree's frontend (its URL is in the session's
|
||||
instructions, or `FRONTEND_PORT` in `.env.local`):
|
||||
|
||||
```js
|
||||
export default {
|
||||
baseURL: 'http://localhost:3000',
|
||||
start: '/?workspace=admins', // first page shown in the video
|
||||
// Runs unrecorded; its cookies carry into the recording. Log in here.
|
||||
setup: async ({ page }) => {
|
||||
const r = await page.request.post('/api/auth/login',
|
||||
{ data: { email: 'admin@windmill.dev', password: 'changeme' } })
|
||||
if (!r.ok()) throw new Error(`login: ${r.status()}`)
|
||||
},
|
||||
steps: [
|
||||
{ say: 'One sentence about what the viewer sees.' },
|
||||
{ say: 'Clicking the row opens it.', do: ({ click }) => click('text=Daily orders') },
|
||||
{ say: 'Hover shows the menu.', do: async ({ page, hover }) => { await hover('[aria-label="Menu"]') } },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
- `say`: narration, spoken and shown as the caption. It starts before the step's action, and
|
||||
the step stays on screen until it is spoken. Keep each to one short sentence.
|
||||
- `do`: gets `{ page, click, hover, wait }`. `click`/`hover` draw a ring on the target first, so
|
||||
prefer them over `page.click`. Strings are Playwright selectors (the first match is used);
|
||||
a locator is used as given, so a locator matching two elements fails the step. Assert the
|
||||
outcome inside the step by waiting on what proves it worked, e.g.
|
||||
`await page.getByText('Hello, Ada!').waitFor({ timeout: 30000 })`, so a broken feature fails
|
||||
the run instead of recording a wrong screen. There is no `expect` in a scenario.
|
||||
- Captions sit in a band of their own below the page (`captionAt: 'top'` puts it above), so
|
||||
they never cover the UI. The mp4 is the viewport plus that band: 1280x816 by default.
|
||||
- Optional: `hold` (extra ms after a step), `viewport` (default 1280x720), `voice` (macOS
|
||||
`say -v '?'`, default Samantha; `false` for no speech), `settle` (ms after `start` loads),
|
||||
`pad` (ms after each line, default 400), `captionHeight` (band height, default 96, two lines
|
||||
of text; viewport height + band must be even for H.264).
|
||||
- Text selectors (`text=…`) can match hidden copies; for menu items use a role locator,
|
||||
`({ page, hover }) => hover(page.getByRole('menuitem', { name: /Shared sessions/ }))`.
|
||||
- Aim for 5 to 10 steps, under a minute: the video is for checking a feature, not marketing.
|
||||
|
||||
## Test data must match the story
|
||||
|
||||
Plant the data the take needs before recording, and make it what the narration and the prompt
|
||||
say it is. An AI agent in the take reads that data back and reacts to it: given a "Supabase"
|
||||
connection string that pointed at `127.0.0.1`, Codex refused to call it a Supabase connection
|
||||
and the take was unusable. Hosts, names, providers and values must fit the story; when the demo
|
||||
needs the thing to really work, ask the user for a real instance of that kind rather than
|
||||
planting a local stand-in. Never put a real secret on screen.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
node .agents/skills/demo-video/record.mjs <scratch>/demo.mjs [<scratch>/demo.mp4]
|
||||
```
|
||||
|
||||
It prints the mp4 path, or `step N failed: …` plus a screenshot path. Read that screenshot
|
||||
only on failure.
|
||||
|
||||
## Deliver
|
||||
|
||||
The user may not be on this machine, so a local path is not a delivery.
|
||||
|
||||
- **Artifact page**: publish the mp4 through the Artifact `files` map (15 MB per file) and
|
||||
reference it from a `<video controls>`. The captions are burned in, so nothing else is
|
||||
needed. For a video made with `--no-band`, Artifacts do not serve `.vtt` files: write the
|
||||
cues with `narrate.mjs --cues=cues.json` and add them from inline JS:
|
||||
|
||||
```js
|
||||
const track = video.addTextTrack('captions', 'English', 'en')
|
||||
for (const [start, end, text] of CUES) track.addCue(new VTTCue(start, end, text))
|
||||
track.mode = 'showing'
|
||||
```
|
||||
|
||||
- **PR body**: GitHub strips `<video>` from PR bodies and plays no mp4 from a raw URL (it
|
||||
downloads), so embed a GIF and link the narrated mp4. Make the GIF (about 4 MB for 55 s):
|
||||
|
||||
```bash
|
||||
ffmpeg -v error -y -i demo.mp4 -vf "fps=10,scale=960:-1:flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=diff_mode=rectangle" demo.gif
|
||||
```
|
||||
|
||||
Upload both to `windmill-labs/agent-screenshots-internal`, as the `pr` skill does for
|
||||
screenshots. The repo is public and its history permanent: nothing secret may appear in the
|
||||
video.
|
||||
|
||||
```bash
|
||||
REPO=windmill-labs/agent-screenshots-internal
|
||||
for F in demo.gif demo.mp4; do
|
||||
DEST="shots/$(git branch --show-current)/$(date +%s)-$(basename "$F")"
|
||||
base64 < "$F" | tr -d '\n' | jq -Rs --arg m "add $DEST" '{message:$m, content:.}' \
|
||||
| gh api -X PUT "repos/$REPO/contents/$DEST" --input - >/dev/null
|
||||
URL="https://raw.githubusercontent.com/$REPO/main/$DEST"
|
||||
echo "$URL $(curl -sI "$URL" | grep -i '^content-length')"
|
||||
done
|
||||
```
|
||||
|
||||
Check that each `content-length` matches the local file, then put
|
||||
`` and `[Narrated mp4](<mp4 url>)` in the body.
|
||||
@@ -0,0 +1,44 @@
|
||||
// Prints when each watched region of a recording changes, in seconds of the file itself, so
|
||||
// `--cut=` ranges and narration `at` times come from the picture rather than from wall-clock
|
||||
// logs (a vhs mp4 runs shorter than the session it recorded).
|
||||
//
|
||||
// usage: node activity.mjs <in.mp4> <regions.json> [from] [to] [--raw]
|
||||
//
|
||||
// Same sampling and regions.json as cut-waits.mjs (10 samples per second, `min`, `unlessLike`).
|
||||
// Each region gets one line of runs of consecutive changes, `12.3-14.1(952)`: first and last
|
||||
// changing sample, and the most pixels changed in one sample. --raw prints every sample in which
|
||||
// anything changed, marked * when it counts (above `min`) and ~ when `unlessLike` suppressed it.
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { die, need, sampleRegions, SAMPLES } from './lib.mjs'
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const raw = args.includes('--raw')
|
||||
const [input, regionsFile, from, to] = args.filter((a) => a !== '--raw')
|
||||
if (!regionsFile) die('usage: node activity.mjs <in.mp4> <regions.json> [from] [to] [--raw]')
|
||||
need('ffmpeg', 'ffprobe')
|
||||
const regions = JSON.parse(readFileSync(regionsFile, 'utf8'))
|
||||
const samples = await sampleRegions(input, regions, {
|
||||
from: from === undefined ? 0 : Number(from),
|
||||
to: to === undefined ? undefined : Number(to)
|
||||
})
|
||||
|
||||
for (const [k, r] of regions.entries()) {
|
||||
const hits = samples.filter((s) => !s.suppressed[k] && s.changed[k] > r.min)
|
||||
if (raw) {
|
||||
const all = samples.filter((s) => s.changed[k] > 0)
|
||||
const mark = (s) => (s.suppressed[k] ? '~' : s.changed[k] > r.min ? '*' : '')
|
||||
console.log(`${r.name}: ${all.map((s) => `${s.t.toFixed(1)}(${s.changed[k]})${mark(s)}`).join(' ')}`)
|
||||
continue
|
||||
}
|
||||
const runs = []
|
||||
for (const s of hits) {
|
||||
const run = runs.at(-1)
|
||||
if (run && s.t - run.to <= 1.5 / SAMPLES) {
|
||||
run.to = s.t
|
||||
run.max = Math.max(run.max, s.changed[k])
|
||||
} else runs.push({ from: s.t, to: s.t, max: s.changed[k] })
|
||||
}
|
||||
const fmt = (run) =>
|
||||
(run.to > run.from ? `${run.from.toFixed(1)}-${run.to.toFixed(1)}` : run.from.toFixed(1)) + `(${run.max})`
|
||||
console.log(`${r.name}: ${runs.map(fmt).join(' ') || '-'}`)
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// Shrinks the idle stretches of a silent screen recording (a terminal session, a browser take)
|
||||
// to about a second each and marks every cut with a "N s later" note. It measures what changes,
|
||||
// it does not guess: a stretch is idle when no watched region changes.
|
||||
//
|
||||
// usage: node cut-waits.mjs <in.mp4> <out.mp4> <regions.json> [options]
|
||||
// --plan print the cuts and write the check sheets, render nothing
|
||||
// --min-gap=3 cut only stretches at least this long (s)
|
||||
// --head=0.7 keep this much of a stretch after the last change (s)
|
||||
// --tail=0.3 and this much before the next change (s)
|
||||
// --end-hold=5 keep this much after the last change, then end the video (s)
|
||||
// --label-y=12 top of the "N s later" note, in pixels
|
||||
// --cut=12.5-38 also remove this stretch, though the screen changes in it (repeatable)
|
||||
//
|
||||
// --cut is for a wait the measurement cannot see: an AI agent working, whose tool calls keep
|
||||
// scrolling in while the viewer only waits for its answer. Take its bounds from activity.mjs,
|
||||
// which prints when each region changes in seconds of <in.mp4>, never from wall-clock logs.
|
||||
//
|
||||
// regions.json lists the areas to watch, in pixels of <in.mp4>. A pixel changes when its gray
|
||||
// level moves by more than 40 between two samples (10 per second); a region is active when more
|
||||
// than `min` pixels change. Set `min` above what a blinking cursor changes (one cell, 170-210 px at
|
||||
// font size 15) and below what typing changes (several cells per sample).
|
||||
// `unlessLike` ignores a region's changes while a part of it still looks as it did at `at`
|
||||
// seconds, e.g. a status line whose timer ticks while the app works but whose row also receives
|
||||
// real output once the work is done.
|
||||
// [{ "name": "status", "x": 0, "y": 670, "w": 820, "h": 35, "min": 30,
|
||||
// "unlessLike": { "x": 40, "y": 675, "w": 72, "h": 22, "at": 40 } }]
|
||||
//
|
||||
// Writes <out>.regions.json, the regions with each unlessLike.at moved onto the output's timeline,
|
||||
// for activity.mjs and narrate.mjs on the cut file.
|
||||
// Writes <out>.cuts-<n>.png: for every cut, the last frame kept before it beside the first
|
||||
// frame kept after it. Read them before trusting the cut: the two frames of a row must show the
|
||||
// same content, apart from what ticks.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { die, launchBrowser, need, probe, sampleRegions } from './lib.mjs'
|
||||
|
||||
const [input, output, regionsFile, ...rest] = process.argv.slice(2)
|
||||
if (!regionsFile) die('usage: node cut-waits.mjs <in.mp4> <out.mp4> <regions.json> [--plan] [--min-gap=3] ...')
|
||||
need('ffmpeg', 'ffprobe')
|
||||
const forced = rest
|
||||
.filter((a) => a.startsWith('--cut='))
|
||||
.map((a) => {
|
||||
const [from, to] = a.slice('--cut='.length).split('-').map(Number)
|
||||
if (!(to > from)) die(`bad ${a}: expected --cut=<from>-<to> in seconds`)
|
||||
return { from, to }
|
||||
})
|
||||
const opt = Object.fromEntries(
|
||||
rest
|
||||
.filter((a) => !a.startsWith('--cut='))
|
||||
.map((a) => {
|
||||
const [k, v] = a.replace(/^--/, '').split('=')
|
||||
return [k, v === undefined ? true : Number(v)]
|
||||
})
|
||||
)
|
||||
const minGap = opt['min-gap'] ?? 3
|
||||
const head = opt.head ?? 0.7
|
||||
const tail = opt.tail ?? 0.3
|
||||
const endHold = opt['end-hold'] ?? 5
|
||||
const labelY = opt['label-y'] ?? 12
|
||||
if (minGap < head + tail) die(`--min-gap must be at least --head + --tail (${head + tail} s)`)
|
||||
const regions = JSON.parse(readFileSync(regionsFile, 'utf8'))
|
||||
const { fps, duration, hasAudio } = probe(input)
|
||||
|
||||
// 1. Measure: the samples where any watched region changes.
|
||||
const active = (await sampleRegions(input, regions)).filter((s) => s.active).map((s) => s.t)
|
||||
if (!active.length) {
|
||||
console.error('nothing changes in the watched regions')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// 2. Plan: shrink every stretch of at least minGap between two changes, and the ending.
|
||||
const measured = []
|
||||
if (active[0] >= minGap) measured.push({ from: head, to: active[0] - tail })
|
||||
for (let i = 1; i < active.length; i++) {
|
||||
const [a, b] = [active[i - 1], active[i]]
|
||||
if (b - a >= minGap) measured.push({ from: a + head, to: b - tail })
|
||||
}
|
||||
// Cuts less than half a second apart become one: the sliver between them would only flash.
|
||||
const cuts = []
|
||||
for (const c of [...measured, ...forced].sort((a, b) => a.from - b.from)) {
|
||||
const prev = cuts.at(-1)
|
||||
if (prev && c.from <= prev.to + 0.5) prev.to = Math.max(prev.to, c.to)
|
||||
else cuts.push({ ...c })
|
||||
}
|
||||
const last = active.at(-1)
|
||||
if (duration - last > endHold + 0.2) {
|
||||
const from = last + endHold
|
||||
const prev = cuts.at(-1)
|
||||
if (prev && prev.to >= from - 0.5) Object.assign(prev, { to: duration, end: true })
|
||||
else cuts.push({ from, to: duration, end: true })
|
||||
}
|
||||
// Cuts fall on frame times and the render keeps each segment half-open (select, below), so the
|
||||
// output has exactly the planned frames and the times printed and mapped here are the rendered ones.
|
||||
const snap = (t) => Math.round(t * fps) / fps
|
||||
for (const c of cuts) Object.assign(c, { from: snap(c.from), to: c.end ? duration : snap(c.to) })
|
||||
const kept = []
|
||||
let cursor = 0
|
||||
for (const c of cuts) {
|
||||
kept.push([cursor, c.from])
|
||||
cursor = c.to
|
||||
}
|
||||
if (cursor < duration) kept.push([cursor, duration])
|
||||
let outAt = 0
|
||||
cuts.forEach((c, k) => {
|
||||
outAt += kept[k][1] - kept[k][0]
|
||||
c.outAt = outAt
|
||||
c.label = `${Math.round(c.to - c.from)} s later`
|
||||
})
|
||||
const outDuration = kept.reduce((s, [a, b]) => s + b - a, 0)
|
||||
const clock = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`
|
||||
for (const c of cuts)
|
||||
console.log(
|
||||
`${c.end ? 'end' : 'cut'} ${c.from.toFixed(1).padStart(6)} -> ${c.to.toFixed(1).padStart(6)} ` +
|
||||
`${(c.to - c.from).toFixed(1).padStart(5)} s removed, at ${clock(c.outAt)} in the output` +
|
||||
(c.end ? '' : ` "${c.label}"`)
|
||||
)
|
||||
console.log(`duration ${duration.toFixed(1)} s -> ${outDuration.toFixed(1)} s`)
|
||||
|
||||
// The regions for the cut file: an `unlessLike.at` is a time of the file it samples, so it moves
|
||||
// with the cut. A time inside a cut moves to the cut's position in the output.
|
||||
const toOutput = (t) => {
|
||||
let base = 0
|
||||
for (const [a, b] of kept) {
|
||||
if (t < a) return base
|
||||
if (t <= b) return base + t - a
|
||||
base += b - a
|
||||
}
|
||||
return outDuration
|
||||
}
|
||||
const outRegions = output.replace(/\.mp4$/, '') + '.regions.json'
|
||||
writeFileSync(
|
||||
outRegions,
|
||||
JSON.stringify(
|
||||
regions.map((r) => (r.unlessLike ? { ...r, unlessLike: { ...r.unlessLike, at: +toOutput(r.unlessLike.at).toFixed(2) } } : r)),
|
||||
null,
|
||||
1
|
||||
)
|
||||
)
|
||||
console.log(`regions of the output: ${outRegions}`)
|
||||
|
||||
// 3. Check sheets: the frames on both sides of every cut.
|
||||
const work = mkdtempSync(join(tmpdir(), 'cut-waits-'))
|
||||
const shot = (t, file) =>
|
||||
execFileSync('ffmpeg', ['-v', 'error', '-y', '-ss', t.toFixed(3), '-i', input, '-frames:v', '1', '-vf', 'scale=640:-2', file])
|
||||
const rows = cuts.filter((c) => !c.end)
|
||||
for (let s = 0; s * 4 < rows.length; s++) {
|
||||
const files = []
|
||||
rows.slice(s * 4, s * 4 + 4).forEach((c, k) => {
|
||||
const a = join(work, `s${s}r${k}a.png`)
|
||||
const b = join(work, `s${s}r${k}b.png`)
|
||||
shot(Math.max(0, c.from - 1 / fps), a)
|
||||
shot(c.to, b)
|
||||
files.push(a, b)
|
||||
})
|
||||
const n = files.length / 2
|
||||
const graph =
|
||||
files.map((_, i) => (i % 2 ? '' : `[${i}][${i + 1}]hstack[r${i / 2}];`)).join('') +
|
||||
(n > 1 ? `${[...Array(n).keys()].map((i) => `[r${i}]`).join('')}vstack=inputs=${n}` : '[r0]null')
|
||||
const sheet = output.replace(/\.mp4$/, '') + `.cuts-${s + 1}.png`
|
||||
execFileSync('ffmpeg', ['-v', 'error', '-y', ...files.flatMap((f) => ['-i', f]), '-filter_complex', graph, sheet])
|
||||
console.log(`check: ${sheet}`)
|
||||
}
|
||||
if (opt.plan) process.exit(0)
|
||||
|
||||
// 4. Notes, drawn by the browser: Homebrew's ffmpeg has no text filters.
|
||||
const browser = await launchBrowser()
|
||||
const page = await browser.newPage({ viewport: { width: 600, height: 120 } })
|
||||
const notes = new Map()
|
||||
for (const c of rows) {
|
||||
if (notes.has(c.label)) continue
|
||||
await page.setContent(
|
||||
`<body style="margin:0;background:transparent"><div style="display:inline-block;padding:8px 16px;` +
|
||||
`border-radius:999px;background:rgba(17,17,17,.85);border:1px solid rgba(255,255,255,.3);` +
|
||||
`color:#fff;font:600 18px/1 system-ui,sans-serif"></div></body>`
|
||||
)
|
||||
await page.locator('div').evaluate((el, t) => (el.textContent = t), `⏩ ${c.label}`)
|
||||
const file = join(work, `note${notes.size}.png`)
|
||||
await page.locator('div').screenshot({ path: file, omitBackground: true })
|
||||
notes.set(c.label, file)
|
||||
}
|
||||
await browser.close()
|
||||
|
||||
// 5. Render: keep the segments, retime them, show each note for a moment after its cut.
|
||||
const noteFiles = [...notes.values()]
|
||||
// Half a frame below each bound, so a frame exactly on a bound is kept once, by the later segment.
|
||||
const half = 0.5 / fps
|
||||
const keep = kept.map(([a, b]) => `gte(t,${(a - half).toFixed(4)})*lt(t,${(b - half).toFixed(4)})`).join('+')
|
||||
// The second fps= restores the frame rate FFmpeg 7's setpts clears; without it the overlays
|
||||
// below fall back to 25 fps.
|
||||
const filters = [`[0:v]fps=${fps},select='${keep}',setpts=N/(${fps}*TB),fps=${fps}[v0]`]
|
||||
rows.forEach((c, k) => {
|
||||
const next = rows[k + 1]?.outAt ?? outDuration
|
||||
const e = Math.min(c.outAt + 1.4, next)
|
||||
const input = 1 + noteFiles.indexOf(notes.get(c.label))
|
||||
filters.push(
|
||||
`[v${k}][${input}:v]overlay=x=(W-w)/2:y=${labelY}:enable='between(t,${c.outAt.toFixed(3)},${e.toFixed(3)})'[v${k + 1}]`
|
||||
)
|
||||
})
|
||||
execFileSync(
|
||||
'ffmpeg',
|
||||
[
|
||||
'-v', 'error', '-y', '-i', input,
|
||||
...noteFiles.flatMap((f) => ['-i', f]),
|
||||
'-filter_complex', filters.join(';'),
|
||||
'-map', `[v${rows.length}]`, '-an',
|
||||
'-c:v', 'libx264', '-crf', '20', '-preset', 'medium', '-pix_fmt', 'yuv420p', '-movflags', '+faststart',
|
||||
output
|
||||
],
|
||||
{ stdio: ['ignore', 'inherit', 'inherit'] }
|
||||
)
|
||||
if (hasAudio) console.log('note: the input had audio; the output has none')
|
||||
console.log(output)
|
||||
@@ -0,0 +1,210 @@
|
||||
// Shared by the demo-video scripts, and imported by the browser scripts written for a terminal
|
||||
// take: `import { launchBrowser, waitForOutput } from '<repo>/.agents/skills/demo-video/lib.mjs'`.
|
||||
import { createRequire } from 'node:module'
|
||||
import { execFileSync, spawn } from 'node:child_process'
|
||||
import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
export const CODEX_SESSIONS = join(homedir(), '.codex/sessions')
|
||||
export const CLAUDE_PROJECTS = join(homedir(), '.claude/projects')
|
||||
|
||||
export function die(message) {
|
||||
console.error(message)
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const HINTS = {
|
||||
ffmpeg: 'brew install ffmpeg',
|
||||
ffprobe: 'brew install ffmpeg',
|
||||
vhs: 'brew install vhs',
|
||||
say: 'macOS only; use voice: false in a scenario or --voice=none for captions without speech'
|
||||
}
|
||||
export function need(...commands) {
|
||||
for (const c of commands) {
|
||||
try {
|
||||
execFileSync('which', [c], { stdio: 'ignore' })
|
||||
} catch {
|
||||
die(`${c} not found: ${HINTS[c] ?? 'install it'}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The skill pins its own Playwright rather than using frontend/'s, whose older pin may not
|
||||
// install its browser on a current Node.
|
||||
const SKILL = dirname(fileURLToPath(import.meta.url))
|
||||
export function playwright() {
|
||||
try {
|
||||
return createRequire(import.meta.url)('playwright')
|
||||
} catch {
|
||||
die(`Playwright not found: run \`npm ci --prefix ${SKILL}\``)
|
||||
}
|
||||
}
|
||||
export async function launchBrowser(options) {
|
||||
try {
|
||||
return await playwright().chromium.launch(options)
|
||||
} catch (err) {
|
||||
if (/Executable doesn't exist/.test(err.message))
|
||||
die(`Playwright's Chromium is not installed: run \`npx --prefix ${SKILL} playwright install chromium\``)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export function probe(file) {
|
||||
const info = JSON.parse(
|
||||
execFileSync('ffprobe', ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', file])
|
||||
)
|
||||
const vs = info.streams.find((s) => s.codec_type === 'video')
|
||||
const [num, den] = (vs?.r_frame_rate ?? '0/1').split('/').map(Number)
|
||||
return {
|
||||
width: vs?.width,
|
||||
height: vs?.height,
|
||||
fps: num / den,
|
||||
duration: Number(info.format.duration),
|
||||
hasAudio: info.streams.some((s) => s.codec_type === 'audio')
|
||||
}
|
||||
}
|
||||
|
||||
// One narration line as speech. With voice 'none' nothing is spoken and the line lasts as long
|
||||
// as it takes to read.
|
||||
export function speak(text, file, { voice, rate = 0 }) {
|
||||
if (voice === 'none') return { file: null, length: Math.max(1.5, text.split(/\s+/).length / 2.7) }
|
||||
execFileSync('say', ['-v', voice, ...(rate ? ['-r', String(rate)] : []), '-o', file, text])
|
||||
return { file, length: probe(file).duration }
|
||||
}
|
||||
|
||||
// Caption band images, drawn by the browser: Homebrew's ffmpeg has no text filters.
|
||||
export async function captionImages(browser, texts, { width, height, dir }) {
|
||||
const page = await browser.newPage({ viewport: { width, height } })
|
||||
const files = []
|
||||
for (const [k, text] of texts.entries()) {
|
||||
await page.setContent(
|
||||
`<body style="margin:0;height:${height}px;display:flex;align-items:center;justify-content:center;background:#111;">` +
|
||||
`<div style="max-width:88%;color:#fff;font:500 20px/1.35 system-ui,sans-serif;text-align:center;"></div></body>`
|
||||
)
|
||||
await page.locator('div').evaluate((el, t) => (el.textContent = t), text)
|
||||
files.push(join(dir, `caption${k}.png`))
|
||||
await page.screenshot({ path: files.at(-1) })
|
||||
}
|
||||
await page.close()
|
||||
return files
|
||||
}
|
||||
|
||||
// Samples <input> 10 times a second inside [from, to] and returns, for each sample, how many
|
||||
// pixels of each region changed since the previous one. A pixel changes when its gray level
|
||||
// moves by more than 40. `suppressed[k]` is true while region k's `unlessLike` part still looks
|
||||
// as it did at `unlessLike.at`; `active` is whether any region changed by more than its `min`.
|
||||
export const SAMPLES = 10
|
||||
export async function sampleRegions(input, regions, { from = 0, to } = {}) {
|
||||
const { width: W, height: H } = probe(input)
|
||||
const grayFrame = (t) =>
|
||||
execFileSync(
|
||||
'ffmpeg',
|
||||
['-v', 'error', '-ss', String(t), '-i', input, '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'gray', '-'],
|
||||
{ maxBuffer: W * H * 2 }
|
||||
)
|
||||
const lit = (frame, a) => {
|
||||
const bits = new Uint8Array(a.w * a.h)
|
||||
for (let y = 0; y < a.h; y++)
|
||||
for (let x = 0; x < a.w; x++) bits[y * a.w + x] = frame[(a.y + y) * W + a.x + x] > 70 ? 1 : 0
|
||||
return bits
|
||||
}
|
||||
const refs = regions.map((r) => {
|
||||
if (!r.unlessLike) return null
|
||||
const ref = lit(grayFrame(r.unlessLike.at), r.unlessLike)
|
||||
return { ref, lit: ref.reduce((s, b) => s + b, 0) }
|
||||
})
|
||||
const looksLike = (frame, k) => {
|
||||
const bits = lit(frame, regions[k].unlessLike)
|
||||
let diff = 0
|
||||
for (let i = 0; i < bits.length; i++) diff += bits[i] !== refs[k].ref[i]
|
||||
return diff < 0.25 * Math.max(refs[k].lit, 1)
|
||||
}
|
||||
const samples = []
|
||||
await new Promise((done, fail) => {
|
||||
const range = ['-ss', String(from), ...(to !== undefined ? ['-to', String(to)] : [])]
|
||||
const ff = spawn('ffmpeg', ['-v', 'error', ...range, '-i', input, '-vf', `fps=${SAMPLES},format=gray`, '-f', 'rawvideo', '-'])
|
||||
const size = W * H
|
||||
let buf = Buffer.alloc(0)
|
||||
let prev = null
|
||||
let prevLike = []
|
||||
let n = 0
|
||||
ff.stdout.on('data', (chunk) => {
|
||||
buf = Buffer.concat([buf, chunk])
|
||||
while (buf.length >= size) {
|
||||
const frame = Buffer.from(buf.subarray(0, size))
|
||||
buf = buf.subarray(size)
|
||||
const like = regions.map((r, k) => (r.unlessLike ? looksLike(frame, k) : false))
|
||||
if (prev) {
|
||||
const changed = regions.map((r) => {
|
||||
let c = 0
|
||||
for (let y = r.y; y < r.y + r.h; y++)
|
||||
for (let x = r.x, i = y * W + r.x; x < r.x + r.w; x++, i++) {
|
||||
const d = frame[i] - prev[i]
|
||||
if (d > 40 || d < -40) c++
|
||||
}
|
||||
return c
|
||||
})
|
||||
const suppressed = like.map((l, k) => l && prevLike[k])
|
||||
const active = regions.some((r, k) => !suppressed[k] && changed[k] > r.min)
|
||||
samples.push({ t: from + n / SAMPLES, changed, suppressed, active })
|
||||
}
|
||||
prev = frame
|
||||
prevLike = like
|
||||
n++
|
||||
}
|
||||
})
|
||||
ff.on('close', (code) => (code === 0 ? done() : fail(new Error(`ffmpeg exited ${code}`))))
|
||||
})
|
||||
return samples
|
||||
}
|
||||
|
||||
// Waits until the agent session started in `cwd` writes `pattern` to its log, and returns the
|
||||
// match. Only that folder's sessions count: other agents on the machine (a review running in
|
||||
// the same worktree, the recording agent itself) write logs at the same time.
|
||||
// - agent 'codex': files under ~/.codex/sessions whose session_meta names `cwd`. The per-day
|
||||
// folder may not exist when the wait starts; it is looked for again on every poll.
|
||||
// - agent 'claude': files under ~/.claude/projects/<cwd with every other character as ->.
|
||||
// - dirs: any other folders, searched without a cwd check.
|
||||
// Only files written after `since` are read. Logs are JSON: end the pattern before `"` and `\`;
|
||||
// JSON-escaped ampersands (backslash u0026) are turned back into `&` before matching.
|
||||
export async function waitForOutput(
|
||||
pattern,
|
||||
{ agent, cwd = process.cwd(), dirs, since = Date.now(), timeout = 300_000, every = 1000 } = {}
|
||||
) {
|
||||
const real = realpathSync(cwd)
|
||||
const roots =
|
||||
dirs ?? (agent === 'claude' ? [join(CLAUDE_PROJECTS, real.replace(/[^a-zA-Z0-9-]/g, '-'))] : [CODEX_SESSIONS])
|
||||
const mark = agent === 'codex' || (!agent && !dirs) ? `"cwd":${JSON.stringify(real)}` : null
|
||||
const walk = (dir, out) => {
|
||||
try {
|
||||
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = join(dir, e.name)
|
||||
if (e.isDirectory()) walk(p, out)
|
||||
else if (e.isFile()) out.push(p)
|
||||
}
|
||||
} catch {
|
||||
// not created yet, or removed during the poll
|
||||
}
|
||||
return out
|
||||
}
|
||||
const deadline = Date.now() + timeout
|
||||
while (Date.now() < deadline) {
|
||||
for (const root of roots)
|
||||
for (const file of walk(root, [])) {
|
||||
try {
|
||||
if (statSync(file).mtimeMs < since) continue
|
||||
const text = readFileSync(file, 'utf8')
|
||||
if (mark && !text.includes(mark)) continue
|
||||
const m = text.replace(/\\u0026/g, '&').match(pattern)
|
||||
if (m) return m
|
||||
} catch {
|
||||
// written or removed while being read: look again on the next poll
|
||||
}
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, every))
|
||||
}
|
||||
throw new Error(`no match for ${pattern} in ${roots.join(', ')} after ${Math.round(timeout / 1000)} s`)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Lays a spoken voice-over on a silent video: one text-to-speech line (macOS `say`) per entry,
|
||||
// started at the moment of the video it describes. When a line still runs at the next line's
|
||||
// moment, the video holds the frame of that moment until the line ends, so picture and speech
|
||||
// stay together.
|
||||
//
|
||||
// usage: node narrate.mjs <in.mp4> <lines.json> <out.mp4> [options]
|
||||
// --plan speak the lines and print where they land, render nothing
|
||||
// --regions=<file> regions.json of <in.mp4>: warn about a line whose `at` falls just after
|
||||
// a change started, since its caption would then land after that change
|
||||
// --voice=Samantha macOS voice (say -v '?'); --voice=none speaks nothing and gives each
|
||||
// line its reading time, for a machine without `say`
|
||||
// --rate=0 words per minute for say; 0 keeps the voice's own
|
||||
// --gap=0.4 silence between two lines (s)
|
||||
// --end-hold=1.5 keep the last frame this long after the last line (s)
|
||||
// --vtt=<file> also write the lines as WebVTT captions, on the output's timeline
|
||||
// --cues=<file> also write them as JSON [[start, end, text], ...], for a text track
|
||||
// added from inline JS on a page that cannot serve .vtt files
|
||||
// --caption-height=96 height of the caption band added below the video (two lines of text)
|
||||
// --caption-at=top put the band above the video instead
|
||||
// --no-band burn in no captions: the output keeps the input's size
|
||||
//
|
||||
// Each line shows in the band from its start until the next line starts, so captions never
|
||||
// cover the recording.
|
||||
//
|
||||
// lines.json: [{ "at": 0.4, "text": "One sentence about what is on screen." }, ...], `at` in
|
||||
// seconds of <in.mp4>, increasing. Anchor a line a little before the change it describes: a
|
||||
// hold freezes the frame at `at`, so a line anchored after its change starts only once that
|
||||
// change has already played.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { captionImages, die, launchBrowser, need, probe, sampleRegions, speak } from './lib.mjs'
|
||||
|
||||
const [input, linesFile, output, ...rest] = process.argv.slice(2)
|
||||
if (!output) die('usage: node narrate.mjs <in.mp4> <lines.json> <out.mp4> [--plan] [--voice=Samantha] [--gap=0.4] ...')
|
||||
const opt = Object.fromEntries(
|
||||
rest.map((a) => {
|
||||
const [k, ...v] = a.replace(/^--/, '').split('=')
|
||||
return [k, v.length ? v.join('=') : true]
|
||||
})
|
||||
)
|
||||
const voice = opt.voice || 'Samantha'
|
||||
need('ffmpeg', 'ffprobe', ...(voice === 'none' ? [] : ['say']))
|
||||
const rate = Number(opt.rate || 0)
|
||||
const gap = Number(opt.gap ?? 0.4)
|
||||
const endHold = Number(opt['end-hold'] ?? 1.5)
|
||||
const lines = JSON.parse(readFileSync(linesFile, 'utf8'))
|
||||
lines.forEach((l, i) => {
|
||||
if (i && l.at < lines[i - 1].at) die(`line ${i + 1} starts before line ${i}: sort them by "at"`)
|
||||
})
|
||||
|
||||
const vs = probe(input)
|
||||
const { fps, duration } = vs
|
||||
|
||||
// 1. Speak every line.
|
||||
const work = mkdtempSync(join(tmpdir(), 'narrate-'))
|
||||
const cues = lines.map((l, i) => ({ ...l, ...speak(l.text, join(work, `line${i}.aiff`), { voice, rate }) }))
|
||||
|
||||
// 2. Place them. A line that would start before the previous one ends holds the frame at its
|
||||
// own moment for the difference, which delays everything after it.
|
||||
const holds = new Map()
|
||||
const hold = (at, d) => {
|
||||
const near = [...holds.keys()].find((k) => Math.abs(k - at) < 1 / fps)
|
||||
holds.set(near ?? at, (holds.get(near ?? at) ?? 0) + d)
|
||||
}
|
||||
let shift = 0
|
||||
let prevEnd = -Infinity
|
||||
for (const c of cues) {
|
||||
c.start = c.at + shift
|
||||
c.held = 0
|
||||
// Under a frame of overlap only shortens the gap: a hold that short would show nothing.
|
||||
if (c.start < prevEnd + gap - 1 / fps) {
|
||||
c.held = prevEnd + gap - c.start
|
||||
hold(c.at, c.held)
|
||||
shift += c.held
|
||||
c.start += c.held
|
||||
}
|
||||
c.end = c.start + c.length
|
||||
prevEnd = c.end
|
||||
}
|
||||
let outDuration = duration + shift
|
||||
if (prevEnd + endHold > outDuration) {
|
||||
hold(duration, prevEnd + endHold - outDuration)
|
||||
outDuration = prevEnd + endHold
|
||||
}
|
||||
|
||||
// A change that starts in the 0.6 s before a line's `at` is one the line most likely describes.
|
||||
const late = new Map()
|
||||
if (opt.regions) {
|
||||
const regions = JSON.parse(readFileSync(opt.regions, 'utf8'))
|
||||
const samples = await sampleRegions(input, regions)
|
||||
const starts = []
|
||||
samples.forEach((s, i) => {
|
||||
if (!s.active) return
|
||||
const quietBefore = !samples.slice(Math.max(0, i - 5), i).some((p) => p.active)
|
||||
if (quietBefore)
|
||||
starts.push({ t: s.t, region: regions.find((r, k) => !s.suppressed[k] && s.changed[k] > r.min).name })
|
||||
})
|
||||
cues.forEach((c, i) => {
|
||||
const s = starts.find((s) => s.t > c.at - 0.6 && s.t <= c.at)
|
||||
if (s) late.set(i, s)
|
||||
})
|
||||
}
|
||||
|
||||
const clock = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`
|
||||
for (const [i, c] of cues.entries()) {
|
||||
console.log(
|
||||
`${clock(c.start)}-${clock(c.end)} at ${c.at.toFixed(1).padStart(5)}` +
|
||||
(c.held ? ` holds ${c.held.toFixed(1)} s` : '') +
|
||||
` ${c.text}`
|
||||
)
|
||||
if (c.held > 1)
|
||||
console.log(` ^ line ${i} runs ${c.held.toFixed(1)} s into this one's moment: shorten line ${i}`)
|
||||
const s = late.get(i)
|
||||
if (s)
|
||||
console.log(` ^ ${s.region} starts changing at ${s.t.toFixed(1)}, before this line: anchor it at ${Math.max(0, s.t - 0.3).toFixed(1)}`)
|
||||
}
|
||||
console.log(`duration ${duration.toFixed(1)} s -> ${outDuration.toFixed(1)} s`)
|
||||
|
||||
// The band shows each caption until the next line starts.
|
||||
const shown = cues.map((c, k) => [c.start, k + 1 < cues.length ? cues[k + 1].start : outDuration, c.text])
|
||||
if (opt.vtt) {
|
||||
const stamp = (s) => {
|
||||
const ms = Math.round(s * 1000)
|
||||
const p = (n, w = 2) => String(n).padStart(w, '0')
|
||||
return `${p(Math.floor(ms / 3600000))}:${p(Math.floor(ms / 60000) % 60)}:${p(Math.floor(ms / 1000) % 60)}.${p(ms % 1000, 3)}`
|
||||
}
|
||||
writeFileSync(
|
||||
opt.vtt,
|
||||
'WEBVTT\n\n' + cues.map((c, k) => `${k + 1}\n${stamp(c.start)} --> ${stamp(c.end)}\n${c.text}\n`).join('\n')
|
||||
)
|
||||
console.log(`captions: ${opt.vtt}`)
|
||||
}
|
||||
if (opt.cues) {
|
||||
writeFileSync(opt.cues, JSON.stringify(shown.map(([s, e, t]) => [+s.toFixed(2), +e.toFixed(2), t])))
|
||||
console.log(`cues: ${opt.cues}`)
|
||||
}
|
||||
if (opt.plan) process.exit(0)
|
||||
|
||||
// 3. Caption band images.
|
||||
const band = opt['no-band'] ? 0 : Number(opt['caption-height'] ?? 96)
|
||||
if (band % 2 || vs.height % 2 || vs.width % 2) die('video width, height and --caption-height must all be even for H.264')
|
||||
const top = opt['caption-at'] === 'top'
|
||||
if (band) {
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const images = await captionImages(
|
||||
browser,
|
||||
cues.map((c) => c.text),
|
||||
{ width: vs.width, height: band, dir: work }
|
||||
)
|
||||
images.forEach((f, k) => (cues[k].image = f))
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Render: the video cut at every hold, each piece padded with its last frame, then the
|
||||
// lines delayed to their start and mixed.
|
||||
const filters = []
|
||||
const pieces = []
|
||||
let from = 0
|
||||
for (const p of [...holds.keys()].sort((a, b) => a - b)) {
|
||||
// fps= restores the frame rate FFmpeg 7's setpts clears; without it tpad adds no frames.
|
||||
filters.push(
|
||||
`[0:v]trim=start=${from.toFixed(3)}:end=${p.toFixed(3)},setpts=PTS-STARTPTS,fps=${fps},` +
|
||||
`tpad=stop_mode=clone:stop_duration=${holds.get(p).toFixed(3)}[p${pieces.length}]`
|
||||
)
|
||||
pieces.push(`[p${pieces.length}]`)
|
||||
from = p
|
||||
}
|
||||
if (duration - from > 1 / fps) {
|
||||
filters.push(`[0:v]trim=start=${from.toFixed(3)},setpts=PTS-STARTPTS[p${pieces.length}]`)
|
||||
pieces.push(`[p${pieces.length}]`)
|
||||
}
|
||||
filters.push(
|
||||
`${pieces.join('')}concat=n=${pieces.length}:v=1:a=0,fps=${fps}` +
|
||||
(band ? `,pad=${vs.width}:${vs.height + band}:0:${top ? band : 0}:color=#111111[c0]` : `,format=yuv420p[v]`)
|
||||
)
|
||||
const spoken = cues.filter((c) => c.file)
|
||||
if (band) {
|
||||
const firstImage = spoken.length + 1
|
||||
shown.forEach(([s, e], k) => {
|
||||
filters.push(
|
||||
`[c${k}][${firstImage + k}:v]overlay=0:${top ? 0 : vs.height}:` +
|
||||
`enable='between(t,${s.toFixed(3)},${e.toFixed(3)})'[c${k + 1}]`
|
||||
)
|
||||
})
|
||||
filters.push(`[c${cues.length}]format=yuv420p[v]`)
|
||||
}
|
||||
spoken.forEach((c, k) => filters.push(`[${k + 1}:a]adelay=${Math.round(c.start * 1000)}:all=1[a${k}]`))
|
||||
if (spoken.length)
|
||||
filters.push(`${spoken.map((_, k) => `[a${k}]`).join('')}amix=inputs=${spoken.length}:normalize=0,apad[a]`)
|
||||
execFileSync(
|
||||
'ffmpeg',
|
||||
[
|
||||
'-v', 'error', '-y', '-i', input,
|
||||
...spoken.flatMap((c) => ['-i', c.file]),
|
||||
...(band ? cues.flatMap((c) => ['-i', c.image]) : []),
|
||||
'-filter_complex', filters.join(';'),
|
||||
'-map', '[v]', ...(spoken.length ? ['-map', '[a]', '-c:a', 'aac', '-b:a', '128k'] : []),
|
||||
'-t', outDuration.toFixed(3),
|
||||
'-c:v', 'libx264', '-crf', '20', '-preset', 'medium', '-movflags', '+faststart',
|
||||
output
|
||||
],
|
||||
{ stdio: ['ignore', 'inherit', 'inherit'] }
|
||||
)
|
||||
console.log(output)
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "demo-video",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "demo-video",
|
||||
"dependencies": {
|
||||
"playwright": "1.65.1"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.65.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
|
||||
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.65.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.65.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
|
||||
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "demo-video",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"playwright": "1.65.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env node
|
||||
// Usage: node record.mjs <scenario.mjs> [out.mp4]
|
||||
// Prints the mp4 path on success; on a failed step, the step and a screenshot path.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, readdirSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve, dirname, basename } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { captionImages, die, launchBrowser, need, speak } from './lib.mjs'
|
||||
|
||||
const [scenarioPath, outArg] = process.argv.slice(2)
|
||||
if (!scenarioPath) die('usage: node record.mjs <scenario.mjs> [out.mp4]')
|
||||
const sc = (await import(pathToFileURL(resolve(scenarioPath)).href)).default
|
||||
const out = resolve(outArg ?? join(dirname(resolve(scenarioPath)), basename(scenarioPath, '.mjs') + '.mp4'))
|
||||
const work = mkdtempSync(join(tmpdir(), 'demo-video-'))
|
||||
const viewport = sc.viewport ?? { width: 1280, height: 720 }
|
||||
const voice = sc.voice === false ? 'none' : (sc.voice ?? 'Samantha')
|
||||
const BAND = sc.captionHeight ?? 96
|
||||
if (viewport.width % 2 || (viewport.height + BAND) % 2) die('viewport width and height + captionHeight must be even for H.264')
|
||||
need('ffmpeg', 'ffprobe', ...(voice === 'none' ? [] : ['say']))
|
||||
|
||||
// 1. Narration clips, before the browser starts, so recording time is not spent on TTS.
|
||||
const clips = sc.steps.map((s, i) => {
|
||||
if (!s.say) return null
|
||||
const { file, length } = speak(s.say, join(work, `say${i}.aiff`), { voice })
|
||||
return { file, ms: Math.round(length * 1000) }
|
||||
})
|
||||
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
// 2. Setup (login, seeding) runs unrecorded; its cookies carry into the recorded context.
|
||||
let storageState
|
||||
if (sc.setup) {
|
||||
const ctx = await browser.newContext({ viewport, baseURL: sc.baseURL })
|
||||
try {
|
||||
await sc.setup({ context: ctx, page: await ctx.newPage(), baseURL: sc.baseURL })
|
||||
} catch (err) {
|
||||
die(`setup failed: ${err.message.split('\n')[0]}`)
|
||||
}
|
||||
storageState = await ctx.storageState()
|
||||
await ctx.close()
|
||||
}
|
||||
const ctx = await browser.newContext({
|
||||
viewport,
|
||||
storageState,
|
||||
baseURL: sc.baseURL,
|
||||
recordVideo: { dir: work, size: viewport }
|
||||
})
|
||||
const page = await ctx.newPage()
|
||||
const t0rec = Date.now()
|
||||
|
||||
// Helpers handed to each step: a visible ring on what is clicked, so the viewer can follow.
|
||||
const ring = (loc) =>
|
||||
loc
|
||||
.evaluate((el) => {
|
||||
const r = el.getBoundingClientRect()
|
||||
const d = document.createElement('div')
|
||||
d.style.cssText = `position:fixed;left:${r.left - 4}px;top:${r.top - 4}px;width:${r.width + 8}px;height:${r.height + 8}px;border:3px solid #f43f5e;border-radius:8px;z-index:2147483646;pointer-events:none`
|
||||
document.body.appendChild(d)
|
||||
setTimeout(() => d.remove(), 900)
|
||||
})
|
||||
.catch(() => {})
|
||||
const loc = (t) => (typeof t === 'string' ? page.locator(t).first() : t)
|
||||
const helpers = {
|
||||
page,
|
||||
click: async (t) => {
|
||||
const l = loc(t)
|
||||
await l.scrollIntoViewIfNeeded()
|
||||
await ring(l)
|
||||
await page.waitForTimeout(500)
|
||||
await l.click()
|
||||
},
|
||||
hover: async (t) => {
|
||||
const l = loc(t)
|
||||
await l.scrollIntoViewIfNeeded()
|
||||
await ring(l)
|
||||
await l.hover()
|
||||
},
|
||||
wait: (ms) => page.waitForTimeout(ms)
|
||||
}
|
||||
|
||||
if (sc.start) await page.goto(sc.start, { waitUntil: 'networkidle' })
|
||||
await page.waitForTimeout(sc.settle ?? 800)
|
||||
const trimStart = Date.now() - t0rec
|
||||
const cues = []
|
||||
// Each caption shows from its step's start to the next captioned step's start.
|
||||
const captions = []
|
||||
|
||||
// 3. A step's narration starts before its action, and the step stays on screen until both
|
||||
// are done, so a caption never lands after what it describes.
|
||||
for (const [i, s] of sc.steps.entries()) {
|
||||
const at = Date.now() - t0rec
|
||||
if (s.say) {
|
||||
if (captions.length) captions.at(-1).end = at - trimStart
|
||||
captions.push({ text: s.say, start: at - trimStart })
|
||||
}
|
||||
try {
|
||||
if (s.do) await s.do(helpers)
|
||||
} catch (err) {
|
||||
const shot = join(work, `failed-step${i}.png`)
|
||||
await page.screenshot({ path: shot }).catch(() => {})
|
||||
console.error(`step ${i} failed (${s.say ?? 'no narration'}): ${err.message.split('\n')[0]}`)
|
||||
console.error(`screenshot: ${shot}`)
|
||||
process.exitCode = 1
|
||||
break
|
||||
}
|
||||
const left = (clips[i]?.ms ?? 0) + (sc.pad ?? 400) - (Date.now() - t0rec - at)
|
||||
if (left > 0) await page.waitForTimeout(left)
|
||||
if (s.hold) await page.waitForTimeout(s.hold)
|
||||
if (clips[i]?.file) cues.push({ file: clips[i].file, delay: at - trimStart })
|
||||
}
|
||||
await page.waitForTimeout(600)
|
||||
const total = (Date.now() - t0rec - trimStart) / 1000
|
||||
if (captions.length) captions.at(-1).end = total * 1000
|
||||
await ctx.close()
|
||||
if (process.exitCode) process.exit()
|
||||
|
||||
// 4. Captions in a band of their own beside the page, so they never cover it.
|
||||
const images = await captionImages(
|
||||
browser,
|
||||
captions.map((c) => c.text),
|
||||
{ width: viewport.width, height: BAND, dir: work }
|
||||
)
|
||||
|
||||
// 5. Mux: cut the pre-roll, add the caption band, show each caption during its step, lay
|
||||
// each narration clip at its step's start, encode an mp4.
|
||||
const video = join(work, readdirSync(work).find((f) => f.endsWith('.webm')))
|
||||
const args = ['-y', '-loglevel', 'error', '-ss', String(trimStart / 1000), '-i', video]
|
||||
images.forEach((f) => args.push('-i', f))
|
||||
cues.forEach((c) => args.push('-i', c.file))
|
||||
const top = sc.captionAt === 'top'
|
||||
const filters = [
|
||||
`[0:v]pad=${viewport.width}:${viewport.height + BAND}:0:${top ? BAND : 0}:color=#111111[v0]`
|
||||
]
|
||||
captions.forEach((c, k) => {
|
||||
const s = (c.start / 1000).toFixed(2)
|
||||
const e = (c.end / 1000).toFixed(2)
|
||||
filters.push(
|
||||
`[v${k}][${k + 1}:v]overlay=0:${top ? 0 : viewport.height}:enable='between(t,${s},${e})'[v${k + 1}]`
|
||||
)
|
||||
})
|
||||
const audioBase = captions.length + 1
|
||||
cues.forEach((c, k) => filters.push(`[${audioBase + k}:a]adelay=${c.delay}:all=1[a${k}]`))
|
||||
if (cues.length) {
|
||||
filters.push(`${cues.map((_, k) => `[a${k}]`).join('')}amix=inputs=${cues.length}:normalize=0[a]`)
|
||||
}
|
||||
args.push('-filter_complex', filters.join(';'), '-map', `[v${captions.length}]`)
|
||||
if (cues.length) args.push('-map', '[a]', '-c:a', 'aac')
|
||||
args.push('-t', total.toFixed(2), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', out)
|
||||
execFileSync('ffmpeg', args, { stdio: ['ignore', 'inherit', 'inherit'] })
|
||||
console.log(out)
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
# Terminal recordings
|
||||
|
||||
A CLI or TUI session recorded with vhs, optionally beside a browser that reacts to it, then its
|
||||
waits cut and a voice-over added. What each tool needs is in `SKILL.md` next to this file.
|
||||
|
||||
The take runs from a folder of the session scratchpad: the tape, the browser script, `vhs` and
|
||||
the agent all start there, so the files they write (mp4, webm, markers, screenshots) never land
|
||||
in a repo. The skill's scripts are called by their path,
|
||||
`node <repo>/.agents/skills/demo-video/<script>.mjs`, from wherever you are.
|
||||
|
||||
Order of work: plant the test data (it must match the story, see `SKILL.md`), record, compose,
|
||||
measure with `activity.mjs`, cut, measure the cut, narrate.
|
||||
|
||||
## Record the terminal (vhs)
|
||||
|
||||
`brew install vhs` (brings ttyd). Tape skeleton:
|
||||
|
||||
```
|
||||
Output term.mp4
|
||||
Set Shell zsh
|
||||
Set FontSize 15
|
||||
Set Width 820
|
||||
Set Height 820
|
||||
Set Padding 16
|
||||
Set TypingSpeed 35ms
|
||||
Hide
|
||||
Type "export MY_TOKEN=$(cat <scratch>/token); clear"
|
||||
Enter
|
||||
Show
|
||||
Type "mycli"
|
||||
Enter
|
||||
Wait+Screen@150s /text that stays once it is done/
|
||||
Sleep 3s
|
||||
```
|
||||
|
||||
- Run `vhs` from the tape's folder with a relative `Output`: an absolute path fails to parse
|
||||
(`Expected file path after output`).
|
||||
- Everything between `Hide` and `Show` runs off camera: logins, tokens, aliases. Never type a
|
||||
secret after `Show`.
|
||||
- `Wait+Screen@150s /regex/` waits until the regex matches anywhere on the screen, up to 150 s.
|
||||
Plain `Wait /regex/` reads only the last line; without `@<time>` the timeout is
|
||||
`Set WaitTimeout`. The typed command is on the screen too, so wait on text it does not
|
||||
contain (`echo "build $(echo finished)"`, then wait on `/build finished/`). A timed-out wait
|
||||
ends the run with only `recording failed` and no mp4.
|
||||
- Once a plain shell's output scrolls, vhs 0.12's `Wait+Screen` no longer sees the bottom rows:
|
||||
`wmill script run` printed its result below the first screenful and a wait on it timed out
|
||||
while the text was on screen. Make the terminal tall enough that the take never scrolls
|
||||
(`Set Height`), or `clear` off camera before the command. Codex renders in the normal
|
||||
buffer and scrolls too: for a long agent turn, a generous `Sleep` is safer than a wait, and
|
||||
the cut removes the idle time. To see what a failing wait missed, replace it with `Sleep` +
|
||||
`Screenshot f.png`.
|
||||
- A CLI that may open with a dialog (Codex's trust prompt, its "Background server has
|
||||
incompatible feature set" prompt after another Codex run changed its settings) is started in
|
||||
the `Hide` block and the dialog answered there (`Type "1"` picks "Run without daemon this
|
||||
time"), so the take opens on the ready prompt.
|
||||
- Wait on text that stays (a question, the final answer), not on a spinner or a status that
|
||||
flips back. `Sleep` only for what the tape cannot see, such as another process acting; the
|
||||
cut step removes idle time afterwards, so err long.
|
||||
- Keep long command lines off camera: define a function in the `Hide` block
|
||||
(`Type "mycli() { command mycli --flag … \"$@\"; }; clear"`) and type only `mycli` after
|
||||
`Show`. 500 characters at 35 ms is 17 s of typing that the cut step keeps.
|
||||
- A Type string holding both quote kinds goes in backticks: ``Type `cmd -c 'a="b"'` ``.
|
||||
- `Screenshot f.png` takes a still. macOS `date` has no `%3N`: take ms timestamps with
|
||||
`node -e 'console.log(Date.now())'`.
|
||||
|
||||
### The mp4 runs shorter than the session
|
||||
|
||||
vhs drops frames when the machine is busy, so its mp4 is shorter than the wall-clock session:
|
||||
151.7 s of video for about 160 s of session in one Codex take, the gap growing over the take.
|
||||
A wall-clock timestamp (an agent's log, a `Date.now()` marker) therefore points at the wrong
|
||||
moment of the video, more so the later it is. Use wall clock only for a first guess at the
|
||||
start of a take; place every cut, alignment and narration line from the picture, with
|
||||
`activity.mjs` (below).
|
||||
|
||||
## Codex CLI, unattended
|
||||
|
||||
```
|
||||
codex -a never -s read-only \
|
||||
-c check_for_update_on_startup=false \
|
||||
-c 'mcp_servers.<name>.url="https://<host>/<mcp path>"' \
|
||||
-c 'mcp_servers.<name>.bearer_token_env_var="MY_TOKEN"' \
|
||||
-c 'mcp_servers.<name>.default_tools_approval_mode="approve"'
|
||||
```
|
||||
|
||||
- `-a never` never asks; without `default_tools_approval_mode="approve"` every MCP tool call is
|
||||
refused instead of run.
|
||||
- The folder trust prompt cannot be skipped from `-c` (a `projects."<folder>".trust_level`
|
||||
override still shows it, in Codex 0.159). Accept it once for the take folder in a throwaway
|
||||
tape: `Type "codex"`, `Enter`, `Wait+Screen@30s /Trust and continue/`, `Enter`, `Sleep 5s`,
|
||||
`Ctrl+C`, `Ctrl+C`. The answer is saved in `~/.codex/config.toml` under the folder's real
|
||||
path (on macOS, `/private/tmp/…` for the scratchpad).
|
||||
- `check_for_update_on_startup=false` keeps the update banner out of the shot.
|
||||
- The token stays in an env var exported in the `Hide` block. Windmill's own MCP server is
|
||||
`<frontend URL>/api/mcp`, with a token that has the `mcp:all` scope.
|
||||
- Codex writes each session to `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` as it goes.
|
||||
|
||||
## Claude Code, unattended
|
||||
|
||||
```
|
||||
claude --strict-mcp-config --mcp-config <scratch>/mcp.json --allowedTools mcp__<name>
|
||||
```
|
||||
|
||||
- `mcp.json` is `{"mcpServers": {"<name>": {"type": "http", "url": "…", "headers":
|
||||
{"Authorization": "Bearer …"}}}}`. It holds the token, so keep it in the scratchpad and never
|
||||
`cat` it on camera.
|
||||
- `--allowedTools mcp__<name>` runs that server's tools without asking; anything else still
|
||||
asks, which a demo usually wants to show.
|
||||
- The folder trust prompt is saved per folder: accept it once in a throwaway tape
|
||||
(`Type "claude"`, `Enter`, `Wait+Screen@30s /trust/`, `Enter`, `Sleep 5s`, `Ctrl+C`, `Ctrl+C`).
|
||||
- Claude Code writes each session to `~/.claude/projects/<folder path, each non-alphanumeric character as ->/*.jsonl`.
|
||||
- Its layout differs from Codex's: measure its regions from crops (below) rather than reusing
|
||||
the Codex example.
|
||||
|
||||
## Drive a browser beside it
|
||||
|
||||
A Playwright script that records its own video and waits for the agent's output:
|
||||
|
||||
```js
|
||||
import { writeFileSync, existsSync } from 'node:fs'
|
||||
import { launchBrowser, waitForOutput } from '<repo>/.agents/skills/demo-video/lib.mjs'
|
||||
|
||||
const since = Date.now()
|
||||
writeFileSync('browser.pid', String(process.pid))
|
||||
writeFileSync('browser-start.txt', String(since))
|
||||
const browser = await launchBrowser()
|
||||
const ctx = await browser.newContext({
|
||||
viewport: { width: 900, height: 820 },
|
||||
recordVideo: { dir: 'bvideo', size: { width: 900, height: 820 } }
|
||||
})
|
||||
const page = await ctx.newPage()
|
||||
await page.request.post(`${BASE}/api/auth/login`, { data: { email: 'admin@windmill.dev', password: 'changeme' } })
|
||||
await page.goto(`${BASE}/some/page`)
|
||||
const [link] = await waitForOutput(/https:\/\/[^\s"\\]+\/the-page\?[^\s"\\]+/, { agent: 'codex', since })
|
||||
await page.goto(link)
|
||||
try {
|
||||
await page.getByText(/the success message/).waitFor({ timeout: 40000 })
|
||||
} catch {
|
||||
await page.screenshot({ path: 'browser-fail.png' })
|
||||
console.log('end state not seen:', (await page.locator('body').innerText()).slice(0, 400))
|
||||
}
|
||||
while (!existsSync('done.txt')) await new Promise((r) => setTimeout(r, 1000))
|
||||
await ctx.close()
|
||||
await browser.close()
|
||||
```
|
||||
|
||||
- `waitForOutput(pattern, { agent, cwd, since, timeout })` polls the logs of the `agent`
|
||||
(`'codex'` or `'claude'`) sessions started in `cwd` (default: the folder `node` was started
|
||||
from, so start the browser script from the folder vhs starts the agent in) and returns the
|
||||
match. Other agents on the machine write logs during the take too, a review in the same
|
||||
worktree or the recording agent itself, and only this folder's sessions count. It finds a log
|
||||
folder created during the take (Codex's per-day folder), so never build a dated path yourself.
|
||||
Logs are JSON: end the pattern before `"` and `\`. Take `since` when the script starts, before
|
||||
the agent can answer.
|
||||
- `since` skips log files last written before it, but a file written after it is searched from
|
||||
the top. Start a new agent session for each take: a resumed session's log still holds the
|
||||
links of earlier takes, and the first match wins.
|
||||
- The log holds the prompt and every tool result too, and the first match wins. Make the
|
||||
pattern match only the reply: tool results carry look-alike URLs (Windmill's deploy tool
|
||||
returns the page under the instance's base URL, not the host the prompt asked for), and the
|
||||
prompt must not contain the full link. Pin the host the prompt names and the path it leaves
|
||||
for the agent to fill in.
|
||||
- Log in with `page.request.post(...)` before the first navigation.
|
||||
- Run both, then a marker: `node browser.mjs & vhs term.tape; touch done.txt`. The script closes
|
||||
its context once `done.txt` exists, which finishes the webm.
|
||||
- Before every take, stop the driver left by the previous one: `kill $(cat browser.pid)`. A
|
||||
stray one matches the new session's output and acts on it first. Never `pkill -f browser.mjs`,
|
||||
which also kills the takes of other worktrees.
|
||||
- End the browser script on the state the page settles in (the success message), not a
|
||||
transient one, and keep the try/catch so a failed take says why.
|
||||
|
||||
## Compose side by side
|
||||
|
||||
```bash
|
||||
ffmpeg -i term.mp4 -ss <offset> -i browser.webm -filter_complex \
|
||||
"[0:v]fps=25,scale=820:820,setsar=1[a];[1:v]fps=25,scale=900:820,setsar=1[b];[a][b]hstack=2,format=yuv420p[v]" \
|
||||
-map "[v]" -t <terminal duration> -c:v libx264 -crf 12 -preset veryfast side.mp4
|
||||
```
|
||||
|
||||
- `<offset>`: seconds the browser recording began before the terminal one, trimmed off the
|
||||
browser input. Take a first guess from the start timestamps, then set it from frames: the
|
||||
page must open right after the link prints. Check the last interaction between the two sides
|
||||
as well; when the terminal has drifted (above) and the browser reacts visibly early, split
|
||||
the composition at that interaction or retime the browser with `setpts=<factor>*PTS`.
|
||||
- Same height on both sides. crf 12 keeps text sharp for the cut step, which encodes again.
|
||||
|
||||
## Watch regions
|
||||
|
||||
`regions.json` lists the areas to watch, in pixels of the input. Example: a Codex TUI, 820x820
|
||||
at font size 15, left of a 900-wide browser:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "name": "transcript", "x": 0, "y": 0, "w": 820, "h": 670, "min": 150 },
|
||||
{ "name": "status", "x": 0, "y": 670, "w": 820, "h": 35, "min": 30,
|
||||
"unlessLike": { "x": 40, "y": 675, "w": 72, "h": 22, "at": 40 } },
|
||||
{ "name": "composer", "x": 0, "y": 705, "w": 820, "h": 65, "min": 300 },
|
||||
{ "name": "browser", "x": 820, "y": 0, "w": 900, "h": 820, "min": 30 }
|
||||
]
|
||||
```
|
||||
|
||||
- Place the rows from two crops of the bottom of the terminal, one while the CLI works and one
|
||||
after: `ffmpeg -ss <t> -i side.mp4 -frames:v 1 -vf crop=820:180:0:640 f.png`.
|
||||
- Codex's `Working (12s • esc to interrupt)` row ticks and shimmers, so watch it only
|
||||
`unlessLike` its look at a time (`at`) it shows "Working": when the work ends, the newest line
|
||||
of the answer lands in that same row.
|
||||
- Composer: a cursor blink changes ~170 to 210 px per sample and typing 460 or more, so
|
||||
`min` 300. Leave the footer under it out.
|
||||
- A region whose `min` is too low keeps the whole take "active" and nothing gets cut: run
|
||||
`activity.mjs` first and look for a run of equal small counts every ~0.6 s (the blink).
|
||||
|
||||
## See when the screen changes
|
||||
|
||||
```bash
|
||||
node <repo>/.agents/skills/demo-video/activity.mjs side.mp4 regions.json [from] [to]
|
||||
```
|
||||
|
||||
prints, per region, the runs of change in seconds of that file: `48.0-48.5(4744)` is a change
|
||||
from 48.0 s to 48.5 s, 4744 pixels at most in one sample (`--raw` lists every sample). It
|
||||
samples exactly as `cut-waits.mjs` does. Use it for every time you write down: where an agent's
|
||||
work starts and ends (for `--cut=`), when the link prints and the page opens (for the offset),
|
||||
and, on the cut file, where each narration line goes.
|
||||
|
||||
## Cut the waits
|
||||
|
||||
```bash
|
||||
node <repo>/.agents/skills/demo-video/cut-waits.mjs side.mp4 out.mp4 regions.json --plan # cuts + check sheets
|
||||
node <repo>/.agents/skills/demo-video/cut-waits.mjs side.mp4 out.mp4 regions.json # render
|
||||
```
|
||||
|
||||
- Read every `<out>.cuts-N.png` row before rendering: the two frames of a row must show the
|
||||
same content, apart from timers and the cursor. Text appearing between them means a region
|
||||
missed it: fix the region and rerun `--plan`.
|
||||
- Defaults: stretches of 3 s or more shrink to 1 s (0.7 s kept before the cut, 0.3 s after), 5 s
|
||||
kept after the last change, and a "⏩ N s later" note at the top centre for 1.4 s after each
|
||||
cut. Override with `--min-gap`, `--head`, `--tail`, `--end-hold`, `--label-y`.
|
||||
- What changes stays: typing, tool calls appearing, links, the page being filled, the final
|
||||
answer. Time spent waiting on a tool is cut; the call and its result both stay on screen.
|
||||
- An AI agent's own work is not idle to the measurement: its tool calls keep scrolling in while
|
||||
the viewer only waits for the answer. Remove those stretches with `--cut=<from>-<to>`
|
||||
(seconds of the input, repeatable), from just after the agent's first reply to just before the
|
||||
output the viewer needs (its message, the link, the final answer). Take both bounds from
|
||||
`activity.mjs` on `side.mp4`, never from the agent's log timestamps (the mp4 drifts from the
|
||||
wall clock), and confirm them on the check sheet. A forced cut gets the same note.
|
||||
- Silent inputs only: the output carries no audio. Add the voice-over after cutting.
|
||||
|
||||
## Add a voice-over
|
||||
|
||||
```bash
|
||||
node <repo>/.agents/skills/demo-video/narrate.mjs out.mp4 lines.json narrated.mp4 --plan --regions=out.regions.json
|
||||
node <repo>/.agents/skills/demo-video/narrate.mjs out.mp4 lines.json narrated.mp4
|
||||
```
|
||||
|
||||
lines.json: `[{ "at": 0.3, "text": "One sentence." }, ...]`, `at` in seconds of the cut video.
|
||||
Take each `at` from `activity.mjs out.mp4 out.regions.json`: 0.3 s before the change the line
|
||||
describes. `out.regions.json` is written by `cut-waits.mjs`: the same regions, with each
|
||||
`unlessLike.at` moved onto the cut's timeline. If that `at` fell inside a cut, it now points at
|
||||
the first frame after it: check that frame still shows the look to ignore, or pick a new `at`.
|
||||
|
||||
- Each line is spoken by macOS `say` (`--voice`, default Samantha, ~3 words per second;
|
||||
`--voice=none` for captions only). When a line still runs at the next line's `at`, the video
|
||||
holds the frame at that `at` until it ends, so speech never runs over a later step.
|
||||
- A hold only waits at the next line's `at`: whatever happens between the previous line's `at`
|
||||
and that moment plays while the previous line is still speaking. A line anchored after its
|
||||
change therefore starts once the change is already over. `--plan` with `--regions` flags each
|
||||
line whose `at` falls just after a change started and prints the `at` to use instead.
|
||||
- `--plan` also flags each hold longer than 1 s: the line before it is too long for its stretch.
|
||||
Shorten that line rather than accept the freeze.
|
||||
- Read the narrated frames at each hold before delivering.
|
||||
- Each line is burned in as a caption in a band of its own below the video, from its start
|
||||
until the next line starts, so captions never cover the recording: a 1280x720 cut comes out
|
||||
1280x816. `--caption-at=top` puts the band above, `--caption-height` sets its height (default
|
||||
96, two lines of text; keep it even for H.264), `--no-band` leaves the video its own size.
|
||||
- `--vtt=<file>` writes the lines as WebVTT on the output's timeline; `--cues=<file>` writes
|
||||
them as JSON for a text track added from inline JS (see Deliver in `SKILL.md`).
|
||||
@@ -135,7 +135,7 @@ sufficient — see "Flip, or ask first" below. The one standing exception is an
|
||||
leave that PR in draft (usually so it can be tested first) — honour it for that PR, and don't
|
||||
carry it over to the next one.
|
||||
|
||||
1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes 10–30 min; you are woken when it exits — do not stop the session or poll in the foreground while it runs):
|
||||
1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes about 10 min, 20 at most; you are woken when it exits — do not stop the session or poll in the foreground while it runs):
|
||||
|
||||
```bash
|
||||
bash .agents/skills/pr/review-round.sh <PR_NUMBER>
|
||||
@@ -143,6 +143,11 @@ carry it over to the next one.
|
||||
|
||||
It comments `/review` on the PR — which runs the Codex, Claude and Pi CI reviewers even on a draft — waits for the spawned `PR Review Commands` workflow run(s) to complete, then prints one verdict line per reviewer and saves the full review comments to files.
|
||||
|
||||
Waiting rules — a session that breaks one sits idle on results the user can already see:
|
||||
- **Use the waiter, not a loop of your own.** It always exits: as soon as the Codex, Claude and Pi verdicts are posted, once the round's run completes (failed jobs included), at a 20-minute deadline with whatever was posted, or non-zero when no run appeared or GitHub kept erroring — treat a non-zero exit as "look yourself", not "no reviews". A hand-written loop waiting for "a comment from each reviewer" never ends when one reviewer dies (capacity errors, cancelled jobs), since a dead job posts nothing.
|
||||
- **If your harness does not wake you when a background command exits, run the waiter in the foreground** with a timeout of at least 25 minutes. Backgrounding it and ending your turn then means nobody ever reads the result.
|
||||
- **Act on a missing reviewer immediately.** Reviewers that never start or hang are common. The waiter names each reviewer with no review and the jobs that did not finish cleanly; re-trigger each missing one at once with a `/codex`, `/claude` or `/pi` PR comment and run the waiter again, rather than waiting longer.
|
||||
|
||||
`/review` (and `/codex`) are **idempotent per head SHA**: if a running or successful review already covers the current head, they skip that agent and post nothing new — the waiter reads the existing verdict for that head, so a skipped agent is *not* a missing one. A cancelled/failed head run is re-run in place; a fresh run is launched only when nothing covers the head. So an unchanged-head re-review is a near no-op, not a new round — push a commit to get genuinely fresh reviews.
|
||||
|
||||
2. **Judge the round.** Codex is mandatory; Claude, Pi and cubic count whenever they posted. Every review starts with one of the three `REVIEW.md` verdicts:
|
||||
|
||||
@@ -7,19 +7,20 @@
|
||||
# Comments `/review` on the PR (works on drafts), waits for the spawned
|
||||
# "PR Review Commands" workflow run(s) to complete, then prints one verdict
|
||||
# line per reviewer and saves each full review comment to a file. A round
|
||||
# takes 10-30 minutes: run this in the background and act on its output when
|
||||
# takes about 10 minutes, 20 at most: run this in the background and act on its output when
|
||||
# it exits, per the pr skill ("Review rounds").
|
||||
set -euo pipefail
|
||||
|
||||
REPO=${REPO:-$(gh repo view --json nameWithOwner --jq .nameWithOwner)}
|
||||
PR=${1:-$(gh pr view --json number --jq .number)}
|
||||
PR_TITLE=$(gh pr view "$PR" --repo "$REPO" --json title --jq .title)
|
||||
|
||||
# Timestamp of the trigger comment, straight from GitHub, so local clock skew
|
||||
# can't make the run/comment filters below miss part of the round.
|
||||
TRIGGER_TIME=$(gh api "repos/$REPO/issues/$PR/comments" -f body='/review' --jq .created_at)
|
||||
echo "Review round triggered on $REPO#$PR at $TRIGGER_TIME"
|
||||
|
||||
# Retry wrapper for one-off gh/API hiccups: a 45-minute wait must not die on
|
||||
# Retry wrapper for one-off gh/API hiccups: a 20-minute wait must not die on
|
||||
# a single transient failure.
|
||||
retry() {
|
||||
local attempt
|
||||
@@ -31,21 +32,39 @@ retry() {
|
||||
}
|
||||
|
||||
# The /review comment spawns one "PR Review Commands" run holding the
|
||||
# claude/codex/pi jobs. Runs aren't linked to a PR, so wait on every run of
|
||||
# that workflow created after the trigger: a concurrent round on another PR
|
||||
# can only delay the answer, never truncate it. Every issue comment on any PR
|
||||
# spawns a fast-completing parse run of the same workflow, so the round's own
|
||||
# run may briefly lag the listing while unrelated runs already show completed:
|
||||
# require the all-completed state to hold past a floor and across two
|
||||
# consecutive polls before trusting it.
|
||||
DEADLINE=$(( $(date +%s) + 45 * 60 ))
|
||||
# claude/codex/pi jobs. Runs aren't linked to a PR, but an issue_comment run's
|
||||
# display title is the PR's title: match on it, since waiting on every run
|
||||
# after the trigger means a stuck reviewer on any other PR holds this round
|
||||
# to the deadline. Every comment on this PR (the reviewers' own
|
||||
# included) spawns a fast-completing parse run, so the round's own run may
|
||||
# briefly lag the listing while those already show completed: require the
|
||||
# all-completed state to hold past a floor and across two consecutive polls.
|
||||
#
|
||||
# Reviews land 6-10 minutes in. A reviewer that never starts or hangs is common
|
||||
# and only a human re-trigger fixes it, so stop early: as soon as all three
|
||||
# verdicts are posted, else at 20 minutes, naming the jobs still unfinished.
|
||||
VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)'
|
||||
# Claude edits a placeholder comment in place, hence updated_at.
|
||||
all_verdicts_in() {
|
||||
gh api "repos/$REPO/issues/$PR/comments?per_page=100" --paginate 2>/dev/null \
|
||||
| jq -s -e --arg t "$TRIGGER_TIME" --arg re "$VERDICT_RE" '
|
||||
[.[][] | select(.updated_at > $t) | select(.body // "" | test($re))] as $c
|
||||
| ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Codex Review"))))
|
||||
and ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Pi Review"))))
|
||||
and ($c | any(.user.login == "claude[bot]"))' >/dev/null
|
||||
}
|
||||
DEADLINE=$(( $(date +%s) + 20 * 60 ))
|
||||
NO_RUN_DEADLINE=$(( $(date +%s) + 5 * 60 ))
|
||||
MIN_WAIT_UNTIL=$(( $(date +%s) + 3 * 60 ))
|
||||
STABLE=0
|
||||
SEEN=0
|
||||
ALL_IN=0
|
||||
ROUND_RUNS='[]'
|
||||
FAILURES=0
|
||||
while :; do
|
||||
if RUNS=$(gh run list --repo "$REPO" --workflow=pr-review-commands.yml \
|
||||
--created ">=$TRIGGER_TIME" --limit 100 --json status); then
|
||||
--created ">=$TRIGGER_TIME" --limit 500 --json databaseId,status,displayTitle \
|
||||
--jq "[.[] | select(.displayTitle == $(jq -Rn --arg t "$PR_TITLE" '$t'))]"); then
|
||||
FAILURES=0
|
||||
else
|
||||
FAILURES=$(( FAILURES + 1 ))
|
||||
@@ -58,6 +77,13 @@ while :; do
|
||||
continue
|
||||
fi
|
||||
TOTAL=$(jq length <<<"$RUNS")
|
||||
# The limit applies before the title filter, so on a busy repo this PR's run
|
||||
# can age out of the listing: once seen, never report it as missing.
|
||||
if [ "$TOTAL" -gt 0 ]; then SEEN=1; ROUND_RUNS=$RUNS; fi
|
||||
if all_verdicts_in; then
|
||||
ALL_IN=1
|
||||
break
|
||||
fi
|
||||
PENDING=$(jq '[.[] | select(.status != "completed")] | length' <<<"$RUNS")
|
||||
NOW=$(date +%s)
|
||||
if [ "$TOTAL" -gt 0 ] && [ "$PENDING" -eq 0 ] && [ "$NOW" -gt "$MIN_WAIT_UNTIL" ]; then
|
||||
@@ -68,12 +94,12 @@ while :; do
|
||||
else
|
||||
STABLE=0
|
||||
fi
|
||||
if [ "$TOTAL" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then
|
||||
if [ "$SEEN" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then
|
||||
echo "ERROR: no 'PR Review Commands' run appeared within 5 minutes of the /review comment; check that the comment author has write access and the workflow is enabled." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$NOW" -gt "$DEADLINE" ]; then
|
||||
echo "WARNING: review round still pending after 45 minutes; reporting whatever has been posted so far." >&2
|
||||
echo "WARNING: review round still pending after 20 minutes; reporting whatever has been posted so far." >&2
|
||||
break
|
||||
fi
|
||||
sleep 60
|
||||
@@ -100,7 +126,7 @@ head_run_state() {
|
||||
# A re-run-in-place review lands on a head-tied run that finishes after the fast
|
||||
# pr-review-commands run, so let those settle before reading verdicts.
|
||||
for wf in codex-pr-review.yml pi-pr-review.yml pr-ready-review.yml; do
|
||||
while :; do
|
||||
while [ "$ALL_IN" -eq 0 ]; do
|
||||
case "$(head_run_state "$wf")" in
|
||||
""|"completed "*) break ;;
|
||||
*) if [ "$(date +%s)" -gt "$DEADLINE" ]; then break; fi; sleep 30 ;;
|
||||
@@ -121,8 +147,6 @@ REVIEWS_RAW=$(retry gh api "repos/$REPO/pulls/$PR/reviews?per_page=100" --pagina
|
||||
jq -s --arg t "$TRIGGER_TIME" '[.[][] | select((.submitted_at // "") > $t)]' \
|
||||
<<<"$REVIEWS_RAW" > "$OUT_DIR/pr-reviews.json"
|
||||
|
||||
VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)'
|
||||
|
||||
body_by_header() { # <file> <header-substring>
|
||||
jq -r --arg h "$2" '[.[] | select(.body // "" | contains($h))] | last | .body // empty' "$1"
|
||||
}
|
||||
@@ -144,7 +168,11 @@ verdict_body() { # <header|login> <value> <workflow>
|
||||
report() { # <reviewer-name> <comment-body>
|
||||
local name=$1 body=$2 verdict
|
||||
if [ -z "$body" ]; then
|
||||
echo "$name: (no review posted for this head)"
|
||||
if [ "$name" = cubic ]; then
|
||||
echo "$name: (no review posted for this head)"
|
||||
else
|
||||
echo "$name: (no review posted for this head; re-trigger now with a '/$name' PR comment)"
|
||||
fi
|
||||
return
|
||||
fi
|
||||
printf '%s\n' "$body" > "$OUT_DIR/$name.md"
|
||||
@@ -167,6 +195,17 @@ fi
|
||||
report cubic "$CUBIC_BODY"
|
||||
echo
|
||||
echo "Full round output: $OUT_DIR (comments.json, pr-reviews.json, one .md per reviewer)"
|
||||
if [ "$ALL_IN" -eq 0 ]; then
|
||||
UNFINISHED=$(for id in $(jq -r '.[].databaseId' <<<"$ROUND_RUNS"); do
|
||||
gh run view "$id" --repo "$REPO" --json jobs --jq '.jobs[]
|
||||
| select(.status != "completed" or (.conclusion | IN("success", "skipped") | not))
|
||||
| " \(.name): \(.status) \(.conclusion // "") since \(.startedAt // "-")"' 2>/dev/null || true
|
||||
done)
|
||||
if [ -n "$UNFINISHED" ]; then
|
||||
echo "Review jobs that did not finish cleanly:"
|
||||
printf '%s\n' "$UNFINISHED"
|
||||
fi
|
||||
fi
|
||||
if [ -z "$CODEX_BODY" ]; then
|
||||
echo "WARNING: no Codex verdict for $HEAD_SHA - its head run is not green (cancelled/failed/absent, not merely skipped-because-already-reviewed). Re-trigger with a '/codex' PR comment (re-runs the interrupted run in place, or launches one) and wait again." >&2
|
||||
fi
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../.agents/skills/demo-video/SKILL.md
|
||||
@@ -44,6 +44,16 @@ jobs:
|
||||
--health-cmd "mysqladmin ping -h localhost" --health-interval 10s
|
||||
--health-timeout 5s --health-retries 5
|
||||
steps:
|
||||
# Linking one full-graph binary per tests/*.rs file fills the runner disk
|
||||
# ("No space left on device" in cargo test (build)). Drop preinstalled
|
||||
# toolchains no test uses before anything is installed or restored.
|
||||
- name: Free disk space
|
||||
working-directory: /
|
||||
run: |
|
||||
df -h /
|
||||
sudo rm -rf /usr/local/lib/android /opt/ghc /usr/local/.ghcup /usr/share/swift \
|
||||
/usr/local/share/boost /opt/hostedtoolcache/CodeQL || true
|
||||
df -h /
|
||||
- uses: actions/checkout@v4.4.0
|
||||
- uses: actions/setup-dotnet@v4.3.1
|
||||
with:
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "1.882.0"
|
||||
".": "1.884.1"
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ Open-source platform for internal tools, workflows, API integrations, background
|
||||
- **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. For a Codex-driven pass that mirrors the `codex-pr-review` GitHub action against your unpushed work (committed + uncommitted) before you push, use `/local-review-codex` (`.agents/skills/local-review-codex/`) — same `REVIEW.md` policy, `gpt-6.1-sol` model and `xhigh` reasoning as the action; requires the `codex` CLI >= 0.159.3.
|
||||
- **Demo videos**: the `demo-video` skill (`.agents/skills/demo-video/`) records a narrated browser walkthrough with Playwright, or a terminal session (Codex, Claude Code, `wmill`) with vhs beside the browser it drives, cuts the idle waits, and covers putting the result in an Artifact or a PR body. Needs Homebrew `ffmpeg`, macOS `say` for speech, and `vhs` for terminal takes.
|
||||
- **Domain guides**: `.claude/skills/native-trigger/`
|
||||
- **Brand/UI guidelines**: `frontend/brand-guidelines.md`
|
||||
- **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does.
|
||||
|
||||
@@ -1,5 +1,74 @@
|
||||
# Changelog
|
||||
|
||||
## [1.884.1](https://github.com/windmill-labs/windmill/compare/v1.884.0...v1.884.1) (2026-11-25)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* unblock backend CI and deno jobs with a script path ([#12648](https://github.com/windmill-labs/windmill/issues/12648)) ([783d89a](https://github.com/windmill-labs/windmill/commit/783d89a92c6a854d76b24c4a54e23c1a84172502))
|
||||
|
||||
## [1.884.0](https://github.com/windmill-labs/windmill/compare/v1.883.0...v1.884.0) (2026-11-24)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add SAP icon for the sap_hana resource type ([#12633](https://github.com/windmill-labs/windmill/issues/12633)) ([a888954](https://github.com/windmill-labs/windmill/commit/a8889548144110cd2d92a2687d3042365dbe9f3b))
|
||||
* ask for secrets and connect services in the AI chat through a secure card ([#12575](https://github.com/windmill-labs/windmill/issues/12575)) ([9536cfd](https://github.com/windmill-labs/windmill/commit/9536cfdab198dbe189b5181e87934a8ac5f9956a))
|
||||
* full-screen image viewer with zoom, pan, copy and download ([#12634](https://github.com/windmill-labs/windmill/issues/12634)) ([3908150](https://github.com/windmill-labs/windmill/commit/39081509dd9158c5858a616ff8039d243bef8b2b))
|
||||
* give each AI session its own model and effort ([#12632](https://github.com/windmill-labs/windmill/issues/12632)) ([564fdf7](https://github.com/windmill-labs/windmill/commit/564fdf7d2ded8d84fab9172ea6f820954ce1310b))
|
||||
* group consecutive draft writes in the AI chat transcript ([#12597](https://github.com/windmill-labs/windmill/issues/12597)) ([f399a22](https://github.com/windmill-labs/windmill/commit/f399a22c1034ffeb1634fd3a704d5ee44f60f076))
|
||||
* rerun only the failed iterations of a parallel for-loop or branch-all ([#12590](https://github.com/windmill-labs/windmill/issues/12590)) ([6a0283a](https://github.com/windmill-labs/windmill/commit/6a0283a9506b5328466a3983e3b0ec949f88464e))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* bind datatable() args as literals and read _FLOW_PATH on previews ([#12638](https://github.com/windmill-labs/windmill/issues/12638)) ([a8b2228](https://github.com/windmill-labs/windmill/commit/a8b22287533ca72c3c09d59d5c0facadd2973703))
|
||||
* give jailed uv lock its own cache and copy no symlinked deps ([#12641](https://github.com/windmill-labs/windmill/issues/12641)) ([a2de197](https://github.com/windmill-labs/windmill/commit/a2de1979bb895b928693b23b312802dd026e8887))
|
||||
* pass ai agent tools only the inputs in their schema ([#12642](https://github.com/windmill-labs/windmill/issues/12642)) ([b23037e](https://github.com/windmill-labs/windmill/commit/b23037e3e1b6d4b154c3d51a6bf4721eade3bddc))
|
||||
* pin definer function search_path and check sql contextual vars ([#12640](https://github.com/windmill-labs/windmill/issues/12640)) ([2df2c83](https://github.com/windmill-labs/windmill/commit/2df2c83313c871567de448e33acecffda4ad459a))
|
||||
* read request bodies as plain json and keep cancel reasons literal ([#12646](https://github.com/windmill-labs/windmill/issues/12646)) ([114d684](https://github.com/windmill-labs/windmill/commit/114d68456e19b71b3f5d635829b568e6e1edbca9))
|
||||
* scope app dependency relock to the job's workspace ([#12644](https://github.com/windmill-labs/windmill/issues/12644)) ([1683b80](https://github.com/windmill-labs/windmill/commit/1683b801859a15884e139e91f3366d57ab8f8157))
|
||||
* suggest filter values by their label and in any case ([#12582](https://github.com/windmill-labs/windmill/issues/12582)) ([cf8a1c3](https://github.com/windmill-labs/windmill/commit/cf8a1c38500e64567e5e8fd496feee5bf2e3b0b7))
|
||||
|
||||
## [1.883.0](https://github.com/windmill-labs/windmill/compare/v1.882.0...v1.883.0) (2026-11-24)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* alert on same-tag wait deadlocks and fail the waiting parent ([#12613](https://github.com/windmill-labs/windmill/issues/12613)) ([304f912](https://github.com/windmill-labs/windmill/commit/304f9121835655c35091b3a98ddcb6b579548115))
|
||||
* **cli:** 30-day CLI login tokens with expiry picker and token roll ([#12621](https://github.com/windmill-labs/windmill/issues/12621)) ([e810cbb](https://github.com/windmill-labs/windmill/commit/e810cbb93a1847ba823cc5088bc3f88ed7552090))
|
||||
* fold consecutive test runs of one item in the ai chat ([#12599](https://github.com/windmill-labs/windmill/issues/12599)) ([924d9b7](https://github.com/windmill-labs/windmill/commit/924d9b7755485d59379f1ff745a051ad5da3b820))
|
||||
* keep mcp consent page open with a copyable callback for localhost clients ([#12619](https://github.com/windmill-labs/windmill/issues/12619)) ([3194184](https://github.com/windmill-labs/windmill/commit/3194184c521c2ad4a99529f6c7422c14af3ebb84))
|
||||
* let the workspace error handler skip jobs started from the UI ([#12624](https://github.com/windmill-labs/windmill/issues/12624)) ([ade2a55](https://github.com/windmill-labs/windmill/commit/ade2a55e862caa78dfca09646aac74670cbfd901))
|
||||
* **nsjail:** make rlimit_fsize configurable per worker (NSJAIL_RLIMIT_FSIZE_MB) ([#12609](https://github.com/windmill-labs/windmill/issues/12609)) ([e6d9ff8](https://github.com/windmill-labs/windmill/commit/e6d9ff8f9596f7529c899f9f8fd1d34a91698792))
|
||||
* pick how to connect a resource in a wizard, one row per provider ([#12418](https://github.com/windmill-labs/windmill/issues/12418)) ([2ca87ef](https://github.com/windmill-labs/windmill/commit/2ca87efdb8527d591865125db42d9f6f3b42bee3))
|
||||
* redesign the token scope picker and add a scope search ([#12595](https://github.com/windmill-labs/windmill/issues/12595)) ([344694a](https://github.com/windmill-labs/windmill/commit/344694ada73c857724cb8244e7e7f8188efa2611))
|
||||
* restore working in a new fork from the Home session composer ([#12559](https://github.com/windmill-labs/windmill/issues/12559)) ([1fb70c4](https://github.com/windmill-labs/windmill/commit/1fb70c4fab5379874c42d349120ed2e2db9a0806))
|
||||
* show who deployed each version in script and flow history ([#12587](https://github.com/windmill-labs/windmill/issues/12587)) ([ba0ef82](https://github.com/windmill-labs/windmill/commit/ba0ef82eedf97ce310967134b9200c4f93e7c3db))
|
||||
* store refreshed installation JWT for managed GitHub app git sync ([#12592](https://github.com/windmill-labs/windmill/issues/12592)) ([c3cb814](https://github.com/windmill-labs/windmill/commit/c3cb814e9e99c414a56fac9e1874f4eed5c1f42c))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* apply a changed default value to the Time and Date Select app components ([#12581](https://github.com/windmill-labs/windmill/issues/12581)) ([17fe165](https://github.com/windmill-labs/windmill/commit/17fe165d605c6043afd53cdd83a88b63deae3d59))
|
||||
* **cli:** require the dot in .fetch.ts/.bun.ts/.deno.ts language suffixes ([#12583](https://github.com/windmill-labs/windmill/issues/12583)) ([ff8f2e0](https://github.com/windmill-labs/windmill/commit/ff8f2e05fb20cf4f5e931f7169856217c8088312))
|
||||
* derive chat lookup grouping from tool definitions ([#12596](https://github.com/windmill-labs/windmill/issues/12596)) ([3a720da](https://github.com/windmill-labs/windmill/commit/3a720da989416caabed08e9659b81f04cf510ac1))
|
||||
* generate branch predicates from the branch node ([#12623](https://github.com/windmill-labs/windmill/issues/12623)) ([f9ade48](https://github.com/windmill-labs/windmill/commit/f9ade481dae05bdbb0ef876939bcd3e5b7d02da4))
|
||||
* harden telemetry submission ([#12606](https://github.com/windmill-labs/windmill/issues/12606)) ([1d3fcb4](https://github.com/windmill-labs/windmill/commit/1d3fcb4a06c26f0007a95fbe40cc55761d4988f5))
|
||||
* let a Date & Time input become valid again once a later day is picked ([#12584](https://github.com/windmill-labs/windmill/issues/12584)) ([508b9f8](https://github.com/windmill-labs/windmill/commit/508b9f84f3a9ab80eb37db48c9a1e6c480d0ec55))
|
||||
* make schedule and trigger lists usable on small screens ([#12594](https://github.com/windmill-labs/windmill/issues/12594)) ([1fe3704](https://github.com/windmill-labs/windmill/commit/1fe370451576689215678e4da9098b4b342d1220))
|
||||
* raise windmill-worker macro recursion limit so main builds again ([#12612](https://github.com/windmill-labs/windmill/issues/12612)) ([db218c0](https://github.com/windmill-labs/windmill/commit/db218c0d3aff6476643fbf98188cf743a5c285ea))
|
||||
* serialize BigInt and non-finite elements of sql template arrays ([#12616](https://github.com/windmill-labs/windmill/issues/12616)) ([5044d02](https://github.com/windmill-labs/windmill/commit/5044d02325ff788bb5316e115fc52b377ef3c237))
|
||||
* steps inside expanded subflows on the flow detail and run pages ([#12591](https://github.com/windmill-labs/windmill/issues/12591)) ([a5c7dd4](https://github.com/windmill-labs/windmill/commit/a5c7dd4f699c85190eca5cc88717d85fcc28cfae))
|
||||
* stop AI sessions rewriting the tab's copy of the AI settings ([#12615](https://github.com/windmill-labs/windmill/issues/12615)) ([a87ab5d](https://github.com/windmill-labs/windmill/commit/a87ab5d6acfac1f175e4abac90e931de91ae4d50))
|
||||
* use the session's AI config in session editor tabs ([#12593](https://github.com/windmill-labs/windmill/issues/12593)) ([3ceff81](https://github.com/windmill-labs/windmill/commit/3ceff81e72541d63a29029fd8b296c318cd64b77))
|
||||
* **worker:** fall back to host RAM when cgroup v2 memory.max is max ([#12588](https://github.com/windmill-labs/windmill/issues/12588)) ([7d5a09a](https://github.com/windmill-labs/windmill/commit/7d5a09af83d611b06bff881d5c9d6dc57204b567))
|
||||
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* **worker:** read cgroup and proc files directly instead of spawning cat ([#12614](https://github.com/windmill-labs/windmill/issues/12614)) ([3495d42](https://github.com/windmill-labs/windmill/commit/3495d42f78250572b913d15c0209cb9598f89646))
|
||||
|
||||
## [1.882.0](https://github.com/windmill-labs/windmill/compare/v1.881.1...v1.882.0) (2026-11-22)
|
||||
|
||||
|
||||
|
||||
@@ -240,6 +240,20 @@ dismissed, so `userAnswers: []` dismisses every question. Without it the tool re
|
||||
it cannot ask, and the model usually carries on with its own guess, which makes "asks
|
||||
before creating anything" impossible to assert.
|
||||
|
||||
`runtime.secretRequests` does the same for the `request_secret` card, one answer per card in
|
||||
the order they open, and a card past the last answer is dismissed:
|
||||
|
||||
```yaml
|
||||
secretRequests:
|
||||
- action: save # or dismiss
|
||||
fields: { host: db.example.com } # non-secret fields the user fills on the card
|
||||
check: { ok: false, error: password authentication failed } # the card's connection test
|
||||
```
|
||||
|
||||
`save` goes through the card's own save, so the secret variables (with placeholder values)
|
||||
and the resource are created in the workspace, deployed, and the model reads the result the
|
||||
chat would give it. `check` is reported as is; no connection test runs.
|
||||
|
||||
`runtime.profile` runs a session-chat case (`sessionChat: true`) as a non-admin role
|
||||
instead of full access: the prompt, toolset and tool schemas are cut as production's
|
||||
`capabilitiesForRole` cuts them, and the workspace's `operator_settings` are seeded for the
|
||||
|
||||
@@ -23,7 +23,14 @@ import { filterSessionTools } from "../../../../../frontend/src/lib/components/c
|
||||
import { usersWorkspaceStore } from "../../../../../frontend/src/lib/stores";
|
||||
import { resolveResourceTypeSync } from "../../../../../frontend/src/lib/components/copilot/chat/script/core";
|
||||
import { appendPlanModeInstructions } from "../../../../../frontend/src/lib/components/copilot/chat/planMode";
|
||||
import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared";
|
||||
import type {
|
||||
Tool as ProductionTool,
|
||||
ToolCallbacks,
|
||||
} from "../../../../../frontend/src/lib/components/copilot/chat/shared";
|
||||
import {
|
||||
saveSecretRequest,
|
||||
secretFieldsOf,
|
||||
} from "../../../../../frontend/src/lib/components/copilot/chat/secretRequest";
|
||||
import { createEvalPlanTools } from "./planModeTools";
|
||||
import { createEvalPipelineEditors } from "./evalPipelineEditors";
|
||||
import { pipelineTools } from "../../../../../frontend/src/lib/components/copilot/chat/pipeline/core";
|
||||
@@ -40,6 +47,7 @@ import {
|
||||
} from "./evalPreviewTabs";
|
||||
import type {
|
||||
EvalCaseProfile,
|
||||
EvalSecretRequestAnswer,
|
||||
ModeRunContext,
|
||||
PipelineRunSpec,
|
||||
} from "../../../../core/types";
|
||||
@@ -144,6 +152,7 @@ export interface GlobalEvalOptions {
|
||||
model?: string;
|
||||
maxIterations?: number;
|
||||
userAnswers?: string[];
|
||||
secretRequests?: EvalSecretRequestAnswer[];
|
||||
provider?: AIProvider;
|
||||
backend: WindmillBackendSettings;
|
||||
// Artifacts the session already holds when the run starts.
|
||||
@@ -153,6 +162,37 @@ export interface GlobalEvalOptions {
|
||||
runContext?: ModeRunContext;
|
||||
}
|
||||
|
||||
/** The user's side of the secret card: an answer saves through the card's own save, with a
|
||||
* placeholder for each secret, or dismisses it; a card past the last answer is dismissed. */
|
||||
function scriptedSecretCard(
|
||||
answers: EvalSecretRequestAnswer[],
|
||||
): NonNullable<ToolCallbacks["requestSecret"]> {
|
||||
const pending = [...answers];
|
||||
return async (_toolId, request) => {
|
||||
const answer = pending.shift();
|
||||
if (!answer || answer.action === "dismiss") return undefined;
|
||||
const outcome = await saveSecretRequest(
|
||||
request,
|
||||
{
|
||||
path: request.path,
|
||||
replace: request.replace ?? false,
|
||||
secrets: Object.fromEntries(
|
||||
secretFieldsOf(request).map((f) => [
|
||||
f.field,
|
||||
`eval-secret-${f.field || "value"}`,
|
||||
]),
|
||||
),
|
||||
fields: request.resource && {
|
||||
...request.resource.value,
|
||||
...answer.fields,
|
||||
},
|
||||
},
|
||||
new Set(),
|
||||
);
|
||||
return answer.check ? { ...outcome, check: answer.check } : outcome;
|
||||
};
|
||||
}
|
||||
|
||||
export async function runGlobalEval(
|
||||
userPrompt: string,
|
||||
apiKey: string,
|
||||
@@ -272,6 +312,8 @@ export async function runGlobalEval(
|
||||
}
|
||||
: undefined,
|
||||
isPlanModeActive: planMode?.isPlanModeActive,
|
||||
requestSecret:
|
||||
options.secretRequests && scriptedSecretCard(options.secretRequests),
|
||||
isToolAvailable: (name) =>
|
||||
(!pipelineToolNames.has(name) || (pipelineEditors?.folders().length ?? 0) > 0) &&
|
||||
(planMode?.isToolAvailable?.(name) ?? true),
|
||||
|
||||
@@ -52,6 +52,8 @@ export interface RunEvalParams<THelpers, TOutput> {
|
||||
* tool changes what the prompt should say — plan mode's instructions have to come back
|
||||
* out once the plan is approved. Falls back to the fixed `systemMessage`. */
|
||||
getSystemMessage?: () => ChatCompletionSystemMessageParam;
|
||||
/** Stands in for the secret card. Absent, `request_secret` reports that it cannot show one. */
|
||||
requestSecret?: ToolCallbacks["requestSecret"];
|
||||
onAssistantMessageStart?: () => void;
|
||||
onAssistantToken?: (token: string) => void;
|
||||
onAssistantMessageEnd?: () => void;
|
||||
@@ -80,6 +82,7 @@ export async function runEval<THelpers, TOutput>(
|
||||
isPlanModeActive,
|
||||
isToolAvailable,
|
||||
getSystemMessage,
|
||||
requestSecret,
|
||||
} = params;
|
||||
let shouldEmitMessageStart = true;
|
||||
|
||||
@@ -145,6 +148,7 @@ export async function runEval<THelpers, TOutput>(
|
||||
return answer === undefined ? undefined : [answer];
|
||||
},
|
||||
}),
|
||||
...(requestSecret && { requestSecret }),
|
||||
onNewToken: (token: string) => {
|
||||
if (shouldEmitMessageStart) {
|
||||
onAssistantMessageStart?.();
|
||||
|
||||
+251
-6
@@ -406,6 +406,8 @@
|
||||
- write_resource
|
||||
- deploy_workspace_item
|
||||
- delete_workspace_item
|
||||
# The user gave the token, so the secret card would only make them type it again.
|
||||
- request_secret
|
||||
toolCallArgs:
|
||||
- tool: write_variable
|
||||
field: value
|
||||
@@ -584,6 +586,8 @@
|
||||
- write_trigger
|
||||
- deploy_workspace_item
|
||||
- delete_workspace_item
|
||||
# The user gave the password, so the secret card would only make them type it again.
|
||||
- request_secret
|
||||
toolCallArgs:
|
||||
- tool: write_variable
|
||||
field: value
|
||||
@@ -3790,22 +3794,32 @@
|
||||
sessionChat: true
|
||||
userAnswers:
|
||||
- It is for the Stripe API; I will paste the value myself
|
||||
secretRequests:
|
||||
- action: save
|
||||
validate:
|
||||
requiredDrafts:
|
||||
- type: variable
|
||||
valueIncludes:
|
||||
- '"is_secret": true'
|
||||
draftCountExactly: 1
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- request_secret
|
||||
forbiddenToolsUsed:
|
||||
- write_variable
|
||||
- deploy_workspace_item
|
||||
# The card saved the draft: what is left is a deploy the AI offers, not a page to open.
|
||||
- open_page
|
||||
toolCallArgs:
|
||||
- tool: request_secret
|
||||
field: resource_type
|
||||
fieldMustBeAbsent: true
|
||||
assistantExpect:
|
||||
requiredMentionsAnyOf:
|
||||
- - getVariable
|
||||
- get_variable
|
||||
- "$var:"
|
||||
- - deploy
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- stages a secret variable with a placeholder value instead of inventing the key
|
||||
- any example script reads the variable rather than embedding the key; an example given only in the chat is checked separately, so do not score its absence here
|
||||
- asks for the key through one secure card for a secret variable, without asking for it in the chat or staging a placeholder
|
||||
- any example script reads the variable rather than embedding the key
|
||||
|
||||
# Pills that name what an established workspace holds, read from composer_connected_workspace.
|
||||
- id: global-composer-explore-datatable
|
||||
@@ -4239,3 +4253,234 @@
|
||||
- creates a script draft at f/evals/global/open_tasks_per_user
|
||||
- the script fetches the todos and counts the open ones per user
|
||||
- the script returns the per-user counts rather than the raw todo list
|
||||
|
||||
# Connecting a service whose secrets the user has not given goes through one request_secret
|
||||
# card: no question about a field the card takes, and no write of the resource or its secret
|
||||
# variable, since the card saves both as drafts; the AI then offers to deploy them.
|
||||
# `runtime.secretRequests` plays the user on the card and saves through its own save.
|
||||
- id: global-secret-card-supabase-postgres
|
||||
prompt: |-
|
||||
Connect our Supabase Postgres database so my scripts can query it. Save it as f/evals/global/supabase_db.
|
||||
initial: ai_evals/fixtures/frontend/global/initial/user_admin_evals_folder.json
|
||||
runtime:
|
||||
maxTurns: 8
|
||||
userAnswers:
|
||||
- With a connection string
|
||||
secretRequests:
|
||||
- action: save
|
||||
fields:
|
||||
host: aws-0-eu-west-1.pooler.supabase.com
|
||||
port: 5432
|
||||
user: postgres.abcdefgh
|
||||
dbname: postgres
|
||||
sslmode: require
|
||||
check:
|
||||
ok: true
|
||||
validate:
|
||||
draftCountExactly: 2
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- request_secret
|
||||
forbiddenToolsUsed:
|
||||
- write_resource
|
||||
- write_variable
|
||||
- deploy_workspace_item
|
||||
# The card saved the drafts: what is left is a deploy the AI offers, not a page to open.
|
||||
- open_page
|
||||
toolCallArgs:
|
||||
- tool: request_secret
|
||||
field: resource_type
|
||||
stringEqualsAnyOf:
|
||||
- postgresql
|
||||
- tool: request_secret
|
||||
field: path
|
||||
stringEqualsAnyOf:
|
||||
- f/evals/global/supabase_db
|
||||
assistantExpect:
|
||||
# The card leaves drafts, which nothing can run until deployed.
|
||||
requiredMentionsAnyOf:
|
||||
- - deploy
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- asks in the chat for no connection detail the card takes (host, user, database, password, connection string)
|
||||
- connects the database through one secure card at f/evals/global/supabase_db
|
||||
- refers to it as $res:f/evals/global/supabase_db once it is saved
|
||||
|
||||
- id: global-secret-card-openai
|
||||
prompt: |-
|
||||
I want my scripts to call OpenAI. Can you add my OpenAI API key to the workspace?
|
||||
initial: ai_evals/fixtures/frontend/global/initial/user_admin_evals_folder.json
|
||||
runtime:
|
||||
maxTurns: 8
|
||||
secretRequests:
|
||||
- action: save
|
||||
check:
|
||||
ok: true
|
||||
validate:
|
||||
draftCountExactly: 2
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- request_secret
|
||||
forbiddenToolsUsed:
|
||||
- write_resource
|
||||
- write_variable
|
||||
- deploy_workspace_item
|
||||
toolCallArgs:
|
||||
- tool: request_secret
|
||||
field: resource_type
|
||||
stringEqualsAnyOf:
|
||||
- openai
|
||||
assistantExpect:
|
||||
# The card leaves drafts, which nothing can run until deployed.
|
||||
requiredMentionsAnyOf:
|
||||
- - deploy
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- connects OpenAI as an openai resource through one secure card, without asking for the key in the chat
|
||||
|
||||
# A secret that goes into no resource is a request_secret without a resource type.
|
||||
- id: global-secret-card-variable
|
||||
prompt: |-
|
||||
Store our Mailgun API key as a secret variable at f/evals/global/mailgun_api_key. A script will take it as an argument later.
|
||||
initial: ai_evals/fixtures/frontend/global/initial/user_admin_evals_folder.json
|
||||
runtime:
|
||||
maxTurns: 8
|
||||
secretRequests:
|
||||
- action: save
|
||||
validate:
|
||||
draftCountExactly: 1
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- request_secret
|
||||
forbiddenToolsUsed:
|
||||
- write_resource
|
||||
- write_variable
|
||||
- deploy_workspace_item
|
||||
toolCallArgs:
|
||||
- tool: request_secret
|
||||
field: resource_type
|
||||
fieldMustBeAbsent: true
|
||||
- tool: request_secret
|
||||
field: path
|
||||
stringEqualsAnyOf:
|
||||
- f/evals/global/mailgun_api_key
|
||||
assistantExpect:
|
||||
# The card leaves drafts, which nothing can run until deployed.
|
||||
requiredMentionsAnyOf:
|
||||
- - deploy
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- asks for the Mailgun key through one secure card for a secret variable at f/evals/global/mailgun_api_key, without asking for it in the chat
|
||||
- refers to it as $var:f/evals/global/mailgun_api_key once it is saved
|
||||
|
||||
# A rotated password replaces the secret the existing resource references. Asking for the
|
||||
# bare variable at that path and replacing the resource with its fields carried over both
|
||||
# keep the host, user and database.
|
||||
- id: global-secret-card-replace-password
|
||||
prompt: |-
|
||||
The password of our reporting database changed. Can you update it in Windmill?
|
||||
initial: ai_evals/fixtures/frontend/global/initial/reporting_db_resource.json
|
||||
runtime:
|
||||
maxTurns: 8
|
||||
secretRequests:
|
||||
- action: save
|
||||
check:
|
||||
ok: true
|
||||
validate:
|
||||
draftCountAtLeast: 1
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- request_secret
|
||||
forbiddenToolsUsed:
|
||||
- write_resource
|
||||
- write_variable
|
||||
- deploy_workspace_item
|
||||
- delete_workspace_item
|
||||
toolCallArgs:
|
||||
- tool: request_secret
|
||||
field: path
|
||||
stringEqualsAnyOf:
|
||||
- f/evals/global/reporting_db
|
||||
assistantExpect:
|
||||
# The card leaves drafts, which nothing can run until deployed.
|
||||
requiredMentionsAnyOf:
|
||||
- - deploy
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- asks for the new password through one secure card on the existing f/evals/global/reporting_db resource, not in the chat
|
||||
- keeps the resource's host, port, user and database as they are
|
||||
|
||||
- id: global-secret-card-s3
|
||||
prompt: |-
|
||||
Connect our S3 bucket acme-exports in eu-west-1 so flows can write files there. Save it as f/evals/global/exports_s3.
|
||||
initial: ai_evals/fixtures/frontend/global/initial/user_admin_evals_folder.json
|
||||
runtime:
|
||||
maxTurns: 8
|
||||
secretRequests:
|
||||
- action: save
|
||||
check:
|
||||
ok: true
|
||||
validate:
|
||||
draftCountAtLeast: 2
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- request_secret
|
||||
forbiddenToolsUsed:
|
||||
- write_resource
|
||||
- write_variable
|
||||
- deploy_workspace_item
|
||||
toolCallArgs:
|
||||
- tool: request_secret
|
||||
field: resource_type
|
||||
stringEqualsAnyOf:
|
||||
- s3
|
||||
- tool: request_secret
|
||||
field: resource_value.bucket
|
||||
stringIncludesAnyOf:
|
||||
- acme-exports
|
||||
assistantExpect:
|
||||
# The card leaves drafts, which nothing can run until deployed.
|
||||
requiredMentionsAnyOf:
|
||||
- - deploy
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- connects the acme-exports bucket as an s3 resource through one secure card that asks for its access keys
|
||||
- prepares the bucket and region on the card rather than asking for them in the chat
|
||||
|
||||
# A session held in Use has no write tools, but the card is the user's own save, so connecting
|
||||
# a service still leaves its drafts there.
|
||||
- id: global-secret-card-read-only-session
|
||||
prompt: |-
|
||||
Can you add my OpenAI API key to the workspace?
|
||||
initial: ai_evals/fixtures/frontend/global/initial/user_admin_evals_folder.json
|
||||
runtime:
|
||||
maxTurns: 8
|
||||
sessionChat: true
|
||||
profile:
|
||||
operator: true
|
||||
operatorSettings:
|
||||
builder_flows: false
|
||||
builder_apps: false
|
||||
manage_schedules: false
|
||||
manage_triggers: false
|
||||
secretRequests:
|
||||
- action: save
|
||||
check:
|
||||
ok: true
|
||||
validate:
|
||||
draftCountExactly: 2
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- request_secret
|
||||
toolCallArgs:
|
||||
- tool: request_secret
|
||||
field: resource_type
|
||||
stringEqualsAnyOf:
|
||||
- openai
|
||||
assistantExpect:
|
||||
# The card leaves drafts, which nothing can run until deployed.
|
||||
requiredMentionsAnyOf:
|
||||
- - deploy
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- connects OpenAI through the secure card even though the session itself cannot write drafts
|
||||
|
||||
@@ -33,6 +33,9 @@ export interface EvalCaseRuntimeSpec {
|
||||
// past the last one is dismissed, so `[]` dismisses them all. Unset, the question tool
|
||||
// reports that it cannot ask.
|
||||
userAnswers?: string[];
|
||||
// Global mode: the user's side of each request_secret card, in the order the cards open; a
|
||||
// card past the last one is dismissed. Unset, the tool reports that it cannot show the card.
|
||||
secretRequests?: EvalSecretRequestAnswer[];
|
||||
backendPreview?: EvalCaseRuntimeBackendPreview;
|
||||
appContext?: EvalCaseRuntimeAppContextSpec;
|
||||
// Global mode: run as a session chat (preview tools + session prompt) vs the standalone chat.
|
||||
@@ -46,6 +49,17 @@ export interface EvalCaseRuntimeSpec {
|
||||
profile?: EvalCaseProfile;
|
||||
}
|
||||
|
||||
/** What the user does on a request_secret card. `save` goes through the card's own save, so
|
||||
* the secret variables and the resource land in the workspace as production writes them, with
|
||||
* placeholder secret values. */
|
||||
export interface EvalSecretRequestAnswer {
|
||||
action: "save" | "dismiss";
|
||||
/** Non-secret fields the user fills or corrects on the card, over what the model prepared. */
|
||||
fields?: Record<string, unknown>;
|
||||
/** The saved resource's connection test as the card reports it; unset for a type with none. */
|
||||
check?: { ok: true } | { ok: false; error: string };
|
||||
}
|
||||
|
||||
export interface EvalCaseProfile {
|
||||
operator: boolean;
|
||||
operatorSettings?: {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"user": {
|
||||
"username": "admin",
|
||||
"is_admin": true,
|
||||
"folders": ["evals"],
|
||||
"folders_read": ["evals"]
|
||||
},
|
||||
"workspace": {
|
||||
"variables": [
|
||||
{
|
||||
"path": "f/evals/global/reporting_db",
|
||||
"value": "previous-reporting-password",
|
||||
"is_secret": true,
|
||||
"description": "Password for f/evals/global/reporting_db"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"path": "f/evals/global/reporting_db",
|
||||
"resource_type": "postgresql",
|
||||
"description": "Eval reporting database",
|
||||
"value": {
|
||||
"host": "reports-db.internal",
|
||||
"port": 5432,
|
||||
"user": "report_reader",
|
||||
"dbname": "evals_reporting",
|
||||
"sslmode": "require",
|
||||
"password": "$var:f/evals/global/reporting_db"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,7 @@ export function createGlobalModeRunner(
|
||||
: (context.evalCase?.validate as GlobalValidationSpec | undefined)?.pipelineRun,
|
||||
maxIterations: context.evalCase?.runtime?.maxTurns,
|
||||
userAnswers: context.evalCase?.runtime?.userAnswers,
|
||||
secretRequests: context.evalCase?.runtime?.secretRequests,
|
||||
provider: modelConfig.provider,
|
||||
model: modelConfig.model,
|
||||
backend: backendSettings,
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT app_id, value, raw_app FROM app_version WHERE id = $1",
|
||||
"query": "SELECT av.app_id, av.value, av.raw_app FROM app_version av JOIN app a ON a.id = av.app_id\n WHERE av.id = $1 AND a.workspace_id = $2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -21,7 +21,8 @@
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Int8"
|
||||
"Int8",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
@@ -30,5 +31,5 @@
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "19cca1d42f37e860dc54470fea8dd9a35c412d82d27ce369ccb0ba38b9791669"
|
||||
"hash": "0031ec1db8de7a249d2471122d16664e9edd61e34e7265cc8a66f330d71176c5"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT COALESCE((error_handler->>'muted_on_ui_runs')::boolean, false) AS \"muted!\"\n FROM workspace_settings WHERE workspace_id = $1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "muted!",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "0fc3318da2c8dd5304a0ba7a83f25cb2b7728ac069dcc29f9c7e76d915ea3076"
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT id, args->'iter'->'value' AS \"value: sqlx::types::Json<Box<RawValue>>\"\n FROM v2_job WHERE workspace_id = $1 AND id = ANY($2)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "value: sqlx::types::Json<Box<RawValue>>",
|
||||
"type_info": "Jsonb"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"UuidArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "1308b30b6ad40783d9d49922cbd861ecfacc02eae817bfbd0c8bc923e90e344d"
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT id FROM v2_job_completed\n WHERE workspace_id = $1 AND id = ANY($2) AND (status = 'success' OR status = 'skipped')",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"UuidArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "401997343219c77965aa4b700147a42395f4ed5f89e02dcaa2ce60baa5d66949"
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT q.tag, j.parent_job AS \"parent!\"\n FROM v2_job_queue q JOIN v2_job j ON j.id = q.id\n WHERE q.id = $1 AND j.parent_job = COALESCE($2, j.parent_job)\n AND NOT q.running AND q.suspend = 0\n AND q.scheduled_for <= now() - make_interval(secs => $3::bigint::double precision)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "tag",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "parent!",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Uuid",
|
||||
"Int8"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "4c7e47928b56f337a937013e512f24a1c2a22987d0dbd598ddc0560a140e0bef"
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE v2_job_queue SET extras = extras - 'waiting_on' WHERE id = $1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "636af7f63043d20752ef1ef0968efff600fcc5d453edcff05810220daa306bd1"
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT flow_status AS \"flow_status: Json<FlowStatus>\"\n FROM v2_job_completed WHERE id = $1 AND workspace_id = $2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "flow_status: Json<FlowStatus>",
|
||||
"type_info": "Jsonb"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "7255360f4b5c4fd9e1b4f1fd08d3e242854c715fc2f393b84e31ac36ce9fa997"
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE v2_job_queue q SET suspend = 0\n FROM v2_job j, v2_job_status f\n WHERE q.workspace_id = $1 AND q.suspend = $3 AND j.parent_job = $2\n AND f.id = j.id AND q.id = j.id\n AND (f.flow_status->'step')::int = 0",
|
||||
"query": "UPDATE v2_job_queue q SET suspend = 0\n FROM v2_job j, v2_job_status f\n WHERE q.workspace_id = $1 AND q.suspend = $3 AND j.parent_job = $2\n AND f.id = j.id AND q.id = j.id\n AND ((f.flow_status->'step')::int = 0\n OR f.flow_status->'modules'->((f.flow_status->'step')::int)->>'id'\n = f.flow_status->'restarted_from'->>'step_id')",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
@@ -12,5 +12,5 @@
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "f1dbcb6e6d82d17c19eb88c0e67dc1cb8baf5bd40b75a2a9cd3ebac440fda632"
|
||||
"hash": "8e7ab89afc10b5552cc25c00385b3b58f6b28edcfcb8b382580282acea0e9e4d"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT resource AS \"resource!\" FROM (\n SELECT DISTINCT ON (resource) resource, alert_type\n FROM alerts\n WHERE resource LIKE 'tag_deadlock:%' AND created_at > now() - interval '7 days'\n ORDER BY resource, created_at DESC, id DESC\n ) latest WHERE alert_type = 'critical_error'",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "resource!",
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": []
|
||||
},
|
||||
"nullable": [
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "9445708d7e6ba4ea9ad0dc4b50598d044b520fcaf84323890c0caf422cf7944a"
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT c.id, j.runnable_id, c.flow_status AS \"flow_status: Json<FlowStatus>\"\n FROM v2_job_completed c JOIN v2_job j USING (id)\n WHERE c.id = ANY($1) AND c.workspace_id = $2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "runnable_id",
|
||||
"type_info": "Int8"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "flow_status: Json<FlowStatus>",
|
||||
"type_info": "Jsonb"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"UuidArray",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "96a2597c2b5465499731f30841e83f991020f607cdfad2807275a9b246a0f983"
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE v2_job_status SET flow_status = JSONB_SET(flow_status, ARRAY['modules', $1::TEXT], $2) WHERE id = $3",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Jsonb",
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "98ee2b8720b5e0e7b66619406482952630918f4dc07a8358c04a3d22d3166a32"
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE v2_job_queue\n SET extras = jsonb_set(COALESCE(extras, '{}'::jsonb), '{waiting_on}',\n jsonb_build_object('child', $2::uuid, 'at', now()))\n WHERE id = $1 AND running\n AND (extras->'waiting_on'->>'child' IS DISTINCT FROM $2::uuid::text\n OR (extras->'waiting_on'->>'at')::timestamptz < now() - interval '5 seconds')",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "9a9766542a3ecc3b928557234298883554463eb6e5ec6ca47d453528c2175a24"
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n WITH blocked AS (\n SELECT DISTINCT r.worker, c.tag, r.id AS parent\n FROM v2_job_queue r\n JOIN v2_job rj ON rj.id = r.id\n JOIN v2_job_queue c ON c.id = (r.extras->'waiting_on'->>'child')::uuid\n JOIN v2_job cj ON cj.id = c.id AND cj.parent_job = r.id\n WHERE r.running AND r.worker IS NOT NULL AND r.suspend = 0 AND r.started_at IS NOT NULL\n AND (r.extras->'waiting_on'->>'at')::timestamptz\n > now() - make_interval(secs => $3)\n AND rj.kind NOT IN ('flow', 'flowpreview', 'singlestepflow', 'flownode',\n 'unassigned_flow', 'unassigned_singlestepflow')\n AND NOT c.running AND c.suspend = 0\n AND c.scheduled_for <= now() - make_interval(secs => $2::bigint::double precision)\n AND ($1::text IS NULL OR c.tag = $1)\n ),\n live AS (\n SELECT worker, unnest(custom_tags) AS tag, native_mode\n FROM worker_ping\n WHERE ping_at > now() - interval '60 seconds' AND draining IS NOT TRUE\n )\n SELECT l.tag AS \"tag!\", count(*) AS \"workers!\",\n array_agg(b.parent) FILTER (WHERE b.parent IS NOT NULL) AS \"parents!\"\n FROM live l\n LEFT JOIN LATERAL (\n SELECT parent FROM blocked b WHERE b.worker = l.worker AND b.tag = l.tag LIMIT 1\n ) b ON true\n WHERE l.tag IN (SELECT tag FROM blocked)\n GROUP BY l.tag\n HAVING count(*) = count(b.parent) AND NOT bool_or(l.native_mode)\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "tag!",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "workers!",
|
||||
"type_info": "Int8"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "parents!",
|
||||
"type_info": "UuidArray"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Int8",
|
||||
"Float8"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null,
|
||||
null,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "be2bf5ff24ee1daad674cabae2382a0d4d6ca268dbc734cb16b9405914029214"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT pg_advisory_xact_lock(hashtext('tag_deadlock:' || $1::text))",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "pg_advisory_xact_lock",
|
||||
"type_info": "Void"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "c93530173f708742b68b268dc2e80e27ca4a83cb8a9893d88b4cd4101b5bae91"
|
||||
}
|
||||
Generated
+190
-189
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "windmill"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
@@ -88,7 +88,7 @@ members = [
|
||||
exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
|
||||
edition = "2021"
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
6c06d688fe435630e2827bc177f066d2646bb768
|
||||
a403f3ce12fd150dd649098e61562eda1e6a4d81
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- No-op: the previous grants and search_path are not restored.
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Every definer-rights function (prosecdef) owned by the migration role gets a search_path
|
||||
-- ending in pg_temp, so a session's temporary objects never resolve ahead of the schema's
|
||||
-- (pg_temp is searched first unless the path names it), and loses the default PUBLIC EXECUTE
|
||||
-- grant, so only Windmill's own roles use it. The schema comes from current_schema() so installs
|
||||
-- with a non-public PG_SCHEMA resolve (see 20260624103600). A later CREATE OR REPLACE resets the
|
||||
-- path and a new function starts with the PUBLIC grant: both need the same two statements.
|
||||
DO
|
||||
$do$
|
||||
DECLARE
|
||||
target_schema TEXT := current_schema();
|
||||
fn regprocedure;
|
||||
BEGIN
|
||||
FOR fn IN
|
||||
SELECT p.oid::regprocedure
|
||||
FROM pg_proc p
|
||||
JOIN pg_namespace n ON n.oid = p.pronamespace
|
||||
WHERE n.nspname = target_schema
|
||||
AND p.prosecdef
|
||||
AND pg_has_role(current_user, p.proowner, 'USAGE')
|
||||
LOOP
|
||||
EXECUTE format('ALTER FUNCTION %s SET search_path = %I, pg_temp', fn, target_schema);
|
||||
EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', fn);
|
||||
END LOOP;
|
||||
END
|
||||
$do$;
|
||||
|
||||
-- folder_labels() is the only one that is called rather than fired, from user_db transactions
|
||||
-- (SET LOCAL ROLE windmill_user / windmill_admin) and by the owner. Trigger functions need no
|
||||
-- grant: EXECUTE is checked when a trigger is created, not when it fires.
|
||||
GRANT EXECUTE ON FUNCTION folder_labels(text, text) TO windmill_user, windmill_admin;
|
||||
+24
-24
@@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windmill-common"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"aho-corasick",
|
||||
@@ -6430,7 +6430,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-macros"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -6442,7 +6442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"serde",
|
||||
@@ -6451,7 +6451,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-bash"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6463,7 +6463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-csharp"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6475,7 +6475,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-go"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gosyn",
|
||||
@@ -6487,7 +6487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-graphql"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6499,7 +6499,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-java"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6511,7 +6511,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-nu"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"nu-parser",
|
||||
@@ -6522,7 +6522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-php"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -6533,7 +6533,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -6545,7 +6545,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-asset"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -6556,7 +6556,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-imports"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-recursion",
|
||||
@@ -6579,7 +6579,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-r"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6591,7 +6591,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ruby"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6605,7 +6605,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-rust"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"convert_case",
|
||||
@@ -6622,7 +6622,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6635,7 +6635,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql-asset"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde",
|
||||
@@ -6647,7 +6647,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6665,7 +6665,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts-asset"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde-wasm-bindgen",
|
||||
@@ -6681,7 +6681,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-wac"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -6698,7 +6698,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-wasm"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"getrandom 0.2.17",
|
||||
@@ -6730,7 +6730,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-yaml"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6744,7 +6744,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-types"
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
|
||||
@@ -12,7 +12,7 @@ resolver = "2"
|
||||
members = ["."]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.882.0"
|
||||
version = "1.884.1"
|
||||
edition = "2021"
|
||||
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
|
||||
|
||||
|
||||
@@ -4461,6 +4461,17 @@ pub async fn monitor_db(
|
||||
}
|
||||
};
|
||||
|
||||
let tag_deadlock_alerts_f = async {
|
||||
if server_mode && !initial_load {
|
||||
if let Some(db) = conn.as_sql() {
|
||||
if let Err(e) = windmill_common::tag_deadlock::recover_tag_deadlock_alerts(db).await
|
||||
{
|
||||
tracing::error!("Failed to check tag deadlock alerts for recovery: {e:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let worker_groups_alerts_f = async {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if server_mode && !initial_load {
|
||||
@@ -4806,6 +4817,7 @@ pub async fn monitor_db(
|
||||
enforce_offline_caps_f,
|
||||
worker_groups_alerts_f,
|
||||
jobs_waiting_alerts_f,
|
||||
tag_deadlock_alerts_f,
|
||||
low_disk_alerts_f,
|
||||
apply_autoscaling_f,
|
||||
update_min_worker_version_f,
|
||||
|
||||
@@ -576,6 +576,8 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})
|
||||
.arg("iter", json!({ "value": "tests", "index": 0 }))
|
||||
.run_until_complete(&db, false, port)
|
||||
@@ -954,7 +956,11 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
}),
|
||||
})
|
||||
.arg("world", json!("bar"))
|
||||
@@ -984,7 +990,11 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
}),
|
||||
})
|
||||
.arg("world", json!("baz"))
|
||||
@@ -1104,7 +1114,11 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
}),
|
||||
})
|
||||
.arg("tag", json!("second"))
|
||||
@@ -1182,7 +1196,11 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})
|
||||
.run_until_complete(db, false, port)
|
||||
.await;
|
||||
@@ -1314,8 +1332,14 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
}),
|
||||
})
|
||||
.arg("tag", json!("second"))
|
||||
@@ -1452,8 +1476,14 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
}),
|
||||
})
|
||||
.arg("tag", json!("second"))
|
||||
@@ -1549,8 +1579,14 @@ mod job_payload {
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
}),
|
||||
})
|
||||
.run_until_complete(db, false, port)
|
||||
|
||||
@@ -1043,3 +1043,48 @@ async fn app_relock_of_every_component_regenerates_a_kept_stale_lock(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `app_version.id` is one sequence for the whole instance and an imported job row carries the
|
||||
/// `runnable_id` it was given, so a dependency job relocks only a version of its own workspace.
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn app_dependency_job_leaves_a_version_of_another_workspace_alone(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
let (_client, port, _s) = init_client(db.clone()).await;
|
||||
let mut completed = listen_for_completed_jobs(&db).await;
|
||||
|
||||
sqlx::query("INSERT INTO workspace (id, name, owner) VALUES ('other', 'other', 'test-user')")
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let app_id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO app (workspace_id, path, summary, policy, versions, extra_perms)
|
||||
VALUES ('other', 'f/rel/app', '', '{}'::jsonb, '{}', '{}'::jsonb) RETURNING id",
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
let foreign: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO app_version (app_id, value, created_by, raw_app)
|
||||
VALUES ($1, $2, 'test-user', true) RETURNING id",
|
||||
)
|
||||
.bind(app_id)
|
||||
.bind(
|
||||
serde_json::json!({ "runnables": { "a": { "type": "inline", "inlineScript": {
|
||||
"content": A, "language": "python3"
|
||||
}}}}),
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
|
||||
in_test_worker(
|
||||
&db,
|
||||
async {
|
||||
push_app_dependency_job(&db, foreign, None).await;
|
||||
wait_for_jobs(&db, &mut completed, 1).await;
|
||||
assert_eq!(app_lock(&db, foreign).await, None);
|
||||
},
|
||||
port,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! A failed-only restart of a parallel step reruns only its failed iterations, each in its
|
||||
//! original slot. Kept in its own binary: the restart checks the worker version, which other
|
||||
//! test binaries set process-wide.
|
||||
|
||||
#![cfg(feature = "deno_core")]
|
||||
|
||||
use serde_json::json;
|
||||
use sqlx::{Pool, Postgres};
|
||||
use windmill_common::flow_status::{FlowStatus, FlowStatusModule, RestartedFrom};
|
||||
use windmill_common::flows::FlowValue;
|
||||
use windmill_common::jobs::JobPayload;
|
||||
use windmill_test_utils::*;
|
||||
|
||||
async fn first_module(db: &Pool<Postgres>, flow_job_id: uuid::Uuid) -> FlowStatusModule {
|
||||
let status = sqlx::query_scalar!(
|
||||
"SELECT flow_status FROM v2_job_completed WHERE id = $1",
|
||||
flow_job_id,
|
||||
)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("flow_status missing");
|
||||
let status: FlowStatus = serde_json::from_value(status).unwrap();
|
||||
status.modules[0].clone()
|
||||
}
|
||||
|
||||
/// A parallel loop over `items` whose second step fails on all but 'x' when run with tag
|
||||
/// "first". With parallelism 1, the second rerun is queued suspended and must be released by
|
||||
/// the first one completing.
|
||||
fn flow(wrap_in_branchone: bool, items: &str) -> FlowValue {
|
||||
let parallel_loop = json!({
|
||||
"id": "loop",
|
||||
"value": {
|
||||
"type": "forloopflow",
|
||||
"iterator": { "type": "javascript", "expr": items },
|
||||
"skip_failures": true,
|
||||
"parallel": true,
|
||||
"parallelism": { "type": "static", "value": 1 },
|
||||
"modules": [{
|
||||
"id": "prep",
|
||||
"value": {
|
||||
"type": "rawscript",
|
||||
"language": "bun",
|
||||
"input_transforms": {},
|
||||
"content": "export function main() { return 1 }"
|
||||
}
|
||||
}, {
|
||||
"id": "inner",
|
||||
"value": {
|
||||
"type": "rawscript",
|
||||
"language": "bun",
|
||||
"input_transforms": {
|
||||
"iter_val": { "type": "javascript", "expr": "flow_input.iter.value" },
|
||||
"tag": { "type": "javascript", "expr": "flow_input.tag" }
|
||||
},
|
||||
"content": "export function main(iter_val: string, tag: string) { if (tag === 'first' && iter_val !== 'x') throw new Error('boom'); return `${tag}:${iter_val}` }"
|
||||
}
|
||||
}]
|
||||
}
|
||||
});
|
||||
let module = if wrap_in_branchone {
|
||||
json!({ "id": "pick", "value": { "type": "branchone", "branches": [], "default": [parallel_loop] } })
|
||||
} else {
|
||||
parallel_loop
|
||||
};
|
||||
serde_json::from_value(json!({
|
||||
"modules": [module],
|
||||
"schema": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": { "tag": { "type": "string" } },
|
||||
"order": ["tag"]
|
||||
}
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn run(
|
||||
db: &Pool<Postgres>,
|
||||
port: u16,
|
||||
value: FlowValue,
|
||||
tag: &str,
|
||||
restarted_from: Option<RestartedFrom>,
|
||||
) -> CompletedJob {
|
||||
RunJob::from(JobPayload::RawFlow { value, path: None, restarted_from })
|
||||
.arg("tag", json!(tag))
|
||||
.run_until_complete(db, false, port)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Only the failed iterations reran, each in its slot and from its failed step: their `prep`
|
||||
/// step keeps its original job.
|
||||
async fn assert_only_failed_reran(
|
||||
db: &Pool<Postgres>,
|
||||
result: serde_json::Value,
|
||||
original: &[uuid::Uuid],
|
||||
rerun: &[uuid::Uuid],
|
||||
) {
|
||||
assert_eq!(result, json!(["first:x", "second:y", "second:z"]));
|
||||
assert_eq!(rerun[0], original[0]);
|
||||
for slot in 1..3 {
|
||||
assert_ne!(rerun[slot], original[slot]);
|
||||
assert_eq!(
|
||||
first_module(db, rerun[slot]).await.job(),
|
||||
first_module(db, original[slot]).await.job()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test(fixtures("base", "hello"))]
|
||||
async fn test_restart_parallel_loop_failed_only(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
let first_run = run(&db, port, flow(false, "['x', 'y', 'z']"), "first", None).await;
|
||||
let original = first_module(&db, first_run.id).await.flow_jobs().unwrap();
|
||||
|
||||
let restart = RestartedFrom {
|
||||
flow_job_id: first_run.id,
|
||||
step_id: "loop".into(),
|
||||
failed_only: true,
|
||||
from_failed_step: true,
|
||||
..Default::default()
|
||||
};
|
||||
// The reruns use the restarted run's items, not the edited iterator's.
|
||||
let edited = flow(false, "['z', 'y', 'x']");
|
||||
let restarted = run(&db, port, edited, "second", Some(restart)).await;
|
||||
let rerun = first_module(&db, restarted.id).await.flow_jobs().unwrap();
|
||||
assert_only_failed_reran(&db, restarted.json_result().unwrap(), &original, &rerun).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A nested restart carries `failed_only` down to the parallel step its chain ends at.
|
||||
#[sqlx::test(fixtures("base", "hello"))]
|
||||
async fn test_restart_nested_parallel_loop_failed_only(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
let first_run = run(&db, port, flow(true, "['x', 'y', 'z']"), "first", None).await;
|
||||
let first_branch = first_module(&db, first_run.id).await.job().unwrap();
|
||||
let original = first_module(&db, first_branch).await.flow_jobs().unwrap();
|
||||
|
||||
let restart = RestartedFrom {
|
||||
flow_job_id: first_run.id,
|
||||
step_id: "pick".into(),
|
||||
branch_chosen: first_module(&db, first_run.id).await.branch_chosen(),
|
||||
nested: Some(Box::new(RestartedFrom {
|
||||
flow_job_id: first_branch,
|
||||
step_id: "loop".into(),
|
||||
failed_only: true,
|
||||
from_failed_step: true,
|
||||
..Default::default()
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let restarted = run(
|
||||
&db,
|
||||
port,
|
||||
flow(true, "['x', 'y', 'z']"),
|
||||
"second",
|
||||
Some(restart),
|
||||
)
|
||||
.await;
|
||||
let branch = first_module(&db, restarted.id).await.job().unwrap();
|
||||
let rerun = first_module(&db, branch).await.flow_jobs().unwrap();
|
||||
assert_only_failed_reran(&db, restarted.json_result().unwrap(), &original, &rerun).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A restart reuses earlier steps by position and runs only the steps the original run had, so
|
||||
/// an inline loop body whose steps changed starts each failed iteration over.
|
||||
#[sqlx::test(fixtures("base", "hello"))]
|
||||
async fn test_restart_edited_body_starts_failed_iterations_over(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
let first_run = run(&db, port, flow(false, "['x', 'y', 'z']"), "first", None).await;
|
||||
let original = first_module(&db, first_run.id).await.flow_jobs().unwrap();
|
||||
|
||||
// A step appended after the failed `inner`, returning what `inner` does.
|
||||
let mut edited = serde_json::to_value(flow(false, "['x', 'y', 'z']"))?;
|
||||
let body = edited["modules"][0]["value"]["modules"]
|
||||
.as_array_mut()
|
||||
.unwrap();
|
||||
let mut extra = body[1].clone();
|
||||
extra["id"] = json!("extra");
|
||||
body.push(extra);
|
||||
let edited: FlowValue = serde_json::from_value(edited)?;
|
||||
|
||||
let restart = RestartedFrom {
|
||||
flow_job_id: first_run.id,
|
||||
step_id: "loop".into(),
|
||||
failed_only: true,
|
||||
from_failed_step: true,
|
||||
..Default::default()
|
||||
};
|
||||
let restarted = run(&db, port, edited, "second", Some(restart)).await;
|
||||
assert_eq!(
|
||||
restarted.json_result().unwrap(),
|
||||
json!(["first:x", "second:y", "second:z"])
|
||||
);
|
||||
let rerun = first_module(&db, restarted.id).await.flow_jobs().unwrap();
|
||||
for slot in 1..3 {
|
||||
assert_ne!(
|
||||
first_module(&db, rerun[slot]).await.job(),
|
||||
first_module(&db, original[slot]).await.job()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Without `from_failed_step`, each failed iteration reruns from its first step.
|
||||
#[sqlx::test(fixtures("base", "hello"))]
|
||||
async fn test_restart_failed_only_starts_over_by_default(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
let first_run = run(&db, port, flow(false, "['x', 'y', 'z']"), "first", None).await;
|
||||
let original = first_module(&db, first_run.id).await.flow_jobs().unwrap();
|
||||
|
||||
let restart = RestartedFrom {
|
||||
flow_job_id: first_run.id,
|
||||
step_id: "loop".into(),
|
||||
failed_only: true,
|
||||
..Default::default()
|
||||
};
|
||||
let restarted = run(
|
||||
&db,
|
||||
port,
|
||||
flow(false, "['x', 'y', 'z']"),
|
||||
"second",
|
||||
Some(restart),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
restarted.json_result().unwrap(),
|
||||
json!(["first:x", "second:y", "second:z"])
|
||||
);
|
||||
let rerun = first_module(&db, restarted.id).await.flow_jobs().unwrap();
|
||||
assert_eq!(rerun[0], original[0]);
|
||||
for slot in 1..3 {
|
||||
assert_ne!(
|
||||
first_module(&db, rerun[slot]).await.job(),
|
||||
first_module(&db, original[slot]).await.job()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -27,6 +27,8 @@ async fn push_restart(
|
||||
flow_version: Some(flow_version),
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
},
|
||||
windmill_queue::PushArgs::from(&args),
|
||||
"test-user",
|
||||
|
||||
@@ -1240,9 +1240,16 @@ fn main(world: String) -> Result<String, String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The C# tests share the worker's C# cache as `DOTNET_CLI_HOME`, and .NET's first-run setup
|
||||
/// there is not safe to run twice at once: on a fresh machine one of two concurrent first
|
||||
/// builds can crash in it.
|
||||
#[cfg(feature = "csharp")]
|
||||
static CSHARP_FIRST_RUN: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
|
||||
#[cfg(feature = "csharp")]
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn test_csharp_job(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
let _first_run = CSHARP_FIRST_RUN.lock().await;
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
@@ -1292,6 +1299,7 @@ class Script
|
||||
async fn test_csharp_job_omitted_args_take_declared_defaults(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
let _first_run = CSHARP_FIRST_RUN.lock().await;
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
@@ -161,6 +161,8 @@ async fn test_between_steps_zombie_restart_reuses_all_children(
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})
|
||||
.run_until_complete(&db, false, port)
|
||||
.await;
|
||||
@@ -282,6 +284,8 @@ async fn test_mid_iteration_zombie_not_reused(db: Pool<Postgres>) -> anyhow::Res
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})
|
||||
.run_until_complete(&db, false, port)
|
||||
.await;
|
||||
@@ -417,7 +421,11 @@ async fn test_nested_restart_not_swallowed_by_zombie_reuse(
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})),
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})
|
||||
.run_until_complete(&db, false, port)
|
||||
.await;
|
||||
@@ -535,6 +543,8 @@ async fn test_raw_flow_restart_does_not_reuse_edited_step(
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
}),
|
||||
})
|
||||
.run_until_complete(&db, false, port)
|
||||
@@ -646,6 +656,8 @@ async fn test_non_monitor_cancel_is_not_reused(db: Pool<Postgres>) -> anyhow::Re
|
||||
flow_version: None,
|
||||
branch_chosen: None,
|
||||
nested: None,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
})
|
||||
.run_until_complete(&db, false, port)
|
||||
.await;
|
||||
|
||||
@@ -39,3 +39,6 @@ time.workspace = true
|
||||
anyhow.workspace = true
|
||||
jsonwebtoken = { workspace = true, optional = true }
|
||||
reqwest = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
semver.workspace = true
|
||||
|
||||
@@ -140,15 +140,16 @@ impl ApiAuthed {
|
||||
/// reports for these routes. Derived from the token, never from the request, because the
|
||||
/// column is authority-bearing for other kinds (`app` marks a file as app-produced).
|
||||
///
|
||||
/// A browser session is left unstamped rather than marked [`JobTriggerKind::Ui`]: that label
|
||||
/// is one a worker built before this release cannot decode, and it would strand the jobs
|
||||
/// carrying it. `webhook` has always been decodable, so it is safe to write today.
|
||||
/// A browser session is [`JobTriggerKind::Ui`], left unstamped until every worker can decode
|
||||
/// that label: an older one would strand the jobs carrying it.
|
||||
pub fn trigger_or_fallback(&self, trigger: Option<TriggerMetadata>) -> Option<TriggerMetadata> {
|
||||
if trigger.is_some() {
|
||||
return trigger;
|
||||
}
|
||||
if self.is_session_token {
|
||||
return None;
|
||||
return windmill_common::min_version::MIN_VERSION_SUPPORTS_UI_TRIGGER_KIND
|
||||
.met_conservatively()
|
||||
.then(|| TriggerMetadata::new(None, JobTriggerKind::Ui));
|
||||
}
|
||||
Some(TriggerMetadata::new(None, JobTriggerKind::Webhook))
|
||||
}
|
||||
@@ -1600,11 +1601,11 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A browser session is the one shape left unstamped, so the Runs page can say "a token
|
||||
/// started this" without claiming the converse. Every other label — every shape a member
|
||||
/// can pass to `create_token` — is `webhook`.
|
||||
/// A browser session is the one shape stamped `ui`, and only once every worker can decode
|
||||
/// it. Every other label — every shape a member can pass to `create_token` — is `webhook`.
|
||||
#[test]
|
||||
fn only_a_browser_session_is_left_unstamped() {
|
||||
fn only_a_browser_session_is_stamped_ui() {
|
||||
use windmill_common::min_version::MIN_VERSION;
|
||||
let kind_of = |label: Option<&str>| {
|
||||
ApiAuthed {
|
||||
is_session_token: windmill_common::auth::is_session_label(label),
|
||||
@@ -1614,7 +1615,14 @@ mod tests {
|
||||
.map(|t| t.trigger_kind.to_string())
|
||||
};
|
||||
|
||||
assert_eq!(kind_of(Some("session")), None);
|
||||
let before = MIN_VERSION.load_full();
|
||||
MIN_VERSION.store(std::sync::Arc::new(semver::Version::new(0, 0, 0)));
|
||||
assert_eq!(kind_of(Some("session")), None, "unknown fleet");
|
||||
MIN_VERSION.store(std::sync::Arc::new(semver::Version::new(1, 775, 0)));
|
||||
assert_eq!(kind_of(Some("session")), None, "a worker predates ui");
|
||||
MIN_VERSION.store(std::sync::Arc::new(semver::Version::new(1, 776, 0)));
|
||||
assert_eq!(kind_of(Some("session")).as_deref(), Some("ui"));
|
||||
MIN_VERSION.store(before);
|
||||
|
||||
for label in [
|
||||
Some("my-personal-token"),
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use serde_json::json;
|
||||
use serial_test::serial;
|
||||
use sqlx::{Pool, Postgres};
|
||||
use windmill_test_utils::*;
|
||||
|
||||
/// Every test here must be `#[serial]`: the rights cache is process-global and keyed by workspace id
|
||||
/// alone, so parallel tests under this same id read each other's rights.
|
||||
const WS: &str = "test-workspace";
|
||||
|
||||
fn operator_client() -> reqwest::Client {
|
||||
@@ -82,6 +85,7 @@ fn inline_code_flow(path: &str) -> serde_json::Value {
|
||||
/// already deployed and nothing more, and the endpoints that author code stay shut whether or not
|
||||
/// it is granted.
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))]
|
||||
#[serial]
|
||||
async fn test_operator_builder_flows_boundary(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
@@ -477,3 +481,49 @@ async fn check_builder_agents(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Each slot of a flow picks scripts of its own kind. A role without `code` gets the kind it asks
|
||||
/// for, preprocessors without a main included, and still no library.
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))]
|
||||
#[serial]
|
||||
async fn test_operator_lists_scripts_of_the_requested_kind(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
let api = format!("http://localhost:{port}/api/w/{WS}");
|
||||
let c = operator_client();
|
||||
|
||||
add_script(&db, 5001, "u/operator/action", "operator").await?;
|
||||
add_script(&db, 5002, "u/operator/library", "operator").await?;
|
||||
add_script(&db, 5003, "u/operator/prep", "operator").await?;
|
||||
sqlx::query(
|
||||
"UPDATE script SET auto_kind = 'lib',
|
||||
kind = CASE WHEN hash = 5003 THEN 'preprocessor' ELSE kind END
|
||||
WHERE hash IN (5002, 5003)",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
for (query, expected) in [
|
||||
("", vec!["u/operator/action"]),
|
||||
("&kinds=preprocessor", vec!["u/operator/prep"]),
|
||||
(
|
||||
"&kinds=script,preprocessor",
|
||||
vec!["u/operator/action", "u/operator/prep"],
|
||||
),
|
||||
] {
|
||||
let scripts: Vec<serde_json::Value> = c
|
||||
.get(format!("{api}/scripts/list?path_start=u/operator/{query}"))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await?;
|
||||
let mut paths: Vec<&str> = scripts.iter().filter_map(|s| s["path"].as_str()).collect();
|
||||
paths.sort();
|
||||
assert_eq!(paths, expected, "scripts listed for `{query}`");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -512,6 +512,8 @@ pub struct WindmillCompositeResult {
|
||||
result: Option<Box<RawValue>>,
|
||||
}
|
||||
|
||||
const DEADLOCK_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
pub async fn run_wait_result_internal(
|
||||
db: &DB,
|
||||
uuid: Uuid,
|
||||
@@ -542,6 +544,7 @@ pub async fn run_wait_result_internal(
|
||||
// Once we observe the early_return node failed with a failure_module configured,
|
||||
// its result is final — no need to re-query it on every poll.
|
||||
let mut early_return_failed_and_suppressed = false;
|
||||
let mut last_deadlock_check = std::time::Instant::now();
|
||||
|
||||
loop {
|
||||
if let Some(node_id_for_empty_return) = node_id_for_empty_return
|
||||
@@ -603,6 +606,15 @@ pub async fn run_wait_result_internal(
|
||||
break;
|
||||
}
|
||||
|
||||
if last_deadlock_check.elapsed() >= DEADLOCK_CHECK_INTERVAL {
|
||||
last_deadlock_check = std::time::Instant::now();
|
||||
match windmill_common::tag_deadlock::fail_fast_waiting_parent(db, uuid, None).await {
|
||||
Ok(Some(e)) => return Err(e),
|
||||
Ok(None) => (),
|
||||
Err(e) => tracing::warn!("same-tag deadlock check for job {uuid} failed: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
let delay = if accumulated_delay <= fast_poll_duration {
|
||||
*WAIT_RESULT_FAST_POLL_INTERVAL_MS
|
||||
} else {
|
||||
|
||||
@@ -194,7 +194,7 @@ async fn list_scripts(
|
||||
Query(pagination): Query<Pagination>,
|
||||
Query(lq): Query<ListScriptQuery>,
|
||||
) -> JsonResult<Vec<ListableScript>> {
|
||||
// A role that cannot write code lists only what it can run: no libraries, no drafts.
|
||||
// A role that cannot write code lists only what it can run or compose: no libraries, no drafts.
|
||||
let cannot_code = !windmill_common::roles::caller_capabilities(&db, &w_id, &authed)
|
||||
.await?
|
||||
.code;
|
||||
@@ -259,16 +259,19 @@ async fn list_scripts(
|
||||
.limit(per_page)
|
||||
.clone();
|
||||
|
||||
let lowercased_kinds: Option<Vec<String>> = lq
|
||||
let mut lowercased_kinds: Option<Vec<String>> = lq
|
||||
.kinds
|
||||
.map(|x| x.split(",").map(&str::to_lowercase).collect());
|
||||
|
||||
if (!lq.include_without_main.unwrap_or(false)
|
||||
if cannot_code {
|
||||
lowercased_kinds.get_or_insert_with(|| vec!["script".to_string()]);
|
||||
// A preprocessor has no main, so it is a 'lib' that a composed flow can still use.
|
||||
sqlb.and_where("(o.auto_kind IS NULL OR o.auto_kind <> 'lib' OR o.kind = 'preprocessor')");
|
||||
} else if !lq.include_without_main.unwrap_or(false)
|
||||
&& lowercased_kinds
|
||||
.as_ref()
|
||||
.map(|x| !x.contains(&"preprocessor".to_string()))
|
||||
.unwrap_or(true))
|
||||
|| cannot_code
|
||||
.unwrap_or(true)
|
||||
{
|
||||
// only include scripts that have a runnable entrypoint. Use a
|
||||
// deny-list: anything that isn't a 'lib' (library script without
|
||||
@@ -325,9 +328,7 @@ async fn list_scripts(
|
||||
);
|
||||
}
|
||||
}
|
||||
if cannot_code {
|
||||
sqlb.and_where_eq("kind", quote("script"));
|
||||
} else if let Some(lowercased_kinds) = lowercased_kinds {
|
||||
if let Some(lowercased_kinds) = lowercased_kinds {
|
||||
let safe_kinds = lowercased_kinds
|
||||
.into_iter()
|
||||
.map(sql_builder::quote)
|
||||
|
||||
@@ -680,6 +680,9 @@ pub struct EditErrorHandlerNew {
|
||||
pub muted_on_cancel: bool,
|
||||
#[serde(default)]
|
||||
pub muted_on_user_path: bool,
|
||||
/// Skip runs whose `trigger_kind` is `ui`. `None` keeps the stored value, for the same
|
||||
/// reason as `fallback_to_instance_alerts`.
|
||||
pub muted_on_ui_runs: Option<bool>,
|
||||
/// Left as `None` by clients that predate the setting (the CLI among them), which must
|
||||
/// keep the stored value rather than silently reset it on every settings push.
|
||||
pub fallback_to_instance_alerts: Option<bool>,
|
||||
@@ -711,6 +714,7 @@ impl EditErrorHandler {
|
||||
extra_args: legacy.error_handler_extra_args,
|
||||
muted_on_cancel: legacy.error_handler_muted_on_cancel,
|
||||
muted_on_user_path: false, // Old format doesn't have this field
|
||||
muted_on_ui_runs: None,
|
||||
fallback_to_instance_alerts: None,
|
||||
},
|
||||
}
|
||||
@@ -6367,6 +6371,22 @@ async fn edit_error_handler(
|
||||
if let Some(extra_args) = &ee.extra_args {
|
||||
error_handler["extra_args"] = extra_args.clone();
|
||||
}
|
||||
// Written only when set, so the blob of every workspace that never turns it on, and
|
||||
// its `settings.yaml`, stays as it was before the flag existed.
|
||||
let muted_on_ui_runs = match ee.muted_on_ui_runs {
|
||||
Some(muted) => muted,
|
||||
None => sqlx::query_scalar!(
|
||||
"SELECT COALESCE((error_handler->>'muted_on_ui_runs')::boolean, false) AS \"muted!\"
|
||||
FROM workspace_settings WHERE workspace_id = $1",
|
||||
&w_id
|
||||
)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.unwrap_or(false),
|
||||
};
|
||||
if muted_on_ui_runs {
|
||||
error_handler["muted_on_ui_runs"] = serde_json::Value::Bool(true);
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"UPDATE workspace_settings SET error_handler = $1 WHERE workspace_id = $2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: "3.0.3"
|
||||
|
||||
info:
|
||||
version: 1.882.0
|
||||
version: 1.884.1
|
||||
title: Windmill API
|
||||
|
||||
contact:
|
||||
@@ -9182,13 +9182,21 @@ paths:
|
||||
type: string
|
||||
supports_client_credentials:
|
||||
type: boolean
|
||||
supports_authorization_code:
|
||||
type: boolean
|
||||
description: The instance entry declares the authorization-code grant, so users can sign in with their own account when has_shared_credentials is also true.
|
||||
has_shared_credentials:
|
||||
type: boolean
|
||||
description: The instance entry holds a client id and secret users can connect with, for sign-in or as a shared service account. Whether client credentials are shared is get_connect's client_credentials_configured.
|
||||
description: The instance entry holds a client id and secret users can connect with, for sign-in or as a shared service account.
|
||||
shares_client_credentials:
|
||||
type: boolean
|
||||
description: Users may connect as the instance entry's own app with its shared client credentials, with no sign-in.
|
||||
required:
|
||||
- name
|
||||
- supports_client_credentials
|
||||
- supports_authorization_code
|
||||
- has_shared_credentials
|
||||
- shares_client_credentials
|
||||
|
||||
/oauth/get_connect/{client}:
|
||||
get:
|
||||
@@ -15324,6 +15332,35 @@ paths:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
|
||||
/w/{workspace}/ai_session_tools/secret_request/open:
|
||||
post:
|
||||
summary: read the secret request a request_secret link carries
|
||||
description: The page an MCP client's request_secret link opens reads the card to draw from the link's signed token. Refused when the token is invalid, expired, or made for another user or workspace.
|
||||
operationId: openSecretRequest
|
||||
tags:
|
||||
- ai
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- token
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: the card's request
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
|
||||
/w/{workspace}/ai/sessions/list:
|
||||
get:
|
||||
summary: list the calling user's AI session backups in the workspace object storage
|
||||
@@ -17406,6 +17443,12 @@ paths:
|
||||
flow_version:
|
||||
type: integer
|
||||
description: specific flow version to use for restart (optional, uses current version if not specified)
|
||||
failed_only:
|
||||
type: boolean
|
||||
description: for a parallel for-loop or branch-all at the restart point (`step_id`, or the last `nested_path` entry), keep the iterations (branches) that succeeded and rerun only the others from their first step, each in its original position. Cannot be combined with an iteration to restart at on that same step.
|
||||
from_failed_step:
|
||||
type: boolean
|
||||
description: with `failed_only`, resume each failed iteration (branch) at the step where it failed, keeping the steps before it, rather than rerunning it from its first step.
|
||||
nested_path:
|
||||
type: array
|
||||
description: path of additional steps to descend into AFTER `step_id`. Each entry represents one level of nesting inside the spawned child of the previous level's container (BranchOne / sequential ForLoop iteration / Subflow). When non-empty, the actual restart point is the LAST entry's step_id.
|
||||
@@ -19479,6 +19522,15 @@ paths:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- $ref: "#/components/parameters/JobId"
|
||||
- $ref: "#/components/parameters/GetStarted"
|
||||
- name: wait_for_child
|
||||
description: |
|
||||
Set by a job's SDK wait helpers when the calling job is blocked until this job, its
|
||||
child, completes. If every worker of the child's tag is held by such a waiting parent,
|
||||
the child can never start, and the request fails with 409 instead of the wait hanging.
|
||||
Leave unset for a plain status read.
|
||||
in: query
|
||||
schema:
|
||||
type: boolean
|
||||
|
||||
responses:
|
||||
"200":
|
||||
@@ -30843,6 +30895,10 @@ components:
|
||||
muted_on_user_path:
|
||||
type: boolean
|
||||
default: false
|
||||
muted_on_ui_runs:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Skip jobs started from the UI, whose trigger kind is `ui`. Stored only when true.
|
||||
|
||||
SuccessHandlerConfig:
|
||||
type: object
|
||||
@@ -30875,6 +30931,9 @@ components:
|
||||
muted_on_user_path:
|
||||
type: boolean
|
||||
default: false
|
||||
muted_on_ui_runs:
|
||||
type: boolean
|
||||
description: Skip jobs started from the UI, whose trigger kind is `ui`. Omit to leave the stored value untouched.
|
||||
fallback_to_instance_alerts:
|
||||
type: boolean
|
||||
description: Report failed jobs to the instance critical alert channels when no workspace error handler is set. Omit to leave the stored value untouched.
|
||||
@@ -39081,6 +39140,12 @@ components:
|
||||
nested:
|
||||
$ref: "#/components/schemas/RestartedFrom"
|
||||
description: When set, the worker spawns the child for `step_id` as a `RestartedFlow` against `nested.flow_job_id` instead of fresh-launching it.
|
||||
failed_only:
|
||||
type: boolean
|
||||
description: For a parallel for-loop or branch-all at `step_id`, keep the iterations (branches) that succeeded and rerun only the others.
|
||||
from_failed_step:
|
||||
type: boolean
|
||||
description: With `failed_only`, resume each failed iteration (branch) at the step where it failed rather than rerunning it from its first step.
|
||||
|
||||
Policy:
|
||||
type: object
|
||||
|
||||
@@ -96,8 +96,8 @@ pub(crate) async fn run_agent_as(
|
||||
};
|
||||
if let Some(obo) = on_behalf_of.as_ref() {
|
||||
// The worker would interpolate such an input with the job's token, which is the
|
||||
// identity's.
|
||||
if args.values().any(|v| untrusted_arg_interpolates(v.get())) {
|
||||
// identity's. Checked as a whole so an argument name serde_json unwraps is refused too.
|
||||
if untrusted_arg_interpolates(&serde_json::to_string(args)?) {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"Agent {path} runs on behalf of {}, so its inputs cannot reference variables or resources",
|
||||
obo.permissioned_as
|
||||
|
||||
@@ -16,6 +16,10 @@ struct BaseInternalUrl(String);
|
||||
pub(crate) fn workspaced_service(base_internal_url: String) -> Router {
|
||||
Router::new()
|
||||
.route("/{name}", post(call_tool))
|
||||
.route(
|
||||
"/secret_request/open",
|
||||
post(super::secrets::open_secret_request),
|
||||
)
|
||||
.layer(Extension(BaseInternalUrl(base_internal_url)))
|
||||
}
|
||||
|
||||
@@ -162,6 +166,8 @@ pub(crate) enum Effect {
|
||||
/// The call wrote nothing: it needs the AI provider catalog, which the chat builds, and
|
||||
/// is to be made again with it. `resource_refs` are the ones the flow references.
|
||||
NeedsAiProviderCatalog { resource_refs: Vec<String> },
|
||||
/// `request_secret`'s card, which the chat draws and settles: what it asks for.
|
||||
SecretRequest { request: Value },
|
||||
/// The code a write changed, for the card's diff: of a script in `language`, or of an
|
||||
/// app file at `file_path` (`before_file_path` when its language changed).
|
||||
CodeDiff {
|
||||
|
||||
@@ -255,7 +255,7 @@ async fn deploy_variable(
|
||||
if !item_exists(ctx, "variable", None, path).await? {
|
||||
if is_secret && stages_no_value {
|
||||
return Err(format!(
|
||||
"Draft variable \"{}\" is secret but stages no value, so it cannot be created. Run write_variable with its value first.",
|
||||
"Draft variable \"{}\" is secret but stages no value, so it cannot be created. If the user gave you its value, set it with write_variable. If not, discard this draft and call request_secret: the user types the secret in a secure card and you get back only its path.",
|
||||
draft.get("path").map(js_str).unwrap_or_default()
|
||||
));
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -79,7 +79,7 @@
|
||||
"type": "string"
|
||||
},
|
||||
"job_trigger_kind": {
|
||||
"description": "Runs: filter by how the job was triggered — one of webhook, default_email, http, websocket, kafka, email, nats, mqtt, amqp, sqs, postgres, schedule, gcp, azure, google, github, asset, freshness, app. comma-separate to match several values, or prefix each with ! to exclude them instead (never mix included and excluded values in one filter). (e.g. '!schedule' to hide scheduled runs)",
|
||||
"description": "Runs: filter by how the job was triggered — one of webhook, default_email, http, websocket, kafka, email, nats, mqtt, amqp, sqs, postgres, schedule, gcp, azure, google, github, asset, freshness, app, ui. comma-separate to match several values, or prefix each with ! to exclude them instead (never mix included and excluded values in one filter). (e.g. '!schedule' to hide scheduled runs)",
|
||||
"type": "string"
|
||||
},
|
||||
"label": {
|
||||
@@ -398,6 +398,82 @@
|
||||
},
|
||||
"read_only": true
|
||||
},
|
||||
{
|
||||
"name": "request_secret",
|
||||
"description": "Ask the user for secrets (API key, token, password) through a secure input card in Windmill (in an external client, a link to it). The values are saved as drafts of secret variables, encrypted, and never reach you. With resource_type it connects a service: the card shows the fields you prepared and asks for all its secrets, one confirmation saves them and a draft of the resource, and you get back \"$res:<path>\", with a connection test result for the types tested without a deploy. Runs read only deployed items, so the drafts must be deployed before anything uses them. Without resource_type it asks for one secret and you get back \"$var:<path>\". Never ask in the conversation for a value the card takes, secret or not: leave a field you do not know as an empty string in resource_value. Use it for every secret the user has not given you, rather than a placeholder variable for them to fill. A secret the user gave you goes in a secret variable with write_variable, referenced as \"$var:<path>\", never inline in a resource.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "With resource_type, the resource's path; otherwise the secret variable's. Refused if taken, unless replace is set.",
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"replace": {
|
||||
"description": "Set only when the user asked to replace what is at path.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"label": {
|
||||
"description": "What the user is giving or connecting, as they would name it: \"OpenAI API key\" for a bare secret, \"OpenAI\" for a resource.",
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"description": {
|
||||
"description": "One short sentence on what it is used for. Becomes the description of what is saved.",
|
||||
"type": "string"
|
||||
},
|
||||
"help_text": {
|
||||
"description": "Markdown shown on the card: two or three numbered steps to get the values at the user's provider, linking its page when you know it. Include what Windmill needs that the provider's default does not give, e.g. for Supabase the Session pooler string, since the direct host is IPv6-only.",
|
||||
"type": "string"
|
||||
},
|
||||
"resource_type": {
|
||||
"description": "To connect a service: its resource type.",
|
||||
"type": "string"
|
||||
},
|
||||
"resource_value": {
|
||||
"description": "With resource_type: the resource's non-secret fields, matching the type's schema. The user can correct them on the card.",
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string"
|
||||
},
|
||||
"additionalProperties": {}
|
||||
},
|
||||
"secret_fields": {
|
||||
"description": "With resource_type: every secret field of the resource (passwords, keys, tokens; not usernames or hosts).",
|
||||
"minItems": 1,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"field": {
|
||||
"description": "The secret field, e.g. \"api_key\".",
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"label": {
|
||||
"description": "Its label on the card; defaults to the key in words.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"field"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"connection_string": {
|
||||
"description": "With resource_type \"postgresql\": open the card on a connection string rather than the fields, as for Supabase or Neon. The user can switch.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path",
|
||||
"label"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"read_only": false
|
||||
},
|
||||
{
|
||||
"name": "update_user_instructions",
|
||||
"description": "Modify your own persistent personal instructions for the Global assistant. Use when the user asks you to remember a preference, always/never do something, or change/stop a behavior. Edits only the user-level instructions (the USER INSTRUCTIONS block, not workspace-level); changes persist in this browser and take effect on your next message.",
|
||||
@@ -1787,7 +1863,7 @@
|
||||
},
|
||||
{
|
||||
"name": "write_variable",
|
||||
"description": "Create or edit a draft variable. Editing is a partial update: pass only the fields you are changing. You can never read the value of a variable, so to edit a secret variable you MUST omit value — any value you pass replaces the stored secret. FAILS if you pass a \"$var:\" self-reference as the value, or un-secret a variable without giving its new value.",
|
||||
"description": "Create or edit a draft variable. Editing is a partial update: pass only the fields you are changing. You can never read the value of a variable, so to edit a secret variable you MUST omit value — any value you pass replaces the stored secret. FAILS if you pass a \"$var:\" self-reference as the value, or un-secret a variable without giving its new value. For a secret the user has not given you, call request_secret instead.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -4,7 +4,9 @@ use std::sync::LazyLock;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use super::workspace::{finish_draft_write, persist_draft, write_base, Persist};
|
||||
use super::workspace::{
|
||||
finish_draft_write, get_draft, item_exists, persist_draft, write_base, Persist,
|
||||
};
|
||||
use super::{non_null, put, tool_parameters, Ctx, ToolResult, SCHEMAS};
|
||||
|
||||
pub(super) const TOOLS: &[&str] = &[
|
||||
@@ -369,6 +371,10 @@ fn variable_to_draft_state(variable: &Value) -> Value {
|
||||
Value::Object(state)
|
||||
}
|
||||
|
||||
/// Where a write that lacks a secret's value sends the model: it can only get a value the
|
||||
/// user has not typed through the secure input.
|
||||
const ASK_FOR_SECRET: &str = " If it is a secret the user has not given you, call request_secret instead: they type it in a secure card and you get back only its path.";
|
||||
|
||||
/// The draft a `write_variable` call leaves. A variable's value is never read back, so
|
||||
/// an omitted `value` keeps whatever the base holds: `""` for "nothing staged", or the
|
||||
/// `$encrypted:` marker the draft store turned a staged secret into.
|
||||
@@ -382,7 +388,8 @@ fn variable_draft(args: &Value, base: Option<Value>) -> Result<Value, String> {
|
||||
};
|
||||
let value = arg("value");
|
||||
if base.is_none() && (value.is_none() || arg("is_secret").is_none()) {
|
||||
return Err(format!("Variable \"{path}\" does not exist yet, so creating it requires both value and is_secret."));
|
||||
let ask = if value.is_none() { ASK_FOR_SECRET } else { "" };
|
||||
return Err(format!("Variable \"{path}\" does not exist yet, so creating it requires both value and is_secret.{ask}"));
|
||||
}
|
||||
let was_secret = stored("is_secret").and_then(|s| s.as_bool());
|
||||
let is_secret = arg("is_secret")
|
||||
@@ -393,6 +400,11 @@ fn variable_draft(args: &Value, base: Option<Value>) -> Result<Value, String> {
|
||||
// "" is how a secret draft says "nothing staged", so it cannot also mean "set the
|
||||
// secret to empty".
|
||||
if is_secret && value.as_ref() == Some(&empty) {
|
||||
if base.is_none() {
|
||||
return Err(format!(
|
||||
"An empty string is not a valid value for new secret variable \"{path}\".{ASK_FOR_SECRET}"
|
||||
));
|
||||
}
|
||||
return Err(format!("An empty string is not a valid value for secret variable \"{path}\". Omit value to keep the stored secret, or pass the real new one."));
|
||||
}
|
||||
let next_value = value.clone().or_else(|| stored("value"));
|
||||
@@ -562,6 +574,11 @@ async fn write_resource(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let mut parsed = parse_args("write_resource", args)?;
|
||||
let force = take_override(&mut parsed);
|
||||
let path = parsed["path"].as_str().unwrap_or_default().to_string();
|
||||
if let Some(missing) = missing_variable(ctx, &parsed["value"]).await? {
|
||||
return Err(format!(
|
||||
"\"$var:{missing}\" names no variable, deployed or drafted. If the user gave you its value, write that variable first. If it is a secret the user has not given you, call request_secret instead: they type it in a secure card that saves it and this resource as drafts, and you get back only its path."
|
||||
));
|
||||
}
|
||||
write_draft(
|
||||
ctx,
|
||||
"resource",
|
||||
@@ -574,6 +591,35 @@ async fn write_resource(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
.await
|
||||
}
|
||||
|
||||
/// The first `$var:` reference in a resource value that names neither a deployed variable
|
||||
/// nor a draft of one, which every run using the resource would fail on.
|
||||
async fn missing_variable(ctx: &Ctx<'_>, value: &Value) -> Result<Option<String>, String> {
|
||||
fn references<'a>(value: &'a Value, found: &mut Vec<&'a str>) {
|
||||
match value {
|
||||
Value::String(s) => {
|
||||
if let Some(path) = s.strip_prefix("$var:") {
|
||||
if !found.contains(&path) {
|
||||
found.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter().for_each(|v| references(v, found)),
|
||||
Value::Object(fields) => fields.values().for_each(|v| references(v, found)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
references(value, &mut found);
|
||||
for path in found {
|
||||
if get_draft(ctx, "variable", path).await?.is_none()
|
||||
&& !item_exists(ctx, "variable", None, path).await?
|
||||
{
|
||||
return Ok(Some(path.to_string()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn write_variable(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let mut parsed = parse_args("write_variable", args)?;
|
||||
let force = take_override(&mut parsed);
|
||||
|
||||
@@ -69,6 +69,7 @@ mod instructions;
|
||||
mod items;
|
||||
mod misc;
|
||||
mod runs;
|
||||
mod secrets;
|
||||
mod settings;
|
||||
mod views;
|
||||
mod workspace;
|
||||
@@ -217,7 +218,7 @@ macro_rules! groups {
|
||||
}
|
||||
};
|
||||
}
|
||||
groups!(guidance, workspace, items, misc, flows, apps, runs, deploy, data, settings);
|
||||
groups!(guidance, workspace, items, misc, flows, apps, runs, deploy, data, settings, secrets);
|
||||
|
||||
/// A tool as a client lists it.
|
||||
#[cfg(feature = "mcp")]
|
||||
@@ -479,14 +480,22 @@ impl Ctx<'_> {
|
||||
.map_or((page, None), |(p, h)| (p, Some(h)));
|
||||
let sep = if page.contains('?') { '&' } else { '?' };
|
||||
let hash = hash.map(|h| format!("#{h}")).unwrap_or_default();
|
||||
format!(
|
||||
"{}{page}{sep}workspace={}{hash}",
|
||||
self.base_url(),
|
||||
enc(self.w_id)
|
||||
)
|
||||
}
|
||||
|
||||
/// The instance's address as the user opens it.
|
||||
pub fn base_url(&self) -> String {
|
||||
// An instance that never set its base URL holds this placeholder, which no client
|
||||
// can open; the host the client reached is the better guess then.
|
||||
let base = windmill_common::BASE_URL.load();
|
||||
let base = match self.origin {
|
||||
Some(origin) if base.as_str() == "http://localhost" => origin,
|
||||
_ => base.as_str(),
|
||||
};
|
||||
format!("{base}{page}{sep}workspace={}{hash}", enc(self.w_id))
|
||||
match self.origin {
|
||||
Some(origin) if base.as_str() == "http://localhost" => origin.to_string(),
|
||||
_ => base.as_str().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
//! `request_secret`: the user types secrets into a Windmill card, which saves them; the model
|
||||
//! only ever gets the path. The chat draws the card inline. An MCP client cannot draw it, so it
|
||||
//! gets a link to the same card on a Windmill page instead.
|
||||
|
||||
use axum::{extract::Path, Json};
|
||||
use hmac::{Hmac, Mac};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Map, Value};
|
||||
use sha2::Sha256;
|
||||
use windmill_common::error::{Error, JsonResult};
|
||||
use windmill_common::jwt::{decode_with_internal_secret, encode_with_internal_secret, JWT_SECRET};
|
||||
|
||||
use super::chat::Effect;
|
||||
use super::workspace::path_enc;
|
||||
use super::{bool_arg, enc, opt_str_arg, str_arg, Ctx, Surface, ToolResult};
|
||||
use crate::db::ApiAuthed;
|
||||
|
||||
pub(super) const TOOLS: &[&str] = &["request_secret"];
|
||||
|
||||
/// The resource types whose card also takes a connection string: the secret field the
|
||||
/// string's password is saved as, its label, and, as JSON, the fields the card shows when the
|
||||
/// user enters the details instead, for those the model did not prepare.
|
||||
const CONNECTION_STRING_TYPES: &[(&str, &str, &str, &str)] = &[(
|
||||
"postgresql",
|
||||
"password",
|
||||
"Password",
|
||||
r#"{"host": "", "port": 5432, "user": "", "dbname": "", "sslmode": "require"}"#,
|
||||
)];
|
||||
|
||||
/// How long a link to the card can be opened.
|
||||
const LINK_TTL_SECS: u64 = 60 * 60;
|
||||
|
||||
pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult {
|
||||
match name {
|
||||
"request_secret" => request_secret(ctx, args).await,
|
||||
_ => unreachable!("{name} is not a secrets tool"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_secret(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let request = secret_request(ctx.w_id, args)?;
|
||||
let path = request["path"].as_str().unwrap_or_default().to_string();
|
||||
if !bool_arg(args, "replace") {
|
||||
if let Some(taken) = taken_path(ctx, &request).await? {
|
||||
return Err(format!(
|
||||
"{taken}. Ask again with a free path, or with replace: true only if the user asked to replace it."
|
||||
));
|
||||
}
|
||||
}
|
||||
if ctx.surface == Surface::Chat {
|
||||
ctx.effect(Effect::SecretRequest { request });
|
||||
return Ok(String::new());
|
||||
}
|
||||
let claims = LinkClaims::for_user(
|
||||
&JWT_SECRET.load(),
|
||||
&ctx.auth.email,
|
||||
ctx.w_id,
|
||||
request.clone(),
|
||||
)?;
|
||||
let token = encode_with_internal_secret(claims)
|
||||
.await
|
||||
.map_err(|e| format!("Could not sign the link: {e}"))?;
|
||||
// The workspace first, for the login page to return to it; the page also reads it from
|
||||
// the token, so a link cut after the token still opens.
|
||||
let link = format!(
|
||||
"{}/secure_input?workspace={}&token={}",
|
||||
ctx.base_url(),
|
||||
enc(ctx.w_id),
|
||||
enc(&token)
|
||||
);
|
||||
let (kind, reference) = if request.get("resource").is_some() {
|
||||
("resource", format!("$res:{path}"))
|
||||
} else {
|
||||
("secret variable", format!("$var:{path}"))
|
||||
};
|
||||
Ok(format!(
|
||||
"Give the user this link, as a link, and tell them to open it, enter the secret there and come back: {link}\n\
|
||||
It opens a Windmill page, signed in as them, where the secret is saved as a draft of the {kind} {path} without reaching you. \
|
||||
It works for one hour and only for this user. Never ask for the secret in this conversation. \
|
||||
Once they say it is saved, check that the draft of the {kind} exists (they can change the path on the page, so ask which one if it is not at {path}), \
|
||||
then reference it as \"{reference}\". Runs read only deployed items: before running anything that uses it, offer to deploy it with its secret variables."
|
||||
))
|
||||
}
|
||||
|
||||
/// The card's request from the tool's arguments: the combinations it refuses, and a secret the
|
||||
/// model also put in the prepared value dropped, since the card would show it in clear.
|
||||
fn secret_request(w_id: &str, args: &Value) -> Result<Value, String> {
|
||||
let path = str_arg(args, "path")?;
|
||||
let label = str_arg(args, "label")?;
|
||||
let resource_type = opt_str_arg(args, "resource_type");
|
||||
let connection_string = bool_arg(args, "connection_string");
|
||||
let string_type = CONNECTION_STRING_TYPES
|
||||
.iter()
|
||||
.find(|(t, _, _, _)| Some(*t) == resource_type);
|
||||
if connection_string && string_type.is_none() {
|
||||
let types: Vec<_> = CONNECTION_STRING_TYPES.iter().map(|(t, ..)| *t).collect();
|
||||
return Err(format!(
|
||||
"connection_string works with resource_type {} only.",
|
||||
types.join(", ")
|
||||
));
|
||||
}
|
||||
// The string carries one secret, so the fields must ask for that one alone.
|
||||
let secret_fields: Vec<Value> = match string_type {
|
||||
Some((_, field, label, _)) => vec![json!({ "field": field, "label": label })],
|
||||
None => args
|
||||
.get("secret_fields")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let resource_value = args.get("resource_value").filter(|v| !v.is_null());
|
||||
let mut request = Map::new();
|
||||
request.insert("workspace".into(), json!(w_id));
|
||||
request.insert("path".into(), json!(path));
|
||||
request.insert("label".into(), json!(label));
|
||||
if let Some(description) = opt_str_arg(args, "description") {
|
||||
request.insert("description".into(), json!(description));
|
||||
}
|
||||
// Models sometimes escape the newlines of a JSON string twice.
|
||||
if let Some(text) = opt_str_arg(args, "help_text") {
|
||||
request.insert("helpText".into(), json!(text.replace("\\n", "\n")));
|
||||
}
|
||||
if bool_arg(args, "replace") {
|
||||
request.insert("replace".into(), json!(true));
|
||||
}
|
||||
match resource_type {
|
||||
Some(resource_type) => {
|
||||
if secret_fields.is_empty() {
|
||||
return Err("secret_fields is required with resource_type.".to_string());
|
||||
}
|
||||
let secret_keys: Vec<&str> = secret_fields
|
||||
.iter()
|
||||
.filter_map(|f| f.get("field").and_then(Value::as_str))
|
||||
.collect();
|
||||
let mut value: Map<String, Value> = string_type
|
||||
.and_then(|(_, _, _, details)| serde_json::from_str(details).ok())
|
||||
.unwrap_or_default();
|
||||
for (k, v) in resource_value
|
||||
.and_then(Value::as_object)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if !secret_keys.contains(&k.as_str()) {
|
||||
value.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let mut resource = json!({
|
||||
"type": resource_type,
|
||||
"value": value,
|
||||
"secretFields": secret_fields,
|
||||
});
|
||||
if string_type.is_some() {
|
||||
resource["connectionString"] = json!(connection_string);
|
||||
}
|
||||
request.insert("resource".into(), resource);
|
||||
}
|
||||
None if !secret_fields.is_empty() || resource_value.is_some() => {
|
||||
return Err("secret_fields and resource_value need resource_type.".to_string());
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(Value::Object(request))
|
||||
}
|
||||
|
||||
/// Where each secret is saved: the app-connect form's convention, a lone secret at the
|
||||
/// resource's path and several at `<path>_<field>`. Mirrors `secretVariablePaths`.
|
||||
fn variable_paths(request: &Value) -> Vec<String> {
|
||||
let path = request["path"].as_str().unwrap_or_default();
|
||||
let fields = request
|
||||
.pointer("/resource/secretFields")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
if fields.len() <= 1 {
|
||||
return vec![path.to_string()];
|
||||
}
|
||||
fields
|
||||
.iter()
|
||||
.filter_map(|f| f.get("field").and_then(Value::as_str))
|
||||
.map(|field| format!("{path}_{field}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Refused before the card shows, so a path the AI did not check costs it a retry rather than
|
||||
/// costing the user a choice it should have made.
|
||||
async fn taken_path(ctx: &Ctx<'_>, request: &Value) -> Result<Option<String>, String> {
|
||||
let path = request["path"].as_str().unwrap_or_default();
|
||||
if request.get("resource").is_some()
|
||||
&& exists(ctx, &format!("resources/exists/{}", path_enc(path))).await?
|
||||
{
|
||||
return Ok(Some(format!("A resource already exists at {path}")));
|
||||
}
|
||||
for p in variable_paths(request) {
|
||||
if exists(ctx, &format!("variables/exists/{}", path_enc(&p))).await? {
|
||||
return Ok(Some(format!("A variable already exists at {p}")));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn exists(ctx: &Ctx<'_>, route: &str) -> Result<bool, String> {
|
||||
Ok(ctx.get(&ctx.ws(route)).await?.as_bool().unwrap_or(false))
|
||||
}
|
||||
|
||||
fn now_secs() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a link to the card carries. Signed, so a link nobody's tool call made, which could
|
||||
/// pre-fill a host its author controls, does not open; bound to the user who asked.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct LinkClaims {
|
||||
sub: String,
|
||||
w: String,
|
||||
req: Value,
|
||||
exp: u64,
|
||||
}
|
||||
|
||||
impl LinkClaims {
|
||||
fn for_user(secret: &str, email: &str, w_id: &str, req: Value) -> Result<Self, String> {
|
||||
Ok(Self {
|
||||
sub: link_subject(secret, email)?,
|
||||
w: w_id.to_string(),
|
||||
req,
|
||||
exp: now_secs() + LINK_TTL_SECS,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The user a link is for, as a keyed hash of their email: the link passes through the
|
||||
/// client, its logs and its model, so it must carry no personal data, and only this server
|
||||
/// can tell whose it is.
|
||||
fn link_subject(secret: &str, email: &str) -> Result<String, String> {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).map_err(|e| e.to_string())?;
|
||||
mac.update(b"secure_input_link:");
|
||||
mac.update(email.as_bytes());
|
||||
Ok(hex::encode(mac.finalize().into_bytes()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct OpenLink {
|
||||
token: String,
|
||||
}
|
||||
|
||||
/// The card's request a link carries, for the page that draws it.
|
||||
pub(super) async fn open_secret_request(
|
||||
authed: ApiAuthed,
|
||||
Path(w_id): Path<String>,
|
||||
Json(OpenLink { token }): Json<OpenLink>,
|
||||
) -> JsonResult<Value> {
|
||||
let claims: LinkClaims = decode_with_internal_secret(&token)
|
||||
.await
|
||||
.map_err(|_| Error::BadRequest("This link is invalid or has expired.".to_string()))?;
|
||||
let subject = link_subject(&JWT_SECRET.load(), &authed.email).map_err(Error::internal_err)?;
|
||||
if claims.w != w_id || claims.sub != subject {
|
||||
return Err(Error::PermissionDenied(
|
||||
"This link was made for another user or workspace.".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(Json(claims.req))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn secret_request_keeps_secrets_off_the_card() {
|
||||
let request = secret_request(
|
||||
"ws",
|
||||
&json!({
|
||||
"path": "u/a/db", "label": "DB", "resource_type": "postgresql",
|
||||
"connection_string": true,
|
||||
"resource_value": { "host": "h", "password": "typed-by-the-model" },
|
||||
"secret_fields": [{ "field": "password" }, { "field": "root_certificate_pem" }],
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
// The details the user can switch to are complete, whatever the model prepared.
|
||||
assert_eq!(
|
||||
request["resource"]["value"],
|
||||
json!({ "host": "h", "port": 5432, "user": "", "dbname": "", "sslmode": "require" })
|
||||
);
|
||||
assert_eq!(
|
||||
request["resource"]["secretFields"],
|
||||
json!([{ "field": "password", "label": "Password" }])
|
||||
);
|
||||
assert_eq!(request["resource"]["connectionString"], true);
|
||||
let request = secret_request(
|
||||
"ws",
|
||||
&json!({ "path": "u/a/db", "label": "DB", "resource_type": "postgresql" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(request["resource"]["connectionString"], false);
|
||||
|
||||
let refused = |args: Value| secret_request("ws", &args).unwrap_err();
|
||||
assert!(
|
||||
refused(json!({ "path": "p", "label": "l", "resource_type": "s3" }))
|
||||
.contains("secret_fields is required")
|
||||
);
|
||||
assert!(refused(json!({ "path": "p", "label": "l", "resource_type": "mysql", "connection_string": true }))
|
||||
.contains("connection_string works with"));
|
||||
assert!(
|
||||
refused(json!({ "path": "p", "label": "l", "secret_fields": [{ "field": "k" }] }))
|
||||
.contains("need resource_type")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_names_its_user_without_their_email() {
|
||||
let claims = LinkClaims::for_user("key", "alice@example.com", "ws", json!({})).unwrap();
|
||||
assert!(!serde_json::to_string(&claims).unwrap().contains("alice"));
|
||||
let subject = |key: &str, email: &str| link_subject(key, email).unwrap();
|
||||
assert_eq!(claims.sub, subject("key", "alice@example.com"));
|
||||
assert_ne!(claims.sub, subject("key", "bob@example.com"));
|
||||
assert_ne!(claims.sub, subject("another key", "alice@example.com"));
|
||||
}
|
||||
}
|
||||
@@ -170,7 +170,7 @@ pub async fn handle_resume_action(
|
||||
secret.to_string(),
|
||||
)),
|
||||
Query(approver),
|
||||
QueryOrBody(Some(form_data)),
|
||||
QueryOrBody(Some(windmill_common::utils::PlainValue(form_data))),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
@@ -185,7 +185,7 @@ pub async fn handle_resume_action(
|
||||
secret.to_string(),
|
||||
)),
|
||||
Query(approver),
|
||||
QueryOrBody(Some(form_data)),
|
||||
QueryOrBody(Some(windmill_common::utils::PlainValue(form_data))),
|
||||
)
|
||||
.await
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ use windmill_common::runnable_settings::{
|
||||
use windmill_common::runtime_assets::{register_runtime_asset, InsertRuntimeAssetParams};
|
||||
use windmill_common::scripts::{ScriptModule, ScriptRunnableSettingsInline};
|
||||
use windmill_common::triggers::TriggerMetadata;
|
||||
use windmill_common::utils::{RunnableKind, WarnAfterExt};
|
||||
use windmill_common::utils::{PlainValue, RunnableKind, WarnAfterExt};
|
||||
use windmill_common::worker::{Connection, CLOUD_HOSTED, WINDMILL_DIR};
|
||||
use windmill_common::workspace_dependencies::{
|
||||
RawWorkspaceDependencies, MIN_VERSION_WORKSPACE_DEPENDENCIES,
|
||||
@@ -5165,7 +5165,7 @@ async fn validate_approval_token(
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ResumeSuspendedBody {
|
||||
payload: Option<serde_json::Value>,
|
||||
payload: Option<PlainValue>,
|
||||
approval_token: Option<String>,
|
||||
approved: Option<bool>,
|
||||
}
|
||||
@@ -5177,7 +5177,7 @@ async fn resume_suspended(
|
||||
Json(body): Json<ResumeSuspendedBody>,
|
||||
) -> error::Result<StatusCode> {
|
||||
let approved = body.approved.unwrap_or(true);
|
||||
let value = body.payload.unwrap_or(serde_json::Value::Null);
|
||||
let value = body.payload.map_or(serde_json::Value::Null, |v| v.0);
|
||||
|
||||
// Determine if we have a valid authed user or token
|
||||
let has_token = if let Some(ref token) = body.approval_token {
|
||||
@@ -6057,10 +6057,10 @@ pub async fn resume_suspended_job(
|
||||
Extension(db): Extension<DB>,
|
||||
Path((w_id, job_id, resume_id, secret)): Path<(String, Uuid, u32, String)>,
|
||||
Query(approver): Query<QueryApprover>,
|
||||
QueryOrBody(value): QueryOrBody<serde_json::Value>,
|
||||
QueryOrBody(value): QueryOrBody<PlainValue>,
|
||||
) -> error::Result<StatusCode> {
|
||||
resume_suspended_job_internal(
|
||||
value,
|
||||
value.map(|v| v.0),
|
||||
db,
|
||||
w_id,
|
||||
job_id,
|
||||
@@ -6489,10 +6489,10 @@ pub async fn cancel_suspended_job(
|
||||
Extension(db): Extension<DB>,
|
||||
Path((w_id, job_id, resume_id, secret)): Path<(String, Uuid, u32, String)>,
|
||||
Query(approver): Query<QueryApprover>,
|
||||
QueryOrBody(value): QueryOrBody<serde_json::Value>,
|
||||
QueryOrBody(value): QueryOrBody<PlainValue>,
|
||||
) -> error::Result<StatusCode> {
|
||||
resume_suspended_job_internal(
|
||||
value,
|
||||
value.map(|v| v.0),
|
||||
db,
|
||||
w_id,
|
||||
job_id,
|
||||
@@ -7732,6 +7732,14 @@ pub struct RestartFlowRequestBody {
|
||||
/// containers along the way.
|
||||
#[serde(default)]
|
||||
nested_path: Vec<NestedRestartStep>,
|
||||
/// For a parallel ForLoop / BranchAll at `step_id`: rerun only the iterations
|
||||
/// (branches) that did not succeed, keeping the others' results in their slots.
|
||||
#[serde(default)]
|
||||
failed_only: bool,
|
||||
/// With `failed_only`: resume each failed iteration (branch) at the step where it failed
|
||||
/// rather than rerunning it from its first step.
|
||||
#[serde(default)]
|
||||
from_failed_step: bool,
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
@@ -7936,6 +7944,8 @@ async fn resolve_nested_restart(
|
||||
flow_version: None,
|
||||
branch_chosen: child_branch_chosen,
|
||||
nested: deeper_nested,
|
||||
failed_only: false,
|
||||
from_failed_step: false,
|
||||
};
|
||||
|
||||
Ok((parent_branch_chosen, Some(Box::new(nested_chain))))
|
||||
@@ -7953,9 +7963,25 @@ pub async fn restart_flow(
|
||||
branch_or_iteration_n,
|
||||
flow_version,
|
||||
nested_path,
|
||||
failed_only,
|
||||
from_failed_step,
|
||||
}): Json<RestartFlowRequestBody>,
|
||||
) -> error::Result<(StatusCode, String)> {
|
||||
check_license_key_valid().await?;
|
||||
// `failed_only` applies to the restart point: `step_id`, or the last `nested_path` entry.
|
||||
let restart_point_n = nested_path
|
||||
.last()
|
||||
.map_or(branch_or_iteration_n, |s| s.branch_or_iteration_n);
|
||||
if from_failed_step && !failed_only {
|
||||
return Err(Error::BadRequest(
|
||||
"from_failed_step only applies with failed_only".to_string(),
|
||||
));
|
||||
}
|
||||
if failed_only && restart_point_n.unwrap_or(0) != 0 {
|
||||
return Err(Error::BadRequest(
|
||||
"failed_only reruns a whole parallel step; it cannot be combined with an iteration to restart at".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut tx = user_db.clone().begin(&authed).await?;
|
||||
let completed_job = sqlx::query!(
|
||||
@@ -7995,7 +8021,8 @@ pub async fn restart_flow(
|
||||
|
||||
let scheduled_for = run_query.get_scheduled_for(&db).await?;
|
||||
|
||||
let (top_branch_chosen, nested_chain) = resolve_nested_restart(
|
||||
let nested = !nested_path.is_empty();
|
||||
let (top_branch_chosen, mut nested_chain) = resolve_nested_restart(
|
||||
&db,
|
||||
&w_id,
|
||||
job_id,
|
||||
@@ -8005,6 +8032,15 @@ pub async fn restart_flow(
|
||||
flow_version.map(|v| (flow_path.as_str(), v)),
|
||||
)
|
||||
.await?;
|
||||
let mut innermost = nested_chain.as_deref_mut();
|
||||
while let Some(level) = innermost {
|
||||
if level.nested.is_none() {
|
||||
level.failed_only = failed_only;
|
||||
level.from_failed_step = from_failed_step;
|
||||
break;
|
||||
}
|
||||
innermost = level.nested.as_deref_mut();
|
||||
}
|
||||
|
||||
let tx = PushIsolationLevel::Isolated(user_db, authed.clone().into());
|
||||
|
||||
@@ -8020,6 +8056,8 @@ pub async fn restart_flow(
|
||||
flow_version,
|
||||
branch_chosen: top_branch_chosen,
|
||||
nested: nested_chain,
|
||||
failed_only: failed_only && !nested,
|
||||
from_failed_step: from_failed_step && !nested,
|
||||
},
|
||||
push_args,
|
||||
&authed.username,
|
||||
@@ -12650,6 +12688,28 @@ struct CompletedJobResult {
|
||||
#[derive(Deserialize)]
|
||||
struct GetCompletedJobQuery {
|
||||
get_started: Option<bool>,
|
||||
/// The caller is blocked until this job completes (the SDK wait helpers). Only such polls
|
||||
/// may be failed for a same-tag deadlock; a plain status read never is.
|
||||
wait_for_child: Option<bool>,
|
||||
}
|
||||
|
||||
/// Why a job blocked on its own child's result should stop waiting: the child is stuck behind a
|
||||
/// same-tag deadlock. A failed check answers `None`, so the poll carries on.
|
||||
async fn waiting_parent_deadlock(
|
||||
db: &DB,
|
||||
child: Uuid,
|
||||
authed: Option<&ApiAuthed>,
|
||||
wait_for_child: Option<bool>,
|
||||
) -> Option<Error> {
|
||||
if wait_for_child != Some(true) {
|
||||
return None;
|
||||
}
|
||||
let caller = authed?.job_id?;
|
||||
windmill_common::tag_deadlock::fail_fast_waiting_parent(db, child, Some(caller))
|
||||
.await
|
||||
.inspect_err(|e| tracing::warn!("same-tag deadlock check for job {child} failed: {e}"))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn get_completed_job_result_maybe(
|
||||
@@ -12659,7 +12719,7 @@ async fn get_completed_job_result_maybe(
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path((w_id, id)): Path<(String, Uuid)>,
|
||||
Query(GetCompletedJobQuery { get_started }): Query<GetCompletedJobQuery>,
|
||||
Query(GetCompletedJobQuery { get_started, wait_for_child }): Query<GetCompletedJobQuery>,
|
||||
) -> error::Result<Response> {
|
||||
let tags = opt_authed
|
||||
.as_ref()
|
||||
@@ -12712,6 +12772,10 @@ async fn get_completed_job_result_maybe(
|
||||
is_skipped: Some(res.is_skipped),
|
||||
})
|
||||
.into_response())
|
||||
} else if let Some(e) =
|
||||
waiting_parent_deadlock(&db, id, opt_authed.as_ref(), wait_for_child).await
|
||||
{
|
||||
Err(e)
|
||||
} else if get_started.is_some_and(|x| x) {
|
||||
// No completed row yet — the job may be queued/running. Returning its
|
||||
// running-state still discloses information about a (possibly private) job, so
|
||||
|
||||
@@ -71,7 +71,9 @@ pub struct WindmillBackend {
|
||||
/// `DisableDirectDeployment` holds a session to reading and running deployed items for
|
||||
/// everyone, admins and bypassers included: that workspace takes changes from its dev workspace
|
||||
/// or a fork, where drafts can go somewhere. Unreadable rules (`None`) hold it too. The in-app
|
||||
/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both.
|
||||
/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both. The
|
||||
/// chat alone lets a bypasser opt one session into working there directly, behind a confirmation
|
||||
/// an MCP client has no equivalent of, so a token stays held.
|
||||
fn workspace_access(access: SessionAccess, rules: Option<&[ProtectionRuleset]>) -> SessionAccess {
|
||||
let locked = rules.map_or(true, |rules| {
|
||||
rules
|
||||
|
||||
@@ -115,7 +115,9 @@ async fn list_logins() -> error::JsonResult<Logins> {
|
||||
struct OAuthConnectListItem {
|
||||
name: String,
|
||||
supports_client_credentials: bool,
|
||||
supports_authorization_code: bool,
|
||||
has_shared_credentials: bool,
|
||||
shares_client_credentials: bool,
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "private"))]
|
||||
|
||||
@@ -8,13 +8,12 @@ use http::HeaderMap;
|
||||
use hyper::StatusCode;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use sha2::Sha256;
|
||||
use sqlx::types::Uuid;
|
||||
use std::collections::HashMap;
|
||||
use windmill_common::error::{to_anyhow, Error};
|
||||
use windmill_common::flows::ApprovalSkin;
|
||||
use windmill_common::utils::truncate_with_ellipsis;
|
||||
use windmill_common::utils::{truncate_with_ellipsis, PlainValue};
|
||||
use windmill_common::variables::{get_secret_value_as_admin, get_workspace_key};
|
||||
|
||||
use crate::db::{ApiAuthed, DB};
|
||||
@@ -84,7 +83,7 @@ struct State {
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
enum ValueInput {
|
||||
PlainTextInput { value: Option<Value> },
|
||||
PlainTextInput { value: Option<PlainValue> },
|
||||
Datepicker { selected_date: Option<String> },
|
||||
Timepicker { selected_time: Option<String> },
|
||||
StaticSelect { selected_option: Option<SelectedOption> },
|
||||
@@ -888,7 +887,7 @@ fn process_non_datetime_inputs(
|
||||
value
|
||||
.as_ref()
|
||||
.and_then(|v| {
|
||||
v.as_str().and_then(|s| s.parse::<f64>().ok()).map(|num| {
|
||||
v.0.as_str().and_then(|s| s.parse::<f64>().ok()).map(|num| {
|
||||
if action_id.ends_with("_type_integer") {
|
||||
(
|
||||
base_action_id.to_string(),
|
||||
@@ -906,9 +905,9 @@ fn process_non_datetime_inputs(
|
||||
}
|
||||
|
||||
// Plain text input: Extracts the text value
|
||||
ValueInput::PlainTextInput { value } => value
|
||||
.as_ref()
|
||||
.map(|v| (action_id.to_string(), v.clone().into())),
|
||||
ValueInput::PlainTextInput { value } => {
|
||||
value.as_ref().map(|v| (action_id.to_string(), v.0.clone()))
|
||||
}
|
||||
|
||||
// Static select: Extracts the selected option's value
|
||||
ValueInput::StaticSelect { selected_option } => selected_option
|
||||
|
||||
@@ -1235,6 +1235,12 @@ fn plan_document(
|
||||
Value::is_boolean,
|
||||
"a boolean",
|
||||
),
|
||||
(
|
||||
"error_handler",
|
||||
"muted_on_ui_runs",
|
||||
Value::is_boolean,
|
||||
"a boolean",
|
||||
),
|
||||
(
|
||||
"variable_expiration_handler",
|
||||
"muted_on_user_path",
|
||||
@@ -1282,6 +1288,15 @@ fn plan_document(
|
||||
}
|
||||
}
|
||||
}
|
||||
// ...but stores this one only when on, so an off one compares as absent.
|
||||
if let Some(handler) = desired
|
||||
.get_mut("error_handler")
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
if handler.get("muted_on_ui_runs") != Some(&Value::Bool(true)) {
|
||||
handler.remove("muted_on_ui_runs");
|
||||
}
|
||||
}
|
||||
for key in SECRET_KEYS {
|
||||
if let Some(v) = desired.remove(*key) {
|
||||
if let Some(v) = resolve_secret(key, v, mc, &mut warnings) {
|
||||
@@ -1429,6 +1444,7 @@ fn plan_document(
|
||||
"extra_args": handler.get("extra_args"),
|
||||
"muted_on_cancel": handler.get("muted_on_cancel").and_then(Value::as_bool).unwrap_or(false),
|
||||
"muted_on_user_path": handler.get("muted_on_user_path").and_then(Value::as_bool).unwrap_or(false),
|
||||
"muted_on_ui_runs": handler.get("muted_on_ui_runs").and_then(Value::as_bool).unwrap_or(false),
|
||||
"fallback_to_instance_alerts": if fallback_changes { fallback.and_then(|f| f.as_bool()) } else { None },
|
||||
}),
|
||||
);
|
||||
@@ -2361,6 +2377,24 @@ mod tests {
|
||||
assert!(p.changes.is_empty(), "{:?}", keys(&p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn muted_on_ui_runs_off_matches_a_blob_without_it() {
|
||||
let mc = WorkspaceCrypt::new("k");
|
||||
let names = DatatableNames::default();
|
||||
let mut cur = current();
|
||||
cur.insert(
|
||||
"error_handler".into(),
|
||||
json!({ "path": "f/x", "muted_on_cancel": false, "muted_on_user_path": false }),
|
||||
);
|
||||
let off = doc(json!({ "error_handler": { "path": "f/x", "muted_on_ui_runs": false } }));
|
||||
let p = plan_document(cur.clone(), off, false, &mc, &names).unwrap();
|
||||
assert!(p.changes.is_empty(), "{:?}", keys(&p));
|
||||
|
||||
let on = doc(json!({ "error_handler": { "path": "f/x", "muted_on_ui_runs": true } }));
|
||||
let p = plan_document(cur, on, false, &mc, &names).unwrap();
|
||||
assert_eq!(keys(&p), ["error_handler"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_expiration_handler_is_managed_only_when_stated() {
|
||||
let mc = WorkspaceCrypt::new("k");
|
||||
|
||||
@@ -841,6 +841,8 @@ mod reserved_args_tests {
|
||||
("_MODULES\u{0}", r#"{"m.py": "evil"}"#),
|
||||
("_TEMP_SCRIPT_REFS", r#"{"f/a/b": "deadbeef"}"#),
|
||||
("_TEMP_SCRIPT_REFS\u{0}", r#"{"f/a/b": "deadbeef"}"#),
|
||||
("_FLOW_PATH", r#""u/alice/prod_db?""#),
|
||||
("_FLOW_PATH\u{0}", r#""u/alice/prod_db?""#),
|
||||
// Neighbours that must not be caught by a prefix/contains match.
|
||||
("_TEMP_SCRIPT_REFS_", r#"1"#),
|
||||
("entrypoint", r#""main""#),
|
||||
|
||||
@@ -145,6 +145,7 @@ pub mod ssrf;
|
||||
pub mod stats_ee;
|
||||
pub mod stats_oss;
|
||||
pub mod stream;
|
||||
pub mod tag_deadlock;
|
||||
#[cfg(feature = "private")]
|
||||
pub mod teams_ee;
|
||||
pub mod teams_oss;
|
||||
|
||||
@@ -44,10 +44,18 @@ pub const MIN_VERSION_SUPPORTS_ED25519_LICENSE: VC = vc(1, 838, 0, "Ed25519 lice
|
||||
// lease-free pull overlapping its write would keep a mix of old and new files; until the
|
||||
// whole fleet has it, read-only mounts take the lease. Must name the release this ships in.
|
||||
pub const MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES: VC = vc(1, 872, 0, "Lease-free volume reads");
|
||||
// A failed-only restart queues its parallel step as `InProgress` with nil slots to rerun. A
|
||||
// worker that predates it rejects that status and fails the restart. Must name the release
|
||||
// this ships in.
|
||||
pub const MIN_VERSION_SUPPORTS_FAILED_ONLY_RESTART: VC =
|
||||
vc(1, 883, 0, "Rerun only failed iterations");
|
||||
// A worker that predates `FlowStatus::test_subflows` ignores it and runs the deployed subflow,
|
||||
// so a step the test mocks would run for real. Must name the release this ships in.
|
||||
pub const MIN_VERSION_SUPPORTS_FLOW_TEST_SUBFLOWS: VC =
|
||||
vc(1, 879, 0, "Overriding steps inside subflows in flow tests");
|
||||
// A worker before this release decodes `trigger_kind` strictly and cannot read `ui`, so a job
|
||||
// stamped with it would fail on every pull of that worker.
|
||||
pub const MIN_VERSION_SUPPORTS_UI_TRIGGER_KIND: VC = vc(1, 776, 0, "ui trigger kind");
|
||||
pub const MIN_VERSION_SUPPORTS_NODE_DEBOUNCING: VC = vc(1, 658, 0, "Flow node debouncing");
|
||||
pub const MIN_VERSION_SUPPORTS_TOKEN_HASH: VC = vc(1, 659, 0, "Token hash storage");
|
||||
pub const MIN_VERSION_SUPPORTS_SYNC_JOBS_DEBOUNCING: VC = vc(1, 602, 0, "Sync jobs debouncing");
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
//! Same-tag wait deadlocks: every live worker serving a tag is executing a job that has a child
|
||||
//! queued on that same tag, so none of those children can start until a parent gives up.
|
||||
//!
|
||||
//! A parent that merely queued a child and carries on (fire-and-forget), or that reads its
|
||||
//! child's status between other work, looks the same from the queue, and its worker frees up
|
||||
//! once it finishes. So a holder counts only while it is provably blocked on that very child:
|
||||
//! the SDK wait helpers say so on each poll (`wait_for_child`), as does a sync `run_wait_result`,
|
||||
//! and each such check marks the parent's queue row with the child (`extras.waiting_on`). A tag
|
||||
//! is deadlocked only when every holder is freshly marked as waiting on one of its stuck
|
||||
//! children; a parent waiting on a child of another tag is not one.
|
||||
//!
|
||||
//! Everything here reads the queue across workspaces and writes instance-level alerts: it is
|
||||
//! for the server's own maintenance and wait paths, never a workspace-facing query.
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::Mutex,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{error, DB};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
/// How long a child must have been startable without starting before its tag can be called
|
||||
/// deadlocked. It absorbs a worker that is between jobs or a parent that is about to finish.
|
||||
pub static ref TAG_DEADLOCK_GRACE_SECS: i64 = std::env::var("TAG_DEADLOCK_GRACE_SECS")
|
||||
.ok()
|
||||
.and_then(|x| x.parse().ok())
|
||||
.unwrap_or(60);
|
||||
|
||||
static ref CACHE: Mutex<HashMap<String, (Instant, Option<TagDeadlock>)>> =
|
||||
Mutex::new(HashMap::new());
|
||||
}
|
||||
|
||||
const CACHE_TTL: Duration = Duration::from_secs(5);
|
||||
/// How long a parent's last wait check on its stuck child counts as it still waiting. Checks
|
||||
/// mark at most every 5s, so this spans several of them.
|
||||
const WAITING_MARK_TTL_SECS: f64 = 30.0;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TagDeadlock {
|
||||
pub tag: String,
|
||||
/// Live workers serving the tag, all of them held by a blocked parent.
|
||||
pub workers: i64,
|
||||
/// The jobs holding those workers.
|
||||
pub parents: Vec<Uuid>,
|
||||
}
|
||||
|
||||
/// Every tag (or only `tag`) whose live workers are all held by a running job freshly marked as
|
||||
/// waiting on its own child queued on that tag for longer than the grace period (see the module
|
||||
/// doc). The child is reached through the mark rather than by walking the parent's children,
|
||||
/// which on a backlog costs a lookup per queued child.
|
||||
///
|
||||
/// Instance-wide and unauthorized: the parents it returns belong to any workspace, so they may
|
||||
/// reach superadmin alerts but not a workspace caller.
|
||||
///
|
||||
/// A worker's job is read from `v2_job_queue` (`running`, `worker`), not from
|
||||
/// `worker_ping.current_job_id`, which keeps naming the last job after the worker went idle.
|
||||
/// Flow jobs are excluded because they hold no worker while their steps run, and so are
|
||||
/// parked jobs (a suspended workflow-as-code parent keeps `running` but released its slot).
|
||||
/// Native-mode workers run several jobs at once, so a tag one of them serves is never reported.
|
||||
pub async fn deadlocked_tags(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
tag: Option<&str>,
|
||||
) -> error::Result<Vec<TagDeadlock>> {
|
||||
let rows = sqlx::query!(
|
||||
r#"
|
||||
WITH blocked AS (
|
||||
SELECT DISTINCT r.worker, c.tag, r.id AS parent
|
||||
FROM v2_job_queue r
|
||||
JOIN v2_job rj ON rj.id = r.id
|
||||
JOIN v2_job_queue c ON c.id = (r.extras->'waiting_on'->>'child')::uuid
|
||||
JOIN v2_job cj ON cj.id = c.id AND cj.parent_job = r.id
|
||||
WHERE r.running AND r.worker IS NOT NULL AND r.suspend = 0 AND r.started_at IS NOT NULL
|
||||
AND (r.extras->'waiting_on'->>'at')::timestamptz
|
||||
> now() - make_interval(secs => $3)
|
||||
AND rj.kind NOT IN ('flow', 'flowpreview', 'singlestepflow', 'flownode',
|
||||
'unassigned_flow', 'unassigned_singlestepflow')
|
||||
AND NOT c.running AND c.suspend = 0
|
||||
AND c.scheduled_for <= now() - make_interval(secs => $2::bigint::double precision)
|
||||
AND ($1::text IS NULL OR c.tag = $1)
|
||||
),
|
||||
live AS (
|
||||
SELECT worker, unnest(custom_tags) AS tag, native_mode
|
||||
FROM worker_ping
|
||||
WHERE ping_at > now() - interval '60 seconds' AND draining IS NOT TRUE
|
||||
)
|
||||
SELECT l.tag AS "tag!", count(*) AS "workers!",
|
||||
array_agg(b.parent) FILTER (WHERE b.parent IS NOT NULL) AS "parents!"
|
||||
FROM live l
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT parent FROM blocked b WHERE b.worker = l.worker AND b.tag = l.tag LIMIT 1
|
||||
) b ON true
|
||||
WHERE l.tag IN (SELECT tag FROM blocked)
|
||||
GROUP BY l.tag
|
||||
HAVING count(*) = count(b.parent) AND NOT bool_or(l.native_mode)
|
||||
"#,
|
||||
tag,
|
||||
*TAG_DEADLOCK_GRACE_SECS,
|
||||
WAITING_MARK_TTL_SECS,
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| TagDeadlock { tag: r.tag, workers: r.workers, parents: r.parents })
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The deadlock that the parent waiting on `child` is part of, if any: `child` has not started
|
||||
/// past the grace period, and every worker of its tag, the parent's included, is held by a job
|
||||
/// waiting on a child stuck on that tag. `waiter` is the job known to be waiting; `None` takes
|
||||
/// the child's own `parent_job`, for a caller that created the child and is waiting on it.
|
||||
/// Marks that parent as waiting on `child`, which is what lets the other holders' checks count it.
|
||||
async fn deadlock_for_waiting_parent(
|
||||
db: &DB,
|
||||
child: Uuid,
|
||||
waiter: Option<Uuid>,
|
||||
) -> error::Result<Option<(TagDeadlock, Uuid)>> {
|
||||
let stuck = sqlx::query!(
|
||||
r#"SELECT q.tag, j.parent_job AS "parent!"
|
||||
FROM v2_job_queue q JOIN v2_job j ON j.id = q.id
|
||||
WHERE q.id = $1 AND j.parent_job = COALESCE($2, j.parent_job)
|
||||
AND NOT q.running AND q.suspend = 0
|
||||
AND q.scheduled_for <= now() - make_interval(secs => $3::bigint::double precision)"#,
|
||||
child,
|
||||
waiter,
|
||||
*TAG_DEADLOCK_GRACE_SECS,
|
||||
)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
let Some((tag, parent)) = stuck.map(|r| (r.tag, r.parent)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
sqlx::query!(
|
||||
r#"UPDATE v2_job_queue
|
||||
SET extras = jsonb_set(COALESCE(extras, '{}'::jsonb), '{waiting_on}',
|
||||
jsonb_build_object('child', $2::uuid, 'at', now()))
|
||||
WHERE id = $1 AND running
|
||||
AND (extras->'waiting_on'->>'child' IS DISTINCT FROM $2::uuid::text
|
||||
OR (extras->'waiting_on'->>'at')::timestamptz < now() - interval '5 seconds')"#,
|
||||
parent,
|
||||
child,
|
||||
)
|
||||
.execute(db)
|
||||
.await?;
|
||||
|
||||
let cached = CACHE
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&tag)
|
||||
.filter(|(at, _)| at.elapsed() < CACHE_TTL)
|
||||
.map(|(_, d)| d.clone());
|
||||
let deadlock = match cached {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
let d = deadlocked_tags(db, Some(&tag))
|
||||
.await?
|
||||
.into_iter()
|
||||
.next();
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
cache.retain(|_, (at, _)| at.elapsed() < CACHE_TTL);
|
||||
cache.insert(tag, (Instant::now(), d.clone()));
|
||||
d
|
||||
}
|
||||
};
|
||||
Ok(deadlock
|
||||
.filter(|d| d.parents.contains(&parent))
|
||||
.map(|d| (d, parent)))
|
||||
}
|
||||
|
||||
/// The error to fail a parent's wait on `child` with when it is part of a same-tag deadlock
|
||||
/// (see [`deadlock_for_waiting_parent`]), after raising the tag's alert.
|
||||
///
|
||||
/// One failed parent is enough to start draining the tag: its worker takes a child, that child's
|
||||
/// parent completes, and so on. So failing it also clears its waiting mark: until it exits it
|
||||
/// still holds its worker, and every other parent of the tag would otherwise be failed in that
|
||||
/// window too. Under the tag's advisory lock the deadlock is read again rather than from the
|
||||
/// cache, so a check that follows one failure sees that parent no longer waiting.
|
||||
///
|
||||
/// `waiter` must be the authenticated caller's own job, or `None` only when the caller created
|
||||
/// `child` in this request: the check marks that parent as waiting and fails its wait.
|
||||
pub async fn fail_fast_waiting_parent(
|
||||
db: &DB,
|
||||
child: Uuid,
|
||||
waiter: Option<Uuid>,
|
||||
) -> error::Result<Option<error::Error>> {
|
||||
let Some((d, parent)) = deadlock_for_waiting_parent(db, child, waiter).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut tx = db.begin().await?;
|
||||
sqlx::query!(
|
||||
"SELECT pg_advisory_xact_lock(hashtext('tag_deadlock:' || $1::text))",
|
||||
&d.tag
|
||||
)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let Some(d) = deadlocked_tags(&mut *tx, Some(&d.tag))
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|d| d.parents.contains(&parent))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
sqlx::query!(
|
||||
"UPDATE v2_job_queue SET extras = extras - 'waiting_on' WHERE id = $1",
|
||||
parent
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
alert_on_fail_fast(db, &d).await;
|
||||
Ok(Some(deadlock_error(child, &d)))
|
||||
}
|
||||
|
||||
fn deadlock_error(child: Uuid, d: &TagDeadlock) -> error::Error {
|
||||
error::Error::Generic(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
format!(
|
||||
"job {child} cannot start: every worker serving tag `{}` ({} worker{}) is running a job \
|
||||
that waits on a child queued on that same tag, this one included. Run the child on \
|
||||
another tag, add workers to `{}`, or use workflow-as-code so the parent releases its \
|
||||
worker while it waits.",
|
||||
d.tag,
|
||||
d.workers,
|
||||
if d.workers == 1 { "" } else { "s" },
|
||||
d.tag,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const ALERT_RESOURCE_PREFIX: &str = "tag_deadlock:";
|
||||
|
||||
/// Tag deadlock alerts still open: their latest row is the alert, not its recovery. Read from
|
||||
/// `alerts` so every server agrees and a restart does not re-alert.
|
||||
async fn open_alerts(db: &DB) -> error::Result<Vec<String>> {
|
||||
Ok(sqlx::query_scalar!(
|
||||
r#"SELECT resource AS "resource!" FROM (
|
||||
SELECT DISTINCT ON (resource) resource, alert_type
|
||||
FROM alerts
|
||||
WHERE resource LIKE 'tag_deadlock:%' AND created_at > now() - interval '7 days'
|
||||
ORDER BY resource, created_at DESC, id DESC
|
||||
) latest WHERE alert_type = 'critical_error'"#
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn alert_unless_open(db: &DB, d: &TagDeadlock, open: &[String]) {
|
||||
let resource = format!("{ALERT_RESOURCE_PREFIX}{}", d.tag);
|
||||
if open.contains(&resource) {
|
||||
return;
|
||||
}
|
||||
crate::utils::report_critical_error(
|
||||
format!(
|
||||
"Tag `{}` is deadlocked: all {} of its workers are running a job waiting on a child \
|
||||
queued on `{}` for over {}s, which none of them can start. One waiting job is failed \
|
||||
to break it. Jobs holding the workers: {}",
|
||||
d.tag,
|
||||
d.workers,
|
||||
d.tag,
|
||||
*TAG_DEADLOCK_GRACE_SECS,
|
||||
d.parents
|
||||
.iter()
|
||||
.map(|p| p.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
),
|
||||
db.clone(),
|
||||
None,
|
||||
Some(&resource),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Alerts on a deadlock a waiting parent is about to be failed for. This is the only place a tag
|
||||
/// deadlock alert is raised: a deadlock counts only while its parents are polling with a fresh
|
||||
/// waiting mark, and such a poll reaches this path within seconds.
|
||||
async fn alert_on_fail_fast(db: &DB, d: &TagDeadlock) {
|
||||
match open_alerts(db).await {
|
||||
Ok(open) => alert_unless_open(db, d, &open).await,
|
||||
Err(e) => tracing::warn!("could not read open tag deadlock alerts: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Raises a recovered alert for each tag with an open deadlock alert that is no longer
|
||||
/// deadlocked. Instance maintenance, run by the server monitor. The queue is only read while an
|
||||
/// alert is open, so the monitor costs one read of `alerts` the rest of the time.
|
||||
pub async fn recover_tag_deadlock_alerts(db: &DB) -> error::Result<()> {
|
||||
for resource in open_alerts(db).await? {
|
||||
let tag = &resource[ALERT_RESOURCE_PREFIX.len()..];
|
||||
if deadlocked_tags(db, Some(tag)).await?.is_empty() {
|
||||
crate::utils::report_recovered_critical_error(
|
||||
format!("Tag `{tag}` is no longer deadlocked"),
|
||||
db.clone(),
|
||||
None,
|
||||
Some(&resource),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
async fn live_worker(db: &DB, worker: &str) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO worker_ping (worker, worker_instance, ping_at, custom_tags)
|
||||
VALUES ($1, 'test', now(), ARRAY['t1'])",
|
||||
)
|
||||
.bind(worker)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A job of `kind` running on `worker`, with one child queued on `t1` for two minutes.
|
||||
async fn parent_with_stuck_child(
|
||||
db: &DB,
|
||||
worker: &str,
|
||||
kind: &str,
|
||||
) -> anyhow::Result<(Uuid, Uuid)> {
|
||||
let (parent, child) = (Uuid::new_v4(), Uuid::new_v4());
|
||||
sqlx::query("INSERT INTO v2_job (id, workspace_id, kind, tag) VALUES ($1, 'admins', $2::job_kind, 't1')")
|
||||
.bind(parent)
|
||||
.bind(kind)
|
||||
.execute(db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, started_at, worker, tag)
|
||||
VALUES ($1, 'admins', now(), true, now(), $2, 't1')",
|
||||
)
|
||||
.bind(parent)
|
||||
.bind(worker)
|
||||
.execute(db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job (id, workspace_id, kind, tag, parent_job) VALUES ($1, 'admins', 'script', 't1', $2)",
|
||||
)
|
||||
.bind(child)
|
||||
.bind(parent)
|
||||
.execute(db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, tag)
|
||||
VALUES ($1, 'admins', now() - interval '2 minutes', false, 't1')",
|
||||
)
|
||||
.bind(child)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok((parent, child))
|
||||
}
|
||||
|
||||
async fn mark_waiting(db: &DB, parent: Uuid, child: Uuid) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"UPDATE v2_job_queue SET extras = jsonb_build_object('waiting_on',
|
||||
jsonb_build_object('child', $2::uuid, 'at', now())) WHERE id = $1",
|
||||
)
|
||||
.bind(parent)
|
||||
.bind(child)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../migrations")]
|
||||
async fn a_tag_is_deadlocked_only_when_every_worker_holds_a_blocked_parent(
|
||||
db: DB,
|
||||
) -> anyhow::Result<()> {
|
||||
live_worker(&db, "w1").await?;
|
||||
live_worker(&db, "w2").await?;
|
||||
let (p1, c1) = parent_with_stuck_child(&db, "w1", "script").await?;
|
||||
mark_waiting(&db, p1, c1).await?;
|
||||
assert!(deadlocked_tags(&db, None).await?.is_empty(), "w2 is free");
|
||||
|
||||
// A flow holds no worker while its step waits, nor does a parked workflow-as-code parent.
|
||||
let (p2, c2) = parent_with_stuck_child(&db, "w2", "flow").await?;
|
||||
mark_waiting(&db, p2, c2).await?;
|
||||
assert!(deadlocked_tags(&db, None).await?.is_empty());
|
||||
sqlx::query("UPDATE v2_job SET kind = 'script' WHERE id = $1")
|
||||
.bind(p2)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query("UPDATE v2_job_queue SET suspend = 1, started_at = NULL WHERE id = $1")
|
||||
.bind(p2)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
assert!(deadlocked_tags(&db, None).await?.is_empty());
|
||||
|
||||
sqlx::query("UPDATE v2_job_queue SET suspend = 0, started_at = now() WHERE id = $1")
|
||||
.bind(p2)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let d = deadlocked_tags(&db, Some("t1")).await?;
|
||||
assert_eq!(d.len(), 1);
|
||||
assert_eq!(d[0].workers, 2);
|
||||
assert!(d[0].parents.contains(&p1) && d[0].parents.contains(&p2));
|
||||
sqlx::query("UPDATE v2_job_queue SET extras = extras - 'waiting_on'")
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
// p2 has not polled for its child, so it may be about to finish: no wait is failed yet.
|
||||
assert!(deadlock_for_waiting_parent(&db, c1, Some(p1))
|
||||
.await?
|
||||
.is_none());
|
||||
// Nor while p2 waits on a child of another tag: once that one runs, p2 frees its worker.
|
||||
let other = Uuid::new_v4();
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job (id, workspace_id, kind, tag, parent_job)
|
||||
VALUES ($1, 'admins', 'script', 't2', $2)",
|
||||
)
|
||||
.bind(other)
|
||||
.bind(p2)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, tag)
|
||||
VALUES ($1, 'admins', now() - interval '2 minutes', false, 't2')",
|
||||
)
|
||||
.bind(other)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
assert!(deadlock_for_waiting_parent(&db, other, Some(p2))
|
||||
.await?
|
||||
.is_none());
|
||||
CACHE.lock().unwrap().clear();
|
||||
assert!(deadlock_for_waiting_parent(&db, c1, Some(p1))
|
||||
.await?
|
||||
.is_none());
|
||||
CACHE.lock().unwrap().clear();
|
||||
// Once p2 waits too, the polling parent of a stuck child is part of the deadlock.
|
||||
assert!(deadlock_for_waiting_parent(&db, c2, Some(p2))
|
||||
.await?
|
||||
.is_some());
|
||||
assert!(deadlock_for_waiting_parent(&db, c1, None).await?.is_some());
|
||||
assert!(
|
||||
deadlock_for_waiting_parent(&db, c1, Some(p2))
|
||||
.await?
|
||||
.is_none(),
|
||||
"not its child"
|
||||
);
|
||||
|
||||
// One failed parent drains the tag. It stops counting as waiting, so the other holder
|
||||
// is spared while the failed one still holds its worker, whichever process it polls.
|
||||
assert!(fail_fast_waiting_parent(&db, c1, Some(p1)).await?.is_some());
|
||||
assert!(fail_fast_waiting_parent(&db, c2, Some(p2)).await?.is_none());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1698,6 +1698,86 @@ pub fn strip_json_nul(serialized: &str) -> Cow<'_, str> {
|
||||
Cow::Owned(String::from_utf8(out).expect("removing a NUL escape preserves valid UTF-8"))
|
||||
}
|
||||
|
||||
/// The key serde_json's `raw_value` feature reserves: read as a `Value`, an object holding it
|
||||
/// first is replaced by the JSON text in its string, parsed again with a fresh nesting limit.
|
||||
const RAW_VALUE_TOKEN: &str = "$serde_json::private::RawValue";
|
||||
|
||||
/// A `serde_json::Value` read from a request body. Unlike `Value`, it refuses
|
||||
/// [`RAW_VALUE_TOKEN`] as a key at any depth, so the value read is the one jsonb stores, and
|
||||
/// texts nested in texts stay under serde_json's nesting limit.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PlainValue(pub serde_json::Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for PlainValue {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
|
||||
use serde::de::{MapAccess, SeqAccess, Visitor};
|
||||
use serde_json::Value;
|
||||
|
||||
struct PlainVisitor;
|
||||
impl<'de> Visitor<'de> for PlainVisitor {
|
||||
type Value = Value;
|
||||
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("any JSON value")
|
||||
}
|
||||
fn visit_unit<E>(self) -> std::result::Result<Value, E> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
fn visit_none<E>(self) -> std::result::Result<Value, E> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
fn visit_some<D: Deserializer<'de>>(
|
||||
self,
|
||||
d: D,
|
||||
) -> std::result::Result<Value, D::Error> {
|
||||
PlainValue::deserialize(d).map(|v| v.0)
|
||||
}
|
||||
fn visit_bool<E>(self, v: bool) -> std::result::Result<Value, E> {
|
||||
Ok(v.into())
|
||||
}
|
||||
fn visit_i64<E>(self, v: i64) -> std::result::Result<Value, E> {
|
||||
Ok(v.into())
|
||||
}
|
||||
fn visit_u64<E>(self, v: u64) -> std::result::Result<Value, E> {
|
||||
Ok(v.into())
|
||||
}
|
||||
fn visit_f64<E>(self, v: f64) -> std::result::Result<Value, E> {
|
||||
Ok(serde_json::Number::from_f64(v).map_or(Value::Null, Value::Number))
|
||||
}
|
||||
fn visit_str<E>(self, v: &str) -> std::result::Result<Value, E> {
|
||||
Ok(v.into())
|
||||
}
|
||||
fn visit_string<E>(self, v: String) -> std::result::Result<Value, E> {
|
||||
Ok(v.into())
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(
|
||||
self,
|
||||
mut seq: A,
|
||||
) -> std::result::Result<Value, A::Error> {
|
||||
let mut values = Vec::new();
|
||||
while let Some(v) = seq.next_element::<PlainValue>()? {
|
||||
values.push(v.0);
|
||||
}
|
||||
Ok(Value::Array(values))
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(
|
||||
self,
|
||||
mut map: A,
|
||||
) -> std::result::Result<Value, A::Error> {
|
||||
let mut values = serde_json::Map::new();
|
||||
while let Some(k) = map.next_key::<String>()? {
|
||||
if k == RAW_VALUE_TOKEN {
|
||||
return Err(A::Error::custom("reserved key"));
|
||||
}
|
||||
values.insert(k, map.next_value::<PlainValue>()?.0);
|
||||
}
|
||||
Ok(Value::Object(values))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_any(PlainVisitor).map(PlainValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefix of `s` holding at most `max_chars` characters.
|
||||
/// Slicing by byte index (`&s[..n]`) panics when `n` lands inside a multibyte character.
|
||||
pub fn truncate_chars(s: &str, max_chars: usize) -> &str {
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::db::{Authable, UserDB};
|
||||
use crate::error::{self, Error};
|
||||
use crate::scripts::ScriptHash;
|
||||
use crate::secret_backend::{get_secret_value, resolves_externally};
|
||||
use crate::utils::{strip_json_nul, WarnAfterExt};
|
||||
use crate::utils::{strip_json_nul, PlainValue, WarnAfterExt};
|
||||
use crate::worker::{to_raw_value, Connection};
|
||||
use crate::workspace_crypt::CipherFormat;
|
||||
pub use crate::workspace_crypt::WorkspaceCrypt;
|
||||
@@ -43,12 +43,15 @@ pub fn untrusted_arg_interpolates(arg: &str) -> bool {
|
||||
}
|
||||
|
||||
/// `args`, which an untrusted user controls on a job that runs as someone else, with every one the
|
||||
/// worker would interpolate rewritten so it no longer is. The others keep their exact text.
|
||||
/// worker would interpolate rewritten so it no longer is. The others keep their exact text, but
|
||||
/// one named like serde_json's raw value key is dropped: a flow reading `flow_input` as a `Value`
|
||||
/// would get the JSON text in it in place of the args.
|
||||
pub fn omit_untrusted_interpolation(
|
||||
args: HashMap<String, Box<RawValue>>,
|
||||
resource_omitted: &str,
|
||||
) -> HashMap<String, Box<RawValue>> {
|
||||
args.into_iter()
|
||||
.filter(|(k, _)| decoded(&serde_json::json!({ k: 0 }).to_string()).is_some())
|
||||
.map(|(k, v)| {
|
||||
if !may_reference(v.get()) {
|
||||
return (k, v);
|
||||
@@ -68,6 +71,15 @@ pub fn omit_untrusted_interpolation(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `text`, handed as a string to jobs that run under another identity than its writer's, with
|
||||
/// every reference rewritten as [`omit_untrusted_interpolation`] would.
|
||||
pub fn omit_untrusted_text(text: &str) -> String {
|
||||
omitted(
|
||||
text,
|
||||
"The following resource has been omitted for security reasons: ",
|
||||
)
|
||||
}
|
||||
|
||||
/// Without a `$`, spelled out or escaped, an argument holds no reference however jsonb rewrites
|
||||
/// it, so it needs no decoding, even one serde_json cannot read.
|
||||
fn may_reference(arg: &str) -> bool {
|
||||
@@ -76,9 +88,11 @@ fn may_reference(arg: &str) -> bool {
|
||||
|
||||
/// `arg` as its jsonb column will hold it: the NUL stripped as `push` strips it, escapes decoded,
|
||||
/// the last copy of a duplicate key kept. `None` for what serde_json cannot read, which jsonb may
|
||||
/// still store (`1e400`).
|
||||
/// still store (`1e400`), and for what a later read as a `Value` would replace ([`PlainValue`]).
|
||||
fn decoded(arg: &str) -> Option<serde_json::Value> {
|
||||
serde_json::from_str(&strip_json_nul(arg)).ok()
|
||||
serde_json::from_str::<PlainValue>(&strip_json_nul(arg))
|
||||
.ok()
|
||||
.map(|v| v.0)
|
||||
}
|
||||
|
||||
/// The worker's own test on the whole argument, plus a reserved `WM_*` key or value at any depth,
|
||||
@@ -965,7 +979,7 @@ pub async fn get_reserved_variables(
|
||||
})).collect()
|
||||
}
|
||||
|
||||
async fn get_cached_workspace_envs(conn: &Connection, w_id: &str) -> Vec<(String, String)> {
|
||||
pub async fn get_cached_workspace_envs(conn: &Connection, w_id: &str) -> Vec<(String, String)> {
|
||||
let cached_envs_o = CUSTOM_ENVS_CACHE.get(w_id).and_then(|(ts, envs)| {
|
||||
if ts > chrono::Utc::now().timestamp() - (60 * 15) {
|
||||
Some(envs)
|
||||
@@ -1141,6 +1155,34 @@ mod tests {
|
||||
}
|
||||
assert!(omit(r#"{"n": 1e400, "r": "$var:x"}"#).contains("could not be checked"));
|
||||
assert_eq!(omit(r#"{"n": 1e400}"#), r#"{"n": 1e400}"#);
|
||||
// serde_json reads this as the array in the string, NUL still to be stripped.
|
||||
for raw_value in [
|
||||
r#"{"$serde_json::private::RawValue": "[\"$va\\u0000r:x\", \"$var:\"]"}"#,
|
||||
r#"[{"a": 1, "$serde_json::private::Raw\u0000Value": "1"}]"#,
|
||||
] {
|
||||
assert!(
|
||||
omit(raw_value).contains("could not be checked"),
|
||||
"{raw_value}"
|
||||
);
|
||||
}
|
||||
let args = r#"{"$serde_json::private::Raw\u0000Value": 1, "a": 2}"#;
|
||||
let args = omit_untrusted_interpolation(serde_json::from_str(args).unwrap(), "");
|
||||
assert_eq!(args.keys().collect::<Vec<_>>(), ["a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_value_refuses_texts_nested_in_texts() {
|
||||
use crate::utils::PlainValue;
|
||||
let mut nested = "1".to_string();
|
||||
for _ in 0..100 {
|
||||
let text = format!("{}{nested}{}", "[".repeat(120), "]".repeat(120))
|
||||
.replace('\\', "\\u005c")
|
||||
.replace('"', "\\u0022");
|
||||
nested = format!(r#"{{"$serde_json::private::RawValue":"{text}"}}"#);
|
||||
}
|
||||
assert!(serde_json::from_str::<PlainValue>(&nested).is_err());
|
||||
let v: PlainValue = serde_json::from_str(r#"{"a": [1, 2.5, null, "$x"]}"#).unwrap();
|
||||
assert_eq!(v.0, serde_json::json!({"a": [1, 2.5, null, "$x"]}));
|
||||
}
|
||||
use crate::error::Error;
|
||||
use crate::workspace_crypt::WorkspaceCrypt;
|
||||
|
||||
@@ -868,7 +868,7 @@ fn format_pull_query(peek: String) -> String {
|
||||
j.same_worker, j.pre_run_error, j.visible_to_owner,
|
||||
j.tag, j.concurrent_limit, j.concurrency_time_window_s, j.flow_innermost_root_job, j.root_job,
|
||||
j.timeout, j.flow_step_id, j.cache_ttl, q.cache_ignore_s3_path, q.runnable_settings_handle, j.priority, j.raw_code, j.raw_lock, j.raw_flow,
|
||||
j.script_entrypoint_override, j.preprocessed, p.job_token_scopes, COALESCE(pj.runnable_path, j.args->>'_FLOW_PATH') as parent_runnable_path,
|
||||
j.script_entrypoint_override, j.preprocessed, p.job_token_scopes, COALESCE(pj.runnable_path, CASE WHEN j.kind = 'preview' THEN j.args->>'_FLOW_PATH' END) as parent_runnable_path,
|
||||
COALESCE(p.email, j.permissioned_as_email) as permissioned_as_email, p.username as permissioned_as_username, p.is_admin as permissioned_as_is_admin,
|
||||
p.is_operator as permissioned_as_is_operator, p.groups as permissioned_as_groups, p.folders as permissioned_as_folders, p.end_user_email as permissioned_as_end_user_email,
|
||||
p.viewer_data_access, p.mcp_client
|
||||
@@ -1236,18 +1236,8 @@ pub fn apply_custom_tags_setting(q: Option<serde_json::Value>) {
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn parse_file<T: FromStr>(path: &str) -> Option<T> {
|
||||
std::process::Command::new("cat")
|
||||
.args([path])
|
||||
.output()
|
||||
.ok()
|
||||
.map(|o| {
|
||||
String::from_utf8_lossy(&o.stdout)
|
||||
.to_string()
|
||||
.trim()
|
||||
.parse::<T>()
|
||||
.ok()
|
||||
})
|
||||
.flatten()
|
||||
let bytes = fs::read(path).ok()?;
|
||||
String::from_utf8_lossy(&bytes).trim().parse::<T>().ok()
|
||||
}
|
||||
|
||||
#[annotations("#")]
|
||||
@@ -1304,6 +1294,10 @@ pub struct SqlAnnotations {
|
||||
// `wmill datatable serve` to map Postgres results onto the wire protocol
|
||||
// without re-stringifying every JSON value.
|
||||
pub raw_output: bool,
|
||||
// The job's args are values bound to the query's parameters, passed on as they are:
|
||||
// `$var:`/`$res:` strings and `$`-prefixed reserved variable names in them stay text.
|
||||
// Emitted by the SDKs' `datatable()`/`ducklake()` helpers, whose args are run-time data.
|
||||
pub literal_args: bool,
|
||||
}
|
||||
|
||||
impl SqlAnnotations {
|
||||
@@ -1635,7 +1629,18 @@ pub fn pad_string(value: &str, total_length: usize) -> String {
|
||||
format!("{value}{}", " ".repeat(padding_needed)) // Pad with spaces
|
||||
}
|
||||
}
|
||||
/// Copies only directories and regular files, never following a symlink: the
|
||||
/// trees copied here are written by jailed steps (dependency installs, a job's
|
||||
/// `vendor/`) and this runs outside the jail, so a link must not resolve
|
||||
/// against the worker's filesystem. Links are skipped, not recreated, since
|
||||
/// several trees may be merged into one `dst` and `fs::copy` would write the
|
||||
/// next tree's files through a recreated link.
|
||||
pub fn copy_dir_recursively(src: &Path, dst: &Path) -> error::Result<()> {
|
||||
if fs::symlink_metadata(src)?.file_type().is_symlink() {
|
||||
return Err(error::Error::InternalErr(format!(
|
||||
"refusing to copy {src:?}: it is a symlink"
|
||||
)));
|
||||
}
|
||||
if !dst.exists() {
|
||||
fs::create_dir_all(dst)?;
|
||||
}
|
||||
@@ -1647,10 +1652,13 @@ pub fn copy_dir_recursively(src: &Path, dst: &Path) -> error::Result<()> {
|
||||
let src_path = entry.path();
|
||||
let dst_path = dst.join(entry.file_name());
|
||||
|
||||
if src_path.is_dir() && !src_path.is_symlink() {
|
||||
let file_type = entry.file_type()?;
|
||||
if file_type.is_dir() {
|
||||
copy_dir_recursively(&src_path, &dst_path)?;
|
||||
} else {
|
||||
} else if file_type.is_file() {
|
||||
fs::copy(&src_path, &dst_path)?;
|
||||
} else {
|
||||
tracing::warn!("not copying {src_path:?}: neither a directory nor a regular file");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1988,6 +1996,27 @@ fn get_memory_from_meminfo() -> Option<i64> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn cgroup_v2_memory_limit(cgroup_root: &Path, cgroup_path: &Path) -> Option<i64> {
|
||||
let mut min_limit: Option<i64> = None;
|
||||
for dir in cgroup_path.ancestors() {
|
||||
if !dir.starts_with(cgroup_root) {
|
||||
break;
|
||||
}
|
||||
if let Ok(contents) = fs::read_to_string(dir.join("memory.max")) {
|
||||
if let Ok(limit) = contents.trim().parse::<i64>() {
|
||||
if limit >= 0 {
|
||||
min_limit = Some(min_limit.map_or(limit, |m| m.min(limit)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if dir == cgroup_root {
|
||||
break;
|
||||
}
|
||||
}
|
||||
min_limit
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn get_memory() -> Option<i64> {
|
||||
let memory_limit: Option<i64> =
|
||||
@@ -1995,21 +2024,16 @@ pub fn get_memory() -> Option<i64> {
|
||||
// cgroup v1
|
||||
parse_file("/sys/fs/cgroup/memory/memory.limit_in_bytes")
|
||||
} else {
|
||||
// cgroup v2
|
||||
let cgroup_path = get_cgroupv2_path()?;
|
||||
let memory_max_path = format!("{cgroup_path}/memory.max");
|
||||
|
||||
parse_file(&memory_max_path)
|
||||
// cgroup v2: walk up to the cgroup root for the tightest numeric limit;
|
||||
// "max" means uncapped at that level
|
||||
get_cgroupv2_path()
|
||||
.and_then(|p| cgroup_v2_memory_limit(Path::new("/sys/fs/cgroup"), Path::new(&p)))
|
||||
};
|
||||
|
||||
// if memory_max is super high, read machine total memory (meminfo)
|
||||
if memory_limit
|
||||
.as_ref()
|
||||
.is_some_and(|x| x > &(1024 * 1024 * 1024 * 1024 * 1024))
|
||||
{
|
||||
get_memory_from_meminfo()
|
||||
} else {
|
||||
memory_limit
|
||||
// if uncapped ("max" on cgroup v2) or super high (cgroup v1), fall back to host RAM
|
||||
match memory_limit {
|
||||
Some(limit) if limit >= 0 && limit <= 1024 * 1024 * 1024 * 1024 * 1024 => Some(limit),
|
||||
_ => get_memory_from_meminfo(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3449,6 +3473,27 @@ mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn copy_dir_recursively_does_not_follow_symlinks() {
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
std::fs::write(outside.path().join("other"), "s").unwrap();
|
||||
let src = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(src.path().join("pkg")).unwrap();
|
||||
std::fs::write(src.path().join("pkg/a.py"), "a").unwrap();
|
||||
std::os::unix::fs::symlink(outside.path().join("other"), src.path().join("pkg/link"))
|
||||
.unwrap();
|
||||
let dst = tempfile::tempdir().unwrap();
|
||||
|
||||
copy_dir_recursively(src.path(), dst.path()).unwrap();
|
||||
assert!(dst.path().join("pkg/a.py").is_file());
|
||||
assert!(std::fs::symlink_metadata(dst.path().join("pkg/link")).is_err());
|
||||
|
||||
let link = src.path().join("link");
|
||||
std::os::unix::fs::symlink(outside.path(), &link).unwrap();
|
||||
assert!(copy_dir_recursively(&link, dst.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedicated_path_is_read_like_a_job_path() {
|
||||
let path = |p: &str| WorkspacedPath::dedicated("ws", p).path;
|
||||
@@ -4113,6 +4158,19 @@ mod tests {
|
||||
assert!(combined.prepare);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sql_literal_args_annotation() {
|
||||
// As the SDK helpers emit it, among the other leading annotations.
|
||||
let sdk = SqlAnnotations::parse(
|
||||
"-- result_collection=last_statement_first_row\n-- literal_args\n-- role analytics\n-- $1 arg1\nSELECT $1::TEXT",
|
||||
);
|
||||
assert!(sdk.literal_args);
|
||||
|
||||
assert!(!SqlAnnotations::parse("-- $1 arg1\nSELECT $1::TEXT").literal_args);
|
||||
// Only the leading comment block is read: a value cannot switch it on or off.
|
||||
assert!(!SqlAnnotations::parse("SELECT 1;\n-- literal_args").literal_args);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_network_annotation() {
|
||||
assert!(PythonAnnotations::parse("# sandbox\n# no_network\ndef main(): pass").no_network);
|
||||
@@ -4442,4 +4500,45 @@ mod tests {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
// Tests for cgroup v2 memory limit
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn test_cgroup_v2_memory_limit_walks_ancestors_and_handles_max() {
|
||||
let root = std::env::temp_dir().join(format!("wm_cgv2_mem_{}", uuid::Uuid::new_v4()));
|
||||
let slice = root.join("kubepods.slice/pod1");
|
||||
let leaf = slice.join("container1");
|
||||
std::fs::create_dir_all(&leaf).unwrap();
|
||||
|
||||
// All "max" -> None (caller falls back to /proc/meminfo)
|
||||
std::fs::write(slice.join("memory.max"), "max\n").unwrap();
|
||||
std::fs::write(leaf.join("memory.max"), "max\n").unwrap();
|
||||
assert_eq!(cgroup_v2_memory_limit(&root, &leaf), None);
|
||||
|
||||
// Leaf is "max" but parent slice has a 4 GiB limit -> inherits 4 GiB
|
||||
std::fs::write(slice.join("memory.max"), "4294967296\n").unwrap();
|
||||
assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(4_294_967_296));
|
||||
|
||||
// Leaf has 8 GiB, parent has 4 GiB -> minimum effective limit (4 GiB)
|
||||
std::fs::write(leaf.join("memory.max"), "8589934592\n").unwrap();
|
||||
assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(4_294_967_296));
|
||||
|
||||
// Leaf has 2 GiB, parent has 4 GiB -> leaf's tighter limit (2 GiB)
|
||||
std::fs::write(leaf.join("memory.max"), "2147483648\n").unwrap();
|
||||
assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(2_147_483_648));
|
||||
|
||||
// Container cgroup namespace (`0::/` -> "/sys/fs/cgroup/") reads root/memory.max
|
||||
std::fs::write(root.join("memory.max"), "1073741824\n").unwrap();
|
||||
let root_with_slash = PathBuf::from(format!("{}/", root.display()));
|
||||
assert_eq!(
|
||||
cgroup_v2_memory_limit(&root, &root_with_slash),
|
||||
Some(1_073_741_824)
|
||||
);
|
||||
|
||||
// An explicit limit of 0 is preserved (not treated as uncapped); downstream consumers currently treat 0 as no cap.
|
||||
std::fs::write(leaf.join("memory.max"), "0\n").unwrap();
|
||||
assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(0));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2146,6 +2146,18 @@ pub async fn resolve_workspace_governing_datatables(
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Replication connections resolve unqualified names in `pg_catalog` only, never in the
|
||||
/// database's `public` schema, whose objects the workspace manages. A startup option outranks
|
||||
/// `ALTER ROLE/DATABASE ... SET`, and the last `-c` wins over one already in the options of
|
||||
/// `DATABASE_URL`.
|
||||
fn pin_replication_search_path(pg_creds: &mut PgDatabase) {
|
||||
const PIN: &str = "-c search_path=pg_catalog";
|
||||
pg_creds.options = Some(match pg_creds.non_empty_options() {
|
||||
Some(options) => format!("{options} {PIN}"),
|
||||
None => PIN.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Build the `admin` connection for a governing entry: `custom_instance_user` for an instance
|
||||
/// database, on Windmill's cluster or the external one; the user's own resource for a BYO-postgres
|
||||
/// one.
|
||||
@@ -2160,12 +2172,15 @@ async fn resolve_datatable_connection_unchecked(
|
||||
.as_ref()
|
||||
.expect("a governing entry owns a database");
|
||||
if database.resource_type == DataTableCatalogResourceType::ExternalInstance {
|
||||
let pg_creds = crate::external_instance_pg::external_instance_connection_unchecked(
|
||||
let mut pg_creds = crate::external_instance_pg::external_instance_connection_unchecked(
|
||||
db,
|
||||
&database.resource_path,
|
||||
replication,
|
||||
)
|
||||
.await?;
|
||||
if replication {
|
||||
pin_replication_search_path(&mut pg_creds);
|
||||
}
|
||||
serde_json::to_value(&pg_creds)
|
||||
.map_err(|e| Error::internal_err(format!("Error serializing pg creds: {}", e)))
|
||||
} else if database.resource_type == DataTableCatalogResourceType::Instance {
|
||||
@@ -2184,6 +2199,7 @@ async fn resolve_datatable_connection_unchecked(
|
||||
if replication {
|
||||
pg_creds.user = Some("custom_instance_replication_user".to_string());
|
||||
pg_creds.password = Some(get_custom_pg_instance_replication_password(&db).await?);
|
||||
pin_replication_search_path(&mut pg_creds);
|
||||
} else {
|
||||
pg_creds.user = Some(CUSTOM_INSTANCE_USER.to_string());
|
||||
pg_creds.password = Some(get_custom_pg_instance_password(&db).await?);
|
||||
@@ -4017,6 +4033,21 @@ mod tests {
|
||||
DataTableRoleTenants { tenants: list.iter().map(|t| t.to_string()).collect() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replication_search_path_is_pinned_after_the_url_options() {
|
||||
let mut creds = PgDatabase::parse_uri("postgres://u@h/db").unwrap();
|
||||
pin_replication_search_path(&mut creds);
|
||||
assert_eq!(creds.options.as_deref(), Some("-c search_path=pg_catalog"));
|
||||
|
||||
let mut creds =
|
||||
PgDatabase::parse_uri("postgres://u@h/db?options=-c+search_path%3Dpublic").unwrap();
|
||||
pin_replication_search_path(&mut creds);
|
||||
assert_eq!(
|
||||
creds.options.as_deref(),
|
||||
Some("-c search_path=public -c search_path=pg_catalog")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_script_version_is_the_second_segment_of_the_queued_path() {
|
||||
let meets = |p, min| sync_script_meets_min_version(&sync_callback_path(p), min);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
/// Every definer-rights function must have no PUBLIC EXECUTE grant and pin a search_path ending
|
||||
/// in pg_temp. Checked over the catalog so that a new function, or one redefined with CREATE OR
|
||||
/// REPLACE (which resets both), fails here.
|
||||
#[sqlx::test(migrations = "../migrations")]
|
||||
async fn definer_functions_are_pinned_and_closed_to_public(db: Pool<Postgres>) {
|
||||
let exposed: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT p.oid::regprocedure::text
|
||||
FROM pg_proc p
|
||||
JOIN pg_namespace n ON n.oid = p.pronamespace
|
||||
WHERE n.nspname = current_schema()
|
||||
AND p.prosecdef
|
||||
AND (has_function_privilege('public', p.oid, 'EXECUTE')
|
||||
OR NOT EXISTS (
|
||||
SELECT 1 FROM unnest(p.proconfig) AS c
|
||||
WHERE c LIKE 'search_path=%' AND c LIKE '%, pg_temp'))
|
||||
ORDER BY 1",
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
exposed.is_empty(),
|
||||
"executable by PUBLIC, or without a search_path ending in pg_temp: {exposed:?}"
|
||||
);
|
||||
|
||||
let mut tx = db.begin().await.unwrap();
|
||||
sqlx::query("SET LOCAL ROLE windmill_user")
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
let labels: Option<Vec<String>> =
|
||||
sqlx::query_scalar("SELECT folder_labels('admins', 'f/none/item')")
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(labels, None, "windmill_user keeps EXECUTE on folder_labels");
|
||||
}
|
||||
@@ -74,9 +74,10 @@ pub struct ClientWithScopes {
|
||||
/// persist it on client-credentials accounts.
|
||||
pub token_url: String,
|
||||
/// Whether the instance entry carries shared credentials (non-empty id +
|
||||
/// secret). Providers without them are bring-your-own only — the connect
|
||||
/// dialog lists them under "Others", not "Instance-configured".
|
||||
/// secret). Providers without them are bring-your-own only.
|
||||
pub has_shared_credentials: bool,
|
||||
/// [`OAuthClient::shares_client_credentials`] resolved.
|
||||
pub shares_client_credentials: bool,
|
||||
/// [`OAuthClient::pkce`] resolved; only the login flow reads it.
|
||||
pub pkce: bool,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Restarting a parallel ForLoop / BranchAll with `failed_only`: the restarted step's status,
|
||||
//! which keeps the slots that succeeded and marks the others to rerun.
|
||||
|
||||
use serde_json::value::RawValue;
|
||||
use sqlx::{Pool, Postgres};
|
||||
use uuid::Uuid;
|
||||
use windmill_common::{
|
||||
error::Error,
|
||||
flow_status::{
|
||||
BranchAllStatus, FlowJobsDuration, FlowStatusModule, Iterator as FlowIterator,
|
||||
RestartedFrom,
|
||||
},
|
||||
flows::{FlowModule, FlowModuleValue},
|
||||
};
|
||||
|
||||
/// A worker that predates `failed_only` drops it from a restart chain and reruns the whole
|
||||
/// step, so a chain carrying it anywhere is refused until every worker reads it.
|
||||
pub(crate) async fn refuse_failed_only_on_outdated_workers(
|
||||
failed_only: bool,
|
||||
nested: Option<&RestartedFrom>,
|
||||
) -> Result<(), Error> {
|
||||
let mut any = failed_only;
|
||||
let mut level = nested;
|
||||
while let Some(l) = level {
|
||||
any |= l.failed_only;
|
||||
level = l.nested.as_deref();
|
||||
}
|
||||
if any {
|
||||
windmill_common::min_version::MIN_VERSION_SUPPORTS_FAILED_ONLY_RESTART
|
||||
.assert()
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Status of a parallel ForLoop / BranchAll restarted with `failed_only`: a slot whose job
|
||||
/// succeeded keeps it, every other slot holds `Uuid::nil()`. The worker reads a nil slot as
|
||||
/// "rerun this iteration (branch) here" and counts the kept ones as already completed, so the
|
||||
/// step's result stays ordered by slot.
|
||||
pub(crate) async fn create_failed_only_module(
|
||||
db: &Pool<Postgres>,
|
||||
workspace_id: &str,
|
||||
module: &FlowStatusModule,
|
||||
module_definition: &FlowModule,
|
||||
restart_step_id: &str,
|
||||
) -> Result<FlowStatusModule, Error> {
|
||||
let (is_loop, branch_count) = match module_definition.get_value()? {
|
||||
FlowModuleValue::ForloopFlow { parallel: true, .. } => (true, None),
|
||||
FlowModuleValue::BranchAll { parallel: true, branches, .. } => (false, Some(branches.len())),
|
||||
_ => {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"Step {restart_step_id} is not a parallel for-loop or branch-all, only those can rerun their failed iterations"
|
||||
)))
|
||||
}
|
||||
};
|
||||
let original_jobs = module
|
||||
.flow_jobs()
|
||||
.filter(|jobs| !jobs.is_empty())
|
||||
.ok_or_else(|| {
|
||||
Error::BadRequest(format!(
|
||||
"Step {restart_step_id} has no recorded iterations in the original run"
|
||||
))
|
||||
})?;
|
||||
let n = original_jobs.len();
|
||||
if branch_count.is_some_and(|count| count != n) {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"Step {restart_step_id} ran {n} branches but now has {}, its failed branches cannot be matched",
|
||||
branch_count.unwrap_or(0)
|
||||
)));
|
||||
}
|
||||
let succeeded = sqlx::query_scalar!(
|
||||
"SELECT id FROM v2_job_completed
|
||||
WHERE workspace_id = $1 AND id = ANY($2) AND (status = 'success' OR status = 'skipped')",
|
||||
workspace_id,
|
||||
&original_jobs,
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
// An iteration recovered by the error handler completed as a failure but is recorded
|
||||
// as a success of the step, so it is kept too.
|
||||
let recorded_success = module.flow_jobs_success().unwrap_or_default();
|
||||
let flow_jobs: Vec<Uuid> = original_jobs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, job)| {
|
||||
if succeeded.contains(job) || recorded_success.get(i) == Some(&Some(true)) {
|
||||
*job
|
||||
} else {
|
||||
Uuid::nil()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let kept = flow_jobs.iter().filter(|job| !job.is_nil()).count();
|
||||
if kept == n {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"Step {restart_step_id} has no failed iterations to rerun"
|
||||
)));
|
||||
}
|
||||
// A loop reruns its failed iterations on the items they ran on, read from each iteration's
|
||||
// `iter` argument rather than re-evaluating the iterator, so every kept result stays
|
||||
// paired with its item.
|
||||
let itered = if is_loop {
|
||||
let rows = sqlx::query!(
|
||||
"SELECT id, args->'iter'->'value' AS \"value: sqlx::types::Json<Box<RawValue>>\"
|
||||
FROM v2_job WHERE workspace_id = $1 AND id = ANY($2)",
|
||||
workspace_id,
|
||||
&original_jobs,
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let items = original_jobs
|
||||
.iter()
|
||||
.map(|job| {
|
||||
rows.iter()
|
||||
.find(|r| r.id == *job)
|
||||
.and_then(|r| r.value.as_ref())
|
||||
.map(|v| v.0.clone())
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or_else(|| {
|
||||
Error::BadRequest(format!(
|
||||
"The items step {restart_step_id} iterated over in the original run are no longer stored, rerun all its iterations instead"
|
||||
))
|
||||
})?;
|
||||
Some(items)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut flow_jobs_duration = module
|
||||
.flow_jobs_duration()
|
||||
.filter(|d| d.started_at.len() == n && d.duration_ms.len() == n)
|
||||
.unwrap_or_else(|| FlowJobsDuration::new(n));
|
||||
for (i, job) in flow_jobs.iter().enumerate() {
|
||||
if job.is_nil() {
|
||||
flow_jobs_duration.started_at[i] = None;
|
||||
flow_jobs_duration.duration_ms[i] = None;
|
||||
}
|
||||
}
|
||||
Ok(FlowStatusModule::InProgress {
|
||||
id: module.id(),
|
||||
job: Uuid::nil(),
|
||||
iterator: is_loop.then(|| FlowIterator { index: kept, itered, itered_len: Some(n) }),
|
||||
flow_jobs_success: Some(
|
||||
flow_jobs
|
||||
.iter()
|
||||
.map(|j| (!j.is_nil()).then_some(true))
|
||||
.collect(),
|
||||
),
|
||||
flow_jobs: Some(flow_jobs),
|
||||
flow_jobs_duration: Some(flow_jobs_duration),
|
||||
flow_jobs_labels: module.flow_jobs_labels(),
|
||||
branch_chosen: None,
|
||||
branchall: (!is_loop).then(|| BranchAllStatus { branch: kept, len: n }),
|
||||
parallel: true,
|
||||
while_loop: false,
|
||||
progress: None,
|
||||
agent_actions: None,
|
||||
agent_actions_success: None,
|
||||
})
|
||||
}
|
||||
@@ -43,7 +43,7 @@ use windmill_common::bench::BenchmarkIter;
|
||||
use windmill_common::jobs::{
|
||||
args_contain_nul, normalize_nul_in_args, sanitize_untrusted_args, script_path_to_payload,
|
||||
JobTriggerKind, TriggerKindLabel, EMAIL_ERROR_HANDLER_USER_EMAIL, FLOW_TIMEOUT_CANCELER,
|
||||
MODULES_ARG,
|
||||
MODULES_ARG, TEMP_SCRIPT_REFS_ARG,
|
||||
};
|
||||
use windmill_common::min_version::{
|
||||
MIN_VERSION_SUPPORTS_DEBOUNCING, MIN_VERSION_SUPPORTS_DEBOUNCING_V2,
|
||||
@@ -54,7 +54,7 @@ use windmill_common::runnable_settings::{
|
||||
};
|
||||
use windmill_common::triggers::TriggerMetadata;
|
||||
use windmill_common::utils::{calculate_hash, configure_client, now_from_db, strip_json_nul};
|
||||
use windmill_common::variables::omit_untrusted_interpolation;
|
||||
use windmill_common::variables::{omit_untrusted_interpolation, omit_untrusted_text};
|
||||
use windmill_common::worker::Connection;
|
||||
|
||||
use windmill_common::otel_oss::{
|
||||
@@ -94,6 +94,9 @@ use windmill_common::{
|
||||
use backon::ConstantBuilder;
|
||||
use backon::{BackoffBuilder, Retryable};
|
||||
|
||||
use crate::failed_only_restart::{
|
||||
create_failed_only_module, refuse_failed_only_on_outdated_workers,
|
||||
};
|
||||
use crate::flow_status::{update_flow_status_in_progress, update_workflow_as_code_status};
|
||||
use crate::schedule::{get_schedule_opt, push_scheduled_job};
|
||||
use crate::tags::per_workspace_tag;
|
||||
@@ -238,7 +241,7 @@ pub async fn cancel_single_job<'c>(
|
||||
let reason: String = reason
|
||||
.clone()
|
||||
.unwrap_or_else(|| "unexplicited reasons".to_string());
|
||||
let e = serde_json::json!({"message": format!("Job canceled: {reason} by {username}"), "name": "Canceled", "reason": reason, "canceler": username});
|
||||
let e = canceled_result(Some(&reason), Some(&username));
|
||||
|
||||
append_logs(
|
||||
&job_running.id,
|
||||
@@ -1426,8 +1429,8 @@ lazy_static::lazy_static! {
|
||||
static ref RESTART_UNLESS_CANCELLED_CACHE: Cache<(i64, String), (bool, Option<i32>, Option<Vec<String>>)> = Cache::new(10000);
|
||||
|
||||
// Cache for workspace error handler settings with 60s TTL
|
||||
// Key: workspace_id, Value: (error_handler, error_handler_extra_args, error_handler_muted_on_cancel, error_handler_muted_on_user_path, report_to_instance_alerts, expiry_timestamp)
|
||||
static ref WORKSPACE_ERROR_HANDLER_CACHE: Cache<String, (Option<String>, Option<Json<Box<RawValue>>>, bool, bool, bool, i64)> = Cache::new(1000);
|
||||
// Key: workspace_id, Value: (settings, expiry_timestamp)
|
||||
static ref WORKSPACE_ERROR_HANDLER_CACHE: Cache<String, (WorkspaceErrorHandler, i64)> = Cache::new(1000);
|
||||
|
||||
// Best-effort per-worker throttle for the instance-channel fallback: a flapping runnable
|
||||
// would otherwise turn every failure into outbound Slack/SMTP traffic on channels shared by
|
||||
@@ -2989,19 +2992,20 @@ pub async fn report_error_to_workspace_handler_or_critical_side_channel(
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WorkspaceErrorHandler {
|
||||
path: Option<String>,
|
||||
extra_args: Option<Json<Box<RawValue>>>,
|
||||
muted_on_cancel: bool,
|
||||
muted_on_user_path: bool,
|
||||
muted_on_ui_runs: bool,
|
||||
report_to_instance_alerts: bool,
|
||||
}
|
||||
|
||||
async fn fetch_error_handler_from_db(
|
||||
db: &Pool<Postgres>,
|
||||
w_id: &str,
|
||||
) -> Result<
|
||||
(
|
||||
Option<String>,
|
||||
Option<Json<Box<RawValue>>>,
|
||||
bool,
|
||||
bool,
|
||||
bool,
|
||||
),
|
||||
Error,
|
||||
> {
|
||||
) -> Result<WorkspaceErrorHandler, Error> {
|
||||
sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
@@ -3009,6 +3013,7 @@ async fn fetch_error_handler_from_db(
|
||||
Option<Json<Box<RawValue>>>,
|
||||
Option<bool>,
|
||||
Option<bool>,
|
||||
Option<bool>,
|
||||
bool,
|
||||
),
|
||||
>(
|
||||
@@ -3018,6 +3023,7 @@ async fn fetch_error_handler_from_db(
|
||||
(error_handler->'extra_args')::text::json,
|
||||
(error_handler->>'muted_on_cancel')::boolean,
|
||||
(error_handler->>'muted_on_user_path')::boolean,
|
||||
(error_handler->>'muted_on_ui_runs')::boolean,
|
||||
ws.error_handler_fallback_to_instance_alerts AND w.parent_workspace_id IS NULL
|
||||
FROM workspace_settings ws
|
||||
JOIN workspace w ON w.id = ws.workspace_id
|
||||
@@ -3029,14 +3035,20 @@ async fn fetch_error_handler_from_db(
|
||||
.await
|
||||
.context("fetching error handler info from workspace_settings")?
|
||||
.map(
|
||||
|(path, extra_args, muted_on_cancel, muted_on_user_path, report_to_instance_alerts)| {
|
||||
(
|
||||
path,
|
||||
extra_args,
|
||||
muted_on_cancel.unwrap_or(false),
|
||||
muted_on_user_path.unwrap_or(false),
|
||||
report_to_instance_alerts,
|
||||
)
|
||||
|(
|
||||
path,
|
||||
extra_args,
|
||||
muted_on_cancel,
|
||||
muted_on_user_path,
|
||||
muted_on_ui_runs,
|
||||
report_to_instance_alerts,
|
||||
)| WorkspaceErrorHandler {
|
||||
path,
|
||||
extra_args,
|
||||
muted_on_cancel: muted_on_cancel.unwrap_or(false),
|
||||
muted_on_user_path: muted_on_user_path.unwrap_or(false),
|
||||
muted_on_ui_runs: muted_on_ui_runs.unwrap_or(false),
|
||||
report_to_instance_alerts,
|
||||
},
|
||||
)
|
||||
.ok_or_else(|| Error::internal_err(format!("no workspace settings for id {w_id}")))
|
||||
@@ -3051,39 +3063,25 @@ pub async fn send_error_to_workspace_handler<'a, 'c, T: Serialize + Send + Sync>
|
||||
let w_id = &queued_job.workspace_id;
|
||||
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let (
|
||||
error_handler,
|
||||
error_handler_extra_args,
|
||||
error_handler_muted_on_cancel,
|
||||
error_handler_muted_on_user_path,
|
||||
report_to_instance_alerts,
|
||||
) = if let Some(cached) = WORKSPACE_ERROR_HANDLER_CACHE.get(w_id) {
|
||||
if cached.5 > now {
|
||||
(
|
||||
cached.0.clone(),
|
||||
cached.1.clone(),
|
||||
cached.2,
|
||||
cached.3,
|
||||
cached.4,
|
||||
)
|
||||
} else {
|
||||
let row = fetch_error_handler_from_db(db, w_id).await?;
|
||||
let expiry = now + WORKSPACE_HANDLER_CACHE_TTL_SECONDS;
|
||||
let handler = match WORKSPACE_ERROR_HANDLER_CACHE.get(w_id) {
|
||||
Some((handler, expiry)) if expiry > now => handler,
|
||||
_ => {
|
||||
let handler = fetch_error_handler_from_db(db, w_id).await?;
|
||||
WORKSPACE_ERROR_HANDLER_CACHE.insert(
|
||||
w_id.clone(),
|
||||
(row.0.clone(), row.1.clone(), row.2, row.3, row.4, expiry),
|
||||
(handler.clone(), now + WORKSPACE_HANDLER_CACHE_TTL_SECONDS),
|
||||
);
|
||||
row
|
||||
handler
|
||||
}
|
||||
} else {
|
||||
let row = fetch_error_handler_from_db(db, w_id).await?;
|
||||
let expiry = now + WORKSPACE_HANDLER_CACHE_TTL_SECONDS;
|
||||
WORKSPACE_ERROR_HANDLER_CACHE.insert(
|
||||
w_id.clone(),
|
||||
(row.0.clone(), row.1.clone(), row.2, row.3, row.4, expiry),
|
||||
);
|
||||
row
|
||||
};
|
||||
let WorkspaceErrorHandler {
|
||||
path: error_handler,
|
||||
extra_args: error_handler_extra_args,
|
||||
muted_on_cancel,
|
||||
muted_on_user_path,
|
||||
muted_on_ui_runs,
|
||||
report_to_instance_alerts,
|
||||
} = handler;
|
||||
|
||||
// Nothing to do for the vast majority of workspaces, and returning here keeps the
|
||||
// per-runnable mute lookup below off the path of every failed job.
|
||||
@@ -3091,12 +3089,12 @@ pub async fn send_error_to_workspace_handler<'a, 'c, T: Serialize + Send + Sync>
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if is_canceled && error_handler_muted_on_cancel {
|
||||
if is_canceled && muted_on_cancel {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Skip error handler for scripts/flows starting with u/
|
||||
if error_handler_muted_on_user_path {
|
||||
if muted_on_user_path {
|
||||
if let Some(ref path) = queued_job.runnable_path {
|
||||
if path.starts_with("u/") {
|
||||
return Ok(());
|
||||
@@ -3104,6 +3102,15 @@ pub async fn send_error_to_workspace_handler<'a, 'c, T: Serialize + Send + Sync>
|
||||
}
|
||||
}
|
||||
|
||||
if muted_on_ui_runs
|
||||
&& queued_job
|
||||
.trigger_kind
|
||||
.as_ref()
|
||||
.is_some_and(|k| k.is(JobTriggerKind::Ui))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let ws_error_handler_muted: Option<bool> = match queued_job.kind {
|
||||
JobKind::Script => {
|
||||
sqlx::query_scalar!(
|
||||
@@ -6806,6 +6813,23 @@ async fn inherited_low_priority(
|
||||
Ok(priority.flatten())
|
||||
}
|
||||
|
||||
/// Whether the topmost ancestor of `job_id` (or the job itself) is a flow preview pushed
|
||||
/// by its author.
|
||||
async fn is_in_flow_preview(db: &Pool<Postgres>, job_id: Uuid) -> Result<bool, Error> {
|
||||
let root_kind = sqlx::query_scalar::<_, JobKind>(
|
||||
"WITH RECURSIVE a(id, parent_job, kind, depth) AS (
|
||||
SELECT id, parent_job, kind, 0 FROM v2_job WHERE id = $1
|
||||
UNION ALL
|
||||
SELECT j.id, j.parent_job, j.kind, a.depth + 1
|
||||
FROM v2_job j JOIN a ON j.id = a.parent_job WHERE a.depth < 100
|
||||
) SELECT kind FROM a WHERE parent_job IS NULL LIMIT 1",
|
||||
)
|
||||
.bind(job_id)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
Ok(matches!(root_kind, Some(JobKind::FlowPreview)))
|
||||
}
|
||||
|
||||
// #[instrument(level = "trace", skip_all)]
|
||||
async fn push_inner<'c, 'd>(
|
||||
db: &Pool<Postgres>,
|
||||
@@ -6873,6 +6897,30 @@ async fn push_inner<'c, 'd>(
|
||||
PushArgs { extra, args }
|
||||
};
|
||||
|
||||
// `_TEMP_SCRIPT_REFS` points a preview's workspace imports at the temporary script store,
|
||||
// for its author to test undeployed code. A worker pushes a child with args the running
|
||||
// job computed or forwarded (a workflow task, a flow's preprocessor or failure module, an
|
||||
// agent's tool): only the jobs of a flow preview, given its author's refs, keep them.
|
||||
let refs_stripped_args;
|
||||
if let Some(parent_job) = parent_job {
|
||||
let in_args = args.args.contains_key(TEMP_SCRIPT_REFS_ARG);
|
||||
let in_extra = args
|
||||
.extra
|
||||
.as_ref()
|
||||
.is_some_and(|e| e.contains_key(TEMP_SCRIPT_REFS_ARG));
|
||||
if (in_args || in_extra) && !is_in_flow_preview(db, parent_job).await? {
|
||||
if let Some(extra) = args.extra.as_mut() {
|
||||
extra.remove(TEMP_SCRIPT_REFS_ARG);
|
||||
}
|
||||
if in_args {
|
||||
let mut stripped = args.args.clone();
|
||||
stripped.remove(TEMP_SCRIPT_REFS_ARG);
|
||||
refs_stripped_args = stripped;
|
||||
args.args = &refs_stripped_args;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "cloud")]
|
||||
if *CLOUD_HOSTED {
|
||||
// A fork/dev workspace draws its plan and usage from the root (billing) workspace, so its
|
||||
@@ -7381,6 +7429,11 @@ async fn push_inner<'c, 'd>(
|
||||
|
||||
let flow_status: FlowStatus = match restarted_from {
|
||||
Some(restarted_from_val) => {
|
||||
refuse_failed_only_on_outdated_workers(
|
||||
restarted_from_val.failed_only,
|
||||
restarted_from_val.nested.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
let (_, _, _, step_n, truncated_modules, user_states, cleanup_module, _) =
|
||||
restarted_flows_resolution(
|
||||
db,
|
||||
@@ -7390,6 +7443,7 @@ async fn push_inner<'c, 'd>(
|
||||
restarted_from_val.branch_or_iteration_n,
|
||||
restarted_from_val.flow_version,
|
||||
restarted_from_val.nested.is_some(),
|
||||
restarted_from_val.failed_only,
|
||||
Some(&value),
|
||||
)
|
||||
.await?;
|
||||
@@ -7415,6 +7469,8 @@ async fn push_inner<'c, 'd>(
|
||||
flow_version: restarted_from_val.flow_version,
|
||||
branch_chosen: restarted_from_val.branch_chosen,
|
||||
nested: restarted_from_val.nested,
|
||||
failed_only: restarted_from_val.failed_only,
|
||||
from_failed_step: restarted_from_val.from_failed_step,
|
||||
}),
|
||||
user_states,
|
||||
preprocessor_module: None,
|
||||
@@ -7772,7 +7828,10 @@ async fn push_inner<'c, 'd>(
|
||||
flow_version,
|
||||
branch_chosen,
|
||||
nested,
|
||||
failed_only,
|
||||
from_failed_step,
|
||||
} => {
|
||||
refuse_failed_only_on_outdated_workers(failed_only, nested.as_deref()).await?;
|
||||
let (
|
||||
version,
|
||||
flow_path,
|
||||
@@ -7790,6 +7849,7 @@ async fn push_inner<'c, 'd>(
|
||||
branch_or_iteration_n,
|
||||
flow_version,
|
||||
nested.is_some(),
|
||||
failed_only,
|
||||
// RestartedFlow resolves and queues the completed job's stored definition, so the
|
||||
// step validated for reuse is the one that will run.
|
||||
None,
|
||||
@@ -7818,6 +7878,8 @@ async fn push_inner<'c, 'd>(
|
||||
flow_version,
|
||||
branch_chosen,
|
||||
nested,
|
||||
failed_only,
|
||||
from_failed_step,
|
||||
}),
|
||||
user_states,
|
||||
preprocessor_module: None,
|
||||
@@ -8817,7 +8879,9 @@ async fn check_workspace_queue_cap<'c>(
|
||||
/// outside a `MiniPulledJob` — a row read after the pull, say — go through this rather
|
||||
/// than rebuilding the shape.
|
||||
pub fn canceled_result(reason: Option<&str>, canceler: Option<&str>) -> serde_json::Value {
|
||||
let reason = reason.unwrap_or("no reason given");
|
||||
// The reason is the canceler's free text, and the steps after a canceled step receive this
|
||||
// error as an argument, which the worker interpolates.
|
||||
let reason = omit_untrusted_text(reason.unwrap_or("no reason given"));
|
||||
let canceler = canceler.unwrap_or("unknown");
|
||||
serde_json::json!({"message": format!("Job canceled: {reason} by {canceler}"), "name": "Canceled", "reason": reason, "canceler": canceler})
|
||||
}
|
||||
@@ -9071,6 +9135,8 @@ async fn restarted_flows_resolution(
|
||||
// A nested restart chain (RestartedFrom.nested) descends into the restart step's child to
|
||||
// re-run an inner step; zombie reuse would skip the whole container and ignore it.
|
||||
nested_restart: bool,
|
||||
// Keep a parallel restart step's successful iterations/branches and rerun only the rest.
|
||||
failed_only: bool,
|
||||
// The definition the restart queues when it is not the completed job's stored one
|
||||
// (JobPayload::RawFlow queues the editor's, possibly EDITED, definition). Approval gates are
|
||||
// read from it. Zombie reuse validates the restart step against the STORED definition and
|
||||
@@ -9163,8 +9229,28 @@ async fn restarted_flows_resolution(
|
||||
|
||||
if module_id == restart_step_id {
|
||||
refuse_restart_past_unopened_suspend_gate(gate_flow, &truncated_modules)?;
|
||||
if failed_only {
|
||||
let old_module = flow_status
|
||||
.modules
|
||||
.iter()
|
||||
.find(|m| &m.id() == module_id)
|
||||
.ok_or_else(|| {
|
||||
Error::BadRequest(format!(
|
||||
"Step {restart_step_id} did not run in the original flow, it has no failed iterations to rerun"
|
||||
))
|
||||
})?;
|
||||
truncated_modules.push(
|
||||
create_failed_only_module(
|
||||
db,
|
||||
workspace_id,
|
||||
old_module,
|
||||
module_definition,
|
||||
restart_step_id,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
// Mark this and all following modules as WaitingForPriorSteps
|
||||
if branch_or_iteration_n.is_none() || branch_or_iteration_n.unwrap() == 0 {
|
||||
} else if branch_or_iteration_n.is_none() || branch_or_iteration_n.unwrap() == 0 {
|
||||
truncated_modules
|
||||
.push(FlowStatusModule::WaitingForPriorSteps { id: module_id.clone() });
|
||||
} else {
|
||||
@@ -9227,7 +9313,18 @@ async fn restarted_flows_resolution(
|
||||
// (the run page's "Re-start from" button always sends 0); both mean "redo this step",
|
||||
// which for a monitor-reaped zombie means reuse it. `Some(n>=1)` is an explicit
|
||||
// partial container restart and keeps its existing reuse-0..n-1 / rerun-from-n path.
|
||||
if allow_zombie_reuse
|
||||
if failed_only {
|
||||
truncated_modules.push(
|
||||
create_failed_only_module(
|
||||
db,
|
||||
workspace_id,
|
||||
&module,
|
||||
module_definition,
|
||||
restart_step_id,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
} else if allow_zombie_reuse
|
||||
&& reaped_by_monitor
|
||||
&& branch_or_iteration_n.unwrap_or(0) == 0
|
||||
&& !nested_restart
|
||||
@@ -9432,7 +9529,7 @@ pub async fn get_same_worker_job(
|
||||
v2_job.raw_code,
|
||||
v2_job.raw_lock,
|
||||
v2_job.raw_flow,
|
||||
COALESCE(pj.runnable_path, v2_job.args->>'_FLOW_PATH') as parent_runnable_path,
|
||||
COALESCE(pj.runnable_path, CASE WHEN v2_job.kind = 'preview' THEN v2_job.args->>'_FLOW_PATH' END) as parent_runnable_path,
|
||||
p.email as permissioned_as_email, p.username as permissioned_as_username, p.is_admin as permissioned_as_is_admin,
|
||||
p.is_operator as permissioned_as_is_operator, p.groups as permissioned_as_groups, p.folders as permissioned_as_folders, p.end_user_email as permissioned_as_end_user_email,
|
||||
p.viewer_data_access, p.mcp_client
|
||||
@@ -9455,6 +9552,20 @@ pub async fn get_same_worker_job(
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod canceled_result_tests {
|
||||
#[test]
|
||||
fn reason_is_kept_as_plain_text() {
|
||||
for reason in ["$var:u/a/s", "$WM_TOKEN", "see $res:u/a/r"] {
|
||||
let e = super::canceled_result(Some(reason), Some("anonymous")).to_string();
|
||||
assert!(
|
||||
!windmill_common::variables::untrusted_arg_interpolates(&e),
|
||||
"{reason}: {e}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod git_sync_concurrency_key_tests {
|
||||
use super::git_sync_concurrency_key;
|
||||
|
||||
@@ -29,6 +29,7 @@ pub mod freshness_watchdog_oss;
|
||||
pub use freshness_watchdog_ee as freshness_watchdog;
|
||||
#[cfg(not(feature = "private"))]
|
||||
pub use freshness_watchdog_oss as freshness_watchdog;
|
||||
mod failed_only_restart;
|
||||
pub mod jobs;
|
||||
#[cfg(feature = "private")]
|
||||
pub mod jobs_ee;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// Alone in its binary: the worker caches a workspace's handler settings process-wide for 60s,
|
||||
// keyed by workspace id, so a second test here would read the first one's settings.
|
||||
mod workspace_error_handler {
|
||||
use serde_json::json;
|
||||
use sqlx::types::Json;
|
||||
use sqlx::{Pool, Postgres};
|
||||
use uuid::Uuid;
|
||||
|
||||
use windmill_common::jobs::{JobKind, JobTriggerKind};
|
||||
use windmill_common::scripts::{ScriptHash, ScriptLang};
|
||||
use windmill_common::users::username_to_permissioned_as;
|
||||
use windmill_queue::jobs::{send_error_to_workspace_handler, MiniCompletedJob};
|
||||
|
||||
const WS: &str = "test-workspace";
|
||||
const SCRIPT: &str = "f/system/test_script";
|
||||
|
||||
fn failed(trigger_kind: JobTriggerKind) -> MiniCompletedJob {
|
||||
MiniCompletedJob {
|
||||
id: Uuid::new_v4(),
|
||||
workspace_id: WS.to_string(),
|
||||
runnable_id: Some(ScriptHash(100001)),
|
||||
scheduled_for: chrono::Utc::now(),
|
||||
parent_job: None,
|
||||
flow_innermost_root_job: None,
|
||||
runnable_path: Some(SCRIPT.to_string()),
|
||||
kind: JobKind::Script,
|
||||
started_at: Some(chrono::Utc::now()),
|
||||
permissioned_as: username_to_permissioned_as("test-user"),
|
||||
created_by: "test-user".to_string(),
|
||||
script_lang: Some(ScriptLang::Deno),
|
||||
permissioned_as_email: "test@windmill.dev".to_string(),
|
||||
flow_step_id: None,
|
||||
trigger_kind: Some(trigger_kind.into()),
|
||||
trigger: None,
|
||||
priority: None,
|
||||
concurrent_limit: None,
|
||||
tag: "deno".to_string(),
|
||||
cache_ttl: None,
|
||||
cache_ignore_s3_path: None,
|
||||
runnable_settings_handle: None,
|
||||
build_binary_only: false,
|
||||
job_token_scopes: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn handler_jobs(db: &Pool<Postgres>) -> i64 {
|
||||
sqlx::query_scalar("SELECT count(*) FROM v2_job WHERE workspace_id = $1")
|
||||
.bind(WS)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))]
|
||||
async fn muted_on_ui_runs_skips_only_ui_runs(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
sqlx::query("UPDATE workspace_settings SET error_handler = $1 WHERE workspace_id = $2")
|
||||
.bind(json!({ "path": format!("script/{SCRIPT}"), "muted_on_ui_runs": true }))
|
||||
.bind(WS)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let error = json!({ "error": "boom" });
|
||||
|
||||
send_error_to_workspace_handler(&failed(JobTriggerKind::Ui), false, &db, Json(&error))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
handler_jobs(&db).await,
|
||||
0,
|
||||
"a ui run must not reach the handler"
|
||||
);
|
||||
|
||||
send_error_to_workspace_handler(&failed(JobTriggerKind::Webhook), false, &db, Json(&error))
|
||||
.await?;
|
||||
assert_eq!(handler_jobs(&db).await, 1, "any other run still does");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,14 @@ pub struct RestartedFrom {
|
||||
/// `restarted_from` becomes `*nested`, propagating any further levels of nesting.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub nested: Option<Box<RestartedFrom>>,
|
||||
/// For a parallel ForLoop / BranchAll at `step_id`: keep the iterations (branches) that
|
||||
/// succeeded and rerun only the others, each in its original slot.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub failed_only: bool,
|
||||
/// With `failed_only`: resume each failed iteration at the step where it failed, keeping
|
||||
/// the steps before it, rather than rerunning it from its first step.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub from_failed_step: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
|
||||
@@ -56,10 +56,9 @@ pub enum JobTriggerKind {
|
||||
// produced from files a viewer forged by running a declared runnable directly.
|
||||
App,
|
||||
// A run started from the browser (the `/jobs/run*` request carried the session token
|
||||
// minted at login). Nothing writes this yet — it exists so every binary from this release
|
||||
// can decode it, which is what a later release needs before it can start stamping it.
|
||||
// When that happens: attribution, not authority, unlike `App` — a member can have a
|
||||
// session token minted for a script (`/users/refresh_token`), so nothing may gate on it.
|
||||
// minted at login), stamped only once every worker decodes it (`trigger_or_fallback`).
|
||||
// Attribution, not authority, unlike `App` — a member can have a session token minted for
|
||||
// a script (`/users/refresh_token`), so no access decision may gate on it.
|
||||
Ui,
|
||||
}
|
||||
|
||||
@@ -604,6 +603,10 @@ pub enum JobPayload {
|
||||
/// upon reaching `step_id`, should spawn the inner child as a `RestartedFlow`
|
||||
/// using this chain rather than fresh-launching it.
|
||||
nested: Option<Box<crate::flow_status::RestartedFrom>>,
|
||||
/// See `RestartedFrom::failed_only`.
|
||||
failed_only: bool,
|
||||
/// See `RestartedFrom::from_failed_step`.
|
||||
from_failed_step: bool,
|
||||
},
|
||||
RawFlow {
|
||||
value: FlowValue,
|
||||
@@ -744,10 +747,15 @@ pub const MODULES_ARG: &str = "_MODULES";
|
||||
/// honor it on every `JobKind::Preview` job.
|
||||
pub const TEMP_SCRIPT_REFS_ARG: &str = "_TEMP_SCRIPT_REFS";
|
||||
|
||||
/// Job-arg key the preview route sets server-side from its `flow_path` field, so a step
|
||||
/// tested from the flow editor sees its flow's path. `WM_FLOW_PATH`, `WM_STATE_PATH` and
|
||||
/// `WM_OBJECT_PATH` derive from it; the worker honors it only on `JobKind::Preview` jobs.
|
||||
pub const FLOW_PATH_ARG: &str = "_FLOW_PATH";
|
||||
|
||||
/// Job-arg keys that steer *how* a runnable runs rather than what it is given: which
|
||||
/// function the worker calls instead of `main` ([`ENTRYPOINT_OVERRIDE`]), what module files
|
||||
/// are written into the job directory ([`MODULES_ARG`]) and where its workspace imports
|
||||
/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]).
|
||||
/// are written into the job directory ([`MODULES_ARG`]), where its workspace imports
|
||||
/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]) and where its state lives ([`FLOW_PATH_ARG`]).
|
||||
///
|
||||
/// Each is legitimate for a caller that runs code it authored under its own identity (the
|
||||
/// script editor's preprocessor test, dynamic-select helpers, the CLI, workflow-as-code), so
|
||||
@@ -755,8 +763,12 @@ pub const TEMP_SCRIPT_REFS_ARG: &str = "_TEMP_SCRIPT_REFS";
|
||||
/// payload runs under somebody else's identity — an HTTP route body, a native trigger
|
||||
/// message, a public app viewer's inputs — which is what `sanitize_untrusted_args` in
|
||||
/// `windmill_common::jobs` drops.
|
||||
pub const RESERVED_CONTROL_ARGS: [&str; 3] =
|
||||
[ENTRYPOINT_OVERRIDE, MODULES_ARG, TEMP_SCRIPT_REFS_ARG];
|
||||
pub const RESERVED_CONTROL_ARGS: [&str; 4] = [
|
||||
ENTRYPOINT_OVERRIDE,
|
||||
MODULES_ARG,
|
||||
TEMP_SCRIPT_REFS_ARG,
|
||||
FLOW_PATH_ARG,
|
||||
];
|
||||
|
||||
/// Reserved job-arg key holding the inbound W3C `traceparent` captured from the
|
||||
/// request that enqueued the job (run endpoints). It rides the `args` jsonb like
|
||||
|
||||
@@ -108,8 +108,8 @@ mount {
|
||||
}
|
||||
|
||||
mount {
|
||||
src: "{TARGET_DIR}"
|
||||
dst: "{TARGET_DIR}"
|
||||
src: {TARGET_DIR}
|
||||
dst: {TARGET_DIR}
|
||||
is_bind: true
|
||||
rw: true
|
||||
}
|
||||
|
||||
@@ -94,8 +94,8 @@ mount {
|
||||
{TMP_MOUNT_BLOCK}
|
||||
|
||||
mount {
|
||||
src: "{TARGET}"
|
||||
dst: "{TARGET}"
|
||||
src: {TARGET}
|
||||
dst: {TARGET}
|
||||
is_bind: true
|
||||
mandatory: false
|
||||
rw: true
|
||||
|
||||
@@ -87,7 +87,7 @@ mount {
|
||||
is_bind: true
|
||||
}
|
||||
mount {
|
||||
src: "{JOB_DIR}"
|
||||
src: "{CRATE_DIR}"
|
||||
dst: "/tmp"
|
||||
is_bind: true
|
||||
rw: true
|
||||
|
||||
@@ -100,10 +100,11 @@ mount {
|
||||
{HOME_MOUNT_BLOCK}
|
||||
|
||||
# The install dir (package.json, lockfile, registry config; node_modules is
|
||||
# written there) and, for bun, the shared bun cache, writable like the other
|
||||
# install jails' shared caches. A bun install dir inside the cache gets no bind
|
||||
# of its own: that would be a second mount, and bun can only hardlink from its
|
||||
# cache within one.
|
||||
# written there) and, for bun, a cache of this install alone, never the
|
||||
# worker's. Never the job dir either, which the worker reads afterwards: a
|
||||
# staged install or a copy of the job dir bound at its path. The install dir
|
||||
# and the cache share one mount, since bun can only hardlink from its cache
|
||||
# within one.
|
||||
{INSTALL_MOUNTS}
|
||||
|
||||
mount {
|
||||
|
||||
@@ -106,15 +106,8 @@ mount {
|
||||
rw: true
|
||||
}
|
||||
|
||||
# shared uv cache: resolution metadata + where sdist build backends run
|
||||
# (builds-v0/). Writable, as the install jail's target already is; a poisoned
|
||||
# shared cache is the known residual, not a new one.
|
||||
mount {
|
||||
src: "{UV_CACHE_DIR}"
|
||||
dst: "{UV_CACHE_DIR}"
|
||||
is_bind: true
|
||||
rw: true
|
||||
}
|
||||
# No uv cache mount: the worker-wide cache stays out of jailed resolutions.
|
||||
# uv runs with --no-cache and keeps a throwaway cache in this jail's /tmp.
|
||||
|
||||
mount {
|
||||
src: "{PY_INSTALL_DIR}"
|
||||
|
||||
@@ -7,7 +7,7 @@ time_limit: {TIMEOUT}
|
||||
|
||||
{RLIMIT_AS}
|
||||
rlimit_cpu: 1000
|
||||
rlimit_fsize: 1000
|
||||
{RLIMIT_FSIZE}
|
||||
rlimit_nofile: 10000
|
||||
|
||||
cwd: "/tmp"
|
||||
@@ -18,6 +18,9 @@ clone_newuser: {CLONE_NEWUSER}
|
||||
skip_setsid: true
|
||||
keep_caps: false
|
||||
keep_env: true
|
||||
# The script's env vars, proto-quoted. Set here, for the jailed child only,
|
||||
# rather than on the process that execs nsjail.
|
||||
{ENVARS}
|
||||
mount_proc: true
|
||||
|
||||
mount {
|
||||
@@ -172,7 +175,7 @@ mount {
|
||||
iface_no_lo: true
|
||||
|
||||
envar: "LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH"
|
||||
envar: "PYTHONPATH={ADDITIONAL_PYTHON_PATHS}"
|
||||
envar: {PYTHONPATH}
|
||||
envar: "HOME=/tmp"
|
||||
envar: "ANSIBLE_CONFIG=/tmp/ansible.cfg"
|
||||
# Ansible never flushes its own stdout; on the pipe Windmill gives it, python block-buffers
|
||||
|
||||
@@ -15,6 +15,9 @@ clone_newuser: {CLONE_NEWUSER}
|
||||
skip_setsid: true
|
||||
keep_caps: false
|
||||
keep_env: true
|
||||
# The script's env vars, proto-quoted. Set here, for the jailed child only,
|
||||
# rather than on the process that execs nsjail.
|
||||
{ENVARS}
|
||||
mount_proc: true
|
||||
|
||||
mount {
|
||||
|
||||
@@ -7,7 +7,7 @@ time_limit: {TIMEOUT}
|
||||
|
||||
{RLIMIT_AS}
|
||||
rlimit_cpu: 1000
|
||||
rlimit_fsize: 1000
|
||||
{RLIMIT_FSIZE}
|
||||
rlimit_nofile: 10000
|
||||
|
||||
cwd: "{PROJECT_DIR}"
|
||||
|
||||
@@ -15,6 +15,9 @@ clone_newuser: {CLONE_NEWUSER}
|
||||
skip_setsid: true
|
||||
keep_caps: false
|
||||
keep_env: true
|
||||
# The script's env vars, proto-quoted. Set here, for the jailed child only,
|
||||
# rather than on the process that execs nsjail.
|
||||
{ENVARS}
|
||||
mount_proc: true
|
||||
|
||||
mount {
|
||||
|
||||
@@ -7,7 +7,7 @@ time_limit: {TIMEOUT}
|
||||
|
||||
{RLIMIT_AS}
|
||||
rlimit_cpu: 1000
|
||||
rlimit_fsize: 1000
|
||||
{RLIMIT_FSIZE}
|
||||
rlimit_nofile: 10000
|
||||
|
||||
cwd: "/tmp"
|
||||
@@ -18,6 +18,9 @@ clone_newuser: {CLONE_NEWUSER}
|
||||
skip_setsid: true
|
||||
keep_caps: false
|
||||
keep_env: true
|
||||
# The script's env vars, proto-quoted. Set here, for the jailed child only,
|
||||
# rather than on the process that execs nsjail.
|
||||
{ENVARS}
|
||||
mount_proc: true
|
||||
|
||||
mount {
|
||||
@@ -57,8 +60,8 @@ mount {
|
||||
{TMP_MOUNT_BLOCK}
|
||||
|
||||
mount {
|
||||
src: "{JOB_DIR}/{MAIN}.py"
|
||||
dst: "/tmp/{MAIN}.py"
|
||||
src: {MAIN_SRC}
|
||||
dst: {MAIN_DST}
|
||||
is_bind: true
|
||||
}
|
||||
|
||||
@@ -167,7 +170,7 @@ mount {
|
||||
iface_no_lo: true
|
||||
|
||||
envar: "LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH"
|
||||
envar: "PYTHONPATH={ADDITIONAL_PYTHON_PATHS}"
|
||||
envar: {PYTHONPATH}
|
||||
envar: "HOME=/tmp"
|
||||
|
||||
mount {
|
||||
|
||||
@@ -727,6 +727,36 @@ async fn execute_mcp_tool_call(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The model's arguments, keeping only the inputs the tool was advertised with. Control
|
||||
/// arguments (`_ENTRYPOINT_OVERRIDE`, `_TEMP_SCRIPT_REFS`) and a sub-agent's settings
|
||||
/// (`memory`) come from the flow definition, never from the model's call.
|
||||
fn model_tool_call_args(
|
||||
tool_call: &OpenAIToolCall,
|
||||
tool: &Tool,
|
||||
) -> Result<HashMap<String, Box<RawValue>>, Error> {
|
||||
let raw_tool_call_args = if tool_call.function.arguments.is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
tool_call.function.arguments.as_str()
|
||||
};
|
||||
|
||||
let mut tool_call_args = serde_json::from_str::<HashMap<String, Box<RawValue>>>(
|
||||
raw_tool_call_args,
|
||||
)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to parse tool call arguments for tool call {}: {}",
|
||||
tool_call.function.name, tool_call.function.arguments
|
||||
)
|
||||
})?;
|
||||
|
||||
let schema = serde_json::from_str::<serde_json::Value>(tool.def.function.parameters.get())
|
||||
.context("Failed to parse tool schema")?;
|
||||
let offered = schema.get("properties").and_then(|p| p.as_object());
|
||||
tool_call_args.retain(|key, _| offered.is_some_and(|p| p.contains_key(key)));
|
||||
Ok(tool_call_args)
|
||||
}
|
||||
|
||||
/// Execute a Windmill tool (script or flow)
|
||||
async fn enqueue_windmill_tool(
|
||||
ctx: &ToolExecutionContext<'_>,
|
||||
@@ -751,21 +781,7 @@ async fn enqueue_windmill_tool(
|
||||
update_flow_status_module_with_actions(ctx.db, parent_job, actions).await?;
|
||||
}
|
||||
|
||||
let raw_tool_call_args = if tool_call.function.arguments.is_empty() {
|
||||
"{}".to_string()
|
||||
} else {
|
||||
tool_call.function.arguments.clone()
|
||||
};
|
||||
|
||||
let mut tool_call_args = serde_json::from_str::<HashMap<String, Box<RawValue>>>(
|
||||
&raw_tool_call_args,
|
||||
)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to parse tool call arguments for tool call {}: {}",
|
||||
tool_call.function.name, tool_call.function.arguments
|
||||
)
|
||||
})?;
|
||||
let mut tool_call_args = model_tool_call_args(tool_call, tool)?;
|
||||
|
||||
let tool_value = tool_module.get_value()?;
|
||||
|
||||
@@ -1631,6 +1647,60 @@ mod tests {
|
||||
assert!(!interpolating_args(&call(r#"{"x":"$5 and var: 3"}"#)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_job_gets_only_the_inputs_the_model_was_offered() {
|
||||
use super::model_tool_call_args;
|
||||
use windmill_ai::types::{Tool, ToolDef, ToolDefFunction};
|
||||
let tool = |schema: &str| Tool {
|
||||
module: None,
|
||||
def: ToolDef {
|
||||
r#type: "function".to_string(),
|
||||
function: ToolDefFunction {
|
||||
name: "t".to_string(),
|
||||
description: None,
|
||||
parameters: RawValue::from_string(schema.to_string()).unwrap(),
|
||||
},
|
||||
},
|
||||
mcp_source: None,
|
||||
requires_approval: false,
|
||||
question_timeout_secs: None,
|
||||
background_after_secs: None,
|
||||
};
|
||||
let call = |arguments: &str| OpenAIToolCall {
|
||||
id: "call_1".to_string(),
|
||||
function: OpenAIFunction { name: "t".to_string(), arguments: arguments.to_string() },
|
||||
r#type: "function".to_string(),
|
||||
extra_content: None,
|
||||
};
|
||||
let keys = |schema: &str, arguments: &str| {
|
||||
let mut keys = model_tool_call_args(&call(arguments), &tool(schema))
|
||||
.unwrap()
|
||||
.into_keys()
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort();
|
||||
keys
|
||||
};
|
||||
|
||||
let script = r#"{"type":"object","properties":{"check":{"type":"string"}}}"#;
|
||||
assert_eq!(
|
||||
keys(
|
||||
script,
|
||||
r#"{"check":"disk","_ENTRYPOINT_OVERRIDE":"_run","_ENTRYPOINT_OVERRIDE\u0000":"_run","_TEMP_SCRIPT_REFS":{},"argv":[]}"#
|
||||
),
|
||||
["check"]
|
||||
);
|
||||
let agent = r#"{"type":"object","properties":{"user_message":{"type":"string"}}}"#;
|
||||
assert_eq!(
|
||||
keys(
|
||||
agent,
|
||||
r#"{"user_message":"hi","memory":{"kind":"auto","memory_id":"x"}}"#
|
||||
),
|
||||
["user_message"]
|
||||
);
|
||||
assert!(keys("{}", r#"{"x":1}"#).is_empty());
|
||||
assert!(keys(script, "").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_only_the_output_of_an_agent_result() {
|
||||
let envelope = RawValue::from_string(
|
||||
|
||||
@@ -34,15 +34,16 @@ use crate::{
|
||||
bash_executor::BIN_BASH,
|
||||
common::{
|
||||
build_command_with_isolation, check_executor_binary_exists, get_reserved_variables,
|
||||
interpolate_template, read_and_check_result, render_nsjail_rlimit_as,
|
||||
resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, start_child_process,
|
||||
transform_json, validate_relative_path, OccupancyMetrics,
|
||||
interpolate_template, proto_str, read_and_check_result, render_nsjail_rlimit_as,
|
||||
render_nsjail_rlimit_fsize, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block,
|
||||
script_envars, start_child_process, transform_json, validate_relative_path,
|
||||
OccupancyMetrics,
|
||||
},
|
||||
handle_child::{handle_child, run_future_with_polling_update_job_poller},
|
||||
is_sandboxing_enabled,
|
||||
python_executor::{create_dependencies_dir, handle_python_reqs, uv_pip_compile},
|
||||
PyV, DISABLE_NUSER, GIT_PATH, HOME_ENV, NSJAIL_ANSIBLE_RLIMIT_AS_MB, NSJAIL_PATH, PATH_ENV,
|
||||
PROXY_ENVS, PY_INSTALL_DIR, TZ_ENV,
|
||||
PyV, DISABLE_NUSER, GIT_PATH, HOME_ENV, NSJAIL_ANSIBLE_RLIMIT_AS_MB, NSJAIL_PATH,
|
||||
NSJAIL_RLIMIT_FSIZE_MB, PATH_ENV, PROXY_ENVS, PY_INSTALL_DIR, TZ_ENV,
|
||||
};
|
||||
use windmill_common::client::AuthedClient;
|
||||
|
||||
@@ -2137,15 +2138,16 @@ pub async fn handle_ansible_job(
|
||||
get_reserved_variables(job, &client.token, conn, parent_runnable_path).await?;
|
||||
let additional_python_paths_folders = additional_python_paths.join(":");
|
||||
|
||||
if is_sandboxing_enabled() {
|
||||
let run_config = if is_sandboxing_enabled() {
|
||||
let shared_deps = additional_python_paths
|
||||
.into_iter()
|
||||
.map(|pp| {
|
||||
let pp = proto_str(&pp);
|
||||
format!(
|
||||
r#"
|
||||
mount {{
|
||||
src: "{pp}"
|
||||
dst: "{pp}"
|
||||
src: {pp}
|
||||
dst: {pp}
|
||||
is_bind: true
|
||||
rw: false
|
||||
}}
|
||||
@@ -2155,14 +2157,16 @@ mount {{
|
||||
.join("\n");
|
||||
let nsjail_timeout =
|
||||
resolve_nsjail_timeout(conn, &job.workspace_id, job.id, job.timeout).await;
|
||||
let _ = write_file(
|
||||
job_dir,
|
||||
"run.config.proto",
|
||||
&NSJAIL_CONFIG_RUN_ANSIBLE_CONTENT
|
||||
Some(
|
||||
NSJAIL_CONFIG_RUN_ANSIBLE_CONTENT
|
||||
.replace(
|
||||
"{RLIMIT_AS}",
|
||||
&render_nsjail_rlimit_as(NSJAIL_ANSIBLE_RLIMIT_AS_MB.as_deref(), 4096),
|
||||
)
|
||||
.replace(
|
||||
"{RLIMIT_FSIZE}",
|
||||
&render_nsjail_rlimit_fsize(NSJAIL_RLIMIT_FSIZE_MB.as_deref(), 1000),
|
||||
)
|
||||
.replace("{PY_INSTALL_DIR}", &*PY_INSTALL_DIR)
|
||||
.replace("{JOB_DIR}", job_dir)
|
||||
.replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string())
|
||||
@@ -2170,18 +2174,19 @@ mount {{
|
||||
.replace("{SHARED_DEPENDENCIES}", shared_deps.as_str())
|
||||
.replace("{FILE_RESOURCES}", nsjail_extra_mounts.join("\n").as_str())
|
||||
.replace(
|
||||
"{ADDITIONAL_PYTHON_PATHS}",
|
||||
additional_python_paths_folders.as_str(),
|
||||
"{PYTHONPATH}",
|
||||
&proto_str(&format!("PYTHONPATH={additional_python_paths_folders}")),
|
||||
)
|
||||
.replace(
|
||||
"{TMP_MOUNT_BLOCK}",
|
||||
&resolve_nsjail_tmp_mount_block(job_dir).await,
|
||||
)
|
||||
.replace("{TIMEOUT}", &nsjail_timeout),
|
||||
)?;
|
||||
)
|
||||
} else {
|
||||
reserved_variables.insert("PYTHONPATH".to_string(), additional_python_paths_folders);
|
||||
}
|
||||
None
|
||||
};
|
||||
|
||||
let playbook = playbook_override
|
||||
.flatten()
|
||||
@@ -2233,6 +2238,13 @@ fi
|
||||
)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let _ = write_file(
|
||||
job_dir,
|
||||
"run.config.proto",
|
||||
&run_config
|
||||
.unwrap_or_default()
|
||||
.replace("{ENVARS}", &script_envars(&envs, &nsjail_cmd, &[])),
|
||||
)?;
|
||||
start_child_process(nsjail_cmd, NSJAIL_PATH.as_str(), false).await?
|
||||
} else {
|
||||
let ansible_args: Vec<&str> = cmd_args.iter().map(|s| s.as_ref()).collect();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user