Merge remote-tracking branch 'origin/main' into deploy-block-on-failing-ci-tests

# Conflicts:
#	backend/windmill-api/src/ai_session_tools/gen/instructions.json
This commit is contained in:
hugocasa
2026-11-24 17:32:24 +01:00
203 changed files with 5032 additions and 1777 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "1.882.0"
".": "1.883.0"
}
+39
View File
@@ -1,5 +1,44 @@
# Changelog
## [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)
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
+150 -149
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "windmill"
version = "1.882.0"
version = "1.883.0"
authors.workspace = true
edition.workspace = true
@@ -88,7 +88,7 @@ members = [
exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"]
[workspace.package]
version = "1.882.0"
version = "1.883.0"
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
edition = "2021"
+1 -1
View File
@@ -1 +1 @@
6c06d688fe435630e2827bc177f066d2646bb768
a403f3ce12fd150dd649098e61562eda1e6a4d81
+24 -24
View File
@@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windmill-common"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"aes-gcm",
"aho-corasick",
@@ -6430,7 +6430,7 @@ dependencies = [
[[package]]
name = "windmill-macros"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"proc-macro2",
"quote",
@@ -6442,7 +6442,7 @@ dependencies = [
[[package]]
name = "windmill-parser"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"convert_case",
"serde",
@@ -6451,7 +6451,7 @@ dependencies = [
[[package]]
name = "windmill-parser-bash"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6463,7 +6463,7 @@ dependencies = [
[[package]]
name = "windmill-parser-csharp"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"serde_json",
@@ -6475,7 +6475,7 @@ dependencies = [
[[package]]
name = "windmill-parser-go"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"gosyn",
@@ -6487,7 +6487,7 @@ dependencies = [
[[package]]
name = "windmill-parser-graphql"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6499,7 +6499,7 @@ dependencies = [
[[package]]
name = "windmill-parser-java"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"serde_json",
@@ -6511,7 +6511,7 @@ dependencies = [
[[package]]
name = "windmill-parser-nu"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"nu-parser",
@@ -6522,7 +6522,7 @@ dependencies = [
[[package]]
name = "windmill-parser-php"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -6533,7 +6533,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -6545,7 +6545,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-asset"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -6556,7 +6556,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-imports"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"async-recursion",
@@ -6579,7 +6579,7 @@ dependencies = [
[[package]]
name = "windmill-parser-r"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"serde_json",
@@ -6591,7 +6591,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ruby"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6605,7 +6605,7 @@ dependencies = [
[[package]]
name = "windmill-parser-rust"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"convert_case",
@@ -6622,7 +6622,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6635,7 +6635,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql-asset"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"serde",
@@ -6647,7 +6647,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6665,7 +6665,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts-asset"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"serde-wasm-bindgen",
@@ -6681,7 +6681,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wac"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -6698,7 +6698,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wasm"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"getrandom 0.2.17",
@@ -6730,7 +6730,7 @@ dependencies = [
[[package]]
name = "windmill-parser-yaml"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6744,7 +6744,7 @@ dependencies = [
[[package]]
name = "windmill-types"
version = "1.882.0"
version = "1.883.0"
dependencies = [
"anyhow",
"bitflags",
@@ -12,7 +12,7 @@ resolver = "2"
members = ["."]
[workspace.package]
version = "1.882.0"
version = "1.883.0"
edition = "2021"
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
+12
View File
@@ -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,
+8
View File
@@ -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();
+3
View File
@@ -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
+17 -9
View File
@@ -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))
}
@@ -1648,11 +1649,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),
@@ -1662,7 +1663,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"),
@@ -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 {
@@ -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",
+26 -2
View File
@@ -1,7 +1,7 @@
openapi: "3.0.3"
info:
version: 1.882.0
version: 1.883.0
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:
@@ -19485,6 +19493,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":
@@ -30855,6 +30872,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
@@ -30887,6 +30908,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.
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": {
+27 -1
View File
@@ -12650,6 +12650,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 +12681,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 +12734,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
+3 -1
View File
@@ -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
+2
View File
@@ -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"))]
@@ -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");
+1
View File
@@ -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;
@@ -48,6 +48,9 @@ pub const MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES: VC = vc(1, 872, 0, "Lease-fre
// 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");
+455
View File
@@ -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(())
}
}
+72 -25
View File
@@ -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("#")]
@@ -1988,6 +1978,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 +2006,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(),
}
}
@@ -4442,4 +4448,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);
}
}
+3 -2
View File
@@ -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,
}
+54 -50
View File
@@ -1426,8 +1426,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 +2989,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 +3010,7 @@ async fn fetch_error_handler_from_db(
Option<Json<Box<RawValue>>>,
Option<bool>,
Option<bool>,
Option<bool>,
bool,
),
>(
@@ -3018,6 +3020,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 +3032,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 +3060,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 +3086,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 +3099,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!(
@@ -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(())
}
}
+3 -4
View File
@@ -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,
}
@@ -7,7 +7,7 @@ time_limit: {TIMEOUT}
{RLIMIT_AS}
rlimit_cpu: 1000
rlimit_fsize: 1000
{RLIMIT_FSIZE}
rlimit_nofile: 10000
cwd: "/tmp"
@@ -7,7 +7,7 @@ time_limit: {TIMEOUT}
{RLIMIT_AS}
rlimit_cpu: 1000
rlimit_fsize: 1000
{RLIMIT_FSIZE}
rlimit_nofile: 10000
cwd: "{PROJECT_DIR}"
@@ -7,7 +7,7 @@ time_limit: {TIMEOUT}
{RLIMIT_AS}
rlimit_cpu: 1000
rlimit_fsize: 1000
{RLIMIT_FSIZE}
rlimit_nofile: 10000
cwd: "/tmp"
@@ -35,14 +35,14 @@ use crate::{
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,
render_nsjail_rlimit_fsize, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block,
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;
@@ -2163,6 +2163,10 @@ mount {{
"{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())
+37 -6
View File
@@ -1457,23 +1457,37 @@ pub async fn resolve_nsjail_timeout(
/// - `unlimited`/`none`/`inf`/`0` -> `rlimit_as_type: INF` (address space uncapped)
/// - a positive integer (MiB) -> `rlimit_as: {n}`
pub fn render_nsjail_rlimit_as(env_override: Option<&str>, default_mb: u32) -> String {
render_nsjail_rlimit("rlimit_as", env_override, default_mb)
}
/// Render the `rlimit_fsize` line (largest single file a jailed job may write, in
/// MiB) for the nsjail run configs that set one (python3, ansible, dbt), honoring
/// the `NSJAIL_RLIMIT_FSIZE_MB` env var. Same value grammar as
/// [`render_nsjail_rlimit_as`]. The total space a job can fill is bounded
/// separately by its `/tmp` (tmpfs size or, when disk-backed, the worker's disk),
/// so operators who move `/tmp` to disk usually want to raise or lift this too.
pub fn render_nsjail_rlimit_fsize(env_override: Option<&str>, default_mb: u32) -> String {
render_nsjail_rlimit("rlimit_fsize", env_override, default_mb)
}
fn render_nsjail_rlimit(field: &str, env_override: Option<&str>, default_mb: u32) -> String {
match env_override.map(str::trim) {
None | Some("") => format!("rlimit_as: {default_mb}"),
None | Some("") => format!("{field}: {default_mb}"),
Some(v)
if v.eq_ignore_ascii_case("unlimited")
|| v.eq_ignore_ascii_case("none")
|| v.eq_ignore_ascii_case("inf")
|| v == "0" =>
{
"rlimit_as_type: INF".to_string()
format!("{field}_type: INF")
}
Some(v) => match v.parse::<u32>() {
Ok(mb) => format!("rlimit_as: {mb}"),
Ok(mb) => format!("{field}: {mb}"),
Err(_) => {
tracing::warn!(
"Invalid nsjail rlimit_as override {v:?}, using default {default_mb}MiB"
"Invalid nsjail {field} override {v:?}, using default {default_mb}MiB"
);
format!("rlimit_as: {default_mb}")
format!("{field}: {default_mb}")
}
},
}
@@ -1668,7 +1682,7 @@ pub(crate) async fn resolve_nsjail_tmp_mount_block(job_dir: &str) -> String {
#[cfg(test)]
mod nsjail_rlimit_as_tests {
use super::render_nsjail_rlimit_as;
use super::{render_nsjail_rlimit_as, render_nsjail_rlimit_fsize};
#[test]
fn unset_uses_default() {
@@ -1707,6 +1721,23 @@ mod nsjail_rlimit_as_tests {
);
assert_eq!(render_nsjail_rlimit_as(Some("-1"), 4096), "rlimit_as: 4096");
}
#[test]
fn fsize_uses_its_own_field() {
assert_eq!(render_nsjail_rlimit_fsize(None, 1000), "rlimit_fsize: 1000");
assert_eq!(
render_nsjail_rlimit_fsize(Some("20000"), 1000),
"rlimit_fsize: 20000"
);
assert_eq!(
render_nsjail_rlimit_fsize(Some("unlimited"), 1000),
"rlimit_fsize_type: INF"
);
assert_eq!(
render_nsjail_rlimit_fsize(Some("abc"), 1000),
"rlimit_fsize: 1000"
);
}
}
#[cfg(test)]
@@ -143,6 +143,10 @@ pub async fn generate_nuget_lockfile(
.env("NUGET_PACKAGES", format!("{}/nuget", *CSHARP_CACHE_DIR))
.env("DOTNET_CLI_TELEMETRY_OPTOUT", "true")
.env("DOTNET_NOLOGO", "true")
// The SDK's first run otherwise generates an HTTPS dev certificate and puts the global
// tools directory on PATH, in a home every worker sharing the cache may enter at once.
.env("DOTNET_GENERATE_ASPNET_CERTIFICATE", "false")
.env("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false")
.env("MSBUILDDISABLENODEREUSE", "1")
.env("DOTNET_ROOT", DOTNET_ROOT.as_str())
.args(vec!["restore", "--use-lock-file"])
@@ -495,6 +499,8 @@ async fn build_cs_proj(
.env("NUGET_PACKAGES", format!("{}/nuget", *CSHARP_CACHE_DIR))
.env("DOTNET_CLI_TELEMETRY_OPTOUT", "true")
.env("DOTNET_NOLOGO", "true")
.env("DOTNET_GENERATE_ASPNET_CERTIFICATE", "false")
.env("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false")
.env("MSBUILDDISABLENODEREUSE", "1")
.env("DOTNET_ROOT", DOTNET_ROOT.as_str())
.envs(PROXY_ENVS.clone())
@@ -514,6 +520,8 @@ async fn build_cs_proj(
.env("NUGET_PACKAGES", format!("{}/nuget", *CSHARP_CACHE_DIR))
.env("DOTNET_CLI_TELEMETRY_OPTOUT", "true")
.env("DOTNET_NOLOGO", "true")
.env("DOTNET_GENERATE_ASPNET_CERTIFICATE", "false")
.env("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false")
.env("MSBUILDDISABLENODEREUSE", "1")
.env("DOTNET_ROOT", DOTNET_ROOT.as_str())
.args(publish_args.clone())
+8 -3
View File
@@ -31,7 +31,8 @@ use windmill_parser_yaml::{
use windmill_queue::{append_logs, CanceledBy, MiniPulledJob};
use crate::common::{
render_envars, render_nsjail_rlimit_as, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block,
render_envars, render_nsjail_rlimit_as, render_nsjail_rlimit_fsize, resolve_nsjail_timeout,
resolve_nsjail_tmp_mount_block,
};
use crate::common::{start_child_process, OccupancyMetrics};
use crate::dbt_engine::{provision_engine, ProvisionedEngine, DBT_CACHE_DIR};
@@ -46,8 +47,8 @@ use crate::handle_child::{
};
use crate::worker::write_module_files;
use crate::{
is_sandboxing_enabled, GIT_PATH, NSJAIL_DBT_RLIMIT_AS_MB, NSJAIL_PATH, PATH_ENV, PROXY_ENVS,
TZ_ENV,
is_sandboxing_enabled, GIT_PATH, NSJAIL_DBT_RLIMIT_AS_MB, NSJAIL_PATH, NSJAIL_RLIMIT_FSIZE_MB,
PATH_ENV, PROXY_ENVS, TZ_ENV,
};
/// The profile name Windmill renders into `profiles.yml`. dbt takes the profile
@@ -1372,6 +1373,10 @@ pub(crate) async fn prepare_project(
"{RLIMIT_AS}",
&render_nsjail_rlimit_as(NSJAIL_DBT_RLIMIT_AS_MB.as_deref(), 4096),
)
.replace(
"{RLIMIT_FSIZE}",
&render_nsjail_rlimit_fsize(NSJAIL_RLIMIT_FSIZE_MB.as_deref(), 1000),
)
.replace("{JOB_DIR}", &escape_textproto(job_dir))
.replace(
"{PROJECT_DIR}",
+1
View File
@@ -1,3 +1,4 @@
#![recursion_limit = "256"]
#[cfg(feature = "bigquery")]
mod bigquery_executor;
#[cfg(all(feature = "enterprise", feature = "mssql"))]
+10 -6
View File
@@ -153,18 +153,18 @@ use windmill_object_store::get_cache_object_store;
use crate::{
check_no_network_jailed,
common::{
build_command_with_isolation, create_args_and_out_file, get_reserved_variables, read_file,
read_result, render_nsjail_rlimit_as, resolve_nsjail_timeout,
proto_str, resolve_nsjail_tmp_mount_block, start_child_process, OccupancyMetrics,
StreamNotifier, DEV_CONF_NSJAIL,
build_command_with_isolation, create_args_and_out_file, get_reserved_variables, proto_str,
read_file, read_result, render_nsjail_rlimit_as, render_nsjail_rlimit_fsize,
resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, start_child_process,
OccupancyMetrics, StreamNotifier, DEV_CONF_NSJAIL,
},
get_proxy_envs_for_lang, get_run_proxy_envs,
handle_child::handle_child,
is_sandboxing_enabled, nsjail_clone_newnet, read_ee_registry,
worker_utils::ping_job_status,
PyV, DISABLE_NUSER, HOME_ENV, INDEX_CERT, NATIVE_CERT, NSJAIL_AVAILABLE, NSJAIL_PATH,
NSJAIL_PY_RLIMIT_AS_MB, PATH_ENV, PIP_EXTRA_INDEX_URL, PIP_INDEX_URL, PROXY_ENVS,
PY_INSTALL_DIR, TRACING_PROXY_CA_CERT_PATH, TRUSTED_HOST, TZ_ENV, UV_CACHE_DIR,
NSJAIL_PY_RLIMIT_AS_MB, NSJAIL_RLIMIT_FSIZE_MB, PATH_ENV, PIP_EXTRA_INDEX_URL, PIP_INDEX_URL,
PROXY_ENVS, PY_INSTALL_DIR, TRACING_PROXY_CA_CERT_PATH, TRUSTED_HOST, TZ_ENV, UV_CACHE_DIR,
UV_EXCLUDE_NEWER, UV_HTTP_TIMEOUT, UV_INDEX_STRATEGY, UV_PYTHON_INSTALL_MIRROR,
};
use windmill_common::client::AuthedClient;
@@ -1173,6 +1173,10 @@ mount {{
"{RLIMIT_AS}",
&render_nsjail_rlimit_as(NSJAIL_PY_RLIMIT_AS_MB.as_deref(), 4096),
)
.replace(
"{RLIMIT_FSIZE}",
&render_nsjail_rlimit_fsize(NSJAIL_RLIMIT_FSIZE_MB.as_deref(), 1000),
)
.replace("{JOB_DIR}", job_dir)
.replace("{PY_INSTALL_DIR}", &*PY_INSTALL_DIR)
.replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string())
+6
View File
@@ -397,6 +397,12 @@ lazy_static::lazy_static! {
pub static ref NSJAIL_DBT_RLIMIT_AS_MB: Option<String> =
std::env::var("NSJAIL_DBT_RLIMIT_AS_MB").ok();
/// Override for the nsjail `rlimit_fsize` cap (largest single file a jailed
/// python3/ansible/dbt job may write). MiB, or `unlimited`/`none`/`inf`/`0` to
/// uncap. Unset keeps the historical 1000 MiB. See `render_nsjail_rlimit_fsize`.
pub static ref NSJAIL_RLIMIT_FSIZE_MB: Option<String> =
std::env::var("NSJAIL_RLIMIT_FSIZE_MB").ok();
// pub static ref DISABLE_NSJAIL: bool = false;
pub static ref DISABLE_NSJAIL: bool = std::env::var("DISABLE_NSJAIL")
.ok()
+1 -1
View File
@@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts";
import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts";
import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts";
export const VERSION = "v1.882.0";
export const VERSION = "v1.883.0";
export async function login(email: string, password: string): Promise<string> {
return await windmill.UserService.login({
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@windmill-labs/chat-sdk",
"version": "1.882.0",
"version": "1.883.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@windmill-labs/chat-sdk",
"version": "1.882.0",
"version": "1.883.0",
"license": "Apache-2.0",
"devDependencies": {
"@ai-sdk/react": "^4.0.102",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@windmill-labs/chat-sdk",
"description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app",
"version": "1.882.0",
"version": "1.883.0",
"author": "Ruben Fiszel",
"license": "Apache-2.0",
"homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme",
+107
View File
@@ -551,6 +551,106 @@ async function remove(_opts: GlobalOptions, name: string) {
await removeWorkspace(name, false, _opts);
}
const CLI_LOGIN_TOKEN_LABEL_PREFIX = "cli-login:";
// Only a token the CLI's own browser login minted is revoked: a token pasted into the profile may
// also be used elsewhere (CI, another machine), so deleting it could break more than this profile.
async function revokeCliLoginToken(token: string): Promise<boolean> {
const prefix = token.substring(0, 10);
const perPage = 100;
for (let page = 1; page <= 50; page++) {
const tokens = await wmill.listTokens({ excludeEphemeral: true, page, perPage });
const match = tokens.find((t) => t.token_prefix === prefix);
if (match) {
if (!match.label?.startsWith(CLI_LOGIN_TOKEN_LABEL_PREFIX)) {
return false;
}
await wmill.deleteToken({ tokenPrefix: prefix });
return true;
}
if (tokens.length < perPage) {
return false;
}
}
return false;
}
async function login(opts: GlobalOptions, workspaceName?: string) {
const workspace = workspaceName
? await getWorkspaceByName(workspaceName, opts.configDir)
: await getActiveWorkspace(opts);
if (!workspace) {
log.info(
colors.red.bold(
workspaceName
? `! Workspace profile ${workspaceName} does not exist locally`
: "! No active workspace profile. Add one with 'wmill workspace add'."
)
);
return process.exit(1);
}
if (
opts.baseUrl &&
new URL(opts.baseUrl).toString() !== new URL(workspace.remote).toString()
) {
log.info(
colors.red.bold(
`! --base-url ${opts.baseUrl} does not match profile ${workspace.name} (${workspace.remote}). Use 'wmill workspace add' for another instance.`
)
);
return process.exit(1);
}
let token = await tryGetLoginInfo(opts);
if (!token) {
if (!(process.stdin.isTTY ?? false)) {
log.info("Not a TTY, can't login interactively. Pass the token in --token");
return process.exit(1);
}
log.info(
`Signing in again to ${workspace.workspaceId} on ${workspace.remote} for profile ${workspace.name}`
);
token = await loginInteractive(workspace.remote);
}
if (!token) {
log.info(colors.red.bold("! Login failed, the profile was left unchanged."));
return process.exit(1);
}
const remote = workspace.remote.substring(0, workspace.remote.length - 1);
setClient(token, remote);
try {
await wmill.whoami({ workspace: workspace.workspaceId });
} catch (e) {
log.info(
colors.red.bold(
`! The new token cannot access workspace ${workspace.workspaceId}, the profile was left unchanged.`
)
);
throw e;
}
const oldToken = workspace.token;
await addWorkspace({ ...workspace, token }, opts);
// `wmill instance pull --include-workspaces` copies one token into the instance profile and
// every workspace profile it creates: revoking it would sign all the others out.
const { allInstances } = await import("../instance/instance.ts");
const stillReferenced =
(await allWorkspaces(opts.configDir)).some((w) => w.token === oldToken) ||
(await allInstances()).some((i) => i.token === oldToken);
if (oldToken && oldToken !== token && !stillReferenced) {
try {
if (await revokeCliLoginToken(oldToken)) {
log.info("Revoked the profile's previous token.");
}
} catch {
// Already expired or deleted, or owned by another user: nothing left to revoke.
}
}
log.info(colors.green.underline(`Successfully signed in again for profile ${workspace.name}`));
}
async function whoami(_opts: GlobalOptions) {
const whoamiInfo = await requireLogin(_opts);
log.info(JSON.stringify(whoamiInfo, null, 2));
@@ -937,6 +1037,13 @@ const command = new Command()
.description("Remove a workspace")
.arguments("<workspace_name:string>")
.action(remove as any)
.command("login")
.complete("workspace", async () => (await allWorkspaces()).map((x) => x.name))
.description(
"Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it."
)
.arguments("[workspace_name:string:workspace]")
.action(login as any)
.command("whoami")
.description("Show the currently active user")
.action(whoami as any)
+15 -7
View File
@@ -122,19 +122,27 @@ export async function requireLogin(
return process.exit(1);
}
log.infoStderr(
"! Could not reach API given existing credentials. Attempting to reauth..."
);
const isUnauthorized = error && typeof error === "object" &&
"name" in error && (error as { name: unknown }).name === "ApiError" &&
(error as { status?: number }).status === 401;
log.infoStderr(colors.yellow(
isUnauthorized
? `! The token of workspace profile '${workspace.name}' has expired or was revoked. Sign in again to continue.`
: "! Could not reach API given existing credentials. Attempting to reauth..."
));
const newToken = await loginInteractive(workspace.remote);
if (!newToken) {
throw new Error("Unauthorized: Could not authenticate with the provided credentials");
throw new Error(
`Unauthorized: Could not authenticate with the provided credentials. Run 'wmill workspace login ${workspace.name}' in a terminal to sign in again.`
);
}
// Update workspace token
// Removed silently first: `addWorkspace` logs the update to stdout, which would land in the
// output of the command being run (e.g. `wmill variable get … > file`).
const { removeWorkspace, addWorkspace } = await import("../commands/workspace/workspace.ts");
removeWorkspace(workspace.name, false, opts);
await removeWorkspace(workspace.name, true, opts);
workspace.token = newToken;
addWorkspace(workspace, opts);
await addWorkspace(workspace, opts);
setClient(
newToken,
+1 -1
View File
@@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork";
// (e.g. utils.ts) can read it without importing main.ts and creating a circular
// dependency (main → workspace → utils → main) that triggers a TDZ.
// Re-exported from main.ts for backwards compatibility.
export const VERSION = "1.882.0";
export const VERSION = "1.883.0";
+1 -1
View File
@@ -97,7 +97,7 @@ export async function browserLogin(
// Start the server
server.listen(port, () => {
console.log(`Listening on port ${port}`);
log.infoStderr(`Listening on port ${port}`);
});
});
}
+4
View File
@@ -27,6 +27,7 @@ export interface ErrorHandlerConfig {
extra_args?: any;
muted_on_cancel?: boolean;
muted_on_user_path?: boolean;
muted_on_ui_runs?: boolean;
}
export interface SuccessHandlerConfig {
@@ -254,6 +255,9 @@ export async function pushWorkspaceSettings(
for (const key of SETTINGS_MANAGED_ONLY_WHEN_PRESENT) {
delete (localSettings as any)[key];
}
// Such a server reads an error handler body carrying this key as the legacy format, which
// clears the handler.
delete localSettings.error_handler?.muted_on_ui_runs;
const webhookUnreadable = unreadableSecret(localSettings.webhook);
if (webhookUnreadable) {
log.warn(
+2 -1
View File
@@ -8651,7 +8651,7 @@ write a secret you were not given: keep the placeholder.
| Key | Value |
|---|---|
| \`auto_invite\` | \`{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }\`. The instance groups are managed only when \`instance_groups\` is stated; clearing a group removes the members it added. |
| \`error_handler\` / \`success_handler\` | \`{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }\`, \`path\` being \`script/<path>\` or \`flow/<path>\`. |
| \`error_handler\` / \`success_handler\` | \`{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }\`, \`path\` being \`script/<path>\` or \`flow/<path>\`. \`muted_on_ui_runs\` (error handler only) skips jobs started from the UI. |
| \`error_handler_fallback_to_instance_alerts\` | Report failures to the instance critical alert channels when no error handler is set. |
| \`webhook\` | URL POSTed a JSON event on every change to the workspace's items. |
| \`ai_config\` | Providers, default and completion models, custom prompts, \`copilot_disabled\`. |
@@ -9703,6 +9703,7 @@ workspace related commands
- \`--create-workspace-name <workspace_name:string>\` - Specify the workspace name. Ignored if --create is not specified or the workspace already exists. Will default to the workspace id.
- \`--create-username <username:string>\` - Specify your own username in the newly created workspace. Ignored if --create is not specified, the workspace already exists or automatic username creation is enabled on the instance.
- \`workspace remove <workspace_name:string>\` - Remove a workspace
- \`workspace login [workspace_name:string:workspace]\` - Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it.
- \`workspace whoami\` - Show the currently active user
- \`workspace list\` - List local workspace profiles
- \`workspace list-remote\` - List workspaces on the remote server that you have access to
+3 -3
View File
@@ -284,11 +284,11 @@ export function inferContentTypeFromFilePath(
): ScriptLanguage {
if (contentPath.endsWith(".py")) {
return "python3";
} else if (contentPath.endsWith("fetch.ts")) {
} else if (contentPath.endsWith(".fetch.ts")) {
return "nativets";
} else if (contentPath.endsWith("bun.ts")) {
} else if (contentPath.endsWith(".bun.ts")) {
return "bun";
} else if (contentPath.endsWith("deno.ts")) {
} else if (contentPath.endsWith(".deno.ts")) {
return "deno";
} else if (contentPath.endsWith(".ts")) {
return defaultTs ?? "bun";
+7
View File
@@ -391,6 +391,13 @@ describe("inferContentTypeFromFilePath", () => {
expect(inferContentTypeFromFilePath("script.fetch.ts", "bun")).toBe("nativets");
});
test("language suffix needs its dot", () => {
expect(inferContentTypeFromFilePath("f/a/a_fetch.ts", "bun")).toBe("bun");
expect(inferContentTypeFromFilePath("f/a/afetch.ts", "bun")).toBe("bun");
expect(inferContentTypeFromFilePath("f/a/a_bun.ts", "deno")).toBe("deno");
expect(inferContentTypeFromFilePath("f/a/a_deno.ts", "bun")).toBe("bun");
});
test("detects SQL variants", () => {
expect(inferContentTypeFromFilePath("query.pg.sql", undefined)).toBe("postgresql");
expect(inferContentTypeFromFilePath("query.my.sql", undefined)).toBe("mysql");
+8 -5
View File
@@ -37,11 +37,14 @@ Symbols, not line numbers, are cited: they drift less.
so until `whoami` answers that browser still renders as its own last user.
- **`tokens/impersonate`** (superadmin) returns a multi-use token and sets no cookie.
- **`max_token_expiration_days`** caps `POST /users/tokens/create` and `tokens/impersonate`, by
shortening the stored expiration (`cap_token_expiration`), never by refusing: the CLI
authorization page, `wmill user create-token` and the editor's language-server token all pick a
lifetime without reading the setting, and CLIs already installed never will. The CLI signs in
again on its own when its token expires, which is why the authorization page labels it
`cli-login:<username>`, reserved in `is_user_token` so its expiry does not email the user. A token
shortening the stored expiration (`cap_token_expiration`), never by refusing: `wmill user
create-token` and the editor's language-server token pick a lifetime without reading the
setting, and CLIs already installed never will. The CLI authorization page (`/user/cli`) reads
it only to offer the lifetimes that would be kept (30 days by default). The CLI signs in again
on its own when its token expires, which is why the authorization page labels it
`cli-login:<username>`, reserved in `is_user_token` so its expiry does not email the user.
`wmill workspace login` replaces a profile's token before it expires, and revokes the previous
one only when that label shows the browser login minted it. A token
owned by a service account is exempt: one in the workspace the token names, or in any workspace
for a workspace-less token (for `tokens/impersonate`, the impersonated account). Any workspace
admin can therefore create and impersonate a service account to hold an uncapped token, so the
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@windmill-labs/components",
"version": "1.882.0",
"version": "1.883.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@windmill-labs/components",
"version": "1.882.0",
"version": "1.883.0",
"hasInstallScript": true,
"license": "AGPL-3.0",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@windmill-labs/components",
"version": "1.882.0",
"version": "1.883.0",
"scripts": {
"dev": "vite dev",
"dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev",
+12
View File
@@ -23,11 +23,13 @@ import {
isWebSearchEnabledForProvider,
setCopilotInfo,
copilotInfo,
copilotSessionModel,
copilotWorkspace,
getWorkspaceCopilotInfo,
invalidateWorkspaceCopilotInfo,
loadWorkspaceCopilotInfo,
applySavedWorkspaceCopilotInfo,
tryResolveModelFor,
workspaceCopilotInfoFailed
} from './aiStore'
@@ -157,3 +159,13 @@ describe('setCopilotInfo legacy /thinking migration', () => {
expect(isWebSearchEnabledForProvider('anthropic')).toBe(true)
})
})
it("keeps a model pick the tab's workspace does not offer, without sending it there", () => {
const pick = { provider: 'anthropic', model: 'fork-only' } as const
copilotSessionModel.set(pick)
setCopilotInfo(withModel('parent'))
expect(get(copilotSessionModel)).toEqual(pick)
expect(tryResolveModelFor(get(copilotInfo))?.model).toBe('parent')
copilotSessionModel.set(undefined)
})
+19 -18
View File
@@ -2,6 +2,7 @@
// client (`components/copilot/lib`) or anything under `components/copilot/chat` — those
// import aiStore back, and such a cycle crashes the app once the bundler splits it across
// chunks (docs/frontend-import-cycles.md; the build fails on the chunk cycle, not on this).
import { untrack } from 'svelte'
import { writable, get } from 'svelte/store'
import { SvelteMap, SvelteSet } from 'svelte/reactivity'
import {
@@ -125,9 +126,8 @@ function dedupeModels(models: AIProviderModel[]): AIProviderModel[] {
})
}
// The workspace copilotInfo currently reflects. A session send awaits this
// matching its committed workspace so getCurrentModel() can't read the previous
// workspace's provider/model while the scoped load is still in flight.
// The workspace copilotInfo currently reflects: the page's, which an AI session's may not be.
// Session code must not point them at its own workspace.
export const copilotWorkspace = writable<string | undefined>(undefined)
function buildCopilotInfo(aiConfig: AIConfig, userDisabled: boolean): CopilotInfo {
@@ -240,12 +240,20 @@ export function workspaceCopilotInfoFailed(workspace: string): boolean {
return failedWorkspaceCopilotInfos.has(workspace)
}
/** `workspace`'s AI config for a request made on its behalf, without touching the tab's.
// The tab's copy follows only when it describes this workspace: a session's may be another.
function keepWorkspaceCopilotInfo(workspace: string, info: CopilotInfo) {
workspaceCopilotInfos.set(workspace, info)
failedWorkspaceCopilotInfos.delete(workspace)
if (get(copilotWorkspace) === workspace) copilotInfo.set(info)
}
/** `workspace`'s AI config for a request made on its behalf, whatever workspace the tab's is.
* Fetched once and kept until invalidated. `fresh` refetches a config that may have changed
* elsewhere: unlike after a save, the one held stays readable until the new one lands, so what
* shows it does not blank meanwhile, and a load already in flight is as fresh and is shared. */
export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Promise<CopilotInfo> {
const known = workspaceCopilotInfos.get(workspace)
// Untracked: an effect that refreshes would otherwise rerun on its own refresh, forever.
const known = untrack(() => workspaceCopilotInfos.get(workspace))
if (known && !fresh) return Promise.resolve(known)
let load = workspaceLoads.get(workspace)
if (!load) {
@@ -256,8 +264,7 @@ export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Prom
.then((config) => {
if (version !== versionOf(workspace)) return loadWorkspaceCopilotInfo(workspace)
const info = buildCopilotInfo(config, get(aiUserDisabled))
workspaceCopilotInfos.set(workspace, info)
failedWorkspaceCopilotInfos.delete(workspace)
keepWorkspaceCopilotInfo(workspace, info)
return info
})
.catch((e) => {
@@ -271,14 +278,11 @@ export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Prom
/** After a save of `workspace`'s AI config, with the effective config the save returned: what
* shows it keeps a config throughout, where invalidating would blank it until the refetch. A load
* started before the save still refetches. Also updates the tab's copy, but only when the tab is
* on `workspace`: it belongs to the workspace on screen, which a session's may not be. */
* started before the save still refetches. */
export function applySavedWorkspaceCopilotInfo(workspace: string, aiConfig: AIConfig) {
const info = buildCopilotInfo(aiConfig, get(aiUserDisabled))
workspaceVersions.set(workspace, (workspaceVersions.get(workspace) ?? 0) + 1)
workspaceCopilotInfos.set(workspace, info)
failedWorkspaceCopilotInfos.delete(workspace)
if (get(copilotWorkspace) === workspace) applyCopilotInfo(info)
keepWorkspaceCopilotInfo(workspace, info)
}
/** After a save of `workspace`'s AI config, or with none of a config every workspace inherits
@@ -293,13 +297,10 @@ export function invalidateWorkspaceCopilotInfo(workspace?: string) {
}
}
// Leaves copilotSessionModel alone: the pick is shared with sessions in other workspaces, which may
// offer a model this one does not.
export function setCopilotInfo(aiConfig: AIConfig) {
applyCopilotInfo(buildCopilotInfo(aiConfig, get(aiUserDisabled)))
}
export function applyCopilotInfo(info: CopilotInfo) {
copilotSessionModel.update((model) => (model && isOffered(info, model) ? model : undefined))
copilotInfo.set(info)
copilotInfo.set(buildCopilotInfo(aiConfig, get(aiUserDisabled)))
}
function isOffered(info: CopilotInfo, model: AIProviderModel): boolean {
@@ -7,7 +7,7 @@
import TestConnection from './TestConnection.svelte'
import TestAiKey from './copilot/TestAIKey.svelte'
import { aiResourceProvider } from './copilot/aiResourceProvider'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './copilot/chat/aiChatManagerContext'
import Popover from './meltComponents/Popover.svelte'
import Button from './common/button/Button.svelte'
import { Loader2 } from 'lucide-svelte'
@@ -60,6 +60,8 @@
onSynced = undefined
}: Props = $props()
const aiChat = getAiChatManager()
let aiProvider = $derived(aiResourceProvider(resourceType, args))
let schema = $state(emptySchema())
@@ -225,7 +227,7 @@
{aiProvider}
workspace={workspace ?? $operatingWorkspace}
resourceValue={args}
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
model={aiChat.aiInfo?.aiModels.find((m) => m.provider === aiProvider)?.model}
/>
{/if}
{#if resourceType == 'postgresql'}
@@ -29,6 +29,8 @@
let disabled = $state(false)
let isGoogleSignin = $state(false)
let manual = $state(true)
let actionLabel: string | undefined = $state(undefined)
let canGoBack: boolean | undefined = $state(undefined)
let appConnectInner: AppConnectInner | undefined = $state(undefined)
@@ -96,6 +98,8 @@
bind:isGoogleSignin
bind:disabled
bind:manual
bind:actionLabel
bind:canGoBack
on:close={drawer?.closeDrawer}
on:refresh
express={expressOAuthSetup}
@@ -105,9 +109,7 @@
/>
{#snippet actions()}
<div class="flex gap-1">
<!-- Only when the user came through the type picker: opening the drawer for one
resource type skips step 1, so Back would land on a list they never chose from. -->
{#if step > 1 && !rtToLoad}
{#if canGoBack}
<Button variant="default" unifiedSize="md" onClick={() => appConnectInner?.back()}>
Back
</Button>
@@ -121,13 +123,7 @@
{disabled}
onClick={() => appConnectInner?.next()}
>
{#if (step == 2 && !manual) || native}
Connect
{:else if step == 1}
Next
{:else}
Save
{/if}
{actionLabel ?? 'Next'}
</Button>
{/if}
</div>
File diff suppressed because it is too large Load Diff
@@ -18,6 +18,8 @@
let disabled = $state(false)
let manual = $state(true)
let isGoogleSignin = $state(false)
let actionLabel: string | undefined = $state(undefined)
let canGoBack: boolean | undefined = $state(undefined)
let appConnect: AppConnectInner | undefined = $state(undefined)
@@ -42,7 +44,7 @@
{#if !express}
<div class="flex flex-row-reverse w-full pb-2 shrink-0">
<div class="flex gap-2">
{#if step > 2}
{#if canGoBack}
<Button variant="default" unifiedSize="md" onClick={() => appConnect?.back()}>
Back
</Button>
@@ -52,13 +54,7 @@
<GoogleSigninButton {disabled} onClick={() => appConnect?.next()} />
{:else}
<Button variant="accent" unifiedSize="md" {disabled} onClick={() => appConnect?.next()}>
{#if step == 2 && !manual}
Connect
{:else if step == 1}
Next
{:else}
Save
{/if}
{actionLabel ?? 'Next'}
</Button>
{/if}
</div>
@@ -73,6 +69,8 @@
bind:disabled
bind:manual
bind:isGoogleSignin
bind:actionLabel
bind:canGoBack
on:error
on:refresh
/>
+16 -4
View File
@@ -15,7 +15,9 @@
import type { Script } from '$lib/gen'
import Select from './select/Select.svelte'
import type { DiffAiReview, DiffVersionOption } from './diff_drawer'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import type { AIChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte'
import { untrack } from 'svelte'
import AiReview from './deploymentRequest/AiReview.svelte'
import type { ReviewScope } from './deploymentRequest/aiReview'
@@ -61,9 +63,15 @@
interface Props {
restoreDeployed?: () => Promise<void>
isFlow?: boolean
/** The session's chat manager, for a session editor view that mounts this drawer outside
* the session's context. */
aiChat?: AIChatManager
}
let { restoreDeployed = undefined, isFlow = false }: Props = $props()
let { restoreDeployed = undefined, isFlow = false, aiChat: sessionChat }: Props = $props()
const aiChat = untrack(() => sessionChat) ?? getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let data:
| {
@@ -386,11 +394,15 @@
<Drawer bind:this={diffViewer} size="1200px" on:close>
<DrawerContent title="Diff" on:close={diffViewer.closeDrawer}>
<div class="flex flex-col gap-4 h-full">
{#if data && aiReviewScope && $copilotInfo.enabled}
{#if data && aiReviewScope && aiInfo?.enabled}
<div class="max-h-[40vh] overflow-y-auto shrink-0">
<!-- A new diff is a new review: a result never carries over to it. -->
{#key aiReviewScope}
<AiReview scope={aiReviewScope} source="draft_diff" />
<AiReview
scope={aiReviewScope}
source="draft_diff"
info={aiChat.loadedSessionAiTarget?.info}
/>
{/key}
</div>
{/if}
@@ -498,7 +498,8 @@
.filter((o) => {
if (selectedValues.includes(o.value)) return false
if (!searchSuffix) return true
return o.value.includes(searchSuffix)
const q = searchSuffix.toLowerCase()
return [o.value, o.label].some((t) => t?.toLowerCase().includes(q))
})
.map((option) => ({
type: 'option' as const,
@@ -14,6 +14,8 @@
import { publishLinkedAgentTools } from './flows/flowState'
import { linkedToolsScope } from './flows/linkedAgentToolsStore.svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import type { ExpandedSubflow } from './graph/graphBuilder.svelte'
import { resolveLoadedExpandedSubflowStep } from './flows/expandedSubflowStep'
const operatingWorkspace = useOperatingWorkspace()
@@ -31,6 +33,8 @@
noGraph?: boolean
triggerNode?: boolean
stepDetail?: FlowModule | string | undefined
/** Subflows crossed to reach `stepDetail`, set when it is inside an expanded subflow. */
subflowPathChain?: string[]
workspace?: string | undefined
minHeight?: number
noBorder?: boolean
@@ -50,6 +54,7 @@
noGraph = false,
triggerNode = false,
stepDetail = $bindable(undefined),
subflowPathChain = $bindable(),
workspace = $operatingWorkspace,
minHeight = 400,
noBorder = false,
@@ -60,6 +65,7 @@
}: Props = $props()
let availableHeight = $state(0)
let expandedSubflows: Record<string, ExpandedSubflow> = $state({})
if (provideTriggerContext && !hasContext('TriggerContext')) {
const triggersCount = writable<TriggersCount | undefined>(undefined)
@@ -136,7 +142,9 @@
preprocessorModule={flow?.value?.preprocessor_module}
notes={flow?.value?.notes}
groups={flow?.value?.groups}
bind:expandedSubflows
onSelect={(nodeId) => {
subflowPathChain = undefined
if (nodeId === 'Trigger') {
dispatch('triggerDetail')
return
@@ -144,6 +152,14 @@
stepDetail = flow?.value?.failure_module
} else if (nodeId === 'preprocessor') {
stepDetail = flow?.value?.preprocessor_module
} else if (typeof nodeId === 'string' && nodeId.startsWith('subflow:')) {
const resolved = resolveLoadedExpandedSubflowStep(
nodeId,
flow?.value?.modules ?? [],
expandedSubflows
)
stepDetail = resolved?.module
subflowPathChain = resolved?.pathChain
} else {
stepDetail = dfs(flow?.value?.modules ?? [], (m) => m).find((m) => m?.id === nodeId)
}
@@ -162,7 +178,13 @@
noGraph ? 'border-0 w-max' : ''
)}
>
<FlowGraphViewerStep schema={flow?.schema} {stepDetail} {hideDefaultInputs} {workspace} />
<FlowGraphViewerStep
schema={flow?.schema}
{stepDetail}
{subflowPathChain}
{hideDefaultInputs}
{workspace}
/>
</div>
{/if}
</div>
@@ -1,7 +1,7 @@
<script lang="ts">
import HighlightCode from './HighlightCode.svelte'
import InputTransformsViewer from './InputTransformsViewer.svelte'
import IconedPath from './IconedPath.svelte'
import FlowModuleIcon from './flows/FlowModuleIcon.svelte'
import type { FlowModule } from '$lib/gen'
import { Badge, Button, Drawer, DrawerContent } from './common'
import { Link } from 'lucide-svelte'
@@ -10,13 +10,13 @@
import typescript from 'svelte-highlight/languages/typescript'
import FlowPathViewer from './flows/content/FlowPathViewer.svelte'
import SchemaViewer from './SchemaViewer.svelte'
import { scriptPathToHref } from '$lib/scripts'
import { cleanExpr, copyToClipboard } from '$lib/utils'
import { flowPathToHref, scriptPathToHref } from '$lib/scripts'
import { cleanExpr } from '$lib/utils'
import { hubBaseUrlStore } from '$lib/stores'
import { twMerge } from 'tailwind-merge'
import FlowModuleScript from './flows/content/FlowModuleScript.svelte'
import { Copy, Expand } from 'lucide-svelte'
import { ChevronRight, Expand, ExternalLink } from 'lucide-svelte'
import HighlightTheme from './HighlightTheme.svelte'
import LanguageIcon from './common/languageIcons/LanguageIcon.svelte'
import FlowGraphViewerStepHeader from './FlowGraphViewerStepHeader.svelte'
@@ -34,6 +34,9 @@
workspace?: string
/** Given, the step header starts with a back control that calls it. */
onBack?: () => void
/** For a step inside an inline-expanded subflow: path of each subflow crossed, outermost
* first. */
subflowPathChain?: string[]
}
let {
@@ -42,27 +45,43 @@
jobScriptHash = undefined,
hideDefaultInputs = false,
workspace = undefined,
onBack = undefined
onBack = undefined,
subflowPathChain = undefined
}: Props = $props()
let ws = $derived(workspace ?? $operatingWorkspace)
function flowHref(path: string): string {
return path.startsWith('hub/')
? flowPathToHref(path)
: `/flows/get/${path}?workspace=${encodeURIComponent(ws ?? '')}`
}
let codeViewer: Drawer | undefined = $state()
</script>
<HighlightTheme />
{#snippet pathLink(href: string, module: FlowModule, path: string)}
<a
rel="noreferrer"
target="_blank"
{href}
class="inline-flex min-w-0 items-center gap-1.5 text-xs text-accent hover:underline"
>
<FlowModuleIcon {module} size={14} />
<span class="truncate">{path}</span>
<ExternalLink size={12} class="shrink-0" />
</a>
{/snippet}
<Drawer bind:this={codeViewer} size="900px">
<DrawerContent title={'Expanded Code'} on:close={codeViewer?.closeDrawer}>
{#if stepDetail && typeof stepDetail != 'string'}
{#if stepDetail.value.type == 'script'}
<div class="mb-4">
<a
rel="noreferrer"
target="_blank"
href={scriptPathToHref(stepDetail?.value?.path ?? '', $hubBaseUrlStore)}
class=""
>
<IconedPath path={stepDetail?.value?.path ?? ''} />
</a>
{@render pathLink(
scriptPathToHref(stepDetail.value.path, $hubBaseUrlStore),
stepDetail,
stepDetail.value.path
)}
</div>
<div class="text-xs mb-4 mt-2">
<h3 class="mb-1 text-xs font-semibold text-emphasis">Step inputs</h3>
@@ -124,17 +143,30 @@
<!-- A direct child of the scrolling root: a sticky row can only hold within its parent's
box, so wrapped with the path link below it would scroll away with that wrapper. -->
<FlowGraphViewerStepHeader {stepDetail} {onBack} />
{#if subflowPathChain?.length}
<div class="flex flex-wrap items-center gap-1 pb-2 text-xs text-secondary">
<span>In</span>
{#each subflowPathChain as path, i (i)}
{#if i > 0}
<ChevronRight size={12} class="shrink-0" />
{/if}
<a
class="text-accent hover:underline"
href={flowHref(path)}
target="_blank"
rel="noreferrer">{path}</a
>
{/each}
</div>
{/if}
<div class="">
{#if stepDetail.value.type == 'script'}
<div class="pb-2">
<a
rel="noreferrer"
target="_blank"
href={scriptPathToHref(stepDetail?.value?.path ?? '', $hubBaseUrlStore)}
class=""
>
<IconedPath path={stepDetail?.value?.path ?? ''} />
</a>
{@render pathLink(
scriptPathToHref(stepDetail.value.path, $hubBaseUrlStore),
stepDetail,
stepDetail.value.path
)}
</div>
{/if}
</div>
@@ -280,25 +312,8 @@
{/each}
</div>
{:else if stepDetail.value.type == 'flow'}
<div class="text-sm mb-1 flex justify-between flex-row items-center">
<span class="text-xs font-normal text-secondary"
>Flow path: <span class="text-emphasis">{stepDetail.value.path}</span>
</span>
<Button
unifiedSize="sm"
startIcon={{ icon: Copy }}
variant="subtle"
on:click={() => {
if (typeof stepDetail !== 'string') {
const val = stepDetail?.value
if (val?.type == 'flow') {
copyToClipboard(val.path)
}
}
}}
>
Copy path
</Button>
<div class="pb-2">
{@render pathLink(flowHref(stepDetail.value.path), stepDetail, stepDetail.value.path)}
</div>
<FlowPathViewer noSide path={stepDetail.value.path} />
{/if}
@@ -39,6 +39,7 @@
import { deepEqual } from 'fast-equals'
import FlowTimeline from './FlowTimeline.svelte'
import { dfs } from './flows/dfs'
import { resolveLoadedExpandedSubflowStep } from './flows/expandedSubflowStep'
import { dfs as dfsPreviousResults } from '$lib/components/flows/previousResults'
import Alert from './common/alert/Alert.svelte'
import FlowGraphViewerStep from './FlowGraphViewerStep.svelte'
@@ -1363,6 +1364,7 @@
let flowTimeline: FlowTimeline | undefined = $state()
let stepDetail: FlowModule | string | undefined = $state(undefined)
let subflowPathChain: string[] | undefined = $state(undefined)
let storedListJobs: Record<number, Job> = $state({})
@@ -2192,6 +2194,7 @@
runDone={job?.type === 'CompletedJob'}
bind:expandedSubflows
onSelect={(e) => {
subflowPathChain = undefined
if (rightColumnSelect != 'node_definition' && rightColumnSelect != 'tracing') {
rightColumnSelect = 'node_status'
}
@@ -2204,10 +2207,15 @@
stepDetail = 'end'
} else {
const id = e.startsWith(AI_TOOL_CALL_PREFIX) ? e.split('-').pop() : e
const mod = dfs(job?.raw_flow?.modules ?? [], (m) => m).find(
(m) => m?.id === id
const resolved = resolveLoadedExpandedSubflowStep(
e,
job?.raw_flow?.modules ?? [],
expandedSubflows ?? {}
)
stepDetail = mod
stepDetail =
resolved?.module ??
dfs(job?.raw_flow?.modules ?? [], (m) => m).find((m) => m?.id === id)
subflowPathChain = resolved?.pathChain
selectedNode = e
if (e.startsWith(AI_TOOL_CALL_PREFIX)) {
const [_prefix, agentModuleId, j, _toolModuleId] = e.split('-')
@@ -2518,7 +2526,11 @@
</div>
{:else if rightColumnSelect == 'node_definition'}
{@const node = selectedNode ? localModuleStates[selectedNode] : undefined}
<FlowGraphViewerStep {stepDetail} jobScriptHash={node?.script_hash} />
<FlowGraphViewerStep
{stepDetail}
{subflowPathChain}
jobScriptHash={node?.script_hash}
/>
{:else if rightColumnSelect == 'user_states'}
<div class="p-2">
<JobArgs argLabel="Key" args={job?.flow_status?.user_states ?? {}} />
@@ -195,8 +195,8 @@
)
const instanceConnects = $derived(new Set(oauthConnects.current ?? []))
/**
* Matches what the dialog itself decides (`AppConnectInner.open`: `manual = !inConnects &&
* !registryCcCapable()`). An instance client is the usual route, but a provider the
* The types worth offering Connect for: an instance OAuth entry, or a provider the
* registry marks client-credentials-capable. An instance client is the usual route, but a provider the
* registry marks client-credentials-capable is connectable without one, because those
* credentials are entered per resource rather than held by a superadmin. Test only the
* first half and Connect disappears on the eight such providers, where it would work.
@@ -17,7 +17,7 @@
import TestConnection from './TestConnection.svelte'
import TestAiKey from './copilot/TestAIKey.svelte'
import { aiResourceProvider, isTokenVertexResource } from './copilot/aiResourceProvider'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './copilot/chat/aiChatManagerContext'
import GfmMarkdown from './GfmMarkdown.svelte'
import TestTriggerConnection from './triggers/TestTriggerConnection.svelte'
import GitHubAppIntegration from './GitHubAppIntegration.svelte'
@@ -94,6 +94,8 @@
onCredentialStored
}: Props = $props()
const aiChat = getAiChatManager()
let ws = $derived(workspace ?? $operatingWorkspace)
let aiProvider = $derived(aiResourceProvider(resource_type, args))
@@ -325,7 +327,7 @@
{aiProvider}
workspace={ws}
resourceValue={args}
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
model={aiChat.aiInfo?.aiModels.find((m) => m.provider === aiProvider)?.model}
/>
{/if}
{#if resource_type === 'git_repository' && ws && (actingUser?.is_admin || actingUser?.is_super_admin)}
@@ -1,6 +1,6 @@
<script lang="ts">
import { Pane, Splitpanes } from 'svelte-splitpanes'
import { emptyString } from '$lib/utils'
import { displayDate, emptyString } from '$lib/utils'
import { ScriptService, type ScriptHistory } from '$lib/gen'
import { Skeleton } from '$lib/components/common'
import FlowModuleScript from './flows/content/FlowModuleScript.svelte'
@@ -59,6 +59,10 @@
loadVersions()
function versionMeta(version: ScriptHistory): string {
return [version.created_by, displayDate(version.created_at)].filter(Boolean).join(' · ')
}
let showDiff: boolean = $state(false)
let previousHash: string | undefined = $state()
</script>
@@ -93,9 +97,14 @@
deploymentMsgUpdateMode = false
}}
>
<span class="text-xs truncate">
{#if emptyString(version.deployment_msg)}Version {version.script_hash}{:else}{version.deployment_msg}{/if}
</span>
<div class="flex flex-col gap-0.5 truncate">
<span class="text-xs truncate">
{#if emptyString(version.deployment_msg)}Version {version.script_hash}{:else}{version.deployment_msg}{/if}
</span>
<span class="text-2xs text-tertiary truncate" title={versionMeta(version)}>
{versionMeta(version)}
</span>
</div>
{#snippet action()}
{#if openDetails}
<Button
@@ -109,10 +109,9 @@
<AIUserSettings />
</div>
</div>
<!-- Keyed on the workspace `copilotInfo` reflects, not on `$workspaceStore`:
a session acting on another workspace loads that workspace's AI config
while navigation stays put, and pricing usage from one workspace with
another's rates would silently misstate it. -->
<!-- Keyed on the workspace `copilotInfo` reflects, not on `$workspaceStore`,
which is ahead of it while a switch loads: pricing usage from one
workspace with another's rates would silently misstate it. -->
{#if $copilotWorkspace}
<AiUsagePanel
workspace={$copilotWorkspace}
@@ -25,6 +25,9 @@
menuItems = undefined,
disableTitle = false,
forkableWorkspaces,
onClick = undefined,
compact = false,
stagedDev = undefined,
class: className = ''
}: {
workspaceId?: string
@@ -61,6 +64,12 @@
// resolves its name/family for a workspace absent from `$userWorkspaces`.
// Omitted consumers fall back to the member-only list.
forkableWorkspaces?: UserWorkspace[]
// For a chip that is not a dropdown's trigger, such as Home's staged fork.
onClick?: () => void
// Fork icon, fork name and chevron only: no parent segment, "(new)" or the base's dev badge.
compact?: boolean
// A staged fork that will be created as a dev workspace: the compact chip shows its badge.
stagedDev?: { label?: string }
class?: string
} = $props()
@@ -76,7 +85,7 @@
)
// The parent segment only appears for a fork of a fork — forking off the
// root is the default and doesn't need spelling out.
const shownParent = $derived(parentId !== root?.id ? parentName : undefined)
const shownParent = $derived(!compact && parentId !== root?.id ? parentName : undefined)
// A fork with a workspace color re-themes the whole chip: forkAccentStyle
// derives light/dark bg+text at that hue (matching the default blue's
@@ -115,6 +124,7 @@
<Button
variant="subtle"
unifiedSize="xs"
{onClick}
title={disableTitle ? undefined : showFork && shownParent ? `${shownParent} → ${name}` : name}
tabindex={interactive ? undefined : -1}
style={accentStyle ?? ''}
@@ -168,9 +178,16 @@
{showFork ? name : (rootLabel ?? name)}
</span>
{/if}
{#if pendingFork}
{#if compact && stagedDev}
<DevWorkspaceBadge
label={stagedDev.label}
{color}
fallbackClass="dark:bg-surface-accent-primary text-white dark:text-white"
class="text-3xs px-1 py-0"
/>
{:else if pendingFork && !compact}
<span class="shrink-0 opacity-70 font-normal">(new)</span>
{:else if currentWs?.is_dev_workspace}
{:else if currentWs?.is_dev_workspace && !compact}
<DevWorkspaceBadge
label={currentWs.dev_workspace_label}
color={color ?? (pendingFork ? undefined : currentWs.color)}
@@ -69,8 +69,9 @@
function handleDefault(defaultValue: string | undefined) {
value = defaultValue
if (value) {
const date = parseISO(value)
const date = value ? parseISO(value) : undefined
// A default that is not a date yet (one being typed in a linked input) leaves the selects as they are.
if (date && !isNaN(date.getTime())) {
const locale = getLocale(resolvedConfig.locale)
selectedDay = String(date.getDate())
selectedMonth = formatDateFns(date, 'MMMM', { locale })
@@ -198,7 +199,7 @@
}
$effect.pre(() => {
resolvedConfig.defaultValue
untrack(() => !value && handleDefault(resolvedConfig.defaultValue))
untrack(() => handleDefault(resolvedConfig.defaultValue))
})
let monthItems = $derived(computeMonthItems(resolvedConfig?.locale))
$effect.pre(() => {
@@ -115,6 +115,7 @@
const r = formatDate(value, resolvedConfig.outputFormat)
outputs?.result.set(r)
const valueDate = new Date(value)
let isValid = true
if (resolvedConfig.minDateTime) {
const minDate = new Date(resolvedConfig.minDateTime)
@@ -123,11 +124,11 @@
minDate.getMonth() === valueDate.getMonth() &&
minDate.getFullYear() === valueDate.getFullYear()
) {
outputs?.validity.set(minDate.getTime() < valueDate.getTime())
isValid &&= minDate.getTime() < valueDate.getTime()
}
if (minDate.getTime() > valueDate.getTime()) {
outputs?.validity.set(false)
isValid = false
}
}
@@ -139,13 +140,14 @@
maxDate.getMonth() === valueDate.getMonth() &&
maxDate.getFullYear() === valueDate.getFullYear()
) {
outputs?.validity.set(maxDate.getTime() > valueDate.getTime())
isValid &&= maxDate.getTime() > valueDate.getTime()
}
if (maxDate.getTime() < valueDate.getTime()) {
outputs?.validity.set(false)
isValid = false
}
}
outputs?.validity.set(isValid)
untrack(() => setIterValue(value))
} else {
outputs?.result.set(undefined)
@@ -67,7 +67,7 @@
let css = $state(initCss($app.css?.timeinputcomponent, untrack(() => customCss)))
$effect.pre(() => {
resolvedConfig.defaultValue
!value && untrack(() => handleDefault(resolvedConfig.defaultValue))
untrack(() => handleDefault(resolvedConfig.defaultValue))
})
$effect.pre(() => {
if (value) {
@@ -102,6 +102,9 @@
// At the end, set the validity
outputs?.validity.set(isValid)
} else {
outputs?.result.set(undefined)
outputs?.validity.set(true)
}
fireOnChange()
})
@@ -4,7 +4,7 @@
import { slide } from 'svelte/transition'
import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { logFeatureUsage } from '$lib/utils/featureUsage'
interface Props {
@@ -19,6 +19,9 @@
const { onEditInstructions, instructions, runnableType, path }: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
const operatingWorkspace = useOperatingWorkspace()
let expanded = $state(false)
@@ -46,7 +49,7 @@
<OpenInSessionButton source={sessionSource} btnProps={{ unifiedSize }} deferToHeader />
{/snippet}
{#if $copilotInfo.workspaceDisabled}
{#if !aiInfo || aiInfo.workspaceDisabled}
<!-- The workspace hid the assistant. -->
{:else if instructions}
<div class="my-2 flex flex-col gap-1">
@@ -1,7 +1,7 @@
<script lang="ts">
import TextInput from '../text_input/TextInput.svelte'
import SettingToggle from '../itemSettings/SettingToggle.svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
interface Props {
prompt?: string | undefined
@@ -10,12 +10,15 @@
let { prompt = $bindable(), type = 'script' }: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// An empty prompt is stored as undefined, so the row keeps its own open state to show the field
// between turning the toggle on and typing.
let open = $state(false)
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<SettingToggle
setting="ai-prompt"
label="AI prompt"
@@ -1,15 +1,18 @@
<script lang="ts">
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { codeCompletionSessionEnabled, CODE_COMPLETION_SETTING_NAME } from '$lib/stores'
import { storeLocalSetting } from '$lib/utils'
import Toggle from '../Toggle.svelte'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
function storeSetting() {
storeLocalSetting(CODE_COMPLETION_SETTING_NAME, $codeCompletionSessionEnabled.toString())
}
</script>
{#if $copilotInfo.enabled && $copilotInfo.codeCompletionModel}
{#if aiInfo?.enabled && aiInfo.codeCompletionModel}
<Toggle
size="xs"
bind:checked={$codeCompletionSessionEnabled}
@@ -18,7 +21,7 @@
}}
options={{ right: 'AI code completion' }}
/>
{:else}
{:else if aiInfo}
<Toggle
disabled
size="xs"
@@ -0,0 +1,69 @@
import { afterEach, expect, it, vi } from 'vitest'
import { flushSync, mount, tick, unmount } from 'svelte'
import type { AIConfig } from '$lib/gen'
import { loadWorkspaceCopilotInfo, setCopilotInfo } from '$lib/aiStore'
import { AIChatManager } from './chat/AIChatManager.svelte'
import CronGen from './CronGen.svelte'
import { getNonStreamingMetadataCompletion } from './lib'
vi.mock('$app/navigation', () => ({
goto: vi.fn(),
afterNavigate: vi.fn(),
beforeNavigate: vi.fn()
}))
vi.mock('monaco-editor', () => ({ Selection: class Selection {} }))
vi.mock('$lib/utils/featureUsage', () => ({ logFeatureUsage: vi.fn() }))
vi.mock('./lib', async (importOriginal) => ({
...(await importOriginal<typeof import('./lib')>()),
getNonStreamingMetadataCompletion: vi.fn(async () => '0 0 * * 1')
}))
const CONFIGS: Record<string, AIConfig> = {
staging: {
providers: { anthropic: { resource_path: 'u/admin/a', models: ['claude-x'] } },
default_model: { provider: 'anthropic', model: 'claude-x' }
},
fork: {
providers: { mistral: { resource_path: 'u/admin/m', models: ['fork-z'] } },
default_model: { provider: 'mistral', model: 'fork-z' }
}
}
vi.mock('$lib/gen', async (importOriginal) => ({
...(await importOriginal<typeof import('$lib/gen')>()),
WorkspaceService: {
getCopilotInfo: async ({ workspace }: { workspace: string }) => CONFIGS[workspace]
}
}))
let component: ReturnType<typeof mount> | undefined
afterEach(() => component && unmount(component))
it("a generator in a session's editor sends with the session's workspace, not the tab's", async () => {
// The tab's copy holds staging; the session works in its fork.
setCopilotInfo(CONFIGS.staging)
const manager = new AIChatManager()
manager.isSessionChat = true
manager.workspaceResolver = () => 'fork'
await loadWorkspaceCopilotInfo('fork')
component = mount(CronGen, {
target: document.body,
props: { schedule: '', cronVersion: 'v2' },
context: new Map([['aiChatManager', manager]])
})
flushSync()
document.querySelector<HTMLButtonElement>('button[title="AI Assistant"]')!.click()
await tick()
const input = document.querySelector<HTMLInputElement>(
'input[placeholder="CRON schedule description"]'
)!
input.value = 'every monday'
input.dispatchEvent(new Event('input', { bubbles: true }))
input.dispatchEvent(new KeyboardEvent('keypress', { key: 'Enter', bubbles: true }))
await tick()
const target = vi.mocked(getNonStreamingMetadataCompletion).mock.calls[0]?.[2]
expect(target?.workspace).toBe('fork')
expect(target?.info.defaultModel?.model).toBe('fork-z')
})
@@ -6,8 +6,11 @@
import { sendUserToast } from '$lib/toast'
import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs'
import { copilotInfo } from '$lib/aiStore'
import { untrack } from 'svelte'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
interface Props {
schedule: string
@@ -53,7 +56,11 @@
}
]
const response = await getNonStreamingMetadataCompletion(messages, abortController)
const response = await getNonStreamingMetadataCompletion(
messages,
abortController,
aiChat.loadedSessionAiTarget
)
if (response.startsWith('ERROR:')) {
throw response.replace('ERROR:', '').trim()
@@ -78,7 +85,7 @@
})
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<Popover floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}>
{#snippet trigger()}
<Button
@@ -95,7 +102,7 @@
{/snippet}
{#snippet content({ close })}
<div class="border rounded-lg shadow-lg p-4 bg-surface">
{#if $copilotInfo.enabled}
{#if aiInfo?.enabled}
<div class="flex w-96">
<input
bind:this={instructionsField}
@@ -10,7 +10,10 @@
import { dfs } from '../flows/dfs'
import { yamlStringifyExceptKeys } from './utils'
import { stepInputCompletionEnabled } from '$lib/stores'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let generatedContent = $state('')
let loading = $state(false)
@@ -69,7 +72,8 @@ Only output the expression, do not explain or discuss.`
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
} catch (err) {
if (!abortController.signal.aborted) {
@@ -81,7 +85,7 @@ Only output the expression, do not explain or discuss.`
}
export function onKeyUp(event: KeyboardEvent) {
if (!$copilotInfo.enabled || !$stepInputCompletionEnabled) {
if (!aiInfo?.enabled || !$stepInputCompletionEnabled) {
return
}
if (event.key === 'Tab') {
@@ -120,7 +124,7 @@ Only output the expression, do not explain or discuss.`
})
$effect(() => {
if ($copilotInfo.enabled && $stepInputCompletionEnabled && focused) {
if (aiInfo?.enabled && $stepInputCompletionEnabled && focused) {
untrack(() => {
automaticGeneration()
})
@@ -3,7 +3,8 @@
import { isInitialCode } from '$lib/script_helpers'
import { Check, Loader2, Wand2 } from 'lucide-svelte'
import { metadataCompletionEnabled } from '$lib/stores'
import { copilotInfo, getMetadataModel } from '$lib/aiStore'
import { getMetadataModel, resolveMetadataModelFor } from '$lib/aiStore'
import { getAiChatManager } from './chat/aiChatManagerContext'
import { onDestroy, untrack } from 'svelte'
import { sendUserToast } from '$lib/toast'
import { twMerge } from 'tailwind-merge'
@@ -20,6 +21,9 @@
} from '../text_input/TextInput.svelte'
import { AIBtnClasses } from './chat/AIButtonStyle'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
type PromptConfig = {
system: string
user: string
@@ -176,8 +180,11 @@ Generate a tool name for the script below:
content: config.user.replace(`{${config.placeholderName}}`, placeholderContent)
}
]
const target = aiChat.loadedSessionAiTarget
const response = await getCompletion(messages, abortController, undefined, {
forceModelProvider: getMetadataModel()
forceModelProvider: target ? resolveMetadataModelFor(target.info) : getMetadataModel(),
workspace: target?.workspace,
info: target?.info
})
generatedContent = ''
for await (const chunk of response) {
@@ -197,7 +204,7 @@ Generate a tool name for the script below:
}
if (
$copilotInfo.enabled &&
aiInfo?.enabled &&
$metadataCompletionEnabled &&
untrack(() => generateOnAppear) &&
!content &&
@@ -216,7 +223,7 @@ Generate a tool name for the script below:
$effect(() => {
active =
$copilotInfo.enabled &&
!!aiInfo?.enabled &&
$metadataCompletionEnabled &&
!content &&
(loading || focused || !!generatedContent) &&
@@ -267,7 +274,7 @@ Generate a tool name for the script below:
}
}}
onkeydown={(event) => {
if (!$copilotInfo.enabled || !$metadataCompletionEnabled) {
if (!aiInfo?.enabled || !$metadataCompletionEnabled) {
return
}
if (event.key === 'Tab') {
@@ -13,16 +13,21 @@
import { stepInputCompletionEnabled } from '$lib/stores'
import Popover from '$lib/components/meltComponents/Popover.svelte'
import type { Flow } from '$lib/gen'
import { copilotInfo } from '$lib/aiStore'
import { AIBtnClasses } from './chat/AIButtonStyle'
import { twMerge } from 'tailwind-merge'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let loading = $state(false)
interface Props {
/** Id of the branching step, which isn't the selected id when a branch node is selected. */
moduleId: string
pickableProperties?: PickableProperties | undefined
}
let { pickableProperties = undefined }: Props = $props()
let { moduleId, pickableProperties = undefined }: Props = $props()
let instructions = $state('')
let instructionsField: HTMLInputElement | undefined = $state(undefined)
@@ -31,31 +36,32 @@
})
let abortController = $state(new AbortController())
const { flowStore, selectionManager } = getContext<FlowEditorContext>('FlowEditorContext')
const { flowStore } = getContext<FlowEditorContext>('FlowEditorContext')
const dispatch = createEventDispatcher()
async function generatePredicate() {
abortController = new AbortController()
loading = true
const flow: Flow = JSON.parse(JSON.stringify(flowStore.val))
const idOrders = dfs(flow.value.modules, (x) => x.id)
const upToIndex = idOrders.indexOf(selectionManager.getSelectedId())
if (upToIndex === -1) {
throw new Error('Could not find the selected id in the flow')
}
const flowDetails =
'Take into account the following information for never tested results:\n<flowDetails>\n' +
yamlStringifyExceptKeys(sliceModules(flow.value.modules, upToIndex, idOrders), ['lock']) +
'</flowDetails>'
try {
const flow: Flow = JSON.parse(JSON.stringify(flowStore.val))
const idOrders = dfs(flow.value.modules, (x) => x.id)
const upToIndex = idOrders.indexOf(moduleId)
if (upToIndex === -1) {
throw new Error('Could not find the branching step in the flow')
}
const flowDetails =
'Take into account the following information for never tested results:\n<flowDetails>\n' +
yamlStringifyExceptKeys(sliceModules(flow.value.modules, upToIndex, idOrders), ['lock']) +
'</flowDetails>'
const availableData = {
results: pickableProperties?.priorIds,
flow_input: pickableProperties?.flow_input
}
const user = `I'm building a workflow which is a DAG of script steps.
The current step is ${selectionManager.getSelectedId()} and is a branching step (if-else).
The current step is ${moduleId} and is a branching step (if-else).
The user wants to generate a predicate for the branching condition.
Here's the user's request: ${instructions}
You can find the details of all the steps below:
@@ -75,7 +81,8 @@ Only return the expression without any wrapper. Do not explain or discuss.`
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
dispatch('setExpr', result)
@@ -90,7 +97,7 @@ Only return the expression without any wrapper. Do not explain or discuss.`
}
</script>
{#if $copilotInfo.enabled && $stepInputCompletionEnabled}
{#if aiInfo?.enabled && $stepInputCompletionEnabled}
<Popover
floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}
contentClasses="p-4 flex w-96"
@@ -10,7 +10,10 @@
import { autoPlacement } from '@floating-ui/core'
import { ExternalLink, HistoryIcon, Wand2 } from 'lucide-svelte'
import { createEventDispatcher } from 'svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// state
let funcDesc: string = $state('')
@@ -39,7 +42,8 @@
content: funcDesc
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
dispatch('gen', { res: res, prompt: funcDesc })
funcDesc = ''
@@ -92,7 +96,7 @@
}
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<Popover
floatingConfig={{
middleware: [
@@ -118,7 +122,7 @@
{/snippet}
{#snippet content({ close })}
<div class="block text-primary p-4">
{#if $copilotInfo.enabled}
{#if aiInfo?.enabled}
<div class="flex flex-col gap-4">
<div class="flex w-96">
<input
@@ -5,8 +5,11 @@
import Popover from '$lib/components/meltComponents/Popover.svelte'
import { sendUserToast } from '$lib/toast'
import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs'
import { copilotInfo } from '$lib/aiStore'
import type { Schema } from '$lib/common'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
interface Props {
args: Record<string, any>
@@ -94,7 +97,11 @@
}
]
let response = await getNonStreamingMetadataCompletion(messages, abortController)
let response = await getNonStreamingMetadataCompletion(
messages,
abortController,
aiChat.loadedSessionAiTarget
)
// Strip markdown fences if present
response = response.trim()
@@ -118,7 +125,7 @@
})
</script>
{#if !$copilotInfo.workspaceDisabled}
{#if aiInfo && !aiInfo.workspaceDisabled}
<Popover floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}>
{#snippet trigger()}
<Button
@@ -137,7 +144,7 @@
{/snippet}
{#snippet content({ close })}
<div class="border rounded-lg shadow-lg p-4 bg-surface">
{#if $copilotInfo.enabled}
{#if aiInfo?.enabled}
<div class="flex flex-col w-80 gap-2">
<textarea
bind:this={instructionsField}
@@ -5,7 +5,7 @@
import type { SupportedLanguage } from '$lib/common'
import { WandSparkles } from 'lucide-svelte'
import type { AIChatManager } from './chat/AIChatManager.svelte'
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte'
import { getOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext'
import { AIBtnClasses } from './chat/AIButtonStyle'
@@ -30,6 +30,9 @@
moduleId?: string
} = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
// The enclosing editor's "Open in AI session" hand-off (ScriptEditor for a
// standalone script, FlowBuilder for a step).
const handoff = getOpenInSessionHandoff()
@@ -74,7 +77,7 @@
const sessionScopedManager = getContext<AIChatManager | undefined>('aiChatManager')
</script>
{#if SUPPORTED_LANGUAGES.has(lang) && !$copilotInfo.workspaceDisabled}
{#if SUPPORTED_LANGUAGES.has(lang) && aiInfo && !aiInfo.workspaceDisabled}
{#if sessionScopedManager}
<Button
title="Fix the failing run in this chat"
@@ -1,5 +1,5 @@
<script lang="ts">
import { copilotInfo } from '$lib/aiStore'
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
import { ScriptService, type ListableScript } from '$lib/gen'
import { Wand2, Loader2 } from 'lucide-svelte'
@@ -29,8 +29,11 @@
disableAi = false,
filteredItems = $bindable([])
}: Props = $props()
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let prefilteredItems = $derived(scripts ?? [])
let aiHidden = $derived(disableAi || $copilotInfo.workspaceDisabled)
let aiHidden = $derived(disableAi || !aiInfo || aiInfo.workspaceDisabled)
const dispatch = createEventDispatcher()
@@ -14,12 +14,15 @@
import { stepInputCompletionEnabled } from '$lib/stores'
import type { SchemaProperty } from '$lib/common'
import FlowCopilotInputsModal from './FlowCopilotInputsModal.svelte'
import { copilotInfo } from '$lib/aiStore'
import Button from '../common/button/Button.svelte'
import { AIBtnClasses } from './chat/AIButtonStyle'
import { Check, Wand2 } from 'lucide-svelte'
import { twMerge } from 'tailwind-merge'
import { newFlowInputOf, newFlowInputsInstruction } from './stepInputFlowInputs'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let generatedContent = $state('')
let loading = $state(false)
@@ -119,7 +122,8 @@ Only return the expression without any wrapper.`
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
const newInput = newFlowInputOf(generatedContent, pickableProperties)
@@ -137,7 +141,7 @@ Only return the expression without any wrapper.`
}
export function onKeyUp(event: KeyboardEvent) {
if (!$copilotInfo.enabled || !$stepInputCompletionEnabled) {
if (!aiInfo?.enabled || !$stepInputCompletionEnabled) {
return
}
if (event.key === 'Tab') {
@@ -206,7 +210,7 @@ Only return the expression without any wrapper.`
}
</script>
{#if $copilotInfo.enabled && $stepInputCompletionEnabled}
{#if aiInfo?.enabled && $stepInputCompletionEnabled}
<FlowCopilotInputsModal
on:confirmed={async () => {
createFlowInput()
@@ -14,7 +14,6 @@
import { logStepInputFill } from './stepInputFillTelemetry'
import { Check, ExternalLink, Loader2, Wand2 } from 'lucide-svelte'
import { stepInputCompletionEnabled } from '$lib/stores'
import { copilotInfo } from '$lib/aiStore'
import Popover from '$lib/components/meltComponents/Popover.svelte'
import type { SchemaProperty, Schema } from '$lib/common'
import FlowCopilotInputsModal from './FlowCopilotInputsModal.svelte'
@@ -22,6 +21,10 @@
import { twMerge } from 'tailwind-merge'
import { AIBtnClasses } from './chat/AIButtonStyle'
import { newFlowInputOf, newFlowInputsInstruction } from './stepInputFlowInputs'
import { getAiChatManager } from './chat/aiChatManagerContext'
const aiChat = getAiChatManager()
const aiInfo = $derived(aiChat.aiInfo)
let loading = $state(false)
interface Props {
@@ -101,7 +104,8 @@ input_name2: expression2
content: user
}
],
abortController
abortController,
aiChat.loadedSessionAiTarget
)
parsedInputs = generatedContent.split('\n').map((x) => x.split(': '))
@@ -191,7 +195,7 @@ input_name2: expression2
</script>
<div class="flex flex-row justify-end">
{#if $copilotInfo.enabled && $stepInputCompletionEnabled}
{#if aiInfo?.enabled && $stepInputCompletionEnabled}
<FlowCopilotInputsModal
on:confirmed={async () => {
createFlowInputs()
@@ -225,7 +229,7 @@ input_name2: expression2
Fill inputs
{/if}
</Button>
{:else if !$copilotInfo.workspaceDisabled}
{:else if aiInfo && !aiInfo.workspaceDisabled}
<Popover
floatingConfig={{
placement: 'top-end'
@@ -248,7 +252,7 @@ input_name2: expression2
{#snippet content({ close })}
<div class="p-4">
<p class="text-sm">
{#if !$copilotInfo.enabled}
{#if !aiInfo?.enabled}
Enable Windmill AI in the{' '}
<a
href="/workspace_settings?tab=ai"
@@ -22,6 +22,7 @@
starter = undefined,
onSent = undefined,
inputPreface,
actingOn,
workModeLock = undefined,
initialInstructions = undefined,
onDraftChange = undefined,
@@ -46,6 +47,7 @@
starter?: import('./starter/starterPrompts.svelte').ChatStarter
onSent?: () => void
inputPreface?: import('svelte').Snippet
actingOn?: import('svelte').Snippet
workModeLock?: import('./workMode').WorkModeLock
// Seed / observe the composer's draft (forwarded to AIChatDisplay).
initialInstructions?: string
@@ -229,6 +231,7 @@
{starter}
{onSent}
{inputPreface}
{actingOn}
{workModeLock}
{initialInstructions}
{onDraftChange}
@@ -128,6 +128,7 @@
starter = undefined,
onSent = undefined,
inputPreface,
actingOn,
workModeLock = undefined,
footerSettings,
initialInstructions = undefined,
@@ -169,6 +170,8 @@
/** After the composer hands a new turn to the host. */
onSent?: () => void
inputPreface?: Snippet
/** Where the session acts: first among the controls after the attach button. */
actingOn?: Snippet
/** Holds a session chat in Use, and says why in the picker. */
workModeLock?: WorkModeLock
/** The settings control at the footer's right edge, where the copilot puts its
@@ -200,7 +203,7 @@
let plusMenuOpen = $state(false)
let editingMessageIndex = $state<number | null>(null)
const groupChatItems = createChatItemGrouper()
const chatItems = $derived(groupChatItems(messages))
const chatItems = $derived(groupChatItems(messages, chatHost.groupingTools))
// Mounting a message parses its markdown, so a long transcript mounted at once blocks the
// page for every message in it. Only the tail is mounted when a transcript arrives; older
@@ -903,6 +906,7 @@
const showFooterLeftControls = $derived(
!footerMessageShown &&
(canAttachFiles ||
!!actingOn ||
attachmentsOffReason !== undefined ||
showContextPicker ||
showAutonomyModeSelector ||
@@ -1563,6 +1567,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
onchange={onFolderInputChange}
/>
{/if}
{@render actingOn?.()}
{#if showAutonomyModeSelector}
<AutonomyModePicker
mode={chatHost.autonomyMode}
@@ -111,7 +111,6 @@ import {
type CopilotInfo
} from '$lib/aiStore'
import type { ReasoningProviderModel } from '../reasoningRegistry'
import { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot'
import { askTools, prepareAskSystemMessage, prepareAskUserMessage } from './ask/core'
import { readDocsPageTool, searchDocsTool } from './docs/core'
import { withWebSearchFallback } from './web/core'
@@ -203,6 +202,8 @@ import {
assembleGlobalTools,
type GlobalAssemblyOpts
} from './global/globalAssembly'
import type { GroupingTools } from './toolGroups'
import { chatGroupingTools } from './groupingTools'
import { formatChatJobCompletion } from './datatableTools'
import { loadMcpServers, type McpServer } from './global/mcpTools'
import type { PipelineAIChatHelpers } from './pipeline/core'
@@ -448,23 +449,16 @@ function getSendRequestErrorMessage(
return appendWebSearchErrorHint(message, webSearchUnavailable)
}
/** Re-fetch copilotInfo after a free-tier turn so the usage banner tracks spend live and the
* exhausting turn flips `freeTier.exhausted`; otherwise these update only on the next workspace
/** Re-fetch the chat workspace's config after a free-tier turn so the usage banner tracks spend
* live and the exhausting turn flips `freeTier.exhausted`; otherwise these update only on the next
* load. Scoped to a live (non-exhausted) free tier so configured-key users pay no extra request. */
async function refreshFreeTierUsage(workspace: string | undefined) {
function refreshFreeTierUsage(workspace: string | undefined) {
if (!workspace) return
// copilotInfo is a singleton shared across sessions: a warm session finishing after a
// workspace switch must not loadCopilot for its now-background workspace. Gate on the
// most-recently-*requested* workspace (set synchronously) so a refresh can't win the
// monotonic token over a newer load still in flight.
if (get(copilotWorkspaceRequested) !== workspace) return
const info = get(copilotInfo)
if (!info.freeTier || info.freeTier.exhausted) return
try {
await loadCopilot(workspace)
} catch (err) {
const info = getWorkspaceCopilotInfo(workspace)
if (!info?.freeTier || info.freeTier.exhausted) return
loadWorkspaceCopilotInfo(workspace, true).catch((err) =>
console.error('Failed to refresh free-tier usage', err)
}
)
}
/** A message queued while a turn streams: the draft lanes and the pinned
@@ -847,6 +841,11 @@ export class AIChatManager implements ChatViewHost {
* Set before `moving`, which waits for the editors to hand over their pending edits. */
moveStarted = $state(false)
onWorkModeChanged: ((mode: AIWorkMode) => void) | undefined = undefined
/** The protected workspace the session was opted into working in directly (`direct_in`). */
directInResolver: (() => string | undefined) | undefined = undefined
get directIn(): string | undefined {
return this.directInResolver?.()
}
workModesAvailable = $derived(this.isSessionChat && supportsPlanMode(this.mode))
/** Use is the only mode: the workspace is protected, or the user's role builds nothing in it. */
#useOnly = $derived(this.workModesAvailable && !canBuild(this.sessionAccess))
@@ -927,6 +926,10 @@ export class AIChatManager implements ChatViewHost {
...(this.workModesAvailable && !this.#useOnly ? Object.values(this.#workModeSwitches) : [])
])
)
// A getter: the manager is built while the tool modules that groupingTools.ts imports still load.
get groupingTools(): GroupingTools {
return chatGroupingTools()
}
/** Whether a tool the call was made with is no longer shipped: a switch to Use withdraws
* every write while its card waits. The mode transitions are not assembled, so never are. */
isToolWithdrawn = (toolName: string): boolean => {
@@ -3228,7 +3231,9 @@ export class AIChatManager implements ChatViewHost {
return
}
const generation = ++this.sessionAccessGeneration
const access = await resolveSessionAccess(workspace)
const access = await resolveSessionAccess(workspace, {
direct: this.directIn === workspace
})
if (generation !== this.sessionAccessGeneration) return
this.sessionAccess = workspace === (this.operatingWorkspace ?? '') ? access : undefined
if (this.mode === AIMode.GLOBAL) {
@@ -5071,7 +5076,7 @@ export class AIChatManager implements ChatViewHost {
this.reasoningReveal.reset()
// Refresh the free-tier usage meter after every turn (success or error), and
// let the turn that exhausts the grant flip to the exhausted state live.
void refreshFreeTierUsage(this.operatingWorkspace)
refreshFreeTierUsage(this.operatingWorkspace)
}
// Flush the queued message. Send it after a cleanly committed turn OR a
// deliberate user cancel (Esc / Stop) — in both cases the user is ready
@@ -60,7 +60,8 @@
}))
const w = work
if (!w) return postures
const lockedOut = (m: AIWorkMode) => !!w.lock && m !== AIWorkMode.USE
const lockedOut = (m: AIWorkMode) => !!w.lock && !w.lock.onPick && m !== AIWorkMode.USE
const onPick = w.lock?.onPick
const workItems: Item[] = workModeOptions
.filter((o) => o.mode !== AIWorkMode.PLAN || w.planAvailable || w.lock)
.map((o, i) => {
@@ -76,7 +77,7 @@
selected: workOption?.mode === o.mode,
disabled: locked,
tooltip: locked ? w.lock?.reason : undefined,
action: () => w.onChange(o.mode)
action: () => (onPick && o.mode !== AIWorkMode.USE ? onPick(o.mode) : w.onChange(o.mode))
}
})
const escape = w.lock?.escape
@@ -8,7 +8,7 @@
COPILOT_SESSION_REASONING_SETTING_NAME
} from '$lib/stores'
import { storeLocalSetting } from '$lib/utils'
import { copilotInfo, copilotSessionModel } from '$lib/aiStore'
import { copilotInfo, copilotSessionModel, tryResolveModelFor } from '$lib/aiStore'
import type { AIProvider } from '$lib/gen'
import {
getReasoningCapability,
@@ -17,14 +17,14 @@
type ReasoningProviderModel
} from '../reasoningRegistry'
let providerModel = $derived(
($copilotSessionModel ??
$copilotInfo.defaultModel ??
$copilotInfo.aiModels[0] ?? {
model: 'No model',
provider: 'No provider'
}) as ReasoningProviderModel
)
let providerModel = $derived.by(() => {
// Subscribes only: `tryResolveModelFor` reads the pick through `get()`, which tracks nothing.
void $copilotSessionModel
return (tryResolveModelFor($copilotInfo) ?? {
model: 'No model',
provider: 'No provider'
}) as ReasoningProviderModel
})
let multipleModels = $derived($copilotInfo.aiModels.length > 1)
@@ -41,6 +41,11 @@
}
}
// A test group's latest run is what the loop got to, so its card stays shown under the
// header while the earlier runs fold.
const shownLast = $derived(group.groupKind === 'test' ? group.entries.at(-1) : undefined)
const folded = $derived(shownLast ? group.entries.slice(0, -1) : group.entries)
const calls = $derived(
group.entries.map((e) => e.message).filter((m): m is ToolDisplayMessage => m.role === 'tool')
)
@@ -63,8 +68,9 @@
: undefined
)
// What the group is doing right now, so a collapsed run still names its current step.
// A test group's live call is its shown run, whose card already says so.
const liveLine = $derived(
running
running && !shownLast
? (
calls.findLast((m) => m.isLoading || m.isStreamingArguments) ??
calls.find((m) => m.isQueued)
@@ -125,9 +131,14 @@
headerLeft={mcpServer ? serverMark : undefined}
contentClass="border-0 border-l rounded-none bg-transparent p-0 pl-2 ml-1.5 mt-0.5"
>
{#each group.entries as { message, index } (index)}
{#each folded as { message, index } (index)}
<div bind:this={rows[index]}>
{@render entry(message, index)}
</div>
{/each}
</ChatCollapsibleCard>
{#if shownLast}
<div class="mt-1" bind:this={rows[shownLast.index]}>
{@render entry(shownLast.message, shownLast.index)}
</div>
{/if}
@@ -524,6 +524,7 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [
{
def: getListFilesToolDef(),
planModeSafe: true,
lookup: true,
fn: async ({ helpers, toolId, toolCallbacks }) => {
toolCallbacks.setToolStatus(toolId, { content: 'Listing files...' })
const files = helpers.getFiles()
@@ -560,6 +561,7 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [
{
def: getGetFrontendFileToolDef(),
planModeSafe: true,
lookup: true,
fn: async ({ args, helpers, toolId, toolCallbacks }) => {
const parsedArgs = getGetFrontendFileSchema().parse(args)
toolCallbacks.setToolStatus(toolId, {
@@ -693,6 +695,7 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [
{
def: getGetBackendRunnableToolDef(),
planModeSafe: true,
lookup: true,
fn: async ({ args, helpers, toolId, toolCallbacks }) => {
const parsedArgs = getGetBackendRunnableSchema().parse(args)
toolCallbacks.setToolStatus(toolId, {
@@ -781,6 +784,7 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [
{
def: getLintToolDef(),
planModeSafe: true,
lookup: true,
fn: async ({ helpers, toolId, toolCallbacks }) => {
toolCallbacks.setToolStatus(toolId, { content: 'Linting app...' })
const lintResult = helpers.lint()
@@ -803,6 +807,7 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [
{
def: getListDatatablesToolDef(),
planModeSafe: true,
lookup: true,
fn: async ({ helpers, toolId, toolCallbacks }) => {
toolCallbacks.setToolStatus(toolId, { content: 'Listing datatables...' })
try {
@@ -826,6 +831,7 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [
{
def: getGetDatatableTableSchemaToolDef(),
planModeSafe: true,
lookup: true,
fn: async ({ args, helpers, toolId, toolCallbacks }) => {
const parsedArgs = getGetDatatableTableSchemaSchema().parse(args)
toolCallbacks.setToolStatus(toolId, {
@@ -234,6 +234,7 @@ export const artifactTools: SessionTool<{}>[] = [
"List the current session's artifacts (id, name, kind, version, role, approvedVersion). `version` is the latest one saved, which is not necessarily the one the user is reading — get_preview_status reports the version they have pinned. `role` is `plan` on the session's one plan document and on nothing else. On that one, `approvedVersion` is the version the user signed off: below `version` means the current text is a proposal they have not agreed to, and absent means nothing here was ever approved."
),
planModeSafe: true,
lookup: true,
fn: async ({ toolId, toolCallbacks, helpers }) => {
const h = helpers as ArtifactToolHelpers
const sessionId = h.sessionId
@@ -269,6 +270,7 @@ export const artifactTools: SessionTool<{}>[] = [
"Read an artifact's full markdown content by id, at its current or an earlier version."
),
planModeSafe: true,
lookup: true,
fn: async ({ args, toolId, toolCallbacks, helpers }) => {
const parsed = readArtifactSchema.parse(args)
const h = helpers as ArtifactToolHelpers
@@ -337,6 +339,7 @@ export const artifactTools: SessionTool<{}>[] = [
// How the model recovers the approved plan once a refused draft stands in front of it;
// the fail-closed gate would otherwise block that in the posture that needs it.
planModeSafe: true,
lookup: true,
fn: async ({ args, toolId, toolCallbacks, helpers }) => {
const parsed = listArtifactVersionsSchema.parse(args)
const h = helpers as ArtifactToolHelpers

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