From 2aa6059e58e1cf4708ba65927d6e6338d364127a Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:53:43 +0100 Subject: [PATCH 1/7] fix: reserve the username anonymous used by logged-out visitors (#12146) * fix: reserve the username anonymous used by logged-out visitors * chore: update ee-repo-ref to fd0a13b710988f51d38751cd7e493d3ce8739378 This commit updates the EE repository reference after PR #940 was merged in windmill-ee-private. Previous ee-repo-ref: 5c6e145f79df2fef2aa403b7ab2336ffba7f0c8b New ee-repo-ref: fd0a13b710988f51d38751cd7e493d3ce8739378 Automated by sync-ee-ref workflow. --------- Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- .../tests/users.rs | 51 ++++++++++++++++ backend/windmill-api/src/apps.rs | 2 +- backend/windmill-api/src/jobs.rs | 10 ++-- backend/windmill-api/src/users.rs | 58 ++++++++++--------- backend/windmill-common/src/usernames.rs | 30 +++++++++- backend/windmill-queue/src/jobs.rs | 2 +- 7 files changed, 118 insertions(+), 37 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 61f3036bf4..8d0e9b5082 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -9dff0e516841b64b54d7a5b50951016d45161b51 +fd0a13b710988f51d38751cd7e493d3ce8739378 diff --git a/backend/windmill-api-integration-tests/tests/users.rs b/backend/windmill-api-integration-tests/tests/users.rs index cf9d2c39d5..290ec4568d 100644 --- a/backend/windmill-api-integration-tests/tests/users.rs +++ b/backend/windmill-api-integration-tests/tests/users.rs @@ -1212,3 +1212,54 @@ async fn test_rename_keeps_other_workspaces_like_named_memberships( Ok(()) } + +/// Logged-out visitors of public apps run as `anonymous`. Renaming an account that already holds +/// that name must not take their jobs with it, nor their logged-out access to them. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_rename_from_anonymous_keeps_visitor_jobs(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + "UPDATE usr SET username = 'anonymous' WHERE email = 'test3@windmill.dev'; + UPDATE password SET username = 'anonymous' WHERE email = 'test3@windmill.dev'; + INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, kind, tag, args) + VALUES (gen_random_uuid(), 'test-workspace', 'anonymous', 'u/test-user', 'script', 'deno', '{}'::jsonb);", + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/users/rename/test3@windmill.dev" + ))) + .json(&json!({ "new_username": "former_anonymous" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "rename: {}", resp.text().await?); + + let username: String = + sqlx::query_scalar("SELECT username FROM usr WHERE email = 'test3@windmill.dev'") + .fetch_one(&db) + .await?; + assert_eq!(username, "former_anonymous"); + let created_by: Vec = + sqlx::query_scalar("SELECT created_by FROM v2_job WHERE workspace_id = 'test-workspace'") + .fetch_all(&db) + .await?; + assert_eq!(created_by, vec!["anonymous"]); + + Ok(()) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_generated_username_skips_anonymous(db: Pool) -> anyhow::Result<()> { + let mut tx = db.begin().await?; + let username = windmill_common::usernames::generate_instance_wide_unique_username( + &mut tx, + "anonymous@acme.com", + ) + .await?; + assert_eq!(username, "anonymous2"); + Ok(()) +} diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index c7b61a1211..d55bdb8ea6 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -4414,7 +4414,7 @@ async fn get_on_behalf_details_from_policy_and_authed( let username = opt_authed .as_ref() .map(|a| a.username.clone()) - .unwrap_or_else(|| "anonymous".to_string()); + .unwrap_or_else(|| windmill_common::usernames::ANONYMOUS_USERNAME.to_string()); let (permissioned_as, email) = get_on_behalf_of(&policy, w_id, db).await?; (username, permissioned_as, email) } diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 9e9fdcfaa3..1aa5340b67 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -2246,7 +2246,9 @@ async fn require_unauthed_job_read_access( created_by: &str, view_token: Option<&str>, ) -> error::Result<()> { - if created_by == "anonymous" || public_view_token_grants(db, w_id, job_id, view_token).await? { + if created_by == windmill_common::usernames::ANONYMOUS_USERNAME + || public_view_token_grants(db, w_id, job_id, view_token).await? + { return Ok(()); } Err(Error::BadRequest( @@ -2659,7 +2661,7 @@ impl<'a> GetQuery<'a> { fn check_auth(&self, email: Option<&str>) -> error::Result<()> { if let Some(email) = email { if self.with_auth.is_some_and(|x| x.is_none()) - && email != "anonymous" + && email != windmill_common::usernames::ANONYMOUS_USERNAME && !self.with_public_view_grant { return Err(Error::BadRequest( @@ -11521,7 +11523,7 @@ async fn get_job_update_data( .await? .ok_or_else(|| Error::NotFound(format!("Job not found: {}", job_id)))?; - if created_by != "anonymous" { + if created_by != windmill_common::usernames::ANONYMOUS_USERNAME { return Err(Error::BadRequest( "As a non logged in user, you can only see jobs ran by anonymous users" .to_string(), @@ -11769,7 +11771,7 @@ async fn get_job_update_data( .ok_or_else(|| Error::NotFound(format!("Job not found: {}", job_id)))?; if opt_authed.is_none() && !*unauthed_read_authorized { - if record.created_by != "anonymous" { + if record.created_by != windmill_common::usernames::ANONYMOUS_USERNAME { return Err(Error::BadRequest( "As a non logged in user, you can only see jobs ran by anonymous users" .to_string(), diff --git a/backend/windmill-api/src/users.rs b/backend/windmill-api/src/users.rs index 11875cdba3..8a46272a5e 100644 --- a/backend/windmill-api/src/users.rs +++ b/backend/windmill-api/src/users.rs @@ -29,7 +29,7 @@ use windmill_api_auth::{ use windmill_audit::audit_oss::audit_log; use windmill_audit::ActionKind; use windmill_common::audit::AuditAuthor; -use windmill_common::usernames::validate_username; +use windmill_common::usernames::{validate_username, ANONYMOUS_USERNAME}; use windmill_common::{ error::{self, Error, Result}, DB, @@ -477,34 +477,38 @@ async fn update_username_in_workpsace<'c>( .execute(&mut **tx) .await?; - sqlx::query!( - "UPDATE v2_job SET created_by = $1 WHERE created_by = $2 AND workspace_id = $3", - new_username, - old_username, - w_id - ) - .execute(&mut **tx) - .await?; + // An account still named `anonymous` shares that name with logged-out visitors' jobs, which + // must stay theirs: moving them would hand the visitors' runs to the account. + if old_username != ANONYMOUS_USERNAME { + sqlx::query!( + "UPDATE v2_job SET created_by = $1 WHERE created_by = $2 AND workspace_id = $3", + new_username, + old_username, + w_id + ) + .execute(&mut **tx) + .await?; - // ---- v2_job_queue ---- - sqlx::query!( - "UPDATE v2_job_queue SET canceled_by = $1 WHERE canceled_by = $2 AND workspace_id = $3", - new_username, - old_username, - w_id - ) - .execute(&mut **tx) - .await?; + // ---- v2_job_queue ---- + sqlx::query!( + "UPDATE v2_job_queue SET canceled_by = $1 WHERE canceled_by = $2 AND workspace_id = $3", + new_username, + old_username, + w_id + ) + .execute(&mut **tx) + .await?; - // ---- v2_job_completed ---- - sqlx::query!( - "UPDATE v2_job_completed SET canceled_by = $1 WHERE canceled_by = $2 AND workspace_id = $3", - new_username, - old_username, - w_id - ) - .execute(&mut **tx) - .await?; + // ---- v2_job_completed ---- + sqlx::query!( + "UPDATE v2_job_completed SET canceled_by = $1 WHERE canceled_by = $2 AND workspace_id = $3", + new_username, + old_username, + w_id + ) + .execute(&mut **tx) + .await?; + } // ---- resources---- sqlx::query!( diff --git a/backend/windmill-common/src/usernames.rs b/backend/windmill-common/src/usernames.rs index 38dc1c2809..abdc895121 100644 --- a/backend/windmill-common/src/usernames.rs +++ b/backend/windmill-common/src/usernames.rs @@ -19,6 +19,11 @@ lazy_static::lazy_static! { /// Width of the `username` columns of `usr`, `password` and `pending_user`. pub const USERNAME_MAX_LEN: usize = 50; +/// The `created_by` of jobs run by logged-out visitors of public apps. Logged-out callers may +/// read and cancel jobs created by it, so no new account may take it. Those checks compare +/// exactly, so only this exact spelling is reserved. +pub const ANONYMOUS_USERNAME: &str = "anonymous"; + /// The rule for every username a caller chooses. It is exactly what the generators produce /// (`INVALID_USERNAME_CHARS` stripped), so automatic creation always satisfies it. No hyphen: /// Windmill's own job creators and identities are hyphenated (`group-` becomes `g/`, @@ -33,6 +38,11 @@ pub fn validate_username(username: &str) -> error::Result<()> { at most {USERNAME_MAX_LEN} characters" ))); } + if username == ANONYMOUS_USERNAME { + return Err(Error::BadRequest( + "The username anonymous is reserved".to_string(), + )); + } Ok(()) } @@ -75,7 +85,7 @@ pub async fn generate_instance_wide_unique_username<'c>( ))); } username = fit_username(&base_username, i); - username_conflict = sqlx::query_scalar!( + username_conflict = username == ANONYMOUS_USERNAME || sqlx::query_scalar!( "SELECT EXISTS(SELECT 1 FROM usr WHERE username = $1 and email != $2 UNION SELECT 1 FROM password WHERE username = $1 UNION SELECT 1 FROM pending_user WHERE username = $1)", &username, &email @@ -202,10 +212,24 @@ mod tests { #[test] fn test_validate_username() { - for ok in ["jean_luc", "42", "A", &"a".repeat(USERNAME_MAX_LEN)] { + for ok in [ + "jean_luc", + "42", + "A", + "Anonymous", + &"a".repeat(USERNAME_MAX_LEN), + ] { assert!(validate_username(ok).is_ok(), "{ok}"); } - for bad in ["", "jean-luc", "group-ops", "josé", "a b", &"a".repeat(51)] { + for bad in [ + "", + "jean-luc", + "group-ops", + "josé", + "a b", + "anonymous", + &"a".repeat(51), + ] { assert!(validate_username(bad).is_err(), "{bad}"); } } diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index e357150cd2..19bb2fae41 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -299,7 +299,7 @@ pub async fn cancel_job<'c>( let mut job = job.unwrap(); - if require_anonymous && job.created_by != "anonymous" { + if require_anonymous && job.created_by != windmill_common::usernames::ANONYMOUS_USERNAME { return Err(Error::BadRequest( "You are not logged in and this job was not created by an anonymous user like you so you cannot cancel it".to_string(), )); From 3d0ca92ef2ad98b1c3e5abe68a7a5b10c94f05df Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Mon, 2 Nov 2026 15:40:22 +0100 Subject: [PATCH 2/7] feat: upgrade the bundled DuckDB engine to 2.0.0 LTS (#11924) * feat: upgrade the bundled DuckDB engine to 2.0.0 LTS Co-Authored-By: Claude Opus 5.5 * fix: never repeat a ducklake attach option, duckdb 2.0 rejects duplicates Co-Authored-By: Claude Opus 5.5 * fix: dedupe quoted attach option names and drop comments from the list Co-Authored-By: Claude Opus 5.5 * fix: pin duckdb 2.0 from crates.io and revert more 2.0 defaults that change results Co-Authored-By: Claude Opus 5.5 * fix: fail duckdb jobs with a clear message on x86 cpus without avx2 Co-Authored-By: Claude Opus 5.5 * fix: strip sql comments from lake attach args before appending fork options Co-Authored-By: Claude Opus 5.5 * fix: scan E'' escape-string literals when stripping attach option comments Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- backend/windmill-common/src/workspaces.rs | 97 ++++- .../windmill-duckdb-ffi-internal/Cargo.lock | 338 ++++++------------ .../windmill-duckdb-ffi-internal/Cargo.toml | 2 +- .../windmill-duckdb-ffi-internal/src/lib.rs | 50 +++ .../windmill-worker/src/duckdb_executor.rs | 176 +++++++-- backend/windmill-worker/src/duckdb_runner.rs | 17 + docs/duckdb-execution.md | 40 ++- frontend/src/lib/infer.svelte.ts | 7 +- 8 files changed, 464 insertions(+), 263 deletions(-) diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index 0a3bf0ac6f..248754dba8 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -2815,9 +2815,87 @@ pub fn fork_ducklake_ancestor_alias(lake_name: &str, ancestor_w_id: &str) -> Str ) } +/// The byte length of the string literal or quoted identifier starting at byte `i` of `sql` +/// ('…', "…", $tag$…$tag$, or E'…' with backslash escapes), if one starts there. An +/// unterminated one runs to the end. +pub fn sql_literal_len(sql: &str, i: usize) -> Option { + let rest = &sql[i..]; + let after_ident = sql[..i] + .chars() + .next_back() + .is_some_and(|c| c.is_alphanumeric() || c == '_'); + match rest.as_bytes()[0] { + b'E' | b'e' if !after_ident && rest[1..].starts_with('\'') => { + let bytes = rest.as_bytes(); + let mut j = 2; + while j < bytes.len() { + match bytes[j] { + b'\\' => j += 2, + b'\'' if bytes.get(j + 1) == Some(&b'\'') => j += 2, + b'\'' => return Some(j + 1), + _ => j += 1, + } + } + Some(rest.len()) + } + q @ (b'\'' | b'"') => Some(rest[1..].find(q as char).map_or(rest.len(), |e| e + 2)), + b'$' => rest[1..] + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .filter(|&n| rest[1 + n..].starts_with('$')) + .map(|n| { + let delim = &rest[..n + 2]; + rest[n + 2..] + .find(delim) + .map_or(rest.len(), |e| n + 2 + e + delim.len()) + }), + _ => None, + } +} + +/// Replaces each SQL comment outside string literals ([`sql_literal_len`]) with a space, +/// following DuckDB: `--` runs to the end of the line and `/* */` nests. An unterminated block +/// comment is kept as is, so the statement it ends up in fails to parse rather than silently +/// losing what follows. +pub fn strip_sql_comments(sql: &str) -> String { + let mut out = String::with_capacity(sql.len()); + let mut i = 0; + while i < sql.len() { + let rest = &sql[i..]; + if let Some(len) = sql_literal_len(sql, i) { + out.push_str(&rest[..len]); + i += len; + } else if rest.starts_with("--") { + i += rest.find('\n').unwrap_or(rest.len()); + out.push(' '); + } else if rest.starts_with("/*") { + let (mut depth, mut j) = (1usize, 2); + while depth > 0 && j < rest.len() { + if rest[j..].starts_with("/*") { + (depth, j) = (depth + 1, j + 2); + } else if rest[j..].starts_with("*/") { + (depth, j) = (depth - 1, j + 2); + } else { + j += rest[j..].chars().next().map_or(1, char::len_utf8); + } + } + if depth > 0 { + out.push_str(rest); + break; + } + out.push(' '); + i += j; + } else { + let c = rest.chars().next().unwrap(); + out.push(c); + i += c.len_utf8(); + } + } + out +} + /// Strip `METADATA_SCHEMA` / `DATA_PATH` / `OVERRIDE_DATA_PATH` tokens from ducklake ATTACH /// extra args. In a fork these options are injected by the fork resolution; a user- or -/// settings-supplied duplicate silently wins (DuckDB keeps the last occurrence) and would +/// settings-supplied duplicate silently wins (the worker keeps the last occurrence) and would /// escape the fork namespace back to the parent's, so they are removed rather than overridden. pub fn strip_fork_reserved_attach_args(extra_args: &str) -> String { lazy_static::lazy_static! { @@ -2826,8 +2904,10 @@ pub fn strip_fork_reserved_attach_args(extra_args: &str) -> String { ) .unwrap(); } + // Comments go first: the fork-owned options are appended after these args, and a trailing + // `-- …` would otherwise comment them out of the ATTACH. RESERVED - .replace_all(extra_args, "") + .replace_all(&strip_sql_comments(extra_args), "") .split(',') .map(str::trim) .filter(|s| !s.is_empty()) @@ -4280,6 +4360,19 @@ mod tests { strip_fork_reserved_attach_args("METADATA_SCHEMA 'wm_fork_evil'"), "" ); + // A trailing comment must not survive to comment out the fork options appended after. + assert_eq!( + strip_fork_reserved_attach_args("READ_ONLY false -- why, '/*'"), + "READ_ONLY false" + ); + assert_eq!( + strip_sql_comments("a /* x /* y */ x */ b '--' $q$/*$q$ -- c\nd /* open"), + "a b '--' $q$/*$q$ \nd /* open" + ); + assert_eq!( + strip_sql_comments(r"x E'a\'/* k */\'b' /* d */ e'c''/*'"), + r"x E'a\'/* k */\'b' e'c''/*'" + ); } #[test] diff --git a/backend/windmill-duckdb-ffi-internal/Cargo.lock b/backend/windmill-duckdb-ffi-internal/Cargo.lock index 74cd7b8a18..b5a36aeee8 100644 --- a/backend/windmill-duckdb-ffi-internal/Cargo.lock +++ b/backend/windmill-duckdb-ffi-internal/Cargo.lock @@ -51,15 +51,6 @@ dependencies = [ "libc", ] -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arrayvec" version = "0.7.8" @@ -68,9 +59,9 @@ checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cfdd0833e32a9874d2b55089333ad310c0be208aafa277385ce2461dec90be3" +checksum = "234ce58e76c04e8162c2e4bc3fe53fa7c2418ef5fba7bb2838b8531b7d4fbf14" dependencies = [ "arrow-arith", "arrow-array", @@ -86,9 +77,9 @@ dependencies = [ [[package]] name = "arrow-arith" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a41203398f0eaa6f7ec8e62c0da742a21abf282c148fc157f6c35c90e29981a" +checksum = "2303ebedb1071f4f72d71171e383859a9a285c94d99e4892685a96fca9890720" dependencies = [ "arrow-array", "arrow-buffer", @@ -100,9 +91,9 @@ dependencies = [ [[package]] name = "arrow-array" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae33dad492b7df00a217563a7b0ef2874df68a0deea1b1a3acf628152f7f7a69" +checksum = "51dff6e4b9f158864a0aeb6a131ad53858ecbae7a2fc8989307b9b3c6b2f122e" dependencies = [ "ahash 0.8.12", "arrow-buffer", @@ -111,6 +102,7 @@ dependencies = [ "chrono", "half", "hashbrown 0.17.1", + "libc", "num-complex", "num-integer", "num-traits", @@ -118,9 +110,9 @@ dependencies = [ [[package]] name = "arrow-buffer" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9552f96391c005e6ab449fa941420935e7e062489b12b8b1b08879b2163f5b5" +checksum = "c7235b863533e9db3ab86905b4521251de11226275b436ff3cb2d0010558d1c5" dependencies = [ "bytes", "half", @@ -130,9 +122,9 @@ dependencies = [ [[package]] name = "arrow-cast" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a8a327c9649f30d8406995f27642b68df354713cca3baaaf100f076f18d5f34" +checksum = "d52cf840f0c34aeeb7e8b05aba72d66878e6c001827f423331f0b260209e7b7e" dependencies = [ "arrow-array", "arrow-buffer", @@ -141,7 +133,7 @@ dependencies = [ "arrow-schema", "arrow-select", "atoi", - "base64 0.22.1", + "base64", "chrono", "comfy-table", "half", @@ -151,10 +143,21 @@ dependencies = [ ] [[package]] -name = "arrow-data" -version = "58.4.0" +name = "arrow-cmp" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b24852db04738907e06c04ea61e42fe7fda962a34513022dc0d0e754fb7976b" +checksum = "73a0e9adb28d95739fabcdae637261a2c14e618caf58ba1b88857120f9ee2687" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-schema", +] + +[[package]] +name = "arrow-data" +version = "60.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa06d5e22786c4966ffc4d2f171d0cb65d95f6bdea108a14e8c335e9faa437f" dependencies = [ "arrow-buffer", "arrow-schema", @@ -165,12 +168,13 @@ dependencies = [ [[package]] name = "arrow-ord" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63a083ec750f5c043f02946b4baf05fcdbb55f4560a3277055caca5cc99f3eb0" +checksum = "5a7ac2c6a9cdc782fa9548d3763461eaec8c93347e297fddbaa44807e70a3698" dependencies = [ "arrow-array", "arrow-buffer", + "arrow-cmp", "arrow-data", "arrow-schema", "arrow-select", @@ -178,9 +182,9 @@ dependencies = [ [[package]] name = "arrow-row" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "514ba0ef0d4c5896202dae736251ce415abb43a950bed570fb7981b8716c0e4c" +checksum = "758b87e9648d80001e0916c083334ed93074c677a81a96144d5c84bd2d8eab2a" dependencies = [ "arrow-array", "arrow-buffer", @@ -191,22 +195,23 @@ dependencies = [ [[package]] name = "arrow-schema" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21ca356ad6425cecb6eb7b28e4f659f1ee7880fbb1a16127de7dd62901efee9e" +checksum = "f85a9a58cd03560526b0066487574aacb9008e413504fa0ee23d61141e96c338" dependencies = [ "bitflags", ] [[package]] name = "arrow-select" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c58da39eb3d8350ad4a549e5c2bc49284dac554016c69829310350f1731b0aad" +checksum = "ba3482b7d03bf4a3bf0b195f08a7f2b071595ccd54897e35b975ac63d3104977" dependencies = [ "ahash 0.8.12", "arrow-array", "arrow-buffer", + "arrow-cmp", "arrow-data", "arrow-schema", "num-traits", @@ -214,9 +219,9 @@ dependencies = [ [[package]] name = "arrow-string" -version = "58.4.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6789b388467525e3271326b6b4915666ecfdf5142aef09779445c954b67543c" +checksum = "f300b4400b1e7cd58f7cbbd5dd2a0072cc59e73bfaee2a152b3ac660e46d9dd1" dependencies = [ "arrow-array", "arrow-buffer", @@ -231,9 +236,9 @@ dependencies = [ [[package]] name = "atoi" -version = "2.0.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +checksum = "d12c37257553c19e9aee6cba77814fdc9e07844abfc8b3a2c377cd920ee5a993" dependencies = [ "num-traits", ] @@ -244,12 +249,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - [[package]] name = "base64" version = "0.23.1" @@ -274,6 +273,15 @@ dependencies = [ "wyz", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "borsh" version = "1.8.0" @@ -377,15 +385,20 @@ dependencies = [ [[package]] name = "comfy-table" -version = "7.1.4" +version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a65ebfec4fb190b6f90e944a817d60499ee0744e582530e2c9900a22e591d9a" +checksum = "b96a46ad395a5e00676eddaca4a45ed78b29c08be5a878d35e4b071c625637dd" dependencies = [ - "crossterm", "unicode-segmentation", "unicode-width", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const-random" version = "0.1.18" @@ -412,6 +425,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.0" @@ -421,28 +443,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossterm" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" -dependencies = [ - "bitflags", - "crossterm_winapi", - "parking_lot", - "rustix 0.38.44", - "winapi", -] - -[[package]] -name = "crossterm_winapi" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" -dependencies = [ - "winapi", -] - [[package]] name = "crunchy" version = "0.2.4" @@ -450,25 +450,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] -name = "derive_arbitrary" -version = "1.4.2" +name = "crypto-common" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", ] [[package]] name = "duckdb" -version = "1.10506.0" +version = "1.20000.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3472b9152d879c5534353b20854e43525b2c78b2dbba156711e9939d30278b4" +checksum = "d807ca47d4fa206f102ff568046e018fb84518eb0a0b5e65a165a2eb7bd4a7c2" dependencies = [ "arrow", "cast", - "comfy-table", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -530,7 +538,6 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", "miniz_oxide", - "zlib-rs", ] [[package]] @@ -670,6 +677,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -796,19 +812,19 @@ checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] name = "libduckdb-sys" -version = "1.10506.0" +version = "1.20000.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aac3459f2f7f0221d5be9114fa77ff5877040c8de456d3b986a680579fe202b" +checksum = "0140448c472968ee5cf5ba697435deebe558b366ef1e5c080d24d9696b600725" dependencies = [ "cc", "flate2", "pkg-config", "serde", "serde_json", + "sha2", "tar", "ureq", "vcpkg", - "zip", ] [[package]] @@ -817,27 +833,12 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" -[[package]] -name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - [[package]] name = "linux-raw-sys" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - [[package]] name = "log" version = "0.4.33" @@ -862,9 +863,9 @@ dependencies = [ [[package]] name = "num-bigint" -version = "0.4.8" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" dependencies = [ "num-integer", "num-traits", @@ -904,29 +905,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - [[package]] name = "percent-encoding" version = "2.3.2" @@ -1049,15 +1027,6 @@ dependencies = [ "getrandom 0.2.17", ] -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - [[package]] name = "regex" version = "1.13.1" @@ -1156,19 +1125,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "rustix" -version = "0.38.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", -] - [[package]] name = "rustix" version = "1.1.4" @@ -1178,7 +1134,7 @@ dependencies = [ "bitflags", "errno", "libc", - "linux-raw-sys 0.12.1", + "linux-raw-sys", "windows-sys 0.61.2", ] @@ -1229,12 +1185,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - [[package]] name = "seahash" version = "4.1.0" @@ -1285,6 +1235,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -1309,12 +1270,6 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" - [[package]] name = "strum" version = "0.27.2" @@ -1446,6 +1401,12 @@ dependencies = [ "winnow", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -1476,7 +1437,7 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "972d7902c8735f2695410b8aed7df6ed12a47394aa1c8d7af49f0497b731a94d" dependencies = [ - "base64 0.23.1", + "base64", "log", "percent-encoding", "rustls", @@ -1492,7 +1453,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da5f78b09e6941e1a0f2e30e695e4b120377b54d5e0aec11b594bb57b3971613" dependencies = [ - "base64 0.23.1", + "base64", "http", "httparse", "log", @@ -1596,28 +1557,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "windmill_duckdb_ffi_internal" version = "0.1.0" @@ -1698,15 +1637,6 @@ dependencies = [ "windows-targets", ] -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -1811,7 +1741,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.4", + "rustix", ] [[package]] @@ -1840,40 +1770,8 @@ version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" -[[package]] -name = "zip" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb2a05c7c36fde6c09b08576c9f7fb4cda705990f73b58fe011abf7dfb24168b" -dependencies = [ - "arbitrary", - "crc32fast", - "flate2", - "indexmap", - "memchr", - "zopfli", -] - -[[package]] -name = "zlib-rs" -version = "0.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" - [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - -[[package]] -name = "zopfli" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] diff --git a/backend/windmill-duckdb-ffi-internal/Cargo.toml b/backend/windmill-duckdb-ffi-internal/Cargo.toml index ba78e3522d..7a2bffc553 100644 --- a/backend/windmill-duckdb-ffi-internal/Cargo.toml +++ b/backend/windmill-duckdb-ffi-internal/Cargo.toml @@ -13,7 +13,7 @@ chrono = "0.4.41" # # Pinned exactly, so `cargo update` cannot move the engine (and the prebuilt extensions it # must match) under us. -duckdb = { version = "=1.10506.0", features = [ +duckdb = { version = "=1.20000.1", features = [ "bundled", "rust_decimal", ] } diff --git a/backend/windmill-duckdb-ffi-internal/src/lib.rs b/backend/windmill-duckdb-ffi-internal/src/lib.rs index 0de7d3bd79..3efbce038c 100644 --- a/backend/windmill-duckdb-ffi-internal/src/lib.rs +++ b/backend/windmill-duckdb-ffi-internal/src/lib.rs @@ -219,6 +219,22 @@ fn configure_duckdb_resource_limits( Ok(()) } +// DuckDB 2.0 defaults that would change what a script written for 1.x returns, reverted so it +// keeps running unchanged; a script can SET any of them back. Without `legacy_disable_null_type` +// an untyped `NULL` column has the NULL type, which duckdb-rs cannot read and panics on. The +// storage version keeps `.duckdb` files a script writes readable by 1.x. `lambda_syntax` is +// removed in DuckDB 2.1, which will make `x -> ...` lambdas an error again. +fn keep_duckdb_1x_semantics(conn: &duckdb::Connection) -> Result<(), String> { + conn.execute_batch( + "SET lambda_syntax='enable_single_arrow'; + SET error_on_division_by_zero=false; + SET legacy_disable_null_type=true; + SET regex_match_operator_semantics='full'; + SET storage_compatibility_version='v0.10.2';", + ) + .map_err(|e| format!("Error applying DuckDB 1.x compatibility settings: {e}")) +} + fn setup_duckdb_connection( conn: &duckdb::Connection, token: &str, @@ -227,6 +243,7 @@ fn setup_duckdb_connection( limits: &ResourceLimits, ) -> Result<(), String> { configure_duckdb_resource_limits(conn, limits)?; + keep_duckdb_1x_semantics(conn)?; let (s3_access_key, s3_secret_key) = token.rsplit_once('.').unwrap_or(("", token)); let (s3_endpoint_ssl, s3_endpoint) = base_internal_url @@ -240,8 +257,11 @@ fn setup_duckdb_connection( let s3_secret_key = sql_single_quote(s3_secret_key); let endpoint = sql_single_quote(&format!("{s3_endpoint}/api/w/{w_id}/s3_proxy")); + // `s3_uploader_max_filesize` is DuckDB 1.x's cap on one multipart upload; 2.0 lowered it to + // 80GB. It is an httpfs setting, so it can only be set once httpfs is loaded. conn.execute_batch(&format!( "INSTALL httpfs; LOAD httpfs; + SET s3_uploader_max_filesize='800GB'; INSTALL azure; LOAD azure; CREATE OR REPLACE SECRET s3_secret ( TYPE s3, @@ -1016,6 +1036,36 @@ mod temporal_json_tests { ); } + #[test] + fn scripts_written_for_duckdb_1x_keep_their_semantics() { + let conn = duckdb::Connection::open_in_memory().unwrap(); + keep_duckdb_1x_semantics(&conn).unwrap(); + let (lambda, int_div, modulo): (String, Option, Option) = conn + .query_row( + "SELECT list_transform([1, 2], x -> x + 1)::VARCHAR, 1 // 0, 1 % 0", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .unwrap(); + assert_eq!(lambda, "[2, 3]"); + assert_eq!((int_div, modulo), (None, None)); + + // Read as a `Value`, the way results are rendered: an untyped NULL column panics there + // without `legacy_disable_null_type`. + let (untyped_null, nested_null, partial_match): ( + duckdb::types::Value, + duckdb::types::Value, + bool, + ) = conn + .query_row("SELECT NULL, {'a': NULL}, 'foobar' ~ 'foo'", [], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?)) + }) + .unwrap(); + assert_eq!(untyped_null, duckdb::types::Value::Null); + assert!(matches!(nested_null, duckdb::types::Value::Struct(_))); + assert!(!partial_match, "`~` must keep matching the whole string"); + } + #[test] fn temporal_values_render_iso_through_real_query() { let conn = duckdb::Connection::open_in_memory().unwrap(); diff --git a/backend/windmill-worker/src/duckdb_executor.rs b/backend/windmill-worker/src/duckdb_executor.rs index 0db954d85f..8c3bab10ed 100644 --- a/backend/windmill-worker/src/duckdb_executor.rs +++ b/backend/windmill-worker/src/duckdb_executor.rs @@ -10,7 +10,7 @@ use windmill_common::utils::sanitize_string_from_password; use windmill_common::worker::{get_memory, to_raw_value, Connection, SqlResultCollectionStrategy}; use windmill_common::workspaces::{ get_datatable_resource_from_db, get_ducklake_from_db_unchecked, - strip_fork_reserved_attach_args, DatatableAccess, DatatableConnectAs, + sql_literal_len, strip_fork_reserved_attach_args, strip_sql_comments, DatatableAccess, DatatableConnectAs, DucklakeCatalogResourceType, }; use windmill_common::PgDatabase; @@ -1602,7 +1602,6 @@ pub async fn do_duckdb( ) .await?; - let base_internal_url = client.base_internal_url.clone(); let w_id = job.workspace_id.clone(); let job_dir = job_dir.to_string(); @@ -2234,11 +2233,18 @@ async fn db_resource_to_attach_statements( ) .to_string(); - Ok(vec![ + let mut statements = vec![ get_attach_db_install_str(db_type)?.to_string(), format!("LOAD {};", db_type), - attach_str, - ]) + ]; + // DuckDB 2.0's MySQL scanner hands whole queries to the server by default, which turns + // binary-collated text into BLOB and moves grouping to MySQL's collation. Read when the + // ATTACH runs, so it has to precede it. + if db_type == "mysql" { + statements.push("SET mysql_enable_remote_pushdown=false;".to_string()); + } + statements.push(attach_str); + Ok(statements) } async fn transform_attach_ducklake( @@ -2267,7 +2273,7 @@ async fn transform_attach_ducklake( Connection::Sql(db) => get_ducklake_from_db_unchecked(name, w_id, db).await?, }; // In a fork, METADATA_SCHEMA / DATA_PATH / OVERRIDE_DATA_PATH are owned by the fork - // resolution (DuckDB silently keeps the last occurrence of a duplicated option, so a + // resolution (the last occurrence of a duplicated option is the one kept, so a // user-supplied one would escape the fork namespace back to the parent's). let user_extra_args = if ducklake.fork_defer.is_some() { strip_fork_reserved_attach_args(&user_extra_args) @@ -2308,37 +2314,18 @@ async fn transform_attach_ducklake( let data_path = ducklake.storage.path.replace('\'', "''"); let extra_args = if let Some(default_extra_args) = ducklake.extra_args { - format!("{},{}", extra_args, default_extra_args) + // A newline, so a trailing `--` comment in the script's args ends before the config's. + format!("{}\n,{}", extra_args, default_extra_args) } else { extra_args }; - // Ducklake 0.3 only requires DATA_PATH at creation and then stores it internally in the catalog - // But it will fail if DATA_PATH changes afterwards which is annoying for us - // So we always enable override - let extra_args = if extra_args.contains("OVERRIDE_DATA_PATH") { - extra_args - } else { - format!(", OVERRIDE_DATA_PATH TRUE{extra_args}") - }; - // Automatically migrate ducklake - let extra_args = if extra_args.contains("AUTOMATIC_MIGRATION") { - extra_args - } else { - format!(", AUTOMATIC_MIGRATION TRUE{extra_args}") - }; - // In a fork, re-emit the fork-owned DATA_PATH as the LAST option: DuckDB keeps the last - // occurrence of a duplicated option, so this wins over anything the arg stripping might - // not recognize (e.g. a dollar-quoted literal), regardless of literal syntax. The - // METADATA_SCHEMA injected by the fork resolution is already last within `extra_args`. - let extra_args = if ducklake.fork_defer.is_some() { - format!("{extra_args}, DATA_PATH 's3://{storage}/{data_path}'") - } else { - extra_args - }; - - let attach_str = format!( - "ATTACH 'ducklake:{db_type}:{db_conn_str}' AS {alias_name} (DATA_PATH 's3://{storage}/{data_path}'{extra_args});", + let options = ducklake_attach_options( + &format!("s3://{storage}/{data_path}"), + &extra_args, + ducklake.fork_defer.is_some(), ); + let attach_str = + format!("ATTACH 'ducklake:{db_type}:{db_conn_str}' AS {alias_name} ({options});"); let install_db_ext_str = get_attach_db_install_str(db_type)?; let mut statements = vec![ @@ -2359,6 +2346,86 @@ async fn transform_attach_ducklake( Ok(Some(statements)) } +/// The option list of a lake's ATTACH. `extra_args` are the script's then the lake config's, +/// each part prefixed by a comma; later options override earlier ones, so Windmill's defaults +/// come first and, in a fork, the fork-owned DATA_PATH last (it must win over anything the +/// reserved-arg stripping did not recognize, e.g. a dollar-quoted literal). +fn ducklake_attach_options(data_path: &str, extra_args: &str, fork: bool) -> String { + // OVERRIDE_DATA_PATH: DuckLake stores DATA_PATH at creation and refuses a different one + // afterwards. DUCKLAKE_VERSION '1.0': a catalog migrated to 1.1 cannot be downgraded and is + // unreadable by DuckDB 1.x engines, so one job on an upgraded worker would break every older + // worker and any rollback. Unpinned, AUTOMATIC_MIGRATION targets the newest format and new + // catalogs are created at it. + let mut options = format!( + "DATA_PATH '{data_path}', OVERRIDE_DATA_PATH TRUE, AUTOMATIC_MIGRATION TRUE, \ + DUCKLAKE_VERSION '1.0'{extra_args}" + ); + if fork { + options.push_str(&format!("\n, DATA_PATH '{data_path}'")); + } + keep_last_attach_option(&options) +} + +/// Drops every occurrence of an ATTACH option but its last. DuckDB 1.x kept the last of +/// duplicated options; 2.0 rejects the statement ("Unexpected duplicate option"). +fn keep_last_attach_option(options: &str) -> String { + let parts = split_attach_options(options); + let key = |part: &str| -> String { + match part.strip_prefix('"') { + Some(quoted) => quoted.split('"').next().unwrap_or_default().to_string(), + None => part + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(), + } + .to_ascii_uppercase() + }; + let keys: Vec = parts.iter().map(|p| key(p)).collect(); + parts + .iter() + .enumerate() + .filter(|(i, _)| keys[i + 1..].iter().all(|k| k.is_empty() || *k != keys[*i])) + .map(|(_, p)| p.as_str()) + .collect::>() + .join(", ") +} + +/// Splits an ATTACH option list on the commas outside string literals ([`sql_literal_len`]) +/// and parentheses, dropping empty parts. SQL comments are dropped too: a `--` comment would +/// otherwise swallow whatever is joined after it on the same line, `);` included. +fn split_attach_options(options: &str) -> Vec { + let options = strip_sql_comments(options); + let options = options.as_str(); + let mut parts = vec![]; + let mut part = String::new(); + let mut depth = 0usize; + let mut i = 0; + while i < options.len() { + let rest = &options[i..]; + if let Some(len) = sql_literal_len(options, i) { + part.push_str(&rest[..len]); + i += len; + continue; + } + let c = rest.chars().next().unwrap(); + match c { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + parts.push(std::mem::take(&mut part).trim().to_string()); + i += 1; + continue; + } + _ => {} + } + part.push(c); + i += c.len_utf8(); + } + parts.push(part.trim().to_string()); + parts.retain(|p| !p.is_empty()); + parts +} + // Double-quote a possibly schema-qualified table reference, each dotted segment // independently (local copy of sql_materialize's private helper). fn quote_qualified_table(name: &str) -> String { @@ -2420,8 +2487,8 @@ fn fork_defer_statements( .map(|s| format!(", METADATA_SCHEMA '{}'", s.replace('\'', "''"))) .unwrap_or_default(); // The ancestor config's own non-reserved args (e.g. `ENCRYPTED true`) — an - // option-dependent lake wouldn't attach without them. Emitted FIRST: DuckDB keeps the - // last occurrence of a duplicated option, so the fork-owned DATA_PATH / READ_ONLY / + // option-dependent lake wouldn't attach without them. Emitted FIRST: the last occurrence + // of a duplicated option is the one kept, so the fork-owned DATA_PATH / READ_ONLY / // METADATA_SCHEMA after them always win. let extra_args = a .extra_args @@ -2432,8 +2499,11 @@ fn fork_defer_statements( // / CREATE_IF_NOT_EXISTS: an ancestor lake that would need creating or migrating fails // loudly rather than being mutated from a fork. IF NOT EXISTS: several ATTACH blocks in // one script (e.g. the user's + the materialize synthetic one) emit the same ancestors. + let options = keep_last_attach_option(&format!( + "{extra_args}DATA_PATH 's3://{storage}/{data_path}', OVERRIDE_DATA_PATH TRUE, READ_ONLY{metadata_schema}" + )); stmts.push(format!( - "ATTACH IF NOT EXISTS 'ducklake:{db_type}:{conn_str}' AS {} ({extra_args}DATA_PATH 's3://{storage}/{data_path}', OVERRIDE_DATA_PATH TRUE, READ_ONLY{metadata_schema});", + "ATTACH IF NOT EXISTS 'ducklake:{db_type}:{conn_str}' AS {} ({options});", a.alias )); } @@ -2906,6 +2976,40 @@ mod tests { ) } + #[test] + fn ducklake_attach_pins_catalog_format_and_never_repeats_an_option() { + assert_eq!( + ducklake_attach_options("s3://b/p", "", false), + "DATA_PATH 's3://b/p', OVERRIDE_DATA_PATH TRUE, AUTOMATIC_MIGRATION TRUE, \ + DUCKLAKE_VERSION '1.0'" + ); + // The script's then the lake config's args override the defaults; in a fork the + // fork-owned DATA_PATH overrides everything. + assert_eq!( + ducklake_attach_options( + "s3://b/fork", + ", data_path 's3://b/parent', ducklake_version '1.1',METADATA_SCHEMA 'a,b'", + true + ), + "OVERRIDE_DATA_PATH TRUE, AUTOMATIC_MIGRATION TRUE, ducklake_version '1.1', \ + METADATA_SCHEMA 'a,b', DATA_PATH 's3://b/fork'" + ); + assert_eq!( + keep_last_attach_option("X 'it''s, ok', ENCRYPTED $t$a, b$t$, X 1, f(a, b)"), + "ENCRYPTED $t$a, b$t$, X 1, f(a, b)" + ); + assert_eq!( + keep_last_attach_option( + "DATA_PATH 'a', \"data_path\" 'b', READ_ONLY false -- why, it is\n, /* x, */ E 1" + ), + "\"data_path\" 'b', READ_ONLY false, E 1" + ); + assert_eq!( + keep_last_attach_option("READ_ONLY false /* a /* b, */ c, */, E 1"), + "READ_ONLY false, E 1" + ); + } + #[test] fn test_fork_defer_statements_ancestor_extra_args() { // The ancestor config's own args (e.g. ENCRYPTED) must ride on its read-only attach — diff --git a/backend/windmill-worker/src/duckdb_runner.rs b/backend/windmill-worker/src/duckdb_runner.rs index 56b3c1f5cc..68e4912834 100644 --- a/backend/windmill-worker/src/duckdb_runner.rs +++ b/backend/windmill-worker/src/duckdb_runner.rs @@ -293,11 +293,28 @@ fn parse_duckdb_size(s: &str) -> Option { Some((num * mult) as u64) } +/// DuckDB's prebuilt linux_amd64 extensions target x86-64-v3, and every job loads httpfs, so +/// on a CPU without AVX2 the runner would die with SIGILL and an opaque crash message. +fn check_cpu_supported() -> Result<()> { + #[cfg(all(target_arch = "x86_64", target_os = "linux"))] + if !std::arch::is_x86_feature_detected!("avx2") { + return Err(Error::ExecutionErr( + "DuckDB requires a CPU with AVX2 (x86-64-v3): its extensions crash on this worker's \ + CPU. On a VM, set the CPU type to `host` or `x86-64-v3` (Proxmox's default \ + `x86-64-v2-AES` hides AVX2; on VMware, raise the EVC mode to Haswell or later), or \ + run DuckDB jobs on a worker group with a newer CPU." + .to_string(), + )); + } + Ok(()) +} + pub(crate) async fn run( mode: RunnerMode, req: &RunnerRequest<'_>, job_dir: &str, ) -> Result { + check_cpu_supported()?; let spill_dir = format!("{}/spill", work_dir(job_dir)); tokio::fs::create_dir_all(&spill_dir).await?; let req = RunnerRequest { temp_directory: &spill_dir, ..*req }; diff --git a/docs/duckdb-execution.md b/docs/duckdb-execution.md index 70f9218ee4..42afe5fc5f 100644 --- a/docs/duckdb-execution.md +++ b/docs/duckdb-execution.md @@ -81,9 +81,43 @@ affects its own connection, and is no more than a Python job could do. ## The engine -The runner links duckdb-rs from crates.io, pinned with `=` so `cargo update` cannot move the -engine. The engine loads the **prebuilt** extensions from `extensions.duckdb.org`, compiled for the -exact release it reports, so an engine bump is a version change in `Cargo.toml` and nothing else. +The runner links duckdb-rs pinned exactly (`=`) so `cargo update` cannot move the engine. The engine loads the **prebuilt** extensions from `extensions.duckdb.org`, +compiled for the exact release it reports, so an engine bump is a version change in `Cargo.toml` +and nothing else. The reported version comes from the vendored sources' `pragma_version.cpp`: a +build that calls itself `vX.Y.Z-devN` downloads from a per-commit path that does not exist, and +every extension `INSTALL` 404s. Check `SELECT version()` after a bump. + +The engine is built from source with baseline flags, but the prebuilt 2.0 linux_amd64 extensions +are compiled for x86-64-v3: on a CPU without AVX2 (pre-Haswell, or a VM CPU model such as +Proxmox's `x86-64-v2-AES` or a low VMware EVC baseline) `LOAD httpfs` dies with SIGILL, and +every job loads httpfs. `duckdb_runner::run` therefore fails the job up front on such a CPU, with +a message naming the VM settings to change, rather than letting the runner crash. linux_arm64 +extensions run on Cortex-A53 and later. + +What a bump can break is user scripts and shared state, so a major one keeps the previous major's +behavior and leaves the new one opt-in: + +- `setup_duckdb_connection` reverts the defaults DuckDB 2.0 changed that would make a query that + worked on 1.x return something else: `x -> …` lambdas, `NULL` for integer `//` / `%` by zero, + untyped `NULL` columns typed INTEGER (the 2.0 NULL type makes duckdb-rs panic on read), + whole-string `~`, `.duckdb` files written at a version 1.x can open, and the 800GB S3 upload + cap. A script can `SET` any of them back. DuckDB 2.1 removes `lambda_syntax`, and the setting + has to go then. +- `ieee_floating_point_ops` stays at 2.0's default on purpose. Turning it off does not restore + 1.x: `/` by zero then returns `NULL` where 1.x returned infinity. Left on, the only change is + that `sqrt(-1)`, `ln(0)` and the like return NaN instead of erroring. +- MySQL resource attaches turn off `mysql_enable_remote_pushdown`, which is read when the + ATTACH runs. Left on, binary-collated text comes back as BLOB and grouping follows MySQL's + collation. +- What no setting restores: auto-generated names of unaliased expressions (`main.` prefixes + dropped), unnamed structs rendered as `element1`… instead of a single `""` key, JSON + auto-detection typing offset timestamps as TIMESTAMPTZ, `GROUP BY ALL` over an `UNNEST` + erroring, `X'..'` literals typed BLOB, and Parquet columns from constants written REQUIRED. +- `transform_attach_ducklake` attaches lakes with `DUCKLAKE_VERSION '1.0'` unless the lake's + extra args name one. Windmill also passes `AUTOMATIC_MIGRATION TRUE`, which unpinned migrates to + the newest catalog format. A migrated catalog cannot be downgraded and older engines cannot read + it, so a mixed-version worker fleet or a rollback would lose the lake. A lake opts into 1.1 + with `DUCKLAKE_VERSION '1.1'` in its extra args, once no worker runs DuckDB 1.x. Confinement belongs to the job isolation, not to engine settings. DuckDB spills through the same file system a query reads with, so `disabled_filesystems='LocalFileSystem'` also stops every query diff --git a/frontend/src/lib/infer.svelte.ts b/frontend/src/lib/infer.svelte.ts index cc34fc64fa..8e153d0780 100644 --- a/frontend/src/lib/infer.svelte.ts +++ b/frontend/src/lib/infer.svelte.ts @@ -70,9 +70,14 @@ type QueryEntry = [string, InferAssetsSqlQueryDetails] // DuckDB prepare replaces $N params with NULL. Some functions (read_parquet, read_csv, etc.) // reject NULL arguments, which is expected — the query will work at execution time with real args. +// DuckDB 1.x says "cannot take NULL"; 2.0 reports the NULL as an argument no overload accepts. function isNullParamSubstitutionError(error?: string): boolean { if (!error) return false - return error.includes('cannot take NULL') || error.includes('Could not choose a best candidate') + return ( + error.includes('cannot take NULL') || + error.includes('Could not choose a best candidate') || + error.includes('No function matches the given name and argument types') + ) } function mapPrepareResults( From 23fbf1edfe62339eaff2b576aeea32d81e37d97b Mon Sep 17 00:00:00 2001 From: hugocasa Date: Mon, 2 Nov 2026 16:00:50 +0100 Subject: [PATCH 3/7] feat: publish a folder sub-path to the Hub as its own project (#12081) * feat: accept nested folder paths for Hub project publish and import A Hub project can be published from, and imported into, a sub-path of a folder (`hub/billing`, i.e. items under `f/hub/billing/...`). The backend folder check and the import wizard's folder check accept `/`-separated segments; an import into a nested destination creates only the base folder. Co-Authored-By: Claude Opus 5.5 * docs: describe nested folder source keys on HubPublishCtx Co-Authored-By: Claude Opus 5.5 * feat: choose a folder sub-path when publishing to or importing from the Hub Publishing keeps each item's sub-path under the project slug instead of flattening items outside `f//` to their last segment, so a nested source folder is bundled like a root one. The publish drawer gets a scope select listing the folder's sub-paths, and the import wizard an optional sub-path field next to the folder picker. A nested project's name defaults to its last segment. Co-Authored-By: Claude Opus 5.5 * feat: pick the Hub publish scope from a folder tree, drop nested import Co-Authored-By: Claude Opus 5.5 * feat: show sub-folders already published to the Hub in the publish drawer Co-Authored-By: Claude Opus 5.5 * feat: open the Hub publish drawer on the folder's projects, tree only for a new one Co-Authored-By: Claude Opus 5.5 * fix: let the last sub-folder become a Hub project and keep other projects' items out of updates Co-Authored-By: Claude Opus 5.5 * fix: open sub-folder Hub projects from a list and block only nested projects on update Co-Authored-By: Claude Opus 5.5 * refactor: render the Hub project list with ListRow Co-Authored-By: Claude Opus 5.5 * revert: keep the Hub project list as bordered card rows like the drawer's other lists Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- backend/windmill-api/src/hub_publish.rs | 44 +++- .../components/WorkspaceDeployLayout.svelte | 207 ++++++++++++------ .../lib/components/home/TreeOwnerRow.svelte | 9 + .../src/lib/components/home/TreeView.svelte | 23 +- .../lib/components/home/TreeViewRoot.svelte | 10 +- .../workspaceSettings/DeployToHub.svelte | 180 ++++++++++++++- .../deployToHubItems.test.ts | 25 +++ .../workspaceSettings/deployToHubItems.ts | 34 +++ .../deployToHubSession.svelte.ts | 143 ++++++++++-- .../workspaceSettings/projectBundle.test.ts | 14 ++ .../workspaceSettings/projectBundle.ts | 26 ++- 11 files changed, 606 insertions(+), 109 deletions(-) diff --git a/backend/windmill-api/src/hub_publish.rs b/backend/windmill-api/src/hub_publish.rs index 4e79aba943..64154c3764 100644 --- a/backend/windmill-api/src/hub_publish.rs +++ b/backend/windmill-api/src/hub_publish.rs @@ -57,12 +57,16 @@ struct HubScope { folder: Option, } +/// A base folder name, or one followed by `/`-separated sub-path segments +/// (`hub/billing`): every segment non-empty, so no leading, trailing or doubled `/`. fn validate_folder(folder: &str) -> Result<(), Error> { - let ok = !folder.is_empty() - && folder.len() <= 255 - && folder - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'); + let ok = folder.len() <= 255 + && folder.split('/').all(|seg| { + !seg.is_empty() + && seg + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + }); if ok { Ok(()) } else { @@ -118,10 +122,11 @@ impl std::fmt::Display for ProjectSlug { /// Handlers can only reach the Hub via this extractor's methods, so a new /// endpoint cannot forget the admin check or folder validation. /// -/// A workspace can publish one Hub project per folder. The stable, never-mutated -/// link key is `workspace_id:folder_name` (folder name is the path segment and is +/// A workspace can publish one Hub project per folder or folder sub-path. The +/// stable, never-mutated link key is `workspace_id:folder` (`folder` is the base +/// folder name, optionally followed by `/`-separated sub-path segments, and is /// never renamed — only display_name changes). `:` is safe: neither workspace ids -/// nor folder names (alphanumeric, underscore, hyphen) contain it. +/// nor folder paths (alphanumeric, underscore, hyphen, `/`) contain it. struct HubPublishCtx { source_id: Option, token: String, @@ -740,7 +745,28 @@ async fn forward_to_hub( #[cfg(test)] mod tests { - use super::is_public_hub; + use super::{is_public_hub, validate_folder}; + + #[test] + fn folder_accepts_nested_sub_paths() { + for ok in ["hub", "my-folder_2", "hub/billing", "hub/billing/v-2"] { + assert!(validate_folder(ok).is_ok(), "{ok} should be valid"); + } + let too_long = format!("a/{}", "b".repeat(254)); + for bad in [ + "", + "/hub", + "hub/", + "hub//billing", + "hub/../x", + "hub/./x", + "hub/bil ling", + "hub\\billing", + too_long.as_str(), + ] { + assert!(validate_folder(bad).is_err(), "{bad} should be rejected"); + } + } #[test] fn public_hub_recognized_in_every_spelling() { diff --git a/frontend/src/lib/components/WorkspaceDeployLayout.svelte b/frontend/src/lib/components/WorkspaceDeployLayout.svelte index 62894ea508..1cd1f858f2 100644 --- a/frontend/src/lib/components/WorkspaceDeployLayout.svelte +++ b/frontend/src/lib/components/WorkspaceDeployLayout.svelte @@ -1,3 +1,7 @@ + + +{#snippet itemRow(item: DeployableItem, depth: number, subPath: string)} + {@const isSelectable = selectablePredicate(item)} + {@const isSelected = selectedItems.includes(item.key)} + {@const status = deploymentStatus[item.key]} + {@const isDeployed = status?.status === 'deployed'} + {@const blockedReason = !isSelectable && !isDeployed ? selectBlockedReason?.(item) : undefined} + + {@const showPath = + isAgent?.(item) || + (item.kind !== 'resource' && item.kind !== 'variable' && item.kind !== 'resource_type')} + + handleSelect(item)} + path={showPath ? item.path : ''} + marked={undefined} + kind={isAgent?.(item) ? 'agent' : item.kind} + triggerKind={item.triggerKind} + canFavorite={false} + workspaceId="" + {depth} + > + {#snippet customSummary()} + {#if itemSummary} + {@render itemSummary(item)} + {:else} + {item.path} + {/if} + {/snippet} + {#snippet pathDisplay()} + {#if itemPath} + {@render itemPath(item)} + {:else} + {showPath ? subPath : ''} + {/if} + {/snippet} + {#snippet actions()} + {#if itemActions} + {@render itemActions(item)} + {/if} + + {#if status} + {#if status.status === 'loading'} + + {:else if status.status === 'deployed'} + Deployed + {:else if status.status === 'failed'} +
+ Failed + {status.error} +
+ {/if} + {/if} + {/snippet} +
+{/snippet} + +{#snippet treeLeaf(leaf: ItemType, depth: number)} + {@const item = leaf as unknown as DeployableItem} + {@render itemRow(item, depth, item.path.split('/').pop() ?? item.path)} +{/snippet} + +{#snippet prefixCheckbox(prefix: string)} + {@const under = underPrefix(prefix)} + {@const selectable = bulkSelectable(under)} + {@const selectedCount = selectable.filter((i) => selectedItems.includes(i.key)).length} + 0 && selectedCount === selectable.length} + indeterminate={selectedCount > 0 && selectedCount < selectable.length} + disabled={selectable.length === 0} + title={selectedCount === selectable.length + ? `Deselect all in ${prefix}` + : `Select all in ${prefix}`} + onChange={() => toggleGroup({ items: under })} + /> +{/snippet} +
{#if header} @@ -197,7 +311,20 @@
{/if} - {#if items.length > 0} + {#if items.length > 0 && nested} +
+ {}} + sortCompare={(a, b) => a.path.localeCompare(b.path)} + leaf={treeLeaf} + ownerLead={hideSelection ? undefined : prefixCheckbox} + ownerDetail={folderDetail} + /> +
+ {:else if items.length > 0}
@@ -248,73 +375,15 @@
{/if} {#each group.items as item (item.key)} - {@const isSelectable = selectablePredicate(item)} - {@const isSelected = selectedItems.includes(item.key)} - {@const status = deploymentStatus[item.key]} - {@const isDeployed = status?.status === 'deployed'} - {@const blockedReason = - !isSelectable && !isDeployed ? selectBlockedReason?.(item) : undefined} - - {@const showPath = - isAgent?.(item) || - (item.kind !== 'resource' && - item.kind !== 'variable' && - item.kind !== 'resource_type')} - {@const subPath = - group.key && item.path.startsWith(group.key + '/') + {@render itemRow( + item, + 0, + showGroupHeaders && group.key && item.path.startsWith(group.key + '/') ? item.path.slice(group.key.length + 1) - : item.path} - - handleSelect(item)} - path={showPath ? item.path : ''} - marked={undefined} - kind={isAgent?.(item) ? 'agent' : item.kind} - triggerKind={item.triggerKind} - canFavorite={false} - workspaceId="" - > - {#snippet customSummary()} - {#if itemSummary} - {@render itemSummary(item)} - {:else} - {item.path} - {/if} - {/snippet} - {#snippet pathDisplay()} - {#if itemPath} - {@render itemPath(item)} - {:else} - {showPath ? (showGroupHeaders ? subPath : item.path) : ''} - {/if} - {/snippet} - {#snippet actions()} - {#if itemActions} - {@render itemActions(item)} - {/if} - - {#if status} - {#if status.status === 'loading'} - - {:else if status.status === 'deployed'} - Deployed - {:else if status.status === 'failed'} -
- Failed - {status.error} -
- {/if} - {/if} - {/snippet} -
+ : item.path + )} {/each} {/each}
diff --git a/frontend/src/lib/components/home/TreeOwnerRow.svelte b/frontend/src/lib/components/home/TreeOwnerRow.svelte index 0786c1f9f4..7a815b28a2 100644 --- a/frontend/src/lib/components/home/TreeOwnerRow.svelte +++ b/frontend/src/lib/components/home/TreeOwnerRow.svelte @@ -20,6 +20,9 @@ detail: Snippet /** Controls rendered next to the name. Clicks on them do not toggle the row. */ actions?: Snippet + /** Always-visible control before the icon (e.g. a checkbox). Clicks on it do not + * toggle the row. */ + lead?: Snippet /** Always-visible controls before the chevron. They stop their own clicks. */ trailing?: Snippet /** False for a row known to group nothing: it renders without a chevron and does not toggle. */ @@ -35,6 +38,7 @@ toggleLabel, detail, actions, + lead, trailing, expandable = true }: Props = $props() @@ -54,6 +58,11 @@ class="flex flex-row items-center gap-4" style={indent > 0 ? `padding-left: ${indent}px;` : ''} > + {#if lead} + + +
e.stopPropagation()}>{@render lead()}
+ {/if}
diff --git a/frontend/src/lib/components/home/TreeView.svelte b/frontend/src/lib/components/home/TreeView.svelte index 3df43e0fd0..e3723fd475 100644 --- a/frontend/src/lib/components/home/TreeView.svelte +++ b/frontend/src/lib/components/home/TreeView.svelte @@ -64,10 +64,15 @@ leaf?: Snippet<[ItemType, number]> // Remembers which nodes the user opened by hand, so they reopen on the next visit // while expand/collapse-all is in its collapsed state. - openMemory?: TreeOpenMemory + openMemory?: Pick // Adds a "Manage folder" menu ("View folder" for a non-owner) to top-level folder rows. // Subfolders are path segments, not folders with permissions of their own, so get none. onManageFolder?: (folderName: string) => void + // An always-visible control before a folder/user row's icon, given the node's + // full path prefix (e.g. a checkbox selecting everything under it). + ownerLead?: Snippet<[string]> + // Appended to a folder/user row's item count, given the node's full path prefix. + ownerDetail?: Snippet<[string]> } let { @@ -88,7 +93,9 @@ indent = 0, leaf, openMemory, - onManageFolder + onManageFolder, + ownerLead, + ownerDetail }: Props = $props() const unruled = inUnruledList() @@ -335,6 +342,12 @@ {/if} {/snippet} +{#snippet ownerLeadForNode()} + {#if nodePrefix != undefined} + {@render ownerLead?.(nodePrefix)} + {/if} +{/snippet} + {#if isFolder(item) || isUser(item)}
{#snippet detail()} @@ -362,6 +376,9 @@ {:else} ({pluralize(loadedHere, ' item')}) {/if} + {#if ownerDetail && nodePrefix != undefined} + {@render ownerDetail(nodePrefix)} + {/if} {/snippet} {/if} {@render footerSettings?.()} {#if chatHost.mode === AIMode.GLOBAL} - + +
+ +{#if chatHost.mode === AIMode.GLOBAL} + +{/if} diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index ac6f21844e..b40a75169c 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -6,6 +6,7 @@ import { contextElementKey, createAttachedFileContextElement, + isMentionContext, isSameContextElement, type AppDomSelectorElement, type ContextElement @@ -864,9 +865,7 @@ // Workspace items are fetched on-demand and not in availableContext, // so skip the availableContext check for them const isWorkspaceItem = - contextElement.type === 'workspace_script' || - contextElement.type === 'workspace_flow' || - contextElement.type === 'workspace_app' + isMentionContext(contextElement) if ( !isWorkspaceItem && !availableContext.find( diff --git a/frontend/src/lib/components/copilot/chat/AssistantDangerZoneSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantDangerZoneSection.svelte new file mode 100644 index 0000000000..c9a935ae42 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/AssistantDangerZoneSection.svelte @@ -0,0 +1,78 @@ + + + +
+ + Hides AI sessions and every other AI assistant button from all members of + {ws}. AI agent steps in flows keep working. Turn it back on in + the workspace settings, under Windmill AI. + +
+ + void hideSessions()} + onCanceled={() => (confirming = false)} +> + + Every member of {ws} loses AI sessions and the AI assistant buttons. + The page reloads on Home. + + diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 5d8f700604..547940bde9 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -47,6 +47,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio User } from 'lucide-svelte' import { untrack } from 'svelte' + import { useReducedMotion } from '$lib/svelte5Utils.svelte' import { getAiChatManager } from './aiChatManagerContext' import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte' import { @@ -55,7 +56,12 @@ its block on a detail page laid over the list, like a skill in the Skills sectio saveFolderInstruction, type FolderInstructionRow } from './folderInstructions' - import { buildSkillTree, countSkills, type SkillTreeNode } from './skills/skillTree' + import { + buildSkillTree, + countSkills, + foldedByDefault, + type SkillTreeNode + } from './skills/skillTree' const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) @@ -63,10 +69,13 @@ its block on a detail page laid over the list, like a skill in the Skills sectio let { ws, active, + focusRoot, blocksClose = $bindable() }: { /** The workspace the chat operates on, which is not always the one on screen. */ ws: string + /** The folder (`f/x` or `u/x`) the modal was opened on: the only top-level one open. */ + focusRoot?: string /** Whether this is the panel on screen. The list costs a settings read and a * resource listing, so it is fetched when someone looks at instructions rather * than on every open of the modal. */ @@ -157,8 +166,9 @@ its block on a detail page laid over the list, like a skill in the Skills sectio let folderRows = $state([]) let folderLoadError = $state(undefined) let tree = $derived(buildSkillTree(folderRows)) - /** Folders the user closed, keyed by full prefix. */ + /** Folders the user closed or opened, keyed by full prefix. */ let collapsed = $state>({}) + const isFolded = (path: string) => collapsed[path] ?? foldedByDefault(path, focusRoot) // The folder instruction on the detail page: what Monaco holds against what was read. let folderContent = $state('') @@ -175,13 +185,14 @@ its block on a detail page laid over the list, like a skill in the Skills sectio let folderChanged = $derived( detail?.kind === 'new' ? folderContent.trim() !== '' - : detail?.kind === 'folder' && folderContent !== folderOriginal + : detail?.kind === 'folder' && + (folderContent !== folderOriginal || newPath !== detail.row.path) ) /** Unsaved folder instructions the user moved away from, by workspace and path: the editor * holds one at a time, and opening another would otherwise drop this one's text. */ let parkedFolderDrafts = $state< - Record + Record >({}) const draftKey = (path: string, workspace = ws) => `${workspace}\0${path}` let parkedHere = $derived( @@ -315,7 +326,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio workspaceDraft = workspaceSaved userDraft = userSaved // The editor may still hold another workspace's open draft, which is not this one's to drop. - if (opened?.workspace === ws) setFolderContent(folderOriginal) + if (opened?.workspace === ws) revertFolder() for (const [key] of parkedHere) delete parkedFolderDrafts[key] delete parkedNewDrafts[ws] } @@ -323,7 +334,16 @@ its block on a detail page laid over the list, like a skill in the Skills sectio function revertPage() { if (detail?.kind === 'workspace') workspaceDraft = workspaceSaved else if (detail?.kind === 'user') userDraft = userSaved - else setFolderContent(folderOriginal) + else revertFolder() + } + + /** The open folder instruction back to its saved body and its own path. */ + function revertFolder() { + setFolderContent(folderOriginal) + if (opened?.detail.kind === 'folder' && newPath !== opened.detail.row.path) { + newPath = opened.detail.row.path + editorSeq++ + } } /** Moves the open folder instruction's unsaved text aside, before the editor is reused. @@ -342,11 +362,12 @@ its block on a detail page laid over the list, like a skill in the Skills sectio } if (held.kind !== 'folder') return bodyEditor?.flushPendingChanges() - if (folderContent === folderOriginal) return + if (folderContent === folderOriginal && newPath === held.row.path) return parkedFolderDrafts[draftKey(held.row.path, workspace)] = { workspace, content: folderContent, - original: folderOriginal + original: folderOriginal, + path: newPath } folderOriginal = folderContent } @@ -364,6 +385,18 @@ its block on a detail page laid over the list, like a skill in the Skills sectio bodyEditor?.setCode(next) } + /** Back on the list with the folds reset, for `focusRoot` to decide them. */ + export function showFolder() { + closeDetail() + collapsed = {} + pulse++ + } + /** Replays the focused folder's flash, so the eye finds it in the list. A reload remounts + * the rows, so the flash already played is remembered rather than replayed. */ + let pulse = $state(0) + let played = $state(0) + const reducedMotion = useReducedMotion() + /** Lands on the rendered instructions: reading them is the common reason to open * them, and the header's View/Edit switch is one click from the other half. */ async function openFolder(row: FolderInstructionRow) { @@ -379,6 +412,9 @@ its block on a detail page laid over the list, like a skill in the Skills sectio visit++ setFolderContent(parked.content) folderOriginal = parked.original + // Save renames to `newPath`, which still holds whatever was open in between. + newPath = parked.path + editorSeq++ folderMode = 'edit' opened = { workspace: ws, detail: { kind: 'folder', row } } detailOpen = true @@ -393,6 +429,8 @@ its block on a detail page laid over the list, like a skill in the Skills sectio if (source !== ws || seq !== visit) return setFolderContent(body) folderOriginal = body + newPath = row.path + editorSeq++ folderMode = 'view' opened = { workspace: source, detail: { kind: 'folder', row } } detailOpen = true @@ -451,7 +489,8 @@ its block on a detail page laid over the list, like a skill in the Skills sectio if (current?.kind !== 'folder' && current?.kind !== 'new') return if (blockedByPendingFork()) return const target = ws - const path = current.kind === 'new' ? newPath : current.row.path + const path = newPath + const from = current.kind === 'folder' ? current.row.path : undefined // Monaco hands its text to `folderContent` on a debounce, so the last keystrokes // before a quick click would otherwise be left out of the save. bodyEditor?.flushPendingChanges() @@ -459,14 +498,17 @@ its block on a detail page laid over the list, like a skill in the Skills sectio const seq = visit saving = true try { - await saveFolderInstruction(target, path, content, { create: current.kind === 'new' }) + await saveFolderInstruction(target, path, content, { + create: current.kind === 'new', + from + }) sendUserToast(current.kind === 'new' ? `Added ${path}` : `Saved ${path}`) await loadFolders(target) refreshChat(target) // Another instruction opened meanwhile owns the editor now. if (seq !== visit) return folderOriginal = content - if (current.kind === 'new') { + if (path !== from) { const row = folderRows.find((r) => r.path === path) if (row) opened = { workspace: target, detail: { kind: 'folder', row } } folderMode = 'view' @@ -660,17 +702,32 @@ its block on a detail page laid over the list, like a skill in the Skills sectio openBlock(kind)} /> {/snippet} +{#snippet focusPulse(focused: boolean)} + + {#if focused && pulse !== played && !reducedMotion.val} + {#key pulse} + + {/key} + {/if} +{/snippet} + {#snippet folder(node: SkillTreeNode, root: boolean)} -
+
+ {@render focusPulse(root && node.path === focusRoot)} - {#if !collapsed[node.path]} + {#if !isFolded(node.path)}
{#each node.children as child (child.path)} {@render folder(child, false)} @@ -844,7 +901,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
- {#if detail?.kind === 'new'} + {#if detail?.kind === 'new' || detail?.kind === 'folder'}
+ {#if detail?.kind === 'folder'} +
+ Stored as an ai_instruction resource. + +
+ {/if}
diff --git a/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte index 1a0cb075f2..aa0683c0d4 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMcpSection.svelte @@ -41,6 +41,7 @@ switch that decides whether this chat carries its tools. let { ws, active, + focusRoot, count = $bindable(), blocksClose = $bindable() }: { @@ -50,6 +51,9 @@ switch that decides whether this chat carries its tools. * costs a read of the instance OAuth connects — not worth paying for on a modal * opened for one of the other three sections. */ active: boolean + /** The folder (`f/x` or `u/x`) the modal was opened on: the list shows its servers + * until the user asks for all of them. */ + focusRoot?: string /** Number of connected servers, for the sidebar badge. */ count: number /** True while this section is in the middle of something the modal must not @@ -151,6 +155,18 @@ switch that decides whether this chat carries its tools. let page = $derived(connectOpen ? 'connect' : detailOpen ? 'detail' : 'list') + let showAll = $state(false) + let shown = $derived( + focusRoot && !showAll ? servers.filter((s) => ownerRoot(s.path) === focusRoot) : servers + ) + + /** Back on the list narrowed to `focusRoot`. A connection holding unsaved edits stays + * open, as the Skills editor does. */ + export function showFolder() { + showAll = false + if (!editingChanged) detailOpen = false + } + $effect(() => { count = servers.length }) @@ -481,7 +497,7 @@ switch that decides whether this chat carries its tools. /> {:else}
- {#each servers as server (server.path)} + {#each shown as server (server.path)} {#snippet icon()} {/snippet} @@ -531,6 +547,17 @@ switch that decides whether this chat carries its tools. onClick={() => openServer(server)} /> {/each} + {#if shown.length < servers.length} + + {/if}
{/if} diff --git a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte index c030fe5c9d..74e56530b2 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte @@ -17,6 +17,7 @@ callers that already know which section they mean, such as the "+" menu's Manage | 'mcp' | 'files' | 'permissions' + | 'danger' -{#snippet leafIcon(leaf: DrillLeaf)} - +{#snippet leafIcon(leaf: DrillLeaf)} + {#if 'kind' in leaf.data} + + {:else} + + {/if} {/snippet} -{#snippet branchIcon(branch: DrillBranch)} +{#snippet branchIcon(branch: DrillBranch)} {#if branch.icon} {@const Icon = branch.icon} @@ -140,7 +150,10 @@ at the workspace root because the parent menu item already names the scope. onPick={handlePick} {leafIcon} {branchIcon} - leafSecondary={(leaf, scope) => relativizeWorkspacePath(workspaceItemDisplayPath(leaf.data), scope)} + leafSecondary={(leaf, scope) => + 'kind' in leaf.data + ? relativizeWorkspacePath(workspaceItemDisplayPath(leaf.data), scope) + : undefined} onScopeChange={handleScopeChange} onFilterChange={loader.onFilterChange} rootLoading={WORKSPACE_KINDS.some((k) => !loader.loaded[k] && loader.loadingKind[k])} diff --git a/frontend/src/lib/components/copilot/chat/context.ts b/frontend/src/lib/components/copilot/chat/context.ts index f57862c179..b025a3d407 100644 --- a/frontend/src/lib/components/copilot/chat/context.ts +++ b/frontend/src/lib/components/copilot/chat/context.ts @@ -9,13 +9,16 @@ import { TextSelect, Table2, LayoutDashboard, - MousePointer2 + MousePointer2, + Folder } from 'lucide-svelte' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import type { ScriptLang } from '$lib/gen/types.gen' import { type DBSchema } from '$lib/stores' import { type Change } from 'diff' import type { AppDatatableMetadata, BackendRunnable, SelectedContext } from './app/core' +import type { DrillLeaf, DrillNode } from '$lib/components/drillPicker' +import { dirKey } from '$lib/components/workspacePicker' export const ContextIconMap = { code: Code, @@ -31,6 +34,7 @@ export const ContextIconMap = { workspace_script: Code2, workspace_flow: BarsStaggered, workspace_app: LayoutDashboard, + workspace_folder: Folder, // Fallback — the badge renders attached_file with the per-extension file icon. attached_file: FileText // flow_module type is handled with FlowModuleIcon @@ -286,6 +290,51 @@ export interface WorkspaceAppElement { summary?: string } +/** Workspace folder context element — everything under a path prefix: a folder (`f/team`, or a + * subfolder of an owner) or a user's own items (`u/alice`). Its items are read by the chat on + * demand like any other workspace reference. */ +export interface WorkspaceFolderElement { + type: 'workspace_folder' + path: string + title: string +} + +export function folderContextElement( + path: string +): WorkspaceFolderElement & { deletable: boolean } { + return { type: 'workspace_folder', path, title: path, deletable: true } +} + +/** Whether a folder context path is a user's own items (`u/alice`) rather than a folder. */ +export function isUserContextPath(path: string): boolean { + return /^u\/[^/]+$/.test(path) +} + +const DIR_PREFIX = dirKey('all', '') + +/** Opens every `f/` and `u/` directory of a flat workspace tree (any depth) on a leaf that picks + * the directory itself, so it is taken as context from inside it, or by searching its path. */ +export function withFolderContextLeaves( + nodes: DrillNode[] +): DrillNode[] { + return nodes.map((node) => { + if (node.type !== 'branch') return node + const children = withFolderContextLeaves(node.children) + const path = node.key.startsWith(DIR_PREFIX) ? node.key.slice(DIR_PREFIX.length) : '' + if (!/^[fu]\/./.test(path)) return { ...node, children } + const leaf: DrillLeaf = { + type: 'leaf', + key: `folder:${path}`, + label: isUserContextPath(path) ? 'All their items' : 'Whole folder', + secondary: path, + icon: Folder, + data: folderContextElement(path), + searchableText: path + } + return { ...node, children: [leaf, ...children] } + }) +} + /** Message-attached text file, rendered with the shared context badge. Never part * of `selectedContext` — constructed at render time from the composer's / a sent * message's `files` state (see createAttachedFileContextElement). */ @@ -318,6 +367,7 @@ export type ContextElement = ( | WorkspaceScriptElement | WorkspaceFlowElement | WorkspaceAppElement + | WorkspaceFolderElement | AttachedFileElement ) & { deletable?: boolean @@ -334,8 +384,18 @@ export function contextElementKey(c: ContextElement): string { /** An `@`-mentioned workspace item, attached to one message the way a DOM pick * is. Membership only: this does not gate on mode, so every caller must. Outside * GLOBAL these stay selected as chips the user removes by hand. */ -export function isMentionContext(c: ContextElement): boolean { - return c.type === 'workspace_script' || c.type === 'workspace_flow' || c.type === 'workspace_app' +export type MentionContext = Extract< + ContextElement, + { type: 'workspace_script' | 'workspace_flow' | 'workspace_app' | 'workspace_folder' } +> + +export function isMentionContext(c: ContextElement): c is MentionContext { + return ( + c.type === 'workspace_script' || + c.type === 'workspace_flow' || + c.type === 'workspace_app' || + c.type === 'workspace_folder' + ) } export function isSameContextElement(a: ContextElement, b: ContextElement): boolean { diff --git a/frontend/src/lib/components/copilot/chat/folderInstructions.ts b/frontend/src/lib/components/copilot/chat/folderInstructions.ts index 3d33757756..306c1d0bc6 100644 --- a/frontend/src/lib/components/copilot/chat/folderInstructions.ts +++ b/frontend/src/lib/components/copilot/chat/folderInstructions.ts @@ -90,7 +90,7 @@ export async function saveFolderInstruction( workspace: string, path: string, content: string, - { create = false }: { create?: boolean } = {} + { create = false, from = path }: { create?: boolean; from?: string } = {} ): Promise { if (create) { await ResourceService.createResource({ @@ -102,7 +102,11 @@ export async function saveFolderInstruction( } }) } else { - await ResourceService.updateResource({ workspace, path, requestBody: { value: { content } } }) + await ResourceService.updateResource({ + workspace, + path: from, + requestBody: { path, value: { content } } + }) } } diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 06c17b6ce5..4a95ff2f2e 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -186,7 +186,7 @@ import { scriptLangToEditorLang } from '$lib/scripts' import { appFileEditorLang } from '../appFileEditorLang' import { searchDocsTool, readDocsPageTool } from '../docs/core' import { createDbSchemaTool } from '../script/core' -import type { ContextElement } from '../context' +import { isMentionContext, isUserContextPath, type ContextElement } from '../context' import { getDatatableTools } from '../datatableTools' import { getDatatableMigrationTools } from '../datatableMigrationTools' import { getDucklakeTools } from '../ducklakeTools' @@ -10122,12 +10122,7 @@ export function prepareGlobalUserMessage( selectedContext: ContextElement[] = [], options: GlobalUserMessageOptions = {} ): ChatCompletionUserMessageParam { - const selectedWorkspaceItems = selectedContext.filter( - (context) => - context.type === 'workspace_script' || - context.type === 'workspace_flow' || - context.type === 'workspace_app' - ) + const selectedWorkspaceItems = selectedContext.filter(isMentionContext) const activeEditor = options.activeEditor ?? (options.workspace ? getActiveGlobalEditorContext(options.workspace) : undefined) @@ -10158,6 +10153,10 @@ export function prepareGlobalUserMessage( if (selectedWorkspaceItems.length > 0) { content += '## SELECTED CONTEXT\n' for (const context of selectedWorkspaceItems) { + if (context.type === 'workspace_folder') { + content += `- type: ${isUserContextPath(context.path) ? 'user' : 'folder'}, path: ${context.path} (its items: list_workspace_items with path_prefix "${context.path}/")\n` + continue + } const itemType = context.type === 'workspace_script' ? 'script' diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index fdd5e0cea3..55c63f3718 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -39,6 +39,7 @@ import type { PasteAttachment } from './pasteTokens' import { dataUrlToImagePart, type AttachedImage } from './imageUtils' import type { AttachedTextFile } from './textFileUtils' import type { CodePieceElement, ContextElement, FlowModuleCodePieceElement } from './context' +import { isUserContextPath } from './context' import { workspaceStore } from '$lib/stores' import type { ExtendedOpenFlow } from '$lib/components/flows/types' import { findModuleInFlow, findModuleInModules } from '$lib/components/flows/flowTree' @@ -465,6 +466,11 @@ export function buildContextString(selectedContext: ContextElement[]): string { workspaceItemsContext = 'SELECTED WORKSPACE ITEMS:\n' } workspaceItemsContext += `- type: raw_app, path: ${context.path}\n` + } else if (context.type === 'workspace_folder') { + if (!workspaceItemsContext) { + workspaceItemsContext = 'SELECTED WORKSPACE ITEMS:\n' + } + workspaceItemsContext += `- type: ${isUserContextPath(context.path) ? 'user' : 'folder'}, path: ${context.path}\n` } } diff --git a/frontend/src/lib/components/copilot/chat/skills/skillTree.ts b/frontend/src/lib/components/copilot/chat/skills/skillTree.ts index d2de4eb655..cb6ac7cd74 100644 --- a/frontend/src/lib/components/copilot/chat/skills/skillTree.ts +++ b/frontend/src/lib/components/copilot/chat/skills/skillTree.ts @@ -1,8 +1,4 @@ -/** Grouping for the Skills list: skills sorted into the folders that hold them. - * - * Only worth showing when the skills are spread over more than one folder — see - * `skillFolderPaths` — since a tree over a single folder is a list with a header - * on top of it. */ +/** Grouping for the Skills list: skills sorted into the folders that hold them. */ /** A folder in the skills tree. `path` is the whole prefix the node covers, so it * is unique across the tree and can key collapsed state. */ @@ -19,11 +15,6 @@ export type SkillTreeNode = { type Skill = { path: string; name: string } -/** The folders holding these skills — one entry per distinct parent path. */ -export function skillFolderPaths(skills: readonly Skill[]): Set { - return new Set(skills.map((s) => s.path.split('/').slice(0, -1).join('/'))) -} - /** Every skill under `node`, its subfolders included. */ export function countSkills(node: SkillTreeNode): number { return node.skills.length + node.children.reduce((n, c) => n + countSkills(c), 0) @@ -40,6 +31,12 @@ export type SkillTreeEntry = { key: string; parentKey?: string } & ( | { kind: 'skill'; skill: T } ) +/** Whether a folder the user has not folded or unfolded starts folded: with a folder focused + * (`f/x` or `u/x`), every other top-level folder does, so the focused one is what is left. */ +export function foldedByDefault(path: string, focusRoot: string | undefined): boolean { + return focusRoot !== undefined && path.split('/').length === 2 && path !== focusRoot +} + /** A folder and a skill can hold the same path — `f/skills/deploy` names both when * `f/skills/deploy/rollback` exists beside it — so the kind is part of the key. */ export function folderKey(path: string): string { diff --git a/frontend/src/lib/components/copilot/chat/skills/skills.test.ts b/frontend/src/lib/components/copilot/chat/skills/skills.test.ts index ae2e737af2..aaeb82bc2c 100644 --- a/frontend/src/lib/components/copilot/chat/skills/skills.test.ts +++ b/frontend/src/lib/components/copilot/chat/skills/skills.test.ts @@ -12,7 +12,7 @@ vi.mock('$lib/stores', () => ({ import { isMcpEnabled } from '$lib/components/mcp/enabledServers' import { isSkillEnabled, setSkillEnabled } from './enabledSkills' import { ambiguousSkillNames, truncateChars, truncateForPrompt } from './skillResources' -import { buildSkillTree, countSkills, skillFolderPaths, visibleEntries } from './skillTree' +import { buildSkillTree, countSkills, visibleEntries } from './skillTree' describe('enabledSkills', () => { beforeEach(() => { @@ -112,12 +112,6 @@ describe('skill tree', () => { 'folder:f/skills' ]) }) - - // What the list uses to choose between the tree and a flat list. - it('counts the folders holding the skills, not the skills', () => { - expect(skillFolderPaths(skills).size).toBe(3) - expect(skillFolderPaths([skills[1], { path: 'f/skills/deploy', name: 'deploy' }]).size).toBe(1) - }) }) describe('skill names', () => { diff --git a/frontend/src/lib/components/copilot/chat/workingScope.ts b/frontend/src/lib/components/copilot/chat/workingScope.ts index 30ae5becc7..0c1d270ad7 100644 --- a/frontend/src/lib/components/copilot/chat/workingScope.ts +++ b/frontend/src/lib/components/copilot/chat/workingScope.ts @@ -221,12 +221,6 @@ export function scopeBadge(option: ScopeOption): string { ].join(' · ') } -/** How a folder's instructions and skills reach the AI, in the one wording the picker and the - * tree badge share. */ -export function scopeRule(root: string): string { - return `Working in ${root} puts its instructions in the AI's prompt and keeps its skills on; skills from other folders are off. Outside it, the AI gets a folder's instructions the first time it touches that folder.` -} - export type ScopeKind = 'workspace' | 'none' | 'folder' | 'user_space' | 'several' export type ScopeSource = 'default' | 'preset' | 'manual' diff --git a/frontend/src/lib/components/home/HomeAIChat.svelte b/frontend/src/lib/components/home/HomeAIChat.svelte index 9d6f3949a7..d37dae0575 100644 --- a/frontend/src/lib/components/home/HomeAIChat.svelte +++ b/frontend/src/lib/components/home/HomeAIChat.svelte @@ -11,15 +11,12 @@ -
+
- {#if hero} - - + {#if showComposer} + {#snippet homeMenu()} - - - {#if !sideTripsInBar || (showComposer && removed) || homeQuickAccessSettings.hidden} - + + {#if !sideTripsInBar || homeQuickAccessSettings.hidden} - {#if pulsing} - - - {/if} - + {#if homeQuickAccessSettings.hideCount > 0 && !reducedMotion.val} {#key homeQuickAccessSettings.hideCount} { - logFeatureUsage('home', 'ai_hero_pin') - setHomeComposerRemoved(false) - } - } - ] - : []), ...(homeQuickAccessSettings.hidden ? [ { diff --git a/frontend/src/lib/components/home/HomeFolderBadge.svelte b/frontend/src/lib/components/home/HomeFolderBadge.svelte index 7014fe62a0..6002fcfaba 100644 --- a/frontend/src/lib/components/home/HomeFolderBadge.svelte +++ b/frontend/src/lib/components/home/HomeFolderBadge.svelte @@ -1,14 +1,13 @@ -{#if row && badge} - - -
e.stopPropagation()}> - - {#snippet trigger()} - - {/snippet} - {#snippet content()} - {#if row.instructions.length} -
-

Instructions

- {#each row.instructions as path (path)} -

{path}

- {/each} -
- {/if} - {#if row.skills.length} -
-

Skills

- {#each row.skills as path (path)} -

{path}

- {/each} -
- {/if} - {#if row.mcpServers.length} -
-

MCP servers

- {#each row.mcpServers as path (path)} -

{path}

- {/each} -
- {/if} -

{scopeRule(root)}

- - {/snippet} -
-
+{#if parts.length} + + {#each parts as part (part.section)} + + {/each} + {/if} diff --git a/frontend/src/lib/components/home/HomeQuickAccess.svelte b/frontend/src/lib/components/home/HomeQuickAccess.svelte index 82afb77db4..5bba8d1112 100644 --- a/frontend/src/lib/components/home/HomeQuickAccess.svelte +++ b/frontend/src/lib/components/home/HomeQuickAccess.svelte @@ -22,6 +22,7 @@ import { useEditRights } from '$lib/operatorWriteRights' import { roleCapabilities, userStore } from '$lib/stores' import { AppService } from '$lib/gen' + import { SvelteMap } from 'svelte/reactivity' import { copyToClipboard, type Item } from '$lib/utils' import RowIcon from '$lib/components/common/table/RowIcon.svelte' import DraftBadge from '$lib/components/DraftBadge.svelte' @@ -120,14 +121,39 @@ // A favorite app arrives as plain `app` (the layout lists apps without their subtype), and // `/apps/edit` mounts the low-code editor whatever it opens, so the editor routes ask which // one it is, once, when its menu opens. + const appKinds = new SvelteMap() async function editorKind(item: Entry): Promise { if (item.kind !== 'app') return item.kind + const known = appKinds.get(`${workspace}/${item.path}`) + if (known) return known + let kind: RecentKind = 'app' try { const app: any = await AppService.getAppLiteByPath({ workspace, path: item.path }) - return app?.raw_app ? 'raw_app' : 'app' - } catch { - return 'app' - } + if (app?.raw_app) kind = 'raw_app' + } catch {} + appKinds.set(`${workspace}/${item.path}`, kind) + return kind + } + + // Only scripts, flows and raw apps can be context, so another card keeps its menu while the + // composer is open; an `app` card is a visual one until the hover's lookup says otherwise. + function canMention(item: Entry): boolean { + if (item.kind === 'app') return appKinds.get(`${workspace}/${item.path}`) === 'raw_app' + return item.kind !== 'agent' + } + + function contextElementFor(item: Entry, kind: RecentKind) { + return itemContextElement({ + kind: kind === 'raw_app' ? 'app' : kind, + rawApp: kind === 'raw_app', + path: item.path, + summary: item.title === item.path ? undefined : item.title + }) + } + + async function mention(item: Entry) { + const element = contextElementFor(item, await editorKind(item)) + if (element) await homeComposerContext.attach(element) } // The row menus' actions that need nothing but the kind and path. Moving, deleting and @@ -135,12 +161,7 @@ async function menuItems(item: Entry, favorite: boolean): Promise { const kind = await editorKind(item) const base = kind === 'raw_app' ? 'apps_raw' : `${kind}s` - const contextElement = itemContextElement({ - kind: kind === 'raw_app' ? 'app' : kind, - rawApp: kind === 'raw_app', - path: item.path, - summary: item.title === item.path ? undefined : item.title - }) + const contextElement = contextElementFor(item, kind) return [ { displayName: 'Add to AI session context', @@ -366,8 +387,11 @@ {#snippet card(item: Entry, favorite: boolean)} + {@const mentionable = canMention(item)} {@const draft = draftByItem.get(`${item.starKind}/${item.path}`)}
homeComposerContext.available && void editorKind(item)} + onfocusin={() => homeComposerContext.available && void editorKind(item)} class="group flex items-center gap-1 rounded-md border border-light bg-surface-tertiary hover:bg-surface-hover transition-colors min-w-0 group-has-[[data-composer-open]]/home:border-transparent group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:hover:bg-surface-hover" > (now = Date.now())} role="note" @@ -421,9 +447,33 @@ {/if} -
+ +
menuItems(item, favorite)} size="xs" fixedHeight={false} />
+ {#if mentionable} + + + {/if}
{/snippet} diff --git a/frontend/src/lib/components/home/TreeView.svelte b/frontend/src/lib/components/home/TreeView.svelte index e3723fd475..5d1e7c8fbb 100644 --- a/frontend/src/lib/components/home/TreeView.svelte +++ b/frontend/src/lib/components/home/TreeView.svelte @@ -3,11 +3,13 @@ import { createEventDispatcher, onDestroy, untrack, type Snippet } from 'svelte' import ResizeTransitionWrapper from '$lib/components/common/ResizeTransitionWrapper.svelte' - import { Eye, Folder, FolderTree, Pen, User } from 'lucide-svelte' + import { AtSign, Eye, Folder, FolderTree, Pen, User } from 'lucide-svelte' import { userStore } from '$lib/stores' import Dropdown from '$lib/components/DropdownV2.svelte' import TreeOwnerRow from './TreeOwnerRow.svelte' import HomeFolderBadge from './HomeFolderBadge.svelte' + import { homeComposerContext } from '../sessions/homeComposerContext.svelte' + import { folderContextElement } from '../copilot/chat/context' import PipelineRow from '../common/table/PipelineRow.svelte' import Item from './Item.svelte' import { @@ -120,6 +122,7 @@ ? `f/${item.folderName}` : undefined ) + const mentionRoot = $derived(homeComposerContext.available ? badgeRoot : undefined) // Hidden while searching: pipelines aren't part of the text filter (the list // view hides their rows on a query too), so a folder matching the search @@ -313,10 +316,35 @@ } -{#snippet folderBadge()} - {#if badgeRoot} - - {/if} +{#snippet folderTrailing()} + + {#if badgeRoot} + + {/if} + {#if mentionRoot} + {@const path = mentionRoot} + + + + + {/if} + {/snippet} {#snippet manageFolderMenu()} @@ -332,6 +360,13 @@ fixedHeight={false} placement="bottom-start" items={[ + { + displayName: 'Add to AI session context', + icon: AtSign, + type: 'ai', + action: () => homeComposerContext.attach(folderContextElement(`f/${folderName}`)), + hide: !homeComposerContext.available + }, { displayName: canWrite ? 'Manage folder' : 'View folder', icon: canWrite ? Pen : Eye, @@ -359,7 +394,7 @@ indent={visualDepth * 16} actions={onManageFolder && depth === 0 && isFolder(item) ? manageFolderMenu : undefined} lead={ownerLead && nodePrefix != undefined ? ownerLeadForNode : undefined} - trailing={badgeRoot ? folderBadge : undefined} + trailing={badgeRoot ? folderTrailing : undefined} > {#snippet detail()} {#if ownerCount != undefined} diff --git a/frontend/src/lib/components/home/homeComposerPin.svelte.ts b/frontend/src/lib/components/home/homeComposerPin.svelte.ts deleted file mode 100644 index ff7aaed0d1..0000000000 --- a/frontend/src/lib/components/home/homeComposerPin.svelte.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { BROWSER } from 'esm-env' -import { getLocalSetting, storeLocalSetting } from '$lib/utils' - -// Whether this reader put the composer away from the home page, so it lives per browser -// rather than per workspace or account. It has nothing to do with the composer's one-line -// state despite the key's name; renaming the key would reset every reader's choice. -const REMOVED_SETTING = 'home-ai-composer-collapsed' - -export const homeComposerPin = $state({ - removed: BROWSER && getLocalSetting(REMOVED_SETTING) === 'true' -}) - -export function setHomeComposerRemoved(removed: boolean): void { - homeComposerPin.removed = removed - storeLocalSetting(REMOVED_SETTING, removed ? 'true' : undefined) -} - -/** Starting a session asks for the composer: it is the only place one is typed. */ -export function pinHomeComposer(): void { - if (homeComposerPin.removed) setHomeComposerRemoved(false) -} diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte index cfdf64206a..95e4e4000a 100644 --- a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -91,6 +91,7 @@ }, focus: () => aiChat?.focusInput(), flash: () => aiChat?.flashComposer(), + openSettings: (section, root) => aiChat?.openAssistantSettings(section, root), runtime }) }) diff --git a/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts index 29a35feb45..a37858f288 100644 --- a/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts +++ b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts @@ -33,6 +33,8 @@ type Registration = { focus: () => void /** The box's accent outline, for a composer the user is sent to without it moving. */ flash: () => void + /** Assistant settings on `section`, focused on `root`'s folder. */ + openSettings: (section: 'instructions' | 'skills' | 'mcp', root: string) => void runtime: SessionRuntime } @@ -66,6 +68,9 @@ export const homeComposerContext = { flash(): void { registered?.flash() }, + openSettings(section: 'instructions' | 'skills' | 'mcp', root: string): void { + registered?.openSettings(section, root) + }, /** Returns the unregister, which only clears its own registration: a remount registers * the new composer before the old one is destroyed. */ register(registration: Registration): () => void { diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index 330311f900..ce699998de 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -24,7 +24,6 @@ import { } from './sessionState.svelte' import { sessionTargetHref, withPreviewParams } from './sessionMode.svelte' import { fixupUrlAfterWorkspaceSwitch } from '../sidebar/workspaceSwitchUrl' -import { pinHomeComposer } from '../home/homeComposerPin.svelte' import { homeComposerContext } from './homeComposerContext.svelte' // Type-only: erased at compile time, so the component graph stays out of this // navigation seam (see the dynamic import in openEditorInSession). @@ -80,11 +79,9 @@ export async function resumeAiSessions(opts?: { replace?: boolean }): Promise { lastSessionId = id - pinHomeComposer() const onHome = typeof window !== 'undefined' && window.location.pathname === '/' // The draft already on screen is focused where it is: rebuilding the composer would fold it // to one line and open it again under the user's eyes.