mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-04 00:06:39 +00:00
Merge origin/main into access-view-read-only
This commit is contained in:
@@ -1 +1 @@
|
||||
303e60fa90f55b08fa04d5c71319c96392f3fc6c
|
||||
bd75bb821b30723c2789081cac004ee134bd10a1
|
||||
|
||||
@@ -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<Postgres>) -> 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<String> =
|
||||
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<Postgres>) -> 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(())
|
||||
}
|
||||
|
||||
@@ -1756,9 +1756,13 @@ async fn delete_user(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query!("DELETE FROM usr_to_group WHERE usr = $1", &username)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query!(
|
||||
"DELETE FROM usr_to_group WHERE usr = $1 AND workspace_id = $2",
|
||||
&username,
|
||||
&row.workspace_id
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"DELETE FROM workspace_invite WHERE email = $1",
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -57,12 +57,16 @@ struct HubScope {
|
||||
folder: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
token: String,
|
||||
@@ -740,7 +745,28 @@ async fn forward_to_hub<T: Serialize>(
|
||||
|
||||
#[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() {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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-<g>` becomes `g/<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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<usize> {
|
||||
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]
|
||||
|
||||
+118
-220
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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",
|
||||
] }
|
||||
|
||||
@@ -219,6 +219,20 @@ 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.
|
||||
// `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';",
|
||||
)
|
||||
.map_err(|e| format!("Error applying DuckDB 1.x compatibility settings: {e}"))
|
||||
}
|
||||
|
||||
fn setup_duckdb_connection(
|
||||
conn: &duckdb::Connection,
|
||||
token: &str,
|
||||
@@ -227,6 +241,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 +255,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 +1034,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<i64>, Option<i64>) = 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();
|
||||
|
||||
@@ -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(),
|
||||
));
|
||||
|
||||
@@ -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<String> = 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::<Vec<_>>()
|
||||
.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<String> {
|
||||
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 —
|
||||
|
||||
@@ -293,11 +293,28 @@ fn parse_duckdb_size(s: &str) -> Option<u64> {
|
||||
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<RunnerOutput> {
|
||||
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 };
|
||||
|
||||
@@ -81,9 +81,45 @@ 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 `~`, 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.
|
||||
- `.duckdb` files are written at 2.0's storage version, which DuckDB 1.x cannot open. Windmill
|
||||
keeps none of its own state in them, so it only reaches a script that persists one outside
|
||||
its job dir for a 1.x reader; that script can `SET storage_compatibility_version`.
|
||||
- `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
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
<script lang="ts" module>
|
||||
const treeOpenState = new Map<string, boolean>()
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { Folder, Loader2, User } from 'lucide-svelte'
|
||||
import { Badge } from './common'
|
||||
@@ -6,6 +10,8 @@
|
||||
import Tooltip from './Tooltip.svelte'
|
||||
import type { Snippet } from 'svelte'
|
||||
import type { Kind } from '$lib/utils_deployable'
|
||||
import TreeViewRoot from './home/TreeViewRoot.svelte'
|
||||
import type { ItemType } from './home/treeViewUtils'
|
||||
|
||||
interface DeployableItem {
|
||||
key: string
|
||||
@@ -25,6 +31,11 @@
|
||||
|
||||
interface Props {
|
||||
items: DeployableItem[]
|
||||
/** Show the items as the home page's folder tree, each folder row selecting
|
||||
* everything under it, instead of grouped by top-level folder. */
|
||||
nested?: boolean
|
||||
/** With `nested`, appended to a folder row's item count, given its full path prefix. */
|
||||
folderDetail?: Snippet<[string]>
|
||||
selectedItems: string[]
|
||||
selectablePredicate?: (item: DeployableItem) => boolean
|
||||
/** Selectable on its own row, but never swept in by a bulk action (the group
|
||||
@@ -68,6 +79,8 @@
|
||||
|
||||
let {
|
||||
items,
|
||||
nested = false,
|
||||
folderDetail,
|
||||
selectedItems,
|
||||
selectablePredicate = () => true,
|
||||
bulkExcluded = () => false,
|
||||
@@ -138,15 +151,34 @@
|
||||
// selection frozen, so they don't count toward the group's tri-state. Bulk-excluded
|
||||
// rows are left out too — the group checkbox is a bulk action, so it must neither
|
||||
// select them nor let them hold its tri-state short of full.
|
||||
function groupSelectable(group: DeployGroup): DeployableItem[] {
|
||||
return group.items.filter(
|
||||
function bulkSelectable(list: DeployableItem[]): DeployableItem[] {
|
||||
return list.filter(
|
||||
(i) =>
|
||||
selectablePredicate(i) && !bulkExcluded(i) && deploymentStatus[i.key]?.status !== 'deployed'
|
||||
)
|
||||
}
|
||||
function groupSelectable(group: DeployGroup): DeployableItem[] {
|
||||
return bulkSelectable(group.items)
|
||||
}
|
||||
|
||||
function toggleGroup(group: DeployGroup) {
|
||||
const selectable = groupSelectable(group)
|
||||
// The tree keys its leaves by `type`; the rows keep every other field as they are.
|
||||
let treeItems = $derived(
|
||||
nested ? (items.map((i) => ({ ...i, type: i.kind })) as unknown as ItemType[]) : []
|
||||
)
|
||||
// While selecting, top-level folders start open and sub-folders closed; without a
|
||||
// selection to make, the tree opens fully, since every row may carry an action.
|
||||
// Held at module level so a toggle survives the remount the Hub drawer does when the
|
||||
// selection changes its scope.
|
||||
const treeOpen = {
|
||||
isOpen: (prefix: string) => treeOpenState.get(prefix) ?? prefix.split('/').length === 2,
|
||||
setOpen: (prefix: string, open: boolean) => void treeOpenState.set(prefix, open)
|
||||
}
|
||||
function underPrefix(prefix: string): DeployableItem[] {
|
||||
return items.filter((i) => i.path.startsWith(prefix + '/'))
|
||||
}
|
||||
|
||||
function toggleGroup(group: Pick<DeployGroup, 'items'>) {
|
||||
const selectable = bulkSelectable(group.items)
|
||||
const target = !selectable.every((i) => selectedItems.includes(i.key))
|
||||
// Snapshot which items need flipping before mutating: onToggleItem updates
|
||||
// the parent's selection, which feeds back into `selectedItems` mid-loop.
|
||||
@@ -157,6 +189,88 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
{#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}
|
||||
<!-- A resource is titled by its path, except an agent, titled by its summary. -->
|
||||
{@const showPath =
|
||||
isAgent?.(item) ||
|
||||
(item.kind !== 'resource' && item.kind !== 'variable' && item.kind !== 'resource_type')}
|
||||
|
||||
<Row
|
||||
isSelectable={!hideSelection && isSelectable && !isDeployed}
|
||||
selectDisabledReason={blockedReason}
|
||||
selectOnRowClick={!hideSelection}
|
||||
alignWithSelectable={!hideSelection}
|
||||
disabled={!hideSelection && (blockedReason ? false : !isSelectable)}
|
||||
selected={isSelected && !isDeployed}
|
||||
onSelect={() => 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}
|
||||
<!-- Deployment status always shown -->
|
||||
{#if status}
|
||||
{#if status.status === 'loading'}
|
||||
<Loader2 class="animate-spin" />
|
||||
{:else if status.status === 'deployed'}
|
||||
<Badge color="green">Deployed</Badge>
|
||||
{:else if status.status === 'failed'}
|
||||
<div class="inline-flex gap-1">
|
||||
<Badge color="red">Failed</Badge>
|
||||
<Tooltip>{status.error}</Tooltip>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Row>
|
||||
{/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}
|
||||
<Checkbox
|
||||
checked={selectable.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}
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- Header section -->
|
||||
{#if header}
|
||||
@@ -197,7 +311,20 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if items.length > 0}
|
||||
{#if items.length > 0 && nested}
|
||||
<div class="overflow-y-auto">
|
||||
<TreeViewRoot
|
||||
items={treeItems}
|
||||
collapseAll={!hideSelection}
|
||||
openMemory={treeOpen}
|
||||
showCode={() => {}}
|
||||
sortCompare={(a, b) => a.path.localeCompare(b.path)}
|
||||
leaf={treeLeaf}
|
||||
ownerLead={hideSelection ? undefined : prefixCheckbox}
|
||||
ownerDetail={folderDetail}
|
||||
/>
|
||||
</div>
|
||||
{:else if items.length > 0}
|
||||
<!-- Items list -->
|
||||
<div class="overflow-y-auto">
|
||||
<div class="border rounded-md bg-surface-tertiary">
|
||||
@@ -248,73 +375,15 @@
|
||||
</div>
|
||||
{/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}
|
||||
<!-- A resource is titled by its path, except an agent, titled by its summary. -->
|
||||
{@const showPath =
|
||||
isAgent?.(item) ||
|
||||
(item.kind !== 'resource' &&
|
||||
item.kind !== 'variable' &&
|
||||
item.kind !== 'resource_type')}
|
||||
<!-- The group header already names the folder — the path line only
|
||||
carries what's below it. -->
|
||||
{@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}
|
||||
|
||||
<Row
|
||||
isSelectable={!hideSelection && isSelectable && !isDeployed}
|
||||
selectDisabledReason={blockedReason}
|
||||
selectOnRowClick={!hideSelection}
|
||||
alignWithSelectable={!hideSelection}
|
||||
disabled={!hideSelection && (blockedReason ? false : !isSelectable)}
|
||||
selected={isSelected && !isDeployed}
|
||||
onSelect={() => 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}
|
||||
<!-- Deployment status always shown -->
|
||||
{#if status}
|
||||
{#if status.status === 'loading'}
|
||||
<Loader2 class="animate-spin" />
|
||||
{:else if status.status === 'deployed'}
|
||||
<Badge color="green">Deployed</Badge>
|
||||
{:else if status.status === 'failed'}
|
||||
<div class="inline-flex gap-1">
|
||||
<Badge color="red">Failed</Badge>
|
||||
<Tooltip>{status.error}</Tooltip>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Row>
|
||||
: item.path
|
||||
)}
|
||||
{/each}
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
@@ -128,6 +128,13 @@
|
||||
aiChatDisplay?.flashComposer()
|
||||
}
|
||||
|
||||
export function openAssistantSettings(
|
||||
section: import('./AssistantSettingsModal.svelte').AssistantSettingsSection,
|
||||
root?: string
|
||||
) {
|
||||
aiChatDisplay?.openAssistantSettings(section, root)
|
||||
}
|
||||
|
||||
export async function attachContext(element: import('./context').ContextElement) {
|
||||
await aiChatDisplay?.attachContext(element)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
MousePointer2,
|
||||
Plug,
|
||||
Plus,
|
||||
SlidersHorizontal,
|
||||
TextSelect,
|
||||
X,
|
||||
XIcon
|
||||
@@ -34,7 +35,9 @@
|
||||
import ContextUsageIndicator from './ContextUsageIndicator.svelte'
|
||||
import AIChatModelSettings from './AIChatModelSettings.svelte'
|
||||
import ScrollFade from '$lib/components/ScrollFade.svelte'
|
||||
import AssistantSettingsModal from './AssistantSettingsModal.svelte'
|
||||
import AssistantSettingsModal, {
|
||||
type AssistantSettingsSection
|
||||
} from './AssistantSettingsModal.svelte'
|
||||
import WorkingInPicker from './WorkingInPicker.svelte'
|
||||
import { scopeLabel } from './workingScope'
|
||||
import { SkillsMenu } from './skills/skillsMenu.svelte'
|
||||
@@ -311,6 +314,12 @@
|
||||
aiChatInput?.focusInput(selection)
|
||||
}
|
||||
|
||||
/** With `root`, focused on that folder. */
|
||||
export function openAssistantSettings(section: AssistantSettingsSection, root?: string) {
|
||||
if (root) void assistantSettings?.openFolder(section, root)
|
||||
else assistantSettings?.open(section)
|
||||
}
|
||||
|
||||
/** Mention a workspace item in the draft, as "+" → Mention file does, and hand the user
|
||||
* the caret after it. Focusing is what opens Home's one-line composer. */
|
||||
export async function attachContext(element: ContextElement) {
|
||||
@@ -1393,7 +1402,24 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
{/if}
|
||||
{@render footerSettings?.()}
|
||||
{#if chatHost.mode === AIMode.GLOBAL}
|
||||
<AssistantSettingsModal bind:this={assistantSettings} />
|
||||
<Tooltip small placement="top">
|
||||
<Button
|
||||
unifiedSize="2xs"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: SlidersHorizontal }}
|
||||
aria-label="Assistant settings"
|
||||
onClick={() => assistantSettings?.open()}
|
||||
/>
|
||||
{#snippet text()}
|
||||
<div class="max-w-64 text-xs">
|
||||
<p class="font-semibold">Assistant settings</p>
|
||||
<p class="mt-1"
|
||||
>The tools, skills, instructions and MCP servers this chat can use.</p
|
||||
>
|
||||
</div>
|
||||
{/snippet}
|
||||
</Tooltip>
|
||||
{/if}
|
||||
|
||||
{#if chatHost.mode === AIMode.APP && appContext && (appContext.inspectorElement || appContext.codeSelection)}
|
||||
@@ -1476,3 +1502,8 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<!-- Outside the composer: Home's folded composer drops its toolbar, and the folder badges open
|
||||
this without unfolding it. -->
|
||||
{#if chatHost.mode === AIMode.GLOBAL}
|
||||
<AssistantSettingsModal bind:this={assistantSettings} />
|
||||
{/if}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<!--
|
||||
@component
|
||||
The Danger zone of the assistant settings modal: workspace-wide switches an admin reaches from the
|
||||
chat itself. Each one is also in the workspace's AI settings, which stay the place to undo it.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { Alert, Section } from '$lib/components/common'
|
||||
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
|
||||
import { WorkspaceService } from '$lib/gen'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { getAiChatManager } from './aiChatManagerContext'
|
||||
|
||||
let { ws }: { ws: string } = $props()
|
||||
|
||||
const aiChatManager = getAiChatManager()
|
||||
|
||||
let confirming = $state(false)
|
||||
let saving = $state(false)
|
||||
|
||||
// Until a staged fork's first send creates it, `ws` is the parent: hiding here would hide AI
|
||||
// for every member of the parent. Read at click, since the fork commits mid-session.
|
||||
function openConfirm() {
|
||||
const parent = aiChatManager.sessionContextResolver?.()?.pendingForkOf
|
||||
if (parent !== undefined) {
|
||||
sendUserToast(
|
||||
`This session has not created its workspace yet, so AI sessions would be hidden in "${parent}" instead. Send a message first.`,
|
||||
true
|
||||
)
|
||||
return
|
||||
}
|
||||
confirming = true
|
||||
}
|
||||
|
||||
async function hideSessions() {
|
||||
saving = true
|
||||
try {
|
||||
// The endpoint replaces the whole config, so the stored one goes back with the flag set.
|
||||
const stored = (await WorkspaceService.getSettings({ workspace: ws })).ai_config ?? {}
|
||||
await WorkspaceService.editCopilotConfig({
|
||||
workspace: ws,
|
||||
requestBody: { ...stored, copilot_disabled: true }
|
||||
})
|
||||
// Every AI entry point read the config when it mounted; a reload is what drops them all.
|
||||
window.location.assign('/')
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not hide AI sessions: ${e}`, true)
|
||||
saving = false
|
||||
confirming = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Section label="Danger zone" description="Settings that apply to every member of this workspace.">
|
||||
<Alert
|
||||
type="error"
|
||||
title="Hide AI sessions"
|
||||
size="xs"
|
||||
actions={[{ label: 'Hide AI sessions', variant: 'accent', onClick: openConfirm }]}
|
||||
>
|
||||
Hides AI sessions and every other AI assistant button from all members of
|
||||
<span class="font-mono">{ws}</span>. AI agent steps in flows keep working. Turn it back on in
|
||||
the workspace settings, under Windmill AI.
|
||||
</Alert>
|
||||
</Section>
|
||||
|
||||
<ConfirmationModal
|
||||
open={confirming}
|
||||
title="Hide AI sessions"
|
||||
confirmationText="Hide for everyone"
|
||||
loading={saving}
|
||||
onConfirmed={() => void hideSessions()}
|
||||
onCanceled={() => (confirming = false)}
|
||||
>
|
||||
<span class="text-xs text-primary">
|
||||
Every member of <span class="font-semibold">{ws}</span> loses AI sessions and the AI assistant buttons.
|
||||
The page reloads on Home.
|
||||
</span>
|
||||
</ConfirmationModal>
|
||||
@@ -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<FolderInstructionRow[]>([])
|
||||
let folderLoadError = $state<string | undefined>(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<Record<string, boolean>>({})
|
||||
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<string, { workspace: string; content: string; original: string }>
|
||||
Record<string, { workspace: string; content: string; original: string; path: string }>
|
||||
>({})
|
||||
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
|
||||
<ListRow {icon} {title} {subtitle} onClick={() => openBlock(kind)} />
|
||||
{/snippet}
|
||||
|
||||
{#snippet focusPulse(focused: boolean)}
|
||||
<!-- `opacity-0` at rest: the keyframes carry no fill mode, so the overlay would come back
|
||||
at full strength once the animation ends. -->
|
||||
{#if focused && pulse !== played && !reducedMotion.val}
|
||||
{#key pulse}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
onanimationend={() => (played = pulse)}
|
||||
class="pointer-events-none absolute inset-0 rounded-lg ring-2 ring-inset ring-blue-500/60 bg-blue-500/10 opacity-0 animate-fade-out"
|
||||
></span>
|
||||
{/key}
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<!-- One folder and everything under it. Recursive: a path may name folders below the `u/x`
|
||||
or `f/x` root it starts from. -->
|
||||
{#snippet folder(node: SkillTreeNode<FolderInstructionRow>, root: boolean)}
|
||||
<div>
|
||||
<div class="relative">
|
||||
{@render focusPulse(root && node.path === focusRoot)}
|
||||
<button
|
||||
type="button"
|
||||
class="w-full flex items-center gap-2 px-2 py-2 text-left rounded-md hover:bg-surface-hover"
|
||||
aria-expanded={!collapsed[node.path]}
|
||||
onclick={() => (collapsed[node.path] = !collapsed[node.path])}
|
||||
aria-expanded={!isFolded(node.path)}
|
||||
onclick={() => (collapsed[node.path] = !isFolded(node.path))}
|
||||
>
|
||||
{#if collapsed[node.path]}
|
||||
{#if isFolded(node.path)}
|
||||
<ChevronRight size={14} class="text-tertiary shrink-0" />
|
||||
{:else}
|
||||
<ChevronDown size={14} class="text-tertiary shrink-0" />
|
||||
@@ -686,7 +743,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
|
||||
<span class="text-xs font-normal text-emphasis truncate">{node.label}</span>
|
||||
<span class="text-2xs text-secondary">{countSkills(node)}</span>
|
||||
</button>
|
||||
{#if !collapsed[node.path]}
|
||||
{#if !isFolded(node.path)}
|
||||
<div class="pl-4 flex flex-col gap-0.5">
|
||||
{#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
|
||||
</div>
|
||||
</div>
|
||||
<div class="{folderMode === 'edit' ? 'flex' : 'hidden'} flex-col gap-3">
|
||||
{#if detail?.kind === 'new'}
|
||||
{#if detail?.kind === 'new' || detail?.kind === 'folder'}
|
||||
<Label label="Path">
|
||||
<span class="text-xs font-normal text-secondary">
|
||||
The folder decides what these cover: every item under it, for everyone who can
|
||||
@@ -854,7 +911,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
|
||||
<Path
|
||||
bind:path={newPath}
|
||||
bind:error={newPathError}
|
||||
initialPath=""
|
||||
initialPath={detail.kind === 'folder' ? detail.row.path : ''}
|
||||
fullNamePlaceholder="AGENTS"
|
||||
kind="resource"
|
||||
workspaceOverride={ws}
|
||||
@@ -890,7 +947,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button
|
||||
onClick={() => setFolderContent(folderOriginal)}
|
||||
onClick={revertFolder}
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: RotateCcw }}
|
||||
@@ -903,15 +960,27 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
|
||||
variant="accent"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: detail?.kind === 'new' ? Plus : Pencil }}
|
||||
disabled={saving ||
|
||||
!folderChanged ||
|
||||
(detail?.kind === 'new' && (!newPath || !!newPathError))}
|
||||
disabled={saving || !folderChanged || !newPath || !!newPathError}
|
||||
>
|
||||
{detail?.kind === 'new' ? 'Add instructions' : 'Save instructions'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if detail?.kind === 'folder'}
|
||||
<div class="flex items-center gap-1 text-xs text-secondary">
|
||||
Stored as an <code>ai_instruction</code> resource.
|
||||
<Button
|
||||
href="/resources?path={encodeURIComponent(detail.row.path)}&workspace={ws}"
|
||||
target="_blank"
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
endIcon={{ icon: ExternalLink }}
|
||||
>
|
||||
Open in Resources
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
@@ -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}
|
||||
<div class="flex flex-col gap-0.5">
|
||||
{#each servers as server (server.path)}
|
||||
{#each shown as server (server.path)}
|
||||
{#snippet icon()}
|
||||
<McpServerIcon icon={server.icon} size={16} />
|
||||
{/snippet}
|
||||
@@ -531,6 +547,17 @@ switch that decides whether this chat carries its tools.
|
||||
onClick={() => openServer(server)}
|
||||
/>
|
||||
{/each}
|
||||
{#if shown.length < servers.length}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
wrapperClasses="self-start"
|
||||
btnClasses="text-secondary"
|
||||
onClick={() => (showAll = true)}
|
||||
>
|
||||
Show all {servers.length} connections
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</Section>
|
||||
|
||||
@@ -17,6 +17,7 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
| 'mcp'
|
||||
| 'files'
|
||||
| 'permissions'
|
||||
| 'danger'
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
@@ -28,22 +29,24 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
Plug,
|
||||
ScrollText,
|
||||
ShieldCheck,
|
||||
SlidersHorizontal
|
||||
TriangleAlert
|
||||
} from 'lucide-svelte'
|
||||
import Button from '$lib/components/common/button/Button.svelte'
|
||||
import Modal2 from '$lib/components/common/modal/Modal2.svelte'
|
||||
import SidebarNavigation from '$lib/components/common/sidebar/SidebarNavigation.svelte'
|
||||
import Tooltip from '$lib/components/meltComponents/Tooltip.svelte'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { getAiChatManager } from './aiChatManagerContext'
|
||||
import { summarizeTools } from './agentContext'
|
||||
import AssistantToolsSection from './AssistantToolsSection.svelte'
|
||||
import AssistantSkillsSection from './AssistantSkillsSection.svelte'
|
||||
import AssistantInstructionsSection from './AssistantInstructionsSection.svelte'
|
||||
import { tick } from 'svelte'
|
||||
import AssistantMcpSection from './AssistantMcpSection.svelte'
|
||||
import AssistantFilesSection from './AssistantFilesSection.svelte'
|
||||
import AssistantPermissionsSection from './AssistantPermissionsSection.svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
import AssistantDangerZoneSection from './AssistantDangerZoneSection.svelte'
|
||||
import { useActingUser } from '$lib/actingUser.svelte'
|
||||
|
||||
// Prefilled title marks the issue as AI Sessions feedback for triage.
|
||||
const FEEDBACK_ISSUE_URL =
|
||||
@@ -80,7 +83,8 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
instructions: instructionsBusy,
|
||||
mcp: mcpBusy,
|
||||
files: filesBusy,
|
||||
permissions: false
|
||||
permissions: false,
|
||||
danger: false
|
||||
})
|
||||
let blockingSection = $derived<AssistantSettingsSection | undefined>(
|
||||
busyBySection[section]
|
||||
@@ -118,24 +122,40 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
|
||||
// The session's capability surface, not this turn's: the heading answers what the
|
||||
// assistant can call here, so it must not shift when the autonomy picker does.
|
||||
// The danger zone writes the workspace's AI config, which only its admins may change.
|
||||
const acting = useActingUser(() => ws)
|
||||
let isWsAdmin = $derived(!!acting.current && (acting.current.is_admin || acting.current.is_super_admin))
|
||||
|
||||
let tools = $derived(summarizeTools(aiChatManager.availableTools))
|
||||
let providerTools = $derived(aiChatManager.providerTools)
|
||||
|
||||
/** The folder (`f/x` or `u/x`) the modal was opened on, from a folder's badge: in Skills
|
||||
* and Instructions it is the only top-level folder open, and MCP lists only its servers. */
|
||||
let focusRoot = $state<string | undefined>(undefined)
|
||||
|
||||
// `SidebarNavigation`'s item shape, which is what the instance and workspace settings
|
||||
// navs are built from too.
|
||||
let sections = $derived([
|
||||
{ id: 'tools', label: 'Tools', icon: Boxes, count: tools.length + providerTools.length },
|
||||
{ id: 'skills', label: 'Skills', icon: BookOpen, count: skillCount },
|
||||
{ id: 'instructions', label: 'Instructions', icon: ScrollText },
|
||||
// Folder instructions only: the workspace's and yours are fixed rows, set or not.
|
||||
{
|
||||
id: 'instructions',
|
||||
label: 'Instructions',
|
||||
icon: ScrollText,
|
||||
count: aiChatManager.scopeResources.instructions.length
|
||||
},
|
||||
{ id: 'mcp', label: 'MCP connections', icon: Plug, count: mcpCount },
|
||||
// The count is what is readable rather than what is attached: a locked folder under
|
||||
// a heading about what the assistant can use would say the opposite of the truth.
|
||||
{ id: 'files', label: 'Files & folders', icon: Paperclip, count: fileCount },
|
||||
{ id: 'permissions', label: 'Permissions', icon: ShieldCheck }
|
||||
{ id: 'permissions', label: 'Permissions', icon: ShieldCheck },
|
||||
...(isWsAdmin ? [{ id: 'danger', label: 'Danger zone', icon: TriangleAlert }] : [])
|
||||
])
|
||||
|
||||
/** Opens on `target`, or back on whichever section was last read. */
|
||||
export function open(target: AssistantSettingsSection = section) {
|
||||
focusRoot = undefined
|
||||
section = target
|
||||
isOpen = true
|
||||
refresh()
|
||||
@@ -143,6 +163,19 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
record(target)
|
||||
}
|
||||
|
||||
let skillsSection: AssistantSkillsSection | undefined = $state()
|
||||
let instructionsSection: AssistantInstructionsSection | undefined = $state()
|
||||
let mcpSection: AssistantMcpSection | undefined = $state()
|
||||
/** Opens on `target` focused on `root`. The sections mount with the modal. */
|
||||
export async function openFolder(target: AssistantSettingsSection, root: string) {
|
||||
open(target)
|
||||
focusRoot = root
|
||||
await tick()
|
||||
skillsSection?.showFolder()
|
||||
instructionsSection?.showFolder()
|
||||
mcpSection?.showFolder()
|
||||
}
|
||||
|
||||
// `context_panel` is the kind registered in `feature_usage_ee.rs`; an unregistered
|
||||
// pair is dropped silently, so the name is fixed there rather than here.
|
||||
//
|
||||
@@ -172,6 +205,7 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
// values the turn was actually given, which is the honest answer anyway.
|
||||
if (!aiChatManager.loading && !aiChatManager.sendInFlight) {
|
||||
void aiChatManager.refreshGlobalSkills()
|
||||
void aiChatManager.refreshGlobalFolderInstructions()
|
||||
void aiChatManager.refreshMcpServers()
|
||||
void aiChatManager.refreshSessionAccess()
|
||||
}
|
||||
@@ -180,23 +214,6 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
|
||||
<svelte:window onkeydown={onKeydown} />
|
||||
|
||||
<Tooltip small placement="top">
|
||||
<Button
|
||||
unifiedSize="2xs"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: SlidersHorizontal }}
|
||||
aria-label="Assistant settings"
|
||||
onClick={() => open()}
|
||||
/>
|
||||
{#snippet text()}
|
||||
<div class="max-w-64 text-xs">
|
||||
<p class="font-semibold">Assistant settings</p>
|
||||
<p class="mt-1">The tools, skills, instructions and MCP servers this chat can use.</p>
|
||||
</div>
|
||||
{/snippet}
|
||||
</Tooltip>
|
||||
|
||||
<Modal2
|
||||
bind:isOpen
|
||||
title="Assistant settings"
|
||||
@@ -254,7 +271,9 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
laid over each other, and each keeps a scroll position of its own. -->
|
||||
<div class="{section === 'skills' ? 'flex' : 'hidden'} grow min-h-0 flex-col overflow-hidden">
|
||||
<AssistantSkillsSection
|
||||
bind:this={skillsSection}
|
||||
{ws}
|
||||
{focusRoot}
|
||||
active={section === 'skills'}
|
||||
bind:count={skillCount}
|
||||
bind:blocksClose={skillsBusy}
|
||||
@@ -266,7 +285,9 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
: 'hidden'} grow min-h-0 flex-col overflow-hidden"
|
||||
>
|
||||
<AssistantInstructionsSection
|
||||
bind:this={instructionsSection}
|
||||
{ws}
|
||||
{focusRoot}
|
||||
active={section === 'instructions'}
|
||||
bind:blocksClose={instructionsBusy}
|
||||
/>
|
||||
@@ -275,7 +296,9 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
PagedContent pages laid over each other. -->
|
||||
<div class="{section === 'mcp' ? 'flex' : 'hidden'} grow min-h-0 flex-col overflow-hidden">
|
||||
<AssistantMcpSection
|
||||
bind:this={mcpSection}
|
||||
{ws}
|
||||
{focusRoot}
|
||||
active={section === 'mcp'}
|
||||
bind:count={mcpCount}
|
||||
bind:blocksClose={mcpBusy}
|
||||
@@ -289,6 +312,13 @@ callers that already know which section they mean, such as the "+" menu's Manage
|
||||
>
|
||||
<AssistantPermissionsSection {ws} />
|
||||
</div>
|
||||
{#if isWsAdmin}
|
||||
<div
|
||||
class="{section === 'danger' ? 'block' : 'hidden'} grow min-h-0 overflow-y-auto pr-2"
|
||||
>
|
||||
<AssistantDangerZoneSection {ws} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</Modal2>
|
||||
|
||||
@@ -25,11 +25,13 @@ and the actions that create, edit, import and delete them.
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { tick, untrack } from 'svelte'
|
||||
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
|
||||
import {
|
||||
ArrowLeft,
|
||||
BookOpen,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
Folder,
|
||||
FolderTree,
|
||||
@@ -45,7 +47,6 @@ and the actions that create, edit, import and delete them.
|
||||
import { forgetSkill, isSkillEnabled, setSkillEnabled } from './skills/enabledSkills'
|
||||
import { ownerRoot } from './workingScope'
|
||||
import {
|
||||
ambiguousSkillNames,
|
||||
deleteSkillResource,
|
||||
listSkillResources,
|
||||
readSkillBody,
|
||||
@@ -62,9 +63,9 @@ and the actions that create, edit, import and delete them.
|
||||
import {
|
||||
buildSkillTree,
|
||||
countSkills,
|
||||
foldedByDefault,
|
||||
folderKey,
|
||||
nodeSkills,
|
||||
skillFolderPaths,
|
||||
skillKey,
|
||||
visibleEntries,
|
||||
type SkillTreeEntry,
|
||||
@@ -74,11 +75,14 @@ and the actions that create, edit, import and delete them.
|
||||
let {
|
||||
ws,
|
||||
active,
|
||||
focusRoot,
|
||||
count = $bindable(),
|
||||
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. Gates the editor page's build: it is
|
||||
* worth paying for once someone is looking at skills, not on every open of a
|
||||
* modal whose other three sections have nothing to do with them. */
|
||||
@@ -190,25 +194,30 @@ What the assistant should do when this skill applies.
|
||||
let pendingSkipped: string[] = $state([])
|
||||
let overwriteChoices: Record<string, boolean> = $state({})
|
||||
|
||||
let ambiguous = $derived(ambiguousSkillNames(skills))
|
||||
// Skills in one folder are a list; spread over several, the folder is what tells
|
||||
// two of them apart, so they are grouped under it instead.
|
||||
let grouped = $derived(skillFolderPaths(skills).size > 1)
|
||||
let tree = $derived(buildSkillTree(skills))
|
||||
/** Folders the user closed, keyed by full prefix. Everything opens expanded: the
|
||||
* point of this list is seeing what the assistant carries. */
|
||||
/** Folders the user closed or opened, keyed by full prefix. Everything opens expanded
|
||||
* unless a folder is focused: the point of this list is seeing what the assistant carries. */
|
||||
let collapsed = $state<Record<string, boolean>>({})
|
||||
const isFolded = (path: string) => collapsed[path] ?? foldedByDefault(path, focusRoot)
|
||||
|
||||
/** Back on the list with the folds reset, for `focusRoot` to decide them. An editor
|
||||
* holding unsaved text stays open, as it does when the section is parked. */
|
||||
export function showFolder() {
|
||||
if (!contentChanged && !pathChanged) editorOpen = false
|
||||
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()
|
||||
/** The list top to bottom as it stands, for the keyboard to walk. Empty whenever
|
||||
* the rows are not the thing on screen — a reload after a save or a delete shows
|
||||
* the loading line, and a failed one shows the error, both over the rows this
|
||||
* would otherwise still walk. Flat mode has no folders, so the same keys drive
|
||||
* both layouts. */
|
||||
* would otherwise still walk. */
|
||||
let entries: SkillTreeEntry<Row>[] = $derived(
|
||||
loading || loadError !== undefined
|
||||
? []
|
||||
: grouped
|
||||
? visibleEntries(tree, (path) => collapsed[path] === true)
|
||||
: skills.map((skill) => ({ kind: 'skill', key: skillKey(skill.path), skill }))
|
||||
loading || loadError !== undefined ? [] : visibleEntries(tree, isFolded)
|
||||
)
|
||||
/** Where each entry sits in the walk, so a row rendered deep in the tree can say
|
||||
* whether it is the highlighted one. */
|
||||
@@ -233,7 +242,7 @@ What the assistant should do when this skill applies.
|
||||
const entry = entries[index]
|
||||
if (entry === undefined) return
|
||||
if (entry.kind === 'skill') openSkill(entry.skill)
|
||||
else fold(entry.key, entry.node.path, !collapsed[entry.node.path])
|
||||
else fold(entry.key, entry.node.path, !isFolded(entry.node.path))
|
||||
}
|
||||
// No `activateEnterFrom`: Enter is answered by `onListKeydown`, which does not
|
||||
// depend on where focus happens to be.
|
||||
@@ -409,7 +418,7 @@ What the assistant should do when this skill applies.
|
||||
} else if (event.key === 'Enter') {
|
||||
answer()
|
||||
if (current.kind === 'skill') openSkill(current.skill)
|
||||
else fold(current.key, current.node.path, !collapsed[current.node.path])
|
||||
else fold(current.key, current.node.path, !isFolded(current.node.path))
|
||||
} else if (event.key === 'ArrowRight') {
|
||||
answer()
|
||||
if (current.kind === 'skill') {
|
||||
@@ -417,14 +426,14 @@ What the assistant should do when this skill applies.
|
||||
// `PagedContent`, which steps to the editor page — showing whichever skill
|
||||
// it was last parked on, not this one.
|
||||
openSkill(current.skill)
|
||||
} else if (collapsed[current.node.path]) {
|
||||
} else if (isFolded(current.node.path)) {
|
||||
fold(current.key, current.node.path, false)
|
||||
} else {
|
||||
// Into what opening it revealed: the next row down is its first child.
|
||||
highlight.move(1)
|
||||
}
|
||||
} else if (event.key === 'ArrowLeft') {
|
||||
if (current.kind === 'folder' && !collapsed[current.node.path]) {
|
||||
if (current.kind === 'folder' && !isFolded(current.node.path)) {
|
||||
answer()
|
||||
fold(current.key, current.node.path, true)
|
||||
} else if (current.parentKey !== undefined) {
|
||||
@@ -946,15 +955,9 @@ What the assistant should do when this skill applies.
|
||||
/>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-0.5">
|
||||
{#if grouped}
|
||||
{#each tree as node (node.path)}
|
||||
{@render folder(node, true)}
|
||||
{/each}
|
||||
{:else}
|
||||
{#each skills as skill (skill.path)}
|
||||
{@render row(skill)}
|
||||
{/each}
|
||||
{/if}
|
||||
{#each tree as node (node.path)}
|
||||
{@render folder(node, true)}
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</Section>
|
||||
@@ -969,9 +972,8 @@ What the assistant should do when this skill applies.
|
||||
{/snippet}
|
||||
{#snippet title()}
|
||||
<span class="truncate leading-5">
|
||||
<!-- Grouped, the folder above the row is what tells two skills of the same
|
||||
name apart; flat, the path has to do it. -->
|
||||
{!grouped && ambiguous.has(skill.name) ? skill.path : skill.name}
|
||||
<!-- The folder above the row is what tells two skills of the same name apart. -->
|
||||
{skill.name}
|
||||
</span>
|
||||
{/snippet}
|
||||
{@const note = scopeNote(skill.path)}
|
||||
@@ -1023,10 +1025,25 @@ What the assistant should do when this skill applies.
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
{#snippet focusPulse(focused: boolean)}
|
||||
<!-- `opacity-0` at rest: the keyframes carry no fill mode, so the overlay would come back
|
||||
at full strength once the animation ends. -->
|
||||
{#if focused && pulse !== played && !reducedMotion.val}
|
||||
{#key pulse}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
onanimationend={() => (played = pulse)}
|
||||
class="pointer-events-none absolute inset-0 rounded-lg ring-2 ring-inset ring-blue-500/60 bg-blue-500/10 opacity-0 animate-fade-out"
|
||||
></span>
|
||||
{/key}
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<!-- One folder and everything under it. Recursive: a path may name folders below
|
||||
the `u/x` or `f/x` root it starts from. -->
|
||||
{#snippet folder(node: SkillTreeNode<Row>, root: boolean)}
|
||||
<div>
|
||||
<div class="relative">
|
||||
{@render focusPulse(root && node.path === focusRoot)}
|
||||
<!-- The switch sits beside the header button rather than inside it: a switch
|
||||
nested in a button would fold the folder on every flip. `pr-14` clears the
|
||||
row menu column, so a folder's switch stands in the same column as the
|
||||
@@ -1044,10 +1061,10 @@ What the assistant should do when this skill applies.
|
||||
<button
|
||||
type="button"
|
||||
class="grow min-w-0 flex items-center gap-2 px-2 py-2 text-left"
|
||||
aria-expanded={!collapsed[node.path]}
|
||||
onclick={() => fold(folderKey(node.path), node.path, !collapsed[node.path])}
|
||||
aria-expanded={!isFolded(node.path)}
|
||||
onclick={() => fold(folderKey(node.path), node.path, !isFolded(node.path))}
|
||||
>
|
||||
{#if collapsed[node.path]}
|
||||
{#if isFolded(node.path)}
|
||||
<ChevronRight size={14} class="text-tertiary shrink-0" />
|
||||
{:else}
|
||||
<ChevronDown size={14} class="text-tertiary shrink-0" />
|
||||
@@ -1071,7 +1088,7 @@ What the assistant should do when this skill applies.
|
||||
on:change={async (e) => await toggleFolder(node, e.detail)}
|
||||
/>
|
||||
</div>
|
||||
{#if !collapsed[node.path]}
|
||||
{#if !isFolded(node.path)}
|
||||
<div class="pl-4 flex flex-col gap-0.5">
|
||||
{#each node.children as child (child.path)}
|
||||
{@render folder(child, false)}
|
||||
@@ -1103,10 +1120,10 @@ What the assistant should do when this skill applies.
|
||||
Skills
|
||||
</Button>
|
||||
</div>
|
||||
<!-- `headerClass` keeps a long skill name on one line: the View/Edit group shares
|
||||
<!-- `headerClass` keeps a long skill path on one line: the View/Edit group shares
|
||||
the header row and would otherwise wrap the title under itself. -->
|
||||
<Section
|
||||
label={editing ? editing.name : 'New skill'}
|
||||
label={editing ? editing.path : 'New skill'}
|
||||
wrapperClass="mt-1"
|
||||
headerClass="min-w-0 truncate pr-2"
|
||||
>
|
||||
@@ -1204,6 +1221,20 @@ What the assistant should do when this skill applies.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if editing}
|
||||
<div class="flex items-center gap-1 text-xs text-secondary">
|
||||
Stored as an <code>ai_skill</code> resource.
|
||||
<Button
|
||||
href="/resources?path={encodeURIComponent(editing.path)}&workspace={ws}"
|
||||
target="_blank"
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
endIcon={{ icon: ExternalLink }}
|
||||
>
|
||||
Open in Resources
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
@@ -39,6 +39,7 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216
|
||||
import type { AttachedFile, AttachedFolder } from './files/attachedFiles.svelte'
|
||||
import {
|
||||
ContextIconMap,
|
||||
withFolderContextLeaves,
|
||||
type ContextElement,
|
||||
type WorkspaceAppElement,
|
||||
type WorkspaceFlowElement,
|
||||
@@ -266,12 +267,14 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216
|
||||
if (diffs) branches.push(diffs)
|
||||
if (modules) branches.push(modules)
|
||||
if (dbs) branches.push(dbs)
|
||||
const wsChildren = buildWorkspaceTree({
|
||||
loaded: loadedForTree,
|
||||
kinds: WORKSPACE_KINDS,
|
||||
loadingKind: loader.loadingKind,
|
||||
layout: 'flat'
|
||||
}) as DrillNode<ChatLeafData>[]
|
||||
const wsChildren: DrillNode<ChatLeafData>[] = withFolderContextLeaves(
|
||||
buildWorkspaceTree({
|
||||
loaded: loadedForTree,
|
||||
kinds: WORKSPACE_KINDS,
|
||||
loadingKind: loader.loadingKind,
|
||||
layout: 'flat'
|
||||
})
|
||||
)
|
||||
// Workspace-only (e.g. global chat with no diffs/modules/dbs): skip
|
||||
// the redundant 'Workspace' row and surface its children at the root.
|
||||
if (branches.length === 0) return wsChildren
|
||||
@@ -326,6 +329,9 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216
|
||||
}
|
||||
onSelectWorkspaceItem(element)
|
||||
}
|
||||
} else if (d.type === 'workspace_folder') {
|
||||
// A folder is a workspace reference like an item, never in availableContext.
|
||||
onSelectWorkspaceItem?.(d)
|
||||
} else {
|
||||
// Runtime context element — added directly.
|
||||
onSelect(d)
|
||||
|
||||
@@ -83,9 +83,7 @@ export default class ContextManager {
|
||||
this.workspace = workspace
|
||||
this.selectedContext = currentlySelectedContext.filter(
|
||||
(context) =>
|
||||
context.type === 'workspace_script' ||
|
||||
context.type === 'workspace_flow' ||
|
||||
context.type === 'workspace_app'
|
||||
isMentionContext(context)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -164,9 +162,7 @@ export default class ContextManager {
|
||||
newSelectedContext = newSelectedContext
|
||||
.filter(
|
||||
(c) =>
|
||||
c.type === 'workspace_script' ||
|
||||
c.type === 'workspace_flow' ||
|
||||
c.type === 'workspace_app' ||
|
||||
isMentionContext(c) ||
|
||||
newAvailableContext.some((ac) => ac.type === c.type && ac.title === c.title)
|
||||
)
|
||||
.map((c) =>
|
||||
@@ -293,9 +289,7 @@ export default class ContextManager {
|
||||
c.type === 'code' ||
|
||||
// Workspace references are user-picked via @-mention and not in
|
||||
// availableContext; preserve so badges survive editor refreshes.
|
||||
c.type === 'workspace_script' ||
|
||||
c.type === 'workspace_flow' ||
|
||||
c.type === 'workspace_app' ||
|
||||
isMentionContext(c) ||
|
||||
newAvailableContext.some((ac) => ac.type === c.type && ac.title === c.title)
|
||||
)
|
||||
.map((c) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!--
|
||||
@component
|
||||
Workspace-only picker for the AI session composer's `+ -> Mention file`
|
||||
submenu. It mirrors ChatContextPicker's workspace branch, but starts directly
|
||||
submenu. It mirrors ChatContextPicker's workspace branch, folders included, but starts directly
|
||||
at the workspace root because the parent menu item already names the scope.
|
||||
-->
|
||||
<script lang="ts">
|
||||
@@ -17,13 +17,17 @@ at the workspace root because the parent menu item already names the scope.
|
||||
import { useWorkspaceItemsLoader } from '$lib/components/workspaceItemsLoader.svelte'
|
||||
import { buildWorkspaceTree, relativizeWorkspacePath } from '$lib/components/workspaceTree'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
import type {
|
||||
ContextElement,
|
||||
WorkspaceAppElement,
|
||||
WorkspaceFlowElement,
|
||||
WorkspaceScriptElement
|
||||
import {
|
||||
withFolderContextLeaves,
|
||||
type ContextElement,
|
||||
type WorkspaceAppElement,
|
||||
type WorkspaceFlowElement,
|
||||
type WorkspaceFolderElement,
|
||||
type WorkspaceScriptElement
|
||||
} from './context'
|
||||
|
||||
type LeafData = WorkspaceItem | WorkspaceFolderElement
|
||||
|
||||
interface Props {
|
||||
onSelect: (element: ContextElement) => void
|
||||
onAfterClose?: () => void
|
||||
@@ -50,13 +54,15 @@ at the workspace root because the parent menu item already names the scope.
|
||||
return { ...loaded, app: loaded.app.filter((a) => a.raw_app) }
|
||||
})
|
||||
|
||||
const tree = $derived<DrillNode<WorkspaceItem>[]>(
|
||||
buildWorkspaceTree({
|
||||
loaded: loadedForTree,
|
||||
kinds: WORKSPACE_KINDS,
|
||||
loadingKind: loader.loadingKind,
|
||||
layout: 'flat'
|
||||
}) as DrillNode<WorkspaceItem>[]
|
||||
const tree = $derived<DrillNode<LeafData>[]>(
|
||||
withFolderContextLeaves(
|
||||
buildWorkspaceTree({
|
||||
loaded: loadedForTree,
|
||||
kinds: WORKSPACE_KINDS,
|
||||
loadingKind: loader.loadingKind,
|
||||
layout: 'flat'
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
function workspaceElement(item: WorkspaceItem): ContextElement | undefined {
|
||||
@@ -89,8 +95,8 @@ at the workspace root because the parent menu item already names the scope.
|
||||
}
|
||||
}
|
||||
|
||||
function handlePick(leaf: DrillLeaf<WorkspaceItem>) {
|
||||
const element = workspaceElement(leaf.data)
|
||||
function handlePick(leaf: DrillLeaf<LeafData>) {
|
||||
const element = 'kind' in leaf.data ? workspaceElement(leaf.data) : leaf.data
|
||||
if (!element) return
|
||||
onSelect(element)
|
||||
close(onAfterClose)
|
||||
@@ -119,11 +125,15 @@ at the workspace root because the parent menu item already names the scope.
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet leafIcon(leaf: DrillLeaf<WorkspaceItem>)}
|
||||
<RowIcon kind={leaf.data.kind} size={12} />
|
||||
{#snippet leafIcon(leaf: DrillLeaf<LeafData>)}
|
||||
{#if 'kind' in leaf.data}
|
||||
<RowIcon kind={leaf.data.kind} size={12} />
|
||||
{:else}
|
||||
<Folder size={12} class="shrink-0 text-tertiary" />
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet branchIcon(branch: DrillBranch<WorkspaceItem>)}
|
||||
{#snippet branchIcon(branch: DrillBranch<LeafData>)}
|
||||
{#if branch.icon}
|
||||
{@const Icon = branch.icon}
|
||||
<Icon size={12} class="shrink-0 text-tertiary" />
|
||||
@@ -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])}
|
||||
|
||||
@@ -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<L>(
|
||||
nodes: DrillNode<L>[]
|
||||
): DrillNode<L | WorkspaceFolderElement>[] {
|
||||
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<WorkspaceFolderElement> = {
|
||||
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 {
|
||||
|
||||
@@ -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<void> {
|
||||
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 } }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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`
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<T> = {
|
||||
|
||||
type Skill = { path: string; name: string }
|
||||
|
||||
/** The folders holding these skills — one entry per distinct parent path. */
|
||||
export function skillFolderPaths(skills: readonly Skill[]): Set<string> {
|
||||
return new Set(skills.map((s) => s.path.split('/').slice(0, -1).join('/')))
|
||||
}
|
||||
|
||||
/** Every skill under `node`, its subfolders included. */
|
||||
export function countSkills<T>(node: SkillTreeNode<T>): number {
|
||||
return node.skills.length + node.children.reduce((n, c) => n + countSkills(c), 0)
|
||||
@@ -40,6 +31,12 @@ export type SkillTreeEntry<T> = { 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 {
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -11,15 +11,12 @@
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { ExternalLink, Globe2, PinOff, PlugZap } from 'lucide-svelte'
|
||||
import { ExternalLink, Globe2, PlugZap } from 'lucide-svelte'
|
||||
import Button from '../common/button/Button.svelte'
|
||||
import CloseButton from '../common/CloseButton.svelte'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { hubBaseUrlStore, roleCapabilities, workspaceStore } from '$lib/stores'
|
||||
import { homeDraft, sessionState } from '../sessions/sessionState.svelte'
|
||||
import { currentWorkspaceRootId } from '../sessions/sessionScope.svelte'
|
||||
import { HOME_SHOW_HUB } from '$lib/consts'
|
||||
import { homeComposerPin, setHomeComposerRemoved } from './homeComposerPin.svelte'
|
||||
import { useReducedMotion } from '$lib/svelte5Utils.svelte'
|
||||
import { BROWSER } from 'esm-env'
|
||||
import HomeConnectDrawer from './HomeConnectDrawer.svelte'
|
||||
@@ -44,32 +41,7 @@
|
||||
|
||||
let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined)
|
||||
|
||||
// Whether this reader wants the composer on the home page at all. Starting a session puts
|
||||
// it back (see pinHomeComposer).
|
||||
const removed = $derived(homeComposerPin.removed)
|
||||
|
||||
// Removing puts the composer away rather than throwing it out, and the way back is one item in
|
||||
// the band's menu — so the ellipsis flashes as it appears, in a corner nobody is watching while
|
||||
// the composer leaves the page.
|
||||
//
|
||||
// A keyframe animation, not a transition: this mounts in the same flush that removes the
|
||||
// composer, so the frame that would paint it at rest is the frame it is already told to leave, and
|
||||
// one `requestAnimationFrame` is not reliably past that paint. The flash then goes straight to
|
||||
// invisible without ever being drawn. Mounted only while pulsing, so each removal replays it.
|
||||
const PULSE_MS = 1000
|
||||
const reducedMotion = useReducedMotion()
|
||||
let pulsing = $state(false)
|
||||
let pulseEndTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function removeComposer() {
|
||||
// The `close` key keeps these events in the series they have always been counted in.
|
||||
logFeatureUsage('home', 'ai_hero_remove', { key: 'close' })
|
||||
setHomeComposerRemoved(true)
|
||||
if (reducedMotion.val) return
|
||||
clearTimeout(pulseEndTimer)
|
||||
pulsing = true
|
||||
pulseEndTimer = setTimeout(() => (pulsing = false), PULSE_MS)
|
||||
}
|
||||
|
||||
let HomeSessionStarter = $state(loadedStarter)
|
||||
if (!loadedStarter) void loadStarter().then((c) => (HomeSessionStarter = c))
|
||||
@@ -91,23 +63,11 @@
|
||||
prefersSessionHandoff(!$roleCapabilities.code) && !inPreviewFrame && !homeAiHidden.hidden
|
||||
)
|
||||
|
||||
let hero = $derived(showComposer && !removed)
|
||||
</script>
|
||||
|
||||
<div class="w-full {hero ? 'mt-2' : 'mb-1'}">
|
||||
<div class="w-full {showComposer ? 'mt-2' : 'mb-1'}">
|
||||
<div class="relative group/composer">
|
||||
{#if hero}
|
||||
<!-- In the page's side padding, clear of the composer's own controls at its right end,
|
||||
and centred on the composer's first row: the one-line box's middle, and where that
|
||||
row stays once the box opens downward. Shown on hover; the container starts at the
|
||||
composer's edge so the pointer reaches the unpin button without leaving the hovered
|
||||
zone. Below `sm` there is no side padding to hold it, so unpinning is in the band's
|
||||
menu instead. -->
|
||||
<div
|
||||
class="hidden sm:block absolute top-4 left-full pl-1 z-20 transition-opacity opacity-0 group-hover/composer:opacity-100 focus-within:opacity-100"
|
||||
>
|
||||
<CloseButton small noBg Icon={PinOff} title="Unpin from Home" onClick={removeComposer} />
|
||||
</div>
|
||||
{#if showComposer}
|
||||
<!-- The block is a session's chat, so it waits for the sessions it might reuse. Keyed on
|
||||
the workspace family, not the workspace: another family needs its own draft, but a
|
||||
fork shares its parent's, and remounting for it only flashes the block. Also keyed
|
||||
@@ -132,14 +92,14 @@
|
||||
|
||||
<HomeConnectDrawer bind:this={homeConnectDrawer} />
|
||||
|
||||
<!-- Everything the hero offered beside the composer lives in the band's menu: the connect helper,
|
||||
the hub, and the way back to the composer once it has been put away. -->
|
||||
<!-- Everything the hero offered beside the composer lives in the band's menu: the connect helper
|
||||
and the hub. -->
|
||||
<!-- Last in the bar whatever else the page registers: a menu of side trips belongs after the
|
||||
buttons that act on what is on screen. -->
|
||||
<PageHeaderContent actions={homeMenu} actionsOrder={100} />
|
||||
|
||||
{#snippet homeMenu()}
|
||||
<!-- The band's own menu: the connect helper, the hub, and whether the composer is on this page
|
||||
<!-- The band's own menu: the connect helper, the hub, and the way back to favorites & recent
|
||||
— all of them preferences or side trips, none of them the page's work. -->
|
||||
<span class="flex items-center gap-1">
|
||||
<!-- Wide enough, and the two side trips are buttons of their own: a menu is where a thing
|
||||
@@ -172,26 +132,12 @@
|
||||
</Button>
|
||||
{/if}
|
||||
{/if}
|
||||
<!-- Nothing left to hold once the side trips stand in the bar and the composer is on the
|
||||
page: an ellipsis that opens an empty menu is a button that does nothing. -->
|
||||
<!-- No menu while the hero is on the page and its side trips are in the bar: the hero's own
|
||||
unpin button removes it, so an ellipsis holding a second way to do that is a button whose only
|
||||
item is a duplicate. -->
|
||||
{#if !sideTripsInBar || (showComposer && removed) || homeQuickAccessSettings.hidden}
|
||||
<!-- The flash rides the ellipsis itself, not the row: with the side trips beside it the
|
||||
row is three controls wide, and marking all three names none of them. -->
|
||||
<!-- Nothing left to hold once the side trips stand in the bar: an ellipsis that opens an
|
||||
empty menu is a button that does nothing. -->
|
||||
{#if !sideTripsInBar || homeQuickAccessSettings.hidden}
|
||||
<span class="relative inline-flex">
|
||||
{#if pulsing}
|
||||
<!-- `opacity-0` at rest: the keyframes carry no fill mode, so at the end of the
|
||||
animation the element returns to its own opacity. At 1 that is the flash coming
|
||||
back at full strength until the unmount timer catches up. -->
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none absolute -inset-1 rounded-lg bg-blue-500/30 opacity-0 animate-fade-out"
|
||||
></span>
|
||||
{/if}
|
||||
<!-- The same flash for hiding the favorites & recent section. It rests at opacity 0, so
|
||||
it can stay mounted; the key replays it on each hide. -->
|
||||
<!-- Hiding favorites & recent puts its way back in this menu, so the ellipsis flashes on
|
||||
each hide. It rests at opacity 0, so it can stay mounted; the key replays it. -->
|
||||
{#if homeQuickAccessSettings.hideCount > 0 && !reducedMotion.val}
|
||||
{#key homeQuickAccessSettings.hideCount}
|
||||
<span
|
||||
@@ -205,20 +151,6 @@
|
||||
size="sm"
|
||||
customWidth={240}
|
||||
items={[
|
||||
// Every phone gets the menu, and there the composer has no room for its own unpin
|
||||
// button. The menu can also hold the section's pin, so the label names the session.
|
||||
...(hero ? [{ displayName: 'Unpin session from Home', action: removeComposer }] : []),
|
||||
...(showComposer && removed
|
||||
? [
|
||||
{
|
||||
displayName: 'Pin session hero to homepage',
|
||||
action: () => {
|
||||
logFeatureUsage('home', 'ai_hero_pin')
|
||||
setHomeComposerRemoved(false)
|
||||
}
|
||||
}
|
||||
]
|
||||
: []),
|
||||
...(homeQuickAccessSettings.hidden
|
||||
? [
|
||||
{
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
<!--
|
||||
@component
|
||||
What a folder or user row carries for the assistant: its instructions, skills and MCP servers,
|
||||
counted on the row and named in a popover.
|
||||
one button each, counted. A click opens that section of Assistant settings on the folder.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/common'
|
||||
import Popover from '$lib/components/meltComponents/Popover.svelte'
|
||||
import { BookOpen, ExternalLink } from 'lucide-svelte'
|
||||
import { BookOpen, Plug, ScrollText } from 'lucide-svelte'
|
||||
import { homeComposerContext } from '../sessions/homeComposerContext.svelte'
|
||||
import { scopeBadge, scopeOption, scopeRule } from '../copilot/chat/workingScope'
|
||||
import { scopeOption } from '../copilot/chat/workingScope'
|
||||
|
||||
let { root }: { root: string } = $props()
|
||||
|
||||
@@ -16,60 +15,48 @@ counted on the row and named in a popover.
|
||||
const row = $derived(
|
||||
manager ? scopeOption(root, manager.scopeIdentity, manager.scopeResources) : undefined
|
||||
)
|
||||
const badge = $derived(row ? scopeBadge(row) : '')
|
||||
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
|
||||
const parts = $derived(
|
||||
row
|
||||
? [
|
||||
{
|
||||
section: 'instructions' as const,
|
||||
icon: ScrollText,
|
||||
count: row.instructions.length,
|
||||
label: plural(row.instructions.length, 'instruction')
|
||||
},
|
||||
{
|
||||
section: 'skills' as const,
|
||||
icon: BookOpen,
|
||||
count: row.skills.length,
|
||||
label: plural(row.skills.length, 'skill')
|
||||
},
|
||||
{
|
||||
section: 'mcp' as const,
|
||||
icon: Plug,
|
||||
count: row.mcpServers.length,
|
||||
label: `${row.mcpServers.length} MCP`
|
||||
}
|
||||
].filter((p) => p.count > 0)
|
||||
: []
|
||||
)
|
||||
</script>
|
||||
|
||||
{#if row && badge}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div onclick={(e) => e.stopPropagation()}>
|
||||
<Popover placement="bottom-end" contentClasses="p-3 w-72 flex flex-col gap-2 text-xs">
|
||||
{#snippet trigger()}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="2xs"
|
||||
startIcon={{ icon: BookOpen }}
|
||||
nonCaptureEvent
|
||||
>
|
||||
{badge}
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
{#if row.instructions.length}
|
||||
<div>
|
||||
<p class="text-2xs text-secondary">Instructions</p>
|
||||
{#each row.instructions as path (path)}
|
||||
<p class="font-mono text-primary">{path}</p>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if row.skills.length}
|
||||
<div>
|
||||
<p class="text-2xs text-secondary">Skills</p>
|
||||
{#each row.skills as path (path)}
|
||||
<p class="font-mono text-primary">{path}</p>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if row.mcpServers.length}
|
||||
<div>
|
||||
<p class="text-2xs text-secondary">MCP servers</p>
|
||||
{#each row.mcpServers as path (path)}
|
||||
<p class="font-mono text-primary">{path}</p>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<p class="text-2xs text-secondary">{scopeRule(root)}</p>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
endIcon={{ icon: ExternalLink }}
|
||||
href="/resources?owner={encodeURIComponent(root)}"
|
||||
btnClasses="!justify-start !px-0"
|
||||
>
|
||||
Open {root} in Resources
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
</div>
|
||||
{#if parts.length}
|
||||
<span class="inline-flex items-center gap-0.5">
|
||||
{#each parts as part (part.section)}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="2xs"
|
||||
startIcon={{ icon: part.icon }}
|
||||
title="Open in Assistant settings"
|
||||
onClick={(e) => {
|
||||
e?.stopPropagation()
|
||||
homeComposerContext.openSettings(part.section, root)
|
||||
}}
|
||||
>
|
||||
{part.label}
|
||||
</Button>
|
||||
{/each}
|
||||
</span>
|
||||
{/if}
|
||||
|
||||
@@ -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<string, RecentKind>()
|
||||
async function editorKind(item: Entry): Promise<RecentKind> {
|
||||
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<Item[]> {
|
||||
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 @@
|
||||
<svelte:window bind:innerWidth />
|
||||
|
||||
{#snippet card(item: Entry, favorite: boolean)}
|
||||
{@const mentionable = canMention(item)}
|
||||
{@const draft = draftByItem.get(`${item.starKind}/${item.path}`)}
|
||||
<div
|
||||
onpointerenter={() => 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"
|
||||
>
|
||||
<a
|
||||
@@ -413,7 +437,9 @@
|
||||
{/if}
|
||||
{#if !favorite && item.at}
|
||||
<span
|
||||
class="shrink-0 text-2xs text-secondary"
|
||||
class="shrink-0 text-2xs text-secondary {mentionable
|
||||
? 'group-has-[[data-composer-open]]/home:group-hover:hidden group-has-[[data-composer-open]]/home:group-focus-within:hidden'
|
||||
: ''}"
|
||||
title={recentTooltip(item.at, item.via)}
|
||||
onmouseenter={() => (now = Date.now())}
|
||||
role="note"
|
||||
@@ -421,9 +447,33 @@
|
||||
<TimeAgo date={new Date(item.at).toISOString()} compact noSeconds />
|
||||
</span>
|
||||
{/if}
|
||||
<div class="shrink-0 pr-1 text-secondary">
|
||||
<!-- While Home's composer is open the menu gives way to Mention, like the items' rows
|
||||
(AskAiRowButton). -->
|
||||
<div
|
||||
class="shrink-0 pr-1 text-secondary {mentionable
|
||||
? 'group-has-[[data-composer-open]]/home:hidden'
|
||||
: ''}"
|
||||
>
|
||||
<DropdownV2 items={() => menuItems(item, favorite)} size="xs" fixedHeight={false} />
|
||||
</div>
|
||||
{#if mentionable}
|
||||
<!-- Takes the time's place on the hovered or focused card only: holding a place on every
|
||||
card would leave the narrow cards no room for their titles. -->
|
||||
<div
|
||||
class="shrink-0 pr-1 hidden group-has-[[data-composer-open]]/home:group-hover:block group-has-[[data-composer-open]]/home:group-focus-within:block"
|
||||
>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
btnClasses="!text-ai font-medium"
|
||||
title="Mention"
|
||||
aria-label="Mention {item.title}"
|
||||
onClick={() => mention(item)}
|
||||
>
|
||||
+@
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
|
||||
@@ -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}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="flex" onclick={(e) => e.stopPropagation()}>{@render lead()}</div>
|
||||
{/if}
|
||||
<Icon size={16} class="text-secondary shrink-0" />
|
||||
<div>
|
||||
<div class="flex flex-row items-center gap-1">
|
||||
|
||||
@@ -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 {
|
||||
@@ -64,10 +66,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<TreeOpenMemory, 'isOpen' | 'setOpen'>
|
||||
// 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 +95,9 @@
|
||||
indent = 0,
|
||||
leaf,
|
||||
openMemory,
|
||||
onManageFolder
|
||||
onManageFolder,
|
||||
ownerLead,
|
||||
ownerDetail
|
||||
}: Props = $props()
|
||||
|
||||
const unruled = inUnruledList()
|
||||
@@ -113,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
|
||||
@@ -306,10 +316,35 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet folderBadge()}
|
||||
{#if badgeRoot}
|
||||
<HomeFolderBadge root={badgeRoot} />
|
||||
{/if}
|
||||
{#snippet folderTrailing()}
|
||||
<span class="flex flex-row items-center gap-2">
|
||||
{#if badgeRoot}
|
||||
<HomeFolderBadge root={badgeRoot} />
|
||||
{/if}
|
||||
{#if mentionRoot}
|
||||
{@const path = mentionRoot}
|
||||
<!-- While Home's composer is open its place is kept on every row, so the badges stay put
|
||||
to its left, and it shows on the hovered or tabbed-into row. The row toggles on click,
|
||||
so the press stops here. -->
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="hidden group-has-[[data-composer-open]]/home:inline-flex invisible group-hover/row:visible group-has-[:focus-visible]/row:visible"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
btnClasses="!text-ai font-medium"
|
||||
title="Add to AI session context"
|
||||
aria-label="Add {path} to AI session context"
|
||||
onClick={() => homeComposerContext.attach(folderContextElement(path))}
|
||||
>
|
||||
+@
|
||||
</Button>
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
{/snippet}
|
||||
|
||||
{#snippet manageFolderMenu()}
|
||||
@@ -325,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,
|
||||
@@ -335,6 +377,12 @@
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet ownerLeadForNode()}
|
||||
{#if nodePrefix != undefined}
|
||||
{@render ownerLead?.(nodePrefix)}
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#if isFolder(item) || isUser(item)}
|
||||
<div>
|
||||
<TreeOwnerRow
|
||||
@@ -345,7 +393,8 @@
|
||||
expandable={!empty || opened}
|
||||
indent={visualDepth * 16}
|
||||
actions={onManageFolder && depth === 0 && isFolder(item) ? manageFolderMenu : undefined}
|
||||
trailing={badgeRoot ? folderBadge : undefined}
|
||||
lead={ownerLead && nodePrefix != undefined ? ownerLeadForNode : undefined}
|
||||
trailing={badgeRoot ? folderTrailing : undefined}
|
||||
>
|
||||
{#snippet detail()}
|
||||
{#if ownerCount != undefined}
|
||||
@@ -362,6 +411,9 @@
|
||||
{:else}
|
||||
({pluralize(loadedHere, ' item')})
|
||||
{/if}
|
||||
{#if ownerDetail && nodePrefix != undefined}
|
||||
{@render ownerDetail(nodePrefix)}
|
||||
{/if}
|
||||
{/snippet}
|
||||
</TreeOwnerRow>
|
||||
<!-- ResizeObserver, not a slide: a freshly-opened owner fetches its rows, so its height
|
||||
@@ -400,6 +452,8 @@
|
||||
{indent}
|
||||
{leaf}
|
||||
{onManageFolder}
|
||||
{ownerLead}
|
||||
{ownerDetail}
|
||||
/>
|
||||
{/each}
|
||||
{#if effectiveMax < item.items.length}
|
||||
|
||||
@@ -52,9 +52,13 @@
|
||||
// See TreeView's `leaf`.
|
||||
leaf?: Snippet<[ItemType, number]>
|
||||
// See TreeView's `openMemory`.
|
||||
openMemory?: TreeOpenMemory
|
||||
openMemory?: Pick<TreeOpenMemory, 'isOpen' | 'setOpen'>
|
||||
// See TreeView's `onManageFolder`.
|
||||
onManageFolder?: (folderName: string) => void
|
||||
// See TreeView's `ownerLead`.
|
||||
ownerLead?: Snippet<[string]>
|
||||
// See TreeView's `ownerDetail`.
|
||||
ownerDetail?: Snippet<[string]>
|
||||
// Inject folders `ownerCounts` calls empty, as "0 items". Off under a kind filter,
|
||||
// where those counts are per kind and every folder lacking that kind would show.
|
||||
keepEmptyFolders?: boolean
|
||||
@@ -85,6 +89,8 @@
|
||||
leaf,
|
||||
openMemory,
|
||||
onManageFolder,
|
||||
ownerLead,
|
||||
ownerDetail,
|
||||
keepEmptyFolders = false,
|
||||
keptFolders
|
||||
}: Props = $props()
|
||||
@@ -295,6 +301,8 @@
|
||||
{leaf}
|
||||
{openMemory}
|
||||
{onManageFolder}
|
||||
{ownerLead}
|
||||
{ownerDetail}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -91,6 +91,7 @@
|
||||
},
|
||||
focus: () => aiChat?.focusInput(),
|
||||
flash: () => aiChat?.flashComposer(),
|
||||
openSettings: (section, root) => aiChat?.openAssistantSettings(section, root),
|
||||
runtime
|
||||
})
|
||||
})
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
selectSession,
|
||||
sessionPageHref,
|
||||
sessionLastActivityAt,
|
||||
sessionLastStateChangeAt,
|
||||
sessionState,
|
||||
setSessionArchived,
|
||||
syncWorkspaceTo,
|
||||
@@ -199,8 +200,8 @@
|
||||
})
|
||||
)
|
||||
|
||||
// Sessions grouped by workspace family for display, each group newest-first.
|
||||
// Family order is stable (by most-recent activity) and deliberately NOT tied
|
||||
// Sessions grouped by workspace family for display, each group by its last turn
|
||||
// start or end, latest first. Family order follows its latest session and is NOT tied
|
||||
// to the current workspace: pinning the active family first reshuffled the
|
||||
// whole list on every workspace switch, which is disorienting.
|
||||
const sessionGroups = $derived.by(() => {
|
||||
@@ -212,12 +213,12 @@
|
||||
else byRoot.set(root, [s])
|
||||
}
|
||||
const groups = [...byRoot.entries()].map(([rootId, sessions]) => {
|
||||
sessions.sort((a, b) => b.createdAt - a.createdAt)
|
||||
sessions.sort((a, b) => sessionLastStateChangeAt(b) - sessionLastStateChangeAt(a))
|
||||
return {
|
||||
rootId,
|
||||
name: $userWorkspaces.find((w) => w.id === rootId)?.name || rootId || 'Workspace',
|
||||
sessions,
|
||||
mostRecent: sessions[0]?.createdAt ?? 0
|
||||
mostRecent: sessions[0] ? sessionLastStateChangeAt(sessions[0]) : 0
|
||||
}
|
||||
})
|
||||
groups.sort((a, b) => b.mostRecent - a.mostRecent)
|
||||
@@ -233,7 +234,7 @@
|
||||
return all.filter((i) => workspaceRootId(i.workspace.id, $userWorkspaces) === currentRoot)
|
||||
})
|
||||
|
||||
// Sessions keyed by their exact workspace, newest-first — nested under each
|
||||
// Sessions keyed by their exact workspace, latest turn first — nested under each
|
||||
// workspace node in tree mode.
|
||||
const sessionsByWorkspace = $derived.by(() => {
|
||||
const map = new Map<string, Session[]>()
|
||||
@@ -244,7 +245,8 @@
|
||||
if (arr) arr.push(s)
|
||||
else map.set(wsId, [s])
|
||||
}
|
||||
for (const arr of map.values()) arr.sort((a, b) => b.createdAt - a.createdAt)
|
||||
for (const arr of map.values())
|
||||
arr.sort((a, b) => sessionLastStateChangeAt(b) - sessionLastStateChangeAt(a))
|
||||
return map
|
||||
})
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -66,6 +66,16 @@ describe('planSessionPush', () => {
|
||||
expect(plan?.images).toEqual([])
|
||||
})
|
||||
|
||||
it('pushes the head when a turn moves the sort key, so a restore keeps the order', () => {
|
||||
const plan = planSessionPush({
|
||||
session: session({ lastStateChangeAt: 42 }),
|
||||
chats: [chat('c1', 10, ['i1'])],
|
||||
artifacts: noArtifacts,
|
||||
sync: synced()
|
||||
})
|
||||
expect(plan?.entry?.head).toMatchObject({ lastStateChangeAt: 42 })
|
||||
})
|
||||
|
||||
it('carries only the chat whose lastModified moved, plus its new images', () => {
|
||||
const plan = planSessionPush({
|
||||
session: session(),
|
||||
|
||||
@@ -98,6 +98,7 @@ export type SessionHead = Pick<
|
||||
| 'activePreviewTabId'
|
||||
| 'previewCollapsed'
|
||||
| 'previewSize'
|
||||
| 'lastStateChangeAt'
|
||||
>
|
||||
|
||||
export function sessionHead(s: Session): SessionHead {
|
||||
@@ -113,6 +114,7 @@ export function sessionHead(s: Session): SessionHead {
|
||||
if (s.activePreviewTabId !== undefined) head.activePreviewTabId = s.activePreviewTabId
|
||||
if (s.previewCollapsed !== undefined) head.previewCollapsed = s.previewCollapsed
|
||||
if (s.previewSize !== undefined) head.previewSize = s.previewSize
|
||||
if (s.lastStateChangeAt !== undefined) head.lastStateChangeAt = s.lastStateChangeAt
|
||||
return head
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,9 @@ import {
|
||||
commitSessionWorkspace,
|
||||
deleteSession as deleteSessionState,
|
||||
getEffectiveWorkspaceId,
|
||||
markSessionStateChanged,
|
||||
materializeTransient,
|
||||
noteRemoteStateChange,
|
||||
sessionState,
|
||||
setGeneratedSessionSummary,
|
||||
setSessionChatId,
|
||||
@@ -453,6 +455,7 @@ function createRuntime(session: Session): SessionRuntime {
|
||||
// tabs re-read whichever record it ended on.
|
||||
manager.runHeldElsewhereResolver = () => runHeldElsewhere(session.id)
|
||||
manager.onRunningChanged = (running) => {
|
||||
markSessionStateChanged(session.id)
|
||||
if (running) localRunStarted(session.id, manager.historyManager.getCurrentChatId())
|
||||
else localRunEnded(session.id, manager.historyManager.getCurrentChatId())
|
||||
}
|
||||
@@ -1436,6 +1439,7 @@ export function getRuntime(sessionId: string): SessionRuntime | undefined {
|
||||
const catchUps = new Map<string, Promise<void>>()
|
||||
|
||||
onRemoteTurnEnd((sessionId, chatId) => {
|
||||
noteRemoteStateChange(sessionId)
|
||||
const next = (catchUps.get(sessionId) ?? Promise.resolve())
|
||||
.then(() => applyRemoteTurnEnd(sessionId, chatId))
|
||||
.catch((e) => console.error('Failed to catch up on a turn from another tab', e))
|
||||
|
||||
@@ -138,6 +138,9 @@ export type Session = {
|
||||
// Absent on records last written before the field existed; readers fall back
|
||||
// to createdAt via sessionLastActivityAt.
|
||||
lastActivityAt?: number
|
||||
// Epoch ms of the last time a turn started or ended. The ungrouped sidebar list orders by
|
||||
// it, so typing, renaming, archiving or switching preview tabs does not move a session there.
|
||||
lastStateChangeAt?: number
|
||||
// When this browser restored the session from its backup, by this browser's clock.
|
||||
// The restore sets `lastActivityAt` to the backup's time, the storage's clock; the
|
||||
// retention counts from whichever is later, so a browser clock ahead of the storage's
|
||||
@@ -498,6 +501,30 @@ export function sessionLastActivityAt(s: Session): number {
|
||||
return s.lastActivityAt ?? s.createdAt
|
||||
}
|
||||
|
||||
/** The ungrouped sidebar's sort key: the last turn start or end. A session that never ran a
|
||||
* turn (an unsent draft, a record from before the field) sorts by creation, since its last
|
||||
* activity moves on the very touches this key ignores. */
|
||||
export function sessionLastStateChangeAt(s: Session): number {
|
||||
return s.lastStateChangeAt ?? s.createdAt
|
||||
}
|
||||
|
||||
/** Stamps a turn starting or ending. A turn is a use of the session, so it is a touch too. */
|
||||
export function markSessionStateChanged(id: string): void {
|
||||
const s = sessionState.sessions.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
s.lastStateChangeAt = Date.now()
|
||||
persistTouched(s)
|
||||
}
|
||||
|
||||
/** A turn another tab ran: the driving tab persisted the stamp, so this tab only re-sorts.
|
||||
* Writing here would put this tab's stale copy of the whole record (title, tabs, committed
|
||||
* workspace) over the driver's; carrying the stamp in memory also keeps any later write
|
||||
* from this tab from rolling it back. */
|
||||
export function noteRemoteStateChange(id: string): void {
|
||||
const s = sessionState.sessions.find((x) => x.id === id)
|
||||
if (s) s.lastStateChangeAt = Date.now()
|
||||
}
|
||||
|
||||
// Sessions whose record has been removed from IndexedDB. Ids come from createLongHash
|
||||
// and are never reused, so an entry can only ever match the record it was recorded for.
|
||||
// In-memory by design: a reload re-runs reconciliation, which re-derives the set.
|
||||
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
homeStarterSession,
|
||||
isForkSession,
|
||||
isTearingDownOpenSession,
|
||||
markSessionStateChanged,
|
||||
opensOnHome,
|
||||
sessionLastStateChangeAt,
|
||||
renameSession,
|
||||
setDraftsDiscardedHandler,
|
||||
sessionInCurrentFamily,
|
||||
@@ -347,6 +349,32 @@ describe('session summary generation guards', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('sessionLastStateChangeAt', () => {
|
||||
it('moves on a turn, not on a rename', () => {
|
||||
const now = Date.now()
|
||||
const older = { id: 'sort-older-draft', name: 'd', createdAt: now - 60_000 } as Session
|
||||
const newer = {
|
||||
id: 'sort-newer',
|
||||
name: 'n',
|
||||
createdAt: now - 30_000,
|
||||
lastStateChangeAt: now - 1
|
||||
} as Session
|
||||
sessionState.sessions.push(older, newer)
|
||||
const entry = (id: string) => sessionState.sessions.find((x) => x.id === id)!
|
||||
try {
|
||||
markSessionStateChanged(older.id)
|
||||
const stamped = sessionLastStateChangeAt(entry(older.id))
|
||||
expect(stamped).toBeGreaterThan(sessionLastStateChangeAt(entry(newer.id)))
|
||||
renameSession(older.id, 'Renamed')
|
||||
expect(sessionLastStateChangeAt(entry(older.id))).toBe(stamped)
|
||||
} finally {
|
||||
sessionState.sessions = sessionState.sessions.filter(
|
||||
(s) => s.id !== older.id && s.id !== newer.id
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('decideSessionLifecycle — the never-orphaned rule (pure)', () => {
|
||||
const mk = (over: Partial<Session> = {}): Session => ({
|
||||
id: 'x',
|
||||
|
||||
@@ -62,6 +62,7 @@ import {
|
||||
setSessionDraftPrompt,
|
||||
setSessionTabs,
|
||||
setSessionChatId,
|
||||
noteRemoteStateChange,
|
||||
reconcileSessionsLifecycle,
|
||||
__resetDeletedSessionIdsForTesting,
|
||||
setSessionArchived,
|
||||
@@ -180,6 +181,29 @@ describe('sessionState IndexedDB persistence', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it("noteRemoteStateChange re-sorts without writing this tab's stale copy", async () => {
|
||||
const user = freshUser()
|
||||
await login(user)
|
||||
|
||||
const stale = session({ id: 's1', createdAt: 100, summary: 'old summary' })
|
||||
await putSession(stale)
|
||||
await putSession(
|
||||
session({ id: 's1', createdAt: 100, summary: 'newer summary', lastStateChangeAt: 500 })
|
||||
)
|
||||
|
||||
sessionState.sessions = [stale]
|
||||
noteRemoteStateChange('s1')
|
||||
await flush()
|
||||
expect(sessionState.sessions[0].lastStateChangeAt).toBeGreaterThan(500)
|
||||
|
||||
await rehydrate(user)
|
||||
await vi.waitFor(() => {
|
||||
const s = sessionState.sessions.find((x) => x.id === 's1')
|
||||
expect(s?.summary).toBe('newer summary')
|
||||
expect(s?.lastStateChangeAt).toBe(500)
|
||||
})
|
||||
})
|
||||
|
||||
it('does not persist a transient (untouched) session — it is in-memory only', async () => {
|
||||
const user = freshUser()
|
||||
await login(user)
|
||||
|
||||
@@ -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<vo
|
||||
}
|
||||
|
||||
// A plain session starts on Home, and an unsent draft is shown there rather than on a
|
||||
// page of its own. Asking for one puts the composer back on Home if the reader had
|
||||
// unpinned it: there is nowhere else to type it.
|
||||
// page of its own.
|
||||
async function toHome(id: string, opts?: { replace?: boolean; flash?: boolean }): Promise<void> {
|
||||
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.
|
||||
|
||||
@@ -23,18 +23,22 @@
|
||||
import RawAppRecordSession from './RawAppRecordSession.svelte'
|
||||
import AssetGraphCanvas from '$lib/components/assets/AssetGraph/AssetGraphCanvas.svelte'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Cloud,
|
||||
Code2,
|
||||
Database,
|
||||
Eye,
|
||||
ExternalLink,
|
||||
FolderTree,
|
||||
Image as ImageIcon,
|
||||
Info,
|
||||
LayoutDashboard,
|
||||
Loader2,
|
||||
Play,
|
||||
Plus,
|
||||
RotateCcw,
|
||||
TriangleAlert,
|
||||
X,
|
||||
@@ -43,19 +47,113 @@
|
||||
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
|
||||
import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte'
|
||||
import Popover from '$lib/components/Popover.svelte'
|
||||
import { untrack } from 'svelte'
|
||||
|
||||
// Folder name (no `f/`) this project is scoped to; provided by the /folders launcher.
|
||||
let { folder: folderProp }: { folder: string } = $props()
|
||||
|
||||
// The whole folder or one of its sub-paths (`hub/billing`); each is its own Hub project.
|
||||
let scope = $state(untrack(() => folderProp))
|
||||
|
||||
// All deploy state lives in a session keyed by (workspace, folder): switching
|
||||
// either replaces the instance (and the {#key} below remounts the UI, closing
|
||||
// drawers), so nothing here needs resetting by hand.
|
||||
const deployHub = useDeployToHubSession({
|
||||
workspace: () => $workspaceStore,
|
||||
folder: () => folderProp,
|
||||
folder: () => scope,
|
||||
listFolder: () => folderProp,
|
||||
hasEeLicense: () => !!$enterpriseLicense
|
||||
})
|
||||
|
||||
// Until a scope has a Hub project, its selection decides which project it is.
|
||||
// Waiting on `hubChecked` keeps an existing project from being left before it is found.
|
||||
$effect(() => {
|
||||
const s = deployHub.session
|
||||
if (!s || s.phase !== 'predeploy' || s.effectiveSlug || !s.hubChecked) return
|
||||
if (s.selectedItems.length && s.selectionScope !== s.folder) scope = s.selectionScope
|
||||
})
|
||||
|
||||
type HubProject = { folder: string; status: string; name: string }
|
||||
// The folder's Hub projects (the whole folder and any sub-paths), found once when the
|
||||
// drawer opens; undefined until then. None: the tree. Only the whole folder: that
|
||||
// project, as on main. Any sub-path project: a list to pick from, the one place to
|
||||
// start another.
|
||||
let projects = $state<HubProject[] | undefined>(undefined)
|
||||
let showList = $state(false)
|
||||
const wholeIsProject = $derived(!!projects?.some((p) => p.folder === folderProp))
|
||||
const hasSubProjects = $derived(!!projects?.some((p) => p.folder !== folderProp))
|
||||
|
||||
function statusOf(s: DeployToHubSession): string {
|
||||
return s.liveOnHub || s.phase === 'live'
|
||||
? 'live'
|
||||
: s.phase === 'under_review'
|
||||
? 'under_review'
|
||||
: 'draft'
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const s = deployHub.session
|
||||
if (projects || !s || s.folder !== folderProp || !s.hubChecked || !s.subProjectsChecked) return
|
||||
const found: HubProject[] = [
|
||||
...(s.effectiveSlug
|
||||
? [{ folder: folderProp, status: statusOf(s), name: s.hubName || s.hubSlug }]
|
||||
: []),
|
||||
...s.subProjects
|
||||
]
|
||||
projects = found
|
||||
showList = s.subProjects.length > 0
|
||||
})
|
||||
|
||||
// The open project keeps its list entry current: one created here joins the list,
|
||||
// and a submit or approval shows up when going back to it.
|
||||
$effect(() => {
|
||||
const s = deployHub.session
|
||||
if (!s?.effectiveSlug) return
|
||||
const entry = { folder: s.folder, status: statusOf(s), name: s.hubName || s.hubSlug }
|
||||
untrack(() => {
|
||||
if (!projects) return
|
||||
const cur = projects.find((p) => p.folder === entry.folder)
|
||||
if (cur?.status === entry.status && cur.name === entry.name) return
|
||||
projects = [...projects.filter((p) => p.folder !== entry.folder), entry].sort((a, b) =>
|
||||
a.folder.localeCompare(b.folder)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// No project takes in items another one holds. A new one is kept out of every
|
||||
// project; an existing one only out of projects nested inside it, never out of its
|
||||
// own items because a project above it was published later.
|
||||
$effect(() => {
|
||||
const s = deployHub.session
|
||||
if (!s || !projects) return
|
||||
const folders = projects.map((p) => p.folder)
|
||||
s.blockedFolders = s.effectiveSlug
|
||||
? folders.filter((f) => f.startsWith(`${s.folder}/`))
|
||||
: folders
|
||||
})
|
||||
|
||||
// Once the folder has projects, a new one is a sub-path: the whole folder would
|
||||
// take in their items.
|
||||
function needsSubFolder(s: DeployToHubSession): boolean {
|
||||
return !s.effectiveSlug && s.folder === folderProp && !!projects?.length
|
||||
}
|
||||
|
||||
function startNewProject() {
|
||||
showList = false
|
||||
scope = folderProp
|
||||
}
|
||||
function openProject(folder: string) {
|
||||
showList = false
|
||||
scope = folder
|
||||
}
|
||||
function statusBadge(status: string): { color: 'green' | 'yellow' | 'gray'; label: string } {
|
||||
return status === 'live'
|
||||
? { color: 'green', label: 'Live on Hub' }
|
||||
: status === 'under_review'
|
||||
? { color: 'yellow', label: 'In review on Hub' }
|
||||
: { color: 'gray', label: 'Draft on Hub' }
|
||||
}
|
||||
|
||||
let recordDrawer = $state<Drawer | undefined>()
|
||||
let appRecordDrawer = $state<Drawer | undefined>()
|
||||
let appRecordTarget = $state<DeployItem | undefined>(undefined)
|
||||
@@ -153,7 +251,59 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if deployHub.session}
|
||||
{#snippet subProjectNote(prefix: string)}
|
||||
{@const sp = projects?.find((p) => `f/${p.folder}` === prefix)}
|
||||
{#if sp}
|
||||
{@const b = statusBadge(sp.status)}
|
||||
<Badge small color={b.color} wrapperClass="ml-1">
|
||||
<Cloud size={10} class="mr-1" />
|
||||
{b.label}
|
||||
</Badge>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#if !projects}
|
||||
<div class="flex items-center gap-2 py-8 text-xs text-secondary">
|
||||
<Loader2 size={14} class="animate-spin" /> Looking for Hub projects…
|
||||
</div>
|
||||
{:else if showList}
|
||||
<div class="flex flex-col gap-3 max-w-2xl">
|
||||
<span class="text-sm font-semibold text-emphasis">Hub projects from this folder</span>
|
||||
<span class="text-xs text-primary">Pick a project to update, record or submit.</span>
|
||||
<div class="flex flex-col border rounded-md bg-surface-tertiary divide-y">
|
||||
{#each projects as p (p.folder)}
|
||||
{@const b = statusBadge(p.status)}
|
||||
<button
|
||||
class="flex items-center gap-3 px-4 py-3 text-left hover:bg-surface-hover"
|
||||
onclick={() => openProject(p.folder)}
|
||||
>
|
||||
<FolderTree size={16} class="text-secondary shrink-0" />
|
||||
<span class="flex flex-col gap-0.5 min-w-0">
|
||||
<span class="text-xs font-semibold text-emphasis truncate">{p.name}</span>
|
||||
<span class="text-2xs font-mono text-secondary truncate">f/{p.folder}/</span>
|
||||
</span>
|
||||
<Badge small color={b.color} wrapperClass="ml-auto">
|
||||
<Cloud size={10} class="mr-1" />
|
||||
{b.label}
|
||||
</Badge>
|
||||
<ChevronRight size={16} class="text-secondary shrink-0" />
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{#if !wholeIsProject}
|
||||
<div class="flex">
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: Plus }}
|
||||
onclick={startNewProject}
|
||||
>
|
||||
New project from another sub-folder
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if deployHub.session}
|
||||
<ConfirmationModal
|
||||
open={discardTarget !== undefined}
|
||||
title="Discard update"
|
||||
@@ -175,6 +325,10 @@
|
||||
<div>
|
||||
<WorkspaceDeployLayout
|
||||
items={s.items}
|
||||
nested
|
||||
folderDetail={subProjectNote}
|
||||
selectablePredicate={(i) => !s.isBlocked(i.path)}
|
||||
selectBlockedReason={() => 'Already part of another Hub project'}
|
||||
selectedItems={s.selectedItemKeys}
|
||||
deploymentStatus={s.deploymentStatus}
|
||||
hideSelection={s.phase !== 'predeploy'}
|
||||
@@ -224,6 +378,16 @@
|
||||
</li>
|
||||
</ol>
|
||||
<div class="flex flex-wrap items-center gap-2 pt-4">
|
||||
{#if hasSubProjects}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: ArrowLeft }}
|
||||
title="Back to Hub projects"
|
||||
onclick={() => (showList = true)}
|
||||
/>
|
||||
{/if}
|
||||
{#if s.phase === 'predeploy'}
|
||||
<span class="text-sm font-semibold text-primary">
|
||||
Step 1: Bundle your project
|
||||
@@ -256,6 +420,7 @@
|
||||
variant="accent"
|
||||
loading={s.deploying || s.triggersLoading}
|
||||
disabled={s.selectedItems.length === 0 ||
|
||||
needsSubFolder(s) ||
|
||||
s.triggersLoading ||
|
||||
s.triggerDiscoveryFailed}
|
||||
startIcon={{ icon: Cloud }}
|
||||
@@ -325,6 +490,14 @@
|
||||
<span class="font-mono">{s.selectedFolder}/</span>.
|
||||
{s.selectedItems.length} of {s.filteredWorkspaceItems.length} items selected.
|
||||
</span>
|
||||
{#if needsSubFolder(s) && s.selectedItems.length}
|
||||
<span
|
||||
class="flex items-center gap-1.5 text-xs text-yellow-700 dark:text-yellow-400"
|
||||
>
|
||||
<TriangleAlert size={12} class="shrink-0" />
|
||||
Select items inside one sub-folder: the whole folder already holds other Hub projects.
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2 text-xs">
|
||||
<span class="font-semibold text-primary shrink-0">
|
||||
@@ -766,7 +939,8 @@
|
||||
<div class="flex flex-col gap-3">
|
||||
<p class="text-xs text-secondary">
|
||||
Run this {s.recordTarget?.kind} once with the inputs below. The full execution — args, logs,
|
||||
intermediate step outputs and final result — is saved as a <b>replayable recording</b>
|
||||
intermediate step outputs and final result — is saved as a
|
||||
<b>replayable recording</b>
|
||||
shown on the Hub page. Visitors can step through it to see how the {s.recordTarget
|
||||
?.kind} works without running anything themselves.
|
||||
</p>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
canRecordSession,
|
||||
commonFolderPath,
|
||||
folderSubPaths,
|
||||
inputResourceTypes,
|
||||
mergeAppTableOrigin,
|
||||
type DeployItem
|
||||
@@ -62,3 +64,26 @@ describe('inputResourceTypes', () => {
|
||||
expect(inputResourceTypes(schema, new Set())).toEqual(all)
|
||||
})
|
||||
})
|
||||
|
||||
describe('folderSubPaths', () => {
|
||||
it('lists every sub-path that holds an item, at every depth', () => {
|
||||
expect(
|
||||
folderSubPaths(
|
||||
['f/hub/top', 'f/hub/billing/utils/x', 'f/hub/notifications/send', 'f/other/a/b'],
|
||||
'hub'
|
||||
)
|
||||
).toEqual(['hub/billing', 'hub/billing/utils', 'hub/notifications'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('commonFolderPath', () => {
|
||||
it('is the deepest sub-path holding every selected item', () => {
|
||||
expect(commonFolderPath(['f/hub/billing/charge', 'f/hub/billing/utils/format'])).toBe(
|
||||
'hub/billing'
|
||||
)
|
||||
expect(commonFolderPath(['f/hub/billing/utils/format'])).toBe('hub/billing/utils')
|
||||
expect(commonFolderPath(['f/hub/billing/charge', 'f/hub/notifications/send'])).toBe('hub')
|
||||
expect(commonFolderPath(['f/hub/billing/charge', 'f/hub/readme_bot'])).toBe('hub')
|
||||
expect(commonFolderPath([])).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -82,3 +82,37 @@ export function mergeAppTableOrigin(
|
||||
})
|
||||
return changed ? merged : draftItems
|
||||
}
|
||||
|
||||
/**
|
||||
* Every sub-path of `folder` that holds at least one item, at every depth, sorted:
|
||||
* `hub` with `f/hub/billing/utils/x` gives `['hub/billing', 'hub/billing/utils']`.
|
||||
*/
|
||||
export function folderSubPaths(paths: string[], folder: string): string[] {
|
||||
const prefix = `f/${folder}/`
|
||||
const out = new Set<string>()
|
||||
for (const p of paths) {
|
||||
if (!p.startsWith(prefix)) continue
|
||||
const dirs = p.slice(prefix.length).split('/').slice(0, -1)
|
||||
for (let i = 1; i <= dirs.length; i++) out.add(`${folder}/${dirs.slice(0, i).join('/')}`)
|
||||
}
|
||||
return [...out].sort()
|
||||
}
|
||||
|
||||
/**
|
||||
* The deepest folder sub-path holding every selected `f/...` path: `f/hub/billing/a`
|
||||
* and `f/hub/billing/utils/b` give `hub/billing`. `undefined` for an empty selection.
|
||||
*/
|
||||
export function commonFolderPath(paths: string[]): string | undefined {
|
||||
let common: string[] | undefined
|
||||
for (const p of paths) {
|
||||
const dirs = p.split('/').slice(1, -1)
|
||||
if (!common) {
|
||||
common = dirs
|
||||
continue
|
||||
}
|
||||
let n = 0
|
||||
while (n < common.length && n < dirs.length && common[n] === dirs[n]) n++
|
||||
common = common.slice(0, n)
|
||||
}
|
||||
return common?.length ? common.join('/') : undefined
|
||||
}
|
||||
|
||||
@@ -37,6 +37,8 @@ import type { Kind } from '$lib/utils_deployable'
|
||||
import {
|
||||
canRecord,
|
||||
canRecordSession,
|
||||
commonFolderPath,
|
||||
folderSubPaths,
|
||||
inputResourceTypes,
|
||||
mergeAppTableOrigin,
|
||||
HIDDEN_RESOURCE_TYPES,
|
||||
@@ -141,6 +143,9 @@ export class DeployToHubSession {
|
||||
readonly folder: string
|
||||
/** `f/`-prefixed folder path the project is scoped to. */
|
||||
readonly selectedFolder: string
|
||||
/** The base folder whose items are offered for selection; `folder` is it or one of
|
||||
* its sub-paths. */
|
||||
readonly listFolder: string
|
||||
|
||||
#disposed = false
|
||||
#deps: SessionDeps
|
||||
@@ -265,11 +270,22 @@ export class DeployToHubSession {
|
||||
#previewItemCache = new Map<string, Promise<FetchedItem | undefined>>()
|
||||
#previewTypeCache = new Map<string, Promise<string | undefined>>()
|
||||
|
||||
constructor(workspace: string, folder: string, deps: SessionDeps) {
|
||||
constructor(
|
||||
workspace: string,
|
||||
folder: string,
|
||||
deps: SessionDeps,
|
||||
listFolder: string = folder,
|
||||
seed?: { items: DeployItem[]; deselected: Set<string> }
|
||||
) {
|
||||
this.workspace = workspace
|
||||
this.folder = folder
|
||||
this.selectedFolder = `f/${folder}`
|
||||
this.listFolder = listFolder
|
||||
this.#deps = deps
|
||||
if (seed) {
|
||||
this.workspaceItems = seed.items
|
||||
this.manualDeselected = seed.deselected
|
||||
}
|
||||
}
|
||||
|
||||
dispose() {
|
||||
@@ -301,8 +317,22 @@ export class DeployToHubSession {
|
||||
}
|
||||
}
|
||||
|
||||
/** Set once the Hub has said whether this scope already has a project. */
|
||||
hubChecked = $state(false)
|
||||
/** Sub-paths of the base folder that are Hub projects of their own. */
|
||||
subProjects = $state<{ folder: string; status: string; name: string }[]>([])
|
||||
/** Set once `subProjects` has been looked up. */
|
||||
subProjectsChecked = $state(false)
|
||||
#subProjectsLoaded = false
|
||||
/** Folders already published as other projects: their items cannot join this one. */
|
||||
blockedFolders = $state<string[]>([])
|
||||
isBlocked = (path: string) => this.blockedFolders.some((f) => path.startsWith(`f/${f}/`))
|
||||
// A scope with a Hub project offers only its own items, so an update cannot drift
|
||||
// into another scope's project; until then the whole base folder is offered.
|
||||
filteredWorkspaceItems = $derived(
|
||||
this.workspaceItems.filter((i) => i.path.startsWith(this.selectedFolder + '/'))
|
||||
this.workspaceItems.filter((i) =>
|
||||
i.path.startsWith(`f/${this.effectiveSlug ? this.folder : this.listFolder}/`)
|
||||
)
|
||||
)
|
||||
// Derived (not merged at load time) so it settles regardless of which of the
|
||||
// racing loads (#loadWorkspace / rehydrateFromHub) finishes last.
|
||||
@@ -312,13 +342,24 @@ export class DeployToHubSession {
|
||||
)
|
||||
selectedItems = $derived(
|
||||
this.phase === 'predeploy'
|
||||
? this.filteredWorkspaceItems.filter((i) => !this.manualDeselected.has(i.key))
|
||||
? this.filteredWorkspaceItems.filter(
|
||||
(i) => !this.manualDeselected.has(i.key) && !this.isBlocked(i.path)
|
||||
)
|
||||
: []
|
||||
)
|
||||
selectedItemKeys = $derived(this.selectedItems.map((i) => i.key))
|
||||
allSelected = $derived(
|
||||
this.phase === 'predeploy' &&
|
||||
this.selectedItemKeys.length === this.filteredWorkspaceItems.length
|
||||
this.selectedItemKeys.length ===
|
||||
this.filteredWorkspaceItems.filter((i) => !this.isBlocked(i.path)).length
|
||||
)
|
||||
/** The project the selection describes: the whole base folder while everything is
|
||||
* selected and no other project holds part of it, else the deepest sub-path holding
|
||||
* all of it. */
|
||||
selectionScope = $derived.by(() =>
|
||||
this.allSelected && !this.blockedFolders.length
|
||||
? this.listFolder
|
||||
: (commonFolderPath(this.selectedItems.map((i) => i.path)) ?? this.folder)
|
||||
)
|
||||
// A raw app's recorded session counts towards the project's recordings just as
|
||||
// a script's captured run does — both are what a visitor replays.
|
||||
@@ -596,6 +637,36 @@ export class DeployToHubSession {
|
||||
}
|
||||
}
|
||||
|
||||
// ponytail: one lookup per sub-path; a by-prefix Hub query if folders grow deep.
|
||||
async loadSubProjects() {
|
||||
if (this.#subProjectsLoaded) return
|
||||
this.#subProjectsLoaded = true
|
||||
const subs = folderSubPaths(
|
||||
this.workspaceItems.map((i) => i.path),
|
||||
this.listFolder
|
||||
)
|
||||
const found = await Promise.all(
|
||||
subs.map(async (folder) => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/w/${this.workspace}/hub/project?folder=${encodeURIComponent(folder)}`,
|
||||
{ credentials: 'include', headers: { accept: 'application/json' } }
|
||||
)
|
||||
if (!res.ok) return undefined
|
||||
const p = await res.json()
|
||||
return p?.slug
|
||||
? { folder, status: String(p.status ?? 'draft'), name: String(p.name || p.slug) }
|
||||
: undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
})
|
||||
)
|
||||
if (this.#disposed) return
|
||||
this.subProjects = found.filter((p) => p !== undefined)
|
||||
this.subProjectsChecked = true
|
||||
}
|
||||
|
||||
async rehydrateFromHub() {
|
||||
try {
|
||||
const res = await fetch(`/api/w/${this.workspace}/hub/project${this.#folderQs()}`, {
|
||||
@@ -638,7 +709,10 @@ export class DeployToHubSession {
|
||||
} satisfies DeployItem
|
||||
})
|
||||
this.hubItemIds = ids
|
||||
} catch {}
|
||||
} catch {
|
||||
} finally {
|
||||
if (!this.#disposed) this.hubChecked = true
|
||||
}
|
||||
}
|
||||
|
||||
/** Kick off schedule-preview fetches for any relevant schedule trigger missing one. */
|
||||
@@ -689,7 +763,14 @@ export class DeployToHubSession {
|
||||
const triggerVars = this.#triggerVarPaths(this.relevantTriggers)
|
||||
let cancelled = false
|
||||
const timer = setTimeout(() => {
|
||||
buildProjectBundle(seed, slug, this.#cachedBundleDeps(), triggerResources, triggerVars)
|
||||
buildProjectBundle(
|
||||
seed,
|
||||
slug,
|
||||
this.#cachedBundleDeps(),
|
||||
triggerResources,
|
||||
triggerVars,
|
||||
this.folder
|
||||
)
|
||||
.then((b) => {
|
||||
if (cancelled) return
|
||||
this.bundlePreview = b
|
||||
@@ -887,7 +968,7 @@ export class DeployToHubSession {
|
||||
|
||||
/** Prefill bundle metadata and start migration detection (bundle drawer opening). */
|
||||
prepareBundle() {
|
||||
this.hubName = this.hubName || this.folder
|
||||
this.hubName = this.hubName || (this.folder.split('/').pop() ?? this.folder)
|
||||
void this.regenerateMigrations()
|
||||
}
|
||||
|
||||
@@ -1062,7 +1143,8 @@ export class DeployToHubSession {
|
||||
): Promise<void> {
|
||||
const pathMap = buildPathMap(
|
||||
relevant.map((t) => t.path),
|
||||
slug
|
||||
slug,
|
||||
this.folder
|
||||
)
|
||||
const triggers: Array<Record<string, unknown>> = []
|
||||
const skipped: string[] = []
|
||||
@@ -1157,7 +1239,8 @@ export class DeployToHubSession {
|
||||
slug,
|
||||
this.#buildBundleDeps(),
|
||||
triggerResources,
|
||||
triggerVars
|
||||
triggerVars,
|
||||
this.folder
|
||||
)
|
||||
// Full path map (incl. unresolved) so a trigger's resource path is always
|
||||
// relocated — never leaks the publisher's original private path to the Hub.
|
||||
@@ -1858,6 +1941,8 @@ export class DeployToHubSession {
|
||||
export function useDeployToHubSession(args: {
|
||||
workspace: () => string | undefined
|
||||
folder: () => string
|
||||
/** The base folder offered for selection; `folder` is it or one of its sub-paths. */
|
||||
listFolder: () => string
|
||||
hasEeLicense: () => boolean
|
||||
}) {
|
||||
let session = $state<DeployToHubSession | undefined>()
|
||||
@@ -1865,13 +1950,28 @@ export function useDeployToHubSession(args: {
|
||||
$effect(() => {
|
||||
const workspace = args.workspace()
|
||||
const folder = args.folder()
|
||||
const listFolder = args.listFolder()
|
||||
if (!workspace) return
|
||||
untrack(() => {
|
||||
if (session && session.workspace === workspace && session.folder === folder) return
|
||||
session?.dispose()
|
||||
const next = new DeployToHubSession(workspace, folder, {
|
||||
hasEeLicense: args.hasEeLicense
|
||||
})
|
||||
const prev = session
|
||||
// A scope change made by editing the selection keeps that selection.
|
||||
const seed =
|
||||
prev &&
|
||||
prev.workspace === workspace &&
|
||||
prev.listFolder === listFolder &&
|
||||
prev.phase === 'predeploy' &&
|
||||
!prev.effectiveSlug
|
||||
? { items: prev.workspaceItems, deselected: prev.manualDeselected }
|
||||
: undefined
|
||||
prev?.dispose()
|
||||
const next = new DeployToHubSession(
|
||||
workspace,
|
||||
folder,
|
||||
{ hasEeLicense: args.hasEeLicense },
|
||||
listFolder,
|
||||
seed
|
||||
)
|
||||
session = next
|
||||
next.load()
|
||||
})
|
||||
@@ -1889,16 +1989,27 @@ export function useDeployToHubSession(args: {
|
||||
})
|
||||
})
|
||||
|
||||
// Leaving/entering predeploy invalidates manual selection tweaks.
|
||||
// Leaving/entering predeploy invalidates manual selection tweaks; a new session
|
||||
// keeps the selection it was seeded with.
|
||||
let phaseSeen: { s: DeployToHubSession; phase: Phase } | undefined
|
||||
$effect(() => {
|
||||
const s = session
|
||||
if (!s) return
|
||||
s.phase
|
||||
const phase = s.phase
|
||||
untrack(() => {
|
||||
s.manualDeselected = new Set()
|
||||
if (phaseSeen?.s === s && phaseSeen.phase !== phase) s.manualDeselected = new Set()
|
||||
phaseSeen = { s, phase }
|
||||
})
|
||||
})
|
||||
|
||||
// The base folder looks up which of its sub-paths are published on their own, once
|
||||
// its items have loaded.
|
||||
$effect(() => {
|
||||
const s = session
|
||||
if (s && s.hubChecked && !s.loading && s.folder === s.listFolder)
|
||||
untrack(() => void s.loadSubProjects())
|
||||
})
|
||||
|
||||
// Schedule previews for relevant schedule triggers (deduped in the session).
|
||||
$effect(() => {
|
||||
session?.ensureSchedulePreviews()
|
||||
|
||||
@@ -129,6 +129,20 @@ describe('buildPathMap', () => {
|
||||
expect(m.get('f/proj/a/x')).toBe('f/proj/a/x')
|
||||
expect(m.get('f/proj/b/x')).toBe('f/proj/b/x')
|
||||
})
|
||||
it('keeps the sub-path of every item in a nested source folder', () => {
|
||||
const m = buildPathMap(
|
||||
['f/hub/billing/charge', 'f/hub/billing/utils/format', 'f/hub/billing/stripe/format'],
|
||||
'billing',
|
||||
'hub/billing'
|
||||
)
|
||||
expect(m.get('f/hub/billing/charge')).toBe('f/billing/charge')
|
||||
expect(m.get('f/hub/billing/utils/format')).toBe('f/billing/utils/format')
|
||||
expect(m.get('f/hub/billing/stripe/format')).toBe('f/billing/stripe/format')
|
||||
// The same for a top-level folder whose name is not its slug.
|
||||
expect(buildPathMap(['f/my_tools/a/x'], 'my-tools', 'my_tools').get('f/my_tools/a/x')).toBe(
|
||||
'f/my-tools/a/x'
|
||||
)
|
||||
})
|
||||
it('relocates an external onto a suffix when its leaf collides with an internal path', () => {
|
||||
const m = buildPathMap(['f/proj/db', 'u/admin/db'], 'proj')
|
||||
expect(m.get('f/proj/db')).toBe('f/proj/db')
|
||||
|
||||
@@ -174,18 +174,25 @@ export function extractAppRefs(value: any): Ref[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the relocation map. Internal paths (`f/<slug>/...`) map to themselves
|
||||
* and are reserved first; external paths relocate to `f/<slug>/<name>` (`_2`/`_3`…
|
||||
* on collision). Input is sorted so suffix assignment is deterministic.
|
||||
* Build the relocation map. Paths under the source folder (`f/<sourceFolder>/...`,
|
||||
* possibly nested like `hub/billing`) keep their sub-path under `f/<slug>/` and are
|
||||
* reserved first; other paths relocate to `f/<slug>/<name>` (`_2`/`_3`… on
|
||||
* collision). Input is sorted so suffix assignment is deterministic.
|
||||
*/
|
||||
export function buildPathMap(paths: Iterable<string>, slug: string): Map<string, string> {
|
||||
export function buildPathMap(
|
||||
paths: Iterable<string>,
|
||||
slug: string,
|
||||
sourceFolder: string = slug
|
||||
): Map<string, string> {
|
||||
const map = new Map<string, string>()
|
||||
const used = new Set<string>()
|
||||
const sorted = [...new Set(paths)].sort()
|
||||
const sourcePrefix = `f/${sourceFolder}/`
|
||||
for (const p of sorted) {
|
||||
if (classifyPath(p, slug) === 'internal') {
|
||||
map.set(p, p)
|
||||
used.add(p)
|
||||
if (p.startsWith(sourcePrefix)) {
|
||||
const kept = `f/${slug}/${p.slice(sourcePrefix.length)}`
|
||||
map.set(p, kept)
|
||||
used.add(kept)
|
||||
}
|
||||
}
|
||||
for (const old of sorted) {
|
||||
@@ -640,7 +647,8 @@ export async function buildProjectBundle(
|
||||
slug: string,
|
||||
deps: BundleDeps,
|
||||
extraResourcePaths: string[] = [],
|
||||
extraVarPaths: string[] = []
|
||||
extraVarPaths: string[] = [],
|
||||
sourceFolder: string = slug
|
||||
): Promise<ProjectBundle> {
|
||||
const fetched = new Map<string, FetchedItem>()
|
||||
const queued = new Set<string>()
|
||||
@@ -701,7 +709,7 @@ export async function buildProjectBundle(
|
||||
|
||||
const fetchedItems = [...fetched.values()]
|
||||
const itemPaths = fetchedItems.map((it) => it.path)
|
||||
const map = buildPathMap([...itemPaths, ...resourcePaths, ...varPaths], slug)
|
||||
const map = buildPathMap([...itemPaths, ...resourcePaths, ...varPaths], slug, sourceFolder)
|
||||
|
||||
const items: BundledItem[] = fetchedItems.map((it) => {
|
||||
const rewritten: BundledItem = { ...it, newPath: map.get(it.path) ?? it.path }
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user