mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 16:06:22 +00:00
Merge remote-tracking branch 'origin/access-view-grant' into run-as-service-accounts
This commit is contained in:
@@ -69,7 +69,7 @@ Open-source platform for internal tools, workflows, API integrations, background
|
||||
- **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does.
|
||||
- **CLI commands**: when adding/modifying/removing a command, subcommand, option, or description in `cli/src/commands/`, run `python system_prompts/generate.py` to refresh `system_prompts/auto-generated/` and `cli/src/guidance/skills.gen.ts`. The CLI docs the agents use to operate `wmill` are derived from the source — stale generated files give agents the wrong flags.
|
||||
- **AI guidance** (chat prompts and CLI skills): what the AI knows about Windmill itself — how flows, scripts, apps, pipelines and resources work — is written once, in `system_prompts/base/` and `system_prompts/languages/`, and `system_prompts/generate.py` builds both the chat's `$system_prompts` exports and the CLI's skills from it. Add or change such guidance there, never inline in one consumer: a sentence only one side should see goes in a `<!-- cli-only -->` / `<!-- chat-only -->` block, and a new file reaches both through the `TOPICS` table. The chat prompt builders under `frontend/src/lib/components/copilot/chat/` add only tool plumbing and runtime values, and shared markdown names no chat tool, since it reaches every chat mode. Rerun `generate.py` after editing; `system_prompts/README.md` has the details.
|
||||
- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v<N>` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools.
|
||||
- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`); the two copies of that rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v<N>` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools.
|
||||
- **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise).
|
||||
- **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server.
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
-- Nothing to do here: the stripped `/` named nothing.
|
||||
@@ -0,0 +1,12 @@
|
||||
-- A schedule's target is compared with the path of the jobs it queues, and with a renamed
|
||||
-- runnable's old path, neither of which starts with `/`. A target with more than one leading `/`
|
||||
-- names nothing and is left as is: firing the schedule refuses it.
|
||||
UPDATE schedule SET script_path = substr(script_path, 2)
|
||||
WHERE script_path LIKE '/%' AND script_path NOT LIKE '//%';
|
||||
-- A restore puts the trashed row back as saved, so the copies awaiting one get the same fix.
|
||||
UPDATE trashbin
|
||||
SET item_data = jsonb_set(item_data, '{row,script_path}',
|
||||
to_jsonb(substr(item_data #>> '{row,script_path}', 2)))
|
||||
WHERE item_kind = 'schedule'
|
||||
AND item_data #>> '{row,script_path}' LIKE '/%'
|
||||
AND item_data #>> '{row,script_path}' NOT LIKE '//%';
|
||||
@@ -0,0 +1,43 @@
|
||||
use serde_json::json;
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
use windmill_test_utils::*;
|
||||
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn create_stores_the_parsed_target(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let base = format!(
|
||||
"http://localhost:{}/api/w/test-workspace/schedules",
|
||||
server.addr.port()
|
||||
);
|
||||
let client = reqwest::Client::new();
|
||||
let create = |path: &str, script_path: &str| {
|
||||
client
|
||||
.post(format!("{base}/create"))
|
||||
.bearer_auth("SECRET_TOKEN")
|
||||
.json(&json!({
|
||||
"path": path,
|
||||
"schedule": "0 0 0 * * *",
|
||||
"timezone": "UTC",
|
||||
"script_path": script_path,
|
||||
"is_flow": false,
|
||||
"args": {},
|
||||
"enabled": false,
|
||||
}))
|
||||
.send()
|
||||
};
|
||||
|
||||
let resp = create("u/test-user/one_slash", "/u/test-user/x").await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
let stored: String = sqlx::query_scalar(
|
||||
"SELECT script_path FROM schedule WHERE workspace_id = 'test-workspace' AND path = 'u/test-user/one_slash'",
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert_eq!(stored, "u/test-user/x");
|
||||
|
||||
let resp = create("u/test-user/two_slashes", "//u/test-user/x").await?;
|
||||
assert_eq!(resp.status(), 400, "{}", resp.text().await?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -21,6 +21,7 @@ use windmill_api_auth::{
|
||||
};
|
||||
use windmill_audit::audit_oss::audit_log;
|
||||
use windmill_audit::ActionKind;
|
||||
use windmill_common::runnable_ref::RunnableRef;
|
||||
use windmill_common::DB;
|
||||
use windmill_common::{
|
||||
can_preserve_on_behalf_of,
|
||||
@@ -268,10 +269,17 @@ async fn create_schedule(
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Json(ns): Json<NewSchedule>,
|
||||
Json(mut ns): Json<NewSchedule>,
|
||||
) -> Result<String> {
|
||||
check_scopes(&authed, || format!("schedules:write:{}", ns.path))?;
|
||||
reject_reserved_schedule_path(&ns.path)?;
|
||||
// Stored as parsed: the next-run check, the monitor's re-arm, the run history and renames
|
||||
// all match the stored target exactly against job paths, which never start with `/`.
|
||||
if !ns.script_path.is_empty() {
|
||||
ns.script_path = RunnableRef::from_path(&ns.script_path, ns.is_flow)?
|
||||
.path()
|
||||
.to_string();
|
||||
}
|
||||
|
||||
let authed = maybe_refresh_folders(&ns.path, &w_id, authed, &db).await;
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1019,7 +1019,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "Workspace path of the script to test.",
|
||||
"description": "Workspace path of the script to test, or a hub/<version>/<app>/<name> path from search_hub_scripts to try a hub script.",
|
||||
"type": "string"
|
||||
},
|
||||
"args": {
|
||||
|
||||
@@ -1,26 +1,58 @@
|
||||
//! The instructions a client receives on connecting: the session's system prompt as
|
||||
//! rendered for an external client (`gen/prompt.json`), filled in for the caller. What
|
||||
//! differs per workspace is cut out of it, so a connection spanning several workspaces
|
||||
//! gets the rest up front and each workspace's part from `get_workspace_context`.
|
||||
//! rendered for an external client, filled in for the caller. `gen/prompt.json` holds one
|
||||
//! template (`EXTERNAL_PROMPT` in the chat's `global/core.ts`) and, per access profile, the
|
||||
//! flags and variables the generator computed for it: what the caller may do is decided there,
|
||||
//! and only rendered here. The profile is the token's scope and, for a full token, the caller's
|
||||
//! role in the workspace. The folder guidance differs per workspace, so a connection spanning
|
||||
//! several workspaces gets the rest up front and each workspace's part from
|
||||
//! `get_workspace_context`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use serde::Deserialize;
|
||||
use windmill_common::{
|
||||
roles::{caller_capabilities, AuthorLevel, RoleCapabilities},
|
||||
workspaces::{check_deploy_rules, RuleCheckResult},
|
||||
DB,
|
||||
};
|
||||
use windmill_mcp::server::McpAuth;
|
||||
|
||||
use super::{guidance::list_skills, Ctx};
|
||||
use super::{guidance::list_skills, Ctx, SessionAccess};
|
||||
|
||||
/// The prompt with a `{{folder_guidance}}` slot, the guidance once per folder situation,
|
||||
/// and the sections appended when the workspace has something to put there.
|
||||
/// As generated by `mcpSessionGen.test.ts`.
|
||||
#[derive(Deserialize)]
|
||||
struct PromptParts {
|
||||
base: String,
|
||||
folder_guidance: FolderGuidance,
|
||||
template: String,
|
||||
profiles: HashMap<String, Profile>,
|
||||
folder_guidance: FolderGuidanceSets,
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
rendered_sha256: HashMap<String, String>,
|
||||
skills_header: String,
|
||||
skill_line: String,
|
||||
workspace_instructions: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Profile {
|
||||
/// The flags set, space-separated.
|
||||
flags: String,
|
||||
vars: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
fn flags(&self) -> HashSet<&str> {
|
||||
self.flags.split_whitespace().collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct FolderGuidanceSets {
|
||||
create_folder: FolderGuidance,
|
||||
no_create_folder: FolderGuidance,
|
||||
}
|
||||
|
||||
/// The `{{folder_guidance}}` text per folder situation, with its leading newline.
|
||||
#[derive(Deserialize)]
|
||||
struct FolderGuidance {
|
||||
admin: String,
|
||||
@@ -35,6 +67,136 @@ static PARTS: LazyLock<PromptParts> = LazyLock::new(|| {
|
||||
serde_json::from_str(include_str!("gen/prompt.json")).expect("gen/prompt.json is valid")
|
||||
});
|
||||
|
||||
/// `promptTemplate.ts`'s grammar, which this must render identically (the generator's
|
||||
/// `rendered_sha256` pins it): `{{#flag}}…{{/flag}}` keeps its body when the flag is set,
|
||||
/// `{{^flag}}…{{/flag}}` when it is not, `{{name}}` takes a variable, and a variable not given
|
||||
/// stays as written for a later pass to fill.
|
||||
fn render_template(
|
||||
template: &str,
|
||||
flags: &HashSet<&str>,
|
||||
vars: &HashMap<String, String>,
|
||||
) -> String {
|
||||
let mut out = String::with_capacity(template.len());
|
||||
// Each open section, and whether it keeps its body.
|
||||
let mut open: Vec<(&str, bool)> = Vec::new();
|
||||
let mut rest = template;
|
||||
while let Some(start) = rest.find("{{") {
|
||||
let keeping = open.iter().all(|(_, keep)| *keep);
|
||||
let Some(tag) = rest[start + 2..]
|
||||
.find("}}")
|
||||
.map(|end| &rest[start + 2..start + 2 + end])
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let (kind, name) = match tag.as_bytes().first() {
|
||||
Some(b'#' | b'^' | b'/') => (Some(tag.as_bytes()[0]), &tag[1..]),
|
||||
_ => (None, tag),
|
||||
};
|
||||
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_lowercase() || b == b'_') {
|
||||
// Not a tag: keep the first brace as text, as the regex there scans on.
|
||||
if keeping {
|
||||
out.push_str(&rest[..start + 1]);
|
||||
}
|
||||
rest = &rest[start + 1..];
|
||||
continue;
|
||||
}
|
||||
if keeping {
|
||||
out.push_str(&rest[..start]);
|
||||
}
|
||||
let whole = &rest[start..start + 4 + tag.len()];
|
||||
rest = &rest[start + whole.len()..];
|
||||
match kind {
|
||||
Some(b'#') => open.push((name, flags.contains(name))),
|
||||
Some(b'^') => open.push((name, !flags.contains(name))),
|
||||
Some(_) => {
|
||||
let closed = open.pop().map(|(n, _)| n);
|
||||
debug_assert_eq!(closed, Some(name), "unbalanced prompt template");
|
||||
}
|
||||
None if keeping => out.push_str(vars.get(name).map_or(whole, String::as_str)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if open.iter().all(|(_, keep)| *keep) {
|
||||
out.push_str(rest);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The key of a full-access caller holding every capability: what a connection spanning
|
||||
/// several workspaces is told before it learns its role in each.
|
||||
const UNRESTRICTED: &str = "full:11:1:full:full:11";
|
||||
|
||||
fn level(level: AuthorLevel) -> &'static str {
|
||||
match level {
|
||||
AuthorLevel::None => "none",
|
||||
AuthorLevel::Compose => "compose",
|
||||
AuthorLevel::Full => "full",
|
||||
}
|
||||
}
|
||||
|
||||
fn bit(b: bool) -> char {
|
||||
if b {
|
||||
'1'
|
||||
} else {
|
||||
'0'
|
||||
}
|
||||
}
|
||||
|
||||
/// Which generated prompt the caller reads, keyed as `mcpSessionGen.test.ts` generates them.
|
||||
/// A failed lookup reads as allowed: the prompt only describes, the API still refuses.
|
||||
pub(crate) async fn prompt_profile(
|
||||
db: &DB,
|
||||
auth: &crate::db::ApiAuthed,
|
||||
w_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> String {
|
||||
match access {
|
||||
SessionAccess::ReadOnly => return "read_only".to_string(),
|
||||
SessionAccess::ReadAndRun => return "read_run".to_string(),
|
||||
SessionAccess::Full => {}
|
||||
}
|
||||
let caps = caller_capabilities(db, w_id, auth)
|
||||
.await
|
||||
.unwrap_or(RoleCapabilities::FULL);
|
||||
let deploy = !matches!(
|
||||
check_deploy_rules(w_id, &auth.username, &auth.groups, auth.is_admin, db).await,
|
||||
Ok(RuleCheckResult::Blocked(_))
|
||||
);
|
||||
full_profile(auth.is_admin, deploy, &caps)
|
||||
}
|
||||
|
||||
fn full_profile(is_admin: bool, deploy: bool, caps: &RoleCapabilities) -> String {
|
||||
format!(
|
||||
"full:{}{}:{}:{}:{}:{}{}",
|
||||
bit(is_admin),
|
||||
bit(deploy),
|
||||
bit(caps.code),
|
||||
level(caps.flows),
|
||||
level(caps.apps),
|
||||
bit(caps.manage_schedules),
|
||||
bit(caps.manage_triggers),
|
||||
)
|
||||
}
|
||||
|
||||
fn profile_for(profile: &str) -> &'static Profile {
|
||||
let parts = &*PARTS;
|
||||
// A role no profile covers (full flows without code, which writes refuse) reads as the
|
||||
// unrestricted one.
|
||||
parts
|
||||
.profiles
|
||||
.get(profile)
|
||||
.or_else(|| parts.profiles.get(UNRESTRICTED))
|
||||
.expect("the unrestricted profile is generated")
|
||||
}
|
||||
|
||||
/// The prompt for `profile`, with the caller's username and folder guidance filled in.
|
||||
fn render(profile: &Profile, username: &str, folder_guidance: &str) -> String {
|
||||
let mut vars = profile.vars.clone();
|
||||
vars.insert("username".to_string(), username.to_string());
|
||||
vars.insert("folder_guidance".to_string(), folder_guidance.to_string());
|
||||
render_template(&PARTS.template, &profile.flags(), &vars)
|
||||
}
|
||||
|
||||
/// Folders named in the prompt before the rest are counted rather than listed, as the
|
||||
/// session does, so a folder-heavy workspace cannot dominate the instructions.
|
||||
const MAX_LISTED_FOLDERS: usize = 40;
|
||||
@@ -53,7 +215,17 @@ fn folder_list(names: &[&str]) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn folder_guidance(auth: &crate::db::ApiAuthed) -> String {
|
||||
/// Flags of `EXTERNAL_PROMPT` this file reads itself, which `folder_guidance_follows_the_template`
|
||||
/// pins: the template shows the folder guidance only under the first, in path conventions that
|
||||
/// name `create_folder` under the second.
|
||||
const WRITES_FLAG: &str = "can_write_any_draft";
|
||||
const CREATE_FOLDER_FLAG: &str = "can_create_folder";
|
||||
|
||||
fn folder_guidance(auth: &crate::db::ApiAuthed, profile: &Profile) -> String {
|
||||
let flags = profile.flags();
|
||||
if !flags.contains(WRITES_FLAG) {
|
||||
return String::new();
|
||||
}
|
||||
let writable: Vec<&str> = auth
|
||||
.folders()
|
||||
.iter()
|
||||
@@ -67,7 +239,11 @@ fn folder_guidance(auth: &crate::db::ApiAuthed) -> String {
|
||||
.map(|(name, _, _)| name.as_str())
|
||||
.collect();
|
||||
|
||||
let guidance = &PARTS.folder_guidance;
|
||||
let guidance = if flags.contains(CREATE_FOLDER_FLAG) {
|
||||
&PARTS.folder_guidance.create_folder
|
||||
} else {
|
||||
&PARTS.folder_guidance.no_create_folder
|
||||
};
|
||||
let template = match (auth.is_admin(), writable.is_empty(), readonly.is_empty()) {
|
||||
(true, false, _) => &guidance.admin,
|
||||
(true, true, _) => &guidance.admin_no_folders,
|
||||
@@ -121,32 +297,142 @@ async fn appendix(ctx: &Ctx<'_>) -> String {
|
||||
}
|
||||
|
||||
/// The whole prompt, for a connection that reaches one workspace.
|
||||
pub(crate) async fn session_instructions(ctx: &Ctx<'_>) -> String {
|
||||
let mut prompt = PARTS
|
||||
.base
|
||||
.replace("{{folder_guidance}}", &folder_guidance(ctx.auth))
|
||||
.replace("{{username}}", ctx.auth.username());
|
||||
prompt.push_str(&appendix(ctx).await);
|
||||
prompt
|
||||
pub(crate) async fn session_instructions(ctx: &Ctx<'_>, profile: &str) -> String {
|
||||
let profile = profile_for(profile);
|
||||
let mut text = render(
|
||||
profile,
|
||||
ctx.auth.username(),
|
||||
&folder_guidance(ctx.auth, profile),
|
||||
);
|
||||
text.push_str(&appendix(ctx).await);
|
||||
text
|
||||
}
|
||||
|
||||
/// The prompt without anything specific to a workspace, for a connection that reaches
|
||||
/// several: usernames are per workspace, so paths read `u/<username>/...`.
|
||||
pub(crate) fn generic_session_instructions() -> String {
|
||||
PARTS
|
||||
.base
|
||||
.replace("{{folder_guidance}}", "")
|
||||
.replace("{{username}}", "<username>")
|
||||
/// several: usernames and roles are per workspace, so paths read `u/<username>/...` and a full
|
||||
/// token reads the unrestricted prompt until `workspace_context` narrows it.
|
||||
pub(crate) fn generic_session_instructions(access: SessionAccess) -> String {
|
||||
render(profile_for(generic_profile(access)), "<username>", "")
|
||||
}
|
||||
|
||||
/// What `generic_session_instructions` leaves out, for one workspace.
|
||||
pub(crate) async fn workspace_context(ctx: &Ctx<'_>) -> String {
|
||||
fn generic_profile(access: SessionAccess) -> &'static str {
|
||||
match access {
|
||||
SessionAccess::ReadOnly => "read_only",
|
||||
SessionAccess::ReadAndRun => "read_run",
|
||||
SessionAccess::Full => UNRESTRICTED,
|
||||
}
|
||||
}
|
||||
|
||||
/// What `generic_session_instructions(token_access)` leaves out, for one workspace. A role or
|
||||
/// workspace that narrows the prompt gets its own in full, since its rules replace the general
|
||||
/// ones; `ctx.access` may be narrower than the token's.
|
||||
pub(crate) async fn workspace_context(
|
||||
ctx: &Ctx<'_>,
|
||||
profile: &str,
|
||||
token_access: SessionAccess,
|
||||
) -> String {
|
||||
let username = ctx.auth.username();
|
||||
format!(
|
||||
let header = format!(
|
||||
"Workspace `{}`. Your username here is \"{username}\", so your personal paths are \
|
||||
`u/{username}/<name>`.\n{}{}",
|
||||
ctx.w_id,
|
||||
folder_guidance(ctx.auth).trim_end(),
|
||||
`u/{username}/<name>`.\n",
|
||||
ctx.w_id
|
||||
);
|
||||
let profile = profile_for(profile);
|
||||
let folders = folder_guidance(ctx.auth, profile);
|
||||
// Roles that differ in name can read the same prompt, so the text decides.
|
||||
let general =
|
||||
render(profile, "", "") == render(profile_for(generic_profile(token_access)), "", "");
|
||||
let body = if general {
|
||||
folders.trim_end().to_string()
|
||||
} else {
|
||||
format!(
|
||||
"Your access in this workspace is narrower than the general instructions assume. \
|
||||
Here, these rules replace them:\n\n{}",
|
||||
render(profile, username, &folders)
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"{header}{}{}",
|
||||
body.trim_start_matches('\n'),
|
||||
appendix(ctx).await
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[test]
|
||||
fn folder_guidance_follows_the_template() {
|
||||
for (key, profile) in &PARTS.profiles {
|
||||
let flags = profile.flags();
|
||||
let mut vars = profile.vars.clone();
|
||||
vars.insert("folder_guidance".to_string(), "@@folders@@".to_string());
|
||||
let text = render_template(&PARTS.template, &flags, &vars);
|
||||
assert_eq!(
|
||||
text.contains("@@folders@@"),
|
||||
flags.contains(WRITES_FLAG),
|
||||
"{key}"
|
||||
);
|
||||
assert_eq!(
|
||||
text.contains("create_folder"),
|
||||
flags.contains(CREATE_FOLDER_FLAG),
|
||||
"{key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// This renderer reads every profile as `promptTemplate.ts` rendered it when generating.
|
||||
#[test]
|
||||
fn renders_every_profile_as_the_generator_did() {
|
||||
for (key, profile) in &PARTS.profiles {
|
||||
let text = render_template(&PARTS.template, &profile.flags(), &profile.vars);
|
||||
assert_eq!(
|
||||
hex::encode(Sha256::digest(text.as_bytes())),
|
||||
PARTS.rendered_sha256[key],
|
||||
"{key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every role a caller can hold reads a prompt generated for it, rather than falling back
|
||||
/// to the unrestricted one: the keys here and in `mcpSessionGen.test.ts` must agree.
|
||||
#[test]
|
||||
fn every_valid_role_has_a_generated_prompt() {
|
||||
let levels = [AuthorLevel::None, AuthorLevel::Compose, AuthorLevel::Full];
|
||||
for deploy in [true, false] {
|
||||
assert!(PARTS.profiles.contains_key(&full_profile(
|
||||
true,
|
||||
deploy,
|
||||
&RoleCapabilities::FULL
|
||||
)));
|
||||
for code in [true, false] {
|
||||
for flows in levels {
|
||||
for apps in levels {
|
||||
if !code && (flows == AuthorLevel::Full || apps == AuthorLevel::Full) {
|
||||
continue;
|
||||
}
|
||||
for (manage_schedules, manage_triggers) in
|
||||
[(true, true), (true, false), (false, true), (false, false)]
|
||||
{
|
||||
let caps = RoleCapabilities {
|
||||
code,
|
||||
flows,
|
||||
apps,
|
||||
manage_schedules,
|
||||
manage_triggers,
|
||||
..RoleCapabilities::FULL
|
||||
};
|
||||
let key = full_profile(false, deploy, &caps);
|
||||
assert!(PARTS.profiles.contains_key(&key), "{key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
PARTS.profiles.contains_key("read_only") && PARTS.profiles.contains_key("read_run")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ mod workspace;
|
||||
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) use instructions::{
|
||||
generic_session_instructions, session_instructions, workspace_context,
|
||||
generic_session_instructions, prompt_profile, session_instructions, workspace_context,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -750,7 +750,7 @@ async fn call_generated_tool(
|
||||
_ => "is read-only",
|
||||
};
|
||||
return Err(CallRefused::NotAllowed(format!(
|
||||
"Tool '{name}' changes or runs something, and this token {token}"
|
||||
"Tool '{name}' changes or runs something, and this session {token}"
|
||||
)));
|
||||
}
|
||||
dispatch(ctx, name, args).await.ok_or_else(|| {
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde_json::{json, Map, Value};
|
||||
|
||||
use super::chat::{Effect, RunPhase};
|
||||
use super::workspace::{
|
||||
api_message, get_draft, infer_script_schema, load_flow, load_script, path_enc,
|
||||
api_message, get_draft, infer_script_schema, load_flow, load_script_to_run, path_enc,
|
||||
};
|
||||
use super::{enc, js_head, js_len, js_tail, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult};
|
||||
|
||||
@@ -943,7 +943,7 @@ fn form_keys(schema: Option<&Value>) -> Vec<String> {
|
||||
}
|
||||
|
||||
async fn resolve_test_script(ctx: &Ctx<'_>, path: &str) -> Result<Resolved, String> {
|
||||
let script = load_script(ctx, path).await?;
|
||||
let script = load_script_to_run(ctx, path).await?;
|
||||
Ok(Resolved {
|
||||
schema: script.schema,
|
||||
code: Some(script.content.clone()),
|
||||
@@ -1643,7 +1643,7 @@ async fn resolve_step(ctx: &Ctx<'_>, path: &str, step_id: &str) -> Result<Resolv
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let loaded = load_script(ctx, &target).await?;
|
||||
let loaded = load_script_to_run(ctx, &target).await?;
|
||||
(loaded.content, loaded.language, loaded.schema)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -20,7 +20,7 @@ pub(crate) fn allowed(name: &str, access: SessionAccess) -> bool {
|
||||
pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult {
|
||||
if !allowed(name, ctx.access) {
|
||||
return Err(format!(
|
||||
"{name} shows drafts to deploy, and this token cannot deploy."
|
||||
"{name} shows drafts to deploy, and this session cannot deploy."
|
||||
));
|
||||
}
|
||||
match name {
|
||||
|
||||
@@ -982,6 +982,30 @@ pub(super) struct LoadedScript {
|
||||
pub schema: Option<Value>,
|
||||
}
|
||||
|
||||
/// A hub script, by its `hub/<version>/<app>/<name>` path. Hub scripts live outside the
|
||||
/// workspace: they have no draft and no workspace row.
|
||||
pub(super) async fn get_hub_script(ctx: &Ctx<'_>, path: &str) -> Result<Value, String> {
|
||||
ctx.get(&format!("/scripts/hub/get_full/{}", path_enc(path)))
|
||||
.await
|
||||
}
|
||||
|
||||
/// The script a test run executes: `load_script`, or a hub script as published. Only test
|
||||
/// runs take a hub path: an edit would save a draft no run reads, and `run_script` stays
|
||||
/// limited to deployed workspace scripts, which is all a read-and-run session may run.
|
||||
pub(super) async fn load_script_to_run(ctx: &Ctx<'_>, path: &str) -> Result<LoadedScript, String> {
|
||||
if !path.starts_with("hub/") {
|
||||
return load_script(ctx, path).await;
|
||||
}
|
||||
let script = get_hub_script(ctx, path).await?;
|
||||
let text = |key: &str| script.get(key).and_then(Value::as_str).map(String::from);
|
||||
Ok(LoadedScript {
|
||||
content: text("content").unwrap_or_default(),
|
||||
language: text("language").unwrap_or_default(),
|
||||
summary: text("summary"),
|
||||
schema: non_null(script.get("schema")).cloned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn load_script(ctx: &Ctx<'_>, path: &str) -> Result<LoadedScript, String> {
|
||||
let text = |value: &Value, key: &str| value.get(key).and_then(Value::as_str).map(String::from);
|
||||
if let Some((item, _)) = get_draft_item(ctx, "script", path, None).await? {
|
||||
@@ -1664,9 +1688,7 @@ async fn read_workspace_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
|
||||
let item = match item_type {
|
||||
"script" if hub => {
|
||||
let script = ctx
|
||||
.get(&format!("/scripts/hub/get_full/{}", path_enc(path)))
|
||||
.await?;
|
||||
let script = get_hub_script(ctx, path).await?;
|
||||
let mut row = script.clone();
|
||||
row["path"] = json!(path);
|
||||
let mut item = with_value(
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use async_trait::async_trait;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use windmill_common::workspaces::{get_protection_rules, ProtectionRules, ProtectionRuleset};
|
||||
use windmill_common::{db::UserDB, runnable_ref::RunnableRef, DB};
|
||||
use windmill_mcp::common::schema::enrich_resource_schemas;
|
||||
use windmill_mcp::common::transform::transform_property_keys;
|
||||
@@ -66,23 +67,36 @@ pub struct WindmillBackend {
|
||||
pub auth_cache: Arc<AuthCache>,
|
||||
}
|
||||
|
||||
impl WindmillBackend {
|
||||
/// The instructions only read, so they are built at the token's own read-only flag.
|
||||
fn session_ctx<'a>(&'a self, auth: &'a ApiAuthed, w_id: &'a str) -> session::Ctx<'a> {
|
||||
let access = if auth.read_only {
|
||||
SessionAccess::ReadOnly
|
||||
} else {
|
||||
SessionAccess::Full
|
||||
};
|
||||
self.session_ctx_with(auth, w_id, access)
|
||||
/// `DisableDirectDeployment` holds a session to reading and running deployed items for
|
||||
/// everyone, admins and bypassers included: that workspace takes changes from its dev workspace
|
||||
/// or a fork, where drafts can go somewhere. Unreadable rules (`None`) hold it too. The in-app
|
||||
/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both.
|
||||
fn workspace_access(access: SessionAccess, rules: Option<&[ProtectionRuleset]>) -> SessionAccess {
|
||||
let locked = rules.map_or(true, |rules| {
|
||||
rules
|
||||
.iter()
|
||||
.any(|r| r.rules.contains(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT))
|
||||
});
|
||||
match access {
|
||||
SessionAccess::Full if locked => SessionAccess::ReadAndRun,
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn session_ctx_with<'a>(
|
||||
impl WindmillBackend {
|
||||
async fn session_ctx_with<'a>(
|
||||
&'a self,
|
||||
auth: &'a ApiAuthed,
|
||||
w_id: &'a str,
|
||||
access: SessionAccess,
|
||||
) -> session::Ctx<'a> {
|
||||
let access = match access {
|
||||
SessionAccess::Full => {
|
||||
let rules = get_protection_rules(w_id, &self.db).await.ok();
|
||||
workspace_access(access, rules.as_deref().map(Vec::as_slice))
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access))
|
||||
}
|
||||
|
||||
@@ -470,16 +484,26 @@ impl McpBackend for WindmillBackend {
|
||||
&self,
|
||||
auth: &ApiAuthed,
|
||||
workspace_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> BackendResult<String> {
|
||||
Ok(session::session_instructions(&self.session_ctx(auth, workspace_id)).await)
|
||||
let ctx = self.session_ctx_with(auth, workspace_id, access).await;
|
||||
let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await;
|
||||
Ok(session::session_instructions(&ctx, &profile).await)
|
||||
}
|
||||
|
||||
fn generic_session_instructions(&self) -> String {
|
||||
session::generic_session_instructions()
|
||||
fn generic_session_instructions(&self, access: SessionAccess) -> String {
|
||||
session::generic_session_instructions(session::access(access))
|
||||
}
|
||||
|
||||
async fn workspace_context(&self, auth: &ApiAuthed, workspace_id: &str) -> String {
|
||||
session::workspace_context(&self.session_ctx(auth, workspace_id)).await
|
||||
async fn workspace_context(
|
||||
&self,
|
||||
auth: &ApiAuthed,
|
||||
workspace_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> String {
|
||||
let ctx = self.session_ctx_with(auth, workspace_id, access).await;
|
||||
let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await;
|
||||
session::workspace_context(&ctx, &profile, session::access(access)).await
|
||||
}
|
||||
|
||||
fn session_tools(&self, access: SessionAccess) -> Vec<Tool> {
|
||||
@@ -499,7 +523,7 @@ impl McpBackend for WindmillBackend {
|
||||
access: SessionAccess,
|
||||
origin: Option<&str>,
|
||||
) -> BackendResult<CallToolResult> {
|
||||
let mut ctx = self.session_ctx_with(auth, workspace_id, access);
|
||||
let mut ctx = self.session_ctx_with(auth, workspace_id, access).await;
|
||||
ctx.origin = origin;
|
||||
session::call_session_tool(&ctx, name, args).await
|
||||
}
|
||||
@@ -867,7 +891,30 @@ pub fn toolset_service() -> Router {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{scoped_to_selection, serves_session_toolset};
|
||||
use super::{
|
||||
scoped_to_selection, serves_session_toolset, workspace_access, ProtectionRules,
|
||||
ProtectionRuleset, SessionAccess,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn direct_deployment_lock_holds_full_sessions_to_read_and_run() {
|
||||
let ruleset = |rules| ProtectionRuleset {
|
||||
workspace_id: "w".to_string(),
|
||||
name: "r".to_string(),
|
||||
rules,
|
||||
bypass_groups: vec![],
|
||||
bypass_users: vec!["admin".to_string()],
|
||||
fork_role_mapping: Default::default(),
|
||||
};
|
||||
let locked = [ruleset(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)];
|
||||
let open = [ruleset(ProtectionRules::RESTRICT_DEPLOY_TO_DEPLOYERS)];
|
||||
use SessionAccess::*;
|
||||
assert_eq!(workspace_access(Full, Some(&locked)), ReadAndRun);
|
||||
assert_eq!(workspace_access(Full, None), ReadAndRun);
|
||||
assert_eq!(workspace_access(Full, Some(&open)), Full);
|
||||
assert_eq!(workspace_access(Full, Some(&[])), Full);
|
||||
assert_eq!(workspace_access(ReadOnly, Some(&locked)), ReadOnly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_token_without_mcp_all_is_a_selection() {
|
||||
|
||||
@@ -9,7 +9,7 @@ use windmill_mcp::server::{
|
||||
use crate::ai_session_tools::{self as tools, CallRefused};
|
||||
|
||||
pub(super) use tools::{
|
||||
generic_session_instructions, session_instructions, workspace_context, Ctx,
|
||||
generic_session_instructions, prompt_profile, session_instructions, workspace_context, Ctx,
|
||||
};
|
||||
|
||||
pub(super) fn access(access: SessionAccess) -> tools::SessionAccess {
|
||||
|
||||
@@ -261,18 +261,24 @@ pub trait McpBackend: Send + Sync + Clone + 'static {
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// The instructions a client reaching one workspace receives on connecting, built for
|
||||
/// this user.
|
||||
/// this user and what the token lets them do.
|
||||
async fn session_instructions(
|
||||
&self,
|
||||
auth: &Self::Auth,
|
||||
workspace_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> BackendResult<String>;
|
||||
|
||||
/// The instructions for a client reaching several workspaces: what holds in all of them.
|
||||
fn generic_session_instructions(&self) -> String;
|
||||
fn generic_session_instructions(&self, access: SessionAccess) -> String;
|
||||
|
||||
/// What `generic_session_instructions` leaves out, for one workspace.
|
||||
async fn workspace_context(&self, auth: &Self::Auth, workspace_id: &str) -> String;
|
||||
async fn workspace_context(
|
||||
&self,
|
||||
auth: &Self::Auth,
|
||||
workspace_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> String;
|
||||
|
||||
/// The tools a token with this access is offered.
|
||||
fn session_tools(&self, access: SessionAccess) -> Vec<Tool>;
|
||||
|
||||
@@ -196,7 +196,9 @@ impl<B: McpBackend> SessionRunner<B> {
|
||||
"Every tool takes a `workspace_id`: pass `{}`, the workspace this connection \
|
||||
works in.\n\n{}",
|
||||
only.id,
|
||||
self.backend.session_instructions(&auth, &only.id).await?
|
||||
self.backend
|
||||
.session_instructions(&auth, &only.id, access(&auth, &caller.scope))
|
||||
.await?
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
@@ -220,7 +222,8 @@ impl<B: McpBackend> SessionRunner<B> {
|
||||
below), the folders you can write to, and the workspace's skills and \
|
||||
instructions. When the user has not said which workspace, ask rather than \
|
||||
guess, and name the workspace whenever you change something.\n\n{}",
|
||||
self.backend.generic_session_instructions()
|
||||
self.backend
|
||||
.generic_session_instructions(access(&caller.auth, &caller.scope))
|
||||
)
|
||||
}
|
||||
};
|
||||
@@ -371,7 +374,10 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
|
||||
};
|
||||
let auth = self.auth_in(&caller, &workspace_id).await?;
|
||||
if request.name == GET_WORKSPACE_CONTEXT {
|
||||
let text = self.backend.workspace_context(&auth, &workspace_id).await;
|
||||
let text = self
|
||||
.backend
|
||||
.workspace_context(&auth, &workspace_id, access(&auth, &caller.scope))
|
||||
.await;
|
||||
return Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into());
|
||||
}
|
||||
let result = self
|
||||
|
||||
@@ -23,6 +23,7 @@ use windmill_common::get_latest_flow_version_id_for_path;
|
||||
use windmill_common::jobs::JobPayload;
|
||||
use windmill_common::jobs::JobTriggerKind;
|
||||
use windmill_common::jobs::OnBehalfOf;
|
||||
use windmill_common::runnable_ref::RunnableRef;
|
||||
use windmill_common::runnable_settings::ConcurrencySettings;
|
||||
use windmill_common::runnable_settings::DebouncingSettings;
|
||||
use windmill_common::schedule::schedule_to_user;
|
||||
@@ -43,6 +44,7 @@ use windmill_common::{
|
||||
async fn get_schedule_metadata<'c>(
|
||||
tx: &mut sqlx::Transaction<'c, sqlx::Postgres>,
|
||||
schedule: &Schedule,
|
||||
target: &RunnableRef,
|
||||
) -> Result<(
|
||||
Option<String>, // tag
|
||||
Option<i32>, // timeout
|
||||
@@ -61,7 +63,7 @@ async fn get_schedule_metadata<'c>(
|
||||
None,
|
||||
&mut **tx,
|
||||
&schedule.workspace_id,
|
||||
&schedule.script_path,
|
||||
target.path(),
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
@@ -70,7 +72,7 @@ async fn get_schedule_metadata<'c>(
|
||||
&mut **tx,
|
||||
version,
|
||||
&schedule.workspace_id,
|
||||
&schedule.script_path,
|
||||
target.path(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -87,7 +89,7 @@ async fn get_schedule_metadata<'c>(
|
||||
Some(version),
|
||||
parsed_retry,
|
||||
))
|
||||
} else if schedule.script_path.starts_with("hub/") {
|
||||
} else if target.path().starts_with("hub/") {
|
||||
Ok((None, None, None, None, None, parsed_retry))
|
||||
} else {
|
||||
let (
|
||||
@@ -111,7 +113,7 @@ async fn get_schedule_metadata<'c>(
|
||||
) = windmill_common::get_latest_hash_for_path(
|
||||
&mut **tx,
|
||||
&schedule.workspace_id,
|
||||
&schedule.script_path,
|
||||
target.path(),
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
@@ -138,6 +140,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
));
|
||||
}
|
||||
|
||||
let target = RunnableRef::from_path(&schedule.script_path, schedule.is_flow)?;
|
||||
let sched =
|
||||
ScheduleType::from_str(&schedule.schedule, schedule.cron_version.as_deref(), false)?;
|
||||
|
||||
@@ -200,7 +203,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
&schedule.workspace_id,
|
||||
&schedule.path,
|
||||
next,
|
||||
&schedule.script_path
|
||||
target.path()
|
||||
)
|
||||
.fetch_one(&mut *tx)
|
||||
.warn_after_seconds_with_sql(1, "already_exists_job".to_string())
|
||||
@@ -326,11 +329,11 @@ pub async fn push_scheduled_job<'c>(
|
||||
|
||||
// Get metadata from the scheduled script/flow for tag, timeout, etc.
|
||||
let (tag, timeout, on_behalf_of, hash, flow_version, retry) =
|
||||
get_schedule_metadata(&mut tx, schedule).await?;
|
||||
get_schedule_metadata(&mut tx, schedule, &target).await?;
|
||||
|
||||
(
|
||||
JobPayload::SingleStepFlow {
|
||||
path: schedule.script_path.clone(),
|
||||
path: target.path().to_string(),
|
||||
hash,
|
||||
flow_version,
|
||||
language: None,
|
||||
@@ -366,7 +369,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
None,
|
||||
&mut *tx,
|
||||
&schedule.workspace_id,
|
||||
&schedule.script_path,
|
||||
target.path(),
|
||||
false,
|
||||
)
|
||||
.warn_after_seconds_with_sql(1, "get_latest_flow_version_id_for_path".to_string())
|
||||
@@ -376,7 +379,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
&mut *tx,
|
||||
version,
|
||||
&schedule.workspace_id,
|
||||
&schedule.script_path,
|
||||
target.path(),
|
||||
)
|
||||
.warn_after_seconds_with_sql(1, "get_flow_version_info_from_version".to_string())
|
||||
.await?;
|
||||
@@ -391,7 +394,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
|
||||
(
|
||||
JobPayload::Flow {
|
||||
path: schedule.script_path.clone(),
|
||||
path: target.path().to_string(),
|
||||
dedicated_worker,
|
||||
apply_preprocessor: false,
|
||||
version,
|
||||
@@ -402,18 +405,18 @@ pub async fn push_scheduled_job<'c>(
|
||||
None,
|
||||
on_behalf_of,
|
||||
)
|
||||
} else if schedule.script_path.starts_with("hub/") {
|
||||
} else if target.path().starts_with("hub/") {
|
||||
let tag = schedule.tag.clone().filter(|t| !t.is_empty());
|
||||
let payload = match &schedule.retry {
|
||||
// The language is what lets `push` materialize this as a native retry
|
||||
// instead of a flow wrapper, which would queue the next tick at start.
|
||||
Some(retry) => JobPayload::SingleStepFlow {
|
||||
path: schedule.script_path.clone(),
|
||||
path: target.path().to_string(),
|
||||
hash: None,
|
||||
flow_version: None,
|
||||
language: Some(
|
||||
get_full_hub_script_by_path(
|
||||
StripPath(schedule.script_path.clone()),
|
||||
StripPath(target.path().to_string()),
|
||||
&HTTP_CLIENT,
|
||||
Some(db),
|
||||
)
|
||||
@@ -438,10 +441,9 @@ pub async fn push_scheduled_job<'c>(
|
||||
concurrency_settings: ConcurrencySettings::default(),
|
||||
debouncing_settings: DebouncingSettings::default(),
|
||||
},
|
||||
None => JobPayload::ScriptHub {
|
||||
path: schedule.script_path.clone(),
|
||||
apply_preprocessor: false,
|
||||
},
|
||||
None => {
|
||||
JobPayload::ScriptHub { path: target.path().to_string(), apply_preprocessor: false }
|
||||
}
|
||||
};
|
||||
(payload, tag, None, None)
|
||||
} else {
|
||||
@@ -466,7 +468,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
) = windmill_common::get_latest_hash_for_path(
|
||||
&mut *tx,
|
||||
&schedule.workspace_id,
|
||||
&schedule.script_path,
|
||||
target.path(),
|
||||
false,
|
||||
)
|
||||
.warn_after_seconds_with_sql(1, "get_latest_hash_for_path".to_string())
|
||||
@@ -500,7 +502,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
// cannot be evaluated and fails closed (no retry).
|
||||
(
|
||||
JobPayload::SingleStepFlow {
|
||||
path: schedule.script_path.clone(),
|
||||
path: target.path().to_string(),
|
||||
hash: Some(hash),
|
||||
flow_version: None,
|
||||
language: Some(language),
|
||||
@@ -534,7 +536,7 @@ pub async fn push_scheduled_job<'c>(
|
||||
(
|
||||
JobPayload::ScriptHash {
|
||||
hash,
|
||||
path: schedule.script_path.clone(),
|
||||
path: target.path().to_string(),
|
||||
cache_ttl,
|
||||
cache_ignore_s3_path,
|
||||
dedicated_worker,
|
||||
|
||||
@@ -145,6 +145,26 @@ mod schedule_push {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))]
|
||||
async fn test_push_parses_target(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
let authed = make_authed();
|
||||
let schedule = make_schedule(|s| s.script_path = "/f/system/test_script".to_string());
|
||||
let tx = db.begin().await?;
|
||||
push_scheduled_job(&db, tx, &schedule, Some(&authed), None)
|
||||
.await?
|
||||
.commit()
|
||||
.await?;
|
||||
let (_, path, _, _) = get_queued_job(&db).await.unwrap();
|
||||
assert_eq!(path.as_deref(), Some("f/system/test_script"));
|
||||
|
||||
let schedule = make_schedule(|s| s.script_path = "//f/system/test_script".to_string());
|
||||
let tx = db.begin().await?;
|
||||
assert!(push_scheduled_job(&db, tx, &schedule, Some(&authed), None)
|
||||
.await
|
||||
.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// push_scheduled_job: flow schedule
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@@ -230,7 +230,7 @@ const createHTML = (jsPath: string, cssPath: string, appCtx: unknown) => `
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>window.ctx = ${JSON.stringify(appCtx).replace(/</g, "\\u003c")};</script>
|
||||
<script>window.ctx = ${JSON.stringify(appCtx).replace(/</g, "\\u003c")}; window.ctx.query = Object.fromEntries(new URLSearchParams(location.search));</script>
|
||||
<script src="${jsPath}"></script>
|
||||
<script>
|
||||
// Live reload via EventSource
|
||||
|
||||
@@ -107,6 +107,13 @@ async function get(opts: GlobalOptions & { json?: boolean }, path: string) {
|
||||
}
|
||||
}
|
||||
|
||||
// A server stores a target without its one tolerated leading `/`, while one predating
|
||||
// that stores it as typed. Compared as written, the two spellings never match and every
|
||||
// push re-saves the schedule, which resets its run-as to a non-admin pusher.
|
||||
function canonicalTarget(path: string): string {
|
||||
return path?.startsWith("/") && !path.startsWith("//") ? path.slice(1) : path;
|
||||
}
|
||||
|
||||
export async function pushSchedule(
|
||||
workspace: string,
|
||||
path: string,
|
||||
@@ -130,6 +137,8 @@ export async function pushSchedule(
|
||||
// Strip CLI-only boolean marker before sending to API
|
||||
delete (localSchedule as any).has_permissioned_as;
|
||||
|
||||
localSchedule.script_path = canonicalTarget(localSchedule.script_path);
|
||||
|
||||
// In a fork, the file's `enabled` is the parent's for a path the parent
|
||||
// also has (see sync push's `parentOwnedScheduleEnabled`): the fork's own
|
||||
// flag stays as it is.
|
||||
@@ -158,7 +167,8 @@ export async function pushSchedule(
|
||||
}
|
||||
|
||||
if (schedule) {
|
||||
if (isSuperset(localSchedule, schedule)) {
|
||||
const remote = { ...schedule, script_path: canonicalTarget(schedule.script_path) };
|
||||
if (isSuperset(localSchedule, remote)) {
|
||||
log.debug(`Schedule ${path} is up to date`);
|
||||
return;
|
||||
}
|
||||
|
||||
Generated
+2
@@ -6782,6 +6782,8 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! }
|
||||
|
||||
**Set the browser tab title with \`document.title = '...'\`** (or a \`<title>\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes.
|
||||
|
||||
**Read the page's context from \`window.ctx\`**: \`ctx\` is the viewer (absent for anonymous visitors), \`workspace\` and \`path\` the app's (\`path\` is not set under \`wmill app dev\`), and \`query\` the page URL's query parameters as strings (\`…/apps/get/u/me/app?customer=42\` gives \`window.ctx.query.customer === '42'\`, and no query gives \`{}\`). Read it there, not from \`window.location\`, which in a sandboxed app is not the page's address. It is read once when the app loads.
|
||||
|
||||
**Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen.
|
||||
|
||||
### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`)
|
||||
|
||||
@@ -13,12 +13,13 @@ import { mockServices } from "./mock_services.ts";
|
||||
|
||||
let updateScheduleCalls: any[] = [];
|
||||
let remotePermissionedAs: string | undefined = "u/svc";
|
||||
let remoteScriptPath = "u/admin/script";
|
||||
|
||||
const REMOTE_SCHEDULE = () => ({
|
||||
path: "u/admin/sched",
|
||||
schedule: "0 0 */6 * * *",
|
||||
timezone: "Etc/UTC",
|
||||
script_path: "u/admin/script",
|
||||
script_path: remoteScriptPath,
|
||||
is_flow: false,
|
||||
args: {},
|
||||
enabled: false,
|
||||
@@ -74,8 +75,8 @@ await mockModule("../src/core/auth.ts", (real) => ({
|
||||
requireLogin: async () => ({}),
|
||||
}));
|
||||
|
||||
const scheduleCommand = (await import("../src/commands/schedule/schedule.ts"))
|
||||
.default;
|
||||
const scheduleModule = await import("../src/commands/schedule/schedule.ts");
|
||||
const scheduleCommand = scheduleModule.default;
|
||||
|
||||
async function pushIn(wmillYamlTail: string): Promise<void> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "windmill_sched_push_"));
|
||||
@@ -107,6 +108,7 @@ describe("wmill schedule push ownership", () => {
|
||||
beforeEach(() => {
|
||||
updateScheduleCalls = [];
|
||||
remotePermissionedAs = "u/svc";
|
||||
remoteScriptPath = "u/admin/script";
|
||||
});
|
||||
|
||||
test("keeps the remote's permissioned_as under syncBehavior v1", async () => {
|
||||
@@ -141,4 +143,20 @@ describe("wmill schedule push ownership", () => {
|
||||
expect(body.permissioned_as).toBeUndefined();
|
||||
expect(body.preserve_permissioned_as).toBeUndefined();
|
||||
});
|
||||
|
||||
for (const [server, stored] of [
|
||||
["a current server", "u/admin/script"],
|
||||
["an older server", "/u/admin/script"],
|
||||
]) {
|
||||
test(`a target written with one leading slash matches what ${server} stores (${stored})`, async () => {
|
||||
remoteScriptPath = stored;
|
||||
const { permissioned_as: _, path: __, ...remote } = REMOTE_SCHEDULE();
|
||||
await scheduleModule.pushSchedule("w", "u/admin/sched.schedule.yaml", undefined, {
|
||||
...remote,
|
||||
script_path: "/u/admin/script",
|
||||
} as any);
|
||||
|
||||
expect(updateScheduleCalls).toHaveLength(0);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -20,6 +20,12 @@
|
||||
import SyncResourceTypes from './SyncResourceTypes.svelte'
|
||||
import { parsePostgresConnectionString } from '$lib/utils/postgresConnectionString'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
import DropdownV2 from './DropdownV2.svelte'
|
||||
import ResourceValueReference, {
|
||||
canReferenceWholeValue,
|
||||
resourceValueMenuItems,
|
||||
resourceValueReference
|
||||
} from './ResourceValueReference.svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
|
||||
@@ -72,6 +78,7 @@
|
||||
if (!resourceTypeInfo) return
|
||||
rawCode = '{}'
|
||||
viewJsonSchema = false
|
||||
referencePinned = false
|
||||
try {
|
||||
schema = resourceTypeInfo.schema as any
|
||||
// A resource type may declare no properties at all — `dbt_profile` is a
|
||||
@@ -111,6 +118,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
let reference = $derived(resourceValueReference(args))
|
||||
// Pinned only by the picker: text typed into the JSON editor that parses to a reference keeps
|
||||
// that editor, while any other form would replace the string with its own fields.
|
||||
let referencePinned = $state(false)
|
||||
let showReference = $derived(
|
||||
!!reference && (referencePinned || !(notFound || viewJsonSchema || !schema?.properties))
|
||||
)
|
||||
let valueReference: ResourceValueReference | undefined = $state(undefined)
|
||||
|
||||
function setWholeValue(v: Record<string, any> | string) {
|
||||
referencePinned = typeof v === 'string'
|
||||
// The "As JSON" toggle holds its own state and remounts unchecked with the form.
|
||||
viewJsonSchema = false
|
||||
rawCode = JSON.stringify(v, null, 2)
|
||||
args = v
|
||||
}
|
||||
|
||||
let connectionString = $state('')
|
||||
let validConnectionString = $state(true)
|
||||
function parseConnectionString(close: (_: any) => void) {
|
||||
@@ -171,101 +195,113 @@
|
||||
|
||||
{#if !notFound}
|
||||
<div class="w-full flex gap-2 flex-row-reverse items-center">
|
||||
<Toggle
|
||||
on:change={(e) => switchTab(e.detail)}
|
||||
options={{
|
||||
right: 'As JSON'
|
||||
}}
|
||||
class="as-json-toggle"
|
||||
/>
|
||||
<ResourceGen
|
||||
bind:args
|
||||
{resourceType}
|
||||
resourceSchema={notFound ? undefined : schema}
|
||||
isFileset={resourceTypeInfo?.is_fileset ?? false}
|
||||
/>
|
||||
<TestConnection {resourceType} {args} />
|
||||
{#if aiProvider}
|
||||
<TestAiKey
|
||||
{aiProvider}
|
||||
workspace={workspace ?? $operatingWorkspace}
|
||||
resourceValue={args}
|
||||
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
|
||||
{#if showReference || canReferenceWholeValue(resourceTypeInfo)}
|
||||
<DropdownV2
|
||||
placement="bottom-end"
|
||||
items={() =>
|
||||
resourceValueMenuItems(showReference ? reference : undefined, {
|
||||
pickVariable: () => valueReference?.pickVariable(),
|
||||
editFields: () => setWholeValue({})
|
||||
})}
|
||||
/>
|
||||
{/if}
|
||||
{#if resourceType == 'postgresql'}
|
||||
<Popover
|
||||
floatingConfig={{
|
||||
placement: 'bottom'
|
||||
{#if !showReference}
|
||||
<Toggle
|
||||
on:change={(e) => switchTab(e.detail)}
|
||||
options={{
|
||||
right: 'As JSON'
|
||||
}}
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<Button spacingSize="sm" size="xs" unifiedSize="md" variant="default" nonCaptureEvent>
|
||||
From connection string
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#snippet content({ close })}
|
||||
<div class="block text-primary p-4">
|
||||
<div class="w-[550px] flex flex-col items-start gap-1">
|
||||
<div class="flex flex-row gap-1 w-full">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={connectionString}
|
||||
placeholder="postgres://user:password@host:5432/dbname?sslmode=disable"
|
||||
/>
|
||||
<Button
|
||||
size="xs"
|
||||
color="blue"
|
||||
buttonType="button"
|
||||
on:click={() => {
|
||||
parseConnectionString(close)
|
||||
}}
|
||||
disabled={connectionString.length <= 0}
|
||||
>
|
||||
Apply
|
||||
</Button>
|
||||
class="as-json-toggle"
|
||||
/>
|
||||
<ResourceGen
|
||||
bind:args
|
||||
{resourceType}
|
||||
resourceSchema={notFound ? undefined : schema}
|
||||
isFileset={resourceTypeInfo?.is_fileset ?? false}
|
||||
/>
|
||||
<TestConnection {resourceType} {args} />
|
||||
{#if aiProvider}
|
||||
<TestAiKey
|
||||
{aiProvider}
|
||||
workspace={workspace ?? $operatingWorkspace}
|
||||
resourceValue={args}
|
||||
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
|
||||
/>
|
||||
{/if}
|
||||
{#if resourceType == 'postgresql'}
|
||||
<Popover
|
||||
floatingConfig={{
|
||||
placement: 'bottom'
|
||||
}}
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<Button spacingSize="sm" size="xs" unifiedSize="md" variant="default" nonCaptureEvent>
|
||||
From connection string
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#snippet content({ close })}
|
||||
<div class="block text-primary p-4">
|
||||
<div class="w-[550px] flex flex-col items-start gap-1">
|
||||
<div class="flex flex-row gap-1 w-full">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={connectionString}
|
||||
placeholder="postgres://user:password@host:5432/dbname?sslmode=disable"
|
||||
/>
|
||||
<Button
|
||||
size="xs"
|
||||
color="blue"
|
||||
buttonType="button"
|
||||
on:click={() => {
|
||||
parseConnectionString(close)
|
||||
}}
|
||||
disabled={connectionString.length <= 0}
|
||||
>
|
||||
Apply
|
||||
</Button>
|
||||
</div>
|
||||
{#if !validConnectionString}
|
||||
<p class="text-red-500 text-xs">Could not parse connection string</p>
|
||||
{/if}
|
||||
</div>
|
||||
{#if !validConnectionString}
|
||||
<p class="text-red-500 text-xs">Could not parse connection string</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
{/if}
|
||||
{#if resourceType == 'postgresql' && supabaseWizard}
|
||||
<!-- Imported here rather than at the top so the wizard's Supabase graph stays out of
|
||||
{/snippet}
|
||||
</Popover>
|
||||
{/if}
|
||||
{#if resourceType == 'postgresql' && supabaseWizard}
|
||||
<!-- Imported here rather than at the top so the wizard's Supabase graph stays out of
|
||||
this form's chunk, which loads on the resources page and in every resource drawer. -->
|
||||
{#await import('./workspaceSettings/SupabaseResourceConnect.svelte')}
|
||||
<Loader2 class="animate-spin" />
|
||||
{:then Module}
|
||||
<Module.default onPicked={applySupabasePick} />
|
||||
{/await}
|
||||
{/if}
|
||||
<GitHubAppIntegration
|
||||
{resourceType}
|
||||
{args}
|
||||
{description}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
rawCodeEditor?.setCode(rawCode)
|
||||
}}
|
||||
onDescriptionUpdate={(newDescription) => (description = newDescription)}
|
||||
/>
|
||||
<!-- Last in a `flex-row-reverse` row, so it lands beside the GitHub App
|
||||
{#await import('./workspaceSettings/SupabaseResourceConnect.svelte')}
|
||||
<Loader2 class="animate-spin" />
|
||||
{:then Module}
|
||||
<Module.default onPicked={applySupabasePick} />
|
||||
{/await}
|
||||
{/if}
|
||||
<GitHubAppIntegration
|
||||
{resourceType}
|
||||
{args}
|
||||
{description}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
rawCodeEditor?.setCode(rawCode)
|
||||
}}
|
||||
onDescriptionUpdate={(newDescription) => (description = newDescription)}
|
||||
/>
|
||||
<!-- Last in a `flex-row-reverse` row, so it lands beside the GitHub App
|
||||
button without splitting it from its own refresh control. -->
|
||||
<GitLabIntegration
|
||||
{resourceType}
|
||||
{args}
|
||||
{workspace}
|
||||
{onCredentialStored}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
rawCodeEditor?.setCode(rawCode)
|
||||
}}
|
||||
/>
|
||||
<GitLabIntegration
|
||||
{resourceType}
|
||||
{args}
|
||||
{workspace}
|
||||
{onCredentialStored}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
rawCodeEditor?.setCode(rawCode)
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{#if resourceType?.includes('bedrock') && !isCloudHosted()}
|
||||
<BedrockCredentialsCheck />
|
||||
@@ -277,7 +313,13 @@
|
||||
>
|
||||
<SyncResourceTypes {resourceType} {onSynced} />
|
||||
{/if}
|
||||
{#if notFound || viewJsonSchema || !schema?.properties}
|
||||
<ResourceValueReference
|
||||
bind:this={valueReference}
|
||||
reference={showReference ? reference : undefined}
|
||||
workspace={workspace ?? $operatingWorkspace}
|
||||
onPick={setWholeValue}
|
||||
/>
|
||||
{#if showReference}{:else if notFound || viewJsonSchema || !schema?.properties}
|
||||
{#if !emptyString(error)}<span class="text-red-400 text-xs mb-1 flex flex-row-reverse"
|
||||
>{error}</span
|
||||
>{:else}<div class="py-2"></div>{/if}
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
|
||||
const bubble = createBubbler()
|
||||
import type { Schema } from '$lib/common'
|
||||
import { VariableService, type ScriptLang } from '$lib/gen'
|
||||
import { type ScriptLang } from '$lib/gen'
|
||||
import { Button } from './common'
|
||||
import ItemPicker from './ItemPicker.svelte'
|
||||
import VariableEditor from './VariableEditor.svelte'
|
||||
import type ItemPicker from './ItemPicker.svelte'
|
||||
import type VariableEditor from './VariableEditor.svelte'
|
||||
import VariablePicker from './VariablePicker.svelte'
|
||||
import { Pen, Plus, X } from 'lucide-svelte'
|
||||
import { Pane, Splitpanes } from 'svelte-splitpanes'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
@@ -14,7 +15,6 @@
|
||||
import PropertyEditor from './schema/PropertyEditor.svelte'
|
||||
import SimpleEditor from './SimpleEditor.svelte'
|
||||
import { createEventDispatcher, untrack } from 'svelte'
|
||||
import { watch } from 'runed'
|
||||
import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import Label from './Label.svelte'
|
||||
@@ -186,11 +186,6 @@
|
||||
let itemPicker: ItemPicker | undefined = $state(undefined)
|
||||
let variableEditor: VariableEditor | undefined = $state(undefined)
|
||||
|
||||
watch(
|
||||
() => ws,
|
||||
() => itemPicker?.reloadItems()
|
||||
)
|
||||
|
||||
let keys: string[] = $state(
|
||||
(Array.isArray(schema?.order)
|
||||
? [...schema.order]
|
||||
@@ -923,40 +918,16 @@
|
||||
</div>
|
||||
|
||||
{#if !noVariablePicker}
|
||||
<ItemPicker
|
||||
bind:this={itemPicker}
|
||||
pickCallback={(path, _) => {
|
||||
if (pickForField) {
|
||||
if (args) {
|
||||
args[pickForField] = '$var:' + path
|
||||
}
|
||||
<VariablePicker
|
||||
bind:itemPicker
|
||||
bind:variableEditor
|
||||
workspace={ws}
|
||||
onPick={(path) => {
|
||||
if (pickForField && args) {
|
||||
args[pickForField] = '$var:' + path
|
||||
}
|
||||
}}
|
||||
itemName="Variable"
|
||||
tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow."
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets"
|
||||
extraField="path"
|
||||
loadItems={async () =>
|
||||
(await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({
|
||||
name: x.path,
|
||||
...x
|
||||
}))}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<div>
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
startIcon={{ icon: Plus }}
|
||||
on:click={() => variableEditor?.initNew?.()}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
|
||||
<VariableEditor bind:this={variableEditor} workspace={ws} />
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
import type Editor from './Editor.svelte'
|
||||
import ItemPicker from './ItemPicker.svelte'
|
||||
import VariableEditor from './VariableEditor.svelte'
|
||||
import VariablePicker from './VariablePicker.svelte'
|
||||
import Button from './common/button/Button.svelte'
|
||||
import HighlightCode from './HighlightCode.svelte'
|
||||
import DrawerContent from './common/drawer/DrawerContent.svelte'
|
||||
@@ -157,10 +157,9 @@
|
||||
let ws = $derived(workspace ?? $operatingWorkspace)
|
||||
|
||||
let contextualVariablePicker: ItemPicker | undefined = $state()
|
||||
let variablePicker: ItemPicker | undefined = $state()
|
||||
let variablePicker: VariablePicker | undefined = $state()
|
||||
let resourcePicker: ItemPicker | undefined = $state()
|
||||
let resourceTypePicker: ItemPicker | undefined = $state()
|
||||
let variableEditor: VariableEditor | undefined = $state()
|
||||
let resourceEditor: ResourceEditorDrawer | undefined = $state()
|
||||
let s3FilePicker: S3FilePicker | undefined = $state()
|
||||
let ducklakePicker: ItemPicker | undefined = $state()
|
||||
@@ -372,10 +371,6 @@
|
||||
editor && untrack(() => addEditorActions())
|
||||
})
|
||||
|
||||
async function loadVariables() {
|
||||
return await VariableService.listVariable({ workspace: ws ?? '' })
|
||||
}
|
||||
|
||||
async function loadContextualVariables() {
|
||||
return await VariableService.listContextualVariables({
|
||||
workspace: ws ?? 'NO_W'
|
||||
@@ -664,9 +659,11 @@
|
||||
loadItems={loadContextualVariables}
|
||||
/>
|
||||
|
||||
<ItemPicker
|
||||
<VariablePicker
|
||||
editable
|
||||
bind:this={variablePicker}
|
||||
pickCallback={(path, name) => {
|
||||
workspace={ws}
|
||||
onPick={(path, name) => {
|
||||
if (!editor) return
|
||||
if (['javascript', 'typescript'].includes(scriptLangToEditorLang(lang))) {
|
||||
if (!editor.getCode().includes('import * as wmill from')) {
|
||||
@@ -730,27 +727,7 @@ string ${windmillPathToCamelCaseName(path)} = await client.GetStringAsync(uri);
|
||||
}
|
||||
sendUserToast(`${name} inserted at cursor`)
|
||||
}}
|
||||
tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow."
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets"
|
||||
itemName="Variable"
|
||||
extraField="path"
|
||||
loadItems={loadVariables}
|
||||
buttons={{ 'Edit/View': (x) => variableEditor?.editVariable(x) }}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<div class="flex flex-row">
|
||||
<Button
|
||||
variant="accent"
|
||||
startIcon={{ icon: Plus }}
|
||||
on:click={() => {
|
||||
variableEditor?.initNew()
|
||||
}}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
/>
|
||||
|
||||
<ItemPicker
|
||||
bind:this={resourcePicker}
|
||||
@@ -870,7 +847,6 @@ JsonNode ${windmillPathToCamelCaseName(path)} = JsonNode.Parse(await client.GetS
|
||||
workspace={ws}
|
||||
on:refresh={resourcePicker.openDrawer}
|
||||
/>
|
||||
<VariableEditor bind:this={variableEditor} workspace={ws} on:create={variablePicker.openDrawer} />
|
||||
|
||||
{#if showDucklakePicker}
|
||||
<ItemPicker
|
||||
@@ -1081,7 +1057,7 @@ JsonNode ${windmillPathToCamelCaseName(path)} = JsonNode.Parse(await client.GetS
|
||||
aiDescription="Add variable"
|
||||
title="Add variable"
|
||||
variant="subtle"
|
||||
on:click={variablePicker.openDrawer}
|
||||
on:click={() => variablePicker?.openDrawer()}
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: DollarSign }}
|
||||
{iconOnly}
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { VariableService } from '$lib/gen'
|
||||
import { watch } from 'runed'
|
||||
import { Plus } from 'lucide-svelte'
|
||||
import { Button } from './common'
|
||||
import ItemPicker from './ItemPicker.svelte'
|
||||
import VariableEditor from './VariableEditor.svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
import type ItemPicker from './ItemPicker.svelte'
|
||||
import type VariableEditor from './VariableEditor.svelte'
|
||||
import VariablePicker from './VariablePicker.svelte'
|
||||
|
||||
interface Props {
|
||||
/** The transforms being edited. A picked variable is written into `pickForField`'s. */
|
||||
@@ -27,44 +21,15 @@
|
||||
itemPicker = $bindable(),
|
||||
variableEditor = $bindable()
|
||||
}: Props = $props()
|
||||
|
||||
let ws = $derived(workspace ?? $operatingWorkspace)
|
||||
|
||||
watch(
|
||||
() => ws,
|
||||
() => itemPicker?.reloadItems()
|
||||
)
|
||||
</script>
|
||||
|
||||
<ItemPicker
|
||||
bind:this={itemPicker}
|
||||
pickCallback={(path, _) => {
|
||||
<VariablePicker
|
||||
bind:itemPicker
|
||||
bind:variableEditor
|
||||
{workspace}
|
||||
onPick={(path) => {
|
||||
if (pickForField) {
|
||||
args[pickForField].value = '$var:' + path
|
||||
}
|
||||
}}
|
||||
itemName="Variable"
|
||||
extraField="path"
|
||||
loadItems={async () =>
|
||||
(await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({
|
||||
name: x.path,
|
||||
...x
|
||||
}))}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<div class="flex flex-row-reverse w-full border-t border-gray-200 rounded-bl-lg rounded-br-lg">
|
||||
<Button
|
||||
variant="accent"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: Plus }}
|
||||
on:click={() => {
|
||||
variableEditor?.initNew?.()
|
||||
}}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
|
||||
<VariableEditor bind:this={variableEditor} workspace={ws} />
|
||||
/>
|
||||
|
||||
@@ -28,12 +28,15 @@
|
||||
applyButtonIcon = undefined,
|
||||
// Render ```mermaid blocks as diagrams. Off by default so untrusted
|
||||
// markdown surfaces don't execute mermaid — the chat opts in.
|
||||
renderMermaid = false
|
||||
renderMermaid = false,
|
||||
// Draw diagrams in the light theme whatever the app's theme (printing).
|
||||
lightMermaid = false
|
||||
}: {
|
||||
showApplyButton?: boolean
|
||||
onApplyCode?: () => void
|
||||
applyButtonIcon?: typeof ClipboardCopy
|
||||
renderMermaid?: boolean
|
||||
lightMermaid?: boolean
|
||||
} = $props()
|
||||
|
||||
const astNode = getAstNode()
|
||||
@@ -131,7 +134,7 @@
|
||||
<div class="flex flex-col gap-0.5 rounded-md relative not-prose !text-xs">
|
||||
<div class="relative w-full bg-surface-secondary rounded-md overflow-hidden">
|
||||
{#if renderMermaid && language === 'mermaid'}
|
||||
<MermaidDisplay code={code ?? ''} />
|
||||
<MermaidDisplay code={code ?? ''} forceLight={lightMermaid} />
|
||||
{:else}
|
||||
<HighlightCode
|
||||
className="px-3 py-2.5 !text-xs"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import ResourceDescriptionField from './ResourceDescriptionField.svelte'
|
||||
import type { Schema } from '$lib/common'
|
||||
import type { Resource, ResourceType } from '$lib/gen'
|
||||
import { onDestroy } from 'svelte'
|
||||
import { onDestroy, untrack } from 'svelte'
|
||||
import { setEditorUnparseable } from './pendingEditorFlush'
|
||||
import { emptyString, isOwner, urlize } from '$lib/utils'
|
||||
import { Alert, Skeleton } from './common'
|
||||
@@ -26,6 +26,12 @@
|
||||
import Label from './Label.svelte'
|
||||
import ResourcePathHint from './ResourcePathHint.svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
import DropdownV2 from './DropdownV2.svelte'
|
||||
import ResourceValueReference, {
|
||||
canReferenceWholeValue,
|
||||
resourceValueMenuItems,
|
||||
resourceValueReference
|
||||
} from './ResourceValueReference.svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
|
||||
@@ -93,6 +99,30 @@
|
||||
let rawCode: string | undefined = $state(undefined)
|
||||
let textFileContent: string = $state('')
|
||||
|
||||
let reference = $derived(resourceValueReference(args))
|
||||
let rawMode = $derived(
|
||||
viewJsonSchema ||
|
||||
(!resourceTypeInfo?.is_fileset && !(resourceSchema && resourceSchema.properties))
|
||||
)
|
||||
// Pinned when the value arrives as a reference (loaded or picked), not when the JSON editor's
|
||||
// text parses to one: that editor stays mounted while it is being typed into. Any other form
|
||||
// would replace the string with its own fields, so it never renders over a reference.
|
||||
let referencePinned = $state(untrack(() => !!resourceValueReference(args)))
|
||||
let showReference = $derived(!!reference && (referencePinned || !rawMode))
|
||||
let valueReference: ResourceValueReference | undefined = $state(undefined)
|
||||
|
||||
function setWholeValue(v: Record<string, any> | string) {
|
||||
args = v as Record<string, any>
|
||||
referencePinned = typeof v === 'string'
|
||||
jsonError = ''
|
||||
// Reseeded from the new value by the effect below once the raw editor is the input again.
|
||||
rawCode = undefined
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (showReference) isValid = true
|
||||
})
|
||||
|
||||
// This field is a bare SimpleEditor parsed here, so it never passes through JsonEditor —
|
||||
// it has to register itself, or a caller persisting what is on screen would save the
|
||||
// last value that parsed and leave without the text in front of the user.
|
||||
@@ -115,11 +145,7 @@
|
||||
// The raw JSON editor is the active input whenever the "As JSON" toggle is on,
|
||||
// or no schema-based form can be rendered (e.g. the resource type is missing
|
||||
// from the workspace). In both cases rawCode must be seeded from args.
|
||||
let usesRawEditor = $derived(
|
||||
!loadingSchema &&
|
||||
(viewJsonSchema ||
|
||||
(!resourceTypeInfo?.is_fileset && !(resourceSchema && resourceSchema.properties)))
|
||||
)
|
||||
let usesRawEditor = $derived(!loadingSchema && !showReference && rawMode)
|
||||
|
||||
$effect(() => {
|
||||
if (rawCode !== undefined) parseJson()
|
||||
@@ -142,7 +168,13 @@
|
||||
// Seed the JSON editor when the resource type schema is missing
|
||||
// (restores the old ResourceEditor's catch-block behavior)
|
||||
$effect(() => {
|
||||
if (resource_type && !loadingSchema && !resourceSchema && rawCode === undefined) {
|
||||
if (
|
||||
resource_type &&
|
||||
!loadingSchema &&
|
||||
!resourceSchema &&
|
||||
!showReference &&
|
||||
rawCode === undefined
|
||||
) {
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
}
|
||||
})
|
||||
@@ -200,79 +232,98 @@
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="w-full flex gap-4 flex-row-reverse items-center">
|
||||
<Toggle
|
||||
bind:checked={viewJsonSchema}
|
||||
on:change={(e) => {
|
||||
if (e.detail) {
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
} else if (resourceTypeInfo?.format_extension && !resourceTypeInfo?.is_fileset) {
|
||||
textFileContent = args?.content ?? ''
|
||||
}
|
||||
}}
|
||||
options={{
|
||||
right: 'As JSON'
|
||||
}}
|
||||
/>
|
||||
<ResourceGen
|
||||
bind:args
|
||||
resourceType={resource_type}
|
||||
resourceName={path}
|
||||
resourceDescription={description}
|
||||
{resourceSchema}
|
||||
/>
|
||||
{#if resourceToEdit?.resource_type === 'nats' || resourceToEdit?.resource_type === 'kafka'}
|
||||
<TestTriggerConnection kind={resourceToEdit?.resource_type} args={{ connection: args }} />
|
||||
{:else}
|
||||
<TestConnection
|
||||
resourceType={resourceToEdit?.resource_type}
|
||||
{args}
|
||||
workspaceOverride={workspace}
|
||||
{#if can_write && (showReference || canReferenceWholeValue(resourceTypeInfo))}
|
||||
<DropdownV2
|
||||
placement="bottom-end"
|
||||
items={() =>
|
||||
resourceValueMenuItems(showReference ? reference : undefined, {
|
||||
pickVariable: () => valueReference?.pickVariable(),
|
||||
editFields: () => setWholeValue({})
|
||||
})}
|
||||
/>
|
||||
{/if}
|
||||
{#if aiProvider}
|
||||
<TestAiKey
|
||||
{aiProvider}
|
||||
workspace={ws}
|
||||
resourceValue={args}
|
||||
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
|
||||
/>
|
||||
{/if}
|
||||
{#if resource_type === 'git_repository' && ws && (actingUser?.is_admin || actingUser?.is_super_admin)}
|
||||
<GitHubAppIntegration
|
||||
resourceType={resource_type}
|
||||
{args}
|
||||
{description}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
// The raw editor is also what a workspace missing the resource type
|
||||
// gets, and it holds its own copy of the value: without this the
|
||||
// picker fills in a URL nothing on screen ever shows.
|
||||
if (viewJsonSchema || !resourceSchema) {
|
||||
{#if !showReference}
|
||||
<Toggle
|
||||
bind:checked={viewJsonSchema}
|
||||
on:change={(e) => {
|
||||
if (e.detail) {
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
} else if (resourceTypeInfo?.format_extension && !resourceTypeInfo?.is_fileset) {
|
||||
textFileContent = args?.content ?? ''
|
||||
}
|
||||
}}
|
||||
onDescriptionUpdate={(newDescription) => (description = newDescription)}
|
||||
/>
|
||||
<GitLabIntegration
|
||||
resourceType={resource_type}
|
||||
{args}
|
||||
workspace={ws}
|
||||
{onCredentialStored}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
// The raw editor is also what a workspace missing the resource type
|
||||
// gets, and it holds its own copy of the value: without this the
|
||||
// picker fills in a URL nothing on screen ever shows.
|
||||
if (viewJsonSchema || !resourceSchema) {
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
}
|
||||
options={{
|
||||
right: 'As JSON'
|
||||
}}
|
||||
/>
|
||||
<ResourceGen
|
||||
bind:args
|
||||
resourceType={resource_type}
|
||||
resourceName={path}
|
||||
resourceDescription={description}
|
||||
{resourceSchema}
|
||||
/>
|
||||
{#if resourceToEdit?.resource_type === 'nats' || resourceToEdit?.resource_type === 'kafka'}
|
||||
<TestTriggerConnection kind={resourceToEdit?.resource_type} args={{ connection: args }} />
|
||||
{:else}
|
||||
<TestConnection
|
||||
resourceType={resourceToEdit?.resource_type}
|
||||
{args}
|
||||
workspaceOverride={workspace}
|
||||
/>
|
||||
{/if}
|
||||
{#if aiProvider}
|
||||
<TestAiKey
|
||||
{aiProvider}
|
||||
workspace={ws}
|
||||
resourceValue={args}
|
||||
model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model}
|
||||
/>
|
||||
{/if}
|
||||
{#if resource_type === 'git_repository' && ws && (actingUser?.is_admin || actingUser?.is_super_admin)}
|
||||
<GitHubAppIntegration
|
||||
resourceType={resource_type}
|
||||
{args}
|
||||
{description}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
// The raw editor is also what a workspace missing the resource type
|
||||
// gets, and it holds its own copy of the value: without this the
|
||||
// picker fills in a URL nothing on screen ever shows.
|
||||
if (viewJsonSchema || !resourceSchema) {
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
}
|
||||
}}
|
||||
onDescriptionUpdate={(newDescription) => (description = newDescription)}
|
||||
/>
|
||||
<GitLabIntegration
|
||||
resourceType={resource_type}
|
||||
{args}
|
||||
workspace={ws}
|
||||
{onCredentialStored}
|
||||
onArgsUpdate={(newArgs) => {
|
||||
args = newArgs
|
||||
// The raw editor is also what a workspace missing the resource type
|
||||
// gets, and it holds its own copy of the value: without this the
|
||||
// picker fills in a URL nothing on screen ever shows.
|
||||
if (viewJsonSchema || !resourceSchema) {
|
||||
rawCode = JSON.stringify(args, null, 2)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{#if loadingSchema}
|
||||
<ResourceValueReference
|
||||
bind:this={valueReference}
|
||||
reference={showReference ? reference : undefined}
|
||||
disabled={!can_write}
|
||||
workspace={ws}
|
||||
onPick={setWholeValue}
|
||||
/>
|
||||
{#if showReference}{:else if loadingSchema}
|
||||
<Skeleton layout={[[4]]} />
|
||||
{:else if !viewJsonSchema && resourceTypeInfo?.is_fileset}
|
||||
<div class="mt-1 flex items-center gap-2">
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<script module lang="ts">
|
||||
import type { Item } from '$lib/utils'
|
||||
import type { ResourceType } from '$lib/gen'
|
||||
|
||||
/** The whole value of a resource can be a single `$jsonvar:`/`$var:`/`$res:` string, resolved
|
||||
* at runtime. No form may render over it: a schema form replaces it with empty fields. */
|
||||
export function resourceValueReference(value: unknown): string | undefined {
|
||||
return typeof value === 'string' &&
|
||||
['$jsonvar:', '$var:', '$res:'].some((p) => value.startsWith(p))
|
||||
? value
|
||||
: undefined
|
||||
}
|
||||
|
||||
/** A file-type resource is `{ content }` and a fileset a map of files: neither is a JSON
|
||||
* document a variable could hold whole. */
|
||||
export function canReferenceWholeValue(resourceTypeInfo: ResourceType | undefined): boolean {
|
||||
return !resourceTypeInfo?.format_extension && !resourceTypeInfo?.is_fileset
|
||||
}
|
||||
|
||||
export function resourceValueMenuItems(
|
||||
reference: string | undefined,
|
||||
actions: { pickVariable: () => void; editFields: () => void }
|
||||
): Item[] {
|
||||
return reference
|
||||
? [{ displayName: 'Edit fields instead', action: actions.editFields }]
|
||||
: [
|
||||
{
|
||||
displayName: 'Whole value from a variable',
|
||||
description: "The variable's content is parsed as JSON",
|
||||
action: actions.pickVariable
|
||||
}
|
||||
]
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { DollarSign } from 'lucide-svelte'
|
||||
import { Button } from './common'
|
||||
import type VariableEditor from './VariableEditor.svelte'
|
||||
import VariablePicker from './VariablePicker.svelte'
|
||||
|
||||
interface Props {
|
||||
/** The reference to show, `undefined` when the value is not one: the picker still mounts. */
|
||||
reference: string | undefined
|
||||
disabled?: boolean
|
||||
workspace: string | undefined
|
||||
onPick: (reference: string) => void
|
||||
}
|
||||
|
||||
let { reference, disabled = false, workspace, onPick }: Props = $props()
|
||||
|
||||
let picker: VariablePicker | undefined = $state(undefined)
|
||||
let variableEditor: VariableEditor | undefined = $state(undefined)
|
||||
|
||||
let referencedResource = $derived(reference?.startsWith('$res:') ? reference.slice(5) : undefined)
|
||||
let referencedVariable = $derived(
|
||||
reference && !referencedResource ? reference.slice(reference.indexOf(':') + 1) : undefined
|
||||
)
|
||||
|
||||
export function pickVariable() {
|
||||
picker?.openDrawer()
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if reference}
|
||||
<div class="flex flex-col gap-1 w-full">
|
||||
<div class="flex items-center gap-2 h-8 pl-2 pr-0.5 rounded-md bg-surface-secondary">
|
||||
<span class="grow truncate text-xs font-mono text-emphasis">{reference}</span>
|
||||
{#if !disabled}
|
||||
<Button
|
||||
iconOnly
|
||||
startIcon={{ icon: DollarSign }}
|
||||
unifiedSize="sm"
|
||||
onClick={pickVariable}
|
||||
variant="default"
|
||||
btnClasses="bg-surface-tertiary"
|
||||
title="Pick another variable"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-2xs text-hint">
|
||||
{#if referencedResource}
|
||||
Linked to resource <a
|
||||
target="_blank"
|
||||
href="/resources{workspace
|
||||
? `?workspace=${workspace}`
|
||||
: ''}#/resource/{referencedResource}"
|
||||
class="text-accent underline">{referencedResource}</a
|
||||
>
|
||||
{:else}
|
||||
Linked to variable <button
|
||||
class="text-accent underline font-normal"
|
||||
onclick={() => variableEditor?.editVariable?.(referencedVariable ?? '')}
|
||||
>{referencedVariable}</button
|
||||
>.
|
||||
{reference.startsWith('$jsonvar:')
|
||||
? 'Its content is parsed as JSON and used as the whole value.'
|
||||
: 'Its content is used as the whole value.'}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<VariablePicker
|
||||
bind:this={picker}
|
||||
bind:variableEditor
|
||||
{workspace}
|
||||
tooltip="The variable must hold the whole value as JSON. It is parsed when the resource is used."
|
||||
onPick={(path) => onPick('$jsonvar:' + path)}
|
||||
/>
|
||||
@@ -3,19 +3,17 @@
|
||||
|
||||
const bubble = createBubbler()
|
||||
import type { Schema } from '$lib/common'
|
||||
import { VariableService } from '$lib/gen'
|
||||
import { allTrue, type DynamicInput } from '$lib/utils'
|
||||
import { computeShow, quickjsSettled } from '$lib/utils/quickjsEval.svelte'
|
||||
import { Button } from './common'
|
||||
import ItemPicker from './ItemPicker.svelte'
|
||||
import VariableEditor from './VariableEditor.svelte'
|
||||
import type ItemPicker from './ItemPicker.svelte'
|
||||
import type VariableEditor from './VariableEditor.svelte'
|
||||
import VariablePicker from './VariablePicker.svelte'
|
||||
import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte'
|
||||
import { getResourceTypes } from './resourceTypesStore'
|
||||
import { Plus } from 'lucide-svelte'
|
||||
import ArgInput from './ArgInput.svelte'
|
||||
import { createEventDispatcher, untrack } from 'svelte'
|
||||
import { watch } from 'runed'
|
||||
import { deepEqual } from 'fast-equals'
|
||||
import {
|
||||
dragHandleZone,
|
||||
@@ -159,11 +157,6 @@
|
||||
let itemPicker: ItemPicker | undefined = $state(undefined)
|
||||
let variableEditor: VariableEditor | undefined = $state(undefined)
|
||||
|
||||
watch(
|
||||
() => ws,
|
||||
() => itemPicker?.reloadItems()
|
||||
)
|
||||
|
||||
let resourceTypes: string[] | undefined = $state(undefined)
|
||||
|
||||
async function loadResourceTypes() {
|
||||
@@ -506,36 +499,14 @@
|
||||
{/if}
|
||||
</div>
|
||||
{#if !noVariablePicker}
|
||||
<ItemPicker
|
||||
bind:this={itemPicker}
|
||||
pickCallback={(path, _) => {
|
||||
<VariablePicker
|
||||
bind:itemPicker
|
||||
bind:variableEditor
|
||||
workspace={ws}
|
||||
onPick={(path) => {
|
||||
if (pickForField && args) {
|
||||
args[pickForField] = '$var:' + path
|
||||
}
|
||||
}}
|
||||
itemName="Variable"
|
||||
tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow."
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets"
|
||||
extraField="path"
|
||||
loadItems={async () =>
|
||||
(await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({
|
||||
name: x.path,
|
||||
...x
|
||||
}))}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<div>
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="md"
|
||||
startIcon={{ icon: Plus }}
|
||||
on:click={() => variableEditor?.initNew?.()}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
|
||||
<VariableEditor bind:this={variableEditor} workspace={ws} />
|
||||
/>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<script lang="ts">
|
||||
import { VariableService } from '$lib/gen'
|
||||
import { watch } from 'runed'
|
||||
import { Plus } from 'lucide-svelte'
|
||||
import { Button } from './common'
|
||||
import ItemPicker from './ItemPicker.svelte'
|
||||
import VariableEditor from './VariableEditor.svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
|
||||
interface Props {
|
||||
onPick: (path: string, name: string) => void
|
||||
workspace?: string | undefined
|
||||
tooltip?: string
|
||||
/** Adds an Edit/View button to each row. */
|
||||
editable?: boolean
|
||||
/** Handed back for forms whose fields open the picker or a linked variable themselves. */
|
||||
itemPicker?: ItemPicker | undefined
|
||||
variableEditor?: VariableEditor | undefined
|
||||
}
|
||||
|
||||
let {
|
||||
onPick,
|
||||
workspace = undefined,
|
||||
tooltip = 'Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow.',
|
||||
editable = false,
|
||||
itemPicker = $bindable(),
|
||||
variableEditor = $bindable()
|
||||
}: Props = $props()
|
||||
|
||||
let ws = $derived(workspace ?? $operatingWorkspace)
|
||||
|
||||
watch(
|
||||
() => ws,
|
||||
() => itemPicker?.reloadItems()
|
||||
)
|
||||
|
||||
export function openDrawer() {
|
||||
itemPicker?.openDrawer()
|
||||
}
|
||||
</script>
|
||||
|
||||
<ItemPicker
|
||||
bind:this={itemPicker}
|
||||
pickCallback={onPick}
|
||||
itemName="Variable"
|
||||
{tooltip}
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets"
|
||||
extraField="path"
|
||||
loadItems={async () =>
|
||||
(await VariableService.listVariable({ workspace: ws ?? '' })).map((x) => ({
|
||||
name: x.path,
|
||||
...x
|
||||
}))}
|
||||
buttons={editable ? { 'Edit/View': (path) => variableEditor?.editVariable(path) } : {}}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="md"
|
||||
startIcon={{ icon: Plus }}
|
||||
onClick={() => variableEditor?.initNew()}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
|
||||
<!-- Creating one from the picker must refresh the list it is picking from. -->
|
||||
<VariableEditor
|
||||
bind:this={variableEditor}
|
||||
workspace={ws}
|
||||
onSaved={() => itemPicker?.reloadItems()}
|
||||
/>
|
||||
@@ -39,9 +39,7 @@
|
||||
import ComponentList from './componentsPanel/ComponentList.svelte'
|
||||
import ContextPanel from './contextPanel/ContextPanel.svelte'
|
||||
|
||||
import ItemPicker from '$lib/components/ItemPicker.svelte'
|
||||
import VariableEditor from '$lib/components/VariableEditor.svelte'
|
||||
import { VariableService } from '$lib/gen'
|
||||
import VariablePicker from '$lib/components/VariablePicker.svelte'
|
||||
import { initHistory } from '$lib/history.svelte'
|
||||
import { Component, Minus, Paintbrush, Plus, Smartphone, Scan, Hand, Grab } from 'lucide-svelte'
|
||||
import { animateTo, findGridItemParentGrid } from './appUtils'
|
||||
@@ -346,9 +344,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
let itemPicker: ItemPicker | undefined = $state(undefined)
|
||||
|
||||
let variableEditor: VariableEditor | undefined = $state(undefined)
|
||||
let variablePicker: VariablePicker | undefined = $state(undefined)
|
||||
|
||||
setContext<ContextPanelContext>('ContextPanel', {
|
||||
search: writable<string>(''),
|
||||
@@ -825,7 +821,7 @@
|
||||
})
|
||||
$effect(() => {
|
||||
if ($pickVariableCallback) {
|
||||
itemPicker?.openDrawer()
|
||||
variablePicker?.openDrawer()
|
||||
}
|
||||
})
|
||||
// Animation logic for cssInput
|
||||
@@ -1305,38 +1301,7 @@
|
||||
App editor not available to operators
|
||||
{/if}
|
||||
|
||||
<ItemPicker
|
||||
bind:this={itemPicker}
|
||||
pickCallback={(path, _) => {
|
||||
$pickVariableCallback?.(path)
|
||||
}}
|
||||
itemName="Variable"
|
||||
extraField="path"
|
||||
loadItems={async () =>
|
||||
(await VariableService.listVariable({ workspace: $workspaceStore ?? '' })).map((x) => ({
|
||||
name: x.path,
|
||||
...x
|
||||
}))}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<div
|
||||
class="flex flex-row-reverse w-full bg-surface border-t border-gray-200 rounded-bl-lg rounded-br-lg"
|
||||
>
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
startIcon={{ icon: Plus }}
|
||||
on:click={() => {
|
||||
variableEditor?.initNew?.()
|
||||
}}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
|
||||
<VariableEditor bind:this={variableEditor} />
|
||||
<VariablePicker bind:this={variablePicker} onPick={(path) => $pickVariableCallback?.(path)} />
|
||||
|
||||
<style global>
|
||||
#o1 > .splitpanes__pane {
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
path,
|
||||
onEdit,
|
||||
onLoadState,
|
||||
syncHashToUrl = true,
|
||||
ownsPageUrl = true,
|
||||
ownsPageHeader = false
|
||||
}: {
|
||||
workspace: string
|
||||
@@ -50,8 +50,8 @@
|
||||
/** How the load ended, for a host that renders its own state around this viewer.
|
||||
* A 403 is deliberately neither: the app exists, this member just cannot open it. */
|
||||
onLoadState?: (state: 'loaded' | 'not_found') => void
|
||||
/** Whether a raw app's route lives in the page URL's hash; see `RawAppPreview`. */
|
||||
syncHashToUrl?: boolean
|
||||
/** Whether a raw app owns the page's address and title; see `RawAppPreview`. */
|
||||
ownsPageUrl?: boolean
|
||||
} = $props()
|
||||
|
||||
// The app, its permission check and everything this viewer renders belong to `workspace`,
|
||||
@@ -291,7 +291,7 @@
|
||||
jwtError={false}
|
||||
inWorkspace
|
||||
{hideRefreshBar}
|
||||
{syncHashToUrl}
|
||||
{ownsPageUrl}
|
||||
onLoginSuccess={() => loadApp()}
|
||||
></PublicApp>
|
||||
{/snippet}
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
license = undefined,
|
||||
inWorkspace = false,
|
||||
hideRefreshBar = false,
|
||||
syncHashToUrl = true
|
||||
ownsPageUrl = true
|
||||
}: {
|
||||
notExists: boolean
|
||||
noPermission: boolean
|
||||
@@ -48,8 +48,8 @@
|
||||
*/
|
||||
inWorkspace?: boolean
|
||||
hideRefreshBar?: boolean
|
||||
/** Whether a raw app's route lives in the page URL's hash; see `RawAppPreview`. */
|
||||
syncHashToUrl?: boolean
|
||||
/** Whether a raw app owns the page's address and title; see `RawAppPreview`. */
|
||||
ownsPageUrl?: boolean
|
||||
} = $props()
|
||||
|
||||
// Use workspace from props or from app.workspace_id (for custom path responses)
|
||||
@@ -114,7 +114,7 @@
|
||||
secret={app.bundle_secret}
|
||||
path={app.path}
|
||||
runnables={(app.value?.runnables ?? {}) as Record<string, Runnable>}
|
||||
{syncHashToUrl}
|
||||
{ownsPageUrl}
|
||||
/>
|
||||
</div>
|
||||
{:else if app.raw_app && !effectiveWorkspace}
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div class={twMerge(!hideIcon && 'ml-1', 'w-full')}>
|
||||
<div class={twMerge(!hideIcon && 'ml-1', 'w-full min-w-0')}>
|
||||
{#if hasTitleRow}
|
||||
<div class={twMerge('w-full flex flex-row items-center justify-between')}>
|
||||
<span
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
XIcon
|
||||
} from 'lucide-svelte'
|
||||
import Button from '$lib/components/common/button/Button.svelte'
|
||||
import Kbd from '$lib/components/common/kbd/Kbd.svelte'
|
||||
import { fade } from 'svelte/transition'
|
||||
import Popover from '$lib/components/meltComponents/Popover.svelte'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
@@ -638,6 +639,33 @@
|
||||
if (!isComposerOverlay(e.target) && !asksForComposer(e.target)) closeComposer()
|
||||
}
|
||||
|
||||
// The composer clears on a second Escape: the first only shows the hint, so a single
|
||||
// stray press cannot throw a draft away. Any other key, a click in the composer or
|
||||
// leaving it disarms it.
|
||||
const CLEAR_ARM_MS = 2000
|
||||
let clearArmed = $state(false)
|
||||
let clearArmTimer: ReturnType<typeof setTimeout> | undefined
|
||||
function disarmClear() {
|
||||
clearTimeout(clearArmTimer)
|
||||
clearArmed = false
|
||||
}
|
||||
function onComposerEscape(repeat: boolean) {
|
||||
if (!aiChatInput?.hasClearableContent()) return false
|
||||
// A held key is one press: its repeats must not count as the second.
|
||||
if (repeat) return true
|
||||
if (clearArmed) {
|
||||
// Still armed if refused (an attachment still being read): the next press retries.
|
||||
if (aiChatInput.clearDraft()) disarmClear()
|
||||
} else {
|
||||
clearArmed = true
|
||||
clearArmTimer = setTimeout(disarmClear, CLEAR_ARM_MS)
|
||||
}
|
||||
return true
|
||||
}
|
||||
$effect(() => () => clearTimeout(clearArmTimer))
|
||||
// Off once the draft is gone some other way, such as a send.
|
||||
const clearHintShown = $derived(clearArmed && !!aiChatInput?.hasClearableContent())
|
||||
|
||||
// While the box plays its accent outline (app.css, `data-composer-flash`).
|
||||
let flashing = $state(false)
|
||||
|
||||
@@ -756,8 +784,10 @@
|
||||
variant="accent"
|
||||
startIcon={{ icon: KeyRound }}
|
||||
href="/workspace_settings?tab=ai"
|
||||
wrapperClasses="min-w-0 max-w-full"
|
||||
btnClasses="min-w-0"
|
||||
>
|
||||
Add your own API key
|
||||
<span class="truncate">Add your own API key</span>
|
||||
</Button>
|
||||
</div>
|
||||
</Alert>
|
||||
@@ -766,7 +796,7 @@
|
||||
|
||||
{#snippet freeTierUsageBanner()}
|
||||
<div
|
||||
class="my-1 flex items-center justify-between gap-2 rounded-md border bg-surface-secondary px-2 py-1"
|
||||
class="my-1 flex flex-wrap items-center justify-between gap-x-2 gap-y-1 rounded-md border bg-surface-secondary px-2 py-1"
|
||||
>
|
||||
<span class="text-xs text-secondary tabular-nums">
|
||||
{freeTierUsedPct}% of your free Windmill AI used
|
||||
@@ -776,8 +806,10 @@
|
||||
variant="default"
|
||||
startIcon={{ icon: KeyRound }}
|
||||
href="/workspace_settings?tab=ai"
|
||||
wrapperClasses="min-w-0 shrink"
|
||||
btnClasses="min-w-0"
|
||||
>
|
||||
Configure your API key
|
||||
<span class="truncate">Configure your API key</span>
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
@@ -1051,9 +1083,29 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
onfocusin={(e) => {
|
||||
if (starterLayout && e.target instanceof HTMLTextAreaElement) composerOpened = true
|
||||
}}
|
||||
oninput={() => disarmClear()}
|
||||
onpointerdown={() => disarmClear()}
|
||||
onfocusout={(e) => {
|
||||
if (!composerEl?.contains(e.relatedTarget as Node | null)) disarmClear()
|
||||
}}
|
||||
onkeydown={(e) => {
|
||||
// A prevented Escape closed something inside first, such as the @-mention picker.
|
||||
if (e.key !== 'Escape' || e.defaultPrevented) return
|
||||
// A prevented Escape was handled inside, such as a running turn's stop. An IME
|
||||
// cancel is the input method's.
|
||||
if (e.key !== 'Escape') {
|
||||
disarmClear()
|
||||
return
|
||||
}
|
||||
if (e.defaultPrevented || e.isComposing) return
|
||||
// The `@` and `/` pickers close on this press reaching `document` unprevented.
|
||||
if (aiChatInput?.hasOpenPicker()) return
|
||||
// The field's own presses only: a toolbar button keeps focus while the dialog it
|
||||
// opened (assistant settings) closes on the same Escape.
|
||||
if (e.target instanceof HTMLTextAreaElement && onComposerEscape(e.repeat)) {
|
||||
// Kept from the panel or drawer around the chat, which would close on it.
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
return
|
||||
}
|
||||
if (!starterLayout || !composerOpened) return
|
||||
closeComposer()
|
||||
if (aiChatInput?.isDraftEmpty() ?? true) (document.activeElement as HTMLElement)?.blur()
|
||||
@@ -1128,6 +1180,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
collapsed={composerCollapsed}
|
||||
chatIcon={starterLayout}
|
||||
{onSent}
|
||||
clearHint={!starterLayout && clearHintShown}
|
||||
>
|
||||
{#snippet collapsedControls()}
|
||||
{#if chatHost.mode === AIMode.GLOBAL}
|
||||
@@ -1481,7 +1534,12 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
<!-- Opens and closes with the box, so the page under it slides rather than jumps. -->
|
||||
<div use:smoothHeight={{ enabled: starterLayout, key: composerCollapsed }}>
|
||||
<div>
|
||||
{#if starterLayout && starter && !disabled && !composerCollapsed && starter.suggestions.length > 0}
|
||||
<!-- On Home the hint stands in for the suggestions, at their height. -->
|
||||
{#if starterLayout && clearHintShown}
|
||||
<div class="pt-2 h-9 flex items-center gap-1 text-xs text-hint" role="status">
|
||||
Press <Kbd small>Esc</Kbd> again to clear
|
||||
</div>
|
||||
{:else if starterLayout && starter && !disabled && !composerCollapsed && starter.suggestions.length > 0}
|
||||
<div class="pt-2">
|
||||
<ComposerSuggestions
|
||||
suggestions={starter.suggestions}
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
import Portal from '$lib/components/Portal.svelte'
|
||||
import { zIndexes } from '$lib/zIndexes'
|
||||
import { ArrowUp, Loader2, Square, X } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import { Button, Kbd } from '$lib/components/common'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { type PasteAttachment } from './pasteTokens'
|
||||
import { chatDraft, expanded } from './chatDraft'
|
||||
@@ -89,6 +89,8 @@
|
||||
onSendRequest?: (instructions: string) => void
|
||||
showContext?: boolean
|
||||
bottomRightSnippet?: Snippet
|
||||
/** Shows "Press Esc again to clear" next to the send button. */
|
||||
clearHint?: boolean
|
||||
onKeyDown?: (e: KeyboardEvent) => void
|
||||
// When provided, overrides `chatHost.loading` for the send/stop
|
||||
// button — useful for callers driving their own request lifecycle
|
||||
@@ -144,6 +146,7 @@
|
||||
onSendRequest = undefined,
|
||||
showContext = true,
|
||||
bottomRightSnippet,
|
||||
clearHint = false,
|
||||
onKeyDown = undefined,
|
||||
loading,
|
||||
onCancel,
|
||||
@@ -683,6 +686,42 @@
|
||||
return draft.isEmpty
|
||||
}
|
||||
|
||||
// Only GLOBAL's context is chips the user added; the editors' modes seed theirs with the
|
||||
// code being edited, which an Escape must neither count nor drop.
|
||||
const userContext = $derived(chatHost.mode === AIMode.GLOBAL ? selectedContext : [])
|
||||
|
||||
const attachmentsInFlight = $derived(
|
||||
pendingImages > 0 || pendingFiles > 0 || pendingBlobs > 0 || ingestionHolds > 0
|
||||
)
|
||||
|
||||
/** Whether there is anything for `clearDraft` to drop: the draft, a context chip, or an
|
||||
* attachment still being read. */
|
||||
export function hasClearableContent(): boolean {
|
||||
return !draft.isEmpty || userContext.length > 0 || attachmentsInFlight
|
||||
}
|
||||
|
||||
/** Whether an `@` or `/` picker is open: an Escape then belongs to it. */
|
||||
export function hasOpenPicker(): boolean {
|
||||
return showAppContextTooltip || (contextTextareaComponent?.hasOpenPicker() ?? false)
|
||||
}
|
||||
|
||||
/** Drops everything the user put in the composer: text, attachments and context chips.
|
||||
* Refused while an attachment is still being read, as a send is: it would land after the
|
||||
* clear. Returns whether it cleared. */
|
||||
export function clearDraft(): boolean {
|
||||
if (attachmentsInFlight) return false
|
||||
if (chatHost.mode === AIMode.GLOBAL) {
|
||||
// GLOBAL drops every chip below, so the per-`@`-mention removals are skipped. The
|
||||
// editor modes keep them: they are what drops a mention's chip with its text.
|
||||
contextTextareaComponent?.clearForSend()
|
||||
draft.clear()
|
||||
selectedContext = []
|
||||
} else {
|
||||
draft.clear()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export function focusInput(selection?: ComposerSelection) {
|
||||
if (isContextEnabledMode) {
|
||||
contextTextareaComponent?.focus(selection)
|
||||
@@ -1305,25 +1344,37 @@
|
||||
selectedContext.length === 0))}
|
||||
<!-- Accent only once there is something to send, so the button lights up as the draft
|
||||
becomes sendable; idle and Stop stay quiet. -->
|
||||
<Button
|
||||
variant={!isLoading && !sendDisabled ? 'accent' : 'subtle'}
|
||||
unifiedSize={size}
|
||||
iconOnly
|
||||
title={isLoading
|
||||
? 'Stop'
|
||||
: needsTextForAttachment
|
||||
? 'Write a message to send with the attachment'
|
||||
: 'Send'}
|
||||
startIcon={{ icon: isLoading ? Square : ArrowUp }}
|
||||
disabled={!isLoading && sendDisabled}
|
||||
on:click={() => {
|
||||
if (isLoading) {
|
||||
onCancel ? onCancel() : chatHost.cancel()
|
||||
} else if (!sendDisabled) {
|
||||
submitRequest()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div class="relative flex shrink-0">
|
||||
<!-- Floats over the field so the box keeps its size; the field's colour hides the text
|
||||
under it. -->
|
||||
{#if clearHint}
|
||||
<div
|
||||
class="absolute right-full top-1/2 -translate-y-1/2 mr-1.5 flex items-center gap-1 whitespace-nowrap rounded bg-surface-input pl-2 text-xs text-hint pointer-events-none"
|
||||
role="status"
|
||||
>
|
||||
Press <Kbd small>Esc</Kbd> again to clear
|
||||
</div>
|
||||
{/if}
|
||||
<Button
|
||||
variant={!isLoading && !sendDisabled ? 'accent' : 'subtle'}
|
||||
unifiedSize={size}
|
||||
iconOnly
|
||||
title={isLoading
|
||||
? 'Stop'
|
||||
: needsTextForAttachment
|
||||
? 'Write a message to send with the attachment'
|
||||
: 'Send'}
|
||||
startIcon={{ icon: isLoading ? Square : ArrowUp }}
|
||||
disabled={!isLoading && sendDisabled}
|
||||
on:click={() => {
|
||||
if (isLoading) {
|
||||
onCancel ? onCancel() : chatHost.cancel()
|
||||
} else if (!sendDisabled) {
|
||||
submitRequest()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<!-- One wrapping row for every badge-shaped chip: selected context (or, when the
|
||||
|
||||
@@ -88,7 +88,13 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<DropdownV2 {items} placement="bottom-start" fixedHeight={false} customWidth={work ? 260 : 240}>
|
||||
<DropdownV2
|
||||
{items}
|
||||
placement="bottom-start"
|
||||
fixedHeight={false}
|
||||
customWidth={work ? 260 : 240}
|
||||
class="min-w-0 max-w-full"
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
<Button
|
||||
nonCaptureEvent
|
||||
@@ -97,14 +103,17 @@
|
||||
title={workOption
|
||||
? (work?.lock?.reason ?? `${workOption.description} ${option.tooltip(availability)}`)
|
||||
: option.tooltip(availability)}
|
||||
btnClasses={workOption?.triggerClass ?? ''}
|
||||
wrapperClasses="min-w-0 shrink"
|
||||
btnClasses="min-w-0 {workOption?.triggerClass ?? ''}"
|
||||
startIcon={{
|
||||
icon: (workOption ?? option).icon,
|
||||
classes: (workOption ?? option).iconColor
|
||||
}}
|
||||
endIcon={{ icon: ChevronDown }}
|
||||
>
|
||||
{workOption ? `${workOption.label} · ${postureLabel}` : postureLabel}
|
||||
<span class="truncate"
|
||||
>{workOption ? `${workOption.label} · ${postureLabel}` : postureLabel}</span
|
||||
>
|
||||
</Button>
|
||||
{/snippet}
|
||||
</DropdownV2>
|
||||
|
||||
@@ -787,6 +787,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the `@` or `/` picker is open. It closes itself on an Escape reaching
|
||||
* `document` unprevented. */
|
||||
export function hasOpenPicker(): boolean {
|
||||
return showContextTooltip || showCommandTooltip
|
||||
}
|
||||
|
||||
// Wipe after dispatching a send: pre-zero `prevMentionedTitles` so the effect
|
||||
// above sees no diff when `value` clears, leaving `selectedContext` for the
|
||||
// send that is already carrying it to settle (see the caller). A manual
|
||||
|
||||
@@ -11,9 +11,10 @@
|
||||
/** The raw text rather than the rendered document. */
|
||||
source: boolean
|
||||
/**
|
||||
* The fenced-code renderer. Defaults to the shared chain's, which keeps mermaid off:
|
||||
* a shared artifact is another member's text. The session viewer passes the chat's,
|
||||
* which draws diagrams and needs the chat context the shared page does not have.
|
||||
* The fenced-code renderer. Defaults to the shared chain's, which keeps mermaid off for
|
||||
* text that can reach readers outside the workspace (a public shared session). The
|
||||
* members-only shared artifact page passes MermaidCodeBlock; the session viewer passes
|
||||
* the chat's, which also needs the chat context the shared pages do not have.
|
||||
*/
|
||||
pre?: Component<any>
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { Check, Copy, Download } from 'lucide-svelte'
|
||||
import { Check, Copy, Download, FileDown } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import { copyToClipboard, download } from '$lib/utils'
|
||||
import { artifactFilename, artifactMimeType, type ArtifactKind } from './artifactsDB'
|
||||
import { printArtifact } from './printArtifact'
|
||||
|
||||
interface Props {
|
||||
name: string
|
||||
@@ -31,11 +32,23 @@
|
||||
title="Copy raw markdown"
|
||||
dropdownItems={[
|
||||
{
|
||||
label: 'Download as .md',
|
||||
label: `Download as .${kind}`,
|
||||
icon: Download,
|
||||
onClick: () => download(artifactFilename({ name, kind }), content, artifactMimeType(kind)),
|
||||
disabled
|
||||
}
|
||||
},
|
||||
// Markdown only: an html artifact is agent-written markup, and printing it would run its
|
||||
// scripts in this origin.
|
||||
...(kind === 'md'
|
||||
? [
|
||||
{
|
||||
label: 'Download as PDF',
|
||||
icon: FileDown,
|
||||
onClick: () => printArtifact(name, content),
|
||||
disabled
|
||||
}
|
||||
]
|
||||
: [])
|
||||
]}
|
||||
>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import Markdown from 'svelte-exmarkdown'
|
||||
import { markdownProse } from '$lib/components/markdownProse'
|
||||
import { markdownPlugins } from '$lib/components/markdownPlugins'
|
||||
import ArtifactPrintCodeBlock from './ArtifactPrintCodeBlock.svelte'
|
||||
|
||||
let { content }: { content: string } = $props()
|
||||
|
||||
const plugins = [...markdownPlugins, { renderer: { pre: ArtifactPrintCodeBlock } }]
|
||||
</script>
|
||||
|
||||
<div class={markdownProse.doc}>
|
||||
<Markdown md={content} {plugins} />
|
||||
</div>
|
||||
@@ -0,0 +1,7 @@
|
||||
<script lang="ts">
|
||||
import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte'
|
||||
</script>
|
||||
|
||||
<!-- The viewer's code block without the chat context its own renderer needs. Mermaid is on as
|
||||
in the viewer: only the session's own artifacts are exported. -->
|
||||
<MarkdownCodeBlock renderMermaid lightMermaid />
|
||||
@@ -0,0 +1,6 @@
|
||||
<script lang="ts">
|
||||
import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte'
|
||||
</script>
|
||||
|
||||
<!-- A `pre` renderer for ArtifactBody: the shared code block, with ```mermaid fences drawn. -->
|
||||
<MarkdownCodeBlock renderMermaid />
|
||||
@@ -0,0 +1,115 @@
|
||||
import { mount, unmount, tick } from 'svelte'
|
||||
import ArtifactPrintBody from './ArtifactPrintBody.svelte'
|
||||
|
||||
/**
|
||||
* Opens the browser's print dialog on a markdown artifact, where "Save as PDF" writes the file.
|
||||
* The browser's print engine keeps the text selectable and the links live, which a
|
||||
* canvas-rendered PDF would not.
|
||||
*
|
||||
* The document is rendered into a hidden iframe with the viewer's renderer rather than printing
|
||||
* this page: the app's own print would include the whole session layout. The iframe copies
|
||||
* this page's stylesheets, and its <html> carries no `dark` class, so the PDF always uses the
|
||||
* light theme.
|
||||
*/
|
||||
// Set while the iframe is being prepared, so a second click before the dialog opens does not
|
||||
// stack a second print behind the first.
|
||||
let preparing = false
|
||||
|
||||
export async function printArtifact(name: string, content: string): Promise<void> {
|
||||
if (preparing) return
|
||||
preparing = true
|
||||
try {
|
||||
await preparePrint(name, content)
|
||||
} finally {
|
||||
preparing = false
|
||||
}
|
||||
}
|
||||
|
||||
async function preparePrint(name: string, content: string): Promise<void> {
|
||||
const iframe = document.createElement('iframe')
|
||||
iframe.setAttribute('aria-hidden', 'true')
|
||||
iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0'
|
||||
document.body.appendChild(iframe)
|
||||
|
||||
const doc = iframe.contentDocument
|
||||
const win = iframe.contentWindow
|
||||
if (!doc || !win) {
|
||||
iframe.remove()
|
||||
return
|
||||
}
|
||||
// The print dialog proposes the title as the PDF's file name.
|
||||
doc.title = name
|
||||
for (const node of Array.from(document.querySelectorAll('link[rel="stylesheet"], style'))) {
|
||||
doc.head.appendChild(node.cloneNode(true))
|
||||
}
|
||||
const page = doc.createElement('style')
|
||||
// Without exact color adjust, browsers drop code-block and callout backgrounds. The break
|
||||
// rules keep a code block, diagram, callout or table row whole and a heading with what follows.
|
||||
// Code blocks scroll on screen; paper cannot, so they wrap and lose their height cap.
|
||||
page.textContent = `
|
||||
@page { margin: 16mm }
|
||||
html, body { background: white }
|
||||
body { margin: 0; print-color-adjust: exact; -webkit-print-color-adjust: exact }
|
||||
pre, svg, blockquote, tr, .markdown-alert { break-inside: avoid }
|
||||
h1, h2, h3, h4, h5, h6 { break-after: avoid }
|
||||
.not-prose, .not-prose * { overflow: visible !important; max-height: none !important }
|
||||
.not-prose pre, .not-prose code { white-space: pre-wrap !important; overflow-wrap: anywhere }
|
||||
`
|
||||
doc.head.appendChild(page)
|
||||
|
||||
// Printing before the stylesheets load gives an unstyled PDF; the cap keeps a link that
|
||||
// never settles from swallowing the click.
|
||||
const stylesheets = Array.from(
|
||||
doc.head.querySelectorAll('link[rel="stylesheet"]'),
|
||||
(link) =>
|
||||
new Promise<void>((resolve) => {
|
||||
link.addEventListener('load', () => resolve(), { once: true })
|
||||
link.addEventListener('error', () => resolve(), { once: true })
|
||||
})
|
||||
)
|
||||
await Promise.race([
|
||||
Promise.all(stylesheets),
|
||||
new Promise((resolve) => setTimeout(resolve, 3000))
|
||||
])
|
||||
|
||||
const component = mount(ArtifactPrintBody, { target: doc.body, props: { content } })
|
||||
await tick()
|
||||
await diagramsSettled(doc)
|
||||
await imagesSettled(doc)
|
||||
await doc.fonts?.ready
|
||||
|
||||
const cleanup = () => {
|
||||
unmount(component)
|
||||
iframe.remove()
|
||||
}
|
||||
// print() blocks until the dialog closes in Chromium and Firefox, but returns at once in
|
||||
// Safari, so the iframe is removed on afterprint rather than after the call.
|
||||
win.addEventListener('afterprint', cleanup, { once: true })
|
||||
win.focus()
|
||||
win.print()
|
||||
}
|
||||
|
||||
/** The print dialog snapshots the document as it is, so an image still loading is missing from
|
||||
* the PDF. A broken image settles through `error`; the cap covers one that never answers. */
|
||||
async function imagesSettled(doc: Document): Promise<void> {
|
||||
const pending = Array.from(doc.images)
|
||||
.filter((img) => !img.complete)
|
||||
.map(
|
||||
(img) =>
|
||||
new Promise<void>((resolve) => {
|
||||
img.addEventListener('load', () => resolve(), { once: true })
|
||||
img.addEventListener('error', () => resolve(), { once: true })
|
||||
})
|
||||
)
|
||||
await Promise.race([Promise.all(pending), new Promise((resolve) => setTimeout(resolve, 10_000))])
|
||||
}
|
||||
|
||||
/** Mermaid draws asynchronously; printing before it lands puts the diagram source in the PDF.
|
||||
* A diagram that fails to parse settles too (as its source), so this waits only on renders
|
||||
* still in flight; the cap covers one that never returns. */
|
||||
async function diagramsSettled(doc: Document): Promise<void> {
|
||||
const deadline = Date.now() + 10_000
|
||||
while (doc.querySelector('[data-mermaid-pending="true"]') && Date.now() < deadline) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { deepEqual } from 'fast-equals'
|
||||
import { promptSafe, type ArtifactVersionTarget } from '$lib/components/sessions/previewRouter'
|
||||
import { canDraftItem, roleCanDraft } from '$lib/editRights'
|
||||
import { renderPromptTemplate } from './promptTemplate'
|
||||
import { $ScriptLang } from '$lib/gen/schemas.gen'
|
||||
import type {
|
||||
CreateVariable,
|
||||
@@ -853,7 +854,11 @@ function waitSecondsToDetachMs(waitSeconds: number | undefined): number | undefi
|
||||
}
|
||||
|
||||
const testRunScriptSchema = z.object({
|
||||
path: z.string().describe('Workspace path of the script to test.'),
|
||||
path: z
|
||||
.string()
|
||||
.describe(
|
||||
'Workspace path of the script to test, or a hub/<version>/<app>/<name> path from search_hub_scripts to try a hub script.'
|
||||
),
|
||||
args: testRunArgsSchema,
|
||||
background: backgroundArgSchema,
|
||||
wait_seconds: waitSecondsArgSchema
|
||||
@@ -1331,7 +1336,7 @@ type FolderPromptContext = {
|
||||
// write anywhere, but `folders` only carries their explicitly-permissioned subset,
|
||||
// so for admins it is a non-exhaustive hint and list_workspace_items has the rest.
|
||||
// Capped so a folder-heavy workspace can't dominate the prompt.
|
||||
function buildFolderGuidance(
|
||||
export function buildFolderGuidance(
|
||||
username: string,
|
||||
ctx: FolderPromptContext | undefined,
|
||||
canCreateFolder: boolean,
|
||||
@@ -1385,50 +1390,118 @@ function buildFolderGuidance(
|
||||
const listJoin = (items: (string | false)[], type: 'conjunction' | 'disjunction' = 'conjunction') =>
|
||||
new Intl.ListFormat('en', { type }).format(items.filter((i): i is string => !!i))
|
||||
|
||||
// The prompt an external MCP client reads. A directory reviewer reads it as a description of
|
||||
// what the server does, so it names only the server's own tools and leaves how each one works
|
||||
// to its description and to get_instructions. OpenAI asks for the most important details in
|
||||
// the first 512 characters and some clients keep only the first 4096, so the drafts rule
|
||||
// opens and the rules come before the path conventions.
|
||||
function buildExternalPrompt(username: string, paths: string, skills: AiSkillListItem[]) {
|
||||
return `This server works in a Windmill workspace as the user "${username}".
|
||||
// Prompt templates: `{{#flag}}…{{/flag}}` keeps its body when the flag is set, `{{^flag}}…{{/flag}}`
|
||||
// when it is not, and `{{name}}` takes a variable (`promptTemplate.ts`). A block carries its own
|
||||
// leading newline, so a dropped one leaves no blank line behind.
|
||||
|
||||
Rules:
|
||||
- What you write is a per-user draft, saved server-side and visible only to this user. Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks.
|
||||
- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (\`url\`), an app draft's editor with its live preview (\`preview_url\`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.
|
||||
- Find items with list_workspace_items and read one with read_workspace_item before changing it. An agent is a resource of type \`ai_agent\`: test it with test_run_agent and run a deployed one with run_agent, never run_flow or run_script.
|
||||
- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language. Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and get_db_schema before writing SQL against a database resource.
|
||||
- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying.
|
||||
- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version "deployed" so the arguments match.
|
||||
- To undo your own work, discard its draft with discard_local_draft. delete_workspace_item removes an item that is deployed.
|
||||
// Shared by the chat and the external prompt. Flags: can_write_any_draft, can_create_folder.
|
||||
// Variables: username, folder_guidance (the folder lines, with their leading newline).
|
||||
const PATH_CONVENTIONS = `{{#can_write_any_draft}}
|
||||
|
||||
Path conventions:
|
||||
- A workspace path starts with one of two namespaces; its trailing <name> may itself contain "/", so a path has three or more segments:
|
||||
- \`u/{{username}}/<name>\` — your personal scope. Default for ad-hoc, exploratory, or scratch work.
|
||||
- \`f/<folder>/<name>\` — a shared folder scope; the <folder> must already exist (a bare \`f/<name>\` with no folder segment is INVALID and will fail).
|
||||
- If the user supplies a fully qualified \`f/<folder>/...\` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a \`u/{{username}}/...\` path unless a tool rejects it.
|
||||
- Default a bare name with no namespace prefix (e.g. "create a flow called myflow") to \`u/{{username}}/<name>\`. Never invent an \`f/<folder>/...\` path for a folder that does not exist{{#can_create_folder}}; create one with \`create_folder\` only when the user explicitly asks for a new folder{{/can_create_folder}}.{{folder_guidance}}{{/can_write_any_draft}}{{#can_create_folder}}{{^can_write_any_draft}}
|
||||
- You can create a shared folder with \`create_folder\` when the user explicitly asks for one. You cannot create anything inside it here, so do not offer to.{{/can_write_any_draft}}{{/can_create_folder}}`
|
||||
|
||||
// The prompt an external MCP client reads, rendered with the flags `externalPromptProfile` gives
|
||||
// an access profile: by the MCP server from `gen/prompt.json`, and by `buildGlobalSystemPrompt`. A directory reviewer reads it as a
|
||||
// description of what the server does, so it names only the server's own tools and leaves how
|
||||
// each one works to its description and to get_instructions. OpenAI asks for the most
|
||||
// important details in the first 512 characters and some clients keep only the first 4096, so
|
||||
// the drafts rule opens and the rules come before the path conventions.
|
||||
// Each gated block mirrors a tool the server refuses this access: what a read-only token or a
|
||||
// restricted role cannot do is stated up front rather than left to a failed call.
|
||||
export const EXTERNAL_PROMPT = `This server works in a Windmill workspace as the user "{{username}}".{{#read_only}}{{#runs_deployed}}
|
||||
|
||||
This connection can read the workspace's items, runs and data, and run scripts, flows and agents that are already deployed. It cannot create, edit, deploy or delete anything, nor test-run code that is not deployed: when the user asks for such a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{^runs_deployed}}
|
||||
|
||||
This connection is read-only: it can read the workspace's items, runs and data, but cannot run, create, edit, deploy or delete anything. When the user asks for a run or a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{/read_only}}{{^read_only}}{{^can_write_draft}}
|
||||
|
||||
This user's role does not let them create or edit {{refused_kinds}} here, so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had, and suggest asking a workspace admin, who can grant their role more.{{#builds_flows}} Their role does let them compose flows out of scripts and flows that are already deployed: write flows with write_flow and patch_flow_json, every step calling a deployed script or flow by path. The server refuses inline code anywhere in the flow, so when a flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.{{/builds_flows}}{{#builds_apps}} Their role does let them build raw apps whose backend runnables are path runnables to deployed scripts or flows; call get_instructions with subject "app" first. The server refuses inline and hub runnables, and runs an app they deploy sandboxed, as the user who deployed it.{{/builds_apps}}{{#has_draft_tools}} They can draft with {{draft_tools}}.{{/has_draft_tools}}{{/can_write_draft}}{{/read_only}}
|
||||
|
||||
Rules:{{#can_write_any_draft}}
|
||||
- What you write is a per-user draft, saved server-side and visible only to this user. {{#can_deploy}}Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks.{{/can_deploy}}{{^can_deploy}}{{#can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, and this workspace's deploy rules let this user deploy only the schedules and triggers their role manages: call deploy_workspace_item for those only when the user asks, and for anything else give them the draft's link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{^can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, which this workspace's deploy rules do not let this user do: when a draft is ready, give them its link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{/can_deploy}}{{/can_write_any_draft}}
|
||||
{{#can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (\`url\`), an app draft's editor with its live preview (\`preview_url\`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}{{^can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, an item's page. Whenever the user will want to see what you found{{#runs}} or ran{{/runs}}, or has to do a step in Windmill themselves: show it with show_run, show_runs or show_item when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}
|
||||
- Find items with list_workspace_items and read one with read_workspace_item{{#can_write_any_draft}} before changing it{{/can_write_any_draft}}. An agent is a resource of type \`ai_agent\`{{#runs}}: {{#can_run_flow_preview}}test it with test_run_agent and {{/can_run_flow_preview}}run a deployed one with run_agent, never run_flow or run_script.{{/runs}}{{^runs}}.{{/runs}}{{#can_write_draft}}
|
||||
- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and{{/can_draft_triggers}}{{^can_draft_triggers}} Call{{/can_draft_triggers}} get_db_schema before writing SQL against a database resource.{{/can_write_draft}}{{^can_write_draft}}{{#can_draft_resources}}
|
||||
- Call get_instructions before writing a resource.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields.{{/can_draft_triggers}}{{/can_draft_resources}}{{/can_write_draft}}{{#can_write_draft}}{{#can_run_preview}}
|
||||
- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying.{{/can_run_preview}}{{/can_write_draft}}{{^can_write_draft}}{{#builds_flows}}{{#can_run_flow_preview}}
|
||||
- After writing a flow, test it with test_run_flow before saying it works. It runs the draft, so nothing needs deploying.{{/can_run_flow_preview}}{{/builds_flows}}{{/can_write_draft}}{{#can_run_preview}}
|
||||
- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version "deployed" so the arguments match.{{/can_run_preview}}{{^can_run_preview}}{{#can_run_flow_preview}}
|
||||
- A request to run a flow or agent also goes to test_run_flow or test_run_agent, which run the draft. Use run_flow or run_agent only when the user asks for the deployed version, and run_script for any script: those run the DEPLOYED item as this user, so read it with read_workspace_item version "deployed" first so the arguments match.{{/can_run_flow_preview}}{{^can_run_flow_preview}}{{#runs}}
|
||||
- run_script, run_flow and run_agent are how you run anything here: they run the DEPLOYED item as this user. Read it with read_workspace_item version "deployed" first so the arguments match.{{/runs}}{{/can_run_flow_preview}}{{/can_run_preview}}{{#can_write_any_draft}}
|
||||
- To undo your own work, discard its draft with discard_local_draft.{{#can_deploy_any_kind}} delete_workspace_item removes an item that is deployed.{{/can_deploy_any_kind}}{{/can_write_any_draft}}{{^can_write_any_draft}}{{^read_only}}
|
||||
- You cannot create or edit anything, but where the server allows it discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes a deployed item.{{/read_only}}{{/can_write_any_draft}}{{^read_only}}{{#unmanaged}}
|
||||
- This workspace does not let this user change {{unmanaged_kinds}}, here or in Windmill: suggest asking a workspace admin.{{/unmanaged}}{{/read_only}}
|
||||
- Listings return only what this user can see. When an item they name is missing, say it may be in a folder they cannot read, not that it does not exist.
|
||||
- No one can read a variable's value through these tools. When editing a variable, pass only the fields that change.
|
||||
- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration.
|
||||
- Only raw apps (\`rawApp\` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words.
|
||||
- Datatables are set up in the workspace settings. Start from list_datatables; one with \`migrations_enabled\` changes its schema through migrations only.
|
||||
- create_resource_type adds a resource type: show the user the schema first and create it once they agree.
|
||||
- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.${paths}${
|
||||
skills.length > 0
|
||||
? `
|
||||
- No one can read a variable's value through these tools.{{#can_draft_variables}} When editing a variable, pass only the fields that change.{{/can_draft_variables}}{{#can_write_draft}}
|
||||
- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration.{{/can_write_draft}}
|
||||
- {{#can_write_app_draft}}Only raw apps (\`rawApp\` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words.{{/can_write_app_draft}}{{^can_write_app_draft}}Only raw apps (\`rawApp\` true) can be read here.{{/can_write_app_draft}}
|
||||
- Datatables are set up in the workspace settings. Start from list_datatables; one with \`migrations_enabled\` changes its schema through migrations only.{{#can_draft_resources}}{{#can_create_resource_type}}
|
||||
- create_resource_type adds a resource type: show the user the schema first and create it once they agree.{{/can_create_resource_type}}{{^can_create_resource_type}}
|
||||
- This user cannot create a resource type here, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin.{{/can_create_resource_type}}{{/can_draft_resources}}
|
||||
- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.${PATH_CONVENTIONS}`
|
||||
|
||||
/** The flags and variables `EXTERNAL_PROMPT` renders with for one access profile, which the
|
||||
* generator exports per `prompt_profile` key: the server only fills the template. */
|
||||
export function externalPromptProfile(access: SessionAccess | undefined, runsDeployed: boolean) {
|
||||
const a = accessFlags(access)
|
||||
const flags: Record<string, boolean> = {
|
||||
read_only: a.readOnly,
|
||||
runs_deployed: runsDeployed,
|
||||
runs: !a.readOnly || runsDeployed,
|
||||
can_write_any_draft: a.canWriteAnyDraft,
|
||||
can_write_draft: a.canWriteDraft,
|
||||
can_write_app_draft: a.canWriteAppDraft,
|
||||
builds_flows: a.buildsFlows,
|
||||
builds_apps: a.buildsApps,
|
||||
has_draft_tools:
|
||||
a.canDraftResources || a.canDraftVariables || a.canDraftSchedules || a.canDraftTriggers,
|
||||
can_draft_triggers: a.canDraftTriggers,
|
||||
can_draft_resources: a.canDraftResources,
|
||||
can_draft_variables: a.canDraftVariables,
|
||||
can_deploy: a.canDeploy,
|
||||
can_deploy_any_kind: a.canDeployAnyKind,
|
||||
can_run_preview: a.canRunPreview,
|
||||
can_run_flow_preview: a.canRunFlowPreview,
|
||||
unmanaged: !a.canManageSchedules || !a.canManageTriggers,
|
||||
can_create_resource_type: a.canCreateResourceType,
|
||||
can_create_folder: a.canCreateFolder
|
||||
}
|
||||
return {
|
||||
flags: new Set(Object.keys(flags).filter((f) => flags[f])),
|
||||
vars: {
|
||||
refused_kinds: listJoin(a.refusedKinds, 'disjunction'),
|
||||
draft_tools: listJoin([
|
||||
a.canDraftResources && 'write_resource',
|
||||
a.canDraftVariables && 'write_variable',
|
||||
a.canDraftSchedules && 'write_schedule',
|
||||
a.canDraftTriggers && 'write_trigger'
|
||||
]),
|
||||
unmanaged_kinds:
|
||||
!a.canManageSchedules && !a.canManageTriggers
|
||||
? 'schedules or triggers'
|
||||
: !a.canManageSchedules
|
||||
? 'schedules'
|
||||
: 'triggers'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function externalSkills(skills: AiSkillListItem[]): string {
|
||||
return skills.length > 0
|
||||
? `
|
||||
|
||||
Skills:
|
||||
- This workspace keeps skills, guidance documents for specific kinds of tasks, listed below by path and description. read_skill returns one: read it when a request matches its description, then do the work with the tools above.
|
||||
${skills.map((s) => `- ${s.path}: ${s.description}`).join('\n')}`
|
||||
: ''
|
||||
}`
|
||||
: ''
|
||||
}
|
||||
|
||||
const buildGlobalSystemPrompt = (
|
||||
username: string,
|
||||
previewTools: boolean,
|
||||
folderCtx?: FolderPromptContext,
|
||||
skills: AiSkillListItem[] = [],
|
||||
mcpServers: McpServer[] = [],
|
||||
access?: SessionAccess,
|
||||
// The prompt an external MCP client reads (`buildExternalPrompt`): it shares only the path
|
||||
// conventions, which carry the folder guidance.
|
||||
external = false
|
||||
) => {
|
||||
function accessFlags(access: SessionAccess | undefined) {
|
||||
// Each `can*` mirrors the capability the matching tools declare in `requires`, so a
|
||||
// rule cannot outlive the tool it describes. An unresolved profile keeps every block.
|
||||
const canWriteDraft = !access || access.has('write_draft')
|
||||
@@ -1498,6 +1571,76 @@ const buildGlobalSystemPrompt = (
|
||||
// resource type text.
|
||||
const canCreateFolder = !access || access.has('deploy')
|
||||
const canCreateResourceType = !access || access.has('deploy')
|
||||
return {
|
||||
canWriteDraft,
|
||||
canWriteFlowDraft,
|
||||
canWriteAppDraft,
|
||||
canDraftSchedules,
|
||||
canDraftTriggers,
|
||||
canDraftResources,
|
||||
canDraftVariables,
|
||||
inlineFlowCode,
|
||||
buildsFlows,
|
||||
buildsApps,
|
||||
canWriteAnyDraft,
|
||||
canDeploy,
|
||||
readOnly,
|
||||
canDeployAnyKind,
|
||||
draftedKinds,
|
||||
draftedOperatorKinds,
|
||||
deployableKinds,
|
||||
refusedKinds,
|
||||
refusedCode,
|
||||
canRunPreview,
|
||||
canRunFlowPreview,
|
||||
testRunTools,
|
||||
canManageSchedules,
|
||||
canManageTriggers,
|
||||
canCreateFolder,
|
||||
canCreateResourceType
|
||||
}
|
||||
}
|
||||
|
||||
const buildGlobalSystemPrompt = (
|
||||
username: string,
|
||||
previewTools: boolean,
|
||||
folderCtx?: FolderPromptContext,
|
||||
skills: AiSkillListItem[] = [],
|
||||
mcpServers: McpServer[] = [],
|
||||
access?: SessionAccess,
|
||||
// The prompt an external MCP client reads (`EXTERNAL_PROMPT`): it shares only the path
|
||||
// conventions, which carry the folder guidance.
|
||||
external = false,
|
||||
// Whether a read-only external session may still run deployed items (`mcp:read_run`).
|
||||
runsDeployed = true
|
||||
) => {
|
||||
const {
|
||||
canWriteDraft,
|
||||
canWriteFlowDraft,
|
||||
canWriteAppDraft,
|
||||
canDraftSchedules,
|
||||
canDraftTriggers,
|
||||
canDraftResources,
|
||||
canDraftVariables,
|
||||
inlineFlowCode,
|
||||
buildsFlows,
|
||||
buildsApps,
|
||||
canWriteAnyDraft,
|
||||
readOnly,
|
||||
canDeployAnyKind,
|
||||
draftedKinds,
|
||||
draftedOperatorKinds,
|
||||
deployableKinds,
|
||||
refusedKinds,
|
||||
refusedCode,
|
||||
canRunPreview,
|
||||
canRunFlowPreview,
|
||||
testRunTools,
|
||||
canManageSchedules,
|
||||
canManageTriggers,
|
||||
canCreateFolder,
|
||||
canCreateResourceType
|
||||
} = accessFlags(access)
|
||||
// Each gated block carries its own leading newline, so dropping one leaves no blank
|
||||
// line behind and a full-access prompt is byte-for-byte the ungated text.
|
||||
const when = (cond: boolean, block: string) => (cond ? block : '')
|
||||
@@ -1558,6 +1701,9 @@ const buildGlobalSystemPrompt = (
|
||||
`
|
||||
- Use deploy_workspace_item only after the user explicitly asks to deploy. It persists a draft to the workspace.`
|
||||
)
|
||||
const resourceTypeRule = canCreateResourceType
|
||||
? '- create_resource_type creates a resource type the workspace lacks. The user confirms the schema in the call itself, so that is where you propose it rather than asking first in chat.\n'
|
||||
: '- This user cannot create a resource type here, in chat or on the Resources page, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin, who can add it.\n'
|
||||
const instructionsRule =
|
||||
'- Use get_instructions before writing scripts, flows, resources, or apps. For scripts, pass the target language.'
|
||||
const testDraftRule = `- After creating or editing a script${canWriteFlowDraft ? ' or flow' : ''} draft, run ${testRunTools} with representative args before reporting that it works. These tools prefer drafts, so testing does not require deployment.`
|
||||
@@ -1569,7 +1715,11 @@ const buildGlobalSystemPrompt = (
|
||||
`
|
||||
- Default to ${testRunTools} for any run request, an existing script included; they prefer drafts and need no deployment. Use run_script or run_flow only when the user names the deployed version ("the deployed X", "in production", "for real") — a bare "run X" is not that. For those two, read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema. ${testRunList}, run_script and run_flow all show the user an argument form prefilled with what you sent, so fill in every argument you can infer rather than asking for it in chat. test_run_step's form is the step's own inputs, not the flow's.`
|
||||
)}${when(
|
||||
!canRunPreview,
|
||||
!canRunPreview && canRunFlowPreview,
|
||||
`
|
||||
- A request to run a flow goes to test_run_flow, which prefers the draft and needs no deployment. Use run_flow only when the user names the deployed version, and run_script for any script: those run the DEPLOYED item under this user's own permissions, so read it with read_workspace_item version: "deployed" first so the arguments match the deployed schema. Each shows the user an argument form prefilled with what you sent, so fill in every argument you can infer rather than asking for it in chat.`
|
||||
)}${when(
|
||||
!canRunPreview && !canRunFlowPreview,
|
||||
`
|
||||
- run_script and run_flow are how you run anything here: they run the DEPLOYED item under this user's own permissions, and show them an argument form prefilled with what you sent. Read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema, and fill in every argument you can infer rather than asking for it in chat.`
|
||||
)}`
|
||||
@@ -1609,24 +1759,22 @@ ${
|
||||
}.`
|
||||
)}`
|
||||
}`
|
||||
const paths = `${when(
|
||||
canWriteAnyDraft,
|
||||
`
|
||||
|
||||
Path conventions:
|
||||
- A workspace path starts with one of two namespaces; its trailing <name> may itself contain "/", so a path has three or more segments:
|
||||
- \`u/${username}/<name>\` — your personal scope. Default for ad-hoc, exploratory, or scratch work.
|
||||
- \`f/<folder>/<name>\` — a shared folder scope; the <folder> must already exist (a bare \`f/<name>\` with no folder segment is INVALID and will fail).
|
||||
- If the user supplies a fully qualified \`f/<folder>/...\` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a \`u/${username}/...\` path unless a tool rejects it.
|
||||
- Default a bare name with no namespace prefix (e.g. "create a flow called myflow") to \`u/${username}/<name>\`. Never invent an \`f/<folder>/...\` path for a folder that does not exist${when(
|
||||
canCreateFolder,
|
||||
'; create one with `create_folder` only when the user explicitly asks for a new folder'
|
||||
)}.${folderGuidanceBlock}`
|
||||
)}${when(
|
||||
canCreateFolder && !canWriteAnyDraft,
|
||||
'\n- You can create a shared folder with `create_folder` when the user explicitly asks for one. You cannot create anything inside it here, so do not offer to.'
|
||||
)}`
|
||||
if (external) return buildExternalPrompt(username, paths, skills)
|
||||
const runtimeVars = { username, folder_guidance: folderGuidanceBlock }
|
||||
if (external) {
|
||||
const profile = externalPromptProfile(access, runsDeployed)
|
||||
return (
|
||||
renderPromptTemplate(EXTERNAL_PROMPT, profile.flags, { ...profile.vars, ...runtimeVars }) +
|
||||
externalSkills(skills)
|
||||
)
|
||||
}
|
||||
const paths = renderPromptTemplate(
|
||||
PATH_CONVENTIONS,
|
||||
new Set([
|
||||
...(canWriteAnyDraft ? ['can_write_any_draft'] : []),
|
||||
...(canCreateFolder ? ['can_create_folder'] : [])
|
||||
]),
|
||||
runtimeVars
|
||||
)
|
||||
|
||||
return `${intro}${paths}
|
||||
|
||||
@@ -1682,9 +1830,9 @@ ${groupMembershipRule}- Listings and reads return only what this user can see: i
|
||||
- Hub scripts are prebuilt, vetted integrations for third-party services, hosted outside the workspace under \`hub/<version>/<app>/<name>\` paths. Check search_hub_scripts before hand-writing code against a third-party API, even when the user never mentions the hub; read a result with read_workspace_item type "script" and its hub path to get its code, language, and input schema. Use what you find in whichever way fits: reference the hub path directly from a flow module or app runnable when a script already does the job, copy it into a workspace draft and adapt it when it is close (note the source hub path in a comment at the top of the code), or take it as a worked example and write your own. A script that does not do what the user asked is still worth reading when it is the only example of that integration: pass its \`integration\` back to search_hub_scripts to list that integration's other scripts with their descriptions, or use the \`suggested_integrations\` a search hands back when it finds nothing.
|
||||
- Before writing your own code against an integration the hub covers, call get_hub_integration with its slug: it returns the resource type to take, its auth fields and the integration's most-used scripts, which beats inferring them from script bodies. Call it for the integration you are about to write against, whichever it is. A search marks an integration \`documented\` when the hub additionally holds provider knowledge checked against the live API — pagination, enums, error codes and gotchas — so read that closely where it appears rather than trusting your own memory of the API.
|
||||
- If you have a web search tool and the hub does not cover a third-party API, search for the vendor's own API documentation rather than writing its endpoints and auth from memory, and link the page you relied on. Reserve it for external APIs: search_docs answers questions about Windmill itself.
|
||||
${when(canCreateResourceType, `- create_resource_type creates a resource type the workspace lacks. The user confirms the schema in the call itself, so that is where you propose it rather than asking first in chat.\n`)}${when(!canCreateResourceType, '- This user cannot create a resource type here, in chat or on the Resources page, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin, who can add it.\n')}${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}${instructionsRule}
|
||||
${resourceTypeRule}${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}${instructionsRule}
|
||||
${pipelineBullet}`
|
||||
)}${when(
|
||||
)}${when(!canWriteDraft && canDraftResources, `\n${resourceTypeRule.trimEnd()}`)}${when(
|
||||
canRunPreview && canWriteDraft,
|
||||
`
|
||||
${testDraftRule}
|
||||
@@ -7344,6 +7492,8 @@ export function prepareGlobalSystemMessage(
|
||||
access?: SessionAccess
|
||||
/** Render for an external MCP client rather than the Windmill chat. */
|
||||
external?: boolean
|
||||
/** For `external` with read-only `access`: whether deployed items may still be run. */
|
||||
runsDeployed?: boolean
|
||||
}
|
||||
): ChatCompletionSystemMessageParam {
|
||||
const user = opts?.user ?? get(userStore)
|
||||
@@ -7363,7 +7513,8 @@ export function prepareGlobalSystemMessage(
|
||||
opts?.skills ?? [],
|
||||
opts?.mcpServers ?? [],
|
||||
opts?.access,
|
||||
opts?.external ?? false
|
||||
opts?.external ?? false,
|
||||
opts?.runsDeployed ?? true
|
||||
)
|
||||
if (instructions?.workspace?.trim()) {
|
||||
content = `${content}\n\nWORKSPACE INSTRUCTIONS (configured by a workspace admin, shared by everyone in this workspace — you cannot modify these):\n${instructions.workspace.trim()}`
|
||||
|
||||
@@ -12,13 +12,21 @@ import { describe, expect, it } from 'vitest'
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { join } from 'node:path'
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
ALL_INSTRUCTION_SUBJECTS,
|
||||
buildFolderGuidance,
|
||||
EXTERNAL_PROMPT,
|
||||
externalPromptProfile,
|
||||
getInstructions,
|
||||
globalToolsFor,
|
||||
prepareGlobalSystemMessage
|
||||
} from './core'
|
||||
import type { ScriptLang } from '$lib/gen'
|
||||
import { renderPromptTemplate } from './promptTemplate'
|
||||
import type { AuthorLevel, ScriptLang } from '$lib/gen'
|
||||
import { FULL_CAPABILITIES } from '$lib/roleCapabilities'
|
||||
import { capabilitiesForRole } from './sessionAccess'
|
||||
import { USE_MODE_ACCESS } from '../sessionCapabilities'
|
||||
import {
|
||||
BUILDER_FRAMEWORK_TEMPLATES,
|
||||
FRAMEWORK_TEMPLATES,
|
||||
@@ -161,9 +169,11 @@ function toolDefs() {
|
||||
const WRITABLE = '{{writable_folders}}'
|
||||
const READONLY = '{{readonly_folders}}'
|
||||
|
||||
type PromptOpts = Parameters<typeof prepareGlobalSystemMessage>[1]
|
||||
|
||||
function prompt(
|
||||
user: { is_admin: boolean; folders?: string[]; folders_read?: string[] },
|
||||
extra: Parameters<typeof prepareGlobalSystemMessage>[1] = {},
|
||||
extra: PromptOpts = {},
|
||||
instructions?: { workspace?: string }
|
||||
): string {
|
||||
const content = prepareGlobalSystemMessage(instructions, {
|
||||
@@ -182,6 +192,71 @@ function suffixOf(longer: string, base: string, what: string): string {
|
||||
return longer.slice(base.length)
|
||||
}
|
||||
|
||||
/** The `{{folder_guidance}}` the server puts in the template, once per folder situation, as
|
||||
* `buildGlobalSystemPrompt` inserts it: with its leading newline. */
|
||||
function folderGuidance(canCreateFolder: boolean) {
|
||||
const variant = (isAdmin: boolean, folders: string[], foldersRead = folders) => {
|
||||
const text = buildFolderGuidance(
|
||||
'{{username}}',
|
||||
{ isAdmin, folders, foldersRead },
|
||||
canCreateFolder,
|
||||
true
|
||||
)
|
||||
return (text ? `\n${text}` : '')
|
||||
.replaceAll('`f/' + WRITABLE + '`', WRITABLE)
|
||||
.replaceAll('`f/' + READONLY + '`', READONLY)
|
||||
}
|
||||
return {
|
||||
admin: variant(true, [WRITABLE]),
|
||||
admin_no_folders: variant(true, []),
|
||||
member: variant(false, [WRITABLE]),
|
||||
member_no_folders: variant(false, []),
|
||||
member_readonly: variant(false, [WRITABLE], [WRITABLE, READONLY]),
|
||||
member_no_folders_readonly: variant(false, [], [READONLY])
|
||||
}
|
||||
}
|
||||
|
||||
const LEVELS: AuthorLevel[] = ['none', 'compose', 'full']
|
||||
const bit = (b: boolean) => (b ? '1' : '0')
|
||||
|
||||
/** Every access profile the server can resolve a caller to, keyed as `prompt_profile` in
|
||||
* `ai_session_tools/instructions.rs` builds the key: the token's scope, then for a full token
|
||||
* the caller's role as `caller_capabilities` and `check_deploy_rules` give it. */
|
||||
function profiles(): [key: string, extra: PromptOpts][] {
|
||||
const out: [string, PromptOpts][] = [
|
||||
['read_only', { access: USE_MODE_ACCESS, runsDeployed: false }],
|
||||
['read_run', { access: USE_MODE_ACCESS, runsDeployed: true }]
|
||||
]
|
||||
for (const isAdmin of [true, false])
|
||||
for (const deploy of [true, false])
|
||||
for (const code of [true, false])
|
||||
for (const flows of LEVELS)
|
||||
for (const apps of LEVELS)
|
||||
for (const manage_schedules of [true, false])
|
||||
for (const manage_triggers of [true, false]) {
|
||||
const caps = {
|
||||
...FULL_CAPABILITIES,
|
||||
code,
|
||||
flows,
|
||||
apps,
|
||||
manage_schedules,
|
||||
manage_triggers
|
||||
}
|
||||
// Full flows or apps without code is refused at write.
|
||||
if (!code && (flows === 'full' || apps === 'full')) continue
|
||||
// An admin holds every capability, so only the full role is reachable.
|
||||
if (isAdmin && JSON.stringify(caps) !== JSON.stringify(FULL_CAPABILITIES)) continue
|
||||
const key = `full:${bit(isAdmin)}${bit(deploy)}:${bit(code)}:${flows}:${apps}:${bit(manage_schedules)}${bit(manage_triggers)}`
|
||||
const access = capabilitiesForRole({
|
||||
isAdmin,
|
||||
deployRulesPass: deploy,
|
||||
capabilities: caps
|
||||
})
|
||||
out.push([key, { access }])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function promptParts() {
|
||||
const member = prompt({ is_admin: false, folders: [WRITABLE] })
|
||||
const skills = suffixOf(
|
||||
@@ -193,37 +268,25 @@ function promptParts() {
|
||||
'the skills section'
|
||||
)
|
||||
const skillLine = skills.split('\n').pop()!
|
||||
// The folder guidance differs per workspace, so it is cut out of the prompt: the server
|
||||
// puts it back for a single workspace, and serves it from `get_workspace_context` otherwise.
|
||||
const withoutFolders = prompt({ is_admin: false })
|
||||
const variants = {
|
||||
admin: prompt({ is_admin: true, folders: [WRITABLE] }),
|
||||
admin_no_folders: prompt({ is_admin: true, folders: [] }),
|
||||
member,
|
||||
member_no_folders: prompt({ is_admin: false, folders: [] }),
|
||||
member_readonly: prompt({
|
||||
is_admin: false,
|
||||
folders: [WRITABLE],
|
||||
folders_read: [WRITABLE, READONLY]
|
||||
}),
|
||||
member_no_folders_readonly: prompt({ is_admin: false, folders: [], folders_read: [READONLY] })
|
||||
const index: Record<string, { flags: string; vars: Record<string, string> }> = {}
|
||||
// What each profile renders to before the server fills the runtime variables, so a Rust
|
||||
// test can check its renderer against this one.
|
||||
const renderedSha256: Record<string, string> = {}
|
||||
for (const [key, extra] of profiles()) {
|
||||
const { flags, vars } = externalPromptProfile(extra?.access, extra?.runsDeployed ?? true)
|
||||
index[key] = { flags: [...flags].sort().join(' '), vars }
|
||||
renderedSha256[key] = createHash('sha256')
|
||||
.update(renderPromptTemplate(EXTERNAL_PROMPT, flags, vars))
|
||||
.digest('hex')
|
||||
}
|
||||
let at: number | undefined
|
||||
const folder_guidance = Object.fromEntries(
|
||||
Object.entries(variants).map(([name, full]) => {
|
||||
let i = 0
|
||||
while (full[i] === withoutFolders[i]) i++
|
||||
const rest = withoutFolders.slice(i)
|
||||
if ((at !== undefined && at !== i) || !full.endsWith(rest)) {
|
||||
throw new Error(`the folder guidance (${name}) is no longer one inserted block`)
|
||||
}
|
||||
at = i
|
||||
return [name, full.slice(i, full.length - rest.length)]
|
||||
})
|
||||
)
|
||||
return {
|
||||
base: withoutFolders.slice(0, at) + '{{folder_guidance}}' + withoutFolders.slice(at),
|
||||
folder_guidance,
|
||||
template: EXTERNAL_PROMPT,
|
||||
profiles: index,
|
||||
folder_guidance: {
|
||||
create_folder: folderGuidance(true),
|
||||
no_create_folder: folderGuidance(false)
|
||||
},
|
||||
rendered_sha256: renderedSha256,
|
||||
skills_header: skills.slice(0, skills.length - skillLine.length),
|
||||
skill_line: skillLine,
|
||||
workspace_instructions: suffixOf(
|
||||
@@ -333,4 +396,40 @@ describe('MCP session server generated definitions', () => {
|
||||
expect(readFileSync(join(OUT_DIR, name), 'utf8'), name).toBe(content)
|
||||
}
|
||||
})
|
||||
|
||||
// A capability that changes the prompt but is missing from the profile key would serve every
|
||||
// role the prompt of whatever value `profiles()` fixed it at.
|
||||
it('key every role capability that changes the prompt', () => {
|
||||
const keyed = ['code', 'flows', 'apps', 'manage_schedules', 'manage_triggers']
|
||||
const render = (capabilities: typeof FULL_CAPABILITIES) => {
|
||||
const access = capabilitiesForRole({ isAdmin: false, deployRulesPass: true, capabilities })
|
||||
const { flags, vars } = externalPromptProfile(access, true)
|
||||
return renderPromptTemplate(EXTERNAL_PROMPT, flags, vars)
|
||||
}
|
||||
const roles = [
|
||||
FULL_CAPABILITIES,
|
||||
{
|
||||
...FULL_CAPABILITIES,
|
||||
code: false,
|
||||
flows: 'compose' as AuthorLevel,
|
||||
apps: 'none' as AuthorLevel
|
||||
}
|
||||
]
|
||||
for (const role of roles)
|
||||
for (const [field, value] of Object.entries(role)) {
|
||||
if (keyed.includes(field)) continue
|
||||
const others =
|
||||
typeof value === 'boolean'
|
||||
? [!value]
|
||||
: typeof value === 'string'
|
||||
? LEVELS.filter((l) => l !== value)
|
||||
: [Object.fromEntries(Object.keys(value).map((k) => [k, false]))]
|
||||
for (const other of others) {
|
||||
expect(
|
||||
render({ ...role, [field]: other }),
|
||||
`role capability "${field}" changes the MCP prompt: add it to the profile key in profiles() and prompt_profile (instructions.rs)`
|
||||
).toBe(render(role))
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// The MCP server renders the same templates in Rust (`ai_session_tools/instructions.rs`,
|
||||
// `render_template`); `mcpSessionGen.test.ts` hashes every profile's render so the two cannot
|
||||
// drift. Keep the grammar to what both implement: `{{#flag}}…{{/flag}}` keeps its body when
|
||||
// the flag is set, `{{^flag}}…{{/flag}}` when it is not, `{{name}}` takes a variable, and a
|
||||
// variable not given stays as written for a later pass to fill.
|
||||
const TAG = /\{\{([#^/]?)([a-z_]+)\}\}/g
|
||||
|
||||
export function renderPromptTemplate(
|
||||
template: string,
|
||||
flags: ReadonlySet<string>,
|
||||
vars: Readonly<Record<string, string>>
|
||||
): string {
|
||||
let out = ''
|
||||
let last = 0
|
||||
const open: { name: string; keep: boolean }[] = []
|
||||
const keeping = () => open.every((s) => s.keep)
|
||||
for (const m of template.matchAll(TAG)) {
|
||||
const [tag, kind, name] = m
|
||||
if (keeping()) out += template.slice(last, m.index)
|
||||
last = m.index + tag.length
|
||||
if (kind === '#' || kind === '^') {
|
||||
open.push({ name, keep: flags.has(name) === (kind === '#') })
|
||||
} else if (kind === '/') {
|
||||
if (open.pop()?.name !== name) throw new Error(`unbalanced {{/${name}}} in prompt template`)
|
||||
} else if (keeping()) {
|
||||
out += Object.hasOwn(vars, name) ? vars[name] : tag
|
||||
}
|
||||
}
|
||||
if (open.length) throw new Error(`unclosed {{#${open[0].name}}} in prompt template`)
|
||||
return out + template.slice(last)
|
||||
}
|
||||
@@ -111,7 +111,8 @@ export function capabilitiesForRole(role: {
|
||||
/** Whether `rulesets` make a session read-only. `DisableDirectDeployment` holds everyone, admins
|
||||
* and bypassers included, since production changes go through its dev workspace or a fork;
|
||||
* `RestrictDeployToDeployers` alone leaves its users their drafts. Unreadable rules protect too:
|
||||
* the server holds deploys to the rule but not drafts. */
|
||||
* the server holds deploys to the rule but not drafts. The MCP server applies the same rule
|
||||
* (`workspace_access` in `backend/windmill-api/src/mcp/core.rs`): change both. */
|
||||
function protects(rulesets: ProtectionRuleset[] | undefined): boolean {
|
||||
return !rulesets || isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment')
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { ClipboardCopy, Download, Maximize2, Minus, Plus, RotateCcw } from 'lucide-svelte'
|
||||
import type { PanZoom } from 'panzoom'
|
||||
|
||||
let { code }: { code: string } = $props()
|
||||
let { code, forceLight = false }: { code: string; forceLight?: boolean } = $props()
|
||||
|
||||
const isDarkMode = useIsDarkMode()
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
// Monotonic token so an earlier-started render that resolves late can't
|
||||
// overwrite the result of a newer one (out-of-order async on rapid code/theme changes).
|
||||
let renderSeq = 0
|
||||
// False while a render is in flight, true once it drew or failed. Exposed as
|
||||
// data-mermaid-pending so a print can wait for diagrams without counting fences.
|
||||
let settled = $state(false)
|
||||
|
||||
let expanded = $state(false)
|
||||
|
||||
@@ -27,8 +30,10 @@
|
||||
if (!source?.trim()) {
|
||||
svg = undefined
|
||||
renderedCode = undefined
|
||||
settled = true
|
||||
return
|
||||
}
|
||||
settled = false
|
||||
try {
|
||||
const mermaid = (await import('mermaid')).default
|
||||
mermaid.initialize({
|
||||
@@ -65,11 +70,13 @@
|
||||
// Parse failure (often a partial block still streaming in): fall back to the
|
||||
// raw source. `showSvg` already hides any previous diagram since `renderedCode`
|
||||
// no longer matches the current `code`.
|
||||
} finally {
|
||||
if (seq === renderSeq) settled = true
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void render(code, isDarkMode.val)
|
||||
void render(code, !forceLight && isDarkMode.val)
|
||||
})
|
||||
|
||||
// Only show the diagram while it corresponds to the current source.
|
||||
@@ -130,8 +137,8 @@
|
||||
</script>
|
||||
|
||||
{#if showSvg}
|
||||
<div class="relative">
|
||||
<div class="absolute top-2 right-2 z-20 flex flex-row gap-1">
|
||||
<div class="relative" data-mermaid-pending={!settled}>
|
||||
<div class="absolute top-2 right-2 z-20 flex flex-row gap-1 print:hidden">
|
||||
<Button
|
||||
onclick={() => copyToClipboard(code)}
|
||||
color="light"
|
||||
@@ -213,5 +220,5 @@
|
||||
</Modal>
|
||||
{:else}
|
||||
<!-- Fallback while loading or when rendering fails: show the raw source -->
|
||||
<pre class="overflow-auto max-h-screen text-xs p-2">{code}</pre>
|
||||
<pre class="overflow-auto max-h-screen text-xs p-2" data-mermaid-pending={!settled}>{code}</pre>
|
||||
{/if}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import {
|
||||
allRunsHref,
|
||||
askAI,
|
||||
failedRunsHref,
|
||||
canAskAI,
|
||||
collisionPrefixes,
|
||||
itemKey,
|
||||
@@ -154,7 +155,7 @@
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class="flex items-center gap-2 px-1.5 pb-1 {data
|
||||
class="flex items-center gap-1 px-1.5 pb-1 whitespace-nowrap {data
|
||||
? 'mt-1.5 pt-2 border-t border-border-light'
|
||||
: 'pt-1'}"
|
||||
>
|
||||
@@ -165,6 +166,16 @@
|
||||
All runs
|
||||
<ExternalLink size={12} />
|
||||
</a>
|
||||
{#if data && data.failed_runs > 0}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
endIcon={{ icon: ExternalLink }}
|
||||
href={failedRunsHref(folder, data.window_hours)}
|
||||
>
|
||||
Failed runs
|
||||
</Button>
|
||||
{/if}
|
||||
{#if onShowPanel}
|
||||
<div class="ml-auto">
|
||||
<Button
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { Button, Skeleton } from '$lib/components/common'
|
||||
import { ExternalLink, PanelRightClose } from 'lucide-svelte'
|
||||
import { ExternalLink, ListFilter, PanelRightClose, Sparkles } from 'lucide-svelte'
|
||||
import Popover from '$lib/components/meltComponents/Popover.svelte'
|
||||
import RecentRunRow from './RecentRunRow.svelte'
|
||||
import {
|
||||
allRunsHref,
|
||||
askAI,
|
||||
canAskAI,
|
||||
collisionPrefixes,
|
||||
failedRunsHref,
|
||||
itemKey,
|
||||
totalLabel,
|
||||
windowLabel,
|
||||
@@ -29,6 +31,16 @@
|
||||
// The failed count also holds runs an item has since recovered from; Ask AI attaches only
|
||||
// the items still failing, so it shows only when there is one.
|
||||
let failing = $derived(data?.items.filter((i) => i.status === 'failure') ?? [])
|
||||
// Every item the failed count is made of, recovered ones included.
|
||||
let failedItems = $derived(data?.items.filter((i) => i.failed_runs > 0) ?? [])
|
||||
let onlyFailing = $state(false)
|
||||
let failedMenuOpen = $state(false)
|
||||
// The menu holding the toggle goes once the last failure is resolved: the filter must go with it.
|
||||
let filtering = $derived(onlyFailing && failedItems.length > 0)
|
||||
$effect(() => {
|
||||
if (data && failedItems.length === 0) onlyFailing = false
|
||||
})
|
||||
let shownItems = $derived(filtering ? failedItems : (data?.items ?? []))
|
||||
let windowText = $derived(data ? windowLabel(data.window_hours) : '')
|
||||
let prefixes = $derived(data && !folder ? collisionPrefixes(data.items) : new Map())
|
||||
</script>
|
||||
@@ -44,30 +56,79 @@
|
||||
{/if}
|
||||
{#if data}
|
||||
<span
|
||||
class="relative min-w-0 truncate text-xs font-normal text-hint wm-page-in"
|
||||
class="flex items-baseline min-w-0 text-xs font-normal text-hint wm-page-in"
|
||||
title="{windowText} · {totalLabel(data)} · {data.failed_runs} failed"
|
||||
>
|
||||
{#if data.failed_runs > 0}
|
||||
<span class="group/failed relative">
|
||||
<span class="text-red-600 dark:text-red-400">{data.failed_runs}</span> failed
|
||||
{#if canAskAI() && failing.length > 0}
|
||||
<button
|
||||
class="absolute left-full top-1/2 -translate-y-1/2 ml-1 h-5 px-1.5 rounded text-[11px] font-medium text-ai bg-ai/10 hover:bg-ai/15 whitespace-nowrap opacity-0 pointer-events-none group-hover/failed:opacity-100 group-hover/failed:pointer-events-auto focus:opacity-100 focus:pointer-events-auto"
|
||||
onclick={() =>
|
||||
askAI(
|
||||
{ kind: 'failing', items: failing },
|
||||
'Investigate why these items are failing'
|
||||
)}
|
||||
>
|
||||
Ask AI
|
||||
</button>
|
||||
{/if}
|
||||
</span>
|
||||
<!-- A popover rather than a hover-revealed button: its content stays open while the
|
||||
pointer travels to it, where a button beside the count vanished on the way. -->
|
||||
<Popover
|
||||
openOnHover
|
||||
debounceDelay={140}
|
||||
placement="bottom-start"
|
||||
bind:isOpen={failedMenuOpen}
|
||||
triggerAttrs={{ 'aria-label': `${data.failed_runs} failed runs` }}
|
||||
class="shrink-0 -mx-1 px-1 rounded whitespace-nowrap hover:bg-surface-hover {filtering ||
|
||||
failedMenuOpen
|
||||
? 'bg-surface-hover'
|
||||
: ''}"
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<span class="text-red-600 dark:text-red-400">{data.failed_runs}</span> failed
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
<div class="flex flex-col p-1 min-w-[200px] text-xs">
|
||||
<!-- Items past the listed ones can hold the whole count: nothing to filter to. -->
|
||||
{#if failedItems.length > 0}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
btnClasses="justify-start"
|
||||
startIcon={{ icon: ListFilter }}
|
||||
onclick={() => {
|
||||
onlyFailing = !onlyFailing
|
||||
failedMenuOpen = false
|
||||
}}
|
||||
>
|
||||
{filtering ? 'Show all items' : `Show only failed (${failedItems.length})`}
|
||||
</Button>
|
||||
{/if}
|
||||
{#if canAskAI() && failing.length > 0}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
btnClasses="justify-start text-ai hover:bg-ai/10"
|
||||
startIcon={{ icon: Sparkles }}
|
||||
onclick={() => {
|
||||
failedMenuOpen = false
|
||||
askAI(
|
||||
{ kind: 'failing', items: failing },
|
||||
'Investigate why these items are failing'
|
||||
)
|
||||
}}
|
||||
>
|
||||
Ask AI about {failing.length} failing item{failing.length === 1 ? '' : 's'}
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
btnClasses="justify-start"
|
||||
startIcon={{ icon: ExternalLink }}
|
||||
href={failedRunsHref(folder, data.window_hours)}
|
||||
>
|
||||
View failed runs
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
{:else}
|
||||
{totalLabel(data)}
|
||||
<span class="truncate">{totalLabel(data)}</span>
|
||||
{/if}
|
||||
<!-- Room goes to the folder name first; the window stays in the tooltip. -->
|
||||
<span class="max-[1180px]:hidden {folder ? 'hidden' : ''}"> · {windowText}</span>
|
||||
<span class="truncate max-[1180px]:hidden {folder ? 'hidden' : ''}">
|
||||
· {windowText}</span
|
||||
>
|
||||
</span>
|
||||
{/if}
|
||||
</h2>
|
||||
@@ -102,7 +163,7 @@
|
||||
{:else if data}
|
||||
<!-- Fades in once, when the first read lands; refreshes update the rows in place. -->
|
||||
<div class="wm-page-in">
|
||||
{#each data.items as item (itemKey(item))}
|
||||
{#each shownItems as item (itemKey(item))}
|
||||
<RecentRunRow
|
||||
{item}
|
||||
now={runs.now}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { IsDocumentVisible, useInterval } from 'runed'
|
||||
import { persistedResource } from '$lib/persistedResource.svelte'
|
||||
import { homeComposerContext } from '$lib/components/sessions/homeComposerContext.svelte'
|
||||
import { runContextElement } from '$lib/components/copilot/chat/context'
|
||||
import { runsTimeframes } from '$lib/components/runs/timeframes'
|
||||
|
||||
export type RecentRuns = ListRecentRunsResponse
|
||||
export type RecentRunItem = RecentRuns['items'][number]
|
||||
@@ -129,6 +130,20 @@ export function allRunsHref(folder: string | undefined) {
|
||||
return folder ? `/runs?folder=${encodeURIComponent(folder)}` : '/runs'
|
||||
}
|
||||
|
||||
/** The runs page over the runs the failed count is made of: unresolved failures of the window. */
|
||||
export function failedRunsHref(folder: string | undefined, windowHours: number) {
|
||||
const params = new URLSearchParams({ status: 'failure', resolved: 'unresolved' })
|
||||
if (folder) params.set('folder', folder)
|
||||
// A preset timeframe stays relative to now, where a `min_ts` would freeze at render.
|
||||
const timeframe = runsTimeframes.find((t) => {
|
||||
const { minTs, maxTs } = t.computeMinMax()
|
||||
const span = minTs && maxTs ? Date.parse(maxTs) - Date.parse(minTs) : NaN
|
||||
return Math.abs(span - windowHours * 3600_000) < 1000
|
||||
})
|
||||
if (timeframe) params.set('timeframe', timeframe.label)
|
||||
return `/runs?${params}`
|
||||
}
|
||||
|
||||
export function windowLabel(hours: number) {
|
||||
return hours > 24 && hours % 24 === 0 ? `last ${hours / 24}d` : `last ${hours}h`
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
RAW_APP_SANDBOX_FLAGS,
|
||||
RAW_APP_PREVIEW_RELAY,
|
||||
rawAppStorageKey,
|
||||
rawAppCtx,
|
||||
readRawAppStorage,
|
||||
applyRawAppStorageOp
|
||||
} from './utils'
|
||||
@@ -43,7 +44,7 @@
|
||||
import type { Modules } from './RawAppModules.svelte'
|
||||
import { isRunnableByName, isRunnableByPath, type PathRunType } from '../apps/inputType'
|
||||
import { aiChatManager, AIMode } from '../copilot/chat/AIChatManager.svelte'
|
||||
import { onMount, onDestroy, untrack } from 'svelte'
|
||||
import { getContext, onMount, onDestroy, untrack } from 'svelte'
|
||||
import type {
|
||||
AppDatatableMetadata,
|
||||
LintResult,
|
||||
@@ -1926,9 +1927,17 @@ addEventListener('message', function (e) {
|
||||
})
|
||||
}
|
||||
|
||||
// In a session pane the page's query is the session's (`?session=…`), not the app's.
|
||||
const inSessionPane = !!getContext('aiChatManager')
|
||||
|
||||
// The deployed app's `window.ctx`: the viewer's membership in the app's workspace.
|
||||
function previewCtx() {
|
||||
return $state.snapshot({ ctx: operatingUser.current, workspace: opWorkspace, path })
|
||||
return rawAppCtx(
|
||||
$state.snapshot(operatingUser.current),
|
||||
opWorkspace,
|
||||
path,
|
||||
inSessionPane ? '' : window.location.search
|
||||
)
|
||||
}
|
||||
|
||||
// A build fed before the viewer is known keeps that viewer until the next one. A failed
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
RAW_APP_SANDBOX_FLAGS,
|
||||
applyRawAppStorageOp,
|
||||
rawAppStorageKey,
|
||||
rawAppCtx,
|
||||
readRawAppStorage,
|
||||
unsandboxedRawAppHtml
|
||||
} from './utils'
|
||||
@@ -27,15 +28,17 @@
|
||||
* (publish flow) needs it to read the app's DOM, which is only possible on
|
||||
* the unsandboxed path. */
|
||||
oniframe?: (iframe: HTMLIFrameElement | undefined) => void
|
||||
/** Mirror the app's own route into the page URL's hash, and start from it, and its
|
||||
* `document.title` into the page's. Off where the app is embedded in a page that is
|
||||
* not its own — an AI session preview tab — since there the hash and title belong to
|
||||
* that page and to whichever app was opened first. */
|
||||
syncHashToUrl?: boolean
|
||||
/** Mirror the app's own route into the page URL's hash, and start from it, its
|
||||
* `document.title` into the page's, and hand it the page's query. Off where the app is
|
||||
* embedded in a page that is not its own (an AI session preview tab, the demo
|
||||
* recorder), since there the address and title belong to that page. */
|
||||
ownsPageUrl?: boolean
|
||||
}
|
||||
|
||||
let { workspace, user, secret, path, runnables, oniframe, syncHashToUrl = true }: Props = $props()
|
||||
const pageHash = () => (syncHashToUrl ? window.location.hash : '')
|
||||
let { workspace, user, secret, path, runnables, oniframe, ownsPageUrl = true }: Props = $props()
|
||||
const pageHash = () => (ownsPageUrl ? window.location.hash : '')
|
||||
const appCtx = (u: UserExt | undefined) =>
|
||||
rawAppCtx(u, workspace, path, ownsPageUrl ? window.location.search : '')
|
||||
|
||||
$effect(() => {
|
||||
const el = unsandboxed ? iframe : undefined
|
||||
@@ -134,7 +137,7 @@
|
||||
const html = unsandboxedRawAppHtml(
|
||||
workspace,
|
||||
secret,
|
||||
{ ctx: u, workspace, path },
|
||||
appCtx(u),
|
||||
window.location.origin,
|
||||
pageHash()
|
||||
)
|
||||
@@ -207,7 +210,7 @@
|
||||
// Same shape as the unsandboxed wrapper: always the object, so
|
||||
// `window.ctx.workspace` works for anonymous viewers too. Snapshotted: a
|
||||
// caller's `$state` user is a proxy, which postMessage cannot clone.
|
||||
ctx: { ctx: $state.snapshot(user), workspace, path },
|
||||
ctx: appCtx($state.snapshot(user)),
|
||||
initialHash,
|
||||
storage: { local: bundleStorage ?? {}, session: {} },
|
||||
// The wrapper turns this into `window.process.env` before it injects the
|
||||
@@ -298,11 +301,11 @@
|
||||
} else if (data?.type === 'windmill:hashchange') {
|
||||
// Keep the parent URL hash in sync for shareable URLs.
|
||||
const newHash = data.hash || ''
|
||||
if (syncHashToUrl && window.location.hash !== newHash) {
|
||||
history.replaceState(null, '', newHash || window.location.pathname)
|
||||
if (ownsPageUrl && window.location.hash !== newHash) {
|
||||
history.replaceState(null, '', newHash || window.location.pathname + window.location.search)
|
||||
}
|
||||
} else if (data?.type === 'windmill:title') {
|
||||
if (syncHashToUrl) setAppTitle(typeof data.title === 'string' ? data.title : '')
|
||||
if (ownsPageUrl) setAppTitle(typeof data.title === 'string' ? data.title : '')
|
||||
} else if (runnerFailed) {
|
||||
refuseRequest(event)
|
||||
} else if (!runner) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
formatRuntimeLogsForChat,
|
||||
genWmillTs,
|
||||
normalizeRawAppRuntimeLogs,
|
||||
rawAppCtx,
|
||||
rawAppPreviewModules,
|
||||
stripRawAppDiffNoise,
|
||||
type Runnable
|
||||
@@ -53,6 +54,16 @@ const flowSchema = {
|
||||
}
|
||||
} as const
|
||||
|
||||
describe('rawAppCtx', () => {
|
||||
it("carries the page's query without Windmill's own parameters", () => {
|
||||
expect(rawAppCtx(undefined, 'ws', 'u/me/app', '?customer=42&wm_coep=1&tab=b').query).toEqual({
|
||||
customer: '42',
|
||||
tab: 'b'
|
||||
})
|
||||
expect(rawAppCtx(undefined, 'ws', 'u/me/app', '').query).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('genWmillTs', () => {
|
||||
it('generates the correct flow args type for path runnables', () => {
|
||||
const runnables: Record<string, Runnable> = {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { isRunnableByName, isRunnableByPath, type RunnableWithFields } from '../
|
||||
import type { InlineScript } from '../apps/sharedTypes'
|
||||
import { stateSnapshot } from '$lib/stateSnapshot.svelte'
|
||||
import { appSourceToDraftValue, normalizeRawAppData } from './rawAppDraftValue'
|
||||
import { urlParamsToObject } from '$lib/utils/queryParams'
|
||||
|
||||
// export type RunnableWithFields = any
|
||||
|
||||
@@ -319,6 +320,22 @@ export function applyRawAppStorageOp(storeKey: string, d: any) {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/** A full-code app's `window.ctx`, on every path that runs one. `query` is the viewer
|
||||
* page's, built as a low-code app's `ctx.query`, and `{}` rather than absent. */
|
||||
export function rawAppCtx(
|
||||
user: unknown,
|
||||
workspace: string | undefined,
|
||||
path: string,
|
||||
search: string
|
||||
) {
|
||||
return {
|
||||
ctx: user,
|
||||
workspace,
|
||||
path,
|
||||
query: urlParamsToObject(new URLSearchParams(search), { stripReserved: true })
|
||||
}
|
||||
}
|
||||
|
||||
// The sandboxed (isolated) raw-app wrapper is generated server-side and served as
|
||||
// a sandboxed, opaque-origin document (see `get_raw_app_data` in the backend
|
||||
// `apps.rs`, WIN-2006) — a blob: URL cannot carry the `CSP: sandbox` response
|
||||
|
||||
@@ -320,7 +320,7 @@
|
||||
{path}
|
||||
onEdit={() => onNavigate(`/apps_raw/edit/${path}`)}
|
||||
onLoadState={setLoadState}
|
||||
syncHashToUrl={false}
|
||||
ownsPageUrl={false}
|
||||
/>
|
||||
{/if}
|
||||
{/key}
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
import {
|
||||
HttpTriggerService,
|
||||
SettingService,
|
||||
VariableService,
|
||||
type AuthenticationMethod,
|
||||
type HttpTrigger,
|
||||
type NewHttpTrigger,
|
||||
@@ -24,9 +23,9 @@
|
||||
import { capitalize, emptyString, generateRandomString, sendUserToast } from '$lib/utils'
|
||||
import { useEditRights } from '$lib/operatorWriteRights'
|
||||
import Section from '$lib/components/Section.svelte'
|
||||
import { Loader2, Pipette, Plus } from 'lucide-svelte'
|
||||
import { Loader2, Pipette } from 'lucide-svelte'
|
||||
import Label from '$lib/components/Label.svelte'
|
||||
import VariableEditor from '../../VariableEditor.svelte'
|
||||
import VariablePicker from '../../VariablePicker.svelte'
|
||||
import { json } from 'svelte-highlight/languages'
|
||||
import { Highlight } from 'svelte-highlight'
|
||||
import JsonEditor from '$lib/components/JsonEditor.svelte'
|
||||
@@ -39,7 +38,6 @@
|
||||
import SimpleEditor from '$lib/components/SimpleEditor.svelte'
|
||||
import { isCloudHosted } from '$lib/cloud'
|
||||
import ResourcePicker from '$lib/components/ResourcePicker.svelte'
|
||||
import ItemPicker from '../../ItemPicker.svelte'
|
||||
import { Popover } from '$lib/components/meltComponents'
|
||||
import {
|
||||
HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING,
|
||||
@@ -174,8 +172,7 @@
|
||||
// Component references
|
||||
let s3FilePicker = $state<S3FilePicker | undefined>(undefined)
|
||||
let s3Editor = $state<SimpleEditor | undefined>(undefined)
|
||||
let variablePicker = $state<ItemPicker | undefined>(undefined)
|
||||
let variableEditor = $state<VariableEditor | undefined>(undefined)
|
||||
let variablePicker = $state<VariablePicker | undefined>(undefined)
|
||||
let drawer = $state<Drawer | undefined>(undefined)
|
||||
let initialConfig: NewHttpTrigger | undefined = undefined
|
||||
let deploymentLoading = $state(false)
|
||||
@@ -231,10 +228,6 @@
|
||||
resource_type?: string
|
||||
}
|
||||
|
||||
async function loadVariables() {
|
||||
return await VariableService.listVariable({ workspace: wsId ?? '' })
|
||||
}
|
||||
|
||||
const authentication_options: AuthenticationOption[] = [
|
||||
{
|
||||
label: 'No Auth',
|
||||
@@ -1136,32 +1129,11 @@
|
||||
</Section>
|
||||
{/if}
|
||||
|
||||
<ItemPicker
|
||||
<VariablePicker
|
||||
editable
|
||||
bind:this={variablePicker}
|
||||
pickCallback={(path, _) => {
|
||||
workspace={wsId}
|
||||
onPick={(path) => {
|
||||
variable_path = path
|
||||
}}
|
||||
tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow."
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets"
|
||||
itemName="Variable"
|
||||
extraField="path"
|
||||
loadItems={loadVariables}
|
||||
buttons={{ 'Edit/View': (x) => variableEditor?.editVariable(x) }}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<div class="flex flex-row">
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
startIcon={{ icon: Plus }}
|
||||
on:click={() => {
|
||||
variableEditor?.initNew()
|
||||
}}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
|
||||
<VariableEditor bind:this={variableEditor} on:create={(e) => variablePicker?.openDrawer()} />
|
||||
/>
|
||||
|
||||
@@ -5,14 +5,13 @@
|
||||
import { emptyStringTrimmed } from '$lib/utils'
|
||||
import TestTriggerConnection from '../TestTriggerConnection.svelte'
|
||||
import Subsection from '$lib/components/Subsection.svelte'
|
||||
import { Plus } from 'lucide-svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ArgInput from '$lib/components/ArgInput.svelte'
|
||||
import ItemPicker from '$lib/components/ItemPicker.svelte'
|
||||
import VariableEditor from '$lib/components/VariableEditor.svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import { VariableService, type AwsAuthResourceType } from '$lib/gen'
|
||||
import type ItemPicker from '$lib/components/ItemPicker.svelte'
|
||||
import type VariableEditor from '$lib/components/VariableEditor.svelte'
|
||||
import VariablePicker from '$lib/components/VariablePicker.svelte'
|
||||
import { type AwsAuthResourceType } from '$lib/gen'
|
||||
import TestingBadge from '../testingBadge.svelte'
|
||||
import MultiSelect from '$lib/components/select/MultiSelect.svelte'
|
||||
import { safeSelectItems } from '$lib/components/select/utils.svelte'
|
||||
@@ -42,9 +41,6 @@
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
const wsId = $derived($operatingWorkspace)
|
||||
|
||||
async function loadVariables() {
|
||||
return await VariableService.listVariable({ workspace: wsId ?? '' })
|
||||
}
|
||||
let itemPicker: ItemPicker | undefined = $state()
|
||||
let variableEditor: VariableEditor | undefined = $state()
|
||||
let cached: string[] = $state([])
|
||||
@@ -169,32 +165,12 @@
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<ItemPicker
|
||||
bind:this={itemPicker}
|
||||
pickCallback={(path, _) => {
|
||||
<VariablePicker
|
||||
editable
|
||||
bind:itemPicker
|
||||
bind:variableEditor
|
||||
workspace={wsId}
|
||||
onPick={(path) => {
|
||||
queue_url = '$var:' + path
|
||||
}}
|
||||
tooltip="Variables are dynamic values that have a key associated to them and can be retrieved during the execution of a Script or Flow."
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/variables_and_secrets"
|
||||
itemName="Variable"
|
||||
extraField="path"
|
||||
loadItems={loadVariables}
|
||||
buttons={{ 'Edit/View': (x) => variableEditor?.editVariable(x) }}
|
||||
>
|
||||
{#snippet submission()}
|
||||
<div class="flex flex-row">
|
||||
<Button
|
||||
variant="accent"
|
||||
size="sm"
|
||||
startIcon={{ icon: Plus }}
|
||||
on:click={() => {
|
||||
variableEditor?.initNew()
|
||||
}}
|
||||
>
|
||||
New variable
|
||||
</Button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</ItemPicker>
|
||||
|
||||
<VariableEditor bind:this={variableEditor} workspace={wsId} on:create={itemPicker.openDrawer} />
|
||||
/>
|
||||
|
||||
@@ -202,6 +202,7 @@
|
||||
{path}
|
||||
runnables={(app.value?.runnables ?? {}) as Record<string, Runnable>}
|
||||
oniframe={onIframe}
|
||||
ownsPageUrl={false}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -27,6 +27,18 @@ export function readSessionHint(cookies?: string): string | undefined {
|
||||
// it renders as. Another tab logging in swaps the session under this one, whose user stays
|
||||
// the old one until its next `whoami`: until then, nothing may be read or written as them.
|
||||
let confirmedHint: string | undefined
|
||||
const confirmationListeners = new Set<() => void>()
|
||||
|
||||
function setConfirmedHint(hint: string | undefined) {
|
||||
if (hint === confirmedHint) return
|
||||
confirmedHint = hint
|
||||
for (const cb of confirmationListeners) cb()
|
||||
}
|
||||
|
||||
/** Called whenever the session this tab's user is confirmed under changes. */
|
||||
export function onSessionConfirmationChange(cb: () => void): void {
|
||||
confirmationListeners.add(cb)
|
||||
}
|
||||
|
||||
/** Whether the session the browser holds is still the one this tab's user was confirmed under. */
|
||||
export function sessionStillConfirmed(): boolean {
|
||||
@@ -50,7 +62,7 @@ function currentLastUser(): UserExt | undefined {
|
||||
export function optimisticUser(workspace: string): UserExt | undefined {
|
||||
const user = currentLastUser()
|
||||
if (user?.workspace_id !== workspace) return undefined
|
||||
confirmedHint = readSessionHint()
|
||||
setConfirmedHint(readSessionHint())
|
||||
return user
|
||||
}
|
||||
|
||||
@@ -68,7 +80,7 @@ export function rememberUser(user: UserExt, sentWith: string | undefined): void
|
||||
try {
|
||||
const hint = readSessionHint()
|
||||
// Who answered is only known for the session the request went out with.
|
||||
confirmedHint = hint === sentWith ? hint : undefined
|
||||
setConfirmedHint(hint === sentWith ? hint : undefined)
|
||||
if (hint && hint === sentWith)
|
||||
localStorage.setItem(KEY, JSON.stringify({ hint, user } satisfies LastSession))
|
||||
else localStorage.removeItem(KEY)
|
||||
@@ -76,7 +88,7 @@ export function rememberUser(user: UserExt, sentWith: string | undefined): void
|
||||
}
|
||||
|
||||
export function forgetLastSession(): void {
|
||||
confirmedHint = undefined
|
||||
setConfirmedHint(undefined)
|
||||
try {
|
||||
localStorage.removeItem(KEY)
|
||||
} catch {}
|
||||
|
||||
@@ -6,7 +6,11 @@ import { OpenAPI } from '$lib/gen'
|
||||
import { userStore } from '$lib/stores'
|
||||
import { userScopedDb } from '$lib/userScopedDb'
|
||||
import { getCurrentUserEmail, onUserChange } from '$lib/userScopedStorage'
|
||||
import { rememberedEmail, sessionStillConfirmed } from '$lib/lastSession'
|
||||
import {
|
||||
onSessionConfirmationChange,
|
||||
rememberedEmail,
|
||||
sessionStillConfirmed
|
||||
} from '$lib/lastSession'
|
||||
|
||||
// Last-known API responses, kept so a page can paint them before its requests return. Every
|
||||
// row in them was filtered by row-level security for one user, so an entry is only ever served
|
||||
@@ -284,7 +288,9 @@ if (BROWSER) {
|
||||
readSnapshot()
|
||||
// Loads the whole (bounded) store into memory once the user is known, and keeps only what
|
||||
// belongs to them: the snapshot's entries for the same identity survive.
|
||||
onUserChange(() => {
|
||||
// The identity is known once both the user and the session they hold are: either can come
|
||||
// second, and a key derived before must follow.
|
||||
const onIdentityChange = () => {
|
||||
userTick++
|
||||
// No user yet (the call at registration, as the app boots): nothing can be read without
|
||||
// an identity, and the snapshot just loaded is waiting for its user. Logout clears memory
|
||||
@@ -294,5 +300,7 @@ if (BROWSER) {
|
||||
const mine = `[${JSON.stringify(identity)},`
|
||||
for (const key of [...memory.keys()]) if (!key.startsWith(mine)) memory.delete(key)
|
||||
void hydrate()
|
||||
})
|
||||
}
|
||||
onUserChange(onIdentityChange)
|
||||
onSessionConfirmationChange(onIdentityChange)
|
||||
}
|
||||
|
||||
@@ -67,7 +67,11 @@ export function persistedResource<A, T>(
|
||||
let latest = 0
|
||||
let inFlight = $state(false)
|
||||
let error = $state<unknown>(undefined)
|
||||
const res = resource<A, Tagged<T>>(source, async (args) => {
|
||||
// The identity is a source too: a response is tagged with the keys of its request, and once
|
||||
// the identity changes no response tagged before matches the keys shown, so without a new
|
||||
// request nothing would be shown until the arguments next change.
|
||||
const sourceWithIdentity = () => ({ args: source(), identity: cacheIdentity() })
|
||||
const res = resource(sourceWithIdentity, async ({ args }): Promise<Tagged<T>> => {
|
||||
const id = ++latest
|
||||
inFlight = true
|
||||
try {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount, untrack } from 'svelte'
|
||||
import { SvelteSet } from 'svelte/reactivity'
|
||||
import { MediaQuery, SvelteSet } from 'svelte/reactivity'
|
||||
import { page } from '$app/state'
|
||||
import {
|
||||
Plus,
|
||||
@@ -438,7 +438,19 @@
|
||||
// pickers at once.
|
||||
let emptyStateNewTabOpen = $state(false)
|
||||
|
||||
let fullscreen = $state(false)
|
||||
// Collapse the preview panel to give the chat the full width. Per-session and
|
||||
// owned by the runtime's previewTabs (restored on switch, written back on
|
||||
// toggle) so it survives session switches with the rest of the tab model.
|
||||
const previewCollapsed = $derived(owner?.collapsed ?? false)
|
||||
|
||||
let fullscreenToggled = $state(false)
|
||||
// Below `sm` the row is too narrow for both panes: the chat's 25% minimum leaves it under
|
||||
// 100px, where messages wrap a character per line. An open panel is full screen there.
|
||||
const narrowScreen = new MediaQuery('(max-width: 639px)')
|
||||
const fullscreen = $derived(fullscreenToggled || (narrowScreen.current && !previewCollapsed))
|
||||
// The band's last breadcrumb stage alone fills a phone's width, leaving the strip and controls
|
||||
// no room there, so a narrow panel keeps them in its own card.
|
||||
const bandFullscreen = $derived(fullscreen && !narrowScreen.current)
|
||||
|
||||
// Going full screen is the preview panel expanding to the left: the chat column shrinks to
|
||||
// nothing and the panel takes its place. Animating that is what carries the switch, so the
|
||||
@@ -451,7 +463,7 @@
|
||||
let panesAnimating = $state(false)
|
||||
let panesAnimationTimer: ReturnType<typeof setTimeout> | undefined = undefined
|
||||
function toggleFullscreen() {
|
||||
fullscreen = !fullscreen
|
||||
fullscreenToggled = !fullscreenToggled
|
||||
if (reducedMotion.val) return
|
||||
panesAnimating = true
|
||||
clearTimeout(panesAnimationTimer)
|
||||
@@ -494,10 +506,6 @@
|
||||
$effect(() => {
|
||||
owner?.setFullscreen(fullscreen)
|
||||
})
|
||||
// Collapse the preview panel to give the chat the full width. Per-session and
|
||||
// owned by the runtime's previewTabs (restored on switch, written back on
|
||||
// toggle) so it survives session switches with the rest of the tab model.
|
||||
const previewCollapsed = $derived(owner?.collapsed ?? false)
|
||||
|
||||
// Collapse works by resizing the preview pane to zero, never unmounting it:
|
||||
// the pane hosts every warm session's preview tabs, and unmounting would
|
||||
@@ -974,12 +982,12 @@
|
||||
so from then on the name comes from there, with its pen and its menu. -->
|
||||
<PageHeaderContent
|
||||
barRightInset={bandInset}
|
||||
section={fullscreen
|
||||
section={bandFullscreen
|
||||
? { label: activeSession?.summary ?? 'Untitled session', noNavPicker: true }
|
||||
: undefined}
|
||||
actions={fullscreen ? fullscreenBand : sessionPageActions}
|
||||
actionsFill={fullscreen}
|
||||
separator={fullscreen ? 'always' : 'none'}
|
||||
actions={bandFullscreen ? fullscreenBand : sessionPageActions}
|
||||
actionsFill={bandFullscreen}
|
||||
separator={bandFullscreen ? 'always' : 'none'}
|
||||
/>
|
||||
|
||||
{#snippet fullscreenBand()}
|
||||
@@ -1002,15 +1010,27 @@
|
||||
{#if previewCollapsed && !fullscreen}
|
||||
<!-- Collapsed preview: the way back to the side panel, in the band with the session's own
|
||||
controls rather than floating over the chat. -->
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: PanelRightOpen }}
|
||||
title="Open side panel"
|
||||
onclick={() => owner?.setCollapsed(false)}
|
||||
>
|
||||
Open side panel
|
||||
</Button>
|
||||
<span class="sm:hidden">
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: PanelRightOpen }}
|
||||
title="Open side panel"
|
||||
onclick={() => owner?.setCollapsed(false)}
|
||||
/>
|
||||
</span>
|
||||
<span class="hidden sm:inline-flex">
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: PanelRightOpen }}
|
||||
title="Open side panel"
|
||||
onclick={() => owner?.setCollapsed(false)}
|
||||
>
|
||||
Open side panel
|
||||
</Button>
|
||||
</span>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
@@ -1129,7 +1149,11 @@
|
||||
panelShare = w / contentWidth
|
||||
}
|
||||
}
|
||||
class="flex-1 min-h-0 flex flex-col {fullscreen ? `p-0 ${BAR_TOP_PAD}` : 'p-2 pl-0'}"
|
||||
class="flex-1 min-h-0 flex flex-col {bandFullscreen
|
||||
? `p-0 ${BAR_TOP_PAD}`
|
||||
: fullscreen
|
||||
? `px-2 pb-2 ${BAR_TOP_PAD}`
|
||||
: 'p-2 pl-0'}"
|
||||
>
|
||||
<!-- The action controls float over the tab strip, so the strip has to reserve
|
||||
their width or tabs slide underneath them. Measured rather than guessed:
|
||||
@@ -1137,17 +1161,21 @@
|
||||
page has no View|Edit toggle), so a fixed padding is either short for
|
||||
the widest case or wasted space for the narrowest. -->
|
||||
<div
|
||||
class="flex flex-col flex-1 min-h-0 overflow-hidden relative bg-surface {fullscreen
|
||||
class="flex flex-col flex-1 min-h-0 overflow-hidden relative bg-surface {bandFullscreen
|
||||
? ''
|
||||
: 'rounded-md border border-light'}"
|
||||
style="--preview-actions-w: {previewActionsWidth + 8}px"
|
||||
>
|
||||
{#if !fullscreen}
|
||||
{#if !bandFullscreen}
|
||||
<!-- Collapse the preview panel — floats over the top-left corner so
|
||||
the tab strip keeps the full width. -->
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => owner?.setCollapsed(true)}
|
||||
onclick={() => {
|
||||
// Full screen toggled on a wide window outlives a narrowing one.
|
||||
fullscreenToggled = false
|
||||
owner?.setCollapsed(true)
|
||||
}}
|
||||
title="Collapse preview"
|
||||
aria-label="Collapse preview"
|
||||
class="absolute top-1 left-1 z-30 inline-flex items-center justify-center w-6 h-6 rounded text-tertiary hover:text-primary hover:bg-surface-hover"
|
||||
@@ -1159,7 +1187,7 @@
|
||||
<!-- In full screen the strip and these controls move into the page header band,
|
||||
which is empty there and has the width for them; the pane below keeps only
|
||||
the content. -->
|
||||
{#if !fullscreen}
|
||||
{#if !bandFullscreen}
|
||||
<!-- Open-in-full-page + full-screen toggle, floating over the top-right
|
||||
corner to mirror the collapse control. Its width is measured so the strip
|
||||
can reserve room and its tabs never scroll underneath. -->
|
||||
@@ -1291,7 +1319,9 @@
|
||||
<ExternalLink size={14} />
|
||||
</a>
|
||||
{/if}
|
||||
{#if fullscreen}
|
||||
{#if narrowScreen.current}
|
||||
<!-- Full screen is automatic there; the card's collapse button leads back to the chat. -->
|
||||
{:else if fullscreen}
|
||||
<!-- Named rather than an icon alone: full screen hid the chat, and what the user wants back
|
||||
is the chat, not a window size. The band has the room for the word. -->
|
||||
<button
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ArtifactBody from '$lib/components/copilot/chat/artifacts/ArtifactBody.svelte'
|
||||
import ArtifactExportButton from '$lib/components/copilot/chat/artifacts/ArtifactExportButton.svelte'
|
||||
import MermaidCodeBlock from '$lib/components/copilot/chat/artifacts/MermaidCodeBlock.svelte'
|
||||
import { AiService } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
@@ -123,7 +124,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-auto rounded-md bg-surface-tertiary px-8">
|
||||
<ArtifactBody content={artifact.content} {source} />
|
||||
<ArtifactBody content={artifact.content} {source} pre={MermaidCodeBlock} />
|
||||
</div>
|
||||
{:else if shared.current?.state === 'gone'}
|
||||
<EmptyState
|
||||
|
||||
@@ -34,10 +34,19 @@ export async function onRequest(context) {
|
||||
// `windmill.dev`) does not match this host, and a browser drops a cookie whose Domain
|
||||
// does not match. Reading them joined (`headers.get`) would merge the session cookie with
|
||||
// the `wm_session` hint set beside it, Domain included.
|
||||
const setCookies = res.headers.getSetCookie();
|
||||
newResponse.headers.delete("set-cookie");
|
||||
for (const c of setCookies) {
|
||||
newResponse.headers.append("set-cookie", c.replace(/;\s*Domain=[^;]*/gi, ""));
|
||||
// Pages runs without a compatibility date, where `getSetCookie` does not exist; its
|
||||
// `getAll` returns the same list there, and only for `set-cookie`.
|
||||
const setCookies: string[] | undefined =
|
||||
typeof res.headers.getSetCookie === "function"
|
||||
? res.headers.getSetCookie()
|
||||
: typeof res.headers.getAll === "function"
|
||||
? res.headers.getAll("set-cookie")
|
||||
: undefined;
|
||||
if (setCookies) {
|
||||
newResponse.headers.delete("set-cookie");
|
||||
for (const c of setCookies) {
|
||||
newResponse.headers.append("set-cookie", c.replace(/;\s*Domain=[^;]*/gi, ""));
|
||||
}
|
||||
}
|
||||
|
||||
newResponse.headers.set("Cross-Origin-Resource-Policy", "cross-origin");
|
||||
|
||||
@@ -1107,6 +1107,8 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! }
|
||||
|
||||
**Set the browser tab title with \`document.title = '...'\`** (or a \`<title>\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes.
|
||||
|
||||
**Read the page's context from \`window.ctx\`**: \`ctx\` is the viewer (absent for anonymous visitors), \`workspace\` and \`path\` the app's (\`path\` is not set under \`wmill app dev\`), and \`query\` the page URL's query parameters as strings (\`…/apps/get/u/me/app?customer=42\` gives \`window.ctx.query.customer === '42'\`, and no query gives \`{}\`). Read it there, not from \`window.location\`, which in a sandboxed app is not the page's address. It is read once when the app loads.
|
||||
|
||||
**Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen.
|
||||
|
||||
### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`)
|
||||
|
||||
@@ -313,6 +313,8 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.
|
||||
|
||||
**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.
|
||||
|
||||
**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.
|
||||
|
||||
**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.
|
||||
|
||||
### Generated bindings (`wmill.d.ts` / `wmill.ts`)
|
||||
|
||||
@@ -72,6 +72,8 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.
|
||||
|
||||
**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes.
|
||||
|
||||
**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.
|
||||
|
||||
**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.
|
||||
|
||||
### Generated bindings (`wmill.d.ts` / `wmill.ts`)
|
||||
|
||||
Reference in New Issue
Block a user