From c3112f8e0757a7bb240a249d3f154e529347eb62 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Tue, 20 Oct 2026 10:26:00 +0200 Subject: [PATCH 001/101] add missing sqlx cache entry for the Slack disconnect query (#11892) Co-authored-by: Claude Opus 5.5 --- ...bb3c369ebb8bf60963283640e02e03a1af42af2782.json | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 backend/.sqlx/query-907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782.json diff --git a/backend/.sqlx/query-907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782.json b/backend/.sqlx/query-907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782.json new file mode 100644 index 0000000000..97f3bd7567 --- /dev/null +++ b/backend/.sqlx/query-907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM slack_agent_channel WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "907f231497ac4889c23b84bb3c369ebb8bf60963283640e02e03a1af42af2782" +} From e6c8ef18a11f079083138a991543f7e273d4e511 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 20 Oct 2026 18:31:38 +0200 Subject: [PATCH 002/101] fix: write a push's runnable settings before it opens its transaction (#11897) Co-authored-by: Claude Opus 5.5 --- backend/tests/push_pool_connections.rs | 63 ++++++++++++++++++++++ backend/windmill-queue/src/jobs.rs | 72 ++++++++++++++++---------- 2 files changed, 109 insertions(+), 26 deletions(-) create mode 100644 backend/tests/push_pool_connections.rs diff --git a/backend/tests/push_pool_connections.rs b/backend/tests/push_pool_connections.rs new file mode 100644 index 0000000000..006340cf8a --- /dev/null +++ b/backend/tests/push_pool_connections.rs @@ -0,0 +1,63 @@ +//! `push` must not need a second pool connection while it holds its transaction: a burst of +//! pushes the size of the pool would each hold one and wait for another until the acquire +//! timeout. On a one-connection pool any such second checkout hangs. + +use std::time::Duration; + +use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; +use windmill_common::jobs::JobPayload; +use windmill_test_utils::RunJob; + +#[sqlx::test(fixtures("base"))] +async fn concurrency_limited_flow_pushes_on_one_connection(db: Pool) { + // The flow and settings caches outlive the test database (they are on disk), so only a + // version and a limit no run has used yet make `push` read the flow and write its settings. + let limit = (uuid::Uuid::new_v4().as_u128() % 1_000_000_000) as i32 + 1; + let version = limit as i64; + let value = format!(r#"{{"modules":[],"concurrent_limit":{limit}}}"#); + sqlx::query( + "WITH f AS ( + INSERT INTO flow (workspace_id, path, summary, description, value, edited_by, schema, extra_perms, versions) + VALUES ('test-workspace', 'f/t/limited', '', '', $1::jsonb, 'test-user', '{}', '{}', ARRAY[$2]) + ) + INSERT INTO flow_version (id, workspace_id, path, value, schema, created_by) + VALUES ($2, 'test-workspace', 'f/t/limited', $1::jsonb, '{}', 'test-user')", + ) + .bind(&value) + .bind(version) + .execute(&db) + .await + .unwrap(); + + let one = PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(Duration::from_secs(5)) + .connect_with((*db.connect_options()).clone()) + .await + .unwrap(); + + let push = RunJob::from(JobPayload::Flow { + path: "f/t/limited".to_string(), + dedicated_worker: None, + apply_preprocessor: false, + version, + labels: None, + job_token_scopes: None, + }) + .push(&one); + let job = tokio::time::timeout(Duration::from_secs(15), push) + .await + .unwrap(); + + let stored: Option = sqlx::query_scalar( + "SELECT cs.concurrent_limit FROM v2_job_queue q + JOIN runnable_settings rs ON rs.hash = q.runnable_settings_handle + JOIN concurrency_settings cs ON cs.hash = rs.concurrency_settings + WHERE q.id = $1", + ) + .bind(job) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored, Some(limit)); +} diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index eafb344870..1b35decd97 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -6200,6 +6200,38 @@ pub async fn push<'c, 'd>( .await } +/// Reads a flow version through the pool unless the caller handed `push` its own transaction, +/// which may hold that version uncommitted. Opening a transaction just for this read would hold +/// its connection while `push` still writes the runnable settings through the pool. +async fn fetch_pushed_flow_version( + tx: &mut PushIsolationLevel<'_>, + db: &Pool, + version: i64, +) -> error::Result> { + // Do not use the lite version unless all workers are updated. + let lite = + !(*DISABLE_FLOW_SCRIPT || (!MIN_VERSION_IS_AT_LEAST_1_432.met().await && !*CLOUD_HOSTED)); + // Fallback to the original version if the lite version is not found. + // This also prevent a race condition where the flow is run just after deploy and + // the lite version is still being created. + macro_rules! fetch { + ($e:expr) => { + if lite { + match cache::flow::fetch_version_lite($e, version).await { + Ok(data) => Ok(data), + Err(_) => cache::flow::fetch_version($e, version).await, + } + } else { + cache::flow::fetch_version($e, version).await + } + }; + } + match tx { + PushIsolationLevel::Transaction(ntx) => fetch!(&mut **ntx), + PushIsolationLevel::Isolated(..) | PushIsolationLevel::IsolatedRoot(_) => fetch!(db), + } +} + // #[instrument(level = "trace", skip_all)] async fn push_inner<'c, 'd>( db: &Pool, @@ -7078,22 +7110,7 @@ async fn push_inner<'c, 'd>( labels, job_token_scopes, } => { - let mut ntx = tx.into_tx().await?; - // Do not use the lite version unless all workers are updated. - let data = if *DISABLE_FLOW_SCRIPT - || (!MIN_VERSION_IS_AT_LEAST_1_432.met().await && !*CLOUD_HOSTED) - { - cache::flow::fetch_version(&mut *ntx, version).await - } else { - // Fallback to the original version if the lite version is not found. - // This also prevent a race condition where the flow is run just after deploy and - // the lite version is still being created. - match cache::flow::fetch_version_lite(&mut *ntx, version).await { - Ok(data) => Ok(data), - Err(_) => cache::flow::fetch_version(&mut *ntx, version).await, - } - }?; - tx = PushIsolationLevel::Transaction(ntx); + let data = fetch_pushed_flow_version(&mut tx, db, version).await?; let mut value = data.value().clone(); refuse_step_scopes_on_outdated_workers(&value).await?; @@ -7463,6 +7480,19 @@ async fn push_inner<'c, 'd>( crate::tags::apply_dev_workspace_suffix(tag, workspace_id, db).await? }; + // Before `into_tx`: these write through the pool on a cache miss, and a burst of pushes each + // holding its transaction would then wait on each other for a second connection. They stay + // off `tx` because they are cached as written, which a rollback would undo. + let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( + RunnableSettings { + debouncing_settings: debouncing_settings.insert_cached(db).await?, + concurrency_settings: concurrency_settings.insert_cached(db).await?, + retry_settings: retry_settings.insert_cached(db).await?, + }, + db, + ) + .await?; + let mut tx = tx.into_tx().await?; let job_id: Uuid = if let Some(job_id) = job_id { @@ -7642,16 +7672,6 @@ async fn push_inner<'c, 'd>( (job_kind, scheduled_for_o) }; - let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( - RunnableSettings { - debouncing_settings: debouncing_settings.insert_cached(db).await?, - concurrency_settings: concurrency_settings.insert_cached(db).await?, - retry_settings: retry_settings.insert_cached(db).await?, - }, - db, - ) - .await?; - let (guarded_concurrent_limit, guarded_concurrency_time_window_s) = if windmill_common::runnable_settings::min_version_supports_runnable_settings_v0().await { (None, None) From 394d345e0c8d9d7da87371e8da090d3becc77ce7 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Tue, 20 Oct 2026 19:07:36 +0200 Subject: [PATCH 003/101] fix: give the agent page's API and Slack sections tabs on small screens (#11901) * fix: give the agent page's API and Slack panel a tab on small screens Co-Authored-By: Claude Opus 5.5 * fix: keep the agent pane mounted across the small-screen breakpoint Co-Authored-By: Claude Opus 5.5 * fix: make the covered agent pane inert on the API tab Co-Authored-By: Claude Opus 5.5 * fix: flatten the agent page's API and Slack sections into its small-screen tabs Co-Authored-By: Claude Opus 5.5 * fix: fall back to the API tab when the agent has no Slack section Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../flows/content/AgentUsePanel.svelte | 13 +- .../agents/get/[...path]/+page.svelte | 142 +++++++++++------- 2 files changed, 98 insertions(+), 57 deletions(-) diff --git a/frontend/src/lib/components/flows/content/AgentUsePanel.svelte b/frontend/src/lib/components/flows/content/AgentUsePanel.svelte index 3f2c473937..83c8fe4217 100644 --- a/frontend/src/lib/components/flows/content/AgentUsePanel.svelte +++ b/frontend/src/lib/components/flows/content/AgentUsePanel.svelte @@ -41,7 +41,8 @@ runsAs, anyone, canShare, - channels + channels, + section }: { agentPath: string workspace: string @@ -65,10 +66,12 @@ /** Whether the user can change its Slack settings: anyone who can edit it. */ canShare: boolean channels: SlackAgentChannel[] + /** Shows only this section, without the panel's own tabs: the page offers them as its tabs. */ + section?: 'api' | 'slack' } = $props() let pickedTab = $state('api') - let tab = $derived(chat ? pickedTab : 'api') + let tab = $derived(section ?? (chat ? pickedTab : 'api')) let handle = $derived(`+${agentPath.split('/').pop()}`) let userSettings: UserSettings | undefined = $state(undefined) @@ -100,7 +103,11 @@ />
- tab, (t) => (pickedTab = t)} wrapperClass="flex-none w-full"> + tab, (t) => (pickedTab = t)} + hideTabs={section !== undefined} + wrapperClass="flex-none w-full" + > {#if chat} diff --git a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte index ed50528dbd..426f56c378 100644 --- a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte @@ -18,7 +18,7 @@ import AgentEditorHost from '$lib/components/flows/content/AgentEditorHost.svelte' import AgentConfigModal from '$lib/components/flows/content/AgentConfigModal.svelte' import RunForm from '$lib/components/RunForm.svelte' - import { Alert } from '$lib/components/common' + import { Alert, Tab, Tabs } from '$lib/components/common' import { keepsManagedMemory } from '$lib/components/flows/agentFormFields' import { agentMenuItems, deleteAgent } from '$lib/components/flows/agentActions' import AgentHistory from '$lib/components/flows/AgentHistory.svelte' @@ -49,6 +49,10 @@ let deleteOpen = $state(false) let evalsModal: AgentEvalsModal | undefined = $state(undefined) let clientWidth = $state(window.innerWidth) + let pickedMobileTab = $state('agent') + // The page is reused across agents, and an agent without managed memory has no Slack tab. + let mobileTab = $derived(pickedMobileTab === 'slack' && !chatAvailable ? 'api' : pickedMobileTab) + let wide = $derived(clientWidth >= 1024) const slack = resource( () => ({ workspace: ws, path }), @@ -62,7 +66,7 @@ // while the chat shows, and the chat's composer owns the key then. function onKeyDown(event: KeyboardEvent) { if (event.defaultPrevented || event.key !== 'Enter' || !(event.ctrlKey || event.metaKey)) return - if (!runForm || testPane?.mode === 'chat') return + if (!runForm || testPane?.mode === 'chat' || (!wide && mobileTab !== 'agent')) return if (isValid) { event.preventDefault() runForm.run() @@ -207,67 +211,97 @@ {/if} {/snippet} -
+ + {#if !wide && ws && config} + mobileTab, (t) => (pickedMobileTab = t)} + wrapperClass="flex-none no-scrollbar" + > + + + {#if chatAvailable} + + {/if} + + {/if} +
- - {#key `${ws}:${path}:${reloaded}`} - configModal?.open()} - > - {#snippet viewForm({ schema, run, loading, actions })} - {#if config && !chatAvailable} - - Each run is answered on its own inputs, so this agent has no chat. That suits - reusing it as a step in a flow.{canEdit - ? ' Turn on managed memory in its configuration to chat with it.' - : ''} - - {/if} - - {/snippet} - - {/key} + +
+ {@render agentPane()} +
- - {#if ws && config && clientWidth >= 1024} + {#if wide && ws && config} - + {@render usePane(ws)} {/if}
+ {#if !wide && ws && config} +
+ {@render usePane(ws, mobileTab === 'slack' ? 'slack' : 'api')} +
+ {/if}
+{#snippet agentPane()} + {#key `${ws}:${path}:${reloaded}`} + configModal?.open()} + > + {#snippet viewForm({ schema, run, loading, actions })} + {#if config && !chatAvailable} + + Each run is answered on its own inputs, so this agent has no chat. That suits reusing it + as a step in a flow.{canEdit + ? ' Turn on managed memory in its configuration to chat with it.' + : ''} + + {/if} + + {/snippet} + + {/key} +{/snippet} + +{#snippet usePane(ws: string, section?: 'api' | 'slack')} + +{/snippet} + {#if ws} {/if} From 613adb5287812cf428a74b10e1ef9362d78751b8 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Tue, 20 Oct 2026 19:09:41 +0200 Subject: [PATCH 004/101] perf: show the AI sessions composer before the chat code loads (#11886) * perf: show the AI sessions composer before the chat code loads Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep the composer placeholder's focus, IME input and draft through the swap Co-Authored-By: Claude Opus 5.5 (1M context) * fix: drop the composer focus hand-off when the session goes inactive Co-Authored-By: Claude Opus 5.5 (1M context) * fix: let an explicit composer focus request override a left placeholder Co-Authored-By: Claude Opus 5.5 (1M context) * chore: update ee-repo-ref to dd0c7087f9b2453260f3d73b0d589042b4393a1d This commit updates the EE repository reference after PR #900 was merged in windmill-ee-private. Previous ee-repo-ref: e922599943c472a6d0f736f629ae04081f866686 New ee-repo-ref: dd0c7087f9b2453260f3d73b0d589042b4393a1d Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: windmill-internal-app[bot] --- .../lib/components/copilot/chat/AIChat.svelte | 11 +- .../copilot/chat/AIChatDisplay.svelte | 5 +- .../copilot/chat/AIChatInput.svelte | 54 ++----- .../copilot/chat/ComposerPlaceholder.svelte | 93 +++++++++++ .../copilot/chat/ContextTextarea.svelte | 7 +- .../copilot/chat/JobsSegment.svelte | 24 ++- .../components/copilot/chat/composerBox.ts | 44 ++++++ .../components/sessions/SessionWrapper.svelte | 145 +++++++++++++++--- .../src/lib/utils/preloadComponent.svelte.ts | 19 +++ .../(root)/(logged)/sessions/+page.svelte | 65 +++++--- 10 files changed, 367 insertions(+), 100 deletions(-) create mode 100644 frontend/src/lib/components/copilot/chat/ComposerPlaceholder.svelte create mode 100644 frontend/src/lib/utils/preloadComponent.svelte.ts diff --git a/frontend/src/lib/components/copilot/chat/AIChat.svelte b/frontend/src/lib/components/copilot/chat/AIChat.svelte index 301a8dba54..129faa9f01 100644 --- a/frontend/src/lib/components/copilot/chat/AIChat.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChat.svelte @@ -10,6 +10,7 @@ import HideButton from '$lib/components/apps/editor/settingsPanel/HideButton.svelte' import { SUPPORTED_CHAT_SCRIPT_LANGUAGES } from './script/core' import { copilotInfo } from '$lib/aiStore' + import type { ComposerSelection } from './composerBox' let { hideHeader = false, @@ -20,7 +21,8 @@ emptyHint, inputPreface, initialInstructions = undefined, - onDraftChange = undefined + onDraftChange = undefined, + placeholder = undefined }: { hideHeader?: boolean hideModeSelector?: boolean @@ -39,6 +41,8 @@ // Seed / observe the composer's draft text (forwarded to AIChatDisplay). initialInstructions?: string onDraftChange?: (text: string) => void + /** Composer placeholder for the first message. Falls back to the per-AI-mode wording. */ + placeholder?: string } = $props() const isAdmin = $derived($userStore?.is_admin || $userStore?.is_super_admin) @@ -106,8 +110,8 @@ aiChatManager.sendRequest(options) } - export function focusInput() { - aiChatDisplay?.focusInput() + export function focusInput(selection?: ComposerSelection) { + aiChatDisplay?.focusInput(selection) } const historyManager = aiChatManager.historyManager @@ -201,4 +205,5 @@ {inputPreface} {initialInstructions} {onDraftChange} + {placeholder} > diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index b233728a19..845126b4ef 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -53,6 +53,7 @@ import ToolGroupDisplay from './ToolGroupDisplay.svelte' import { chatItemKey, groupToolRuns } from './toolGroups' import AIChatInput from './AIChatInput.svelte' + import type { ComposerSelection } from './composerBox' import AttachedFilesBar from './files/AttachedFilesBar.svelte' import QueuedMessageChip from './QueuedMessageChip.svelte' import JobsSegment from './JobsSegment.svelte' @@ -357,8 +358,8 @@ chatHost.sendRequest({ instructions: suggestion }) } - export function focusInput() { - aiChatInput?.focusInput() + export function focusInput(selection?: ComposerSelection) { + aiChatInput?.focusInput(selection) } $effect(() => { diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index 41ea788fac..cd95da5a88 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -13,7 +13,12 @@ import { AIMode } from './AIChatManager.svelte' import { CHAT_INPUT_PADDING, getAiChatManager } from './aiChatManagerContext' import { getChatViewHost } from './chatViewHost' - import { composerBoxClass, COMPOSER_FIELD_RESET } from './composerBox' + import { + composerBoxClass, + COMPOSER_FIELD_RESET, + globalComposerSuggestion, + type ComposerSelection + } from './composerBox' import { formatMention, hasMention, removeMentionFromText } from './mention' import { twMerge } from 'tailwind-merge' import { tick, untrack, type Snippet } from 'svelte' @@ -119,44 +124,12 @@ pendingQuestionToolCallId = undefined }: Props = $props() - // GLOBAL-mode suggestion pool. We pick one at mount-time so each new - // session lands on a different prompt; the choice stays stable for - // the lifetime of this input so the placeholder doesn't shuffle as - // the user is reading it. - const GLOBAL_PLACEHOLDER_SUGGESTIONS = [ - 'Write a hello-world flow', - 'Create a script that lists files in an S3 bucket', - 'Build a CRUD app for a customer table', - 'Schedule a daily cleanup of old runs', - 'Wrap an existing script into a flow with retries', - 'Add an HTTP trigger to an existing script', - 'Generate a report from a SQL query and email it', - 'Create a Postgres resource and a script that queries it', - 'Refactor a script to add error handling', - 'List my workspace flows and scripts' - ] - // An operator authors nothing, so nothing above is theirs to ask for; one with the - // workspace's builder right can compose flows out of deployed scripts as well. - const OPERATOR_PLACEHOLDER_SUGGESTIONS = [ - 'List my workspace flows and scripts', - 'Show the runs that failed today and why', - 'Find the script that sends a report and run it', - 'Rerun the last failed run of a flow' - ] - const BUILDER_PLACEHOLDER_SUGGESTIONS = [ - ...OPERATOR_PLACEHOLDER_SUGGESTIONS, - 'Compose a flow that chains two deployed scripts' - ] + // Picked at mount-time so each new session lands on a different prompt. const permissions = useSessionPermissions(() => chatHost.operatingWorkspace) const suggestionPick = Math.random() - const globalSuggestion = $derived.by(() => { - const pool = permissions.canOpenEditor('script') - ? GLOBAL_PLACEHOLDER_SUGGESTIONS - : permissions.canOpenEditor('flow') - ? BUILDER_PLACEHOLDER_SUGGESTIONS - : OPERATOR_PLACEHOLDER_SUGGESTIONS - return pool[Math.floor(suggestionPick * pool.length)] - }) + const globalSuggestion = $derived( + globalComposerSuggestion(suggestionPick, permissions.canOpenEditor) + ) // Generate mode-specific placeholder const modePlaceholder = $derived.by(() => { @@ -636,11 +609,14 @@ draft.text = removeMentionFromText(draft.text, title) } - export function focusInput() { + export function focusInput(selection?: ComposerSelection) { if (isContextEnabledMode) { - contextTextareaComponent?.focus() + contextTextareaComponent?.focus(selection) } else { instructionsTextareaComponent?.focus() + if (selection) { + instructionsTextareaComponent?.setSelectionRange(selection.start, selection.end) + } } } diff --git a/frontend/src/lib/components/copilot/chat/ComposerPlaceholder.svelte b/frontend/src/lib/components/copilot/chat/ComposerPlaceholder.svelte new file mode 100644 index 0000000000..17c95086ca --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/ComposerPlaceholder.svelte @@ -0,0 +1,93 @@ + + +
+
+
+ + +
+
+
+
+
diff --git a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte index dd3a011da2..c80e9113df 100644 --- a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte +++ b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte @@ -1,5 +1,5 @@ + + (typedEmail = '')}> @@ -157,6 +171,18 @@ {#snippet content()}
Add a new user +
+ +
{#if isServiceAccount} Username @@ -217,38 +243,12 @@ {/if} {/if} - Role - - {#snippet children({ item })} - - - - - {/snippet} - - - {#if isServiceAccount} + {#if !isServiceAccount} + Role +
+ (picked = v)} /> +
+ {:else} Service account role {#snippet children({ item })} diff --git a/frontend/src/lib/components/CompareDrafts.svelte b/frontend/src/lib/components/CompareDrafts.svelte index a05511ea42..976f82c382 100644 --- a/frontend/src/lib/components/CompareDrafts.svelte +++ b/frontend/src/lib/components/CompareDrafts.svelte @@ -34,6 +34,7 @@ } from '$lib/workspaceDrafts.svelte' import type { Kind as LayoutKind } from '$lib/utils_deployable' import { userStore, userWorkspaces } from '$lib/stores' + import { capabilitiesIn } from '$lib/roleCapabilities' import { childWorkspaceNoun } from '$lib/utils/devWorkspaceLabel' interface Props { @@ -329,7 +330,12 @@ workspaceDeployPerm, visibleItems .filter((i) => selectedItems.includes(i.key) && isDeployable(i)) - .map((i) => i.draftKind) + .map((i) => i.draftKind), + capabilitiesIn( + // Superadmin is global; a workspace's admin flag is not. + { is_super_admin: $userStore?.is_super_admin }, + $userWorkspaces.find((w) => w.id === currentWorkspaceId) + ) ) ) // Select all on the first non-empty load (acting on everything is the common diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 5a22ed012d..1c718287fc 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -37,6 +37,7 @@ import WorkspaceDeployItemSummary from './WorkspaceDeployItemSummary.svelte' import ParentWorkspaceProtectionAlert from './ParentWorkspaceProtectionAlert.svelte' import { userWorkspaces, workspaceStore } from '$lib/stores' + import { capabilitiesIn } from '$lib/roleCapabilities' import type { Kind } from '$lib/utils_deployable' import { @@ -1090,7 +1091,12 @@ workspaceDeployPerm, (comparison?.diffs ?? []) .filter((d) => selectedItems.includes(getItemKey(d))) - .map((d) => d.kind) + .map((d) => d.kind), + capabilitiesIn( + // Superadmin is global; a workspace's admin flag is not. + { is_super_admin: $userStore?.is_super_admin }, + $userWorkspaces.find((w) => w.id == deployTargetWorkspace) + ) ) ) diff --git a/frontend/src/lib/components/DraftBadge.svelte b/frontend/src/lib/components/DraftBadge.svelte index 22f7c4e55a..4d21e81b29 100644 --- a/frontend/src/lib/components/DraftBadge.svelte +++ b/frontend/src/lib/components/DraftBadge.svelte @@ -18,7 +18,8 @@ import { goto } from '$lib/navigation' import { OtherUserDraftLoad, editRouteFor } from '$lib/components/otherUserDraftLoad.svelte' import { fetchDeployedValueForDiff } from '$lib/components/otherUserDraftDiff' - import { userStore } from '$lib/stores' + import { roleCapabilities, userStore } from '$lib/stores' + import { roleCanAuthor } from '$lib/editRights' type DraftUser = { username?: string | null } @@ -116,6 +117,10 @@ // Inline actions need full context to fetch and fork drafts. const actionsEnabled = $derived(!!workspace && !!itemKind && !!path && draft_users.length > 0) + // The editors these open are the full ones, which a role without code cannot use. + const canOpenEditor = $derived( + !!itemKind && $roleCapabilities.code && roleCanAuthor(itemKind, $roleCapabilities) + ) const kindLabel = $derived( itemKind === 'flow' ? 'flow' : itemKind === 'app' || itemKind === 'raw_app' ? 'app' : 'script' @@ -303,7 +308,7 @@ {#if actionsEnabled && isSelf} - {#if !$userStore?.operator && itemKind && path} + {#if canOpenEditor && itemKind && path}
diff --git a/frontend/src/lib/components/ForkWorkspaceBanner.svelte b/frontend/src/lib/components/ForkWorkspaceBanner.svelte index 11779afb11..1736520eed 100644 --- a/frontend/src/lib/components/ForkWorkspaceBanner.svelte +++ b/frontend/src/lib/components/ForkWorkspaceBanner.svelte @@ -3,7 +3,13 @@ import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import { Badge } from './common' import { AlertTriangle, ArrowDown, ArrowUp, Pencil } from 'lucide-svelte' - import { workspaceStore, userWorkspaces, userStore, type UserExt } from '$lib/stores' + import { + roleCapabilities, + workspaceStore, + userWorkspaces, + userStore, + type UserExt + } from '$lib/stores' import type { WorkspaceComparison } from '$lib/gen' import { fetchWorkspaceComparison } from '$lib/workspaceComparison' import { Button } from './common' @@ -27,18 +33,18 @@ // prefix) also avoids a parentless "Fork of ()" banner when the linkage is dropped. let isFork = $derived(parentWorkspaceId != null) let currentNoun = $derived(childWorkspaceNoun(currentWorkspaceData)) - // Operators run scripts and flows, they never deploy a fork, so the banner and - // its CTA are noise for them. Gates the fetches too, not just the markup: the - // fork/parent comparison is an expensive tally no operator can act on. + // A role without `code` never deploys a fork, so the banner and its CTA are noise + // for it. Gates the fetches too, not just the markup: the fork/parent comparison + // is an expensive tally such a role cannot act on. // - // Only a role fetched for the workspace we are on answers this. `$workspaceStore` + // Only a user fetched for the workspace we are on answers this. `$workspaceStore` // flips synchronously on a switch while `$userStore` still holds the workspace we // left, so trusting it unqualified would flash the banner at (and start the tally - // for) an operator entering a fork from a workspace where they are not one. - function isConfirmedNonOperator(user: UserExt | undefined, ws: string | undefined): boolean { - return !!user && !!ws && user.workspace_id === ws && !user.operator + // for) a restricted member entering a fork from a workspace where they are not one. + function isUserFor(user: UserExt | undefined, ws: string | undefined): boolean { + return !!user && !!ws && user.workspace_id === ws } - let isNotOperator = $derived(isConfirmedNonOperator($userStore, $workspaceStore)) + let isNotOperator = $derived(isUserFor($userStore, $workspaceStore) && $roleCapabilities.code) let showBanner = $derived(isFork && isNotOperator) // Drafts in this fork. When the fork is otherwise in sync with its parent, a diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index a3a2d19fd6..ad2ee14b99 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -22,6 +22,7 @@ import CriticalAlertChannels from './instanceSettings/CriticalAlertChannels.svelte' import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' + import WorkspaceRolesSetting from './instanceSettings/WorkspaceRolesSetting.svelte' import SmtpSettings from './instanceSettings/SmtpSettings.svelte' import SecretBackendConfig from './instanceSettings/SecretBackendConfig.svelte' import ExternalInstancePgSettings from './instanceSettings/ExternalInstancePgSettings.svelte' @@ -342,6 +343,8 @@ getInstanceConfig() has populated the persisted overrides (which would let a save drop them). --> + {:else if setting.fieldType == 'workspace_roles'} + {:else} + {:else if category == 'Workspace roles'} + {:else if category == 'Service logs'} import { Button } from './common' import Popover from './meltComponents/Popover.svelte' - - import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' - import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' + import RolePicker from './settings/RolePicker.svelte' + import type { EffectiveRole } from '$lib/gen' + import { validRoleOr } from '$lib/workspaceRoles' import { MailPlus } from 'lucide-svelte' interface Props { - inviteUser: (email: string, selected: 'operator' | 'developer' | 'admin') => Promise + /** `selected` is a role name, or `admin`. */ + inviteUser: (email: string, selected: string) => Promise + /** The workspace's roles; undefined while loading. */ + roles: EffectiveRole[] | undefined } - const { inviteUser }: Props = $props() + const { inviteUser, roles }: Props = $props() let email: string = $state('') @@ -23,7 +26,8 @@ } } - let selected: 'operator' | 'developer' | 'admin' = $state('developer') + let picked: string | undefined = $state(undefined) + const selected = $derived(validRoleOr(roles, picked)) @@ -46,30 +50,7 @@ bind:value={email} class="mr-4" /> - - {#snippet children({ item })} - - - - - - {/snippet} - + (picked = v)} />
- {#if !$userStore?.operator} + {#if $roleCapabilities.code} {#if currentTags && currentTags.length > 0}
value, (v) => v && pick(v)} + /> +{/if} diff --git a/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte b/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte deleted file mode 100644 index b9ad80f63e..0000000000 --- a/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte +++ /dev/null @@ -1,295 +0,0 @@ - - -
- {#snippet action()} - - {/snippet} - -
- - -
- -
- - -
- -
- - - - Section - Description - - (allDisabled ? 'false' : allEnabled ? 'true' : ''), - (v) => { - Object.keys(operatorWorkspaceSettings).forEach((key) => { - if (v === 'true') operatorWorkspaceSettings[key] = true - if (v === 'false') operatorWorkspaceSettings[key] = false - }) - } - } - > - {#snippet children({ item })} - - - {/snippet} - - - - - - {#each Object.entries(descriptions) as [key, { title, description }]} - - {title} - {description} - - (operatorWorkspaceSettings[key] = detail === 'on')} - > - {#snippet children({ item })} - - - {/snippet} - - - - {/each} - - -
-
- - (confirmBuilderOpen = false)} - onConfirmed={async () => { - confirmBuilderOpen = false - await saveSettings() - }} -> -
- This applies to every operator of this workspace, not to a chosen few. - - Each of them then consumes a full seat instead of half a seat, which changes what this - instance is billed. - - - They can create, edit and delete {grantedBuilderKinds} wherever their folder permissions already - let them write. Review those permissions before enabling. - -
-
diff --git a/frontend/src/lib/components/settings/WorkspaceRoleOverrides.svelte b/frontend/src/lib/components/settings/WorkspaceRoleOverrides.svelte new file mode 100644 index 0000000000..12e1b3e68e --- /dev/null +++ b/frontend/src/lib/components/settings/WorkspaceRoleOverrides.svelte @@ -0,0 +1,393 @@ + + +{#snippet roleCard(name: string, role: EffectiveRole | undefined)} + {@const { base, unknown } = baseFor(name)} + {@const caps = applyCapabilitiesPatch(base, draft.get(name)?.capabilities)} + {@const overridden = Object.hasOwn(cleanedDraft, name)} + {@const frozen = !role && !data?.custom_roles_enabled} +
+
+
+ + {draft.get(name)?.label?.trim() || role?.label || name} + + {name} +
+ {#if role} + Instance + {#if overridden} + Overridden here + {/if} + {:else if frozen} + Read-only without a license + {:else} + This workspace only + {/if} + + {summary(caps)} + + + {#if role} + + {:else} +
+ {#if errors[name] && !open.get(name)} + {errors[name]} + {/if} + {#if open.get(name)} +
+
+ Label +
+ setLabel(name, e.currentTarget.value) + }} + /> +
+
+ setPatch(name, p)} + /> +
+ {/if} +
+{/snippet} + +
+ {#snippet action()} + + {/snippet} + + {#if !data} + Loading roles... + {:else} +
+ {#each instanceRoles as role (role.name)} + {@render roleCard(role.name, role)} + {/each} + {#each workspaceOnlyNames as name (name)} + {@render roleCard(name, undefined)} + {/each} + + {#if data.custom_roles_enabled} +
+
+ e.key === 'Enter' && addRole() + }} + /> + {#if newRoleError} + {newRoleError} + {/if} +
+ +
+ + A workspace role exists only here. Its unset capabilities default to the operator rights. + One still held by a member, invite, auto-invite or instance group mapping cannot be + removed. + + {:else} + + This workspace can still override what the instance roles allow. Roles added here earlier + keep applying but are read-only; they can still be removed. + + {/if} +
+ {/if} +
+ + (confirmSeatOpen = false)} + onConfirmed={async () => { + confirmSeatOpen = false + await save() + }} +> +
+ + With this change, members holding + {newAuthorRoles.join(', ')} can write code or build flows or apps in this workspace, or + may again if the instance definition allows it. + + + Each of them then consumes a full seat instead of half a seat, which changes what this + instance is billed. They can author wherever their folder permissions already let them write. + +
+
diff --git a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte index 8f5db5f2d9..19ca67a5f7 100644 --- a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte +++ b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte @@ -4,7 +4,17 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' - import WorkspaceOperatorSettings from '$lib/components/settings/WorkspaceOperatorSettings.svelte' + import WorkspaceRoleOverrides from '$lib/components/settings/WorkspaceRoleOverrides.svelte' + import RolePicker from '$lib/components/settings/RolePicker.svelte' + import { + defaultRoleName, + loadWorkspaceRoles, + OPERATOR_ROLE, + pickerValue, + roleLabel, + roleRequestFields, + validRoleOr + } from '$lib/workspaceRoles' import InviteUser from '$lib/components/InviteUser.svelte' import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte' @@ -12,7 +22,7 @@ import Head from '$lib/components/table/Head.svelte' import Toggle from '$lib/components/Toggle.svelte' import Tooltip from '$lib/components/Tooltip.svelte' - import type { CancelablePromise, User, UserUsage } from '$lib/gen' + import type { CancelablePromise, User, UserUsage, WorkspaceRoles } from '$lib/gen' import { UserService, WorkspaceService, GroupService, type WorkspaceInvite } from '$lib/gen' import { userStore, @@ -39,12 +49,28 @@ let offboardingUser: string | undefined = $state(undefined) let offboardingReassignOnly = $state(false) - let users: User[] | undefined = $state(undefined) + // `role` is the member's workspace role, which `listUsers` returns but the spec's `User` omits. + type Member = User & { role?: string } + + let users: Member[] | undefined = $state(undefined) let invites: WorkspaceInvite[] = $state([]) - let filteredUsers: User[] | undefined = $state(undefined) + let filteredUsers: Member[] | undefined = $state(undefined) let userFilter = $state('') let auto_invite_domain: string | undefined = $state() - let operatorOnly: boolean | undefined = $state(undefined) + // Unset until picked or stored; the pickers and payloads fall back to the default role. + let autoInviteRole: string | undefined = $state(undefined) + let workspaceRoles = $state(undefined) + const roles = $derived(workspaceRoles?.roles) + + async function loadRoles(): Promise { + const workspace = $workspaceStore! + try { + const r = await loadWorkspaceRoles(workspace) + if (workspace === $workspaceStore) workspaceRoles = r + } catch (e) { + sendUserToast(`Failed to load the workspace roles: ${e?.body ?? e}`, true) + } + } let autoAdd: boolean | undefined = $state(false) let addAdminsAndDevelopersToForks = $state(false) let nbDisplayed = $state(30) @@ -56,7 +82,7 @@ // Add new instance group form state let selectedNewInstanceGroup: string | undefined = $state(undefined) - let selectedNewRole: string | undefined = $state('developer') + let selectedNewRole: string | undefined = $state(undefined) // Service account creation @@ -113,13 +139,14 @@ enabled?: boolean domain?: string operator?: boolean + role?: string mode?: string instance_groups?: string[] instance_groups_roles?: Record } | undefined auto_invite_domain = autoInvite?.enabled ? (autoInvite?.domain ?? '*') : undefined - operatorOnly = autoInvite?.operator ?? false + autoInviteRole = autoInvite?.role ?? (autoInvite?.operator ? OPERATOR_ROLE : undefined) autoAdd = autoInvite?.mode === 'add' autoAddInstanceGroups = autoInvite?.instance_groups || [] autoAddInstanceGroupsRoles = autoInvite?.instance_groups_roles || {} @@ -190,11 +217,11 @@ let lastSeen: { workspace: string; signature: string; seq: number } | undefined = undefined let usersIssued = 0 - // Every field a paid seat count depends on — the developer/operator split, and the - // two categories billing excludes. - function membershipSignature(list: User[] | undefined): string { + // Every field a paid seat count depends on — the role, and the two categories billing + // excludes. + function membershipSignature(list: Member[] | undefined): string { return (list ?? []) - .map((u) => `${u.email}:${u.operator}:${u.disabled}:${u.is_service_account}`) + .map((u) => `${u.email}:${u.operator}:${u.role}:${u.disabled}:${u.is_service_account}`) .sort() .join(',') } @@ -218,29 +245,25 @@ } } + // Throws, so each caller rolls back its optimistic change. async function saveInstanceGroupSettings(): Promise { - try { - await WorkspaceService.editInstanceGroups({ - workspace: $workspaceStore ?? '', - requestBody: { - groups: autoAddInstanceGroups, - roles: autoAddInstanceGroupsRoles - } - }) - sendUserToast('Instance group settings saved') - // Refresh user list to show newly auto-added users - listUsers() - } catch (e) { - console.error('Failed to save instance group settings:', e) - sendUserToast('Failed to save settings', true) - } + await WorkspaceService.editInstanceGroups({ + workspace: $workspaceStore ?? '', + requestBody: { + groups: autoAddInstanceGroups, + roles: autoAddInstanceGroupsRoles + } + }) + sendUserToast('Instance group settings saved') + // Refresh user list to show newly auto-added users + listUsers() } async function addInstanceGroup(): Promise { - if (!selectedNewInstanceGroup || !selectedNewRole) return + if (!selectedNewInstanceGroup) return const groupToAdd = selectedNewInstanceGroup - const roleToAdd = selectedNewRole + const roleToAdd = validRoleOr(roles, selectedNewRole) try { autoAddInstanceGroups = [...autoAddInstanceGroups, groupToAdd] @@ -248,14 +271,14 @@ // Reset form selectedNewInstanceGroup = undefined - selectedNewRole = 'developer' + selectedNewRole = undefined await saveInstanceGroupSettings() } catch (e) { // Rollback on error autoAddInstanceGroups = autoAddInstanceGroups.filter((g) => g !== groupToAdd) delete autoAddInstanceGroupsRoles[groupToAdd] - sendUserToast('Failed to add instance group', true) + sendUserToast(`Failed to add instance group: ${e?.body ?? e}`, true) } } @@ -273,7 +296,7 @@ if (previousRole) { autoAddInstanceGroupsRoles[groupName] = previousRole } - sendUserToast('Failed to remove instance group', true) + sendUserToast(`Failed to remove instance group: ${e?.body ?? e}`, true) } } @@ -286,7 +309,7 @@ } catch (e) { // Rollback on error autoAddInstanceGroupsRoles[groupName] = previousRole - sendUserToast('Failed to update role', true) + sendUserToast(`Failed to update role: ${e?.body ?? e}`, true) } } @@ -315,6 +338,8 @@ listInvites() loadSettings() loadInstanceGroups() + workspaceRoles = undefined + loadRoles() }) } }) @@ -356,20 +381,16 @@ let nbInviteDisplayed = $state(50) - async function inviteUser(email: string, selected: 'operator' | 'developer' | 'admin') { + async function inviteUser(email: string, selected: string) { try { await WorkspaceService.inviteUser({ workspace: $workspaceStore!, - requestBody: { - email, - is_admin: selected == 'admin', - operator: selected == 'operator' - } + requestBody: { email, ...roleRequestFields(selected) } }) sendUserToast(`Invited ${email}`) } catch (e) { console.error('Failed to invite user:', e) - sendUserToast('Failed to invite user', true) + sendUserToast(`Failed to invite user: ${e?.body ?? e}`, true) } if (!(await UserService.existsEmail({ email }))) { @@ -412,7 +433,7 @@ workspace: $workspaceStore ?? '', requestBody: enable ? { - operator: operatorOnly ?? false, + ...roleRequestFields(validRoleOr(roles, autoInviteRole)), invite_all: !isCloudHosted(), auto_add: autoAdd } @@ -430,7 +451,7 @@ sendUserToast(message) } catch (e) { console.error('Failed to update auto invite:', e) - sendUserToast('Failed to update auto invite', true) + sendUserToast(`Failed to update auto invite: ${e?.body ?? e}`, true) } loadSettings() listInvites() @@ -548,32 +569,18 @@ {/if} Role Role of the auto-added users - { - operatorOnly = e.detail === 'operator' + { + autoInviteRole = v if (auto_invite_domain != undefined) { await updateAutoInvite(true) } }} - > - {#snippet children({ item })} - - - {/snippet} - + />
Role - { - selectedNewRole = e.detail - }} - > - {#snippet children({ item })} - - - - {/snippet} - + (selectedNewRole = v)} + />
@@ -697,7 +680,7 @@ color="blue" size="xs" startIcon={{ icon: Plus }} - disabled={!selectedNewInstanceGroup || !selectedNewRole} + disabled={!selectedNewInstanceGroup} onclick={addInstanceGroup} > Add @@ -730,38 +713,15 @@
- { - autoAddInstanceGroupsRoles[groupName] = e.detail - await updateGroupRole(groupName, e.detail) + { + await updateGroupRole(groupName, v) }} - > - {#snippet children({ item })} - - - - {/snippet} - + />
@@ -800,10 +760,11 @@ {/if} {#if showAutoInviteToggle} - + {/if} { listUsers() listInvites() @@ -851,7 +812,7 @@ {#if filteredUsers} {#each sortedUsers().slice(0, nbDisplayed) as user, index (user.email)} - {@const { email, username, is_admin, operator, disabled, added_via } = user} + {@const { email, username, is_admin, disabled, added_via } = user} {#if hasNonManualUsers && index > 0 && sortedUsers()[index - 1]?.added_via?.source !== 'instance_group' && added_via?.source === 'instance_group'} @@ -901,63 +862,35 @@ {#if added_via?.source === 'instance_group'}
- {is_admin ? 'Admin' : operator ? 'Operator' : 'Developer'} + {roleLabel(roles, pickerValue(user))} Role is managed through instance group configuration above.
{:else} - { - if (is_admin && email == $userStore?.email && e.detail != 'admin') { + { + if (is_admin && email == $userStore?.email && v != 'admin') { sendUserToast( 'Admins cannot be demoted by themselves, ask another admin to demote you', true ) - e.preventDefault() listUsers() return } - const body = - e.detail == 'admin' - ? { is_admin: true, operator: false } - : e.detail == 'operator' - ? { is_admin: false, operator: true } - : { is_admin: false, operator: false } - await UserService.updateUser({ - workspace: $workspaceStore ?? '', - username, - requestBody: body - }) - listUsers() + try { + await UserService.updateUser({ + workspace: $workspaceStore ?? '', + username, + requestBody: roleRequestFields(v) + }) + } catch (e) { + sendUserToast(`Failed to change role: ${e?.body ?? e}`, true) + } + await listUsers() }} - > - {#snippet children({ item })} - - - - - - {/snippet} - + /> {/if}
@@ -1083,7 +1016,9 @@
- +{#if $workspaceStore} + +{/if}
@@ -1118,7 +1053,7 @@ {#snippet action()} {#if showAutoInviteToggle && !isAdminsWorkspaceWithoutEE}
- +
{/if} {/snippet} @@ -1132,56 +1067,27 @@ {#if invites?.length > 0} - {#each invites.slice(0, nbInviteDisplayed) as { email, is_admin, operator }} + {#each invites.slice(0, nbInviteDisplayed) as invite} + {@const { email, is_admin, operator } = invite} {email}
- { - const body = - e.detail == 'admin' - ? { is_admin: true, operator: false } - : e.detail == 'operator' - ? { is_admin: false, operator: true } - : { is_admin: false, operator: false } - await WorkspaceService.inviteUser({ - workspace: $workspaceStore ?? '', - requestBody: { - email, - ...body - } - }) - listUsers() + { + try { + await WorkspaceService.inviteUser({ + workspace: $workspaceStore ?? '', + requestBody: { email, ...roleRequestFields(v) } + }) + } catch (e) { + sendUserToast(`Failed to change role: ${e?.body ?? e}`, true) + } + await listInvites() }} - > - {#snippet children({ item })} - - - - - - {/snippet} - + />
diff --git a/frontend/src/lib/components/sidebar/SettingsMenu.svelte b/frontend/src/lib/components/sidebar/SettingsMenu.svelte index 95dc03992c..13f38840d4 100644 --- a/frontend/src/lib/components/sidebar/SettingsMenu.svelte +++ b/frontend/src/lib/components/sidebar/SettingsMenu.svelte @@ -38,7 +38,6 @@ import { USER_SETTINGS_HASH, SUPERADMIN_SETTINGS_HASH } from './settings' import { accountSetup } from './accountSetup.svelte' import { EXECUTIONS_HINT } from './executionsHint' - import { sidebarPageAllowed } from './operatorRoutes' import { TOUR_PARAM, TOUR_PARAM_VALUE } from '$lib/components/tutorials/operatorTour' import { userWorkspaces, @@ -49,7 +48,8 @@ enterpriseLicense, isCriticalAlertsUIOpen, usageStore, - isPremiumStore + isPremiumStore, + roleCapabilities } from '$lib/stores' let { @@ -250,7 +250,7 @@ icon: Settings, action: () => goto(USER_SETTINGS_HASH) }, - ...($userStore?.operator + ...(!$roleCapabilities.code ? [ { displayName: 'Take the tour', @@ -318,7 +318,7 @@ label="Workers" href="/workers" icon={ServerCog} - disabled={!sidebarPageAllowed($userStore?.operator, currentWs, 'workers')} + disabled={!$roleCapabilities.visibility.workers} {isCollapsed} aiId="sidebar-menu-link-workers" aiDescription="Button to navigate to workers" @@ -364,7 +364,7 @@ label="Audit logs" href="/audit_logs" icon={Eye} - disabled={!sidebarPageAllowed($userStore?.operator, currentWs, 'audit_logs')} + disabled={!$roleCapabilities.visibility.audit_logs} {isCollapsed} aiId="sidebar-menu-link-audit-logs" aiDescription="Button to navigate to audit logs" diff --git a/frontend/src/lib/components/sidebar/SidebarContent.svelte b/frontend/src/lib/components/sidebar/SidebarContent.svelte index 7187709d2c..f08446d4ed 100644 --- a/frontend/src/lib/components/sidebar/SidebarContent.svelte +++ b/frontend/src/lib/components/sidebar/SidebarContent.svelte @@ -8,7 +8,8 @@ workspaceStore, isCriticalAlertsUIOpen, enterpriseLicense, - devopsRole + devopsRole, + roleCapabilities } from '$lib/stores' import { isForkOwner } from '$lib/utils/workspaceHierarchy' import { SIDEBAR_SHOW_SCHEDULES } from '$lib/consts' @@ -65,7 +66,7 @@ import GoogleCloudIcon from '../icons/triggers/GoogleCloudIcon.svelte' import AzureIcon from '../icons/triggers/AzureIcon.svelte' import { leaveCurrentWorkspace } from './leaveWorkspace' - import { sidebarPageAllowed, type OperatorPageKey } from './operatorRoutes' + import type { VisibilityKey } from '$lib/roleCapabilities' import { markChangelogsOpened, readRecentChangelogs } from './changelogs' const { recent: recentChangelogs, hasNew } = readRecentChangelogs() @@ -183,8 +184,8 @@ } const currentWs = $derived($userWorkspaces?.find((w) => w.id === $workspaceStore)) - function allows(key: OperatorPageKey) { - return sidebarPageAllowed($userStore?.operator, currentWs, key) + function allows(key: VisibilityKey) { + return $roleCapabilities.visibility[key] } const itemClass = twMerge( @@ -228,7 +229,7 @@ label: p.label, href: p.path === '/' ? `/` : `${p.path}`, icon: p.icon, - disabled: p.operatorKey ? !allows(p.operatorKey) : false, + disabled: p.visibilityKey ? !allows(p.visibilityKey) : false, ...MAIN_MENU_EXTRAS[p.label] })) .filter((l) => !excludeMainLabels.includes(l.label)) @@ -436,7 +437,7 @@ ] : []) ], - disabled: $userStore?.operator + disabled: !$roleCapabilities.code }, { label: 'Workers', diff --git a/frontend/src/lib/components/sidebar/UserMenu.svelte b/frontend/src/lib/components/sidebar/UserMenu.svelte index ff302d3c5e..40c64d5621 100644 --- a/frontend/src/lib/components/sidebar/UserMenu.svelte +++ b/frontend/src/lib/components/sidebar/UserMenu.svelte @@ -6,8 +6,11 @@ usageStore, workspaceUsageStore, isPremiumStore, - workspaceStore + workspaceStore, + userWorkspaces, + roleCapabilities } from '$lib/stores' + import { isRestricted } from '$lib/roleCapabilities' import { USER_SETTINGS_HASH } from './settings' import { isCloudHosted } from '$lib/cloud' import { twMerge } from 'tailwind-merge' @@ -32,6 +35,12 @@ // An account entered through an invite link that still has no credentials of its own. let pendingSetup = $derived(accountSetup.pending) + // A server that predates roles sends no role name, and its only restricted role is operator. + const roleName = $derived( + $userWorkspaces.find((w) => w.id === $workspaceStore)?.role ?? 'operator' + ) + const roleLabel = $derived(roleName.charAt(0).toUpperCase() + roleName.slice(1)) + const itemClass = twMerge( 'text-secondary text-left font-normal text-xs ', 'flex flex-row items-center gap-2 px-4 py-3 w-full', @@ -62,8 +71,8 @@ Superadmin, not a member of this workspace {:else if $userStore?.is_admin} Admin of this workspace - {:else if $userStore?.operator} - Operator in this workspace + {:else if isRestricted($roleCapabilities)} + {roleLabel} in this workspace {/if} {#if $userStore?.non_member} diff --git a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte index c70fef70a4..97385c7e9d 100644 --- a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte +++ b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte @@ -2,8 +2,10 @@ import { tick, untrack } from 'svelte' import type { MenubarMenuElements } from '@melt-ui/svelte' import { workspaceMenuHref } from './workspaceMenuHref' - import { isOperatorInWorkspace } from './operatorRoutes' + import { capabilitiesIn, hidesPages, isRestricted } from '$lib/roleCapabilities' + import type { RoleCapabilities } from '$lib/gen' import { + roleCapabilities, isPremiumStore, maybePremium, superadmin, @@ -85,16 +87,15 @@ await fixupUrlAfterWorkspaceSwitch(id, { landOnHome }) } - // Operator page access is granted per workspace, so a switch lands on home rather than - // on a page either side may refuse. Both signals are positive: `userStore.operator` is - // an explicit flag for the workspace being left, and `isOperatorInWorkspace` only ever - // confirms the target (its NULL is ambiguous, so a `false` from it is never taken as - // proof of a developer on its own). Leaving one developer workspace for another keeps - // the page, as it always has. + // What a role may see and do is per workspace, so a switch that leaves or enters a restricted + // role lands on home rather than on a page either side may refuse. Leaving one unrestricted + // workspace for another keeps the page. function landsOnHome(id: string): boolean { if (keepPageOnSwitch) return false - if ($userStore?.operator) return true - return isOperatorInWorkspace(($userWorkspaces ?? []).find((w) => w.id === id)) + const gated = (caps: RoleCapabilities) => isRestricted(caps) || hidesPages(caps) + if (gated($roleCapabilities)) return true + const target = ($userWorkspaces ?? []).find((w) => w.id === id) + return gated(capabilitiesIn({ is_super_admin: $userStore?.is_super_admin }, target)) } // Href for the item's navigation (including modifier/middle clicks opening a @@ -160,7 +161,7 @@ // modal carries its own base-workspace picker). Hidden on non-premium cloud, // in the admins workspace, or when forking is disabled. const canForkHere = $derived( - (!isCloudHosted() || $maybePremium) && $workspaceStore !== 'admins' && canCreateFork($userStore) + (!isCloudHosted() || $maybePremium) && $workspaceStore !== 'admins' && canCreateFork($userStore, $roleCapabilities) ) // The row mechanics below — which family to expand, which collapsed row carries the tick — key on // a depth-0 row of the list, which `buildWorkspaceHierarchy` puts at the highest workspace the diff --git a/frontend/src/lib/components/sidebar/navDetached.svelte.ts b/frontend/src/lib/components/sidebar/navDetached.svelte.ts index 19568eaddc..e53f4e7cbb 100644 --- a/frontend/src/lib/components/sidebar/navDetached.svelte.ts +++ b/frontend/src/lib/components/sidebar/navDetached.svelte.ts @@ -1,5 +1,5 @@ import { fromStore } from 'svelte/store' -import { userStore } from '$lib/stores' +import { roleCapabilities } from '$lib/stores' import { useLocalStorageValue } from '$lib/svelte5Utils.svelte' // One preference per role rather than one per account. The same person is both — an operator in @@ -8,21 +8,21 @@ import { useLocalStorageValue } from '$lib/svelte5Utils.svelte' // Empty until that role presses detach or attach once. const operatorPref = useLocalStorageValue('nav_detached_operator', '', 'string') const devPref = useLocalStorageValue('nav_detached_dev', '', 'string') -const user = fromStore(userStore) +const caps = fromStore(roleCapabilities) /** Whether the sidebar is detached: hidden behind a floating button that slides it in over the page. */ export const navDetached = { get val(): boolean { // Unasked, operators start detached: many of them navigate through a workspace's own app, // and a docked sidebar would take its width. - const operator = !!user.current?.operator + const operator = !caps.current.code const pref = operator ? operatorPref : devPref if (pref.val === 'true') return true if (pref.val === 'false') return false return operator }, set val(detached: boolean) { - const pref = user.current?.operator ? operatorPref : devPref + const pref = caps.current.code ? devPref : operatorPref pref.val = String(detached) } } diff --git a/frontend/src/lib/components/sidebar/navPages.ts b/frontend/src/lib/components/sidebar/navPages.ts index 385b93abcc..2461ba6e1a 100644 --- a/frontend/src/lib/components/sidebar/navPages.ts +++ b/frontend/src/lib/components/sidebar/navPages.ts @@ -11,7 +11,7 @@ import { Unplug, Users } from 'lucide-svelte' -import type { OperatorPageKey } from './operatorRoutes' +import type { VisibilityKey } from '$lib/roleCapabilities' /** * The names the page header's breadcrumb gives the workspace's own pages, and the rows the @@ -20,7 +20,7 @@ import type { OperatorPageKey } from './operatorRoutes' * Every entry names a page for the breadcrumb, and its `icon` goes there too. Only the entries * `SidebarContent`'s `MAIN_MENU_EXTRAS` also lists become sidebar links from here — Schedules, * HTTP routes, Workers and Audit logs are grouped differently there and carry their own row, so - * for those four the `operatorKey` below goes unread. Keep the labels in step with those rows by + * for those four the `visibilityKey` below goes unread. Keep the labels in step with those rows by * hand. */ export type NavPage = { @@ -28,23 +28,23 @@ export type NavPage = { /** Path under `base`, matched against the current route by longest prefix. */ path: string icon: any - /** The `operator_settings` key that admits an operator, when the page has one. */ - operatorKey?: OperatorPageKey + /** The role visibility flag that shows the page, when the page has one. */ + visibilityKey?: VisibilityKey } export const NAV_PAGES: NavPage[] = [ { label: 'Home', path: '/', icon: Home }, - { label: 'Runs', path: '/runs', icon: Play, operatorKey: 'runs' }, - { label: 'Variables', path: '/variables', icon: DollarSign, operatorKey: 'variables' }, - { label: 'Resources', path: '/resources', icon: Boxes, operatorKey: 'resources' }, - { label: 'Assets', path: '/assets', icon: Pyramid, operatorKey: 'assets' }, - { label: 'Folders', path: '/folders', icon: FolderOpen, operatorKey: 'folders' }, - { label: 'Groups', path: '/groups', icon: Users, operatorKey: 'groups' }, - { label: 'Schedules', path: '/schedules', icon: Calendar, operatorKey: 'schedules' }, + { label: 'Runs', path: '/runs', icon: Play, visibilityKey: 'runs' }, + { label: 'Variables', path: '/variables', icon: DollarSign, visibilityKey: 'variables' }, + { label: 'Resources', path: '/resources', icon: Boxes, visibilityKey: 'resources' }, + { label: 'Assets', path: '/assets', icon: Pyramid, visibilityKey: 'assets' }, + { label: 'Folders', path: '/folders', icon: FolderOpen, visibilityKey: 'folders' }, + { label: 'Groups', path: '/groups', icon: Users, visibilityKey: 'groups' }, + { label: 'Schedules', path: '/schedules', icon: Calendar, visibilityKey: 'schedules' }, // "Triggers" is the group the sidebar files this under, not the page: the row there reads HTTP. - { label: 'HTTP routes', path: '/routes', icon: Unplug, operatorKey: 'triggers' }, - { label: 'Workers', path: '/workers', icon: HardHat, operatorKey: 'workers' }, - { label: 'Audit logs', path: '/audit_logs', icon: Eye, operatorKey: 'audit_logs' } + { label: 'HTTP routes', path: '/routes', icon: Unplug, visibilityKey: 'triggers' }, + { label: 'Workers', path: '/workers', icon: HardHat, visibilityKey: 'workers' }, + { label: 'Audit logs', path: '/audit_logs', icon: Eye, visibilityKey: 'audit_logs' } ] /** diff --git a/frontend/src/lib/components/sidebar/operatorRoutes.test.ts b/frontend/src/lib/components/sidebar/operatorRoutes.test.ts deleted file mode 100644 index bf14926d00..0000000000 --- a/frontend/src/lib/components/sidebar/operatorRoutes.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { sidebarPageAllowed } from './operatorRoutes' -import type { UserWorkspace } from '$lib/stores' - -const ws = (operator_settings: any): UserWorkspace => - ({ id: 'w', name: 'w', username: 'u', operator_settings }) as UserWorkspace - -describe('sidebarPageAllowed', () => { - it('shows every page to anyone who is not an operator', () => { - expect(sidebarPageAllowed(false, ws(null), 'runs')).toBe(true) - expect(sidebarPageAllowed(undefined, undefined, 'runs')).toBe(true) - }) - - it('admits an operator only where the workspace turned the page on', () => { - expect(sidebarPageAllowed(true, ws({ runs: true }), 'runs')).toBe(true) - expect(sidebarPageAllowed(true, ws({ runs: false }), 'runs')).toBe(false) - }) - - it('withholds a page the settings do not mention', () => { - // `=== true`, not truthiness: a right absent from the jsonb, or settings that were never - // written, must not read as granted. - expect(sidebarPageAllowed(true, ws({ variables: true }), 'runs')).toBe(false) - expect(sidebarPageAllowed(true, ws(null), 'runs')).toBe(false) - expect(sidebarPageAllowed(true, undefined, 'runs')).toBe(false) - }) -}) diff --git a/frontend/src/lib/components/sidebar/operatorRoutes.ts b/frontend/src/lib/components/sidebar/operatorRoutes.ts deleted file mode 100644 index 6824c36c62..0000000000 --- a/frontend/src/lib/components/sidebar/operatorRoutes.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type { OperatorSettings } from '$lib/gen' -import type { UserWorkspace } from '$lib/stores' - -/** - * An `operator_settings` key that admits an operator to one page (`triggers` to all of them). - * - * Only the visibility flags: the same object also carries the write rights `builder_flows`, - * `manage_schedules` and `manage_triggers`, which the `=== true` rule below answers wrongly. A - * write right is granted unless withdrawn, so its absence means "never configured" rather than - * "no" — see `docs/operator-write-rights.md`. - */ -export type OperatorPageKey = Extract< - keyof NonNullable, - | 'runs' - | 'schedules' - | 'resources' - | 'variables' - | 'assets' - | 'audit_logs' - | 'triggers' - | 'groups' - | 'folders' - | 'workers' -> - -/** - * Whether the sidebar shows the page behind `key`. Everyone but an operator sees every page - * (other gates, such as admin-only entries, still apply); an operator sees only the pages the - * workspace's `operator_settings` turn on. - */ -export function sidebarPageAllowed( - isOperator: boolean | undefined, - workspace: UserWorkspace | undefined, - key: OperatorPageKey -): boolean { - return !isOperator || workspace?.operator_settings?.[key] === true -} - -/** - * Whether the user is an operator in `workspace`. The server nulls - * `operator_settings` for a non-operator, so a non-null value narrows an operator - * correctly; the converse does not hold — the column is itself nullable, so a - * genuine operator whose workspace never had settings written also reads as NULL. - * Only rely on `true`, never on `false` meaning "not an operator". - */ -export function isOperatorInWorkspace(workspace: UserWorkspace | undefined): boolean { - return workspace?.operator_settings != null -} diff --git a/frontend/src/lib/components/triggers/TriggerList.svelte b/frontend/src/lib/components/triggers/TriggerList.svelte index 1ccbd21d0e..3931d9660c 100644 --- a/frontend/src/lib/components/triggers/TriggerList.svelte +++ b/frontend/src/lib/components/triggers/TriggerList.svelte @@ -22,7 +22,7 @@ } from '$lib/utils' import { withForkConflictRetry } from '$lib/utils/forkConflict' import { getLocalDraftHint } from '$lib/localDraftHints.svelte' - import { enterpriseLicense, usedTriggerKinds, userWorkspaces, workspaceStore } from '$lib/stores' + import { enterpriseLicense, usedTriggerKinds, workspaceStore } from '$lib/stores' import { goto, setQuery } from '$lib/navigation' import { isCloudHosted } from '$lib/cloud' import { ALL_DEPLOYABLE, isDeployable } from '$lib/utils_deployable' @@ -519,10 +519,7 @@ } const operatorBlocked = $derived( - config.operatorGate && - !!operatingUser.current?.operator && - !!$operatingWorkspace && - !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.triggers + config.operatorGate && !!$operatingWorkspace && !editRights.capabilities.visibility.triggers ) const canCreate = $derived(!config.adminOnly || isAdmin) @@ -883,7 +880,7 @@ {#if operatorBlocked} {:else} diff --git a/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte b/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte index c6b0986226..9a954b211e 100644 --- a/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte +++ b/frontend/src/lib/components/triggers/TriggerRunnablePicker.svelte @@ -15,7 +15,8 @@ scriptPath: string initialScriptPath: string canWrite: boolean - isOperator: boolean + /** Whether to link to the picked runnable's editor: the role must author its kind. */ + allowEdit: boolean promptText?: string promptClass?: string workspace?: string @@ -30,7 +31,7 @@ scriptPath = $bindable(), initialScriptPath, canWrite, - isOperator, + allowEdit, promptText = 'Pick a script or flow to be triggered', promptClass = 'text-xs mb-1 text-primary', workspace = undefined, @@ -53,7 +54,7 @@ bind:itemKind bind:scriptPath allowRefresh={canWrite} - allowEdit={!isOperator} + {allowEdit} {workspace} clearable /> diff --git a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte index 7295ca0c35..c0f4803339 100644 --- a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte @@ -91,7 +91,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const wsId = $derived($operatingWorkspace) let amqp_resource_path: string = $state('') @@ -586,7 +585,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} /> {/if} diff --git a/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte index e0c2008be8..6b52a05428 100644 --- a/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte @@ -54,7 +54,6 @@ let mode = $state('enabled') let dirtyPath = $state(false) const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) let permsPath = $state(undefined) let permsForWrite = $state | undefined>(undefined) // The acting user in the operating workspace arrives asynchronously, and an unknown user @@ -526,7 +525,7 @@ bind:itemKind bind:scriptPath={script_path} allowRefresh={can_write} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte index 38a8243855..9de47ba600 100644 --- a/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte @@ -455,7 +455,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptClass="text-xs mt-3 mb-1 text-primary" > {#snippet createButton()} diff --git a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte index 486711bd6c..04052a54d6 100644 --- a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte @@ -63,7 +63,6 @@ let mode = $state('enabled') let dirtyPath = $state(false) const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) let permsPath = $state(undefined) let permsForWrite = $state | undefined>(undefined) // The acting user in the operating workspace arrives asynchronously, and an unknown user @@ -599,7 +598,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptText="Pick a script or flow to be triggered " > {#snippet createButton()} diff --git a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte index 786137eab4..fe94787167 100644 --- a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte +++ b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte @@ -778,7 +778,7 @@ bind:itemKind bind:scriptPath={script_path} allowRefresh={can_write} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> diff --git a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte index 17a17f98e8..80be6049d3 100644 --- a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte @@ -88,7 +88,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -609,7 +608,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} > {#snippet createButton()} {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte index 5c1fb4aaf0..d58abebe3b 100644 --- a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte @@ -96,7 +96,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -582,7 +581,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} > {#snippet createButton()} {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte index 9e8dc592e9..3246b12a4d 100644 --- a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte @@ -28,15 +28,10 @@ import { deepEqual } from 'fast-equals' import type { Snippet } from 'svelte' import Alert from '$lib/components/common/alert/Alert.svelte' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const triggerLock = useTriggerLock() const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const editRights = useEditRights() interface Props { @@ -540,7 +535,7 @@ bind:itemKind kinds={['script']} allowFlow={true} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> {#if emptyString(scriptPath)} diff --git a/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte index e0ba992e12..db95d73e7f 100644 --- a/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte @@ -84,7 +84,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -578,7 +577,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} > {#snippet createButton()} {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte index 68ee8816b7..402cca53fb 100644 --- a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte @@ -103,7 +103,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -760,7 +759,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptText="Pick a script or flow to be triggered " promptClass="text-xs text-primary" > diff --git a/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte b/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte index 48227dea44..5e167a4337 100644 --- a/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte +++ b/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte @@ -141,9 +141,9 @@ ? editRights.roleCanAuthor('schedule') : editRights.canEditItem('schedule', permsPath, extraPerms) ) - // Editing the runnable is closed to operators, and an unresolved acting user is no - // evidence that this one isn't. - const canEditRunnable = $derived(actingUser !== undefined && !actingUser.operator) + // Editing the runnable needs a role that authors its kind; an unresolved acting user is no + // evidence of that role. + const canEditRunnable = $derived(actingUser !== undefined && editRights.roleCanAuthor(itemKind)) const saveDisabled = $derived( !allowSchedule || pathError != '' || diff --git a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte index 5593dd121f..77f9478026 100644 --- a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte @@ -88,7 +88,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -561,7 +560,7 @@ bind:scriptPath={script_path} {initialScriptPath} canWrite={can_write} - isOperator={!!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} promptText="Pick a script or flow to be triggered " > {#snippet createButton()} diff --git a/frontend/src/lib/components/triggers/triggers.svelte.ts b/frontend/src/lib/components/triggers/triggers.svelte.ts index 7fe40d111d..8ee12aaaea 100644 --- a/frontend/src/lib/components/triggers/triggers.svelte.ts +++ b/frontend/src/lib/components/triggers/triggers.svelte.ts @@ -32,6 +32,7 @@ import type { UserExt } from '$lib/stores' import type { ScheduleTrigger } from '../triggers' import { formatCron, generateRandomString } from '$lib/utils' import { canEditItem } from '$lib/editRights' +import { capabilitiesIn } from '$lib/roleCapabilities' export class Triggers { #triggers = $state([]) @@ -135,9 +136,10 @@ export class Triggers { user: UserExt | undefined = undefined ): number { const currentTriggers = this.#triggers - const operatorSettings = get(userWorkspaces).find( - (w) => w.id === workspaceId - )?.operator_settings + const caps = capabilitiesIn( + user, + get(userWorkspaces).find((w) => w.id === workspaceId) + ) const kind = type === 'schedule' ? 'schedule' : 'trigger' // Identify triggers with draftConfig to preserve const configuredTriggers = currentTriggers.filter( @@ -157,7 +159,7 @@ export class Triggers { path: trigger.path, isPrimary: type === 'schedule' && trigger.path === trigger.script_path, isDraft: false, - canWrite: canEditItem(kind, trigger.path, trigger.extra_perms, user, operatorSettings), + canWrite: canEditItem(kind, trigger.path, trigger.extra_perms, user, caps), draftConfig: draftConfig, lightConfig: getLightConfig(type, trigger) } diff --git a/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte index b011d6fee1..5d19535b01 100644 --- a/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte @@ -105,7 +105,6 @@ }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) const operatingHref = useOperatingWorkspaceHref() const wsId = $derived($operatingWorkspace) @@ -637,7 +636,7 @@ bind:itemKind bind:scriptPath={script_path} allowRefresh={can_write} - allowEdit={!actingUser?.operator} + allowEdit={editRights.roleCanAuthor(itemKind)} clearable /> {#if emptyString(script_path)} diff --git a/frontend/src/lib/components/variables/VariablesList.svelte b/frontend/src/lib/components/variables/VariablesList.svelte index 3805b51bbb..e3d996804e 100644 --- a/frontend/src/lib/components/variables/VariablesList.svelte +++ b/frontend/src/lib/components/variables/VariablesList.svelte @@ -36,7 +36,7 @@ import Tooltip from '$lib/components/Tooltip.svelte' import VariableEditor from '$lib/components/VariableEditor.svelte' import type { ContextualVariable, ListableVariable, WorkspaceDeployUISettings } from '$lib/gen' - import { enterpriseLicense, userWorkspaces } from '$lib/stores' + import { enterpriseLicense } from '$lib/stores' import { sendUserToast } from '$lib/toast' import { isOwner, truncate } from '$lib/utils' import { useEditRights } from '$lib/operatorWriteRights' @@ -317,10 +317,10 @@ -{#if operatingUser.current?.operator && $operatingWorkspace && !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.variables} +{#if $operatingWorkspace && !editRights.capabilities.visibility.variables} {:else} diff --git a/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte b/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte index ed96f56811..d6a43364f0 100644 --- a/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte +++ b/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte @@ -34,7 +34,7 @@ devWorkspacesInChainAbove } from '$lib/utils/workspaceHierarchy' import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte' - import { isOperatorInWorkspace } from '$lib/components/sidebar/operatorRoutes' + import { capabilitiesIn, isRestricted } from '$lib/roleCapabilities' import { canUserBypassRuleKindInRulesets, fetchProtectionRulesForWorkspace, @@ -138,14 +138,14 @@ let forkableWorkspaces = $derived(forkable.current) // Base candidates are the current workspace's family: its root first, then every fork/dev under it. - // Never one the user is an operator in: a fork does not carry the role, so forking such a base + // Never one the user holds a restricted role in: a fork does not carry the role, so forking such a base // would hand them a full-rights copy of it. let familyRoot = $derived(findWorkspaceRoot($workspaceStore, forkableWorkspaces)) let baseCandidates = $derived( (familyRoot ? [familyRoot, ...findWorkspaceDescendants(familyRoot.id, forkableWorkspaces)] : [] - ).filter((w) => !isOperatorInWorkspace(w)) + ).filter((w) => !isRestricted(capabilitiesIn(undefined, w))) ) let baseItems = $derived( baseCandidates.map((w) => ({ diff --git a/frontend/src/lib/editRights.test.ts b/frontend/src/lib/editRights.test.ts index a6d36f693c..fa3366a284 100644 --- a/frontend/src/lib/editRights.test.ts +++ b/frontend/src/lib/editRights.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest' +import type { RoleCapabilities } from '$lib/gen' import type { UserExt } from '$lib/stores' +import { FULL_CAPABILITIES, legacyOperatorCapabilities } from '$lib/roleCapabilities' import { canEditItem, roleCanAuthor, roleCanDraft } from './editRights' function user(overrides: Partial): UserExt { @@ -20,40 +22,49 @@ function user(overrides: Partial): UserExt { } as UserExt } +const role = (overrides: Partial): RoleCapabilities => ({ + ...legacyOperatorCapabilities(undefined), + ...overrides +}) + describe('edit rights', () => { - it('lets a builder operator author flows and nothing else', () => { - const builder = { builder_flows: true } - expect(roleCanAuthor('flow', user({}), builder)).toBe(true) - expect(roleCanAuthor('script', user({}), builder)).toBe(false) - expect(roleCanAuthor('flow', user({}), undefined)).toBe(false) - expect(roleCanDraft('raw_app', user({}), builder)).toBe(false) - expect(roleCanDraft('raw_app', user({}), { builder_apps: true })).toBe(true) + it('lets a compose-only flow role author flows and nothing else', () => { + const builder = role({ flows: 'compose' }) + expect(roleCanAuthor('flow', builder)).toBe(true) + expect(roleCanAuthor('script', builder)).toBe(false) + expect(roleCanAuthor('raw_app', builder)).toBe(false) + expect(roleCanDraft('raw_app', builder)).toBe(false) + expect(roleCanDraft('raw_app', role({ apps: 'compose' }))).toBe(true) }) - // drafts.rs admits an admin before its operator branch; the item handlers do not. - it('lets an admin who is also an operator save drafts, but not author code', () => { - const adminOperator = user({ is_admin: true }) - expect(roleCanDraft('script', adminOperator, undefined)).toBe(true) - expect(roleCanAuthor('script', adminOperator, undefined)).toBe(false) + // apps.rs `require_full_apps`: a composing role builds full-code apps, never low-code ones. + it('keeps low-code apps for full app authors', () => { + expect(roleCanAuthor('app', role({ apps: 'compose' }))).toBe(false) + expect(roleCanAuthor('raw_app', role({ apps: 'compose' }))).toBe(true) + const scripter = { ...FULL_CAPABILITIES, apps: 'none' as const } + expect(roleCanAuthor('script', scripter)).toBe(true) + expect(roleCanAuthor('app', scripter)).toBe(false) + expect(roleCanAuthor('raw_app', scripter)).toBe(false) }) - // drafts.rs admits an operator's draft of a kind they could deploy, and no other. - it('lets an operator draft schedules and triggers until the right is withdrawn', () => { - expect(roleCanDraft('schedule', user({}), undefined)).toBe(true) - expect(roleCanDraft('trigger', user({}), undefined)).toBe(true) - expect(roleCanDraft('schedule', user({}), { manage_schedules: false })).toBe(false) - expect(roleCanDraft('trigger', user({}), { manage_triggers: false })).toBe(false) + // drafts.rs admits a restricted role's draft of a kind it could deploy, and no other. + it('lets a role draft schedules and triggers until the right is withdrawn', () => { + expect(roleCanDraft('schedule', role({}))).toBe(true) + expect(roleCanDraft('trigger', role({}))).toBe(true) + expect(roleCanDraft('schedule', role({ manage_schedules: false }))).toBe(false) + expect(roleCanDraft('trigger', role({ manage_triggers: false }))).toBe(false) }) - it('lets an operator draft resources and variables, but not scripts', () => { - expect(roleCanDraft('resource', user({}), undefined)).toBe(true) - expect(roleCanDraft('variable', user({}), undefined)).toBe(true) - expect(roleCanDraft('script', user({}), undefined)).toBe(false) + it('lets any role draft resources and variables, but scripts only with code', () => { + expect(roleCanDraft('resource', role({}))).toBe(true) + expect(roleCanDraft('variable', role({}))).toBe(true) + expect(roleCanDraft('script', role({}))).toBe(false) + expect(roleCanDraft('script', role({ code: true }))).toBe(true) }) // The role alone is not enough: a builder still cannot edit a flow in a folder they only read. it('requires write access to the item on top of the role', () => { - const builder = { builder_flows: true } + const builder = role({ flows: 'compose' }) expect(canEditItem('flow', 'f/demo/sum', {}, user({}), builder)).toBe(false) expect(canEditItem('flow', 'u/op/sum', {}, user({}), builder)).toBe(true) }) diff --git a/frontend/src/lib/editRights.ts b/frontend/src/lib/editRights.ts index 888b61e818..48ec6c3ee2 100644 --- a/frontend/src/lib/editRights.ts +++ b/frontend/src/lib/editRights.ts @@ -1,16 +1,17 @@ -import type { OperatorSettings } from '$lib/gen' +import type { RoleCapabilities } from '$lib/gen' import type { UserExt } from '$lib/stores' import { canWrite } from '$lib/utils' +import { isRestricted } from '$lib/roleCapabilities' /** * The frontend's one copy of "may this user edit this item". The server decides — drafts.rs - * `require_can_write_path`, the item handlers' operator refusals, `gate_operator_writes`, and + * `require_can_write_path`, the item handlers' role refusals, `gate_operator_writes`, and * row-level security — and this mirrors it so a control the server would refuse is never * offered. Check edits through `canEditItem` (or `useEditRights` in a component), never by - * pairing `canWrite` with an operator test of your own. + * pairing `canWrite` with a role test of your own. */ -/** Kinds whose role half differs. Any other kind is code an operator never authors. */ +/** Kinds whose role half differs. Any other kind is code, authored under `code`. */ export type EditKind = | 'script' | 'flow' @@ -25,82 +26,45 @@ export type EditKind = | 'group' | (string & {}) -type OperatorRights = - | Pick< - NonNullable, - 'builder_flows' | 'builder_apps' | 'manage_schedules' | 'manage_triggers' - > - | null - | undefined - /** - * Whether a user's role lets them author items of `kind` — create, edit, deploy or delete one — - * in a workspace with these `operator_settings`: the role half of every check against the item - * handlers. Saving a draft is `roleCanDraft`'s rule, and which items they may write is - * `canEditItem`'s other half. For an operator: - * - code (scripts, low-code apps, agents, pipelines): never; - * - flows and full-code apps: where the workspace grants `builder_flows` / `builder_apps` - * (`check_operator_can_build`); - * - schedules and triggers: unless the workspace set `manage_*` to false — a withdrawable - * right, so an unset key grants it (docs/operator-write-rights.md); + * Whether a role with `caps` lets its member author items of `kind` (create, edit, deploy or + * delete one): the role half of every check against the item handlers. Saving a draft is + * `roleCanDraft`'s rule, and which items they may write is `canEditItem`'s other half. + * - code (scripts, agents, pipelines): `code`; + * - flows and full-code apps: `compose` or above (`check_operator_can_build`); + * - low-code apps: `full` apps only (apps.rs `require_full_apps`); + * - schedules and triggers: the matching manage right; * - resources, variables and groups: always, their permissions alone decide. */ -export function roleCanAuthor( - kind: EditKind, - user: Pick | undefined, - operatorSettings: OperatorRights -): boolean { - if (!user?.operator) return true +export function roleCanAuthor(kind: EditKind, caps: RoleCapabilities): boolean { switch (kind) { case 'flow': + return caps.flows !== 'none' case 'raw_app': - return builderGrants(kind, operatorSettings) + return caps.apps !== 'none' + case 'app': + return caps.apps === 'full' case 'schedule': - return operatorSettings?.manage_schedules !== false + return caps.manage_schedules case 'trigger': - return operatorSettings?.manage_triggers !== false + return caps.manage_triggers case 'resource': case 'variable': case 'group': return true default: - return false + return caps.code } } /** - * Whether the user may save drafts of `kind` — what every session editor and the chat's draft - * tools write. Mirrors drafts.rs `require_can_write_path`, which differs from the item handlers - * both ways: it admits an admin before its operator branch, and an operator drafts only the kinds - * they could deploy — resources and variables always, flows and full-code apps under their builder - * right, schedules and triggers under the manage rights. + * Whether the role may save drafts of `kind`, which every session editor and the chat's draft + * tools write. Mirrors drafts.rs `operator_can_draft`: a restricted role drafts only the kinds it + * could deploy, and resources and variables always. An unrestricted role drafts every kind. */ -export function roleCanDraft( - kind: EditKind, - user: Pick | undefined, - operatorSettings: OperatorRights -): boolean { - if (user?.is_admin || user?.is_super_admin || !user?.operator) return true - switch (kind) { - case 'flow': - case 'raw_app': - return builderGrants(kind, operatorSettings) - case 'schedule': - case 'trigger': - return roleCanAuthor(kind, user, operatorSettings) - case 'resource': - case 'variable': - return true - default: - return false - } -} - -function builderGrants(kind: EditKind, operatorSettings: OperatorRights): boolean { - return ( - (kind === 'flow' && operatorSettings?.builder_flows === true) || - (kind === 'raw_app' && operatorSettings?.builder_apps === true) - ) +export function roleCanDraft(kind: EditKind, caps: RoleCapabilities): boolean { + if (!isRestricted(caps)) return true + return kind === 'group' ? false : roleCanAuthor(kind, caps) } /** `roleCanDraft` for the item at `path`, with its own permissions as in `canEditItem`. */ @@ -109,9 +73,9 @@ export function canDraftItem( path: string, extraPerms: Record | undefined, user: UserExt | undefined, - operatorSettings: OperatorRights + caps: RoleCapabilities ): boolean { - return roleCanDraft(kind, user, operatorSettings) && canWrite(path, extraPerms ?? {}, user) + return roleCanDraft(kind, caps) && canWrite(path, extraPerms ?? {}, user) } /** Whether `user` may edit the item at `path`: their role authors `kind`, and the item's own @@ -121,7 +85,7 @@ export function canEditItem( path: string, extraPerms: Record | undefined, user: UserExt | undefined, - operatorSettings: OperatorRights + caps: RoleCapabilities ): boolean { - return roleCanAuthor(kind, user, operatorSettings) && canWrite(path, extraPerms ?? {}, user) + return roleCanAuthor(kind, caps) && canWrite(path, extraPerms ?? {}, user) } diff --git a/frontend/src/lib/operatorWriteRights.ts b/frontend/src/lib/operatorWriteRights.ts index 916e39dce6..28a68784e6 100644 --- a/frontend/src/lib/operatorWriteRights.ts +++ b/frontend/src/lib/operatorWriteRights.ts @@ -1,29 +1,38 @@ import { derived, fromStore, get, readable, type Readable } from 'svelte/store' -import { userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' +import type { RoleCapabilities } from '$lib/gen' +import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { useActingUser } from '$lib/actingUser.svelte' import { canDraftItem, canEditItem, roleCanAuthor, roleCanDraft } from '$lib/editRights' +import { capabilitiesIn } from '$lib/roleCapabilities' /** * The `editRights` rules (`roleCanAuthor` / `canEditItem` for the item handlers, `roleCanDraft` / - * `canDraftItem` for drafts) answered for the user acting in the operating workspace, - * with that workspace's `operator_settings` — or in `workspace`, for a component that is handed - * one rather than sitting under a host that declares it. Reads context and registers an effect: - * call during component initialisation. + * `canDraftItem` for drafts) answered for the user acting in the operating workspace, with their + * role's capabilities there, or in `workspace`, for a component that is handed one rather than + * sitting under a host that declares it. Reads context and registers an effect: call during + * component initialisation. */ export function useEditRights(workspace?: () => string | undefined) { const operating = fromStore(useOperatingWorkspace()) const ws = workspace ?? (() => operating.current) const user = useActingUser(ws) const workspaces = fromStore(userWorkspaces) - const settings = () => workspaces.current.find((w) => w.id === ws())?.operator_settings + const caps = () => + capabilitiesIn( + user.current, + workspaces.current.find((w) => w.id === ws()) + ) return { - roleCanAuthor: (kind: string) => roleCanAuthor(kind, user.current, settings()), + get capabilities(): RoleCapabilities { + return caps() + }, + roleCanAuthor: (kind: string) => roleCanAuthor(kind, caps()), canEditItem: (kind: string, path: string, extraPerms: Record | undefined) => - canEditItem(kind, path, extraPerms, user.current, settings()), - roleCanDraft: (kind: string) => roleCanDraft(kind, user.current, settings()), + canEditItem(kind, path, extraPerms, user.current, caps()), + roleCanDraft: (kind: string) => roleCanDraft(kind, caps()), canDraftItem: (kind: string, path: string, extraPerms: Record | undefined) => - canDraftItem(kind, path, extraPerms, user.current, settings()), + canDraftItem(kind, path, extraPerms, user.current, caps()), /** This hook looks the user up on its own, so an editor that retries a failed lookup on * its acting user (`forgetFailures`) must retry this one too, or it stays read-only. */ forgetFailures: () => user.forgetFailures() @@ -31,20 +40,42 @@ export function useEditRights(workspace?: () => string | undefined) { } /** - * Why writes of this kind are locked in the operating workspace, or `undefined` when they are not — + * The role's capabilities in `workspace`, from the workspace list alone: `$userStore` describes + * only the navigation workspace, so elsewhere only superadmin carries over. Admins get full + * capabilities from the server's list. + */ +function capabilitiesStore(workspace: Readable): Readable { + return derived( + [userStore, workspaceStore, userWorkspaces, workspace], + ([$user, $nav, $workspaces, $ws]) => + capabilitiesIn( + $ws === $nav && $user?.workspace_id === $ws + ? $user + : { is_super_admin: $user?.is_super_admin }, + $workspaces.find((w) => w.id === $ws) + ) + ) +} + +/** The role's capabilities in the operating workspace. Reads context: call during component + * initialisation. Code outside any component reads `roleCapabilities` (navigation workspace) or + * `capabilitiesInWorkspace`. */ +export const useRoleCapabilities = () => capabilitiesStore(useOperatingWorkspace()) + +/** The role's capabilities in a given workspace, read once: for code acting on an explicit + * workspace rather than the nav's, such as the global AI chat. */ +export const capabilitiesInWorkspace = (workspace: string | undefined) => + get(capabilitiesStore(readable(workspace))) + +/** + * Why writes of this kind are locked in the operating workspace, or `undefined` when they are not: * the shape `title` and `disabled` both want. See `docs/operator-write-rights.md`. - * - * The role half of `roleCanAuthor`, phrased for the controls that explain it. `operator_settings` - * is non-null exactly for an operator (`isOperatorInWorkspace`), so it stands in for the user. */ function writeLock(kind: 'schedule' | 'trigger', noun: string) { - return derived([userWorkspaces, useOperatingWorkspace()], ([$userWorkspaces, $workspace]) => { - const settings = $userWorkspaces.find((w) => w.id === $workspace)?.operator_settings + return derived(useRoleCapabilities(), (caps) => // Worded as the server words its refusal of the same write. - return roleCanAuthor(kind, { operator: settings != null }, settings) - ? undefined - : `Operators cannot manage ${noun} in this workspace` - }) + roleCanAuthor(kind, caps) ? undefined : `Your role cannot manage ${noun} in this workspace` + ) } /** Reads context: call during component initialisation. */ @@ -52,55 +83,9 @@ export const useScheduleLock = () => writeLock('schedule', 'schedules') /** Reads context: call during component initialisation. */ export const useTriggerLock = () => writeLock('trigger', 'triggers') -/** - * True when the user is an operator of `workspace` and it granted operators the right to compose - * this kind out of runnables that are already deployed. They still author no code, and everywhere - * else `operator` keeps meaning read-only, so a gate on the operator role has to consult this before - * refusing. `operator_settings` is null for a non-operator, so this is false for them. - * - * The two rights are granted independently: anything that authors one kind must gate on that - * kind, or a flows-only workspace offers app affordances the backend then refuses. - */ -function builderRight( - key: 'builder_flows' | 'builder_apps', - workspace: Readable -): Readable { - return derived( - [userWorkspaces, workspace], - ([$userWorkspaces, $workspace]) => - $userWorkspaces.find((w) => w.id === $workspace)?.operator_settings?.[key] === true - ) -} - -/** Either right, only for surfaces that are not per-kind, such as the create menu's visibility. */ -function anyBuilderRight(workspace: Readable): Readable { - return derived( - [builderRight('builder_flows', workspace), builderRight('builder_apps', workspace)], - ([flows, apps]) => flows || apps - ) -} - -/** Builder rights in the operating workspace. Reads context: call during component - * initialisation. */ -export const useOperatorBuilderFlows = () => builderRight('builder_flows', useOperatingWorkspace()) -/** Reads context: call during component initialisation. */ -export const useOperatorBuilderApps = () => builderRight('builder_apps', useOperatingWorkspace()) -/** Reads context: call during component initialisation. */ -export const useOperatorBuilderRights = () => anyBuilderRight(useOperatingWorkspace()) - -/** Builder rights in the navigation workspace, for code outside any component: the legacy AI - * chat is one instance for the whole app and acts on the workspace the nav is on. */ -export const navigationOperatorBuilderFlows = builderRight('builder_flows', workspaceStore) -export const navigationOperatorBuilderApps = builderRight('builder_apps', workspaceStore) -export const navigationOperatorBuilderRights = anyBuilderRight(workspaceStore) - -/** The app builder right in a given workspace, read once: for code acting on an explicit - * workspace rather than the nav's, such as the global AI chat. */ -export const operatorBuilderAppsIn = (workspace: string | undefined) => - get(builderRight('builder_apps', readable(workspace))) - -/** Resolves once the workspace list has loaded. Every builder right reads false until then, so - * code that picks what a builder starts with on a fresh page load has to wait for it. */ +/** Resolves once the workspace list has loaded. Capabilities fall back to the user's legacy + * operator flag until then, so code that picks what a builder starts with on a fresh page load + * has to wait for it. */ export async function workspaceListLoaded(): Promise { let unsubscribe = () => {} await new Promise((resolve) => { diff --git a/frontend/src/lib/roleCapabilities.test.ts b/frontend/src/lib/roleCapabilities.test.ts new file mode 100644 index 0000000000..1962414042 --- /dev/null +++ b/frontend/src/lib/roleCapabilities.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import type { RoleCapabilities } from '$lib/gen' +import { capabilitiesIn, FULL_CAPABILITIES, hidesPages, isRestricted } from './roleCapabilities' + +const scripter: RoleCapabilities = { + ...FULL_CAPABILITIES, + apps: 'none', + visibility: { ...FULL_CAPABILITIES.visibility, workers: false } +} + +describe('capabilitiesIn', () => { + it("takes the server's capabilities, whatever the legacy operator flag says", () => { + const caps = capabilitiesIn({ operator: false }, { capabilities: scripter }) + expect(caps).toEqual(scripter) + expect(isRestricted(caps)).toBe(true) + }) + + it('gives an admin everything', () => { + expect(capabilitiesIn({ is_admin: true }, { capabilities: scripter })).toBe(FULL_CAPABILITIES) + }) + + // A server that predates roles sends `operator` and `operator_settings` only. + it('derives an operator from operator_settings on an older server', () => { + const caps = capabilitiesIn( + { operator: true }, + { operator_settings: { runs: true, builder_flows: true, manage_triggers: false } as any } + ) + expect(caps.code).toBe(false) + expect(caps.flows).toBe('compose') + expect(caps.apps).toBe('none') + expect(caps.manage_schedules).toBe(true) + expect(caps.manage_triggers).toBe(false) + expect(caps.visibility.runs).toBe(true) + // `=== true`: a flag the settings never mention, or settings never written, hide the page. + expect(caps.visibility.workers).toBe(false) + expect(capabilitiesIn({ operator: true }, undefined).visibility.runs).toBe(false) + expect(capabilitiesIn({ operator: false }, undefined)).toBe(FULL_CAPABILITIES) + }) + + // `RoleCapabilities::is_restricted` leaves visibility out, so a full author keeps forking. + it('does not restrict a full role that only hides pages', () => { + const hidden = { ...FULL_CAPABILITIES, visibility: { ...FULL_CAPABILITIES.visibility, workers: false } } + expect(isRestricted(hidden)).toBe(false) + expect(hidesPages(hidden)).toBe(true) + }) +}) diff --git a/frontend/src/lib/roleCapabilities.ts b/frontend/src/lib/roleCapabilities.ts new file mode 100644 index 0000000000..55beec9ee0 --- /dev/null +++ b/frontend/src/lib/roleCapabilities.ts @@ -0,0 +1,74 @@ +import type { OperatorSettings, RoleCapabilities, RoleVisibility } from '$lib/gen' +import type { UserExt, UserWorkspace } from '$lib/stores' +import { FULL_CAPABILITIES, VISIBILITY_KEYS } from '$lib/workspaceRoles' + +/** + * What a member's workspace role lets them author, manage and see: the frontend's copy of + * `windmill_common::roles`, see `docs/workspace-roles.md`. Gate on these, never on + * `UserExt.operator`, which only says "this role cannot write code" and so lets through a role + * that may code but not, say, build apps. + */ + +export type VisibilityKey = keyof RoleVisibility + +export { FULL_CAPABILITIES } + +const VISIBILITY = VISIBILITY_KEYS.map((v) => v.key) + +/** + * The operator role as a server that predates roles describes it, through `operator_settings`: + * builder rights are `compose`, the manage rights are granted unless withdrawn, and a page is + * visible only when its flag is `true` (absent settings hide every page, as they always did). + */ +export function legacyOperatorCapabilities( + settings: OperatorSettings | null | undefined +): RoleCapabilities { + const visibility = Object.fromEntries( + VISIBILITY.map((k) => [k, settings?.[k] === true]) + ) as RoleVisibility + return { + code: false, + flows: settings?.builder_flows === true ? 'compose' : 'none', + apps: settings?.builder_apps === true ? 'compose' : 'none', + manage_schedules: settings?.manage_schedules !== false, + manage_triggers: settings?.manage_triggers !== false, + visibility + } +} + +export type CapabilitiesUser = Partial> +export type CapabilitiesWorkspace = Pick + +/** + * The capabilities of `user` in `workspace` (its entry of `$userWorkspaces`). An admin holds + * everything. The server's `capabilities` win; an older server sends none, and the role is then + * derived from `operator` and `operator_settings` the way it read them. Without a user, a + * non-null `operator_settings` is what marks an operator, as the server sends it to them only. + */ +export function capabilitiesIn( + user: CapabilitiesUser | undefined, + workspace: CapabilitiesWorkspace | undefined +): RoleCapabilities { + if (user?.is_admin || user?.is_super_admin) return FULL_CAPABILITIES + if (workspace?.capabilities) return workspace.capabilities + const operator = user?.operator ?? workspace?.operator_settings != null + return operator ? legacyOperatorCapabilities(workspace?.operator_settings) : FULL_CAPABILITIES +} + +/** Whether the role is gated at all, as `RoleCapabilities::is_restricted`: visibility is left out, + * since hiding a page must not cost a full author what restricted roles are refused, such as + * forking. */ +export function isRestricted(caps: RoleCapabilities): boolean { + return ( + !caps.code || + caps.flows !== 'full' || + caps.apps !== 'full' || + !caps.manage_schedules || + !caps.manage_triggers + ) +} + +/** Whether the role hides any page. */ +export function hidesPages(caps: RoleCapabilities): boolean { + return VISIBILITY.some((k) => !caps.visibility[k]) +} diff --git a/frontend/src/lib/stores.ts b/frontend/src/lib/stores.ts index a3147b171c..16b62da863 100644 --- a/frontend/src/lib/stores.ts +++ b/frontend/src/lib/stores.ts @@ -5,6 +5,7 @@ import type { IntrospectionQuery } from 'graphql' import { CancelablePromise, type OperatorSettings, + type RoleCapabilities, type TokenResponse, type UserWorkspaceList, type Workspace, @@ -12,6 +13,7 @@ import { WorkspaceService } from './gen' import { getLocalSetting, type StateStore } from './utils' +import { capabilitiesIn } from './roleCapabilities' import { createState } from './svelte5Utils.svelte' import { DEFAULT_HUB_BASE_URL } from './hub' import type { DbManagerUriState } from './components/dbManagerDrawerModel.svelte' @@ -46,6 +48,9 @@ export interface UserWorkspace { username: string color?: string operator_settings?: OperatorSettings + /** Absent from a server that predates roles; read it through `capabilitiesIn`. */ + role?: string + capabilities?: RoleCapabilities parent_workspace_id?: string | null is_dev_workspace?: boolean dev_workspace_label?: string | null @@ -191,6 +196,18 @@ export const userWorkspaces: Readable> = derived( } ) +/** The user's role capabilities in the navigation workspace. A component acting on another + * workspace (an AI session) reads `useRoleCapabilities` instead. */ +export const roleCapabilities: Readable = derived( + [userStore, userWorkspaces, workspaceStore], + ([user, workspaces, workspace]) => + capabilitiesIn( + // Mid-switch `user` still describes the workspace being left: only superadmin carries over. + user?.workspace_id === workspace ? user : { is_super_admin: user?.is_super_admin }, + workspaces.find((w) => w.id === workspace) + ) +) + export const codeCompletionLoading = writable(false) export const metadataCompletionEnabled = writable(true) export const stepInputCompletionEnabled = writable(true) diff --git a/frontend/src/lib/utils/editInFork.ts b/frontend/src/lib/utils/editInFork.ts index d43c3644c9..9e74878f39 100644 --- a/frontend/src/lib/utils/editInFork.ts +++ b/frontend/src/lib/utils/editInFork.ts @@ -1,5 +1,8 @@ import { get } from 'svelte/store' +import { isRestricted } from '$lib/roleCapabilities' +import type { RoleCapabilities } from '$lib/gen' import { + roleCapabilities, userStore, userWorkspaces, workspaceStore, @@ -19,16 +22,17 @@ export type ItemType = 'script' | 'flow' | 'app' | 'raw_app' * Whether to show the "edit in fork / dev workspace" affordance. Allowed when the user may create a * fork, OR when the current workspace has a canonical dev to route to — routing into an existing dev * workspace creates no fork, so it survives a locked prod that has `DisableWorkspaceForking` set. - * Never for an operator, who has nothing to edit at the other end either way. User identity is read - * non-reactively (it's stable within a session); reactivity comes from the workspace args. + * Never for a role without `code`, which has nothing to edit at the other end either way. User + * identity is read non-reactively (it's stable within a session); reactivity comes from the + * workspace args. */ export function editInForkAllowed( currentWorkspaceId: string | undefined, allWorkspaces: UserWorkspace[] ): boolean { - const user = get(userStore) - if (user?.operator) return false - return canCreateFork(user) || !!findCanonicalDevWorkspace(currentWorkspaceId, allWorkspaces) + const caps = get(roleCapabilities) + if (!caps.code) return false + return canCreateFork(get(userStore), caps) || !!findCanonicalDevWorkspace(currentWorkspaceId, allWorkspaces) } /** Label for the affordance: "Edit in " when routed to a canonical dev, else "Edit in fork". */ @@ -54,17 +58,17 @@ export function editInForkDescription( } /** - * Whether the user may CREATE a new fork of the current workspace: not an operator, and either - * forking isn't disabled or they can bypass the rule (workspace admins). Keeps the "Fork workspace" - * entry available to admins as the last-resort escape hatch on a locked prod. + * Whether the user may CREATE a new fork of the current workspace: their role is unrestricted, and + * either forking isn't disabled or they can bypass the rule (workspace admins). Keeps the "Fork + * workspace" entry available to admins as the last-resort escape hatch on a locked prod. * - * An operator is refused because a fork does not carry the role: the server writes the forker's - * membership row from the parent's `is_admin` and lets `operator` fall to its `false` default, so - * forking would hand an operator a full-rights copy of the workspace. The server does not refuse it - * — this hides the affordance, it does not enforce the rule. + * Any restricted role is refused because a fork does not carry the role: the server writes the + * forker's membership row from the parent's `is_admin` alone, so the forker gets the default role + * and forking would hand a restricted member a full-rights copy of the workspace. The server does + * not refuse it: this hides the affordance, it does not enforce the rule. */ -export function canCreateFork(user: UserExt | undefined): boolean { - if (user?.operator) return false +export function canCreateFork(user: UserExt | undefined, caps: RoleCapabilities): boolean { + if (isRestricted(caps)) return false return ( !isRuleActive('DisableWorkspaceForking') || canUserBypassRuleKind('DisableWorkspaceForking', user) diff --git a/frontend/src/lib/utils/previewOnBehalfOf.ts b/frontend/src/lib/utils/previewOnBehalfOf.ts index 5ca4d9133c..3b28223b88 100644 --- a/frontend/src/lib/utils/previewOnBehalfOf.ts +++ b/frontend/src/lib/utils/previewOnBehalfOf.ts @@ -5,8 +5,9 @@ type ActingUser = /** * The identity an editor preview should run as: the runnable's configured run-as identity, so a * test behaves like the current deployed run. Only admins and `wm_deployers` may preview as - * someone else, and never operators (the server refuses everyone else); anyone else previews as - * themselves, which is also what their own save would record. + * someone else, and never a role without `code`, which is what `operator` carries (the server + * refuses everyone else); anyone else previews as themselves, which is also what their own save + * would record. */ export function previewOnBehalfOf( user: ActingUser, diff --git a/frontend/src/lib/utils_workspace_deploy.test.ts b/frontend/src/lib/utils_workspace_deploy.test.ts index dfac557d20..b970600ee7 100644 --- a/frontend/src/lib/utils_workspace_deploy.test.ts +++ b/frontend/src/lib/utils_workspace_deploy.test.ts @@ -239,14 +239,17 @@ describe('workspace-level deploy permission', () => { expect(res.reason).toContain('Direct deployment') }) - // The server refuses an operator in the item handler regardless of their global role: a - // superadmin who is an operator in the workspace still gets 401 creating a script. So the - // operator term has to stay above the admin/superadmin short-circuit — hoisting the admin - // checks would offer a deploy the server refuses. - it('refuses an operator who is also a superadmin', async () => { + // Authentication merges superadmin into admin, and `caller_capabilities` gives an admin every + // capability, whatever the workspace role. + it('lets a superadmin whose role is operator deploy', async () => { const res = await permission({ ...member, operator: true, is_super_admin: true }, []) + expect(res.ok).toBe(true) + }) + + it('refuses a member whose role cannot code', async () => { + const res = await permission({ ...member, operator: true }, []) expect(res.ok).toBe(false) - expect(res.reason).toContain('operator') + expect(res.reason).toContain('role') }) }) diff --git a/frontend/src/lib/utils_workspace_deploy.ts b/frontend/src/lib/utils_workspace_deploy.ts index 91820b581e..9d5b5409b8 100644 --- a/frontend/src/lib/utils_workspace_deploy.ts +++ b/frontend/src/lib/utils_workspace_deploy.ts @@ -22,6 +22,11 @@ import { type User } from '$lib/gen' import type { UserDraftItemKind } from '$lib/gen' +import { get } from 'svelte/store' +import { userWorkspaces } from '$lib/stores' +import { capabilitiesIn } from '$lib/roleCapabilities' +import { roleCanAuthor } from '$lib/editRights' +import type { RoleCapabilities } from '$lib/gen' import { fetchProtectionRulesForWorkspace, canUserBypassRuleKindInRulesets @@ -836,6 +841,24 @@ export function kindGatedByDeployRules(kind: Kind | UserDraftItemKind): boolean return GATED_KIND_NAMES.has(kind) } +// The kinds whose item handlers refuse a role per kind (`check_role_can_code`, +// `check_operator_can_build`, `require_full_apps`). `checkDeployPermission` only asks for `code`, +// so a role that codes but cannot author flows or apps is caught here. +const ROLE_GATED_KINDS = new Set(['script', 'flow', 'app', 'raw_app', 'data_pipeline']) + +function roleRefusal( + kind: Kind | UserDraftItemKind, + caps: RoleCapabilities +): DeployPermission | undefined { + if (!ROLE_GATED_KINDS.has(kind) || roleCanAuthor(kind === 'data_pipeline' ? 'script' : kind, caps)) + return undefined + return { + ok: false, + reason: `Your role in this workspace can't deploy ${kind.replace('_', ' ')}s`, + refusedBy: 'operator' + } +} + /** * Narrow a workspace-level refusal to one item kind. Only the direct-deployment term is scoped: * the deployers-only term over-reaches the same way, but it does so on `main` too, and loosening @@ -843,8 +866,11 @@ export function kindGatedByDeployRules(kind: Kind | UserDraftItemKind): boolean */ export function deployPermissionForKind( perm: DeployPermission, - kind: Kind | UserDraftItemKind + kind: Kind | UserDraftItemKind, + caps?: RoleCapabilities ): DeployPermission { + const refusal = caps && roleRefusal(kind, caps) + if (refusal) return refusal if (perm.ok) return perm if (perm.refusedBy === 'DisableDirectDeployment' && !kindGatedByDeployRules(kind)) { return { ok: true } @@ -855,8 +881,11 @@ export function deployPermissionForKind( /** The refusal a bulk action carries: it applies as soon as one selected kind is still refused. */ export function deployPermissionForKinds( perm: DeployPermission, - kinds: (Kind | UserDraftItemKind)[] + kinds: (Kind | UserDraftItemKind)[], + caps?: RoleCapabilities ): DeployPermission { + const refusal = caps && kinds.map((k) => roleRefusal(k, caps)).find((r) => r) + if (refusal) return refusal if (perm.ok) return perm // An empty selection keeps the workspace-level refusal, which is then the only thing left // to say why the action is unavailable. @@ -933,9 +962,9 @@ export async function checkDeployRules( /** * Whether the current user may deploy into `workspace` at all: the protection rules above, - * plus a refusal of every operator. + * plus a refusal of every role without `code`. * - * That refusal is not part of the `check_deploy_rules` mirror. The server refuses operators + * That refusal is not part of the `check_deploy_rules` mirror. The server refuses such roles * in the item handlers instead, and for fewer kinds, so refusing them for everything here is * deliberately stricter than the server rather than a faithful copy of it. A caller mirroring * one handler wants `checkDeployRules`. @@ -948,10 +977,10 @@ export async function checkDeployPermission( ): Promise { try { const me = whoami ?? (await UserService.whoami({ workspace })) - if (me.operator) { + if (!capabilitiesIn(me, get(userWorkspaces).find((w) => w.id === workspace)).code) { return { ok: false, - reason: "You're an operator in this workspace — operators can't deploy", + reason: "Your role in this workspace can't deploy", refusedBy: 'operator' } } diff --git a/frontend/src/lib/workspaceRoles.test.ts b/frontend/src/lib/workspaceRoles.test.ts new file mode 100644 index 0000000000..84f3ff8a71 --- /dev/null +++ b/frontend/src/lib/workspaceRoles.test.ts @@ -0,0 +1,64 @@ +import { describe, it, expect } from 'vitest' +import type { EffectiveRole } from '$lib/gen' +import { + applyCapabilitiesPatch, + baseCapabilitiesFor, + FULL_CAPABILITIES, + validRoleOr, + workspaceRolesErrors +} from './workspaceRoles' + +// These mirror `windmill_common::roles`; the server refuses what they let through. +describe('role capability layering', () => { + it('falls back to full for developer and to the operator rights for any other name', () => { + expect(baseCapabilitiesFor('developer')).toEqual(FULL_CAPABILITIES) + const other = baseCapabilitiesFor('reviewer') + expect([other.code, other.flows, other.manage_schedules]).toEqual([false, 'none', true]) + }) + + it('applies only the keys a patch sets', () => { + const caps = applyCapabilitiesPatch(baseCapabilitiesFor('x'), { + flows: 'compose', + visibility: { workers: false } + }) + expect(caps.flows).toBe('compose') + expect(caps.apps).toBe('none') + expect(caps.visibility.workers).toBe(false) + expect(caps.visibility.runs).toBe(true) + }) + + it('treats a stored null as unset, as serde reads it', () => { + const caps = applyCapabilitiesPatch(baseCapabilitiesFor('developer'), { + code: null as any, + visibility: { runs: null as any } + }) + expect(caps).toEqual(FULL_CAPABILITIES) + expect( + workspaceRolesErrors([{ name: 'developer', capabilities: { code: null as any } }]) + ).toEqual({}) + }) + + it('refuses what parse_instance_roles refuses', () => { + expect(workspaceRolesErrors(undefined)).toEqual({}) + expect(workspaceRolesErrors([])).toHaveProperty('list') + expect(workspaceRolesErrors([{ name: 'admin' }])).toHaveProperty('0.name') + expect(workspaceRolesErrors([{ name: 'a' }, { name: 'a' }])).toHaveProperty('1.name') + expect(workspaceRolesErrors([{ name: 'x', capabilities: { flows: 'full' } }])).toHaveProperty( + '0.capabilities' + ) + expect( + workspaceRolesErrors([{ name: 'developer', capabilities: { apps: 'compose' } }]) + ).toEqual({}) + }) +}) + +describe('validRoleOr', () => { + const role = (name: string) => ({ name }) as EffectiveRole + + it('falls back to developer, or the first role when the instance dropped it', () => { + expect(validRoleOr([role('operator'), role('developer')], undefined)).toBe('developer') + expect(validRoleOr([role('builder'), role('viewer')], undefined)).toBe('builder') + expect(validRoleOr([role('builder'), role('viewer')], 'developer')).toBe('builder') + expect(validRoleOr([role('builder')], 'admin')).toBe('admin') + }) +}) diff --git a/frontend/src/lib/workspaceRoles.ts b/frontend/src/lib/workspaceRoles.ts new file mode 100644 index 0000000000..4cfb3a6089 --- /dev/null +++ b/frontend/src/lib/workspaceRoles.ts @@ -0,0 +1,218 @@ +import { + WorkspaceService, + type AuthorLevel, + type EffectiveRole, + type RoleCapabilities, + type RoleCapabilitiesPatch, + type RoleDefinition, + type RoleVisibility, + type WorkspaceRoles +} from '$lib/gen' + +/** Not a role: the `is_admin` flag, offered next to the roles wherever a member's access is picked. */ +export const ADMIN_ROLE = 'admin' + +export const DEVELOPER_ROLE = 'developer' +export const OPERATOR_ROLE = 'operator' + +export const VISIBILITY_KEYS: { key: keyof RoleVisibility; label: string }[] = [ + { key: 'runs', label: 'Runs' }, + { key: 'schedules', label: 'Schedules' }, + { key: 'resources', label: 'Resources' }, + { key: 'variables', label: 'Variables' }, + { key: 'assets', label: 'Assets' }, + { key: 'triggers', label: 'Triggers' }, + { key: 'audit_logs', label: 'Audit logs' }, + { key: 'groups', label: 'Groups' }, + { key: 'folders', label: 'Folders' }, + { key: 'workers', label: 'Workers' } +] + +const ALL_VISIBLE: RoleVisibility = { + runs: true, + schedules: true, + resources: true, + variables: true, + assets: true, + triggers: true, + audit_logs: true, + groups: true, + folders: true, + workers: true +} + +// Mirror `RoleCapabilities::FULL` and `RoleCapabilities::OPERATOR` in `windmill_common::roles`. +export const FULL_CAPABILITIES: RoleCapabilities = { + code: true, + flows: 'full', + apps: 'full', + manage_schedules: true, + manage_triggers: true, + visibility: ALL_VISIBLE +} + +const OPERATOR_CAPABILITIES: RoleCapabilities = { + code: false, + flows: 'none', + apps: 'none', + manage_schedules: true, + manage_triggers: true, + visibility: ALL_VISIBLE +} + +export const DEFAULT_INSTANCE_ROLES: RoleDefinition[] = [ + { name: DEVELOPER_ROLE, label: 'Developer', capabilities: {} }, + { name: OPERATOR_ROLE, label: 'Operator', capabilities: {} } +] + +/** What a role named `name` holds before any configuration: `RoleCapabilities::base_for`. */ +export function baseCapabilitiesFor(name: string): RoleCapabilities { + return applyCapabilitiesPatch( + name === DEVELOPER_ROLE ? FULL_CAPABILITIES : OPERATOR_CAPABILITIES, + undefined + ) +} + +export function applyCapabilitiesPatch( + base: RoleCapabilities, + patch: RoleCapabilitiesPatch | undefined +): RoleCapabilities { + // Spread rather than `structuredClone`: `base` may be a Svelte state proxy, which cannot be cloned. + const out: RoleCapabilities = { ...base, visibility: { ...base.visibility } } + if (!patch) return out + // `!= null`: a stored `null` deserializes to `None` server-side, so it is unset like `undefined`. + if (patch.code != null) out.code = patch.code + if (patch.flows != null) out.flows = patch.flows + if (patch.apps != null) out.apps = patch.apps + if (patch.manage_schedules != null) out.manage_schedules = patch.manage_schedules + if (patch.manage_triggers != null) out.manage_triggers = patch.manage_triggers + for (const { key } of VISIBILITY_KEYS) { + const v = patch.visibility?.[key] + if (v != null) out.visibility[key] = v + } + return out +} + +/** The error the server raises for these capabilities, if any (`RoleCapabilities::validate`). */ +export function capabilitiesError(caps: RoleCapabilities): string | undefined { + if (!caps.code && (caps.flows === 'full' || caps.apps === 'full')) { + return 'Full flow or app authoring requires the code capability' + } + return undefined +} + +/** `validate_role_name` in `windmill_common::roles`. */ +export function roleNameError(name: string): string | undefined { + if (name === ADMIN_ROLE) return 'The name admin is reserved' + if (!/^[a-z0-9_-]{1,50}$/.test(name)) { + return 'Use 1 to 50 lowercase letters, digits, underscores or hyphens' + } + return undefined +} + +/** A patch with no key set, so it is dropped rather than stored as `{}`. */ +export function isEmptyPatch(patch: RoleCapabilitiesPatch | undefined): boolean { + if (!patch) return true + const { visibility, ...rest } = patch + return ( + Object.values(rest).every((v) => v == null) && + Object.values(visibility ?? {}).every((v) => v == null) + ) +} + +/** + * What `parse_instance_roles` would refuse in a `workspace_roles` value, keyed `.name`, + * `.capabilities` or `list`. An unset value is the defaults and always valid. + */ +export function workspaceRolesErrors(value: unknown): Record { + if (value == undefined) return {} + if (!Array.isArray(value)) return { list: 'Expected a list of roles' } + if (value.length === 0) return { list: 'Keep at least one role' } + const errors: Record = {} + const seen = new Set() + value.forEach((r: RoleDefinition, i) => { + const nameError = roleNameError(r?.name ?? '') + if (nameError) errors[`${i}.name`] = nameError + else if (seen.has(r.name)) errors[`${i}.name`] = 'Another role has this name' + seen.add(r?.name) + const capsError = capabilitiesError( + applyCapabilitiesPatch(baseCapabilitiesFor(r?.name ?? ''), r?.capabilities) + ) + if (capsError) errors[`${i}.capabilities`] = capsError + }) + return errors +} + +/** Whether `roles` is the default list, which is stored as no value at all. */ +export function isDefaultInstanceRoles(roles: RoleDefinition[]): boolean { + return ( + roles.length === DEFAULT_INSTANCE_ROLES.length && + roles.every( + (r, i) => + r.name === DEFAULT_INSTANCE_ROLES[i].name && + (r.label ?? '') === DEFAULT_INSTANCE_ROLES[i].label && + isEmptyPatch(r.capabilities) + ) + ) +} + +export function authorLevelLabel(level: AuthorLevel): string { + return level === 'none' ? 'None' : level === 'compose' ? 'Compose' : 'Full' +} + +export async function loadWorkspaceRoles(workspace: string): Promise { + return await WorkspaceService.listWorkspaceRoles({ workspace }) +} + +/** + * The role a new member gets when none is picked: `developer` while the workspace defines it, + * the first role otherwise, as the server picks one. + */ +export function defaultRoleName(roles: EffectiveRole[] | undefined): string { + if (!roles?.length || roles.some((r) => r.name === DEVELOPER_ROLE)) return DEVELOPER_ROLE + return roles[0].name +} + +/** `value` while the workspace still defines it (or it is Admin), the default role otherwise. */ +export function validRoleOr(roles: EffectiveRole[] | undefined, value: string | undefined): string { + if (value === ADMIN_ROLE || (value && (!roles || roles.some((r) => r.name === value)))) { + return value + } + return defaultRoleName(roles) +} + +/** Role picker items: the workspace's roles in their order, then Admin. */ +export function roleItems( + roles: EffectiveRole[] | undefined, + opts: { admin?: boolean } = {} +): { label: string; value: string }[] { + const items = (roles ?? []).map((r) => ({ label: r.label, value: r.name })) + if (opts.admin ?? true) items.push({ label: 'Admin', value: ADMIN_ROLE }) + return items +} + +export function roleLabel(roles: EffectiveRole[] | undefined, name: string | undefined): string { + if (!name) return '' + if (name === ADMIN_ROLE) return 'Admin' + return roles?.find((r) => r.name === name)?.label ?? name +} + +/** The picker value of a member, invite or mapping: `admin` for an admin, its role otherwise. */ +export function pickerValue(m: { is_admin?: boolean; role?: string; operator?: boolean }): string { + if (m.is_admin) return ADMIN_ROLE + return m.role ?? (m.operator ? OPERATOR_ROLE : DEVELOPER_ROLE) +} + +/** + * The fields a picked value is sent as. An admin keeps a role underneath the flag, `developer` + * being what the server gives one when none is named; `operator` is set for servers that predate + * roles. + */ +export function roleRequestFields(value: string): { + is_admin: boolean + operator: boolean + role?: string +} { + if (value === ADMIN_ROLE) return { is_admin: true, operator: false } + return { is_admin: false, operator: value === OPERATOR_ROLE, role: value } +} diff --git a/frontend/src/routes/(root)/(logged)/+layout.svelte b/frontend/src/routes/(root)/(logged)/+layout.svelte index 3084d7dfc2..fd4b828be3 100644 --- a/frontend/src/routes/(root)/(logged)/+layout.svelte +++ b/frontend/src/routes/(root)/(logged)/+layout.svelte @@ -54,6 +54,7 @@ nonMemberWorkspaces, setNonMemberWorkspaces, clearNonMemberWorkspaces, + roleCapabilities, type UserWorkspace } from '$lib/stores' import CenteredModal from '$lib/components/CenteredModal.svelte' @@ -93,7 +94,6 @@ import { overlayStack } from '$lib/components/common/overlayHost.svelte' import PageHeaderBar from '$lib/components/PageHeaderBar.svelte' import { BAR_HEIGHT_PX, pageHeader } from '$lib/components/pageHeaderRegistry.svelte' - import { sidebarPageAllowed } from '$lib/components/sidebar/operatorRoutes' import type GlobalSearchModal from '$lib/components/search/GlobalSearchModal.svelte' import MenuButton from '$lib/components/sidebar/MenuButton.svelte' import MenuLink from '$lib/components/sidebar/MenuLink.svelte' @@ -166,7 +166,7 @@ let collapsedState = $state(collapsePref.val) // Operators never get the icon-only rail: their docked sidebar is always expanded (a sidebar // they want out of the way is what detaching is for). - let isCollapsed = $derived(collapsedState && !$userStore?.operator) + let isCollapsed = $derived(collapsedState && $roleCapabilities.code) // Resizable desktop rail, sized in REM so it scales with the root font-size the // same way the old `w-52`/`w-12` classes did — `:root` jumps to 18px on screens @@ -247,7 +247,7 @@ // instead: dragging the sidebar off the left edge puts it behind the handle. // Detaching is not a resize, so the width the drag started from is what gets // persisted — re-attaching restores the sidebar at the size it had. - if (collapse && $userStore?.operator) { + if (collapse && !$roleCapabilities.code) { sidebarWidth = widthAtStart stop() setDetached(true) @@ -306,7 +306,7 @@ // (SessionModeSwitch) just navigates in and out of that route. // An operator without the opt-in (`gate.ts`) is refused by /sessions, so their sidebar is not // handed over to a session list the page behind it declines, and they keep the docked chat. - const sessionsAllowed = $derived(sessionsAllowedFor($userStore?.operator)) + const sessionsAllowed = $derived(sessionsAllowedFor(!$roleCapabilities.code)) let sessionMode = $derived(page.url.pathname.startsWith('/sessions') && sessionsAllowed) // Session mode points the bottom settings entry at the open session's own // workspace. An unsent draft hasn't committed one yet, so it falls back to @@ -1146,11 +1146,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden label="Runs" href="/runs" icon={Play} - disabled={!sidebarPageAllowed( - $userStore?.operator, - $userWorkspaces?.find((w) => w.id === $workspaceStore), - 'runs' - )} + disabled={!$roleCapabilities.visibility.runs} isCollapsed={collapsed} aiId="sidebar-menu-link-runs" aiDescription="Button to navigate to runs" @@ -1182,7 +1178,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden with a sidebar they cannot return. --> {#snippet sidebarToggle()} {@const hidden = navDetached.val} - {#if hidden || $userStore?.operator} + {#if hidden || !$roleCapabilities.code} - {#if !($userStore?.operator || (!$userStore?.is_admin && !$superadmin))} + {#if $roleCapabilities.code && ($userStore?.is_admin || $superadmin)} - {/snippet} - - {/if} + {/if} + {/snippet} + - {#if showEditButton} - - - {/if} {/if} {#if canEditInFork} {/if} {/if} {/if} + {#if job?.job_kind === 'script' || job?.job_kind === 'script_hub' || job?.job_kind === 'flow'} + + {#if pageHeader.actionFold >= 1} + goto('#superadmin-settings') }]} + /> + {:else} + + {/if} {/if} + + {/snippet} diff --git a/frontend/src/lib/components/home/ListFilters.svelte b/frontend/src/lib/components/home/ListFilters.svelte index 5482c59c42..9714b18aa4 100644 --- a/frontend/src/lib/components/home/ListFilters.svelte +++ b/frontend/src/lib/components/home/ListFilters.svelte @@ -1,6 +1,6 @@ {#if Array.isArray(filtersAndSelected) && filtersAndSelected.length > 0}
- {#each displayedFilters as filter (filter)} -
- + { selectedFilter = selectedFilter == filter ? undefined : filter writeQuery(selectedFilter) }} - {color} - clickable - selected={filter === selectedFilter} > - - {#if icon} - {@const Icon = icon} - - {:else if resourceType} - {@const SvelteComponent = appIconComponent(filter)} - {#if SvelteComponent} - - {/if} - {:else if filter.startsWith('u/')} - - {:else if filter.startsWith('f/')} - + {#if !icon && resourceType} + {@const AppIcon = appIconComponent(filter)} + {#if AppIcon} + {/if} - + {/if} {resourceType ? integrationDisplayName(filter) : filter} - {#if filter === selectedFilter}✗{/if} - +
{/each} - {#if hiddenCount > 0} -
- (expanded = !expanded)} - > - {expanded ? 'Show less' : '…'} - -
- {/if}
{/if} diff --git a/frontend/src/lib/components/home/TreeOwnerRow.svelte b/frontend/src/lib/components/home/TreeOwnerRow.svelte new file mode 100644 index 0000000000..6a5f95dee3 --- /dev/null +++ b/frontend/src/lib/components/home/TreeOwnerRow.svelte @@ -0,0 +1,58 @@ + + + + +
+
0 ? `padding-left: ${indent}px;` : ''} + > + +
+ {name} +
+ {@render detail()} +
+
+
+ + +
diff --git a/frontend/src/lib/components/home/TreeView.svelte b/frontend/src/lib/components/home/TreeView.svelte index 806787cb76..37d97b1f61 100644 --- a/frontend/src/lib/components/home/TreeView.svelte +++ b/frontend/src/lib/components/home/TreeView.svelte @@ -3,13 +3,14 @@ import { createEventDispatcher, onDestroy, untrack, type Snippet } from 'svelte' import ResizeTransitionWrapper from '$lib/components/common/ResizeTransitionWrapper.svelte' - import { ChevronDown, ChevronUp, Folder, FolderTree, User } from 'lucide-svelte' + import { Folder, FolderTree, User } from 'lucide-svelte' + import TreeOwnerRow from './TreeOwnerRow.svelte' import PipelineRow from '../common/table/PipelineRow.svelte' import Item from './Item.svelte' import { countLeaves, type FolderItem, type ItemType, type UserItem } from './treeViewUtils' - import { twMerge } from 'tailwind-merge' import { pluralize } from '$lib/utils' import { Button } from '$lib/components/common' + import { inUnruledList, rowRule } from '../common/table/unruledList' interface Props { item: ItemType | FolderItem | UserItem @@ -72,6 +73,8 @@ leaf }: Props = $props() + const unruled = inUnruledList() + let visualDepth = $derived(depth + indent) const dispatch = createEventDispatcher<{ reload: void }>() @@ -262,56 +265,30 @@ {#if isFolder(item) || isUser(item)}
- - -
-
0 ? `padding-left: ${visualDepth * 16}px;` : ''} - > -
- {#if isUser(item)} - - {:else if depth === 0} - - {:else} - - {/if} -
- -
- - {#if isUser(item)}u/{item.username}{:else}{#if depth === 0}f/{/if}{item.folderName}{/if} - -
- {#if ownerCount != undefined} - ({pluralize(ownerCount, ' item')}) - {:else if isLazyOwner && !ownerState?.loaded} - -   - {:else if nodeHasMore} - - ({loadedHere}+ items) - {:else} - ({pluralize(loadedHere, ' item')}) - {/if} -
-
-
- -
+ {/snippet} + @@ -350,7 +327,9 @@ {/each} {#if effectiveMax < item.items.length}
diff --git a/frontend/src/lib/components/home/TreeViewRoot.svelte b/frontend/src/lib/components/home/TreeViewRoot.svelte index 753feb6a8b..793667ce5b 100644 --- a/frontend/src/lib/components/home/TreeViewRoot.svelte +++ b/frontend/src/lib/components/home/TreeViewRoot.svelte @@ -3,7 +3,9 @@ import TreeView from './TreeView.svelte' import { countLeaves, groupItems, type ItemType, type UserItem } from './treeViewUtils' import { Button } from '$lib/components/common' - import { ChevronDown, ChevronUp, Users } from 'lucide-svelte' + import { Users } from 'lucide-svelte' + import TreeOwnerRow from './TreeOwnerRow.svelte' + import { inUnruledList, rowRule } from '../common/table/unruledList' import { getLocalSetting, pluralize, storeLocalSetting } from '$lib/utils' interface Props { @@ -40,6 +42,8 @@ onExpandOwner?: (owner: string, more?: boolean, opts?: { all?: boolean }) => void onCollapseOwner?: (owner: string) => void showEditButton?: boolean + /** Off where the tree is part of its host's list rather than a box of its own (Home). */ + framed?: boolean // Tuck every user space but `selfUsername`'s into one collapsible "Other users" row // under it. Only for browsing: a search or filter must not hide its matches behind // a closed row. @@ -66,10 +70,13 @@ onExpandOwner, onCollapseOwner, showEditButton = true, + framed = true, groupOtherUsers = false, leaf }: Props = $props() + const unruled = inUnruledList() + // How many root nodes render at once. A root node is a collapsed owner row that // fetches nothing until expanded, so a large slice costs a row each and no request // — and an owner sliced off the end is indistinguishable from one that doesn't @@ -280,42 +287,25 @@ -
+
{#each rows.slice(0, nbDisplayed) as row (row.kind === 'otherUsers' ? 'other_users' : 'folderName' in row.node ? `f__${row.node.folderName}` : 'username' in row.node ? `u__${row.node.username}` : `i__${row.node.type}__${row.node.path}`)} {#if row.kind === 'otherUsers'} - - -
-
- -
- Other users -
- ({pluralize(otherUsers.length, 'user')}{otherUsersItemCount != undefined - ? ` · ${pluralize(otherUsersItemCount, 'item')}` - : ''}) -
-
-
-
+ {#snippet detail()} + ({pluralize(otherUsers.length, 'user')}{otherUsersItemCount != undefined + ? ` · ${pluralize(otherUsersItemCount, 'item')}` + : ''}) + {/snippet} + {#if otherUsersOpen} @@ -324,7 +314,9 @@ {/each} {#if nbOtherUsersDisplayed < otherUsers.length}
Showing {nbOtherUsersDisplayed} of {otherUsers.length} users diff --git a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte index 33b8ee0e16..813cb3a265 100644 --- a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte +++ b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte @@ -57,7 +57,7 @@
diff --git a/frontend/src/lib/components/home/clampRows.ts b/frontend/src/lib/components/home/clampRows.ts new file mode 100644 index 0000000000..b62b45dcf5 --- /dev/null +++ b/frontend/src/lib/components/home/clampRows.ts @@ -0,0 +1,65 @@ +import type { Action } from 'svelte/action' + +export type ClampRowsOptions = { rows: number; expanded: boolean } + +/** + * Keeps a wrapping row of `[data-chip]` items to `rows` lines, measured rather than counted, so + * how many fit follows the width. The `[data-clamp-toggle]` child shows only on overflow, and + * while collapsed it takes the end of the last line: items are hidden from there back until it + * fits. A `[data-selected]` item is never hidden, since clicking it is how its filter clears. + */ +export const clampRows: Action = (node, initial) => { + let options = initial + let frame = 0 + let width = -1 + + function run() { + frame = 0 + const toggle = node.querySelector('[data-clamp-toggle]') + const items = Array.from(node.querySelectorAll('[data-chip]')) + for (const item of items) item.hidden = false + if (toggle) toggle.hidden = true + + // Every position is read before any item is hidden: reading one after a write forces a + // layout per item, quadratic in the number of chips. + const tops = items.map((item) => item.offsetTop) + const lines = [...new Set(tops)].sort((a, b) => a - b) + if (lines.length <= options.rows || !toggle) return + toggle.hidden = false + if (options.expanded) return + + const lastLine = lines[options.rows - 1] + items.forEach((item, i) => { + if (tops[i] > lastLine && !item.hasAttribute('data-selected')) item.hidden = true + }) + const hideable = items.filter((item) => !item.hidden && !item.hasAttribute('data-selected')) + while (toggle.offsetTop > lastLine && hideable.length) hideable.pop()!.hidden = true + } + + function schedule() { + if (!frame) frame = requestAnimationFrame(run) + } + + // Width only: hiding items changes the height, which must not measure again. + const resize = new ResizeObserver(([entry]) => { + if (entry.contentRect.width === width) return + width = entry.contentRect.width + schedule() + }) + resize.observe(node) + // The items themselves changing; the `hidden` flips above are attributes, not seen here. + const mutations = new MutationObserver(schedule) + mutations.observe(node, { childList: true, subtree: true, characterData: true }) + + return { + update(next) { + options = next + schedule() + }, + destroy() { + cancelAnimationFrame(frame) + resize.disconnect() + mutations.disconnect() + } + } +} diff --git a/frontend/src/lib/components/home/homeQuickAccessSettings.svelte.ts b/frontend/src/lib/components/home/homeQuickAccessSettings.svelte.ts new file mode 100644 index 0000000000..af88da656a --- /dev/null +++ b/frontend/src/lib/components/home/homeQuickAccessSettings.svelte.ts @@ -0,0 +1,56 @@ +import { BROWSER } from 'esm-env' +import { getLocalSetting, storeLocalSetting } from '$lib/utils' + +// Per browser, like the composer's own pin: how a reader likes their Home laid out. +const HIDDEN_SETTING = 'home-quick-access-hidden' +const ROWS_SETTING = 'home-quick-access-rows' +const NO_FAVORITES_SETTING = 'home-quick-access-no-favorites' +const NO_RECENT_SETTING = 'home-quick-access-no-recent' + +export const QUICK_ACCESS_ROWS = [1, 2, 3, 4] as const +export type QuickAccessRows = (typeof QUICK_ACCESS_ROWS)[number] +const DEFAULT_ROWS: QuickAccessRows = 2 + +// Blocked storage (some private windows) throws on write; the setting then lasts the visit. +function save(name: string, value: string | undefined) { + try { + storeLocalSetting(name, value) + } catch {} +} + +function readRows(): QuickAccessRows { + const raw = getLocalSetting(ROWS_SETTING) + return QUICK_ACCESS_ROWS.find((r) => String(r) === raw) ?? DEFAULT_ROWS +} + +class HomeQuickAccessSettings { + hidden = $state(BROWSER && getLocalSetting(HIDDEN_SETTING) === 'true') + rows = $state(BROWSER ? readRows() : DEFAULT_ROWS) + showFavorites = $state(!(BROWSER && getLocalSetting(NO_FAVORITES_SETTING) === 'true')) + showRecent = $state(!(BROWSER && getLocalSetting(NO_RECENT_SETTING) === 'true')) + /** Bumped on each hide, so the header menu that holds the way back can flash. */ + hideCount = $state(0) + + setHidden(next: boolean) { + this.hidden = next + if (next) this.hideCount++ + save(HIDDEN_SETTING, next ? 'true' : undefined) + } + + setShowFavorites(next: boolean) { + this.showFavorites = next + save(NO_FAVORITES_SETTING, next ? undefined : 'true') + } + + setShowRecent(next: boolean) { + this.showRecent = next + save(NO_RECENT_SETTING, next ? undefined : 'true') + } + + setRows(next: QuickAccessRows) { + this.rows = next + save(ROWS_SETTING, next === DEFAULT_ROWS ? undefined : String(next)) + } +} + +export const homeQuickAccessSettings = new HomeQuickAccessSettings() diff --git a/frontend/src/lib/components/home/recentItems.svelte.ts b/frontend/src/lib/components/home/recentItems.svelte.ts new file mode 100644 index 0000000000..edc80e8aba --- /dev/null +++ b/frontend/src/lib/components/home/recentItems.svelte.ts @@ -0,0 +1,99 @@ +import { onUserChange, scopedKey } from '$lib/userScopedStorage' + +export type RecentKind = 'script' | 'flow' | 'app' | 'raw_app' | 'agent' + +export type RecentItem = { + kind: RecentKind + path: string + summary?: string + /** Epoch ms of the last time the item was opened in its editor. */ + at: number +} + +const MAX_ITEMS = 30 +export const MAX_AGE_DAYS = 7 +const MAX_AGE_MS = MAX_AGE_DAYS * 24 * 60 * 60 * 1000 + +function fresh(items: RecentItem[]): RecentItem[] { + const cutoff = Date.now() - MAX_AGE_MS + return items.filter((x) => typeof x.at === 'number' && x.at >= cutoff) +} + +// Per user (scopedKey) and per workspace: what one person opened in one workspace says nothing +// about another, and a shared browser must not show the previous user's items. +function storageKey(workspace: string): string | undefined { + return scopedKey(`homeRecentItems:${workspace}`) +} + +function read(workspace: string): RecentItem[] { + const key = storageKey(workspace) + if (!key) return [] + try { + const parsed = JSON.parse(localStorage.getItem(key) ?? '[]') + return Array.isArray(parsed) + ? parsed.filter((x) => x && typeof x.path === 'string' && typeof x.kind === 'string') + : [] + } catch { + return [] + } +} + +function write(workspace: string, items: RecentItem[]): void { + const key = storageKey(workspace) + if (!key) return + try { + localStorage.setItem(key, JSON.stringify(items)) + } catch {} +} + +class RecentItems { + // Bumped on every write and on the user resolving, so readers re-read storage. + #version = $state(0) + // A page opened by a cold load can finish loading before the user's email resolves, and the + // storage key needs it; those visits wait here instead of being dropped. + #pending: { workspace: string; item: Omit }[] = [] + + constructor() { + onUserChange((email) => { + if (email) { + const pending = this.#pending + this.#pending = [] + for (const p of pending) this.record(p.workspace, p.item) + } + this.#version++ + }) + } + + list(workspace: string): RecentItem[] { + this.#version + return fresh(read(workspace)) + } + + /** Records an item as just opened. A missing summary keeps the one already stored. */ + record(workspace: string, item: Omit): void { + if (!workspace || !item.path) return + if (!storageKey(workspace)) { + this.#pending.push({ workspace, item }) + return + } + const previous = fresh(read(workspace)) + const existing = previous.find((x) => x.kind === item.kind && x.path === item.path) + const next: RecentItem = { + ...item, + summary: item.summary || existing?.summary, + at: Date.now() + } + write(workspace, [next, ...previous.filter((x) => x !== existing)].slice(0, MAX_ITEMS)) + this.#version++ + } + + forget(workspace: string, kind: RecentKind, path: string): void { + write( + workspace, + read(workspace).filter((x) => !(x.kind === kind && x.path === path)) + ) + this.#version++ + } +} + +export const recentItems = new RecentItems() diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte new file mode 100644 index 0000000000..b43af354b3 --- /dev/null +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -0,0 +1,113 @@ + + +{#snippet actingOn()} + {#if session} + + {/if} +{/snippet} + + +{#if session && $copilotWorkspace !== undefined && starterPrompts.fewItems !== undefined} + +{/if} diff --git a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte index 1a992b818b..9aef699490 100644 --- a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte +++ b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte @@ -28,8 +28,9 @@ } -
- Acting on + +
+ s.id === sessionId)) + // Only a session that has never sent opens as the starter block. Read off the record, not + // the transcript: a cold session's history is still loading from storage when it mounts, + // and an empty transcript would show the greeting and then glide the composer away. + // The first send commits the workspace, so this flips only after the transcript has. + const opensSession = $derived(!session?.workspace_id) + const starterPrompts = new StarterPrompts(() => + opensSession ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined + ) + // Seed the composer with the unsent prompt a reload preserved on the session // record (script-init: AIChatInput reads it once at mount). const restoredDraftPrompt = getSessionDraftPrompt(sessionId) @@ -116,6 +133,11 @@ // The placeholder's text counts as unsent input, like the real composer's draft, so the page // does not evict this session's chat (and the text with it) while it waits for the chat code. const PLACEHOLDER_DRAFT_KEY = 'composer-placeholder' + function setPlaceholderText(text: string) { + draftText = text + setSessionDraftPrompt(sessionId, text) + runtime?.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, text.trim() !== '') + } // Drawn once, and shared by the placeholder and the real composer so the text survives the swap. const suggestionPick = Math.random() @@ -372,6 +394,10 @@ {#if !session || !runtime}
Session not found
{:else} + + {#snippet sessionEmptyHint()}{/snippet} + {#snippet inputPreface()} {#if showRecoveryNotice} - {#snippet sessionEmptyHint()}{/snippet} + {#snippet actingOn()} + + {/snippet} + + + {#snippet placeholderToolbar()} +
+
+ {/snippet} {#snippet sessionHeader()} -
+
{#if showChat && aiChatComponent.current} setSessionDraftPrompt(sessionId, text)} + initialAttachments={armedAtInit ? undefined : getSessionDraftAttachments(sessionId)} + onAttachmentsChange={(a) => setSessionDraftAttachments(sessionId, a)} placeholder={composerPlaceholder} forceDisabled={isUnavailable || !!session.archived} forceDisabledMessage={isUnavailable @@ -544,41 +577,62 @@ : session.archived ? 'This session is archived. Unarchive it from the banner above to keep working.' : ''} + starter={opensSession + ? { where: 'session', suggestions: starterPrompts.suggestions } + : undefined} + viewTransitionNames={headerInPage && (opensSession || arrivingFromHomeSend())} emptyHint={sessionEmptyHint} {inputPreface} + actingOn={hasFirstUserMessage ? undefined : actingOn} /> {:else} + its transcript area, its column, and its footer row's height; for a session + that has never sent, the greeting above the centred composer. -->
() => runtime.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, false)} > - {#if runtime.manager.displayMessages.length > 0} + {#if opensSession} +
+
+ +
+
+ {:else if runtime.manager.displayMessages.length > 0}
{/if}
{@render inputPreface()} draftText, - (text) => { - draftText = text - setSessionDraftPrompt(sessionId, text) - runtime.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, text.trim() !== '') - } - } - placeholder={runtime.manager.displayMessages.length > 0 - ? 'Ask followup' - : composerPlaceholder} + bind:value={() => draftText, setPlaceholderText} + toolbar={opensSession ? placeholderToolbar : undefined} + placeholder={opensSession + ? STARTER_PLACEHOLDER + : runtime.manager.displayMessages.length > 0 + ? 'Ask followup' + : composerPlaceholder} disabled={isUnavailable || !!session.archived} autofocus={sessionState.currentSessionId === sessionId && !covered} onSelectionChange={(selection) => (handoff = selection ?? null)} onCompositionChange={(composing) => (placeholderComposing = composing)} /> -
+ {#if !opensSession} +
+ {:else if !isUnavailable && !session.archived && starterPrompts.suggestions.length > 0} +
+ +
+ {/if}
+ {#if opensSession} +
+ {/if}
{/if}
diff --git a/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts new file mode 100644 index 0000000000..3a923c0cbc --- /dev/null +++ b/frontend/src/lib/components/sessions/homeComposerContext.svelte.ts @@ -0,0 +1,50 @@ +import type { ContextElement } from '$lib/components/copilot/chat/context' +import type { BulkKind } from '$lib/components/home/homeSelection.svelte' + +/** Resolves once the element is in the draft, so several attach in the order given. */ +type Attach = (element: ContextElement) => Promise + +/** What the composer can take as context from a workspace item: a script, a flow or a code + * app, as "+" → Mention file builds it. A visual-builder app or an agent has no context + * element, so it gets none. */ +export function itemContextElement(item: { + kind: BulkKind + path: string + summary?: string + rawApp?: boolean +}): ContextElement | undefined { + const type = + item.kind === 'script' + ? 'workspace_script' + : item.kind === 'flow' + ? 'workspace_flow' + : item.kind === 'app' && item.rawApp + ? 'workspace_app' + : undefined + if (!type) return undefined + return { type, path: item.path, title: item.path, summary: item.summary, deletable: true } +} + +let attach = $state(undefined) + +/** + * The way from anywhere on Home into Home's composer: a row's "Ask AI" hands its item over + * here, and the composer takes it as context. Only a mounted composer registers, so a page + * whose composer is removed, hidden or not Home offers no button that would go nowhere. + */ +export const homeComposerContext = { + get available(): boolean { + return attach !== undefined + }, + async attach(element: ContextElement): Promise { + await attach?.(element) + }, + /** Returns the unregister, which only clears its own registration: a remount registers + * the new composer before the old one is destroyed. */ + register(fn: Attach): () => void { + attach = fn + return () => { + if (attach === fn) attach = undefined + } + } +} diff --git a/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts b/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts new file mode 100644 index 0000000000..74a72ec0ce --- /dev/null +++ b/frontend/src/lib/components/sessions/homeSessionsTransition.svelte.ts @@ -0,0 +1,96 @@ +import type { OnNavigate } from '@sveltejs/kit' +import { sessionState } from './sessionState.svelte' + +// Moving between Home and AI Sessions keeps the composer in sight: the browser +// snapshots the page before and after the navigation and glides the element that +// carries the `composer` view-transition-name on both sides (AIChatDisplay names it); +// the rest of the page cross-fades. The timing lives in app.css, keyed on the +// `data-home-sessions-transition` attribute set here for the length of the move. + +const HOME = '/' +const SESSIONS = '/sessions' + +/** Whether the composer had focus when the user left AI Sessions for Home. */ +let composerFocused = false + +/** The focus flag to keep after a navigation from `from` to `to`. Only the return to Home + * hands focus on — the sessions page focuses its composer on its own — and every other + * navigation clears the flag, so a later arrival on Home never acts on a stale one. */ +export function composerFocusAfter( + from: string | undefined, + to: string | undefined, + composerHadFocus: boolean +): boolean { + return from === SESSIONS && to === HOME && composerHadFocus +} + +/** Whether Home should give its composer the focus the sessions page's had. Read once: + * a later visit starts unfocused. */ +export function takeComposerFocus(): boolean { + const focused = composerFocused + composerFocused = false + return focused +} + +// A session that has sent its first message has a composer of its own, not Home's draft, so +// a move between it and Home is not one composer moving: its page names no composer. The one +// exception is the send from Home itself, which lands on that session already under way. +let sentFromHome = $state(false) + +/** Called by Home's composer as its send hands over to the session page. */ +export function composerSentFromHome(): void { + sentFromHome = true +} + +/** Whether the session page arriving now came from a send on Home, so its composer is the + * one Home just sent from. */ +export function arrivingFromHomeSend(): boolean { + return sentFromHome +} + +/** For SvelteKit's `onNavigate`: runs a move between Home and AI Sessions as a view + * transition. Any other navigation, or a browser without the API, is left alone. */ +export function homeSessionsTransition(navigation: OnNavigate): Promise | undefined { + const from = navigation.from?.url.pathname + const to = navigation.to?.url.pathname + composerFocused = composerFocusAfter( + from, + to, + document.activeElement?.closest('[data-session-composer]') != null + ) + const direction = + from === HOME && to === SESSIONS + ? 'enter' + : from === SESSIONS && to === HOME + ? 'leave' + : undefined + // Good for the navigation the send started, and only that one. + if (direction !== 'enter') sentFromHome = false + if (!direction || navigation.willUnload || !document.startViewTransition) return + if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return + const root = document.documentElement + // To or from a session under way there is no composer to carry over: Home's would only + // fade out or in on its own, so the move drops every name and the page cross-fades as + // one. Leaving, the page says so; arriving, the session's record does (it has sent once + // it has a workspace), short of the send from Home that just started it. + const composerOnScreen = Array.from(document.querySelectorAll('[data-session-composer]')).some( + (el) => getComputedStyle(el).viewTransitionName === 'composer' + ) + const arrivingId = navigation.to?.url.searchParams.get('session') ?? sessionState.currentSessionId + const arrivingUnderWay = + !sentFromHome && !!sessionState.sessions.find((s) => s.id === arrivingId)?.workspace_id + const plain = direction === 'leave' ? !composerOnScreen : arrivingUnderWay + root.dataset.homeSessionsTransition = plain ? 'fade' : direction + return new Promise((resolve) => { + const transition = document.startViewTransition(async () => { + resolve() + await navigation.complete + }) + // Rejects when the navigation is cancelled or fails; the attribute goes either way. + const done = () => { + delete root.dataset.homeSessionsTransition + sentFromHome = false + } + void transition.finished.then(done, done) + }) +} diff --git a/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts b/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts new file mode 100644 index 0000000000..4be3f18fce --- /dev/null +++ b/frontend/src/lib/components/sessions/homeSessionsTransition.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { composerFocusAfter } from './homeSessionsTransition.svelte' + +describe('composerFocusAfter', () => { + it('hands focus on only for the return from AI Sessions to Home', () => { + expect(composerFocusAfter('/sessions', '/', true)).toBe(true) + expect(composerFocusAfter('/sessions', '/', false)).toBe(false) + // Going to AI Sessions: that page focuses its own composer, so nothing is kept for Home. + expect(composerFocusAfter('/', '/sessions', true)).toBe(false) + // Any other navigation clears it, so a later arrival on Home never reads a stale flag. + expect(composerFocusAfter('/sessions', '/runs', true)).toBe(false) + expect(composerFocusAfter('/runs', '/', true)).toBe(false) + }) +}) diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index ff05c01a7a..a79d98d713 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -58,6 +58,7 @@ import { setSessionPreviewCollapsed, setSessionPreviewSize, setSessionTabs, + setDraftsDiscardedHandler, type Session } from './sessionState.svelte' import { @@ -306,6 +307,7 @@ export interface SessionRuntime { } const runtimes = new SvelteMap() +const runtimeRoots = new Map void>() function emptyFlow(): Flow { return { @@ -1330,7 +1332,18 @@ async function initRuntime(runtime: SessionRuntime, session: Session) { export function getOrCreateRuntime(session: Session): SessionRuntime { let runtime = runtimes.get(session.id) if (!runtime) { - runtime = createRuntime(session) + // The manager's `$derived` fields belong to whatever effect is running when they are + // built. A runtime outlives the component that first asked for it (Home hands its + // session to /sessions and unmounts), so give it a root of its own; built inside the + // component, its deriveds turn inert once that component is gone. + let created: SessionRuntime | undefined + runtimeRoots.set( + session.id, + $effect.root(() => { + created = createRuntime(session) + }) + ) + runtime = created! runtimes.set(session.id, runtime) // The gate opens even when the restore fails: a session that cannot read its // history is still usable, and a send that waits forever is not. @@ -1347,6 +1360,8 @@ export function disposeRuntime(sessionId: string) { runtime.manager.cancel('runtime disposed') runtime.manager.historyManager.close() runtimes.delete(sessionId) + runtimeRoots.get(sessionId)?.() + runtimeRoots.delete(sessionId) // The sidebar reads the stored chat again rather than trust a read that // predates everything this runtime saw. peeks.delete(sessionId) @@ -1475,6 +1490,8 @@ export function removeSession(sessionId: string): void { deleteSessionState(sessionId) } +setDraftsDiscardedHandler((ids) => ids.forEach(disposeRuntime)) + // The chat calls a new item by its chosen name while its draft is stored at // `draft_`; resolve the name the way the chat's write tools do. function draftStoragePath( diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index f032385d31..4a3abebb4f 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -28,6 +28,7 @@ import { emailOfScopedKey, scopedKeyFor } from '$lib/userScopedStorage' import { deleteItemsForSession } from '../copilot/chat/files/attachedFilesDB' import { deleteArtifactsForSession } from '../copilot/chat/artifacts/artifactsDB' import { deleteSessionChats } from '../copilot/chat/HistoryManager.svelte' +import type { DraftAttachments } from '../copilot/chat/messageDraft.svelte' import { markSessionDirty, markSessionRemoved, @@ -387,6 +388,32 @@ export function getSessionDraftPrompt(sessionId: string): string | undefined { return s.draftPrompt } +// The rest of an unsent draft (collapsed pastes, images, files), so a composer mounted again +// for the same session, on Home or the session page, gets the draft whole: a collapsed paste +// is a token in `draftPrompt` whose content lives here. In memory only, like the attachments +// themselves before a send, so a reload drops them as it always has. +const draftAttachments = new Map() + +export function setSessionDraftAttachments(sessionId: string, attachments: DraftAttachments): void { + const empty = Object.values(attachments).every((lane) => lane.length === 0) + if (empty) { + draftAttachments.delete(sessionId) + return + } + const s = sessionState.sessions.find((x) => x.id === sessionId) + if (!s || s.workspace_id) return + draftAttachments.set(sessionId, attachments) + // Attaching is a touch, as typing is: a draft holding only an image would otherwise still + // read as a blank, be reused by the next hand-off with the image in it, or be dropped. + if (s.transient) persistTouched(s) +} + +export function getSessionDraftAttachments(sessionId: string): DraftAttachments | undefined { + const s = sessionState.sessions.find((x) => x.id === sessionId) + if (!s || s.workspace_id) return undefined + return draftAttachments.get(sessionId) +} + // A hand-off arrives within a navigation; anything older than this is the debris // of one that never landed, and must not fire at whatever the user does next. const AUTO_SEND_TTL_MS = 5 * 60_000 @@ -1070,7 +1097,24 @@ export function createSession(): Session { requestComposerFocus() return reusable } + const session = newTransientSession() + sessionState.currentSessionId = session.id + return session +} + +// Told which never-touched drafts were dropped, so their runtimes go with them. Set by +// sessionRuntime, which imports this module and so cannot be imported back. Home builds a +// runtime for its draft on every mount, so a dropped draft would otherwise leave its +// manager and its history database handle open. +let onDraftsDiscarded: ((ids: string[]) => void) | undefined +export function setDraftsDiscardedHandler(handler: (ids: string[]) => void): void { + onDraftsDiscarded = handler +} + +function newTransientSession(): Session { + const discarded = sessionState.sessions.filter(isDiscardableDraft).map((s) => s.id) sessionState.sessions = sessionState.sessions.filter((s) => !isDiscardableDraft(s)) + if (discarded.length > 0) onDraftsDiscarded?.(discarded) // Start in the workspace you're in. The one exception: a root you can't // deploy to (locked, no bypass) steers to its dev, since a session there // couldn't edit anything. The picker lets you switch. @@ -1103,12 +1147,32 @@ export function createSession(): Session { transient: true } sessionState.sessions = [session, ...sessionState.sessions] - sessionState.currentSessionId = session.id // Transient until first touch: no DB record yet. Persisting is deferred to the // first user edit (the mutation helpers below route through persistTouched). return session } +/** The unsent session Home's composer writes into, so a prompt half-typed on Home is the + * one the empty session page shows, and the reverse. Never selects it: merely opening Home + * must not change which session the AI Sessions switch resumes. A session opened on an + * item (it carries preview tabs) is about that item, so Home starts its own instead. */ +export function homeStarterSession(): Session { + const unsent = (s: Session) => + !s.archived && !s.workspace_id && !s.previewTabs?.length && sessionInCurrentFamily(s) + const current = sessionState.sessions.find((s) => s.id === sessionState.currentSessionId) + if (current && unsent(current)) return current + // Stored but never sent: a draft the user touched, by typing or by picking where it acts. + // Either is theirs to come back to, and leaving it would strand it in the sidebar. + const touched = sessionState.sessions + .filter((s) => unsent(s) && !s.transient) + .sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))[0] + return ( + touched ?? + sessionState.sessions.find((s) => isDiscardableDraft(s) && sessionInCurrentFamily(s)) ?? + newTransientSession() + ) +} + // Promote an in-memory transient session to a persisted IndexedDB record. // No-op when the session isn't transient (already persisted by a prior touch). // Called on the first genuine user touch (via persistTouched) and, idempotently, @@ -1457,6 +1521,7 @@ export function deleteSession(id: string) { // a draft deleted inside the debounce window. clearTimeout(draftPromptFlushHandles.get(id)) draftPromptFlushHandles.delete(id) + draftAttachments.delete(id) sessionState.sessions = sessionState.sessions.filter((x) => x.id !== id) if (sessionState.currentSessionId === id) { sessionState.currentSessionId = sessionState.sessions[0]?.id diff --git a/frontend/src/lib/components/sessions/sessionState.test.ts b/frontend/src/lib/components/sessions/sessionState.test.ts index 710028413e..4c6666a349 100644 --- a/frontend/src/lib/components/sessions/sessionState.test.ts +++ b/frontend/src/lib/components/sessions/sessionState.test.ts @@ -5,11 +5,15 @@ import { createSession, decideSessionLifecycle, findEmptyLandingSession, + getSessionDraftAttachments, + homeStarterSession, isForkSession, isTearingDownOpenSession, renameSession, + setDraftsDiscardedHandler, sessionInCurrentFamily, setGeneratedSessionSummary, + setSessionDraftAttachments, setSessionDraftPrompt, sessionState, withOpenSessionTeardown, @@ -27,6 +31,10 @@ import { type UserWorkspace } from '$lib/stores' import { WorkspaceService } from '$lib/gen' +import type { DraftAttachments } from '$lib/components/copilot/chat/messageDraft.svelte' +import type { PasteAttachment } from '$lib/components/copilot/chat/pasteTokens' + +const NO_ATTACHMENTS: DraftAttachments = { pastes: [], images: [], files: [], blobs: [] } // Force createWorkspaceFork to fail so we can pin commitSessionWorkspace's // failure contract (the invariant the beforeSend abort fix relies on). @@ -451,6 +459,35 @@ describe('createSession — reuses an untouched draft, family-scoped', () => { } }) + it('does not reuse a draft that holds only an attachment', () => { + const restore = withTwoFamilies('rootA') + const prevCurrent = sessionState.currentSessionId + const attached = session({ + id: 'attachment-only', + name: 'session-904', + pending_workspace_id: 'forkA', + transient: true + }) + sessionState.sessions.push(attached) + let createdId: string | undefined + try { + setSessionDraftAttachments('attachment-only', { + ...NO_ATTACHMENTS, + pastes: [{} as PasteAttachment] + }) + createdId = createSession().id + expect(createdId).not.toBe('attachment-only') + expect(getSessionDraftAttachments('attachment-only')).toBeDefined() + } finally { + setSessionDraftAttachments('attachment-only', NO_ATTACHMENTS) + sessionState.sessions = sessionState.sessions.filter( + (s) => s.id !== 'attachment-only' && s.id !== createdId + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + it('clears the recovery notice off the draft it reuses, so `+` is not answered with "not found"', () => { const restore = withTwoFamilies('rootA') const prevCurrent = sessionState.currentSessionId @@ -674,3 +711,64 @@ describe('withOpenSessionTeardown — the gate that holds recovery off during a expect(isTearingDownOpenSession()).toBe(false) }) }) + +describe('homeStarterSession', () => { + it("shows the family's stored draft, not the conversation in view, and selects nothing", () => { + const restore = withTwoFamilies('rootA') + const prevCurrent = sessionState.currentSessionId + const conversation = session({ id: 'conversation', workspace_id: 'rootA' }) + // Touched only by picking where it acts: no text, but stored, so it is the user's draft. + const picked = session({ id: 'picked-draft', pending_workspace_id: 'forkA', lastActivityAt: 2 }) + const otherFamily = session({ + id: 'other-family-draft', + pending_workspace_id: 'rootB', + draftPrompt: 'elsewhere', + lastActivityAt: 3 + }) + sessionState.sessions.push(conversation, picked, otherFamily) + sessionState.currentSessionId = 'conversation' + try { + expect(homeStarterSession().id).toBe('picked-draft') + // Opening Home must leave the AI Sessions switch resuming the conversation. + expect(sessionState.currentSessionId).toBe('conversation') + } finally { + sessionState.sessions = sessionState.sessions.filter( + (s) => !['conversation', 'picked-draft', 'other-family-draft'].includes(s.id) + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + + it('reports the never-touched drafts it drops, so their runtimes can be disposed', () => { + const restore = withTwoFamilies('rootB') + const prevCurrent = sessionState.currentSessionId + const blank = session({ + id: 'blank-other-family', + pending_workspace_id: 'forkA', + transient: true + }) + const typed = session({ + id: 'typed-other-family', + pending_workspace_id: 'rootA', + draftPrompt: 'kept' + }) + sessionState.sessions.push(blank, typed) + const discarded: string[][] = [] + setDraftsDiscardedHandler((ids) => discarded.push(ids)) + let createdId: string | undefined + try { + // No draft of family B exists, so Home starts one, dropping family A's blank draft. + createdId = homeStarterSession().id + expect(discarded).toEqual([['blank-other-family']]) + expect(sessionState.sessions.some((s) => s.id === 'typed-other-family')).toBe(true) + } finally { + setDraftsDiscardedHandler(() => {}) + sessionState.sessions = sessionState.sessions.filter( + (s) => !['blank-other-family', 'typed-other-family', createdId].includes(s.id) + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) +}) diff --git a/frontend/src/lib/components/sidebar/FavoriteMenu.svelte b/frontend/src/lib/components/sidebar/FavoriteMenu.svelte index c3d14d4c4d..448d7644bc 100644 --- a/frontend/src/lib/components/sidebar/FavoriteMenu.svelte +++ b/frontend/src/lib/components/sidebar/FavoriteMenu.svelte @@ -30,6 +30,9 @@ href: string kind: FavoriteKind }[] = $state([]) + /** The workspace `current` was last loaded for, so a reader can tell "none yet" from + * "none". */ + loadedFor: string | undefined = $state(undefined) async unstar(path: string, favorite_kind: FavoriteKind, workspaceId?: string) { this.current = this.current.filter( diff --git a/frontend/src/lib/consts.ts b/frontend/src/lib/consts.ts index a6bbc25d49..62108cf23b 100644 --- a/frontend/src/lib/consts.ts +++ b/frontend/src/lib/consts.ts @@ -10,6 +10,9 @@ export const DEFAULT_WEBHOOK_TYPE: 'async' | 'sync' = 'async' export const HOME_SHOW_HUB = true +/** The width of Home's one column: the composer and the items list below it. */ +export const HOME_COLUMN_WIDTH = 'max-w-[1120px]' + export const HOME_SHOW_CREATE_FLOW = true export const HOME_SEARCH_SHOW_FLOW = true diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 13ae454c92..7341baef49 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -1657,7 +1657,8 @@ export type Item = { href?: string hrefTarget?: '_blank' | '_self' | '_parent' | '_top' disabled?: boolean - type?: 'action' | 'delete' + /** `ai` sets the row in the AI colour, for an action that hands something to the assistant. */ + type?: 'action' | 'delete' | 'ai' hide?: boolean | undefined extra?: Snippet id?: string diff --git a/frontend/src/routes/(root)/(logged)/+layout.svelte b/frontend/src/routes/(root)/(logged)/+layout.svelte index fd4b828be3..6b79582958 100644 --- a/frontend/src/routes/(root)/(logged)/+layout.svelte +++ b/frontend/src/routes/(root)/(logged)/+layout.svelte @@ -58,7 +58,8 @@ type UserWorkspace } from '$lib/stores' import CenteredModal from '$lib/components/CenteredModal.svelte' - import { afterNavigate, beforeNavigate } from '$app/navigation' + import { afterNavigate, beforeNavigate, onNavigate } from '$app/navigation' + import { homeSessionsTransition } from '$lib/components/sessions/homeSessionsTransition.svelte' import { goto } from '$lib/navigation' import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte' import type UserSettings from '$lib/components/UserSettings.svelte' @@ -449,6 +450,8 @@ return kind ? { kind, path: route.itemPath } : undefined } + onNavigate(homeSessionsTransition) + beforeNavigate((navigation) => { if (preserveMenuOnNextNav) { preserveMenuOnNextNav = false @@ -661,27 +664,37 @@ } async function loadFavorites() { - const scripts = await ScriptService.listScripts({ - workspace: $workspaceStore ?? '', - starredOnly: true, - includeWithoutMain: true, - withoutDescription: true - }) - const flows = await FlowService.listFlows({ - workspace: $workspaceStore ?? '', - starredOnly: true, - withoutDescription: true - }) - const apps = await AppService.listApps({ - workspace: $workspaceStore ?? '', - starredOnly: true - }) - const agents = await ResourceService.listResource({ - workspace: $workspaceStore ?? '', - resourceType: 'ai_agent', - starredOnly: true - }) - const assets = await AssetService.listFavoriteAssets({ workspace: $workspaceStore ?? '' }) + const workspace = $workspaceStore ?? '' + try { + await loadFavoritesFor(workspace) + } catch (e) { + // `current` still holds another workspace's favorites, which `loadedFor` is about to + // vouch for as this one's. + if (favoriteManager.loadedFor !== workspace && ($workspaceStore ?? '') === workspace) + favoriteManager.current = [] + throw e + } finally { + // Set on failure too: Home holds its shortcuts back until this says the favorites + // are in, and a failed read must not hold them back for good. Not once the workspace + // has changed: a slow load for the last one would name it and hide them in this one. + if (($workspaceStore ?? '') === workspace) favoriteManager.loadedFor = workspace + } + } + + async function loadFavoritesFor(workspace: string) { + const [scripts, flows, apps, agents, assets] = await Promise.all([ + ScriptService.listScripts({ + workspace, + starredOnly: true, + includeWithoutMain: true, + withoutDescription: true + }), + FlowService.listFlows({ workspace, starredOnly: true, withoutDescription: true }), + AppService.listApps({ workspace, starredOnly: true }), + ResourceService.listResource({ workspace, resourceType: 'ai_agent', starredOnly: true }), + AssetService.listFavoriteAssets({ workspace }) + ]) + if (($workspaceStore ?? '') !== workspace) return favoriteManager.current = [ ...scripts.map((s) => ({ label: s.summary || getFavoriteLabel(s.path, 'script'), diff --git a/frontend/src/routes/(root)/(logged)/+page.svelte b/frontend/src/routes/(root)/(logged)/+page.svelte index 665c93b661..d23f92de96 100644 --- a/frontend/src/routes/(root)/(logged)/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/+page.svelte @@ -1,6 +1,7 @@
diff --git a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte index 57e387ad20..fdcf447f64 100644 --- a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte @@ -17,6 +17,7 @@ import { importStore } from '$lib/components/apps/store' import { onDestroy, untrack } from 'svelte' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { UserDraft } from '$lib/userDraft.svelte' import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import { OtherUserDraftLoad } from '$lib/components/otherUserDraftLoad.svelte' @@ -206,6 +207,14 @@ getDraft }) if (tok !== loadAppToken) return + // A draft-only app has no page for Home's card to open. + if (!backendApp.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'app', + path: backendApp.path, + summary: backendApp.summary + }) + } // Deployed App value for AppEditor's autosave `discardIf`, captured BEFORE // the draft swap below replaces `backendApp.value`. `undefined` when // there's no deployed row (draft-only path). diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte index 92df0e72a4..0a89e2141d 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte @@ -15,6 +15,7 @@ import { openEditorInSession } from '$lib/components/sessions/sessionSwitch.svelte' import { stateSnapshot } from '$lib/svelte5Utils.svelte' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { type RawAppData, DEFAULT_DATA, @@ -312,6 +313,14 @@ rawApp: true })) as any if (tok !== loadAppToken) return + // A draft-only app has no page for Home's card to open. + if (!backendApp.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'raw_app', + path: backendApp.path, + summary: backendApp.summary + }) + } // `other_drafts_users` only computed when `getDraft`; don't clobber the // known list on a `getDraft:false` reload. See /scripts/edit's loader. if (getDraft) { diff --git a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte index d724c4873d..9fd0e65a45 100644 --- a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte @@ -21,6 +21,7 @@ import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import type { stepState } from '$lib/components/stepHistoryLoader.svelte' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { UserDraft, draftValuesEqual } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import UnsavedConfirmationModal from '$lib/components/common/confirmationModal/UnsavedConfirmationModal.svelte' @@ -346,6 +347,14 @@ getDraft }) if (tok !== loadFlowToken) return + // A draft-only flow has no page for Home's card to open. + if (!backendFlow.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'flow', + path: backendFlow.path, + summary: backendFlow.summary + }) + } // `other_drafts_users` only computed when `getDraft`; don't clobber the // known list on a `getDraft:false` reload. See /scripts/edit's loader. if (getDraft) { diff --git a/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte index 6110af0fef..9a9f9fb14e 100644 --- a/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte @@ -18,6 +18,7 @@ import { onDestroy, untrack } from 'svelte' import { stripNewDraftFlag, stripNewDraftFlagOnSave, shouldSeedNewDraft } from '$lib/newDraftFlag' import { page } from '$app/state' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { UserDraft, draftValuesEqual } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { discardDraftAfterDeploy, runResetToDeployed } from '$lib/userDraftToast' @@ -311,6 +312,14 @@ getDraft }) if (tok !== loadScriptToken) return + // A draft-only script has no page for Home's card to open. + if (!backendScript.no_deployed) { + recentItems.record($workspaceStore!, { + kind: 'script', + path: backendScript.path, + summary: backendScript.summary + }) + } // The editor re-infers the schema as soon as it mounts, so a baseline // taken from the raw stored schema would flag every unedited open of a // script whose stored schema differs from what this parser emits. diff --git a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte index 7fc5630b79..b648bd4212 100644 --- a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte @@ -35,8 +35,7 @@ type Scope } from '$lib/components/sessions/PreviewRouterPicker.svelte' import { goto } from '$lib/navigation' - import { resource } from 'runed' - import { WorkspaceService } from '$lib/gen' + import { useWorkspaceAiHidden } from '$lib/components/copilot/workspaceAiHidden.svelte' import SessionWrapper from '$lib/components/sessions/SessionWrapper.svelte' import type PreviewTabHost from '$lib/components/sessions/PreviewTabHost.svelte' import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte' @@ -339,35 +338,16 @@ (activeSession ? getEffectiveWorkspaceId(activeSession) : undefined) ?? $workspaceStore ) - // Whether that workspace hid the AI assistant (`ai_config.copilot_disabled`). Read - // directly rather than from `copilotInfo`: that store holds whichever workspace loaded - // last, and the gate below unmounts the session wrapper that would refresh it, so a - // hidden verdict would stick across session and workspace switches. Tagged with its - // workspace and guarded against a superseded response like the protection-rules - // resource: runed keeps the previous `current` while a new source loads, so a switch - // would otherwise be judged on the previous workspace's verdict. A failed read leaves - // the page usable, as an unloaded config does everywhere else. - const workspaceAiHidden = resource( - () => previewWorkspace, - async (workspace, _prev, { signal }) => { - if (!workspace) return { workspace, hidden: false } - let hidden = false - try { - hidden = (await WorkspaceService.getCopilotInfo({ workspace })).copilot_disabled === true - } catch (e) { - console.error(`Failed to read the AI config of workspace ${workspace}:`, e) - } - // The generated client can't take an abort signal, so drop a superseded response here. - if (signal.aborted) throw new DOMException('superseded', 'AbortError') - return { workspace, hidden } - } + // Whether that workspace hid the AI assistant. The gate below unmounts the session wrapper + // that would refresh `copilotInfo`, so the verdict is read for the workspace itself. + const workspaceAiHidden = useWorkspaceAiHidden(() => previewWorkspace) + const aiHiddenVerdict = $derived(workspaceAiHidden.hidden) + // The full loader is for the page's first verdict only. Later, picking another workspace in + // "Acting on" leaves the session on screen, inert until its verdict lands: covering it for + // a request reads as the page reloading. + const firstVerdictPending = $derived( + aiHiddenVerdict === undefined && !workspaceAiHidden.settledOnce ) - // Only a verdict for the workspace currently judged counts; `undefined` means it has not - // landed yet. - const aiHiddenVerdict = $derived.by(() => { - const current = workspaceAiHidden.current - return current && current.workspace === previewWorkspace ? current.hidden : undefined - }) // Lazy-mount gate: a tab's content only renders once its key lands here (on // first activation) — so restoring a session with N saved tabs boots just @@ -1293,15 +1273,16 @@
- {#if aiHiddenVerdict === undefined} + {#if firstVerdictPending}
{:else if aiHiddenVerdict} +

AI Sessions are hidden in this workspace

A workspace admin hid AI sessions in the workspace settings.

From b435a8f5626ab208a928178f45632c3840ef472a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:07:53 +0200 Subject: [PATCH 027/101] chore(deps): bump certifi (#11919) Bumps the uv group with 1 update in the /python-client/wmill directory: [certifi](https://github.com/certifi/python-certifi). Updates `certifi` from 2026.2.25 to 2026.10.19 - [Commits](https://github.com/certifi/python-certifi/compare/2026.02.25...2026.10.19) --- updated-dependencies: - dependency-name: certifi dependency-version: 2026.10.19 dependency-type: indirect dependency-group: uv ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- python-client/wmill/uv.lock | 103 ++++++++++++++++++++++++++++++++++-- 1 file changed, 100 insertions(+), 3 deletions(-) diff --git a/python-client/wmill/uv.lock b/python-client/wmill/uv.lock index 1c366b42bd..c6ebad85d8 100644 --- a/python-client/wmill/uv.lock +++ b/python-client/wmill/uv.lock @@ -15,7 +15,9 @@ name = "anyio" version = "4.12.1" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/96/f0/5eb65b2bb0d09ac6776f2eb54adee6abe8228ea05b20a5ad0e4945de8aac/anyio-4.12.1.tar.gz", hash = "sha256:41cfcc3a4c85d3f05c932da7c26d0201ac36f72abd4435ba90d0464a3ffed703", size = 228685, upload-time = "2026-01-06T11:45:21.246Z" } wheels = [ @@ -24,11 +26,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.2.25" +version = "2026.10.19" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/af/2d/7bf41579a8986e348fa033a31cdd0e4121114f6bce2457e8876010b092dd/certifi-2026.2.25.tar.gz", hash = "sha256:e887ab5cee78ea814d3472169153c2d12cd43b14bd03329a39a9c6e2e80bfba7", size = 155029, upload-time = "2026-02-25T02:54:17.342Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/3c/c17fb3ca2d9c3acff52e30b309f538586f9f5b9c9cf454f3845fc9af4881/certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa", size = 153684, upload-time = "2026-02-25T02:54:15.766Z" }, + { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, ] [[package]] @@ -40,6 +42,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "exceptiongroup" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" }, +] + [[package]] name = "h11" version = "0.16.0" @@ -128,12 +142,95 @@ version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, { name = "pygments" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] + +[[package]] +name = "tomli" +version = "2.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b0/78/9ad63712633ed3ab5cc1a648d863d7e7da371e9425e209555a0fe711b695/tomli-2.5.0.tar.gz", hash = "sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6", size = 17662, upload-time = "2026-10-07T12:23:37.892Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/ab99b60ee52acd949684febabc3005d0045d0f66bebd9cdebd67372d26dd/tomli-2.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c4dc1c1781f2f716de763d1e9a7b34c6a894e167e291c7c5d16c72f7a9538545", size = 163901, upload-time = "2026-10-07T12:22:15.601Z" }, + { url = "https://files.pythonhosted.org/packages/bc/00/ee01b7ed4579180fff07142d290257f25ba786f23f3ec6005f620933c2f5/tomli-2.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:eff8babca5a7999bc137acbc7482a8b7e17ffca5075ab41f5d770ab408c7bfef", size = 163756, upload-time = "2026-10-07T12:22:16.957Z" }, + { url = "https://files.pythonhosted.org/packages/72/c2/4efebf65372f6583185f79799312109dddb61102d47e5c33dcfd1a297aca/tomli-2.5.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:86665cee9c4835b7a7f1e8ec2c719b5258d4dc782887aded5a8ae7352a96843b", size = 268038, upload-time = "2026-10-07T12:22:18.135Z" }, + { url = "https://files.pythonhosted.org/packages/53/07/5850468e925d898abb36038666f9c333a94d2a223e802a8ba5b6d319d23f/tomli-2.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7e369fd63331746182360977b1892bfc215476a30d61612d732425311639f56", size = 276422, upload-time = "2026-10-07T12:22:19.567Z" }, + { url = "https://files.pythonhosted.org/packages/b4/87/f293984cdcf83c054196d4fd3dad44fc68ae55b4b8c44bc76cef360c3150/tomli-2.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7ad1ea345759240d6463efa0ed1c704402752e49aa21476620738d74d72d8aa1", size = 272616, upload-time = "2026-10-07T12:22:20.794Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ce/db582886b3c1219d3fec93ebd669332482e5aee7a91e0f7838d84f2d1759/tomli-2.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96243987194634bd411066ce40c952e108f86af04db533ecd8ac3ff2a85b1885", size = 276593, upload-time = "2026-10-07T12:22:22.12Z" }, + { url = "https://files.pythonhosted.org/packages/bf/72/7619b87dea4261fc27dd7b54c4461c129c1f7d9bb7ba3aec89c797a431b8/tomli-2.5.0-cp311-cp311-win32.whl", hash = "sha256:610b27d99f28ec5f191c7064a48f3ddb179a1fe6ca73d571483ae859f57b605e", size = 101830, upload-time = "2026-10-07T12:22:23.651Z" }, + { url = "https://files.pythonhosted.org/packages/1e/74/220106da34502304b6751a2a9b8a9fbca6c3fd47e737a2e2e3da7c61c9db/tomli-2.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:c804ae44fe7b4bab5da295e4f980a1ff04670bca9d23fe0a4e887e08ebd741a8", size = 112742, upload-time = "2026-10-07T12:22:24.972Z" }, + { url = "https://files.pythonhosted.org/packages/27/99/7d9c8b41837a7773613e169504147375c157a290167aa59ad74a085f521f/tomli-2.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:cfac177ebd6236003846ea339981f71457cb6eb748f23381eb257e45092e3980", size = 109332, upload-time = "2026-10-07T12:22:26.117Z" }, + { url = "https://files.pythonhosted.org/packages/52/ed/7baa86f87493646a594de388c7c1c40a39dd0461f7e9c0359cbeefc91fe8/tomli-2.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df", size = 164854, upload-time = "2026-10-07T12:22:27.444Z" }, + { url = "https://files.pythonhosted.org/packages/a5/b1/44c0341f2224397855723c7a8a39f718ea6fcbcc3dacc66e5aeca0f334e3/tomli-2.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b", size = 164074, upload-time = "2026-10-07T12:22:28.679Z" }, + { url = "https://files.pythonhosted.org/packages/23/04/e2d5b7d3fba47adedb23de616c16d428ea076c79a3d8e1d95d649ffe197e/tomli-2.5.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0", size = 274274, upload-time = "2026-10-07T12:22:29.804Z" }, + { url = "https://files.pythonhosted.org/packages/43/90/6090e706ff27a6f89f4a40578e3324b95c3cd8c4150868aabf33a8f414c3/tomli-2.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6", size = 286435, upload-time = "2026-10-07T12:22:31.297Z" }, + { url = "https://files.pythonhosted.org/packages/0a/9e/a2c40768df16c408f22430afb0a73e9d7e5f79c950884954649d1146b74d/tomli-2.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc", size = 278119, upload-time = "2026-10-07T12:22:32.601Z" }, + { url = "https://files.pythonhosted.org/packages/12/25/3c0cb485b98e9cfac495629b1c93c87ccf0b72fbe9d2689fd8fe62c6d5a3/tomli-2.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7", size = 286177, upload-time = "2026-10-07T12:22:33.745Z" }, + { url = "https://files.pythonhosted.org/packages/77/8b/0144c65f0e37e51c18d04ae15c21b19431c165002d0131fe9aa8b0b8b1e8/tomli-2.5.0-cp312-cp312-win32.whl", hash = "sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2", size = 102760, upload-time = "2026-10-07T12:22:34.887Z" }, + { url = "https://files.pythonhosted.org/packages/de/32/5d6d8f42fc9a05fce69354e00ff256484192f5f2fc9a2165718fa0de61ec/tomli-2.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7", size = 112722, upload-time = "2026-10-07T12:22:36.162Z" }, + { url = "https://files.pythonhosted.org/packages/30/65/df18032218db0fb9b769fb23c8039a051f15c811993995ea04c350273a32/tomli-2.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea", size = 109534, upload-time = "2026-10-07T12:22:37.296Z" }, + { url = "https://files.pythonhosted.org/packages/42/e5/51736d70da209350969e15aca5c5ab6e2ce1ea87a0a892a6c13aec172a86/tomli-2.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea", size = 163328, upload-time = "2026-10-07T12:22:38.373Z" }, + { url = "https://files.pythonhosted.org/packages/ec/55/086f80dab4ab497602644274e6dea7ec5dd0b4e262e443a8ad3bb7edee2d/tomli-2.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043", size = 162246, upload-time = "2026-10-07T12:22:39.673Z" }, + { url = "https://files.pythonhosted.org/packages/aa/eb/3ecc94459f3635c92321f4e7bde571323fdb2267c50e19e3188a281eae3b/tomli-2.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0", size = 272655, upload-time = "2026-10-07T12:22:41.08Z" }, + { url = "https://files.pythonhosted.org/packages/c0/d7/494fd1f0c37a621f1ad9975c2efadb523e8101f144ed6edb2e7fe64738f2/tomli-2.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b", size = 283595, upload-time = "2026-10-07T12:22:42.222Z" }, + { url = "https://files.pythonhosted.org/packages/70/51/bb8d62b1317e6640866f6949b2d5855e5300f2c99d46de1cd245570bba65/tomli-2.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066", size = 276253, upload-time = "2026-10-07T12:22:43.625Z" }, + { url = "https://files.pythonhosted.org/packages/66/f4/f46bd7f0763cd47de2db697dca9257c6a4adfd1a93b018cc75c8190ed5a8/tomli-2.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b", size = 283582, upload-time = "2026-10-07T12:22:44.983Z" }, + { url = "https://files.pythonhosted.org/packages/ac/03/70f2bcb2923a6db37818d917e124270a7f4cfd38ea576f5aa753a91c0ef5/tomli-2.5.0-cp313-cp313-win32.whl", hash = "sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68", size = 102628, upload-time = "2026-10-07T12:22:46.508Z" }, + { url = "https://files.pythonhosted.org/packages/dc/98/d52024bb5b0ff68b4f0d276d867f634c84a67319a7e9f6b7708a37742333/tomli-2.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc", size = 113301, upload-time = "2026-10-07T12:22:47.647Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f2/540db3a70572a8c23a28aba3e9c358ce0ffffbafc990905c1343aa265b31/tomli-2.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84", size = 109744, upload-time = "2026-10-07T12:22:48.925Z" }, + { url = "https://files.pythonhosted.org/packages/e4/49/caf6b307766eb9567664a8707e9d6be5fcc0e8903f18781c6677a60d80c7/tomli-2.5.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105", size = 162899, upload-time = "2026-10-07T12:22:50.088Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c8/68cfce773a2733a49c74f99d627fb461bd990756860099eac25617889585/tomli-2.5.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646", size = 162080, upload-time = "2026-10-07T12:22:51.558Z" }, + { url = "https://files.pythonhosted.org/packages/7e/b2/e5bb8651fdad593f670501a7d718b1a7f73f064d44dea15e04c04dfef45d/tomli-2.5.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b", size = 273380, upload-time = "2026-10-07T12:22:52.918Z" }, + { url = "https://files.pythonhosted.org/packages/8d/d2/9e2d7f8b1dfe0e2b34c245986ebd55c4c553ea4ce6c47c443b332673253f/tomli-2.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75", size = 283228, upload-time = "2026-10-07T12:22:54.173Z" }, + { url = "https://files.pythonhosted.org/packages/ba/df/ec7b876b7b1a2718bd74a3743c076fff565b04029ba33e8f61fac262739f/tomli-2.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb", size = 277189, upload-time = "2026-10-07T12:22:55.342Z" }, + { url = "https://files.pythonhosted.org/packages/7d/7b/e192d9eed0b9cb80da799f4d77052297fb9a2c3cc9b19f571f56ea88add6/tomli-2.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3", size = 283632, upload-time = "2026-10-07T12:22:56.735Z" }, + { url = "https://files.pythonhosted.org/packages/84/50/ff94454e75461d75623e47401ed323d65c10aab8fe9033242c20cd2fdf32/tomli-2.5.0-cp314-cp314-win32.whl", hash = "sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b", size = 103535, upload-time = "2026-10-07T12:22:58.084Z" }, + { url = "https://files.pythonhosted.org/packages/54/0b/bdacf05f963bd6026ebf6eeb0beda847d1d60e03e440725c64a4e08a0afd/tomli-2.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a", size = 114621, upload-time = "2026-10-07T12:22:59.2Z" }, + { url = "https://files.pythonhosted.org/packages/61/99/53f438fa6ae4f9d4ed0ddde3e7242b3bdc34b48c8f9948b72b9e9b127676/tomli-2.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3", size = 111572, upload-time = "2026-10-07T12:23:00.479Z" }, + { url = "https://files.pythonhosted.org/packages/b9/20/1f88f19427d380a40e90a770e087489eaafe4aeee070ae88ed2bbec00acd/tomli-2.5.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4", size = 171814, upload-time = "2026-10-07T12:23:01.914Z" }, + { url = "https://files.pythonhosted.org/packages/d0/56/cbe5079c9f9a54b9b3e27fc82f08f3cb36edee75561679f53d2380c801d6/tomli-2.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d", size = 171324, upload-time = "2026-10-07T12:23:03.18Z" }, + { url = "https://files.pythonhosted.org/packages/2b/30/1d53fd3b0f1cb3ba542e345ec32c26aefdddc4e829e4f3429af8a4f27782/tomli-2.5.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9", size = 297441, upload-time = "2026-10-07T12:23:04.345Z" }, + { url = "https://files.pythonhosted.org/packages/66/d9/0800acb6a111686f764c1b91ef15cc42a20a66a46013bb42220f1d2c61c1/tomli-2.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f", size = 307476, upload-time = "2026-10-07T12:23:05.671Z" }, + { url = "https://files.pythonhosted.org/packages/e8/63/30a8f3cd51b5bec37f04744bad0b0dc6160df84aad4f27b0e9283d66f221/tomli-2.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374", size = 296113, upload-time = "2026-10-07T12:23:07.202Z" }, + { url = "https://files.pythonhosted.org/packages/ab/18/0b9ffc597e69c5a1e20a7823cb60d54b39a9f54e91edcb8574f022186758/tomli-2.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442", size = 307725, upload-time = "2026-10-07T12:23:08.508Z" }, + { url = "https://files.pythonhosted.org/packages/ab/c7/18f8baae0b5607a60e8e19b4a7fedee43a8ff6458e3896dcbbadeeac9c22/tomli-2.5.0-cp314-cp314t-win32.whl", hash = "sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03", size = 108546, upload-time = "2026-10-07T12:23:09.956Z" }, + { url = "https://files.pythonhosted.org/packages/72/34/4cca9739254130627bde87500b3f2b512154fe2f278efa7e2a5e10ad4bcb/tomli-2.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1", size = 117814, upload-time = "2026-10-07T12:23:11.486Z" }, + { url = "https://files.pythonhosted.org/packages/7d/fb/afa530d47dd80a78fce43beac6bc6e00f84558eafcffbc6f37b21e80d056/tomli-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0", size = 115188, upload-time = "2026-10-07T12:23:12.728Z" }, + { url = "https://files.pythonhosted.org/packages/66/98/316fdc00f8c0939e6fe50461dd343c162d3ad51d1286eb25b7db54361d50/tomli-2.5.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc", size = 162775, upload-time = "2026-10-07T12:23:13.941Z" }, + { url = "https://files.pythonhosted.org/packages/c5/22/7b10fa5bb01c9539f53f69b619361b19350acc73657772ea7ac70ba309a8/tomli-2.5.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276", size = 161406, upload-time = "2026-10-07T12:23:15.215Z" }, + { url = "https://files.pythonhosted.org/packages/9c/e7/1a069d86dfd20f1f84f71c63faed9f83c1d890bc06c27d82dc7d888fb573/tomli-2.5.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52", size = 273855, upload-time = "2026-10-07T12:23:16.471Z" }, + { url = "https://files.pythonhosted.org/packages/ae/83/d1ef43d1687d092ab9c235455c76e6e709483b346b056f086095c7c263a5/tomli-2.5.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7", size = 284910, upload-time = "2026-10-07T12:23:18.166Z" }, + { url = "https://files.pythonhosted.org/packages/cc/05/f4d9cf7de61822ece0c3873f30d291e324911c71a378b8bfe5ced13fd9f5/tomli-2.5.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391", size = 277723, upload-time = "2026-10-07T12:23:19.355Z" }, + { url = "https://files.pythonhosted.org/packages/42/28/78262493141fa543151cf005760c3cb01d09fc28a11f993c05109902cb8c/tomli-2.5.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859", size = 285115, upload-time = "2026-10-07T12:23:20.698Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b9/e1dab9a30bcb677b5cc5cee810609cfd64f24306a3055767dd3fda00b1e0/tomli-2.5.0-cp315-cp315-win32.whl", hash = "sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb", size = 103475, upload-time = "2026-10-07T12:23:21.941Z" }, + { url = "https://files.pythonhosted.org/packages/4c/bd/31a3790c11d6ea95fcf5e6022ac0f8d0543c9b61120b730fc481bd43d3b4/tomli-2.5.0-cp315-cp315-win_amd64.whl", hash = "sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5", size = 114589, upload-time = "2026-10-07T12:23:23.098Z" }, + { url = "https://files.pythonhosted.org/packages/47/a2/4f6310fa699364f0e3af7ee3af88dddd9af066d33e716a0265bbe2b3ea84/tomli-2.5.0-cp315-cp315-win_arm64.whl", hash = "sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd", size = 111493, upload-time = "2026-10-07T12:23:24.233Z" }, + { url = "https://files.pythonhosted.org/packages/68/14/00853f0b396d8971107ae1921bb5b322fdee1650d2f16bf06c20adb532e5/tomli-2.5.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57", size = 171380, upload-time = "2026-10-07T12:23:25.512Z" }, + { url = "https://files.pythonhosted.org/packages/89/ad/fa6949321dadee46b27363974fb197b94c911c3b0f7a5fd26d7dc18fc2a0/tomli-2.5.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd", size = 170553, upload-time = "2026-10-07T12:23:26.855Z" }, + { url = "https://files.pythonhosted.org/packages/53/aa/3056c919eb3e084df3752b2cf5f865dcc04af0b27dba2f66d7b28af4633a/tomli-2.5.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01", size = 294428, upload-time = "2026-10-07T12:23:28.132Z" }, + { url = "https://files.pythonhosted.org/packages/96/b2/faeeb5d8769ea3832021d73e892c8391eae7b4b4f8b55a789127bd8b18a9/tomli-2.5.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f", size = 304909, upload-time = "2026-10-07T12:23:29.381Z" }, + { url = "https://files.pythonhosted.org/packages/f6/52/f094c09e73fb654b621716d019acb5d29bdfd1be01df80c281d552bda48d/tomli-2.5.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a", size = 293220, upload-time = "2026-10-07T12:23:30.608Z" }, + { url = "https://files.pythonhosted.org/packages/86/f5/0c30541078ca4b505ce3bd76ed931facbfec524dd018535d691d1af0a6d2/tomli-2.5.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142", size = 305705, upload-time = "2026-10-07T12:23:32.181Z" }, + { url = "https://files.pythonhosted.org/packages/05/74/590e7d19d6a118fc5cc5704ff358e21d95b8573f6b9443b1519f29ca8825/tomli-2.5.0-cp315-cp315t-win32.whl", hash = "sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5", size = 108432, upload-time = "2026-10-07T12:23:33.496Z" }, + { url = "https://files.pythonhosted.org/packages/1c/b8/63a75cfb27a17c38550e44025d3a6e7be64516fd8608a3b75703bf37d81b/tomli-2.5.0-cp315-cp315t-win_amd64.whl", hash = "sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571", size = 117281, upload-time = "2026-10-07T12:23:34.648Z" }, + { url = "https://files.pythonhosted.org/packages/72/01/e8c1debb2173973372934c68fc8e46170ab60ef23ed4592dff4dec6e8993/tomli-2.5.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7", size = 115069, upload-time = "2026-10-07T12:23:35.77Z" }, + { url = "https://files.pythonhosted.org/packages/60/3f/3e3f8fd0919249b0200c80fbc4f9a1e70be19f9883da71dfb7f8b9ab8aca/tomli-2.5.0-py3-none-any.whl", hash = "sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b", size = 14765, upload-time = "2026-10-07T12:23:36.875Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] From d98a26b1c8cbcbb465d9cadc411ecf7235ab10c3 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Wed, 21 Oct 2026 20:08:04 +0200 Subject: [PATCH 028/101] chore(main): release 1.845.0 (#11927) * chore(main): release 1.845.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 + backend/Cargo.lock | 162 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 +++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 135 insertions(+), 128 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4d5a6e619b..c1da1dae8a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.844.0" + ".": "1.845.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d08a7e746..23f4578675 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.845.0](https://github.com/windmill-labs/windmill/compare/v1.844.0...v1.845.0) (2026-10-21) + + +### Features + +* home and empty ai sessions share one session composer ([#11635](https://github.com/windmill-labs/windmill/issues/11635)) ([56b2e10](https://github.com/windmill-labs/windmill/commit/56b2e106daedb5ae381052d3116346a88ba3f206)) + ## [1.844.0](https://github.com/windmill-labs/windmill/compare/v1.843.0...v1.844.0) (2026-10-21) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index c634538654..647ea423a5 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -8155,9 +8155,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", "stable_deref_trait", @@ -15486,7 +15486,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-nats", @@ -15576,7 +15576,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.844.0" +version = "1.845.0" dependencies = [ "async-stream", "async-trait", @@ -15611,7 +15611,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15624,7 +15624,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "argon2", @@ -15767,7 +15767,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15791,7 +15791,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15808,7 +15808,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "axum", @@ -15834,7 +15834,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.844.0" +version = "1.845.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15844,7 +15844,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15861,7 +15861,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "base64 0.22.1", @@ -15883,7 +15883,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "axum", @@ -15906,7 +15906,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15922,7 +15922,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15944,7 +15944,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15966,7 +15966,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -15980,7 +15980,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-nats", @@ -16016,7 +16016,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "axum", @@ -16042,7 +16042,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -16070,7 +16070,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "axum", @@ -16092,7 +16092,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -16112,7 +16112,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "axum", @@ -16154,7 +16154,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "axum", @@ -16184,7 +16184,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.844.0" +version = "1.845.0" dependencies = [ "lazy_static", "serde", @@ -16196,7 +16196,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.844.0" +version = "1.845.0" dependencies = [ "argon2", "axum", @@ -16220,7 +16220,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -16235,7 +16235,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.844.0" +version = "1.845.0" dependencies = [ "axum", "chrono", @@ -16274,7 +16274,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.844.0" +version = "1.845.0" dependencies = [ "chrono", "lazy_static", @@ -16289,7 +16289,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "axum", @@ -16308,7 +16308,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.844.0" +version = "1.845.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16426,7 +16426,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.844.0" +version = "1.845.0" dependencies = [ "chrono", "futures", @@ -16446,7 +16446,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.844.0" +version = "1.845.0" dependencies = [ "regex", "serde", @@ -16463,7 +16463,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16490,7 +16490,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "futures", @@ -16507,7 +16507,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.844.0" +version = "1.845.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16523,7 +16523,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -16545,7 +16545,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -16576,7 +16576,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "arc-swap", @@ -16601,7 +16601,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-stream", @@ -16637,7 +16637,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "futures", @@ -16656,7 +16656,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.844.0" +version = "1.845.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16665,7 +16665,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -16677,7 +16677,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde_json", @@ -16689,7 +16689,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "gosyn", @@ -16701,7 +16701,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -16713,7 +16713,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde_json", @@ -16725,7 +16725,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "nu-parser", @@ -16736,7 +16736,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16747,7 +16747,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16759,7 +16759,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16770,7 +16770,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-recursion", @@ -16793,7 +16793,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde_json", @@ -16805,7 +16805,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -16819,7 +16819,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16836,7 +16836,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -16849,7 +16849,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde", @@ -16861,7 +16861,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -16879,7 +16879,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16895,7 +16895,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16912,7 +16912,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -16926,7 +16926,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-recursion", @@ -16965,7 +16965,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "const_format", @@ -17003,7 +17003,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.844.0" +version = "1.845.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17014,7 +17014,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-recursion", @@ -17049,7 +17049,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17073,7 +17073,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17106,7 +17106,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17133,7 +17133,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17166,7 +17166,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17186,7 +17186,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17220,7 +17220,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17257,7 +17257,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17280,7 +17280,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17304,7 +17304,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-nats", @@ -17328,7 +17328,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17363,7 +17363,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17391,7 +17391,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-trait", @@ -17416,7 +17416,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17435,7 +17435,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-once-cell", @@ -17553,7 +17553,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.844.0" +version = "1.845.0" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index e82c7e1618..de86a9c39c 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.844.0" +version = "1.845.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.844.0" +version = "1.845.0" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index b4e984bc0b..338d8462f1 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.844.0" +version = "1.845.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.844.0" +version = "1.845.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.844.0" +version = "1.845.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.844.0" +version = "1.845.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 3a028912b5..61a2f25d83 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.844.0" +version = "1.845.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 470cb78735..835c7b029c 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.844.0 + version: 1.845.0 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 3f4666f852..fa3c9c0cdb 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.844.0"; +export const VERSION = "v1.845.0"; export async function login(email: string, password: string): Promise { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index ff39e60b4b..f78ce49324 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.844.0", + "version": "1.845.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.844.0", + "version": "1.845.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index f1cc518c7c..567322997e 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.844.0", + "version": "1.845.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index d959059148..a87ab6ccee 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.844.0"; +export const VERSION = "1.845.0"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1fa54a08b1..73b690fd88 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.844.0", + "version": "1.845.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.844.0", + "version": "1.845.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 21907d2462..a9856d606b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.844.0", + "version": "1.845.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index 32e22ad03a..b9263b558c 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.844.0" +wmill = ">=1.845.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 16514dcca9..f71f046d15 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.844.0 + version: 1.845.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 3f2dd51bcb..c6fa77f9ed 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.844.0' + ModuleVersion = '1.845.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index ca4f8720a4..382aecd375 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.844.0" +version = "1.845.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 3530a5a3c1..a227be7522 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.844.0", + "version": "1.845.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 5a867f7baa..bf8ddbe672 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.844.0", + "version": "1.845.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index 99b9b31364..6c7e7ab02c 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.844.0 +1.845.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index f464d9c3e5..6d61cdb67d 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.844.0", + "version": "1.845.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.844.0", + "version": "1.845.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index d6d19235e7..5a8c427b4a 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.844.0", + "version": "1.845.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 73f655db98dd0f0fd03881c36e6c9310fb2687a2 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Wed, 21 Oct 2026 20:58:44 +0200 Subject: [PATCH 029/101] feat: home list settings menu with sort, library and user-folder toggles (#11928) * feat: restore home sort order and library script toggle in a list settings menu Co-Authored-By: Claude Opus 5.5 * feat: hide other users' folders from the list settings, remember open folders and list settings Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../src/lib/components/home/ItemsList.svelte | 137 +++++++++++++++--- .../src/lib/components/home/TreeView.svelte | 12 +- .../lib/components/home/TreeViewRoot.svelte | 7 +- .../components/home/treeViewState.svelte.ts | 36 +++++ 4 files changed, 171 insertions(+), 21 deletions(-) diff --git a/frontend/src/lib/components/home/ItemsList.svelte b/frontend/src/lib/components/home/ItemsList.svelte index 6b9ee2fc50..29a2362691 100644 --- a/frontend/src/lib/components/home/ItemsList.svelte +++ b/frontend/src/lib/components/home/ItemsList.svelte @@ -27,12 +27,13 @@ Code2, LayoutDashboard, MoreHorizontal, + Settings, Tag } from 'lucide-svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import CreateActionsMenu from './CreateActionsMenu.svelte' import ContentSearchInner from '$lib/components/ContentSearchInner.svelte' - import type { IconType } from '$lib/utils' + import type { IconType, Item as MenuItem } from '$lib/utils' import { HOME_COLUMN_WIDTH, HOME_SEARCH_SHOW_FLOW, HOME_SEARCH_PLACEHOLDER } from '$lib/consts' @@ -50,12 +51,13 @@ import { clampRows } from './clampRows' import { setUnruledList } from '../common/table/unruledList' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' - import { isOwner } from '$lib/utils' + import { getLocalSetting, isOwner, storeLocalSetting } from '$lib/utils' import { sendUserToast } from '$lib/toast' import Drawer from '../common/drawer/Drawer.svelte' import HighlightCode from '../HighlightCode.svelte' import DrawerContent from '../common/drawer/DrawerContent.svelte' import TreeViewRoot from './TreeViewRoot.svelte' + import { TreeOpenMemory } from './treeViewState.svelte' import { effectivePath, type ItemType } from './treeViewUtils' import { tick, untrack } from 'svelte' import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte' @@ -167,7 +169,17 @@ } // Single URL-synced source of truth for the searchbar-driven filters. - let filterValues = useUrlSyncedFilterInstance(untrack(() => searchFilterSchema)) + // The library and user-folder choices outlive the URL: a link that sets one still wins, + // but a bare visit restores the last one made in this browser. + const HIDE_LIBRARY_SETTING_NAME = 'homeHideLibrary' + const ONLY_USER_FOLDERS_SETTING_NAME = 'homeOnlyUserFolders' + let filterValues = useUrlSyncedFilterInstance( + untrack(() => searchFilterSchema), + { + include_library: getLocalSetting(HIDE_LIBRARY_SETTING_NAME) == 'true' ? false : undefined, + only_user_folders: getLocalSetting(ONLY_USER_FOLDERS_SETTING_NAME) == 'true' || undefined + } + ) // Derived views the rest of the data layer reads. The merged-endpoint reload effect // depends on these (search, kind, archived, library, user-folder scope), so changing a @@ -179,7 +191,18 @@ let runnableKinds = $derived(itemKind === 'all' ? undefined : itemKind) let archived = $derived(!!filterValues.val.archived) let includeWithoutMain = $derived((filterValues.val.include_library ?? true) as boolean) - let filterUserFolders = $derived(!!filterValues.val.only_user_folders) + // Gated on the role so a choice remembered from an admin session can't hide other users' + // spaces for a role that is never offered the toggle. + let filterUserFolders = $derived(!!filterValues.val.only_user_folders && !!filterUserFoldersType) + $effect(() => { + storeLocalSetting(HIDE_LIBRARY_SETTING_NAME, includeWithoutMain ? undefined : 'true') + }) + $effect(() => { + storeLocalSetting( + ONLY_USER_FOLDERS_SETTING_NAME, + filterValues.val.only_user_folders ? 'true' : undefined + ) + }) // Content search is a distinct mode: its results come from ContentSearchInner // (which carries only path + content), so the row-list filters can't @@ -374,14 +397,13 @@ } const gen = ++loadGen // Snapshot the cursor now: a later request must not consume a cursor minted - // by a filter that has since changed. + // by an order/filter that has since changed. const cursor = reset ? undefined : serverCursor let res: { items: RunnableItem[]; next_cursor?: string } try { res = await ScriptService.listRunnables({ workspace: ws, - orderBy: 'updated', - orderDesc: true, + ...sortToParams(sortOrder), showArchived: archived ? true : undefined, includeWithoutMain: includeWithoutMain ? true : undefined, kinds: runnableKinds, @@ -601,8 +623,7 @@ try { res = await ScriptService.listRunnables({ workspace: ws, - orderBy: 'updated', - orderDesc: true, + ...sortToParams(sortOrder), showArchived: archived ? true : undefined, includeWithoutMain: includeWithoutMain ? true : undefined, kinds: runnableKinds, @@ -752,15 +773,75 @@ const cmp = new Intl.Collator('en').compare - // Preserve the endpoint's exact order (most recently updated first, starred pinned on top - // of the first page) rather than re-deriving it on the client: each row carries its server - // fetch ordinal (`ord`), which already reflects the (path, kind) tiebreaks, full-precision - // timestamps and the database collation. Sorting by it can never disagree with the server, - // so a later page never jumps above shown rows on "load more". + // The order is applied server-side so it holds across the whole workspace, not just the + // loaded pages. Starred items are pinned on top of the first page. + type SortOrder = 'updated_desc' | 'updated_asc' | 'name_asc' | 'name_desc' + const SORT_SETTING_NAME = 'homeSort' + const sortOptions: { value: SortOrder; label: string }[] = [ + { value: 'updated_desc', label: 'Recently updated' }, + { value: 'updated_asc', label: 'Oldest updated' }, + { value: 'name_asc', label: 'Name (A-Z)' }, + { value: 'name_desc', label: 'Name (Z-A)' } + ] + let sortOrder = $state( + sortOptions.find((o) => o.value === getLocalSetting(SORT_SETTING_NAME))?.value ?? 'updated_desc' + ) + function setSortOrder(o: SortOrder) { + sortOrder = o + storeLocalSetting(SORT_SETTING_NAME, o === 'updated_desc' ? undefined : o) + } + function sortToParams(o: SortOrder): { orderBy: 'updated' | 'name'; orderDesc: boolean } { + return { + orderBy: o.startsWith('name') ? 'name' : 'updated', + orderDesc: o.endsWith('desc') + } + } + + // Preserve the endpoint's exact order rather than re-deriving it on the client: each row + // carries its server fetch ordinal (`ord`), which already reflects the chosen order, the + // (path, kind) tiebreaks, full-precision timestamps and the database collation. Sorting by + // it can never disagree with the server, so a later page never jumps above shown rows on + // "load more". function compareItems(a: { ord?: number }, b: { ord?: number }): number { return (a.ord ?? 0) - (b.ord ?? 0) } + let listSettingsItems: MenuItem[] = $derived([ + { + displayName: 'Show library scripts', + description: 'Scripts without a main function', + toggle: includeWithoutMain, + hide: !($userStore && $roleCapabilities.code), + action: () => { + // On by default, so showing them again clears the key rather than leaving a chip. + if (includeWithoutMain) filterValues.val.include_library = false + else delete filterValues.val.include_library + } + }, + { + displayName: + filterUserFoldersType === 'only f/*' ? 'Hide user folders' : "Hide other users' folders", + description: + filterUserFoldersType === 'only f/*' + ? 'Only f/*' + : `Only u/${$userStore?.username} and f/*`, + toggle: filterUserFolders, + hide: !filterUserFoldersType, + action: () => { + if (filterUserFolders) delete filterValues.val.only_user_folders + else filterValues.val.only_user_folders = true + } + }, + ...sortOptions.map((o, i) => ({ + displayName: o.label, + selected: o.value === sortOrder, + separatorTop: i === 0, + disabled: filter !== '', + tooltip: filter !== '' ? 'Search results are ranked by relevance' : undefined, + action: () => setSortOrder(o.value) + })) + ]) + const opts: uFuzzy.Options = { sort: (info, haystack, needle) => { let { @@ -850,6 +931,12 @@ } let collapseAll = $state(true) + let treeOpenMemory = $derived(new TreeOpenMemory(`homeTreeOpen:${$workspaceStore}`)) + function toggleCollapseAll() { + // Collapsing all is also how to forget the folders reopened on every visit. + if (!collapseAll) treeOpenMemory.clear() + collapseAll = !collapseAll + } // Human-readable list of the filters currently narrowing the list. Empty means no // filter is active, so an empty result then means the workspace itself has no items // (NoItemFound shows the welcome message); otherwise the filters are just too narrow @@ -1160,9 +1247,9 @@ let treeGlobalHasMore = $derived(!treeLazyMode && !searching ? hasMoreServer : false) $effect(() => { if ($userStore && $workspaceStore) { - ;[archived, includeWithoutMain, searching, ownerFilter, itemKind] - // reloadItems (not a bare loadRunnables) so an in-place change — archive, library, - // kind — reloads the global stream AND re-fetches the currently-open owners + ;[archived, includeWithoutMain, sortOrder, searching, ownerFilter, itemKind] + // reloadItems (not a bare loadRunnables) so an in-place change — sort, archive, + // library, kind — reloads the global stream AND re-fetches the currently-open owners // under the new filter, keeping folders expanded (file-explorer style) // rather than collapsing them. Mode changes (owner/search) flip treeLazyMode, so // reloadItems skips the re-fetch and the {#key} remount handles the reset. @@ -1579,9 +1666,21 @@ variant="default" iconOnly title={collapseAll ? 'Expand all' : 'Collapse all'} - on:click={() => (collapseAll = !collapseAll)} + on:click={toggleCollapseAll} startIcon={{ icon: collapseAll ? ChevronsUpDown : ChevronsDownUp }} /> + + {#snippet buttonReplacement()} + +
+ {/if} +
+
{:else} -
e.stopPropagation()}> {#if !currentTag || !schema[currentTag]} - {#if presets.length} + {#if presets.length && !freeTextFilterHint}
Presets
@@ -820,7 +843,7 @@ onClick: item.onClick, label: item.filterSchema.label || item.key, description: item.filterSchema.description, - highlighted: index === highlightedIndex + highlighted: index === highlightedIndex && !freeTextFilterHint })} {/if} {/each} diff --git a/frontend/src/lib/components/filterSearchbarMatch.test.ts b/frontend/src/lib/components/filterSearchbarMatch.test.ts new file mode 100644 index 0000000000..7bc0a5eefa --- /dev/null +++ b/frontend/src/lib/components/filterSearchbarMatch.test.ts @@ -0,0 +1,19 @@ +import { describe, it, expect } from 'vitest' +import { filterMatchesQuery } from './FilterSearchbar.svelte' + +describe('filterMatchesQuery', () => { + const archived = { type: 'boolean' as const, label: 'Only archived' } + + it('matches each word anywhere in the label or key', () => { + expect(filterMatchesQuery('archived', archived, 'archive')).toBe(true) + expect(filterMatchesQuery('archived', archived, 'archived only')).toBe(true) + expect(filterMatchesQuery('archived', archived, 'archived scripts')).toBe(false) + expect( + filterMatchesQuery('include_library', { type: 'boolean', label: 'Library' }, 'include lib') + ).toBe(true) + }) + + it('reads an escaped space as a word break', () => { + expect(filterMatchesQuery('archived', archived, 'archived\\ only')).toBe(true) + }) +}) From 5019fab5a5f996796a07524c770f86309a7a3500 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Wed, 21 Oct 2026 21:56:50 +0200 Subject: [PATCH 034/101] fix: home recent cards include items opened on their own page (#11934) * feat: home recent cards include items opened on their own page Co-Authored-By: Claude Opus 5.5 * fix: bump recent items untracked so an effect recording a visit does not loop Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../apps/editor/InWorkspaceAppViewer.svelte | 10 ++++++++ .../lib/components/details/FlowDetail.svelte | 10 ++++++++ .../components/details/ScriptDetail.svelte | 11 ++++++++ .../components/home/HomeQuickAccess.svelte | 18 +++++++------ .../lib/components/home/recentItems.svelte.ts | 25 ++++++++++++++----- .../agents/edit/[...path]/+page.svelte | 3 ++- .../agents/get/[...path]/+page.svelte | 14 +++++++++++ .../(logged)/apps/edit/[...path]/+page.svelte | 3 ++- .../apps_raw/edit/[...path]/+page.svelte | 3 ++- .../flows/edit/[...path]/+page.svelte | 3 ++- .../scripts/edit/[...path]/+page.svelte | 3 ++- 11 files changed, 84 insertions(+), 19 deletions(-) diff --git a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte index 0d4fb03704..d86713253a 100644 --- a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte +++ b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte @@ -25,6 +25,7 @@ import { isMenuHidden } from '$lib/components/sessions/sessionMode.svelte' import { setOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { useEditRights } from '$lib/operatorWriteRights' + import { recentItems } from '$lib/components/home/recentItems.svelte' let { workspace, @@ -179,6 +180,15 @@ isRawApp = !!lite?.raw_app executionMode = lite?.policy?.execution_mode ?? lite?.execution_mode summary = lite?.summary || undefined + // Only the route's own page is a visit; a session's preview tab opens it on its own. + if (ownsPageHeader) { + recentItems.record(workspace, { + kind: isRawApp ? 'raw_app' : 'app', + path: appPerms.path, + summary, + via: 'view' + }) + } } catch (_) { appPerms = undefined summary = undefined diff --git a/frontend/src/lib/components/details/FlowDetail.svelte b/frontend/src/lib/components/details/FlowDetail.svelte index b727ddcc32..b700269e93 100644 --- a/frontend/src/lib/components/details/FlowDetail.svelte +++ b/frontend/src/lib/components/details/FlowDetail.svelte @@ -95,6 +95,7 @@ openEditInFork } from '$lib/utils/editInFork' import { isCloudHosted } from '$lib/cloud' + import { recentItems } from '$lib/components/home/recentItems.svelte' let { path: routePath, @@ -263,6 +264,15 @@ if (!flow.path.startsWith(`u/${actingUser?.username}`) && flow.path.split('/').length > 2) { invisible_to_owner = flow.visible_to_runner_only } + // Opened from a session's preview tab, it was the session's doing, not a visit. + if (!embedded) { + recentItems.record(workspace!, { + kind: 'flow', + path: flow.path, + summary: flow.summary, + via: 'view' + }) + } intervalId && clearInterval(intervalId) deploymentInProgress = flow.lock_error_logs == '' if (deploymentInProgress) { diff --git a/frontend/src/lib/components/details/ScriptDetail.svelte b/frontend/src/lib/components/details/ScriptDetail.svelte index 78cca8ee8d..618bafe3ab 100644 --- a/frontend/src/lib/components/details/ScriptDetail.svelte +++ b/frontend/src/lib/components/details/ScriptDetail.svelte @@ -119,6 +119,7 @@ import WacDiagram from '$lib/components/graph/WacDiagram.svelte' import { twMerge } from 'tailwind-merge' import CiTestResults from '$lib/components/CiTestResults.svelte' + import { recentItems } from '$lib/components/home/recentItems.svelte' let { hash: routeHash, @@ -370,6 +371,16 @@ if (!script.path.startsWith(`u/${actingUser?.username}`) && script.path.split('/').length > 2) { invisible_to_owner = script.visible_to_runner_only } + // Opened from a session's preview tab, it was the session's doing, not a visit. An + // archived script has no page for Home's card to open. + if (!embedded && !script.archived) { + recentItems.record(workspace!, { + kind: 'script', + path: script.path, + summary: script.summary, + via: 'view' + }) + } onLoadState?.('loaded') } diff --git a/frontend/src/lib/components/home/HomeQuickAccess.svelte b/frontend/src/lib/components/home/HomeQuickAccess.svelte index 12f655350d..df64cbf9bd 100644 --- a/frontend/src/lib/components/home/HomeQuickAccess.svelte +++ b/frontend/src/lib/components/home/HomeQuickAccess.svelte @@ -29,7 +29,7 @@ getFavoriteHref, type FavoriteKind } from '$lib/components/sidebar/FavoriteMenu.svelte' - import { MAX_AGE_DAYS, recentItems, type RecentKind } from './recentItems.svelte' + import { MAX_AGE_DAYS, recentItems, type RecentKind, type RecentVia } from './recentItems.svelte' import { useReducedMotion } from '$lib/svelte5Utils.svelte' import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate' import { @@ -59,6 +59,7 @@ path: string title: string at?: number + via?: RecentVia } function asStarKind(kind: RecentKind): FavoriteKind { @@ -84,7 +85,7 @@ }, { displayName: 'Show recent', - description: `Scripts, flows and apps you opened in their editor in the last ${MAX_AGE_DAYS} days, in this browser`, + description: `Scripts, flows and apps you opened or edited in the last ${MAX_AGE_DAYS} days, in this browser`, toggle: homeQuickAccessSettings.showRecent, disabled: homeQuickAccessSettings.showRecent && !homeQuickAccessSettings.showFavorites, action: () => homeQuickAccessSettings.setShowRecent(!homeQuickAccessSettings.showRecent) @@ -194,8 +195,8 @@ f.kind === 'asset' ? [] : [{ kind: f.kind, starKind: f.kind, path: f.path, title: f.label }] ) ) - // Favorites first, then what was edited lately; a starred item is listed once, as a favorite. - // With the favorites turned off, a starred item edited lately shows among the recent ones. + // Favorites first, then what was opened lately; a starred item is listed once, as a favorite. + // With the favorites turned off, a starred item opened lately shows among the recent ones. let recentAll: Entry[] = $derived.by(() => { const { showFavorites, showRecent } = homeQuickAccessSettings const starred = new Set( @@ -208,7 +209,8 @@ starKind: asStarKind(r.kind), path: r.path, title: r.summary || r.path, - at: r.at + at: r.at, + via: r.via })) }) // Grows by a page from the "Load next" card; back to one page on the next visit. @@ -234,7 +236,7 @@ // page has been open. let now = $state(Date.now()) - function editedTooltip(at: number): string { + function recentTooltip(at: number, via: RecentVia | undefined): string { const mins = Math.max(0, Math.floor((now - at) / 60_000)) const unit = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'} ago` const ago = @@ -245,7 +247,7 @@ : mins < 1440 ? unit(Math.floor(mins / 60), 'hour') : unit(Math.floor(mins / 1440), 'day') - return `Edited by you ${ago}` + return `${via === 'view' ? 'Opened' : 'Edited'} by you ${ago}` } // Everything the lists hold, the recent ones not loaded yet included. @@ -364,7 +366,7 @@ {#if !favorite && item.at} (now = Date.now())} role="note" > diff --git a/frontend/src/lib/components/home/recentItems.svelte.ts b/frontend/src/lib/components/home/recentItems.svelte.ts index edc80e8aba..29057df0f3 100644 --- a/frontend/src/lib/components/home/recentItems.svelte.ts +++ b/frontend/src/lib/components/home/recentItems.svelte.ts @@ -1,3 +1,4 @@ +import { untrack } from 'svelte' import { onUserChange, scopedKey } from '$lib/userScopedStorage' export type RecentKind = 'script' | 'flow' | 'app' | 'raw_app' | 'agent' @@ -6,10 +7,17 @@ export type RecentItem = { kind: RecentKind path: string summary?: string - /** Epoch ms of the last time the item was opened in its editor. */ + /** Epoch ms of the last time the item was opened, in its editor or on its own page. */ at: number + /** How it was last opened: in its editor, or on its page to run or use it. Items stored + * before views were recorded have none, and were all edits. */ + via?: RecentVia } +export type RecentVia = 'edit' | 'view' + +type RecordedItem = Omit & { via: RecentVia } + const MAX_ITEMS = 30 export const MAX_AGE_DAYS = 7 const MAX_AGE_MS = MAX_AGE_DAYS * 24 * 60 * 60 * 1000 @@ -49,9 +57,14 @@ function write(workspace: string, items: RecentItem[]): void { class RecentItems { // Bumped on every write and on the user resolving, so readers re-read storage. #version = $state(0) + // `++` reads the counter too: bumped from an effect (a page recording its visit), the effect + // would depend on it and re-run on its own write, forever. + #bump() { + untrack(() => this.#version++) + } // A page opened by a cold load can finish loading before the user's email resolves, and the // storage key needs it; those visits wait here instead of being dropped. - #pending: { workspace: string; item: Omit }[] = [] + #pending: { workspace: string; item: RecordedItem }[] = [] constructor() { onUserChange((email) => { @@ -60,7 +73,7 @@ class RecentItems { this.#pending = [] for (const p of pending) this.record(p.workspace, p.item) } - this.#version++ + this.#bump() }) } @@ -70,7 +83,7 @@ class RecentItems { } /** Records an item as just opened. A missing summary keeps the one already stored. */ - record(workspace: string, item: Omit): void { + record(workspace: string, item: RecordedItem): void { if (!workspace || !item.path) return if (!storageKey(workspace)) { this.#pending.push({ workspace, item }) @@ -84,7 +97,7 @@ class RecentItems { at: Date.now() } write(workspace, [next, ...previous.filter((x) => x !== existing)].slice(0, MAX_ITEMS)) - this.#version++ + this.#bump() } forget(workspace: string, kind: RecentKind, path: string): void { @@ -92,7 +105,7 @@ class RecentItems { workspace, read(workspace).filter((x) => !(x.kind === kind && x.path === path)) ) - this.#version++ + this.#bump() } } diff --git a/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte index 9690d2c982..7c6b5f9571 100644 --- a/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte @@ -31,7 +31,8 @@ recentItems.record(workspace, { kind: 'agent', path: agentPath, - summary: agent.description + summary: agent.description, + via: 'edit' }) } catch {} } diff --git a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte index d388f96588..0fcb6174e2 100644 --- a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte @@ -23,6 +23,7 @@ import { agentMenuItems, deleteAgent } from '$lib/components/flows/agentActions' import AgentHistory from '$lib/components/flows/AgentHistory.svelte' import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { recentItems } from '$lib/components/home/recentItems.svelte' import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' @@ -44,6 +45,19 @@ config != undefined && (agent?.canWrite ?? false) && $roleCapabilities.code ) + // Recorded once the agent is in: a path with nothing deployed never loads one. + let loaded = $derived(config != undefined) + $effect(() => { + if (ws && loaded) { + recentItems.record(ws, { + kind: 'agent', + path, + summary: agent?.state?.description, + via: 'view' + }) + } + }) + let configModal: AgentConfigModal | undefined = $state(undefined) let shareModal: ShareModal | undefined = $state(undefined) let deploymentDrawer: DeployWorkspaceDrawer | undefined = $state(undefined) diff --git a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte index fdcf447f64..d32c279802 100644 --- a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte @@ -212,7 +212,8 @@ recentItems.record($workspaceStore!, { kind: 'app', path: backendApp.path, - summary: backendApp.summary + summary: backendApp.summary, + via: 'edit' }) } // Deployed App value for AppEditor's autosave `discardIf`, captured BEFORE diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte index 0a89e2141d..aa51d62ea8 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte @@ -318,7 +318,8 @@ recentItems.record($workspaceStore!, { kind: 'raw_app', path: backendApp.path, - summary: backendApp.summary + summary: backendApp.summary, + via: 'edit' }) } // `other_drafts_users` only computed when `getDraft`; don't clobber the diff --git a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte index 9fd0e65a45..cbaf2fd935 100644 --- a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte @@ -352,7 +352,8 @@ recentItems.record($workspaceStore!, { kind: 'flow', path: backendFlow.path, - summary: backendFlow.summary + summary: backendFlow.summary, + via: 'edit' }) } // `other_drafts_users` only computed when `getDraft`; don't clobber the diff --git a/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte index 9a9f9fb14e..003f6c7752 100644 --- a/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/scripts/edit/[...path]/+page.svelte @@ -317,7 +317,8 @@ recentItems.record($workspaceStore!, { kind: 'script', path: backendScript.path, - summary: backendScript.summary + summary: backendScript.summary, + via: 'edit' }) } // The editor re-infers the schema as soon as it mounts, so a baseline From 35b5960c473c89e363cfc00077b2477146a35108 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Wed, 21 Oct 2026 22:03:47 +0200 Subject: [PATCH 035/101] home recent cards show 1m instead of seconds (#11935) Co-authored-by: Claude Opus 5.5 --- frontend/src/lib/components/TimeAgo.svelte | 9 ++++++--- frontend/src/lib/components/home/HomeQuickAccess.svelte | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/frontend/src/lib/components/TimeAgo.svelte b/frontend/src/lib/components/TimeAgo.svelte index 6138cdb6da..1e5515f144 100644 --- a/frontend/src/lib/components/TimeAgo.svelte +++ b/frontend/src/lib/components/TimeAgo.svelte @@ -9,7 +9,8 @@ noDate?: boolean isRecent?: boolean noSeconds?: boolean - /** Single-unit form ("2m", "3h", "5d") for rows too narrow for "2 mins ago". */ + /** Single-unit form ("2m", "3h", "5d") for rows too narrow for "2 mins ago". With + * `noSeconds`, the first minute reads "1m" rather than counting seconds. */ compact?: boolean } @@ -71,7 +72,9 @@ const secs = secondsAgo(new Date(dateString)) const left = secs < 60 - ? 1 + ? compact && noSeconds + ? 60 - secs + : 1 : secs < 3600 ? 60 - (secs % 60) : secs < 86_400 @@ -125,7 +128,7 @@ // (PipelineEventLog, PipelineActivityPanel, IndexerMemorySettings): seconds stay // meaningful right up to the minute mark. const secs = secondsAgo(date) - if (secs < 60) return `${secs}s` + if (secs < 60) return noSeconds ? '1m' : `${secs}s` const mins = minutesAgo(date) if (mins < 60) return `${mins}m` const hours = hoursAgo(date) diff --git a/frontend/src/lib/components/home/HomeQuickAccess.svelte b/frontend/src/lib/components/home/HomeQuickAccess.svelte index df64cbf9bd..b81f848838 100644 --- a/frontend/src/lib/components/home/HomeQuickAccess.svelte +++ b/frontend/src/lib/components/home/HomeQuickAccess.svelte @@ -370,7 +370,7 @@ onmouseenter={() => (now = Date.now())} role="note" > - + {/if}
From 01084cd405ed930b340c729a73f904287b2e353e Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Wed, 21 Oct 2026 22:04:23 +0200 Subject: [PATCH 036/101] chore(main): release 1.846.1 (#11932) * chore(main): release 1.846.1 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 + backend/Cargo.lock | 158 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 +++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 134 insertions(+), 126 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a6a3457d0c..7339eafd50 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.846.0" + ".": "1.846.1" } diff --git a/CHANGELOG.md b/CHANGELOG.md index b5b0fbbfbf..8e97b73451 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## [1.846.1](https://github.com/windmill-labs/windmill/compare/v1.846.0...v1.846.1) (2026-10-21) + + +### Bug Fixes + +* home recent cards include items opened on their own page ([#11934](https://github.com/windmill-labs/windmill/issues/11934)) ([5019fab](https://github.com/windmill-labs/windmill/commit/5019fab5a5f996796a07524c770f86309a7a3500)) +* home search suggests filters whose name matches the typed text ([#11933](https://github.com/windmill-labs/windmill/issues/11933)) ([bf1eb85](https://github.com/windmill-labs/windmill/commit/bf1eb85577419cc08482158c1835d5262ebb87d2)) + ## [1.846.0](https://github.com/windmill-labs/windmill/compare/v1.845.0...v1.846.0) (2026-10-21) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 860aee01b6..13928f21cb 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -15486,7 +15486,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-nats", @@ -15576,7 +15576,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.846.0" +version = "1.846.1" dependencies = [ "async-stream", "async-trait", @@ -15611,7 +15611,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15624,7 +15624,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "argon2", @@ -15767,7 +15767,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15791,7 +15791,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15808,7 +15808,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "axum", @@ -15834,7 +15834,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.846.0" +version = "1.846.1" dependencies = [ "reqwest 0.12.28", "serde", @@ -15844,7 +15844,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15861,7 +15861,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "base64 0.22.1", @@ -15883,7 +15883,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "axum", @@ -15906,7 +15906,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15922,7 +15922,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15944,7 +15944,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15966,7 +15966,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -15980,7 +15980,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-nats", @@ -16016,7 +16016,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "axum", @@ -16042,7 +16042,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -16070,7 +16070,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "axum", @@ -16092,7 +16092,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -16112,7 +16112,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "axum", @@ -16154,7 +16154,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "axum", @@ -16184,7 +16184,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.846.0" +version = "1.846.1" dependencies = [ "lazy_static", "serde", @@ -16196,7 +16196,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.846.0" +version = "1.846.1" dependencies = [ "argon2", "axum", @@ -16220,7 +16220,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -16235,7 +16235,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.846.0" +version = "1.846.1" dependencies = [ "axum", "chrono", @@ -16274,7 +16274,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.846.0" +version = "1.846.1" dependencies = [ "chrono", "lazy_static", @@ -16289,7 +16289,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "axum", @@ -16308,7 +16308,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.846.0" +version = "1.846.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -16426,7 +16426,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.846.0" +version = "1.846.1" dependencies = [ "chrono", "futures", @@ -16446,7 +16446,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.846.0" +version = "1.846.1" dependencies = [ "regex", "serde", @@ -16463,7 +16463,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16490,7 +16490,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "futures", @@ -16507,7 +16507,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.846.0" +version = "1.846.1" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16523,7 +16523,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -16545,7 +16545,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -16576,7 +16576,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "arc-swap", @@ -16601,7 +16601,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-stream", @@ -16637,7 +16637,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "futures", @@ -16656,7 +16656,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.846.0" +version = "1.846.1" dependencies = [ "convert_case 0.6.0", "serde", @@ -16665,7 +16665,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -16677,7 +16677,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde_json", @@ -16689,7 +16689,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "gosyn", @@ -16701,7 +16701,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -16713,7 +16713,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde_json", @@ -16725,7 +16725,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "nu-parser", @@ -16736,7 +16736,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16747,7 +16747,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16759,7 +16759,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -16770,7 +16770,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-recursion", @@ -16793,7 +16793,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde_json", @@ -16805,7 +16805,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -16819,7 +16819,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16836,7 +16836,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -16849,7 +16849,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde", @@ -16861,7 +16861,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -16879,7 +16879,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16895,7 +16895,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -16912,7 +16912,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -16926,7 +16926,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-recursion", @@ -16965,7 +16965,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "const_format", @@ -17003,7 +17003,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.846.0" +version = "1.846.1" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17014,7 +17014,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-recursion", @@ -17049,7 +17049,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17073,7 +17073,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17106,7 +17106,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17133,7 +17133,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17166,7 +17166,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17186,7 +17186,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17220,7 +17220,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17257,7 +17257,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17280,7 +17280,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17304,7 +17304,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-nats", @@ -17328,7 +17328,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17363,7 +17363,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17391,7 +17391,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-trait", @@ -17416,7 +17416,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17435,7 +17435,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-once-cell", @@ -17553,7 +17553,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.846.0" +version = "1.846.1" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 961ee37a24..3f77228280 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.846.0" +version = "1.846.1" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.846.0" +version = "1.846.1" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 61b5894ddf..6c1adc33e8 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.846.0" +version = "1.846.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.846.0" +version = "1.846.1" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.846.0" +version = "1.846.1" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.846.0" +version = "1.846.1" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 5eb1838791..5424540fca 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.846.0" +version = "1.846.1" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index f70ef10aa2..c4c09b5761 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.846.0 + version: 1.846.1 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 8afa1f1380..895e35e45f 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.846.0"; +export const VERSION = "v1.846.1"; export async function login(email: string, password: string): Promise { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 5572137e52..0bc4161402 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.846.0", + "version": "1.846.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.846.0", + "version": "1.846.1", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index a5f869a554..9804654954 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.846.0", + "version": "1.846.1", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 1cf8c6f86a..b0b201d5c9 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.846.0"; +export const VERSION = "1.846.1"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index dbff478923..16d216ce25 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.846.0", + "version": "1.846.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.846.0", + "version": "1.846.1", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 9e288e775a..3d7b92656d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.846.0", + "version": "1.846.1", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index bd03db5db7..f6a8ef64fe 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.846.0" +wmill = ">=1.846.1" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 801e6565f1..963b1a040f 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.846.0 + version: 1.846.1 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 677a51b2d5..74c899cee5 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.846.0' + ModuleVersion = '1.846.1' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 3bbb94870e..ab2395d8f5 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.846.0" +version = "1.846.1" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index b740427ee4..149c16ad26 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.846.0", + "version": "1.846.1", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index e35fac8296..21b26faad1 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.846.0", + "version": "1.846.1", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index b725f63ea5..70e64b51a1 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.846.0 +1.846.1 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 7db1027b47..1dbd1e6d9b 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.846.0", + "version": "1.846.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.846.0", + "version": "1.846.1", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index f240a10653..17e6f6fdab 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.846.0", + "version": "1.846.1", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 9202a74071ba424ad6cfc1cfded518ee7db002dc Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 22 Oct 2026 01:46:37 +0200 Subject: [PATCH 037/101] fix: hold home's ai composer space with a matching placeholder (#11936) * fix: hold home's ai composer space with a matching placeholder while it loads Co-Authored-By: Claude Opus 5.5 * fix: skip remembering the composer height when a draft holds it open Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../src/lib/components/home/HomeAIChat.svelte | 16 ++- .../home/HomeComposerSkeleton.svelte | 102 ++++++++++++++++++ .../sessions/HomeSessionStarter.svelte | 64 +++++++---- 3 files changed, 161 insertions(+), 21 deletions(-) create mode 100644 frontend/src/lib/components/home/HomeComposerSkeleton.svelte diff --git a/frontend/src/lib/components/home/HomeAIChat.svelte b/frontend/src/lib/components/home/HomeAIChat.svelte index e8bad505d9..0aad0adb1a 100644 --- a/frontend/src/lib/components/home/HomeAIChat.svelte +++ b/frontend/src/lib/components/home/HomeAIChat.svelte @@ -24,6 +24,10 @@ import { useReducedMotion } from '$lib/svelte5Utils.svelte' import { BROWSER } from 'esm-env' import HomeConnectDrawer from './HomeConnectDrawer.svelte' + import HomeComposerSkeleton, { + composerHeight, + rememberComposerHeight + } from './HomeComposerSkeleton.svelte' import { prefersSessionHandoff } from '../copilot/chat/global/gate' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' @@ -132,13 +136,23 @@ fork shares its parent's, and remounting for it only flashes the block. --> {#if HomeSessionStarter && sessionState.hydrated && (rulesReady || shownForRoot === $currentWorkspaceRootId)} {#key $currentWorkspaceRootId} - (shownForRoot = $currentWorkspaceRootId)} /> + (shownForRoot = $currentWorkspaceRootId)} + {placeholder} + onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)} + /> {/key} + {:else} + {@render placeholder()} {/if} {/if}
+{#snippet placeholder()} + +{/snippet} + + {#if open} +
+
+ + + + + {STARTER_PLACEHOLDER} + +
+
+
+ {@render bar('w-24')} + {@render bar('w-20')} +
+ {@render bar('w-12')} + {@render sendButton()} +
+
+ {#if suggestions} +
+ {#each ['w-20', 'w-24', 'w-24'] as width, i (i)} + + {@render bar(width)} + + {/each} +
+ {/if} + {:else} +
+ + + + + {STARTER_PLACEHOLDER} + +
+ {@render bar('w-12')} + {@render sendButton()} +
+
+ {/if} +
diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte index 92dcc4dc72..9ab68c3742 100644 --- a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -1,5 +1,5 @@ + +
+ + Create a Slack app in the Slack API console : pick "From a manifest", then YAML, and paste the manifest below. Then copy the Client ID, + Client Secret and Signing Secret here. Socket Mode and token rotation must stay off. More in the + Windmill docs . + +
+ +
+
diff --git a/frontend/src/lib/components/flows/content/AgentUsePanel.svelte b/frontend/src/lib/components/flows/content/AgentUsePanel.svelte index 83c8fe4217..ee5f761b69 100644 --- a/frontend/src/lib/components/flows/content/AgentUsePanel.svelte +++ b/frontend/src/lib/components/flows/content/AgentUsePanel.svelte @@ -139,9 +139,13 @@ {:else} {#if !signingSecretSet} - The server needs the Slack app's signing secret, so Windmill can tell who sent a - message. An instance admin sets it as the SLACK_SIGNING_SECRET environment - variable. + Windmill needs the Slack app's signing secret to tell who sent a message. + {#if isAdmin} + A workspace's own Slack app takes it in the workspace settings, the instance's app + in the instance settings. + {:else} + A workspace or instance admin can set it. + {/if} {/if} {#if !botName} diff --git a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte index d13e213ea4..a51ca2c199 100644 --- a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte @@ -97,6 +97,7 @@ } from '$lib/components/sessions/sessionState.svelte' import TextInput from '$lib/components/text_input/TextInput.svelte' import CollapseLink from '$lib/components/CollapseLink.svelte' + import SlackAppSetup from '$lib/components/common/slack/SlackAppSetup.svelte' import { validateWebhookUrl, validateEncryptionKey } from '$lib/validators/workspaceSettings' import DataTableSettings, { convertDataTableSettingsFromBackend, @@ -180,11 +181,12 @@ // links here with `agents=true`. let slackAgents = $state($page.url.searchParams.get('agents') === 'true') let slackAppType: 'instance' | 'workspace' = $state('instance') - // Agents verify Slack's requests with the server's signing secret, which only the instance's - // Slack app is signed with, so the toggle is offered for that app alone. - let slackAgentsScopes = $derived(slackAgents && slackAppType === 'instance') + // Agents answer only once Windmill can verify Slack's requests with the signing secret of the + // app the workspace connects through. + let slackSigningSecret: string = $state('') + let slackSigningSecretSet: boolean = $state(false) const slackAgentsStatus = resource( - () => (slackAgentsScopes ? $workspaceStore : undefined), + () => (slackAgents ? $workspaceStore : undefined), async (workspace) => workspace ? await SlackAgentsService.getSlackAgentsStatus({ workspace }) : undefined ) @@ -863,6 +865,7 @@ slackOAuthClientId = config.slack_oauth_client_id || '' slackOAuthClientSecret = config.slack_oauth_client_secret || '' slackOAuthConfigLoaded = !!config.slack_oauth_client_id + slackSigningSecretSet = !!config.slack_signing_secret } catch (e) { console.error('Failed to load Slack OAuth config:', e) } @@ -898,15 +901,38 @@ slack_oauth_client_secret: slackOAuthClientSecret } }) + if (slackSigningSecret.trim()) { + await WorkspaceService.setWorkspaceSlackSigningSecret({ + workspace: $workspaceStore, + requestBody: { slack_signing_secret: slackSigningSecret } + }) + } // Redirect to OAuth flow - window.location.href = `/api/oauth/connect_slack?workspace=${$workspaceStore}` + window.location.href = `/api/oauth/connect_slack?workspace=${$workspaceStore}${slackAgents ? '&agents=true' : ''}` } catch (e) { sendUserToast('Failed to save Slack OAuth configuration', true) console.error(e) } } + async function saveSlackSigningSecret(): Promise { + if (!$workspaceStore) return + const secret = slackSigningSecret.trim() || null + try { + await WorkspaceService.setWorkspaceSlackSigningSecret({ + workspace: $workspaceStore, + requestBody: { slack_signing_secret: secret } + }) + slackSigningSecret = '' + slackSigningSecretSet = !!secret + sendUserToast(secret ? 'Signing secret saved' : 'Signing secret removed') + } catch (e) { + sendUserToast('Failed to save the signing secret', true) + console.error(e) + } + } + async function deleteSlackOAuthConfig(): Promise { if (!$workspaceStore) return @@ -924,6 +950,7 @@ slackOAuthClientId = '' slackOAuthClientSecret = '' slackOAuthConfigLoaded = false + slackSigningSecretSet = false await loadSettings() sendUserToast('Workspace Slack app deleted') } catch (e) { @@ -1748,7 +1775,7 @@ } }} onSelect={editSlackCommand} - connectHref="/api/oauth/connect_slack{slackAgentsScopes ? '?agents=true' : ''}" + connectHref="/api/oauth/connect_slack{slackAgents ? '?agents=true' : ''}" createScriptHref="/scripts/add?hub=hub%2F28071%2Fslack%2Fexample_of_responding_to_a_slack_command_slack" createFlowHref="/flows/add?hub=28" documentationLink="https://www.windmill.dev/docs/integrations/slack" @@ -1778,27 +1805,24 @@ {/snippet}
Use the Slack app configured at the instance level if you want to use - the same Slack app for all workspaces. Configure your Slack app here - if you want to use a specific Slack app for this workspace.
The instance app is shared by all workspaces. A workspace app is your + own, for this workspace only.
- {#if slackAppType === 'instance'} - - {#if slackAgentsStatus.current?.signing_secret_set === false} - - An instance admin needs to set the Slack app's signing secret as the - SLACK_SIGNING_SECRET environment variable. - - {/if} + + {#if slackAppType === 'instance' && slackAgentsStatus.current?.signing_secret_set === false} + + An instance admin needs to set the Slack app's signing secret in the + instance settings. + {/if}
{/if} @@ -1817,6 +1841,32 @@ >Client ID for the Slack app configured at the workspace level
+
+
Signing secret
+
+ + +
+
Lets Windmill check that requests come from Slack. Required for AI + agents; recommended for /windmill commands.
+
{:else if slackAppType === 'workspace'}
+ + -
- Create a Slack app at{' '} - - Slack API - . Set the redirect URI to:{' '} - - {window.location.origin}/oauth/callback_slack - -
+
@@ -1863,7 +1915,9 @@ size="xs" variant="accent" onclick={saveAndConnectSlack} - disabled={!slackOAuthClientId || !slackOAuthClientSecret} + disabled={!slackOAuthClientId || + !slackOAuthClientSecret || + (slackAgents && !slackSigningSecret.trim())} startIcon={{ icon: Slack }} btnClasses="w-fit" > From d6adac8b7579ad6c3df5caab9a735451c1ddd896 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Thu, 22 Oct 2026 16:17:05 +0200 Subject: [PATCH 039/101] fix: link a variable to its OAuth account only in the connect flow (#11361) * fix: only let an oauth account's creator or readers link it to a variable Co-Authored-By: Claude Opus 5.5 * fix: drop an oauth account link the caller may not hold instead of failing Co-Authored-By: Claude Opus 5.5 * test: cover relinking an oauth account through a variable update Co-Authored-By: Claude Opus 5.5 * test: cover a permitted relink through a variable update Co-Authored-By: Claude Opus 5.5 * fix: keep an oauth account's creator in step with the user's username Co-Authored-By: Claude Opus 5.5 * fix: follow a non-member superadmin's instance username on the OAuth accounts they created Co-Authored-By: Claude Opus 5.5 * refactor: link a variable to its OAuth account only in the connect flow The variable endpoints no longer take an account link from the caller. The connect flows create the token variable first and pass its path to create_account, which links it server-side. This replaces the creator check and the created_by bookkeeping, along with both migrations. Co-Authored-By: Claude Opus 5.5 * chore: keep the MCP secret variable test's formatting Co-Authored-By: Claude Opus 5.5 * fix: link the account to the token variable AppConnect created, even if the path is edited mid-save Co-Authored-By: Claude Opus 5.5 * fix: stop exporting the OAuth account a variable links, and regenerate the chat tool schema Co-Authored-By: Claude Opus 5.5 * chore: pin the EE refresh and linking checks Co-Authored-By: Claude Opus 5.5 * fix: delete AppConnect's token variable when linking its account fails, so Save can be retried Co-Authored-By: Claude Opus 5.5 * fix: keep the resource AppConnect fills when linking its account fails Deleting a variable also deletes the resource at its path, so the rollback is skipped when filling an existing resource. Co-Authored-By: Claude Opus 5.5 * refactor: create an OAuth token variable and its account in one request createAccount takes the variable and the store creates both in one transaction, so a connect is either fully saved or not at all. The connect flows make that single call instead of creating the variable and linking it afterwards. Co-Authored-By: Claude Opus 5.5 * fix: stop listing the ignored account input in the chat's write_variable instructions Co-Authored-By: Claude Opus 5.5 * chore: drop the account visibility helper the oauth refresh route no longer uses Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to da49c12e3006fc77de789277f1462a4d8d7d92ce This commit updates the EE repository reference after PR #829 was merged in windmill-ee-private. Previous ee-repo-ref: 58681a2e7eafb5689ed739cd2560fa0f5d82c3dc New ee-repo-ref: da49c12e3006fc77de789277f1462a4d8d7d92ce Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- ...e63767da94af0fcb6d660cd6fb0479b9a99d.json} | 7 +- ...281b7ed329ff0c9d1617747f4ccd6014720cf.json | 23 ---- ...514b9a9f2200e5a5db0a741697b28cd8b505f.json | 23 ---- backend/ee-repo-ref.txt | 2 +- .../tests/variables.rs | 62 +++++++++ backend/windmill-api/openapi.yaml | 6 +- backend/windmill-api/src/workspaces_export.rs | 6 +- .../windmill-store/src/oauth_refresh_oss.rs | 17 --- backend/windmill-store/src/variables.rs | 119 ++++++++++-------- .../src/lib/components/AppConnectInner.svelte | 47 ++++--- .../components/copilot/chat/global/core.ts | 2 +- .../copilot/chat/workspaceToolsZod.gen.ts | 2 +- .../src/lib/components/mcp/McpConnect.svelte | 24 ++-- .../mcp/McpServerOAuthConnect.svelte | 31 ++--- .../lib/components/mcp/secretVariable.test.ts | 3 +- .../src/lib/components/mcp/secretVariable.ts | 21 +++- 16 files changed, 203 insertions(+), 192 deletions(-) rename backend/.sqlx/{query-e910ae81fb98642e76644e9691157c3d02adce3ba55324375a2035231c640ac0.json => query-086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d.json} (53%) delete mode 100644 backend/.sqlx/query-7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf.json delete mode 100644 backend/.sqlx/query-c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f.json diff --git a/backend/.sqlx/query-e910ae81fb98642e76644e9691157c3d02adce3ba55324375a2035231c640ac0.json b/backend/.sqlx/query-086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d.json similarity index 53% rename from backend/.sqlx/query-e910ae81fb98642e76644e9691157c3d02adce3ba55324375a2035231c640ac0.json rename to backend/.sqlx/query-086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d.json index 8805e4ee22..e9183fe2d4 100644 --- a/backend/.sqlx/query-e910ae81fb98642e76644e9691157c3d02adce3ba55324375a2035231c640ac0.json +++ b/backend/.sqlx/query-086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d.json @@ -1,16 +1,17 @@ { "db_name": "PostgreSQL", - "query": "SELECT EXISTS (SELECT 1 FROM account WHERE workspace_id = $1 AND id = $2) AS \"exists!\"", + "query": "SELECT EXISTS(SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2 AND account = $3)", "describe": { "columns": [ { "ordinal": 0, - "name": "exists!", + "name": "exists", "type_info": "Bool" } ], "parameters": { "Left": [ + "Text", "Text", "Int4" ] @@ -19,5 +20,5 @@ null ] }, - "hash": "e910ae81fb98642e76644e9691157c3d02adce3ba55324375a2035231c640ac0" + "hash": "086866581c8f253a611d85cc9464e63767da94af0fcb6d660cd6fb0479b9a99d" } diff --git a/backend/.sqlx/query-7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf.json b/backend/.sqlx/query-7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf.json deleted file mode 100644 index b2101cc0d4..0000000000 --- a/backend/.sqlx/query-7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT EXISTS(SELECT 1 FROM variable WHERE account = $1 AND workspace_id = $2)", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exists", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [ - "Int4", - "Text" - ] - }, - "nullable": [ - null - ] - }, - "hash": "7aa589db3199d7f727cc69e63e1281b7ed329ff0c9d1617747f4ccd6014720cf" -} diff --git a/backend/.sqlx/query-c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f.json b/backend/.sqlx/query-c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f.json deleted file mode 100644 index 37025d99d8..0000000000 --- a/backend/.sqlx/query-c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT account FROM variable WHERE path = $1 AND workspace_id = $2", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "account", - "type_info": "Int4" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - true - ] - }, - "hash": "c925264b7b0fd44ea7ab01c9af1514b9a9f2200e5a5db0a741697b28cd8b505f" -} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 66b973f850..f6c4caccbe 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -c8d562aa9d75a7e99bf0ecd1ac224f532452a07e +da49c12e3006fc77de789277f1462a4d8d7d92ce diff --git a/backend/windmill-api-integration-tests/tests/variables.rs b/backend/windmill-api-integration-tests/tests/variables.rs index e5018f4f97..7332383936 100644 --- a/backend/windmill-api-integration-tests/tests/variables.rs +++ b/backend/windmill-api-integration-tests/tests/variables.rs @@ -338,3 +338,65 @@ async fn test_variables_are_cached(db: Pool) -> anyhow::Result<()> { Ok(()) } + +/// Reading a variable linked to an OAuth account refreshes through it and returns the fresh token, +/// so the variable endpoints must not let a caller choose the link. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_variable_endpoints_ignore_account_link(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}/api/w/test-workspace/variables"); + + let account: i32 = sqlx::query_scalar( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token) + VALUES ('test-workspace', 'github', now(), 'r') RETURNING id", + ) + .fetch_one(&db) + .await?; + let link = |path: &'static str| { + let db = db.clone(); + async move { + sqlx::query_scalar::<_, Option>( + "SELECT account FROM variable WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(path) + .fetch_one(&db) + .await + .unwrap() + } + }; + + let path = "u/test-user/oauth_probe"; + let resp = authed(client().post(format!("{base}/create"))) + .json( + &json!({ "path": path, "value": "t", "is_secret": true, "description": "", + "is_oauth": true, "account": account }), + ) + .send() + .await?; + assert_eq!(resp.status(), 201); + assert_eq!(link(path).await, None); + + let other: i32 = sqlx::query_scalar( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token) + VALUES ('test-workspace', 'github', now(), 'r') RETURNING id", + ) + .fetch_one(&db) + .await?; + sqlx::query( + "UPDATE variable SET account = $1 WHERE workspace_id = 'test-workspace' AND path = $2", + ) + .bind(account) + .bind(path) + .execute(&db) + .await?; + let resp = authed(client().post(variable_url(port, "update", path))) + .json(&json!({ "description": "d", "account": other })) + .send() + .await?; + assert_eq!(resp.status(), 200); + assert_eq!(link(path).await, Some(account)); + + Ok(()) +} diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index edbd4165d9..0118184af1 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -8894,6 +8894,9 @@ paths: items: type: string description: "OAuth scopes to use for token refresh. Overrides instance-level scopes." + variable: + $ref: "#/components/schemas/CreateVariable" + description: "The variable holding this account's access token. It is created with the account, in one transaction and with the same checks as createVariable, and linked to it so it refreshes through it." required: - refresh_token - expires_in @@ -32523,7 +32526,8 @@ components: description: The description of the variable account: type: integer - description: The account identifier + deprecated: true + description: Ignored. A variable is linked to an OAuth account only when `createAccount` creates both. is_oauth: type: boolean description: Whether the variable is an OAuth variable diff --git a/backend/windmill-api/src/workspaces_export.rs b/backend/windmill-api/src/workspaces_export.rs index 39227e49ee..87496fed45 100644 --- a/backend/windmill-api/src/workspaces_export.rs +++ b/backend/windmill-api/src/workspaces_export.rs @@ -968,11 +968,13 @@ pub(crate) async fn tarball_workspace( } if !skip_variables.unwrap_or(false) { + // `account` is left out: the variable endpoints ignore it, so a pushed spec carrying it + // would never match the variable it created and every sync would report it changed. let variables = sqlx::query_as::<_, ExportableListableVariable>(if !skip_secrets.unwrap_or(false) { - "SELECT workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" + "SELECT workspace_id, path, value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" } else { - "SELECT workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" + "SELECT workspace_id, path, value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" }) .bind(&w_id) .fetch_all(&mut *tx) diff --git a/backend/windmill-store/src/oauth_refresh_oss.rs b/backend/windmill-store/src/oauth_refresh_oss.rs index 17d49aae4f..3d55b05167 100644 --- a/backend/windmill-store/src/oauth_refresh_oss.rs +++ b/backend/windmill-store/src/oauth_refresh_oss.rs @@ -180,23 +180,6 @@ where Ok(token.access_token) } -/// Whether account `id` exists in `w_id`, read through the caller's user transaction. `account` -/// carries no RLS, so this gates nothing beyond the workspace the caller is already authorized -/// for: a refresh asked for by account id is scoped by that membership, not by ownership. -pub async fn account_visible( - user_conn: &mut sqlx::PgConnection, - w_id: &str, - id: i32, -) -> error::Result { - Ok(sqlx::query_scalar!( - "SELECT EXISTS (SELECT 1 FROM account WHERE workspace_id = $1 AND id = $2) AS \"exists!\"", - w_id, - id - ) - .fetch_one(user_conn) - .await?) -} - async fn current_token(db: &DB, w_id: &str, path: &str) -> error::Result { let value = sqlx::query_scalar!( "SELECT value FROM variable WHERE workspace_id = $1 AND path = $2", diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index 0b0660f967..6a4c34e7dd 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -594,6 +594,49 @@ async fn create_variable( Query(AlreadyEncrypted { already_encrypted }): Query, Json(variable): Json, ) -> Result<(StatusCode, String)> { + let path = variable.path.clone(); + create_variable_with_account( + authed, + &db, + user_db, + &webhook, + w_id, + variable, + already_encrypted.unwrap_or(false), + None, + ) + .await?; + Ok((StatusCode::CREATED, format!("variable {path} created"))) +} + +/// An OAuth account to create with the variable that holds its access token. +pub struct NewOAuthAccount { + pub client: String, + pub expires_in: i64, + pub refresh_token: Option, + pub grant_type: String, + pub cc_client_id: Option, + pub cc_client_secret: Option, + pub cc_token_url: Option, + pub mcp_server_url: Option, + pub scopes: Option>, +} + +/// Creates a variable and, given `account`, the OAuth account it refreshes through, linked in the +/// same transaction. Reading a linked variable refreshes through its account and hands the reader +/// the fresh token, so this is the only way a variable gets a link: `variable.account` is ignored. +/// Returns the new account's id. +pub async fn create_variable_with_account( + authed: ApiAuthed, + db: &DB, + user_db: UserDB, + webhook: &WebhookShared, + w_id: String, + variable: CreateVariable, + already_encrypted: bool, + account: Option, +) -> Result> { + let db = db.clone(); check_scopes(&authed, || format!("variables:write:{}", variable.path))?; check_proper_path(&variable.path)?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( @@ -625,7 +668,7 @@ async fn create_variable( let authed = maybe_refresh_folders(&variable.path, &w_id, authed, &db).await; check_path_conflict(&db, &w_id, &variable.path).await?; - let value = if variable.is_secret && !already_encrypted.unwrap_or(false) { + let value = if variable.is_secret && !already_encrypted { // A restored draft sends the `$encrypted:` marker as-is; decrypt it back // (validating against the workspace key) before the secret backend re-stores it. let plain = if variable.value.starts_with(ENCRYPTED_DRAFT_PREFIX) { @@ -646,6 +689,27 @@ async fn create_variable( let mut tx = user_db.begin(&authed).await?; + let account_id = match account { + Some(a) => Some( + sqlx::query_scalar!( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token, grant_type, cc_client_id, cc_client_secret, cc_token_url, mcp_server_url, scopes) VALUES ($1, $2, now() + ($3 || ' seconds')::interval, $4, $5, $6, $7, $8, $9, $10) RETURNING id", + &w_id, + a.client, + a.expires_in.to_string(), + a.refresh_token, + a.grant_type, + a.cc_client_id, + a.cc_client_secret, + a.cc_token_url, + a.mcp_server_url, + a.scopes.as_deref() + ) + .fetch_one(&mut *tx) + .await?, + ), + None => None, + }; + sqlx::query!( "INSERT INTO variable (workspace_id, path, value, is_secret, description, account, is_oauth, expires_at, labels, edited_by) @@ -655,7 +719,7 @@ async fn create_variable( value, variable.is_secret, variable.description, - variable.account, + account_id, variable.is_oauth.unwrap_or(false), variable.expires_at, variable.labels.as_deref() as Option<&[String]>, @@ -705,10 +769,7 @@ async fn create_variable( WebhookMessage::CreateVariable { workspace: w_id, path: variable.path.clone() }, ); - Ok(( - StatusCode::CREATED, - format!("variable {} created", variable.path), - )) + Ok(account_id) } async fn encrypt_value( @@ -1059,7 +1120,6 @@ struct EditVariable { value: Option, is_secret: Option, description: Option, - account: Option, labels: Option>, ws_specific: Option, } @@ -1156,11 +1216,6 @@ async fn update_variable( has_sql_updates = true; } - if let Some(account_id) = ns.account { - sqlb.set_str("account", account_id); - has_sql_updates = true; - } - if let Some(nbool) = ns.is_secret { let old_secret = sqlx::query_scalar!( "SELECT is_secret from variable WHERE path = $1 AND workspace_id = $2", @@ -1179,20 +1234,6 @@ async fn update_variable( has_sql_updates = true; } - // Get old account_id if we're updating the account field - let old_account_id = if ns.account.is_some() { - sqlx::query_scalar!( - "SELECT account FROM variable WHERE path = $1 AND workspace_id = $2", - &path, - &w_id - ) - .fetch_optional(&db) - .await? - .flatten() - } else { - None - }; - let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; if let Some(npath) = ns.path.clone() { @@ -1366,32 +1407,6 @@ async fn update_variable( ) .await?; - // Clean up old account if it's no longer referenced and different from new account - if let Some(old_acc_id) = old_account_id { - if ns.account.is_some() && ns.account != Some(old_acc_id) { - // Check if old account is still referenced by other variables or resources - let account_still_used = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM variable WHERE account = $1 AND workspace_id = $2)", - old_acc_id, - &w_id - ) - .fetch_one(&mut *tx) - .await? - .unwrap_or(true); - - if !account_still_used { - // Delete the orphaned account - sqlx::query!( - "DELETE FROM account WHERE id = $1 AND workspace_id = $2", - old_acc_id, - &w_id - ) - .execute(&mut *tx) - .await?; - } - } - } - tx.commit().await?; // Detect if this was a rename operation diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index 4dc05972ca..173de7e12b 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -939,9 +939,9 @@ args['realmId'] = responseExtra['realmId'] } - let account: number | undefined = undefined + let accountData: any = undefined if (valueToken?.expires_in != undefined) { - const accountData: any = { + accountData = { refresh_token: valueToken.refresh_token ?? '', expires_in: valueToken.expires_in, client: connectClient, @@ -970,13 +970,6 @@ accountData.cc_token_url = tokenUrl.trim() } } - - account = Number( - await OauthService.createAccount({ - workspace: effectiveWorkspace, - requestBody: accountData - }) - ) } // A copy: the form is still mounted and bound to `args` across the awaits below, and @@ -995,21 +988,27 @@ // OAuth flow: single secret variable for the token if (typeof value == 'string' && value != '' && !value.startsWith('$var:')) { savedVariableCount++ - await VariableService.createVariable({ - workspace: effectiveWorkspace, - requestBody: { - path, - value: value, - is_secret: true, - description: emptyString(description) - ? `OAuth token for ${resourceType}` - : description, - is_oauth: true, - account: account, - ws_specific: wsSpecific - } - }) - resourceValue['token'] = `$var:${path}` + const tokenVariable = { + path, + value: value, + is_secret: true, + description: emptyString(description) ? `OAuth token for ${resourceType}` : description, + is_oauth: true, + ws_specific: wsSpecific + } + if (accountData) { + // Creates the variable with the account it refreshes through, in one transaction. + await OauthService.createAccount({ + workspace: effectiveWorkspace, + requestBody: { ...accountData, variable: tokenVariable } + }) + } else { + await VariableService.createVariable({ + workspace: effectiveWorkspace, + requestBody: tokenVariable + }) + } + resourceValue['token'] = `$var:${tokenVariable.path}` } } else if (linkedSecrets.length === 1) { // Single secret: use the resource path as variable name (original behavior) diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index c832fbfc1f..03356a51f0 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -2854,7 +2854,7 @@ function getResourceInstructions(): string { - Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata. - A resource draft is a workspace item: \`{ type: 'resource', path, summary?, value, isDraft }\`. \`value\` is a CreateResource body: \`{ path, value, description?, resource_type, labels? }\` where the inner \`value\` is the resource type's data shape. - Reading a variable returns \`{ type: 'variable', path, summary?, isSecret, isDraft }\` — never its value, secret or not. \`isSecret\` tells you whether the value is encrypted. -- \`write_variable\` takes \`{ path, value?, is_secret?, description?, account?, is_oauth?, expires_at?, labels? }\`. Creating a variable needs \`value\` and \`is_secret\`; editing one needs only the fields you are changing. Omitting \`value\` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any \`value\` you did not get from the user destroys it. +- \`write_variable\` takes \`{ path, value?, is_secret?, description?, is_oauth?, expires_at?, labels? }\`. Creating a variable needs \`value\` and \`is_secret\`; editing one needs only the fields you are changing. Omitting \`value\` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any \`value\` you did not get from the user destroys it. - For secret fields in a resource value, create the variable with \`write_variable\` and \`is_secret: true\`, and deploy it before the resource (see "Secrets" in the reference below). - Reference formats inside resource values: \`$var:g/all/name\` (global), \`$var:u/user/name\` (user), \`$var:f/folder/name\` (folder). Reference another resource with \`$res:path/to/resource\`. The same strings are also how a resource or variable is passed as a run argument (see the run-argument rule in the resource reference below); what they are never valid as is a variable's own value. - Use \`search_resource_types\` to discover valid \`resource_type\` names and their JSON Schemas. Match the resource value to that schema. diff --git a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts index c6b03cee68..e4817e190c 100644 --- a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts +++ b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts @@ -488,7 +488,7 @@ export const variableRequestSchema = z.object({ "value": z.string().describe("The value of the variable"), "is_secret": z.boolean().describe("Whether the variable is a secret"), "description": z.string().describe("The description of the variable"), - "account": z.number().int().describe("The account identifier").optional(), + "account": z.number().int().describe("Ignored. A variable is linked to an OAuth account only when `createAccount` creates both.").optional(), "is_oauth": z.boolean().describe("Whether the variable is an OAuth variable").optional(), "expires_at": z.string().datetime({ offset: true }).describe("The expiration date of the variable").optional(), "labels": z.array(z.string()).optional(), diff --git a/frontend/src/lib/components/mcp/McpConnect.svelte b/frontend/src/lib/components/mcp/McpConnect.svelte index a8808aa052..5cf286be80 100644 --- a/frontend/src/lib/components/mcp/McpConnect.svelte +++ b/frontend/src/lib/components/mcp/McpConnect.svelte @@ -278,27 +278,21 @@ if (!t) return const { workspace, path } = t try { - let account: number | undefined = undefined - if (res?.expires_in != undefined) { - account = Number( - await OauthService.createAccount({ - workspace, - requestBody: { - refresh_token: res.refresh_token ?? '', - expires_in: res.expires_in, - client: t.client, - scopes: t.scopes - } - }) - ) - } await upsertSecretVariable({ workspace, path, value: res.access_token, resourcePath: path, isOauth: true, - account + account: + res?.expires_in != undefined + ? { + refresh_token: res.refresh_token ?? '', + expires_in: res.expires_in, + client: t.client, + scopes: t.scopes + } + : undefined }) await createMcpResource(t, `$var:${path}`) sendUserToast(`Connected ${t.label}`) diff --git a/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte b/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte index bafbf4b7b4..3d721d6882 100644 --- a/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte +++ b/frontend/src/lib/components/mcp/McpServerOAuthConnect.svelte @@ -1,10 +1,5 @@ + +
+ + {#if locked} + {@const current = connections?.find((c) => c.path === value)} +
+

+ The webhook is registered under this account. To use another one, create a new trigger. +

+ {#if current && canReconnect(current)} + + {/if} +
+ {/if} + {#if unusable} + + Saving acts as the account at {value}. Ask its owner for read access to it, or create a new + trigger with your own account. + + {/if} +
+ + + + diff --git a/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte b/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte new file mode 100644 index 0000000000..18c9428d76 --- /dev/null +++ b/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte @@ -0,0 +1,69 @@ + + +
+ {#if outcome === undefined} +
+ + Finishing the connection... +
+ {:else if outcome.ok} + + Saved as {outcome.path}. You can close this window. + + {:else} + {outcome.error} + {/if} +
diff --git a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte index 3246b12a4d..bf8fe0f7d1 100644 --- a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte @@ -6,8 +6,10 @@ validateCommonFields, getServiceConfig, getTemplatePath, - saveNativeTriggerFromCfg + saveNativeTriggerFromCfg, + setNativeConnectionContext } from './utils' + import NativeConnectionPicker from './NativeConnectionPicker.svelte' import { usedTriggerKinds } from '$lib/stores' import { emptyString, sendUserToast } from '$lib/utils' import { useEditRights, useTriggerLock } from '$lib/operatorWriteRights' @@ -125,6 +127,8 @@ let externalError = $state(undefined) let retryEdit = $state<(() => void) | undefined>(undefined) let enabled = $state(true) + let connectionPath = $state(undefined) + setNativeConnectionContext(() => connectionPath) export function openNew( nis_flow?: boolean, @@ -156,6 +160,7 @@ externalError = undefined retryEdit = undefined enabled = true + connectionPath = undefined } export function openRecreate(nativeTrigger: ExtendedNativeTrigger) { @@ -185,6 +190,7 @@ externalError = undefined retryEdit = undefined enabled = nativeTrigger.enabled + connectionPath = nativeTrigger.connection_path ?? undefined } export async function openEdit( @@ -219,6 +225,7 @@ initialScriptPath = '' summary = '' enabled = true + connectionPath = undefined try { const fullTrigger = await NativeTriggerService.getNativeTrigger({ @@ -236,6 +243,7 @@ externalData = fullTrigger.external_data externalError = fullTrigger.external_error ?? undefined enabled = fullTrigger.enabled + connectionPath = fullTrigger.connection_path ?? undefined // Apply default values if provided (for draft triggers) if (defaultValues) { @@ -263,7 +271,8 @@ script_path: scriptPath, is_flow: isFlow, service_config: serviceConfig, - summary: summary !== '' ? summary : undefined + summary: summary !== '' ? summary : undefined, + connection_path: connectionPath } } @@ -308,7 +317,8 @@ loadingForm || !can_write || !hasChanged || - loadError !== undefined + loadError !== undefined || + (isNew && !connectionPath) ) const saveCfg = $derived.by(getSaveCfg) @@ -557,6 +567,17 @@ {/if} + {#if !loadingConfig} +
+ +
+ {/if} + {#if loadingConfig}
@@ -564,34 +585,39 @@ Loading configuration from {serviceInfo?.serviceDisplayName}...
+ {:else if isNew && !connectionPath} + {:else if ServiceFormComponent} - + {#key connectionPath} + + {/key} {:else}
Failed to load service configuration component for {service}.
- Ensure your workspace has a connected {serviceInfo?.serviceDisplayName} integration. + Check that {serviceInfo?.serviceDisplayName} is configured in the native trigger settings.
diff --git a/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte b/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte index 27add7f797..c058a41560 100644 --- a/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte +++ b/frontend/src/lib/components/triggers/native/services/github/GitHubTriggerForm.svelte @@ -7,8 +7,10 @@ import { sendUserToast } from '$lib/toast' import { Loader2 } from 'lucide-svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useNativeConnection } from '../../utils' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { serviceConfig: Record @@ -66,7 +68,8 @@ loading = true try { repos = await NativeTriggerService.listGithubRepos({ - workspace: $operatingWorkspace + workspace: $operatingWorkspace, + connectionPath: connectionPath() }) } catch (err: any) { console.error('Failed to load GitHub repositories:', err) diff --git a/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte b/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte index f4c6d9894b..3252d7c6aa 100644 --- a/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte +++ b/frontend/src/lib/components/triggers/native/services/google/GoogleCalendarPicker.svelte @@ -6,8 +6,10 @@ import { Loader2, X, RefreshCw } from 'lucide-svelte' import GoogleCalendarIcon from '$lib/components/icons/GoogleCalendarIcon.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useNativeConnection } from '../../utils' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { calendarId: string @@ -26,7 +28,8 @@ loading = true try { calendars = await NativeTriggerService.listGoogleCalendars({ - workspace: $operatingWorkspace + workspace: $operatingWorkspace, + connectionPath: connectionPath() }) if (calendarId && !calendarName) { const found = calendars.find((c) => c.id === calendarId) diff --git a/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte b/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte index 597eb7d514..26e82dbdde 100644 --- a/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte +++ b/frontend/src/lib/components/triggers/native/services/google/GoogleDrivePicker.svelte @@ -9,8 +9,10 @@ import { Debounced, watch } from 'runed' import { untrack } from 'svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useNativeConnection } from '../../utils' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { resourceId: string @@ -53,6 +55,7 @@ try { const params: Parameters[0] = { workspace: $operatingWorkspace, + connectionPath: connectionPath(), pageToken } @@ -98,7 +101,8 @@ try { sharedDrives = await NativeTriggerService.listGoogleSharedDrives({ - workspace: $operatingWorkspace + workspace: $operatingWorkspace, + connectionPath: connectionPath() }) } catch (err: any) { sendUserToast(`Failed to load shared drives: ${err.body || err.message}`, true) diff --git a/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte b/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte index 780ccde9e8..d4f01478ef 100644 --- a/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte +++ b/frontend/src/lib/components/triggers/native/services/nextcloud/NextcloudTriggerForm.svelte @@ -6,10 +6,11 @@ import SchemaForm from '$lib/components/SchemaForm.svelte' import Section from '$lib/components/Section.svelte' import { Loader2 } from 'lucide-svelte' - import { getNextcloudSchema } from '../../utils' + import { getNextcloudSchema, useNativeConnection } from '../../utils' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() + const connectionPath = useNativeConnection() interface Props { serviceConfig: Record @@ -49,7 +50,8 @@ eventsError = undefined try { const events = await NativeTriggerService.listNextCloudEvents({ - workspace: $operatingWorkspace! + workspace: $operatingWorkspace!, + connectionPath: connectionPath() }) availableEvents = events serviceSchema = getNextcloudSchema(events) @@ -116,16 +118,14 @@ {#if eventsError}
Could not load the available events: {eventsError}
{:else} -
No events available. Please ensure your workspace has a connected Nextcloud integration.
+
No events available. Check that the selected Nextcloud account can reach the server.
{/if}
-
@@ -140,8 +140,7 @@ /> {:else}
- Please ensure Nextcloud workspace integration is connected to load available configuration - options. + Select a Nextcloud account to load the available configuration options.
{/if} diff --git a/frontend/src/lib/components/triggers/native/utils.ts b/frontend/src/lib/components/triggers/native/utils.ts index b411429d74..5d0a7f0fca 100644 --- a/frontend/src/lib/components/triggers/native/utils.ts +++ b/frontend/src/lib/components/triggers/native/utils.ts @@ -2,11 +2,97 @@ import type { NativeServiceName, NativeTrigger, NativeTriggerData } from '$lib/g import { isCloudHosted } from '$lib/cloud' import { NativeTriggerService, WorkspaceIntegrationService } from '$lib/gen' import { get, type Writable } from 'svelte/store' +import { getContext, setContext } from 'svelte' import { sendUserToast } from '$lib/toast' +const CONNECTION_CONTEXT = Symbol('nativeTriggerConnection') + +/** Makes the connection a trigger editor acts through available to the pickers of its form. */ +export function setNativeConnectionContext(connectionPath: () => string | undefined) { + setContext(CONNECTION_CONTEXT, connectionPath) +} + +/** The connection the service pickers browse through; undefined lets the server pick. */ +export function useNativeConnection(): () => string | undefined { + return getContext<(() => string | undefined) | undefined>(CONNECTION_CONTEXT) ?? (() => undefined) +} + +const CONNECT_MESSAGE = 'native_trigger_oauth' + +/** Turns the resource connect drawer into the connect step of a native trigger account. */ +export type NativeConnect = { + title: string + defaultName: string + /** Rejects when the connection was not saved; the drawer then stays open on the path. */ + connect: (path: string) => Promise +} + +export type NativeOAuthMessage = + | { type: typeof CONNECT_MESSAGE; ok: true; path: string } + | { type: typeof CONNECT_MESSAGE; ok: false; error: string } + +/** The page the provider redirects to, as registered on the workspace's OAuth apps. */ +export function nativeOAuthRedirectUri(service: NativeServiceName): string { + return `${window.location.origin}/workspace_settings?tab=native_triggers&service=${service}` +} + +/** Hands the outcome of a connect popup back to the page that opened it. */ +export function postNativeOAuthResult( + result: { ok: true; path: string } | { ok: false; error: string } +) { + const message = { type: CONNECT_MESSAGE, ...result } as NativeOAuthMessage + window.opener?.postMessage(message, window.location.origin) +} + +/** + * Connect an account in a popup and resolve with the path of the saved connection. The + * connection is saved at `resourcePath`, or at the caller's default path when omitted. + */ +export async function connectNativeAccount( + workspace: string, + service: NativeServiceName, + resourcePath?: string +): Promise { + const authUrl = await WorkspaceIntegrationService.generateNativeTriggerServiceConnectUrl({ + workspace, + serviceName: service, + requestBody: { redirect_uri: nativeOAuthRedirectUri(service), resource_path: resourcePath } + }) + const popup = window.open(authUrl, '_blank', 'popup,width=600,height=750') + if (!popup) { + throw new Error('The connection window was blocked. Allow popups for this site and retry.') + } + return new Promise((resolve, reject) => { + const onMessage = (event: MessageEvent) => { + if (event.origin !== window.location.origin || event.data?.type !== CONNECT_MESSAGE) return + cleanup() + if (event.data.ok) resolve(event.data.path) + else reject(new Error(event.data.error)) + } + // The callback page posts its result and then closes itself, so a closed window may still + // have a message in flight: give it a moment before treating the close as a cancel. + const closedPoll = setInterval(() => { + if (popup.closed) { + clearInterval(closedPoll) + setTimeout(() => { + cleanup() + reject(new Error('The connection window was closed before finishing')) + }, 1000) + } + }, 500) + function cleanup() { + window.removeEventListener('message', onMessage) + clearInterval(closedPoll) + } + window.addEventListener('message', onMessage) + }) +} + export interface NativeTriggerConfig { readonly serviceDisplayName: string readonly serviceKey: NativeServiceName + /** The type of the resource a connection is saved as. */ + readonly resourceType: string readonly supportsSync: boolean readonly isCloudCompatible: boolean readonly templates?: { @@ -19,6 +105,7 @@ export const NATIVE_TRIGGER_SERVICES: Record + import type { Snippet } from 'svelte' import { sendUserToast } from '$lib/utils' import { Button, Alert } from '$lib/components/common' - import Label from '$lib/components/Label.svelte' + import Modal from '$lib/components/common/modal/Modal.svelte' + import TextInput from '$lib/components/text_input/TextInput.svelte' import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte' - import { Save, ExternalLink } from 'lucide-svelte' + import { ExternalLink } from 'lucide-svelte' interface Props { + open: boolean serviceName: string serviceDisplayName: string existingConfig?: { @@ -16,178 +19,147 @@ redirectUri: string onConfigSaved: (oauthData: any) => Promise requiresBaseUrl?: boolean - baseUrlLabel?: string baseUrlPlaceholder?: string baseUrlSettingsPath?: string clientIdPlaceholder?: string clientSecretPlaceholder?: string setupInstructions?: string[] + /** Shown above the form, for what the service needs before it can be connected. */ + requirements?: Snippet } let { + open = $bindable(), serviceName, serviceDisplayName, existingConfig, onConfigSaved, redirectUri, requiresBaseUrl = true, - baseUrlLabel = `${serviceDisplayName} base URL`, baseUrlPlaceholder = `https://your-${serviceName}.example.com`, baseUrlSettingsPath = '/settings/admin/security', clientIdPlaceholder = `Generated by ${serviceDisplayName} OAuth app`, clientSecretPlaceholder = `Generated by ${serviceDisplayName} OAuth app`, - setupInstructions + setupInstructions, + requirements }: Props = $props() let saving = $state(false) let clientId = $state('') let clientSecret = $state('') let baseUrl = $state('') + $effect(() => { - if (existingConfig) { - clientId = existingConfig.client_id - clientSecret = existingConfig.client_secret - baseUrl = existingConfig.base_url + if (open) { + clientId = existingConfig?.client_id ?? '' + clientSecret = existingConfig?.client_secret ?? '' + baseUrl = existingConfig?.base_url ?? '' } }) - let canSave = $derived( - !saving && - !!clientId.trim() && - !!clientSecret.trim() && - (!requiresBaseUrl || !!baseUrl.trim()) + const baseUrlValid = $derived.by(() => { + try { + return ['http:', 'https:'].includes(new URL(baseUrl.trim()).protocol) + } catch { + return false + } + }) + + const canSave = $derived( + !saving && !!clientId.trim() && !!clientSecret.trim() && (!requiresBaseUrl || baseUrlValid) ) - async function saveConfig() { - if (!canSave) { - sendUserToast('Please fill in all required fields', true) - return - } - + async function save() { + if (!canSave) return saving = true try { - const oauthData: Record = { + await onConfigSaved({ client_id: clientId.trim(), client_secret: clientSecret.trim(), base_url: requiresBaseUrl ? baseUrl.trim().replace(/\/+$/, '') : '', redirect_uri: redirectUri.trim() - } - - await onConfigSaved(oauthData) - resetForm() + }) } catch (err: any) { - sendUserToast(`Failed to configure OAuth client: ${err.message}`, true) + sendUserToast(`Failed to save the OAuth app: ${err.message}`, true) } finally { saving = false } } - - function resetForm() { - clientId = '' - clientSecret = '' - } - - -
-
-

{serviceDisplayName} OAuth Client Configuration

-
+ +
+ {@render requirements?.()} - {#if !existingConfig} - -

- Before you can connect to {serviceDisplayName}, you need to configure an OAuth client. -

- {#if setupInstructions} -
    + {#if !existingConfig && setupInstructions} + +
      {#each setupInstructions as instruction}
    1. {@html instruction}
    2. {/each}
    - {/if} -
    - {/if} + + {/if} -
    -
    - {#if requiresBaseUrl} -
    -
    + {#snippet actions()} + + {/snippet} + diff --git a/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte b/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte index 622a9620a4..e1b8672e03 100644 --- a/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte +++ b/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte @@ -4,22 +4,25 @@ import { Button, Alert } from '$lib/components/common' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte' - import { Check, X, ExternalLink, Cog, Plug } from 'lucide-svelte' + import { Check, ExternalLink, KeyRound, Pencil, Trash2 } from 'lucide-svelte' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import type { Item } from '$lib/utils' import NextcloudIcon from '$lib/components/icons/NextcloudIcon.svelte' import GithubIcon from '$lib/components/icons/GithubIcon.svelte' import GoogleIcon from '$lib/components/icons/GoogleIcon.svelte' - import { WorkspaceIntegrationService, type NativeServiceName } from '$lib/gen' - import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte' + import { + WorkspaceIntegrationService, + type NativeServiceName, + type NativeTriggerConnection + } from '$lib/gen' import OAuthClientConfig from './OAuthClientConfig.svelte' import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte' import { createAsyncConfirmationModal } from '../common/confirmationModal/asyncConfirmationModal.svelte' - import Path from '$lib/components/Path.svelte' - import { page } from '$app/state' - import { goto } from '$app/navigation' + import NativeConnectionPicker from '$lib/components/triggers/native/NativeConnectionPicker.svelte' + import { nativeOAuthRedirectUri } from '$lib/components/triggers/native/utils' interface WorkspaceIntegration { service_name: string - resource_path?: string oauth_data: { client_id: string client_secret: string @@ -44,7 +47,7 @@ nextcloud: { name: 'nextcloud', displayName: 'Nextcloud', - description: 'Connect to Nextcloud for file operations and webhook triggers', + description: 'File events', icon: NextcloudIcon, docsUrl: 'https://www.windmill.dev/docs/integrations/nextcloud', setupInstructions: [ @@ -56,7 +59,7 @@ google: { name: 'google', displayName: 'Google', - description: 'Connect to Google for Drive and Calendar triggers', + description: 'Drive and Calendar changes', icon: GoogleIcon, docsUrl: 'https://www.windmill.dev/docs/core_concepts/native_triggers#google-triggers', requiresBaseUrl: false, @@ -73,7 +76,7 @@ github: { name: 'github', displayName: 'GitHub', - description: 'Connect to GitHub for repository webhook triggers', + description: 'Repository events', icon: GithubIcon, docsUrl: 'https://www.windmill.dev/docs/core_concepts/native_triggers#github-triggers', requiresBaseUrl: false, @@ -89,18 +92,13 @@ } let integrations = $state([]) + let connections = $state>({}) let loading = $state(false) - let connecting = $state(null) - let showingConfig = $state(null) + // The service whose OAuth app dialog is open. + let configOpen = $state>( + Object.fromEntries(Object.keys(supportedServices).map((s) => [s, false])) + ) let instanceSharingAvailable = $state>({}) - let pendingCallback = $state<{ - serviceName: NativeServiceName - code: string - state: string - workspace: string - } | null>(null) - let resourcePath = $state(undefined) - let pathError = $state(undefined) let confirmationModal = createAsyncConfirmationModal() async function loadIntegrations() { @@ -113,9 +111,9 @@ }) integrations = response.map((item) => ({ service_name: item.service_name, - resource_path: item.resource_path ?? undefined, oauth_data: item.oauth_data || null })) + await Promise.all(Object.keys(supportedServices).map(loadConnections)) } catch (err: any) { console.error('Failed to load workspace integrations:', err) sendUserToast(`Failed to load integrations: ${err.message}`, true) @@ -124,59 +122,132 @@ } } + async function loadConnections(serviceName: string) { + if (!$workspaceStore) return + try { + connections[serviceName] = await WorkspaceIntegrationService.listNativeTriggerConnections({ + workspace: $workspaceStore, + serviceName: serviceName as NativeServiceName + }) + } catch { + connections[serviceName] = [] + } + } + async function deleteIntegration(serviceName: string) { if (!$workspaceStore) return const displayName = supportedServices[serviceName]?.displayName ?? serviceName const confirmed = await confirmationModal.ask({ - title: `Disconnect ${displayName}?`, - confirmationText: 'Disconnect', - children: `This will delete all ${displayName} triggers associated with this integration. This action cannot be undone.` + title: `Remove the ${displayName} configuration?`, + confirmationText: 'Remove', + children: `This deletes the workspace's ${displayName} OAuth app, every ${displayName} account connected through it and all ${displayName} triggers, which stop receiving events. This action cannot be undone.` }) if (!confirmed) return try { await WorkspaceIntegrationService.deleteNativeTriggerService({ workspace: $workspaceStore, - serviceName: serviceName as any + serviceName: serviceName as NativeServiceName }) - sendUserToast(`${displayName} disconnected successfully`) + sendUserToast(`${displayName} integration removed`) loadIntegrations() } catch (err: any) { - sendUserToast(`Failed to disconnect ${displayName}: ${err.message}`, true) + sendUserToast(`Failed to remove ${displayName}: ${err.body ?? err.message}`, true) } } - async function connectService(serviceName: string, redirectUri: string) { - if (!$workspaceStore) return + async function setWorkspaceConnection( + serviceName: string, + path: string | undefined + ): Promise { + if (!$workspaceStore) return false - connecting = serviceName - try { - const auth_url = await WorkspaceIntegrationService.generateNativeTriggerServiceConnectUrl({ - workspace: $workspaceStore, - serviceName: serviceName as any, - requestBody: { redirect_uri: redirectUri } + const displayName = supportedServices[serviceName]?.displayName ?? serviceName + if (path) { + const owner = connections[serviceName]?.find((c) => c.path === path)?.owner + const account = owner ? `this account, connected by ${owner}` : 'this account' + const browsable: string | undefined = ( + { google: 'its Drive files and calendars', github: 'its repositories' } as Record< + string, + string + > + )[serviceName] + const browse = browsable ? `, and browse ${browsable} in the trigger editor` : '' + const confirmed = await confirmationModal.ask({ + title: `Share ${path} with the workspace?`, + confirmationText: 'Share', + children: `Every member will be able to create and edit ${displayName} triggers that act as ${account}${browse}. They will not see its token. It replaces any connection shared before.` }) - - if (auth_url) { - window.location.href = auth_url - } - } catch (err: any) { - sendUserToast( - `Failed to connect ${supportedServices[serviceName]?.displayName}: ${err.message}`, - true - ) - connecting = null + if (!confirmed) return false + } else { + const confirmed = await confirmationModal.ask({ + title: 'Stop sharing this account?', + confirmationText: 'Stop sharing', + children: `Members will no longer be able to create or edit ${displayName} triggers through it, unless they can read it. Its triggers keep running.` + }) + if (!confirmed) return false } + + try { + await WorkspaceIntegrationService.setNativeTriggerWorkspaceConnection({ + workspace: $workspaceStore, + serviceName: serviceName as NativeServiceName, + requestBody: { path: path ?? null } + }) + sendUserToast(path ? `${path} is now the shared account` : 'Stopped sharing') + await loadConnections(serviceName) + return true + } catch (err: any) { + sendUserToast(`Failed to update the shared account: ${err.body ?? err.message}`, true) + return false + } + } + + function docsItem(config: ServiceConfig): Item[] { + return config.docsUrl + ? [{ displayName: 'Docs', icon: ExternalLink, href: config.docsUrl, hrefTarget: '_blank' }] + : [] + } + + async function openConfig(serviceName: string, leavingInstanceApp: boolean) { + const displayName = supportedServices[serviceName]?.displayName ?? serviceName + // A refresh token only works with the OAuth app that issued it. + if (leavingInstanceApp && (connections[serviceName]?.length ?? 0) > 0) { + const confirmed = await confirmationModal.ask({ + title: `Use your own ${displayName} OAuth app?`, + confirmationText: 'Continue', + children: `Accounts connected with the instance app will have to be connected again, at the same path, before their triggers work again.` + }) + if (!confirmed) return + } + configOpen[serviceName] = true } async function createOrUpdateIntegration(serviceName: string, oauthData: any) { if (!$workspaceStore) return + const displayName = supportedServices[serviceName]?.displayName ?? serviceName + const current = getIntegrationByService(serviceName)?.oauth_data + // Leaving the instance app is confirmed when the form opens; this covers editing our own app. + const clientChanges = + !!current?.client_id && + !current.instance_shared && + current.client_id !== (oauthData.client_id ?? '') + // A refresh token only works with the OAuth app that issued it. + if (clientChanges && (connections[serviceName]?.length ?? 0) > 0) { + const confirmed = await confirmationModal.ask({ + title: `Change the ${displayName} OAuth app?`, + confirmationText: 'Change', + children: `Accounts connected with the current app must be connected again, at the same path, before their triggers work again.` + }) + if (!confirmed) return + } + try { await WorkspaceIntegrationService.createNativeTriggerService({ workspace: $workspaceStore, - serviceName: serviceName as any, + serviceName: serviceName as NativeServiceName, requestBody: oauthData }) sendUserToast( @@ -207,33 +278,9 @@ } } - async function connectWithInstanceCredentials(serviceName: string) { - if (!$workspaceStore) return - - connecting = serviceName - try { - const redirectUri = getRedirectUri(serviceName) - const auth_url = await WorkspaceIntegrationService.generateInstanceConnectUrl({ - workspace: $workspaceStore, - serviceName: serviceName as NativeServiceName, - requestBody: { redirect_uri: redirectUri } - }) - - if (auth_url) { - window.location.href = auth_url - } - } catch (err: any) { - sendUserToast( - `Failed to connect ${supportedServices[serviceName]?.displayName}: ${err.message}`, - true - ) - connecting = null - } - } - - function isConfigured(integration: WorkspaceIntegration): boolean { - if (integration.oauth_data === null) return false - if (integration.oauth_data.instance_shared) return true + /** Whether the workspace has its own OAuth app for the service. */ + function hasWorkspaceApp(integration: WorkspaceIntegration | null): boolean { + if (!integration?.oauth_data || integration.oauth_data.instance_shared) return false const serviceConfig = supportedServices[integration.service_name] const needsBaseUrl = serviceConfig?.requiresBaseUrl !== false return ( @@ -243,82 +290,10 @@ ) } - function isConnected(integration: WorkspaceIntegration): boolean { - if (integration.oauth_data?.instance_shared) { - return !!integration.resource_path - } - return isConfigured(integration) && !!integration.resource_path - } - function getIntegrationByService(serviceName: string): WorkspaceIntegration | null { return integrations.find((integration) => integration.service_name === serviceName) || null } - function handleOAuthCallback( - workspace: string, - serviceName: NativeServiceName, - code: string, - state: string - ) { - // Phase 1: store callback params and clean URL — don't call backend yet - pendingCallback = { serviceName, code, state, workspace } - - // Pre-populate resource path from existing integration (for reconnect) - const integration = getIntegrationByService(serviceName) - resourcePath = integration?.resource_path ?? undefined - - const url = new URL(page.url) - url.searchParams.delete('code') - url.searchParams.delete('state') - url.searchParams.delete('service') - goto(url.toString(), { replaceState: true, noScroll: true, keepFocus: true }) - } - - async function finalizePendingCallback() { - if (!pendingCallback) return - - const { serviceName, code, state, workspace } = pendingCallback - try { - const redirectUri = getRedirectUri(serviceName) - await WorkspaceIntegrationService.nativeTriggerServiceCallback({ - serviceName, - workspace, - requestBody: { - code, - state, - redirect_uri: redirectUri, - resource_path: resourcePath - } - }) - sendUserToast(`${supportedServices[serviceName]?.displayName} connected successfully!`) - await loadIntegrations() - } catch (err: any) { - sendUserToast(`Failed to complete OAuth connection: ${err.message}`, true) - } finally { - pendingCallback = null - resourcePath = undefined - pathError = undefined - } - } - - $effect(() => { - if ( - page.url.searchParams.has('code') && - page.url.searchParams.has('state') && - page.url.searchParams.has('service') && - $workspaceStore - ) { - const service = page.url.searchParams.get('service')! as NativeServiceName - const code = page.url.searchParams.get('code')! - const state = page.url.searchParams.get('state')! - handleOAuthCallback($workspaceStore, service, code, state) - } - }) - - function getRedirectUri(serviceName: string): string { - return `${window.location.origin}/workspace_settings?tab=native_triggers&service=${serviceName}` - } - $effect(() => { if ($workspaceStore) { loadIntegrations() @@ -329,49 +304,12 @@
    - {#if pendingCallback} - {@const serviceName = pendingCallback.serviceName} - {@const config = supportedServices[serviceName]} -
    -
    - Save {config?.displayName ?? serviceName} credentials as resource -
    -
    - Choose where to save the OAuth resource. This resource will store the access token for the - integration. -
    - -
    - - -
    -
    - {:else if loading} + {#if loading}
    {#each new Array(3) as _} @@ -381,164 +319,144 @@
    {#each Object.entries(supportedServices) as [serviceName, config]} {@const integration = getIntegrationByService(serviceName)} - {@const isConnecting = connecting === serviceName} - {@const isOAuthConfigured = integration && isConfigured(integration)} - {@const isServiceConnected = integration && isConnected(integration)} - {@const isShowingConfig = showingConfig === serviceName} + {@const workspaceApp = hasWorkspaceApp(integration)} + {@const usesInstanceApp = !workspaceApp && instanceSharingAvailable[serviceName]} + {@const workspaceConnection = connections[serviceName]?.find((c) => c.workspace)?.path} -
    -
    -
    -
    - -
    -
    -
    {config.displayName}
    -
    {config.description}
    -
    -
    - -
    - {#if isServiceConnected} -
    - - Connected -
    - - - {:else if isOAuthConfigured} - - - {:else if instanceSharingAvailable[serviceName]} - - {:else} - - {/if} - - {#if config.docsUrl} - - {/if} +
    +
    + +
    +
    {config.displayName}
    +
    {config.description}
    + {#if workspaceApp || usesInstanceApp} + openConfig(serviceName, false) + }, + ...docsItem(config), + { + displayName: 'Remove configuration', + icon: Trash2, + type: 'delete', + action: () => deleteIntegration(serviceName) + } + ] + : [ + { + displayName: 'Use a workspace OAuth app', + icon: KeyRound, + action: () => openConfig(serviceName, true) + }, + ...docsItem(config) + ]} + /> + {:else} + + {/if}
    - {#if instanceSharingAvailable[serviceName] && !isOAuthConfigured} -
    - -

    - Your instance admin has configured Google OAuth for native triggers. Before - connecting, ensure the following redirect URI has been added to the - Google Cloud Console by the instance admin: -

    - + {#if !workspaceApp && !usesInstanceApp} +
    + Not configured. Members can't create {config.displayName} triggers yet. +
    + {:else} +
    + + + {workspaceApp ? 'Configured in workspace.' : 'Configured by instance.'} + Members connect their own {config.displayName} account when they create a trigger. + +
    + + {#if serviceName === 'nextcloud' && !workspaceConnection} + + We recommend connecting one below and sharing it with the workspace. + {/if} + +
    +
    Shared account
    +
    + Members can create triggers as this account and pick from what it can access, + without seeing its token. +
    +
    + + {#key workspaceConnection} + setWorkspaceConnection(serviceName, path)} + onConnectionsChange={() => loadConnections(serviceName)} + /> + {/key} +
    {/if} - {#if isShowingConfig} -
    + { + await createOrUpdateIntegration(serviceName, oauthData) + configOpen[serviceName] = false + }} + > + {#snippet requirements()} {#if serviceName === 'nextcloud'} - -

    Nextcloud integration requires:

    -
      + +
      • Nextcloud 33 or later.
      • The - Windmill integration app - to be installed on your Nextcloud instance. + class="underline">Windmill integration app installed.
      • - Pretty URLs - - to be enabled on your Nextcloud instance. + class="underline">Pretty URLs enabled.
      {/if} - { - await createOrUpdateIntegration(serviceName, oauthData) - showingConfig = null - }} - /> -
    - {/if} + {/snippet} +
    {/each}
    - - {#if integrations.length === 0} - - Connect to external services above to enable native triggers for your workspace. - - {/if} {/if}
    diff --git a/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte b/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte index a428a91e7c..769cc2d5fb 100644 --- a/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/native_triggers/[service_name]/+page.svelte @@ -110,7 +110,7 @@ serviceAvailable = await isServiceAvailable(serviceName, $workspaceStore) if (!serviceAvailable) { sendUserToast( - `${serviceName} integration not available, set it in the workspace settings`, + `${serviceConfig.serviceDisplayName} isn't configured in this workspace`, true ) } @@ -145,7 +145,10 @@ } if (!serviceAvailable) { - sendUserToast('Cannot sync triggers: workspace integration not connected', true) + sendUserToast( + `Cannot sync: ${serviceConfig.serviceDisplayName} isn't configured in this workspace`, + true + ) return } @@ -159,17 +162,7 @@ loadTriggers() } catch (err: any) { const errorMessage = err.body || err.message - if ( - errorMessage.includes('workspace integration') || - errorMessage.includes('not connected') - ) { - sendUserToast( - `Cannot sync: ${serviceConfig.serviceDisplayName} workspace integration not connected. Please connect it in workspace settings.`, - true - ) - } else { - sendUserToast(`Failed to sync triggers: ${errorMessage}`, true) - } + sendUserToast(`Failed to sync triggers: ${errorMessage}`, true) } } @@ -237,8 +230,7 @@ type="warning" >
    - The workspace doesn't have a {serviceConfig?.serviceDisplayName || serviceName} integration - connected + {serviceConfig?.serviceDisplayName || serviceName} isn't configured in this workspace yet.
    - {/snippet} - {#snippet content({ close })} -
    - Add a member - + + +
    + {/snippet} + + {/if} +
    {/snippet}
    {#if can_write && restricted} @@ -480,19 +532,31 @@ {/if} {#if loaded} - + + = MANY_ROWS ? 'h-80' : ''} + > Name - Role - Actions + + Role + + + Actions + - {#each draft.members as member, idx (member.member_name)} + {#each shownMembers as member (member.member_name)} - {member.member_name} + + {member.member_name} + {#if can_write && !restricted} @@ -501,7 +565,7 @@ disabled={isFixedCreatorRow(member.member_name)} selected={member.role} on:selected={(e) => { - draft.members[idx].role = e.detail + member.role = e.detail }} > {#snippet children({ item })} @@ -559,6 +623,13 @@ {/each} + {#if memberQuery && shownMembers.length === 0} + + + No one matches “{memberSearch.trim()}” + + + {/if} {:else} @@ -573,18 +644,45 @@ {#if instance_group?.emails} From 15b0b278775b95f32451e8409cae19b18ae55dac Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:12:20 +0200 Subject: [PATCH 044/101] chore: bump windmill-utils-internal to 1.8.3 and drop its workarounds (#11942) * chore: bump windmill-utils-internal to 1.8.3 and drop frontend workarounds * chore: resolve windmill-utils-internal 1.8.3 in the frontend lockfile --- cli/windmill-utils-internal/package-lock.json | 4 +- cli/windmill-utils-internal/package.json | 2 +- cli/windmill-utils-internal/src/deploy.ts | 6 +- .../src/inline-scripts/replacer.ts | 2 +- .../src/path-utils/path-assigner.ts | 2 +- frontend/package-lock.json | 8 +- frontend/package.json | 2 +- .../src/lib/utils_workspace_deploy.test.ts | 4 +- frontend/src/lib/utils_workspace_deploy.ts | 107 +++--------------- 9 files changed, 35 insertions(+), 102 deletions(-) diff --git a/cli/windmill-utils-internal/package-lock.json b/cli/windmill-utils-internal/package-lock.json index a2fb09f3dc..b9508332f0 100644 --- a/cli/windmill-utils-internal/package-lock.json +++ b/cli/windmill-utils-internal/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-utils-internal", - "version": "1.7.0", + "version": "1.8.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-utils-internal", - "version": "1.7.0", + "version": "1.8.3", "license": "Apache 2.0", "devDependencies": { "@types/node": "^24.2.0", diff --git a/cli/windmill-utils-internal/package.json b/cli/windmill-utils-internal/package.json index 525bb0fc0b..cf4138e6fc 100644 --- a/cli/windmill-utils-internal/package.json +++ b/cli/windmill-utils-internal/package.json @@ -1,6 +1,6 @@ { "name": "windmill-utils-internal", - "version": "1.8.2", + "version": "1.8.3", "description": "Internal utility functions for Windmill", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index d73cb3562c..b2c11253af 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -926,7 +926,11 @@ export async function getItemValue( path, decryptSecret: true, }); - return variable.value; + return { + value: variable.value, + is_secret: variable.is_secret, + description: variable.description, + }; } else if (kind === "resource") { const resource = await provider.getResource({ workspace, path }); // Each workspace resolves its own agent identity, which a deploy never copies. diff --git a/cli/windmill-utils-internal/src/inline-scripts/replacer.ts b/cli/windmill-utils-internal/src/inline-scripts/replacer.ts index d926467b86..b6ed4a4376 100644 --- a/cli/windmill-utils-internal/src/inline-scripts/replacer.ts +++ b/cli/windmill-utils-internal/src/inline-scripts/replacer.ts @@ -190,7 +190,7 @@ export async function replacePathScriptsWithLocal( } const localScript = await scriptReader(toolValue.path); if (localScript) { - (tool as AiAgent["tools"][number]).value = { + (tool as NonNullable[number]).value = { tool_type: "flowmodule", type: "rawscript", content: localScript.content, diff --git a/cli/windmill-utils-internal/src/path-utils/path-assigner.ts b/cli/windmill-utils-internal/src/path-utils/path-assigner.ts index 6aaeea4db1..c718e64e0c 100644 --- a/cli/windmill-utils-internal/src/path-utils/path-assigner.ts +++ b/cli/windmill-utils-internal/src/path-utils/path-assigner.ts @@ -5,7 +5,7 @@ const INLINE_SCRIPT_PREFIX = "inline_script"; /** * Union type of all supported programming languages in Windmill */ -export type SupportedLanguage = RawScript["language"] | "frontend" | "bunnative" | "oracledb" | "rust" | "csharp" | "nu" | "ansible" | "java" | "duckdb"; +export type SupportedLanguage = RawScript["language"] | "frontend" | "bunnative" | "oracledb" | "rust" | "csharp" | "nu" | "ansible" | "java" | "duckdb" | "dbt"; /** * Mapping of supported languages to their file extensions diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 16d216ce25..c550f2d978 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -110,7 +110,7 @@ "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", - "windmill-utils-internal": "1.8.2", + "windmill-utils-internal": "1.8.3", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", @@ -14719,9 +14719,9 @@ "integrity": "sha512-uHNL8F72/Tf96xF3hOHnPDjkEyqXw7fNjcPJiUhth9sTQkcwUIoJMOdwm8/cs+j9kKVRJ4tgNYMHEBLylazp6g==" }, "node_modules/windmill-utils-internal": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.2.tgz", - "integrity": "sha512-Otdn4iCE0QiOtMKPdHX5I89oECfZa3vmO2jdLdSETf7MBSv/gw9gvQm3oUQ29ymIHXLeuhQk/ebPD+WYolQJEA==", + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.3.tgz", + "integrity": "sha512-Lp8fVM/uHUvO6q01rIODIR46hTQ9D9R9BEiKoZHQqw9NJoy1OxhcsvX4usBbkXff/GbHlkWiQfZXCOn0ozJeKQ==", "license": "Apache 2.0" }, "node_modules/word-wrap": { diff --git a/frontend/package.json b/frontend/package.json index 3d7b92656d..98d33e5fb3 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -177,7 +177,7 @@ "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", - "windmill-utils-internal": "1.8.2", + "windmill-utils-internal": "1.8.3", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", diff --git a/frontend/src/lib/utils_workspace_deploy.test.ts b/frontend/src/lib/utils_workspace_deploy.test.ts index b970600ee7..5db05d041a 100644 --- a/frontend/src/lib/utils_workspace_deploy.test.ts +++ b/frontend/src/lib/utils_workspace_deploy.test.ts @@ -32,8 +32,8 @@ vi.mock('$lib/gen', async (importOriginal) => ({ } })) -// The deploy runs the published shared package, whose variable body has no `labels`: this -// pins that the adapter still carries them until a version that does is installed. +// The variable body is built by the installed shared package: this pins that a deploy from the +// app sends the source's labels on create and on update. describe('deploying a variable to another workspace', () => { it('carries its labels on create and on update', async () => { for (const workspaceTo of ['lacks-it', 'has-it']) { diff --git a/frontend/src/lib/utils_workspace_deploy.ts b/frontend/src/lib/utils_workspace_deploy.ts index 9d5b5409b8..efa7f09115 100644 --- a/frontend/src/lib/utils_workspace_deploy.ts +++ b/frontend/src/lib/utils_workspace_deploy.ts @@ -186,30 +186,13 @@ export type AppIdentity = { email: string; permissionedAs: string } export type DeployConflict = { hit: boolean } /** - * `deployItem` overrides only the email half of the identity, while the body it builds - * spreads the *source* item — which carries the source workspace's permissioned_as, valid - * nowhere else since usernames are per-workspace. The key is therefore always overwritten: - * with the picked user's principal for a custom choice, and cleared otherwise so the - * backend derives the target's own from the email it is given. The shared `deployItem` - * does the same, but this app consumes the published package, so the rewrite has to exist - * on both sides until that version ships. - * - * An app carries both halves inside its `policy` instead, so it needs both stamped here: - * the published package leaves the policy untouched, and a source principal beside a - * target address is rejected as a pair naming two different accounts. - * - * A group kept as the target identity travels as its synthetic `group-*@windmill.dev` - * address, which an admin-created account holding it would win on the backend: known and - * accepted, see `users::permissioned_as_from_email`. - * - * An agent carries its principal inside its resource value, and is handed the chosen one as a - * principal, as a trigger is. Every read here drops the source's, so a diff never shows it and - * the published `deployItem` copies none; the write then stamps the chosen one, or none, which - * leaves the backend to make it the deployer's. + * `deployItem` takes the identity only as an email and clears the source workspace's + * principal, leaving the backend to derive the target's own from that email. When the user + * picked a specific user, their principal is known here, so it is stamped on the body: on a + * flow or script directly, and inside the `policy` for an app, which holds both halves. */ function makeProvider( onBehalfOfPrincipal?: string, - onBehalfOf?: string, /** * Refuse the writes the shared `deployItem` reaches for only when the item already exists in * the target, turning its silent switch to an update into a failure the caller can act on. @@ -219,48 +202,16 @@ function makeProvider( */ conflict?: DeployConflict ): DeployProvider { - const withPermissionedAs = >(requestBody: T): T => ({ - ...requestBody, - on_behalf_of: onBehalfOfPrincipal - }) + const withPermissionedAs = >(requestBody: T): T => + onBehalfOfPrincipal ? { ...requestBody, on_behalf_of: onBehalfOfPrincipal } : requestBody const withPolicyIdentity = >(app: T): T => - app.policy - ? { - ...app, - policy: { - ...app.policy, - on_behalf_of: onBehalfOfPrincipal, - on_behalf_of_email: onBehalfOf - } - } + onBehalfOfPrincipal && app.policy + ? { ...app, policy: { ...app.policy, on_behalf_of: onBehalfOfPrincipal } } : app - const agents = new Set() - const withAgentIdentity = >(requestBody: T, path: string): T => - agents.has(path) && requestBody.value && typeof requestBody.value === 'object' - ? { - ...requestBody, - value: onBehalfOf - ? { ...requestBody.value, on_behalf_of: onBehalfOf } - : requestBody.value, - preserve_on_behalf_of: onBehalfOf !== undefined - } - : requestBody const refuseUpdate = (): never => { if (conflict) conflict.hit = true throw new Error('item already exists in the target workspace') } - // The published package builds variable, resource and folder bodies field by field without - // `labels`, so carry the source item's across from the read `deployItem` does just before the - // write. One provider serves one deploy, so the read always belongs to the write that follows. - let sourceLabels: string[] | undefined - const readLabels = (item: T): T => { - sourceLabels = item.labels - return item - } - const withLabels = >(requestBody: T): T => ({ - ...requestBody, - labels: sourceLabels - }) return { existsFlowByPath: (p) => FlowService.existsFlowByPath(p), existsScriptByPath: (p) => ScriptService.existsScriptByPath(p), @@ -305,43 +256,21 @@ function makeProvider( getPublicSecretOfLatestVersionOfApp: (p) => AppService.getPublicSecretOfLatestVersionOfApp(p), getRawAppData: (p) => AppService.getRawAppData(p), deleteApp: (p) => AppService.deleteApp(p), - getVariable: (p) => VariableService.getVariable(p).then(readLabels), - createVariable: (p) => - VariableService.createVariable({ ...p, requestBody: withLabels(p.requestBody) }), - updateVariable: (p) => - VariableService.updateVariable({ ...p, requestBody: withLabels(p.requestBody) }), + getVariable: (p) => VariableService.getVariable(p), + createVariable: (p) => VariableService.createVariable(p), + updateVariable: (p) => VariableService.updateVariable(p), deleteVariable: (p) => VariableService.deleteVariable(p), - getResource: async (p) => { - const resource = readLabels(await ResourceService.getResource(p)) - if (resource.resource_type !== 'ai_agent' || !resource.value) return resource - agents.add(p.path) - const { on_behalf_of: _, ...value } = resource.value as Record - return { ...resource, value } - }, - createResource: (p) => - ResourceService.createResource({ - ...p, - requestBody: withAgentIdentity(withLabels(p.requestBody), p.requestBody.path) - }), - updateResource: (p) => - ResourceService.updateResource({ - ...p, - requestBody: withAgentIdentity(withLabels(p.requestBody), p.path) - }), + getResource: (p) => ResourceService.getResource(p), + createResource: (p) => ResourceService.createResource(p), + updateResource: (p) => ResourceService.updateResource(p), deleteResource: (p) => ResourceService.deleteResource(p), getResourceType: (p) => ResourceService.getResourceType(p), createResourceType: (p) => ResourceService.createResourceType(p), updateResourceType: (p) => ResourceService.updateResourceType(p), deleteResourceType: (p) => ResourceService.deleteResourceType(p), - getFolder: (p) => FolderService.getFolder(p).then(readLabels), - createFolder: (p) => - FolderService.createFolder({ ...p, requestBody: withLabels(p.requestBody) }), - // A folder with no labels reads back without the field, so clearing them needs an explicit []. - updateFolder: (p) => - FolderService.updateFolder({ - ...p, - requestBody: { ...p.requestBody, labels: sourceLabels ?? [] } - }), + getFolder: (p) => FolderService.getFolder(p), + createFolder: (p) => FolderService.createFolder(p), + updateFolder: (p) => FolderService.updateFolder(p), deleteFolder: (p) => FolderService.deleteFolder(p), // Triggers existsTriggerByKind: (kind, p) => triggerServiceFor(kind).exists(p), @@ -483,7 +412,7 @@ export async function deployItem( const conflict: DeployConflict | undefined = createOnly ? { hit: false } : undefined const result = await sharedDeployItem( - makeProvider(onBehalfOfPrincipal, onBehalfOf, conflict), + makeProvider(onBehalfOfPrincipal, conflict), kind as DeployKind, path, workspaceFrom, From 5ef19a88a90b3a4fe05a78547416082dc51763f5 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 22 Oct 2026 17:15:05 +0200 Subject: [PATCH 045/101] fix: stop audit inserts from silently rolling back saves (#11938) * fix: let non-admins write audit rows for jobs run as another user * fix: keep logging audit failures on pool connections * chore: point ee-repo-ref at the import fix * chore: update ee-repo-ref to 06b2eb32cd7d40fd93078285d8b6150648384602 This commit updates the EE repository reference after PR #910 was merged in windmill-ee-private. Previous ee-repo-ref: da546d93c846192ed599b02a5aa3edd5d1ecdcfd New ee-repo-ref: 06b2eb32cd7d40fd93078285d8b6150648384602 Automated by sync-ee-ref workflow. --------- Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- ...audit_insert_policy_windmill_user.down.sql | 7 ++++ ...5_audit_insert_policy_windmill_user.up.sql | 7 ++++ backend/tests/audit_rls.rs | 37 +++++++++++++++++++ backend/tests/workspace_fairness.rs | 17 +-------- backend/windmill-api-auth/src/auth.rs | 7 ++-- backend/windmill-audit/src/audit_oss.rs | 20 +++++++++- backend/windmill-test-utils/src/lib.rs | 19 ++++++++++ 8 files changed, 93 insertions(+), 23 deletions(-) create mode 100644 backend/migrations/20261022000335_audit_insert_policy_windmill_user.down.sql create mode 100644 backend/migrations/20261022000335_audit_insert_policy_windmill_user.up.sql create mode 100644 backend/tests/audit_rls.rs diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index f6c4caccbe..669983e362 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -da49c12e3006fc77de789277f1462a4d8d7d92ce +06b2eb32cd7d40fd93078285d8b6150648384602 diff --git a/backend/migrations/20261022000335_audit_insert_policy_windmill_user.down.sql b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.down.sql new file mode 100644 index 0000000000..2e7bb84888 --- /dev/null +++ b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.down.sql @@ -0,0 +1,7 @@ +DROP POLICY IF EXISTS insert_any ON audit_partitioned; +CREATE POLICY schedule ON audit_partitioned FOR INSERT TO windmill_user + WITH CHECK ((username)::text ~~ 'schedule-%'::text); +CREATE POLICY schedule_audit ON audit_partitioned FOR INSERT TO windmill_user + WITH CHECK ((parameters ->> 'end_user'::text) ~~ 'schedule-%'::text); +CREATE POLICY webhook ON audit_partitioned FOR INSERT TO windmill_user + WITH CHECK ((username)::text ~~ 'webhook-%'::text); diff --git a/backend/migrations/20261022000335_audit_insert_policy_windmill_user.up.sql b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.up.sql new file mode 100644 index 0000000000..ab6b376663 --- /dev/null +++ b/backend/migrations/20261022000335_audit_insert_policy_windmill_user.up.sql @@ -0,0 +1,7 @@ +-- Only the server writes audit rows, so insert policies guard nothing. They did reject rows +-- whose username is not the caller, such as a job pushed as another user by a non-admin, and +-- that failed insert aborted the caller's transaction. Reads stay restricted by `see_own`. +DROP POLICY IF EXISTS schedule ON audit_partitioned; +DROP POLICY IF EXISTS schedule_audit ON audit_partitioned; +DROP POLICY IF EXISTS webhook ON audit_partitioned; +CREATE POLICY insert_any ON audit_partitioned FOR INSERT TO windmill_user WITH CHECK (true); diff --git a/backend/tests/audit_rls.rs b/backend/tests/audit_rls.rs new file mode 100644 index 0000000000..2aca3051ab --- /dev/null +++ b/backend/tests/audit_rls.rs @@ -0,0 +1,37 @@ +//! A non-admin's transaction must accept an audit row recorded under another username, as a +//! job pushed to run as someone else writes one. A rejected insert aborts the transaction and +//! takes the caller's own write down with it. + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::ensure_today_audit_partition; + +#[sqlx::test] +async fn non_admin_writes_an_audit_row_for_another_user(db: Pool) -> anyhow::Result<()> { + ensure_today_audit_partition(&db).await; + + let mut tx = db.begin().await?; + sqlx::query("SET LOCAL ROLE windmill_user") + .execute(&mut *tx) + .await?; + sqlx::query("SELECT set_config('session.user', 'bob', true)") + .execute(&mut *tx) + .await?; + // The shape a schedule run as alice records without an Enterprise license: parameters + // redacted, so no `end_user` names the schedule. + sqlx::query( + "INSERT INTO audit_partitioned + (workspace_id, username, operation, action_kind, resource, parameters, email) + VALUES ('admins', 'alice', 'redacted', 'execute', 'EE only', '{\"redacted\": \"-\"}', 'alice@windmill.dev')", + ) + .execute(&mut *tx) + .await?; + tx.commit().await?; + + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM audit_partitioned WHERE username = 'alice'") + .fetch_one(&db) + .await?; + assert_eq!(count, 1); + Ok(()) +} diff --git a/backend/tests/workspace_fairness.rs b/backend/tests/workspace_fairness.rs index f5922037e4..7f1e82782a 100644 --- a/backend/tests/workspace_fairness.rs +++ b/backend/tests/workspace_fairness.rs @@ -46,6 +46,7 @@ use windmill_common::worker::{ WORKSPACE_FAIRNESS_MIN_TOTAL, WORKSPACE_FAIRNESS_OVERLOADED, }; use windmill_queue::workspace_fairness::refresh_overloaded; +use windmill_test_utils::ensure_today_audit_partition; // --------------------------------------------------------------------------- // Shared helpers @@ -331,22 +332,6 @@ async fn fairness_lifts_when_load_drops(db: Pool) { assert!(overloaded_set().is_empty()); } -/// Ensure today's audit_partitioned partition exists — the migration only -/// creates partitions for the day it ran + 3 days, after which production -/// relies on `monitor::manage_audit_partitions` to roll new ones. That -/// maintenance task does not run in the test binary, so inserts silently -/// fail-and-warn without it. -async fn ensure_today_audit_partition(db: &Pool) { - let today: chrono::NaiveDate = chrono::Utc::now().date_naive(); - let next = today + chrono::Duration::days(1); - let partition = format!("audit_{}", today.format("%Y%m%d")); - let sql = format!( - "CREATE TABLE IF NOT EXISTS \"{partition}\" PARTITION OF audit_partitioned \ - FOR VALUES FROM ('{today}') TO ('{next}')" - ); - let _ = sqlx::query(&sql).execute(db).await; -} - /// Both cap AND uncap transitions must produce audit-log rows. This test /// drives a cap → uncap cycle and inspects `audit_partitioned` directly. #[sqlx::test(fixtures("base"))] diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index f68791179c..e278b644d5 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -903,10 +903,9 @@ async fn admit_and_record_guest_jwt(db: &DB, w_id: &str, email: &str, app_path: return false; } GUEST_JWT_ACTIVITY_CACHE.insert(cache_key, ()); - // Audit last, best-effort, on its own connection: the EE writer swallows an - // `audit_partitioned` failure but that failing statement still aborts the - // transaction it runs in, so auditing before the commit would let the whole - // activity row roll back while this returned success, admitting an uncounted guest. + // Audit last, best-effort, on its own connection: a failed `audit_partitioned` + // insert aborts the transaction it runs in, so auditing before the commit would + // let an audit failure drop the activity row that counts this guest. if first_jwt { let author = windmill_common::audit::AuditAuthor { email: email.to_string(), diff --git a/backend/windmill-audit/src/audit_oss.rs b/backend/windmill-audit/src/audit_oss.rs index 02b075af9d..55babc1625 100644 --- a/backend/windmill-audit/src/audit_oss.rs +++ b/backend/windmill-audit/src/audit_oss.rs @@ -64,6 +64,22 @@ impl AuditAuthorable for AuditAuthor { } } +/// Where an audit row is written decides what a failed insert breaks. On a pool connection it +/// breaks nothing else, so it is logged and the action goes on. On a connection, which may hold +/// the action's transaction, the failure has aborted that transaction and its COMMIT would roll +/// back silently, so it is returned. +pub trait AuditExecutor<'c>: sqlx::Executor<'c, Database = sqlx::Postgres> { + const ISOLATED: bool; +} + +impl<'c> AuditExecutor<'c> for &'c sqlx::Pool { + const ISOLATED: bool = true; +} + +impl<'c> AuditExecutor<'c> for &'c mut sqlx::PgConnection { + const ISOLATED: bool = false; +} + pub trait AuditAuthorable { fn username(&self) -> &str; fn email(&self) -> &str; @@ -75,7 +91,7 @@ pub trait AuditAuthorable { #[cfg(not(feature = "private"))] #[tracing::instrument(level = "trace", skip_all)] -pub async fn audit_log<'c, E: sqlx::Executor<'c, Database = Postgres>>( +pub async fn audit_log<'c, E: AuditExecutor<'c>>( _db: E, _author: &impl AuditAuthorable, mut _operation: &str, @@ -91,7 +107,7 @@ pub async fn audit_log<'c, E: sqlx::Executor<'c, Database = Postgres>>( /// AUTHORIZATION: records entries, checks nothing. The caller must have authorized `author` /// for the operation on every resource in `w_id` before calling. #[cfg(not(feature = "private"))] -pub async fn audit_log_many<'c, E: sqlx::Executor<'c, Database = Postgres>>( +pub async fn audit_log_many<'c, E: AuditExecutor<'c>>( _db: E, _author: &impl AuditAuthorable, _operation: &str, diff --git a/backend/windmill-test-utils/src/lib.rs b/backend/windmill-test-utils/src/lib.rs index f05fff66f8..5f804cee75 100644 --- a/backend/windmill-test-utils/src/lib.rs +++ b/backend/windmill-test-utils/src/lib.rs @@ -71,6 +71,22 @@ fn next_worker_name() -> String { format!("{id}/worker-{thread_name}") } +/// The migration only creates audit partitions for the day it ran and the next three, and the +/// monitor that rolls new ones does not run in tests. A test database cloned from an older +/// template therefore has no partition for today, and a failed audit insert fails the request. +pub async fn ensure_today_audit_partition(db: &Pool) { + let today = chrono::Utc::now().date_naive(); + let next = today + chrono::Duration::days(1); + let partition = format!("audit_{}", today.format("%Y%m%d")); + sqlx::query(&format!( + "CREATE TABLE IF NOT EXISTS \"{partition}\" PARTITION OF audit_partitioned \ + FOR VALUES FROM ('{today}') TO ('{next}')" + )) + .execute(db) + .await + .expect("creating today's audit partition"); +} + pub struct ApiServer { pub addr: std::net::SocketAddr, #[allow(unused)] @@ -104,6 +120,7 @@ impl ApiServer { server_mode: bool, mcp_mode: bool, ) -> anyhow::Result { + ensure_today_audit_partition(&db).await; let (tx, rx) = tokio::sync::broadcast::channel::<()>(1); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") @@ -212,6 +229,7 @@ impl RunJob { } pub async fn push(self, db: &Pool) -> Uuid { + ensure_today_audit_partition(db).await; let RunJob { payload, args, scheduled_for_o, username, email, job_id, workspace_id } = self; let mut hm_args = std::collections::HashMap::new(); for (k, v) in args { @@ -260,6 +278,7 @@ impl RunJob { /// Push the job as a specific user (for testing permissions) pub async fn push_as(self, db: &Pool, username: &str, email: &str) -> Uuid { + ensure_today_audit_partition(db).await; let RunJob { payload, args, scheduled_for_o, job_id, workspace_id, .. } = self; let mut hm_args = std::collections::HashMap::new(); for (k, v) in args { From c6a93a9b565752da6c8b55d383e5bee88f00f229 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Thu, 22 Oct 2026 21:01:09 +0200 Subject: [PATCH 046/101] feat: chat with a saved agent from a raw app through an agent runnable (#11921) * feat(chat-sdk): chat through a raw app's backend runnable Co-Authored-By: Claude Opus 5.5 * fix(chat-sdk): finish a lost stream and wait out a stopped turn in streamChatTurn Co-Authored-By: Claude Opus 5.5 * fix(chat-sdk): show the answer when a stream is lost before a tool call Co-Authored-By: Claude Opus 5.5 * feat(chat-sdk): send attachments through the raw app runnable Co-Authored-By: Claude Opus 5.5 * docs(chat-sdk): point sandboxed attachments at the runnable section Co-Authored-By: Claude Opus 5.5 * feat: agent runnables for raw apps Co-Authored-By: Claude Opus 5.5 * fix: build agent runnables without the parquet feature, cache the agent check query Co-Authored-By: Claude Opus 5.5 * fix: address review nits on the agent picker and the CLI schema doc Co-Authored-By: Claude Opus 5.5 * feat: run an agent runnable once when it is given no memory_id Co-Authored-By: Claude Opus 5.5 * feat: accept previous_messages on agent runs, read-checking the files it quotes Co-Authored-By: Claude Opus 5.5 * fix: refuse an anonymous agent turn while one with the same memory still runs Co-Authored-By: Claude Opus 5.5 * fix: show the agent's settings in the raw-app runnable panel, size its button like the row Co-Authored-By: Claude Opus 5.5 * feat: offer an agent runnable memory_id or previous_messages after the agent's memory Co-Authored-By: Claude Opus 5.5 * feat: take previous_messages in a memory-off agent's run form, type agent attachments as s3object Co-Authored-By: Claude Opus 5.5 * fix: file an anonymous agent turn as a conversation, so its memory is collected and its turns serialized Co-Authored-By: Claude Opus 5.5 * fix: own anonymous agent conversations under a fixed name that fits created_by Co-Authored-By: Claude Opus 5.5 * fix: own anonymous agent conversations as anonymous and keep them out of conversation lists Co-Authored-By: Claude Opus 5.5 * docs: point file_chat_turn at the anonymous conversation owner Co-Authored-By: Claude Opus 5.5 * fix: title the runnable picker after what it lists, in sentence case Co-Authored-By: Claude Opus 5.5 * fix: start a chat with local history listing its stored conversations Co-Authored-By: Claude Opus 5.5 * feat: chat through a raw app's agent runnable with { wmill, runnable } Co-Authored-By: Claude Opus 5.5 * fix: key an agent runnable chat's local history by its app as well Co-Authored-By: Claude Opus 5.5 * fix: address review findings on agent runnables Co-Authored-By: Claude Opus 5.5 * fix: offer memory_id to an agent runnable over an older auto memory Co-Authored-By: Claude Opus 5.5 * fix: drop inherited static inputs from an agent runnable, show the memory-off note only when it is off Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...4dc198a6b69d62fb244691af0601e542b6ac3.json | 23 ++ .../src/lib.rs | 5 +- backend/windmill-api-jobs/src/execution.rs | 33 ++- backend/windmill-api/openapi.yaml | 6 + backend/windmill-api/src/agent_runs.rs | 176 ++++++++---- backend/windmill-api/src/ai_evals/run.rs | 2 + backend/windmill-api/src/apps.rs | 231 ++++++++++++--- backend/windmill-api/src/apps_raw_bundler.ts | 2 +- backend/windmill-common/src/apps.rs | 22 +- .../windmill-common/src/flow_conversations.rs | 5 + chat-sdk/README.md | 49 +++- chat-sdk/src/assistant-ui.ts | 6 +- chat-sdk/src/attachments.ts | 7 +- chat-sdk/src/chat.ts | 41 ++- chat-sdk/src/config.ts | 33 ++- chat-sdk/src/index.ts | 2 + chat-sdk/src/react.ts | 16 +- chat-sdk/src/runnable.ts | 29 ++ chat-sdk/src/types.ts | 37 ++- chat-sdk/test/chat.test.ts | 1 + chat-sdk/test/runnable.test.ts | 68 +++++ cli/src/commands/app/dev.ts | 71 ++++- cli/src/commands/app/metadata.ts | 2 +- cli/src/commands/app/raw_apps.ts | 3 +- cli/src/guidance/skills.gen.ts | 35 ++- docs/operator-builder-rights.md | 7 +- .../src/lib/components/DeployWorkspace.svelte | 2 + .../EmptyInlineScript.svelte | 6 +- .../InlineScriptRunnableByPath.svelte | 172 ++++++++--- .../mainInput/RunnableSelector.svelte | 60 +++- .../mainInput/WorkspaceAgentList.svelte | 83 ++++++ .../mainInput/runnableSelectorUtils.ts | 4 +- frontend/src/lib/components/apps/inputType.ts | 5 +- .../lib/components/copilot/chat/app/core.ts | 23 +- .../copilot/chat/global/core.test.ts | 32 +++ .../components/copilot/chat/global/core.ts | 53 ++-- .../flows/content/AgentEditorHost.svelte | 22 +- .../flows/pickers/PickHubFlow.svelte | 2 +- .../flows/pickers/PickHubScript.svelte | 2 +- .../raw_apps/RawAppBackgroundRunner.svelte | 268 ++++++++++-------- .../components/raw_apps/RawAppEditor.svelte | 8 +- .../RawAppInlineScriptRunnable.svelte | 18 +- .../components/raw_apps/RawAppPreview.svelte | 4 +- .../lib/components/raw_apps/agentRunnable.ts | 43 +++ .../workspaceSettings/projectBundle.ts | 2 + frontend/src/lib/infer.ts | 13 +- system_prompts/auto-generated/prompts.ts | 30 +- .../auto-generated/skills/raw-app/SKILL.md | 35 ++- system_prompts/base/raw-app.md | 42 ++- 49 files changed, 1464 insertions(+), 377 deletions(-) create mode 100644 backend/.sqlx/query-392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3.json create mode 100644 chat-sdk/src/runnable.ts create mode 100644 chat-sdk/test/runnable.test.ts create mode 100644 frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceAgentList.svelte create mode 100644 frontend/src/lib/components/raw_apps/agentRunnable.ts diff --git a/backend/.sqlx/query-392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3.json b/backend/.sqlx/query-392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3.json new file mode 100644 index 0000000000..1b5aa1bd1f --- /dev/null +++ b/backend/.sqlx/query-392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "392b256dd7f36ec3736fc2f9d564dc198a6b69d62fb244691af0601e542b6ac3" +} diff --git a/backend/windmill-api-flow-conversations/src/lib.rs b/backend/windmill-api-flow-conversations/src/lib.rs index 7320721ea5..2ed3531cca 100644 --- a/backend/windmill-api-flow-conversations/src/lib.rs +++ b/backend/windmill-api-flow-conversations/src/lib.rs @@ -14,7 +14,7 @@ pub use windmill_common::flow_conversations::FlowConversation; use windmill_common::{ db::{UserDB, DB}, error::{JsonResult, Result}, - flow_conversations::{running_turns, MessageType, RunningTurn}, + flow_conversations::{running_turns, MessageType, RunningTurn, ANONYMOUS_CONVERSATION_OWNER}, utils::{not_found_if_none, paginate, truncate_with_ellipsis, Pagination}, }; @@ -96,7 +96,8 @@ async fn list_conversations( "created_by", "is_test", ]) - .and_where_eq("workspace_id", "?".bind(&w_id)); + .and_where_eq("workspace_id", "?".bind(&w_id)) + .and_where_ne("created_by", "?".bind(&ANONYMOUS_CONVERSATION_OWNER)); if let Some(flow_path) = &query.flow_path { sqlb.and_where_eq("flow_path", "?".bind(flow_path)); diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index da77acbf7c..53c318b70d 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -916,6 +916,35 @@ pub async fn handle_chat_conversation_messages( is_test: bool, // The run's args, for the files the message carried. args: &HashMap>, +) -> error::Result<()> { + file_chat_turn( + tx, + &authed.username, + authed.is_admin, + w_id, + flow_path, + run_query, + user_message_raw, + job_id, + is_test, + args, + ) + .await +} + +/// [`handle_chat_conversation_messages`] for a conversation owned by `owner`, which need not be a +/// user: an anonymous app visitor's is owned by `ANONYMOUS_CONVERSATION_OWNER`. +pub async fn file_chat_turn( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + owner: &str, + is_admin: bool, + w_id: &str, + flow_path: &str, + run_query: &RunJobQuery, + user_message_raw: Option<&Box>, + job_id: Uuid, + is_test: bool, + args: &HashMap>, ) -> error::Result<()> { // Names the query parameter rather than the field: it is not a flow argument, and // supplying it as one is the first thing tried on reading `memory_id is required`. @@ -945,8 +974,8 @@ pub async fn handle_chat_conversation_messages( tx, w_id, flow_path, - &authed.username, - authed.is_admin, + owner, + is_admin, &user_message, memory_id, is_test, diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index ddc7b70832..6996562aac 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -17107,6 +17107,12 @@ paths: user_attachments: type: array items: {} + previous_messages: + description: | + The history to answer from, as chat messages, when the agent's memory is off. + An agent with managed memory reads its conversation instead and ignores this. + type: array + items: {} responses: "201": description: job created diff --git a/backend/windmill-api/src/agent_runs.rs b/backend/windmill-api/src/agent_runs.rs index f1f85985ea..3bf65c9808 100644 --- a/backend/windmill-api/src/agent_runs.rs +++ b/backend/windmill-api/src/agent_runs.rs @@ -68,51 +68,9 @@ pub(crate) async fn run_agent_as( crate::jobs::check_license_key_valid().await?; // Read through the caller's own permissions: reading the agent is what allows running it. - let mut tx = user_db.clone().begin(authed).await?; - let value = sqlx::query_scalar!( - "SELECT value AS \"value: sqlx::types::Json\" - FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", - w_id, - path - ) - .fetch_optional(&mut *tx) - .await?; - tx.commit().await?; - let Some(sqlx::types::Json(mut value)) = not_found_if_none(value, "Agent", path)? else { - return Err(Error::BadRequest(format!( - "Agent {path} has no configuration" - ))); - }; - // Who the agent runs as and who can ask it in Slack, not inputs: its identity when it opts - // in, as a deployed flow does. - let obj = value.as_object_mut(); - let (agent_obo, run_obo) = obj - .map(|o| { - o.remove("slack_anyone"); - (o.remove("on_behalf_of"), o.remove("run_on_behalf_of")) - }) - .unwrap_or_default(); - let agent_obo = agent_obo - .filter(|_| run_obo.and_then(|v| v.as_bool()).unwrap_or(false)) - .and_then(|v| v.as_str().map(str::to_string)); - let config = config_to_draft(value)?; - - // A chat turn is filed where the agent's chat lists its conversations, which a flow cannot - // name (flow paths carry no `.`), so the two never share a conversation list. let chat = run_query.memory_id.is_some(); - let run_path = if chat { - format!("{path}.chat") - } else { - path.to_string() - }; - // A step memory id would replace the conversation's, and the agent would forget the turns - // before; history comes from the conversation alone. - let flow_value = agent_step_flow( - &config, - AGENT_NODE_ID, - chat, - &["memory_id", "previous_messages"], - )?; + let AgentTurn { flow_value, run_path, agent_obo } = + agent_turn(authed, user_db, w_id, path, chat).await?; let on_behalf_of = windmill_common::on_behalf_of_from_permissioned_as(agent_obo.as_deref(), w_id, db).await?; @@ -210,11 +168,73 @@ pub(crate) async fn run_agent_as( Ok(uuid) } +/// A turn of a saved agent, as the flow that runs it. +pub(crate) struct AgentTurn { + pub flow_value: windmill_common::flows::FlowValue, + /// Where the turn is filed: a chat turn under `.chat`, which a flow cannot name (flow + /// paths carry no `.`), so the agent's conversations never share a list with a flow's. + pub run_path: String, + /// The identity the agent runs as when it opts in (`run_on_behalf_of`). A caller that runs it + /// as some other identity, such as an app's, ignores it. + pub agent_obo: Option, +} + +/// Reads the agent through `authed`'s own permissions and builds the flow of one of its turns. +/// Who it may see and which inputs or slack settings it carries are not inputs of the run. +pub(crate) async fn agent_turn( + authed: &ApiAuthed, + user_db: &UserDB, + w_id: &str, + path: &str, + chat: bool, +) -> Result { + let mut tx = user_db.clone().begin(authed).await?; + let value = sqlx::query_scalar!( + "SELECT value AS \"value: sqlx::types::Json\" + FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + w_id, + path + ) + .fetch_optional(&mut *tx) + .await?; + tx.commit().await?; + let Some(sqlx::types::Json(mut value)) = not_found_if_none(value, "Agent", path)? else { + return Err(Error::BadRequest(format!( + "Agent {path} has no configuration" + ))); + }; + let obj = value.as_object_mut(); + let (agent_obo, run_obo) = obj + .map(|o| { + o.remove("slack_anyone"); + (o.remove("on_behalf_of"), o.remove("run_on_behalf_of")) + }) + .unwrap_or_default(); + let agent_obo = agent_obo + .filter(|_| run_obo.and_then(|v| v.as_bool()).unwrap_or(false)) + .and_then(|v| v.as_str().map(str::to_string)); + let config = config_to_draft(value)?; + let run_path = if chat { + format!("{path}.chat") + } else { + path.to_string() + }; + // A step memory id would replace the conversation's, and the agent would forget the turns + // before; history comes from the conversation alone. + let flow_value = agent_step_flow( + &config, + AGENT_NODE_ID, + chat, + &["memory_id", "previous_messages"], + )?; + Ok(AgentTurn { flow_value, run_path, agent_obo }) +} + /// The step fetches the message's files with its job's token, so a run as the agent's identity /// would read any file that identity can: a caller attaches only what they could download /// themselves, checked as `sign_s3_objects` checks a key before signing it. #[cfg(all(feature = "parquet", feature = "private"))] -async fn check_attachments_readable( +pub(crate) async fn check_attachments_readable( db: &DB, authed: &ApiAuthed, w_id: &str, @@ -224,14 +244,9 @@ async fn check_attachments_readable( get_large_file_storage, get_workspace_s3_resource_and_check_paths, }; use windmill_common::db::DbWithOptAuthed; - use windmill_types::s3::{S3Object, S3Permission}; + use windmill_types::s3::S3Permission; - let Some(raw) = args.get("user_attachments") else { - return Ok(()); - }; - let attachments: Option> = serde_json::from_str(raw.get()) - .map_err(|e| Error::BadRequest(format!("invalid user_attachments: {e}")))?; - for attachment in attachments.iter().flatten().filter(|a| !a.s3.is_empty()) { + for attachment in run_attachments(args)? { // The path check is skipped, not failed, when the storage does not resolve. if get_large_file_storage(db, w_id, attachment.storage.clone()) .await? @@ -254,10 +269,39 @@ async fn check_attachments_readable( Ok(()) } +/// Every file the step fetches with its job's token: the message's attachments, and the +/// `s3_object` parts of the history a caller supplies, which the worker downloads alike. +pub(crate) fn run_attachments( + args: &HashMap>, +) -> Result> { + use windmill_ai::ai_types::{ContentPart, OpenAIContent, OpenAIMessage}; + + let mut files: Vec = match args.get("user_attachments") { + Some(raw) => serde_json::from_str::>>(raw.get()) + .map_err(|e| Error::BadRequest(format!("invalid user_attachments: {e}")))? + .unwrap_or_default(), + None => vec![], + }; + if let Some(raw) = args.get("previous_messages") { + let messages = serde_json::from_str::>>(raw.get()) + .map_err(|e| Error::BadRequest(format!("invalid previous_messages: {e}")))?; + for message in messages.into_iter().flatten() { + if let Some(OpenAIContent::Parts(parts)) = message.content { + files.extend(parts.into_iter().filter_map(|part| match part { + ContentPart::S3Object { s3_object } => Some(s3_object), + _ => None, + })); + } + } + } + files.retain(|f| !f.s3.is_empty()); + Ok(files) +} + /// The agent as a one-step flow, validated by deserializing through `FlowValue` rather than /// trusted as raw JSON. Its own transforms are the step's, minus `without`, and the run's inputs -/// supply the message and the attachments over the top. Always inlined, never a link to the -/// resource: a linked step would resolve the agent when it runs, not as it was read here. +/// supply the message, the attachments and any history over the top. Always inlined, never a link +/// to the resource: a linked step would resolve the agent when it runs, not as it was read here. pub(crate) fn agent_step_flow( config: &AgentDraft, id: &str, @@ -271,7 +315,7 @@ pub(crate) fn agent_step_flow( for key in without { input_transforms.remove(*key); } - for key in ["user_message", "user_attachments"] { + for key in ["user_message", "user_attachments", "previous_messages"] { input_transforms.insert( key.to_string(), serde_json::json!({ "type": "javascript", "expr": format!("flow_input.{}", key) }), @@ -292,3 +336,25 @@ pub(crate) fn agent_step_flow( } Ok(serde_json::from_value(flow)?) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn run_attachments_include_the_files_a_supplied_history_quotes() { + let args: HashMap> = serde_json::from_value(serde_json::json!({ + "user_attachments": [{ "s3": "u/a/attached.png" }], + "previous_messages": [ + { "role": "user", "content": [ + { "type": "text", "text": "look" }, + { "type": "s3_object", "s3_object": { "s3": "u/b/quoted.png" } } + ]}, + { "role": "assistant", "content": "ok" } + ] + })) + .unwrap(); + let keys: Vec<_> = run_attachments(&args).unwrap().into_iter().map(|f| f.s3).collect(); + assert_eq!(keys, ["u/a/attached.png", "u/b/quoted.png"]); + } +} diff --git a/backend/windmill-api/src/ai_evals/run.rs b/backend/windmill-api/src/ai_evals/run.rs index 410e92f515..6b219e5597 100644 --- a/backend/windmill-api/src/ai_evals/run.rs +++ b/backend/windmill-api/src/ai_evals/run.rs @@ -255,6 +255,8 @@ fn agent_module(config: &AgentDraft) -> Result { .entry("input_transforms") .or_insert_with(|| serde_json::json!({})); if let Some(transforms) = transforms.as_object_mut() { + // A case carries no history: each one is asked fresh. + transforms.remove("previous_messages"); for key in ["user_message", "user_attachments"] { transforms.insert( key.to_string(), diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 9f58638046..bc0124b685 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -58,8 +58,8 @@ use windmill_audit::ActionKind; use windmill_common::roles::{caller_capabilities, AuthorLevel}; use windmill_common::{ apps::{ - app_value_has_inline_script, app_value_runnable_paths, AppScriptId, ListAppQuery, - APP_WORKSPACED_ROUTE, + app_value_has_inline_script, app_value_runnable_paths, AppRunnableKind, AppScriptId, + ListAppQuery, APP_WORKSPACED_ROUTE, }, auth::{APP_EMBED_TOKEN_LABEL_PREFIX, RAW_APP_SDK_TOKEN_LABEL_PREFIX, TOKEN_PREFIX_LEN}, cache, @@ -2307,14 +2307,14 @@ pub(crate) enum BuilderAppWrite { } /// The half of the builder-app check that needs no DB (see `docs/operator-builder-rights.md`). -/// Returns every runnable the app can invoke, as `(is_flow, path)`, from both the policy's +/// Returns every runnable the app can invoke, as `(kind, path)`, from both the policy's /// triggerables and the value's path runnables: they are not the same list. fn check_operator_composed_app( write: BuilderAppWrite, raw_app: bool, value: Option<&RawValue>, policy: Option<&mut Policy>, -) -> Result> { +) -> Result> { let verb = if write == BuilderAppWrite::Deploy { "deploy" } else { @@ -2325,7 +2325,7 @@ fn check_operator_composed_app( "Operators with builder rights can only author full-code apps".to_string(), )); } - let mut referenced: Vec<(bool, String)> = Vec::new(); + let mut referenced: Vec<(AppRunnableKind, String)> = Vec::new(); if let Some(value) = value { // The text stored, NULs stripped: a stripped NUL can rename a key into one this reads. let value: serde_json::Value = @@ -2386,9 +2386,9 @@ fn check_operator_composed_app( Ok(referenced) } -/// The runnables a builder app's policy authorizes, as `(is_flow, path)`; refuses a policy that +/// The runnables a builder app's policy authorizes, as `(kind, path)`; refuses a policy that /// pins inline code. -fn checked_policy_runnable_paths(policy: &Policy) -> Result> { +fn checked_policy_runnable_paths(policy: &Policy) -> Result> { // A `rawscript/` triggerable is the deployed app's authorization to run caller-supplied // `raw_code` hashing to it: pinning one hands a builder arbitrary code execution through an // app whose value passed the inline-script check. A composition-only app has none. @@ -2425,21 +2425,24 @@ fn checked_policy_runnable_paths(policy: &Policy) -> Result> std::iter::once(key.as_str()) .chain(key.match_indices(':').map(|(i, _)| &key[i + 1..])) .filter_map(|candidate| { - candidate - .strip_prefix("script/") - .map(|p| (false, p.to_string())) - .or_else(|| { - candidate - .strip_prefix("flow/") - .map(|p| (true, p.to_string())) - }) + [ + ("script/", AppRunnableKind::Script), + ("flow/", AppRunnableKind::Flow), + ("agent/", AppRunnableKind::Agent), + ] + .into_iter() + .find_map(|(prefix, kind)| { + candidate + .strip_prefix(prefix) + .map(|p| (kind, p.to_string())) + }) }) .collect::>() }) .collect()) } -fn refuse_hub_runnables(referenced: &[(bool, String)]) -> Result<()> { +fn refuse_hub_runnables(referenced: &[(AppRunnableKind, String)]) -> Result<()> { for (_, path) in referenced { if path.starts_with("hub/") { return Err(Error::PermissionDenied(format!( @@ -2494,7 +2497,7 @@ async fn require_runnables_readable( db: &DB, user_db: &UserDB, w_id: &str, - referenced: Vec<(bool, String)>, + referenced: Vec<(AppRunnableKind, String)>, ) -> Result<()> { if referenced.is_empty() { return Ok(()); @@ -2504,26 +2507,33 @@ async fn require_runnables_readable( // whichever version the caller happens to see. Resolved before the transaction opens so no // request holds two pool connections at once. let mut hashes = Vec::with_capacity(referenced.len()); - for (is_flow, path) in &referenced { - hashes.push(if *is_flow { - None - } else { + for (kind, path) in &referenced { + hashes.push(if *kind == AppRunnableKind::Script { windmill_common::get_latest_script_hash(db, path, w_id).await? + } else { + None }); } let mut tx = user_db.clone().begin(authed).await?; - for ((is_flow, path), hash) in referenced.into_iter().zip(hashes) { - let readable = if is_flow { - sqlx::query_scalar!( + for ((kind, path), hash) in referenced.into_iter().zip(hashes) { + let readable = match kind { + AppRunnableKind::Flow => sqlx::query_scalar!( "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2)", w_id, path, ) .fetch_one(&mut *tx) .await? - .unwrap_or(false) - } else { - match hash { + .unwrap_or(false), + AppRunnableKind::Agent => sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent')", + w_id, + path, + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false), + AppRunnableKind::Script => match hash { Some(hash) => sqlx::query_scalar!( "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND hash = $2)", w_id, @@ -2533,17 +2543,21 @@ async fn require_runnables_readable( .await? .unwrap_or(false), None => false, - } + }, }; // One message for every cause: telling "no runnable version" apart from "not readable" // would reveal that a path the caller cannot read exists. if !readable { - return Err(Error::PermissionDenied(if is_flow { - format!("Flow {path} does not exist or is not readable by you") - } else { - format!( + return Err(Error::PermissionDenied(match kind { + AppRunnableKind::Flow => { + format!("Flow {path} does not exist or is not readable by you") + } + AppRunnableKind::Agent => { + format!("Agent {path} does not exist or is not readable by you") + } + AppRunnableKind::Script => format!( "Script {path} does not exist, is not readable by you, or has not finished deploying" - ) + ), })); } } @@ -4529,6 +4543,7 @@ async fn execute_component( let previews_hub = payload.path.as_deref().is_some_and(|p| { p.strip_prefix("script/") .or_else(|| p.strip_prefix("flow/")) + .or_else(|| p.strip_prefix("agent/")) .unwrap_or(p) .starts_with("hub/") }); @@ -4545,6 +4560,7 @@ async fn execute_component( let runnable_path = p .strip_prefix("script/") .or_else(|| p.strip_prefix("flow/")) + .or_else(|| p.strip_prefix("agent/")) .unwrap_or(p); require_path_read_access_for_preview(authed, &Some(runnable_path.to_string()))?; } @@ -4880,6 +4896,36 @@ async fn execute_component( // the app identity. Drop it; the legitimate value rides in `extra`. payload.args.remove("_TEMP_SCRIPT_REFS"); + // An agent runnable takes the message and its files, plus optionally the conversation they + // belong to, which names the agent's memory rather than an input of its run. Without it the + // run is a single one, as on the direct agent endpoint. + let agent_path = payload + .path + .as_deref() + .and_then(|p| p.strip_prefix("agent/")) + .map(str::to_string); + let agent_memory_id = if agent_path.is_some() { + let memory_id = payload + .args + .remove("memory_id") + .map(|v| { + serde_json::from_str::>(v.get()) + .map_err(|_| Error::BadRequest("memory_id must be a string".to_string())) + }) + .transpose()? + .flatten() + .filter(|m| !m.trim().is_empty()); + payload.args.retain(|k, _| { + matches!( + k.as_str(), + "user_message" | "user_attachments" | "previous_messages" + ) + }); + memory_id + } else { + None + }; + let (mut args, job_id) = build_args( policy, policy_triggerables, @@ -4918,9 +4964,64 @@ async fn execute_component( } .filter(|t| !t.is_empty()) }; + if agent_path.is_some() { + #[cfg(feature = "enterprise")] + crate::jobs::check_license_key_valid().await?; + let has_attachments = !crate::agent_runs::run_attachments(&args.args)?.is_empty(); + match opt_authed.as_ref() { + // The agent reads the files with the app's token: a viewer attaches only what they + // could download themselves. + Some(_viewer) if has_attachments => { + #[cfg(all(feature = "parquet", feature = "private"))] + crate::agent_runs::check_attachments_readable(&db, _viewer, &w_id, &args.args) + .await?; + } + None if has_attachments => { + return Err(Error::BadRequest( + "an anonymous viewer cannot send files to an agent".to_string(), + )); + } + _ => {} + } + } + // Filed under the viewer, who must therefore be kept past the push below. + let agent_viewer = agent_path.as_ref().and(opt_authed.clone()); + let mut agent_run_path = None; + let component = payload.component.clone(); let (job_payload, tag, _runnable_on_behalf_of) = match (payload.path, payload.raw_code, payload.id) { + (Some(_), None, None) if agent_path.is_some() => { + let agent = agent_path.as_deref().unwrap_or_default(); + // Read as the identity the app runs as: reading the agent is what allows running + // it. The app's identity is also the run's, never the agent's own on-behalf-of. + let run_as = windmill_api_auth::fetch_api_authed_from_permissioned_as( + permissioned_as.clone(), + email.clone(), + &w_id, + &db, + None, + ) + .await?; + let turn = crate::agent_runs::agent_turn( + &run_as, + &user_db, + &w_id, + agent, + agent_memory_id.is_some(), + ) + .await?; + agent_run_path = Some(turn.run_path.clone()); + ( + JobPayload::RawFlow { + value: turn.flow_value, + path: Some(turn.run_path), + restarted_from: None, + }, + None, + None, + ) + } // flow or script: (Some(path), None, None) => { get_payload_tag_from_prefixed_path(&path, &db, &w_id).await? @@ -5061,6 +5162,44 @@ async fn execute_component( .await?; } + if let (Some(run_path), Some(memory_id)) = (agent_run_path.as_deref(), agent_memory_id) { + // A signed-in viewer's turn is filed under them: nobody else may continue their + // conversation. An anonymous visitor's id is derived per app so that it can name no + // signed-in user's conversation (a bare UUID is used as is). Either way the + // conversation's row lock refuses a turn while one runs, and retention collects its + // memory with its messages. + let (owner, is_admin, memory_id) = match agent_viewer.as_ref() { + Some(viewer) => (viewer.username.clone(), viewer.is_admin, memory_id), + None => ( + windmill_common::flow_conversations::ANONYMOUS_CONVERSATION_OWNER.to_string(), + false, + windmill_common::flow_conversations::memory_key( + &w_id, + run_path, + &format!("anonymous:{path}:{memory_id}"), + ) + .to_string(), + ), + }; + let run_query = RunJobQuery { memory_id: Some(memory_id), ..Default::default() }; + if let Some(key) = run_query.memory_key(&w_id, run_path) { + crate::jobs::set_flow_memory_id(&mut tx, uuid, key).await?; + } + crate::jobs::file_chat_turn( + &mut tx, + &owner, + is_admin, + &w_id, + run_path, + &run_query, + args.args.get("user_message"), + uuid, + is_preview, + &args.args, + ) + .await?; + } + // Apply runnable query parameters if provided if let Some(ref run_query) = payload.run_query_params { if let Some(flow_path) = flow_path.as_deref() { @@ -6923,7 +7062,7 @@ mod embed_token_tests { #[cfg(test)] mod operator_app_tests { - use super::{check_operator_composed_app, BuilderAppWrite, Policy}; + use super::{check_operator_composed_app, AppRunnableKind, BuilderAppWrite, Policy}; use windmill_common::error::Result; use windmill_common::worker::to_raw_value; @@ -6941,7 +7080,10 @@ mod operator_app_tests { }}) } - fn composed_app(value: serde_json::Value, policy: &mut Policy) -> Result> { + fn composed_app( + value: serde_json::Value, + policy: &mut Policy, + ) -> Result> { let value = to_raw_value(&value); check_operator_composed_app(BuilderAppWrite::Deploy, true, Some(&value), Some(policy)) } @@ -6959,7 +7101,10 @@ mod operator_app_tests { let referenced = composed_app(clean.clone(), &mut policy).unwrap(); assert_eq!(policy.sandbox, Some(true)); // The runnables the policy authorizes are handed back for the caller to authorize. - assert_eq!(referenced, vec![(false, "f/x/s".to_string())]); + assert_eq!( + referenced, + vec![(AppRunnableKind::Script, "f/x/s".to_string())] + ); // A hub reference is unreviewed code, refused like it is in a flow. let mut policy = builder_policy( @@ -6996,12 +7141,20 @@ mod operator_app_tests { let mut policy = builder_policy(serde_json::json!({})); assert_eq!( composed_app(path_runnable("f/x/s", "script"), &mut policy).unwrap(), - vec![(false, "f/x/s".to_string())] + vec![(AppRunnableKind::Script, "f/x/s".to_string())] ); let mut policy = builder_policy(serde_json::json!({})); assert_eq!( composed_app(path_runnable("f/x/f", "flow"), &mut policy).unwrap(), - vec![(true, "f/x/f".to_string())] + vec![(AppRunnableKind::Flow, "f/x/f".to_string())] + ); + // An agent is reported from both surfaces, for the caller to check it can read it. + let mut policy = builder_policy( + serde_json::json!({"a:agent/f/x/bot": {"static_inputs": {}, "one_of_inputs": {}}}), + ); + assert_eq!( + composed_app(path_runnable("f/x/bot", "agent"), &mut policy).unwrap(), + vec![(AppRunnableKind::Agent, "f/x/bot".to_string())] ); let mut policy = builder_policy(serde_json::json!({})); assert!(composed_app(path_runnable("hub/1/x", "hubscript"), &mut policy).is_err()); @@ -7018,7 +7171,7 @@ mod operator_app_tests { ); assert_eq!( composed_app(clean.clone(), &mut policy).unwrap(), - vec![(false, "f/x/s".to_string())] + vec![(AppRunnableKind::Script, "f/x/s".to_string())] ); // `Viewer` mode makes `execute_component` accept any script/flow path, triggerables or diff --git a/backend/windmill-api/src/apps_raw_bundler.ts b/backend/windmill-api/src/apps_raw_bundler.ts index 965a9289b5..47460be3a6 100644 --- a/backend/windmill-api/src/apps_raw_bundler.ts +++ b/backend/windmill-api/src/apps_raw_bundler.ts @@ -135,7 +135,7 @@ export async function main( const nonEmpty = (v: unknown) => typeof v === 'string' && v.length > 0 // The prefixes `execute_component` resolves a run against; anything else is a // grant no run can match. - const RUN_TYPES = ['script', 'flow', 'hubscript'] + const RUN_TYPES = ['script', 'flow', 'hubscript', 'agent'] const malformed = Object.entries(runnables ?? {}) .filter(([, r]) => r != null) .filter(([, r]) => { diff --git a/backend/windmill-common/src/apps.rs b/backend/windmill-common/src/apps.rs index 4e25cec17d..9ce4326212 100644 --- a/backend/windmill-common/src/apps.rs +++ b/backend/windmill-common/src/apps.rs @@ -34,14 +34,23 @@ pub fn app_value_has_inline_script(value: &Value) -> bool { } } -/// Every workspace runnable the app value points a component at, as `(is_flow, path)`. +/// What a path runnable of an app runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum AppRunnableKind { + Script, + Flow, + /// A saved AI agent (an `ai_agent` resource), run as one chat turn. + Agent, +} + +/// Every workspace runnable the app value points a component at, as `(kind, path)`. /// /// This is what the deployed bundle actually asks `execute_component` to run: it resolves a /// `runnable_id` against the stored `runnables` and sends `{runType}/{path}`. The policy's /// triggerables are a separate surface, so both have to be authorized. Anything not plain text /// is refused, never skipped: the editor compares `type` loosely (`["path"] == "path"`) and /// interpolates `path` (`["u/x"]` → `u/x`), so a skipped entry still runs. -pub fn app_value_runnable_paths(value: &Value) -> error::Result> { +pub fn app_value_runnable_paths(value: &Value) -> error::Result> { let bad = |msg: String| error::Error::BadRequest(msg); let runnables = match value.get("runnables") { None | Some(Value::Null) => return Ok(vec![]), @@ -61,12 +70,13 @@ pub fn app_value_runnable_paths(value: &Value) -> error::Result true, - Some(Value::String(t)) if t == "script" || t == "hubscript" => false, + let kind = match runnable.get("runType") { + Some(Value::String(t)) if t == "flow" => AppRunnableKind::Flow, + Some(Value::String(t)) if t == "script" || t == "hubscript" => AppRunnableKind::Script, + Some(Value::String(t)) if t == "agent" => AppRunnableKind::Agent, _ => return Err(bad(format!("Unsupported runType for runnable {path}"))), }; - out.push((is_flow, path.clone())); + out.push((kind, path.clone())); } Ok(out) } diff --git a/backend/windmill-common/src/flow_conversations.rs b/backend/windmill-common/src/flow_conversations.rs index 571877ead2..12b3daf2ec 100644 --- a/backend/windmill-common/src/flow_conversations.rs +++ b/backend/windmill-common/src/flow_conversations.rs @@ -14,6 +14,11 @@ use crate::utils::truncate_with_ellipsis; /// Changing it detaches every memory stored under a string memory id. const MEMORY_ID_NAMESPACE: Uuid = Uuid::from_u128(0x6f1c2d4e_8a3b_5c7d_9e0f_1a2b3c4d5e6f); +/// Owns anonymous app visitors' agent conversations, as `created_by` names an anonymous app run. +/// It is also a valid username, so listing conversations leaves these out: a user of that name +/// would otherwise list every anonymous visitor's. +pub const ANONYMOUS_CONVERSATION_OWNER: &str = "anonymous"; + /// Memory is stored and carried in `flow_status.memory_id` as a uuid, which names the same memory /// wherever it is passed, as a chat conversation id must. Any other string names a memory through a /// name-based (v5) uuid scoped to its workspace and flow, so the same key in two flows or two diff --git a/chat-sdk/README.md b/chat-sdk/README.md index 006d5407d8..2106d35bee 100644 --- a/chat-sdk/README.md +++ b/chat-sdk/README.md @@ -148,6 +148,45 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) - **`wmill app dev`**: there is no viewer session on the dev server, so pass `baseUrl`, `workspace` and `token` explicitly during development. +### A saved agent, through an agent runnable + +To chat with a saved AI agent (an `ai_agent` resource), give the app an **agent +runnable**: a path runnable of type `agent` naming the agent, picked under "AI agents" +in the editor, or in `raw_app.yaml`: + +```yaml +runnables: + chat: + type: agent + path: f/support/agent +``` + +Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no +frontend SDK scope, viewers get no consent prompt and need no access to the agent. +Name the runnable and pass the app's generated `wmill.ts`, which the chat goes through: + +```tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +``` + +`runnable` is checked against the runnables `wmill.ts` declares, and names the local +history, so two agent runnables in one app keep separate conversations. Going through +`wmill.ts` is what makes the same code work in a deployed app and under `wmill app dev`. + +`createChat` and the assistant-ui runtime take the same options; the AI SDK transport +does not. The runnable takes `user_message` and `memory_id`, the conversation id, which +the agent's memory is keyed by, so it remembers earlier turns (called from `wmill.ts` +without `memory_id`, it is a single run with no conversation). The agent needs managed +memory: one whose memory is off takes `previous_messages` instead, the history you keep. A signed-in viewer's turns +are filed under them, so nobody else can continue their conversations; an anonymous +visitor's are kept apart per app. The chat makes no request of its own: history is +`'local'` (the app's own storage), `stop()` stops following without cancelling the turn, +a message sent while it still runs is refused with `TurnRunningError`, and attachments +are refused. + ## Any framework `createChat` returns a store: `subscribe` calls the listener immediately and on every @@ -178,7 +217,7 @@ await chat.sendMessage('Hello') | Option | | |---|---| -| `flowPath` | Path of the deployed flow, e.g. `f/support/assistant`. Required. | +| `flowPath` | Path of the deployed flow, e.g. `f/support/assistant`. Required unless `follow` is set. | | `baseUrl` | The Windmill origin. Detected inside a raw app. | | `workspace` | Detected inside a raw app. | | `token` | A token, or a function returning one (called before every request, so it can fetch a short-lived token from your backend). Omit it inside a raw app. | @@ -190,6 +229,8 @@ await chat.sendMessage('Hello') | `pollDelayMs` | How often, in ms, the server polls a running turn for the stream (Enterprise; 50 at the fastest, other servers ignore it). Unset, the server relaxes from 100 ms to 3 s over a long turn; set it when tokens must keep flowing at that pace. | | `onFinish`, `onError` | Called when a turn has its answer, or could not run at all. | | `run` | Runs the flow for a turn yourself and returns the job id, instead of the deployed flow at `flowPath` (Windmill's editor chats with an undeployed flow through a preview run this way). Pass `memory_id` = the conversation id. | +| `follow` | With `run`: follows the job through your own client, calling `onStream` with each chunk of its result stream and resolving with its result. The chat then makes no request of its own; `runnable` sets both for a raw app's agent runnable, see [A saved agent](#a-saved-agent-through-an-agent-runnable). | +| `runnable`, `wmill` | In a raw app, chat through the agent runnable of that name, going through the app's generated module (`import * as wmill from './wmill'`). Replaces `flowPath`, `run` and `follow`. | ## State @@ -294,7 +335,8 @@ That store is keyed by the **Windmill user**, so it fits a viewer session or a t issued per user. With one token shared by every visitor of a site, all visitors would see each other's conversations. For that setup use `history: 'local'` (the default with an explicit `token`): the conversation list and messages stay in the browser's -`localStorage`, per Windmill instance, workspace and flow. `'none'` keeps nothing +`localStorage`, per Windmill instance, workspace and flow, and the chat starts with that +list in `state.conversations`, without a `loadConversations()` call. `'none'` keeps nothing beyond the page. When the default `'server'` mode turns out unreadable (a token or sandboxed app @@ -333,7 +375,8 @@ custom integrations. When asked to add a chat over a Windmill flow: the flow must be deployed with chat mode on. Pick the entry point from the table at the top (`useChat` → `@windmill-labs/chat-sdk/ai-sdk`, assistant-ui → `@windmill-labs/chat-sdk/assistant-ui`, otherwise `@windmill-labs/chat-sdk/react`). Inside a -Windmill raw app pass only `flowPath`. Elsewhere pass `baseUrl`, `workspace` and a +Windmill raw app pass only `flowPath`; for a saved agent, use an `agent` runnable and pass +`{ wmill, runnable }`. Elsewhere pass `baseUrl`, `workspace` and a `token`; for a public page use a token scoped to `jobs:run:flows:` and leave `history` at its default. Render `role`, `content`, `pending`, `success` and `tool.status`; never build the SSE handling yourself. diff --git a/chat-sdk/src/assistant-ui.ts b/chat-sdk/src/assistant-ui.ts index b9a76db679..04ab23793e 100644 --- a/chat-sdk/src/assistant-ui.ts +++ b/chat-sdk/src/assistant-ui.ts @@ -7,7 +7,7 @@ import { } from '@assistant-ui/react' import { useEffect, useMemo } from 'react' import { useWindmillChat } from './react' -import type { ChatMessage, ChatOptions } from './types' +import type { ChatMessage, RawAppWmill, TypedChatOptions } from './types' import { parseJsonOr } from './utils' /** One assistant turn: the assistant and tool rows between two user messages. */ @@ -17,7 +17,7 @@ export interface WindmillTurn { messages: ChatMessage[] } -export interface WindmillRuntimeOptions extends ChatOptions { +export type WindmillRuntimeOptions = TypedChatOptions & { /** Load the conversation list on mount so `ThreadListPrimitive` has something to show. Default true. */ threadList?: boolean } @@ -27,7 +27,7 @@ export interface WindmillRuntimeOptions extends ChatOptions { * Conversations become threads, so the thread list primitives switch, create and * delete Windmill conversations. */ -export function useWindmillRuntime(options: WindmillRuntimeOptions): AssistantRuntime { +export function useWindmillRuntime(options: WindmillRuntimeOptions): AssistantRuntime { const chat = useWindmillChat(options) const turns = useMemo(() => groupTurns(chat.messages), [chat.messages]) const withThreadList = options.threadList !== false diff --git a/chat-sdk/src/attachments.ts b/chat-sdk/src/attachments.ts index ac5e71c7d3..a11b0106ba 100644 --- a/chat-sdk/src/attachments.ts +++ b/chat-sdk/src/attachments.ts @@ -88,10 +88,9 @@ export async function uploadAttachments( attachments.map(async (attachment, index) => { try { const blob = attachmentBlob(attachment) - const filename = storedAttachmentName( - attachment.name || `attachment-${index + 1}`, - blob.type - ) + // The last segment only: the name may come from whoever sent the file. + const name = attachment.name?.split(/[\\/]/).pop()?.replace(/^\.+$/, '') + const filename = storedAttachmentName(name || `attachment-${index + 1}`, blob.type) const { file_key } = await api.uploadFile(`${prefix}/${index}/${filename}`, blob, { contentType: blob.type, signal: batch.signal diff --git a/chat-sdk/src/chat.ts b/chat-sdk/src/chat.ts index dfef438f33..2d48d383a0 100644 --- a/chat-sdk/src/chat.ts +++ b/chat-sdk/src/chat.ts @@ -11,11 +11,13 @@ import { resolveConfig, type ResolvedConfig } from './config' import { followJob } from './follow' import { createLocalHistory, type LocalHistory } from './history' import { uploadAttachments } from './attachments' -import type { AgentStreamEvent } from './stream' +import { createStreamEventParser, type AgentStreamEvent } from './stream' import type { Chat, ChatMessage, ChatOptions, + RawAppWmill, + TypedChatOptions, ChatState, Conversation, SendMessageOptions, @@ -62,7 +64,7 @@ interface Turn { streamedText: boolean } -export function createChat(options: ChatOptions): Chat { +export function createChat(options: TypedChatOptions): Chat { return new ChatImpl(options) } @@ -102,7 +104,9 @@ class ChatImpl implements Chat { messages: [], status: 'idle', error: undefined, - conversations: [], + // Browser history is read synchronously, so a chat starts with its list as server history + // cannot: an app that never calls `loadConversations` still shows its conversations. + conversations: this.#config.history === 'local' ? this.#local.listConversations() : [], history: this.#config.history, loadingMessages: false, hasMoreMessages: false @@ -134,6 +138,9 @@ class ChatImpl implements Chat { if (attachments.length > 0 && !attachmentsInput) { throw new Error('windmill-chat: attachments need `attachmentsInput`, the flow input that takes them') } + if (attachments.length > 0 && this.#config.follow) { + throw new Error('windmill-chat: attachments upload with the SDK\'s own requests, which `follow` replaces') + } if (attachmentsInput && !attachmentsInput.multiple && attachments.length > 1) { // Uploading all of them would run with the first and leave the rest stranded in storage. throw new Error(`windmill-chat: \`${attachmentsInput.name}\` holds one file; got ${attachments.length}`) @@ -338,7 +345,7 @@ class ChatImpl implements Chat { this.#set({ messages: finalized(this.#state.messages), status: 'idle' }) this.#persistLocal() } - if (turn.jobId) { + if (turn.jobId && !this.#config.follow) { // Needs `jobs:write` on a token; the stream is closed either way. await this.#api.cancelJob(turn.jobId).catch(() => {}) } @@ -577,6 +584,27 @@ class ChatImpl implements Chat { async #follow(turn: Turn, onStreamStart: () => void): Promise { let started = false + const { follow } = this.#config + if (follow) { + const { signal } = turn.controller + const parser = createStreamEventParser() + const onStream = (chunk: string) => { + if (signal.aborted) return + if (!started) { + started = true + onStreamStart() + } + this.#applyEvents(turn, parser.push(chunk)) + } + // A caller's follow may not honor the signal; the turn stops waiting on it either way. + const aborted = new Promise((_, reject) => { + if (signal.aborted) reject(abortError()) + signal.addEventListener('abort', () => reject(abortError()), { once: true }) + }) + const result = await Promise.race([follow(turn.jobId!, onStream, { signal }), aborted]) + this.#applyEvents(turn, parser.flush()) + return result + } for await (const event of followJob(this.#api, turn.jobId!, { signal: turn.controller.signal })) { if (event.type === 'completed') { if (event.streamLost) this.#dropCutRound(turn) @@ -722,8 +750,9 @@ class ChatImpl implements Chat { let messages = this.#state.messages let failed = false if (isErrorResult(result)) { - // The envelope is also a legitimate result shape; the job's own status decides. - failed = await this.#api + // The envelope is also a legitimate result shape; the job's own status decides, when it + // can be read. + failed = this.#config.follow ? true : await this.#api .getCompletedResult(turn.jobId!, turn.controller.signal) .then((r) => r.success === false) .catch(() => true) diff --git a/chat-sdk/src/config.ts b/chat-sdk/src/config.ts index 1903149d58..98cf97f2b2 100644 --- a/chat-sdk/src/config.ts +++ b/chat-sdk/src/config.ts @@ -1,4 +1,5 @@ import type { ChatOptions, FetchLike, HistoryMode, StorageLike, TokenSource } from './types' +import { rawAppRunnable } from './runnable' export interface ResolvedConfig { flowPath: string @@ -15,6 +16,7 @@ export interface ResolvedConfig { pageSize: number pollDelayMs: number | undefined run: ChatOptions['run'] + follow: ChatOptions['follow'] onFinish: ChatOptions['onFinish'] onError: ChatOptions['onError'] } @@ -51,13 +53,31 @@ export function detectRawApp(): RawAppContext | undefined { } export function resolveConfig(options: ChatOptions): ResolvedConfig { - if (!options.flowPath) throw new Error('windmill-chat: flowPath is required') + if (options.runnable !== undefined) { + if (!options.wmill) throw new Error('windmill-chat: `runnable` needs `wmill`, the app\'s generated module') + if (options.flowPath || options.run || options.follow) { + throw new Error('windmill-chat: `runnable` replaces `flowPath`, `run` and `follow`') + } + // Unsandboxed apps share their origin's storage, so the app's path keeps their histories apart. + const app = (globalThis as { ctx?: { path?: unknown } }).ctx?.path + options = { + ...options, + ...rawAppRunnable(options.wmill.backendAsync[options.runnable], options.wmill.streamJob), + flowPath: `runnable:${typeof app === 'string' ? `${app}:` : ''}${options.runnable}` + } + } + const follow = options.follow + if (follow && !options.run) throw new Error('windmill-chat: `follow` needs `run`, which starts the job it follows') + if (follow && options.history === 'server') { + throw new Error('windmill-chat: server history is read with the SDK\'s own requests, which `follow` replaces') + } + if (!options.flowPath && !follow) throw new Error('windmill-chat: flowPath is required') const explicitToken = options.token !== undefined const detected = options.baseUrl && options.workspace && explicitToken ? undefined : detectRawApp() const baseUrl = options.baseUrl ?? detected?.baseUrl const workspace = options.workspace ?? detected?.workspace - if (!baseUrl || !workspace) { + if ((!baseUrl || !workspace) && !follow) { throw new Error( 'windmill-chat: pass baseUrl and workspace. They are only detected inside a raw app: an unsandboxed one on the Windmill origin, or a sandboxed one whose policy declares frontend SDK scopes.' ) @@ -66,11 +86,11 @@ export function resolveConfig(options: ChatOptions): ResolvedConfig { const token = options.token ?? (options.baseUrl === undefined || options.baseUrl === detected?.baseUrl ? detected?.token : undefined) return { - flowPath: options.flowPath, - baseUrl, - workspace, + flowPath: options.flowPath ?? '', + baseUrl: baseUrl ?? '', + workspace: workspace ?? '', token, - history: options.history ?? (explicitToken ? 'local' : 'server'), + history: options.history ?? (explicitToken || follow ? 'local' : 'server'), historyExplicit: options.history !== undefined, inputs: options.inputs ?? {}, fetch: options.fetch, @@ -79,6 +99,7 @@ export function resolveConfig(options: ChatOptions): ResolvedConfig { pageSize: options.pageSize ?? 50, pollDelayMs: options.pollDelayMs, run: options.run, + follow, onFinish: options.onFinish, onError: options.onError } diff --git a/chat-sdk/src/index.ts b/chat-sdk/src/index.ts index a050edce37..d05a5ab217 100644 --- a/chat-sdk/src/index.ts +++ b/chat-sdk/src/index.ts @@ -31,6 +31,8 @@ export type { Conversation, FetchLike, HistoryMode, + RawAppWmill, + TypedChatOptions, SendMessageOptions, StorageLike, TokenSource, diff --git a/chat-sdk/src/react.ts b/chat-sdk/src/react.ts index c32324ee18..4159008ce7 100644 --- a/chat-sdk/src/react.ts +++ b/chat-sdk/src/react.ts @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react' import { createChat } from './chat' -import type { Chat, ChatOptions, ChatState } from './types' +import type { Chat, ChatOptions, ChatState, RawAppWmill, TypedChatOptions } from './types' export type UseWindmillChat = ChatState & Pick< @@ -19,22 +19,23 @@ export type UseWindmillChat = ChatState & /** * A chat on a chat-mode flow. The chat is created once per `flowPath`, `baseUrl`, - * `workspace`, `history`, `storageKey`, credential and presence of `run`, and + * `workspace`, `history`, `storageKey`, credential and presence of `run` and `follow`, and * destroyed on unmount. A credential change is a new user, whose chat must not * carry the previous one's state: a different token string, or a switch between no * token, a token string and a token function, all recreate it. A token function is * read through a ref on every call, so a new closure per render changes what the * next call runs and nothing else; pass a `storageKey` per user when local history - * must not be shared. `run`, the callbacks and `inputs` are read the same way: the + * must not be shared. `run`, `follow`, the callbacks and `inputs` are read the same way: the * latest render's values go with the next message. */ -export function useWindmillChat(options: ChatOptions): UseWindmillChat { - const latest = useRef(options) +export function useWindmillChat(options: TypedChatOptions): UseWindmillChat { + const latest = useRef(options) latest.current = options const credential = typeof options.token === 'function' ? 'fn' : typeof options.token === 'string' ? `str:${options.token}` : 'none' // A custom runner replaces the deployed flow call, so its presence is part of what the chat is. const customRun = options.run !== undefined + const customFollow = options.follow !== undefined const chat = useMemo( () => createChat({ @@ -49,11 +50,14 @@ export function useWindmillChat(options: ChatOptions): UseWindmillChat { } : options.token, run: customRun ? (args, turn) => (latest.current.run ?? options.run!)(args, turn) : undefined, + follow: customFollow + ? (jobId, onStream, turn) => (latest.current.follow ?? options.follow!)(jobId, onStream, turn) + : undefined, onFinish: (turn) => latest.current.onFinish?.(turn), onError: (error, turn) => latest.current.onError?.(error, turn) }), // eslint-disable-next-line react-hooks/exhaustive-deps - [options.flowPath, options.baseUrl, options.workspace, options.history, options.storageKey, credential, customRun] + [options.flowPath, options.runnable, options.wmill, options.baseUrl, options.workspace, options.history, options.storageKey, credential, customRun, customFollow] ) useEffect(() => () => chat.destroy(), [chat]) const state = useSyncExternalStore(chat.subscribe, chat.getState, chat.getState) diff --git a/chat-sdk/src/runnable.ts b/chat-sdk/src/runnable.ts new file mode 100644 index 0000000000..08ddf592e7 --- /dev/null +++ b/chat-sdk/src/runnable.ts @@ -0,0 +1,29 @@ +import { turnRunningError } from './api' +import type { ChatOptions } from './types' + +/** + * `run` and `follow` over a raw app's agent runnable (a path runnable of type `agent`, naming + * a saved AI agent), behind the `runnable` option. `memory_id` is the conversation id, the + * agent's memory key. + */ +export function rawAppRunnable( + // The generated signature is the runnable's own. + start: (args: any) => Promise, + streamJob: (jobId: string, onUpdate?: (update: { new_result_stream?: string }) => void) => Promise +): Required> { + return { + run: async (args, { conversationId }) => { + try { + return String(await start({ ...args, memory_id: conversationId })) + } catch (e) { + // The host relays the server's refusal as the error's text, possibly behind a stack. + const text = e instanceof Error ? e.message : String(e) + throw turnRunningError(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)) ?? e + } + }, + follow: (jobId, onStream) => + streamJob(jobId, (update) => { + if (update.new_result_stream) onStream(update.new_result_stream) + }) + } +} diff --git a/chat-sdk/src/types.ts b/chat-sdk/src/types.ts index 180238e50c..ad9f30cbfb 100644 --- a/chat-sdk/src/types.ts +++ b/chat-sdk/src/types.ts @@ -88,9 +88,33 @@ export type StorageLike = Pick export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise +/** A raw app's generated `wmill.ts`, as far as a chat uses it. */ +export interface RawAppWmill { + backendAsync: Record Promise> + streamJob: (jobId: string, onUpdate?: (update: { new_result_stream?: string }) => void) => Promise +} + +/** `ChatOptions` whose `runnable` must name one of `wmill`'s runnables. */ +export type TypedChatOptions = ChatOptions & { + wmill?: W + runnable?: keyof W['backendAsync'] & string +} + export interface ChatOptions { - /** Path of a deployed flow with chat mode enabled, e.g. `f/support/assistant`. */ - flowPath: string + /** + * Path of a deployed flow with chat mode enabled, e.g. `f/support/assistant`. Required + * unless `runnable` or `follow` is set, where it only names the local history. + */ + flowPath?: string + /** + * In a raw app, chat through its agent runnable of this name instead of a flow: + * `{ wmill, runnable: 'chat' }`. Each turn runs as the app, so a sandboxed app needs no + * frontend SDK scope and its viewers no access to the agent; the chat follows it as + * with `follow`. It also names the local history, so each runnable keeps its own. + */ + runnable?: string + /** The app's generated module, `import * as wmill from './wmill'`, which `runnable` goes through. */ + wmill?: RawAppWmill /** Windmill origin, e.g. `https://app.windmill.dev`. Detected inside a raw app. */ baseUrl?: string /** Detected inside a raw app. */ @@ -128,6 +152,15 @@ export interface ChatOptions { * Windmill's own editor uses this to chat with an undeployed flow through a preview run. */ run?: (args: Record, turn: { conversationId: string; signal: AbortSignal }) => Promise + /** + * Follows the job `run` returned through your own client instead of the SDK's requests: + * call `onStream` with each chunk of the job's result stream and resolve with its result. + * With it the chat makes no request of its own, so it needs no credential, `baseUrl` or + * `workspace`, and in exchange history is `local` (or `none`), `stop()` stops following + * without cancelling the job, and attachments are refused. `runnable` sets both for a raw + * app's agent runnable. + */ + follow?: (jobId: string, onStream: (chunk: string) => void, turn: { signal: AbortSignal }) => Promise /** Called once a turn has its answer (a failed flow included: its error is the answer). */ onFinish?: (turn: { conversationId: string; jobId?: string; messages: ChatMessage[] }) => void /** Called when a turn could not run or be followed; `state.error` holds the same error. */ diff --git a/chat-sdk/test/chat.test.ts b/chat-sdk/test/chat.test.ts index 3845c91ac7..6c88af5a36 100644 --- a/chat-sdk/test/chat.test.ts +++ b/chat-sdk/test/chat.test.ts @@ -1829,6 +1829,7 @@ describe('createChat with server history', () => { await chat.selectConversation(older) await new Promise((r) => setTimeout(r, 400)) const again = createChat(options({ token: 'tok', storage }, fetch)) + expect(again.getState().conversations.map((c) => c.id)).toEqual([newer, older]) expect((await again.loadConversations()).map((c) => c.id)).toEqual([newer, older]) }) diff --git a/chat-sdk/test/runnable.test.ts b/chat-sdk/test/runnable.test.ts new file mode 100644 index 0000000000..4dcaa60b84 --- /dev/null +++ b/chat-sdk/test/runnable.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from 'bun:test' +import { TurnRunningError } from '../src/api' +import { createChat } from '../src/chat' +import { memoryStorage, ndjson } from './support' + +describe('raw app agent runnable', () => { + test('chats through the runnable without a request of its own', async () => { + const calls: unknown[] = [] + let refuse = false + const start = async (args: unknown) => { + // As the host relays a 409: the server's body behind the error's stack. + if (refuse) { + const body = { error: 'still answering', running_turn: { job_id: 'job-1', user_seq: 1 } } + throw new Error(`Error: ${JSON.stringify(body)}\n at x`) + } + calls.push(args) + return `job-${calls.length}` + } + const streamJob = async (jobId: string, onUpdate?: (u: { new_result_stream?: string }) => void) => { + const stream = ndjson({ type: 'token_delta', content: 'answer ' }, { type: 'token_delta', content: jobId }) + onUpdate?.({ new_result_stream: stream.slice(0, 10) }) + onUpdate?.({ new_result_stream: stream.slice(10) }) + if (jobId === 'job-3') return { error: { name: 'Error', message: 'agent failed' } } + return { output: `answer ${jobId}`, messages: [] } + } + const storage = memoryStorage() + const wmill = { backendAsync: { chat: start, other: start }, streamJob } + const chat = createChat({ + wmill, + runnable: 'chat', + storage, + fetch: () => Promise.reject(new Error('no request expected')) + }) + expect(chat.getState().history).toBe('local') + await chat.sendMessage('hi') + await chat.sendMessage('again') + const conversationId = chat.getState().conversationId + expect(calls).toEqual([ + { user_message: 'hi', memory_id: conversationId }, + { user_message: 'again', memory_id: conversationId } + ]) + expect(chat.getState().messages.map((m) => m.content)).toEqual(['hi', 'answer job-1', 'again', 'answer job-2']) + + await chat.sendMessage('third') + const messages = chat.getState().messages + const last = messages[messages.length - 1] + expect([last.content, last.success]).toEqual(['agent failed', false]) + + // A turn still running elsewhere takes the message back rather than failing a turn. + refuse = true + await expect(chat.sendMessage('fourth')).rejects.toBeInstanceOf(TurnRunningError) + expect(chat.getState().messages).toEqual(messages) + + // Each runnable keeps its own history: another agent never sees this conversation. + expect(createChat({ wmill, runnable: 'chat', storage }).getState().conversations).toHaveLength(1) + expect(createChat({ wmill, runnable: 'other', storage }).getState().conversations).toEqual([]) + // Nor does the same runnable name in another app, whose path the host puts in `ctx`. + const g = globalThis as { ctx?: unknown } + g.ctx = { path: 'u/admin/other_app' } + try { + expect(createChat({ wmill, runnable: 'chat', storage }).getState().conversations).toEqual([]) + } finally { + delete g.ctx + } + // @ts-expect-error a name the app's module does not declare + createChat({ wmill, runnable: 'missing', storage }) + }) +}) diff --git a/cli/src/commands/app/dev.ts b/cli/src/commands/app/dev.ts index fbeba2914f..eb9bb055d6 100644 --- a/cli/src/commands/app/dev.ts +++ b/cli/src/commands/app/dev.ts @@ -1711,6 +1711,49 @@ export function buildWmillTs( return windmillUtils.genWmillTs(runnables); } +/** + * The inputs of an agent runnable, after the agent's memory (see the frontend's + * `agentRunnableSchema`): `memory_id` when it keeps managed memory, `previous_messages` when it + * is off, and neither for an older `manual` setting. + */ +function agentRunnableSchema(memory: any) { + const managed = + memory?.kind === "compaction" || + ((memory?.kind === "window" || memory?.kind === "auto") && + Boolean(memory.context_length)); + const legacy = memory?.kind === "manual"; + const history: Record = {}; + if (managed) { + history.memory_id = { + type: "string", + description: + "The conversation the message belongs to: reuse it to continue one, or omit it for a single run", + }; + } else if (!legacy) { + history.previous_messages = { + type: "array", + description: + "The history to answer from, as chat messages: this agent keeps no memory", + items: { type: "object" }, + }; + } + return { + $schema: "https://json-schema.org/draft/2020-12/schema", + type: "object", + properties: { + user_message: { type: "string", description: "The message to answer" }, + ...history, + user_attachments: { + type: "array", + description: "Files the message carries, as object storage references", + items: { type: "object", resourceType: "s3object" }, + }, + }, + required: ["user_message"], + order: ["user_message", ...Object.keys(history), "user_attachments"], + }; +} + /** * Fetches schemas from the Windmill API for path-based runnables (script / flow). * Returns a map of runnableId -> schema. Path-based runnables don't store their @@ -1741,6 +1784,12 @@ export async function fetchPathRunnableSchemas( path: runnable.path, }); if (script.schema) schemas[runnableId] = script.schema; + } else if (runnable.runType === "agent") { + const agent = await wmill.getResource({ + workspace: workspaceId, + path: runnable.path, + }); + schemas[runnableId] = agentRunnableSchema((agent.value as any)?.memory); } else if (runnable.runType === "flow") { const flow = await wmill.getFlowByPath({ workspace: workspaceId, @@ -1771,7 +1820,8 @@ function convertRunnablesToApiFormat(runnables: Record): void { if ( runnable?.type === "script" || runnable?.type === "hubscript" || - runnable?.type === "flow" + runnable?.type === "flow" || + runnable?.type === "agent" ) { // Convert from file format to API format // { type: "script" } -> { type: "path", runType: "script" } @@ -2029,9 +2079,11 @@ async function streamJobWithSSE( ws: WebSocket, baseUrl: string, token: string, + streamOffset?: number, ): Promise { const sseUrl = - `${baseUrl}api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?fast=true`; + `${baseUrl}api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?fast=true` + + (streamOffset !== undefined ? `&stream_offset=${streamOffset}` : ""); const extraHeaders = getHeaders(); const response = await fetch(sseUrl, { @@ -2057,6 +2109,7 @@ async function streamJobWithSSE( const decoder = new TextDecoder(); let buffer = ""; + let lastOffset = streamOffset; try { while (true) { @@ -2076,8 +2129,17 @@ async function streamJobWithSSE( if (type === "ping" || type === "timeout") { if (type === "timeout") { + // The server ends every stream after a while; the job goes on, so it is resumed. reader.cancel(); - return; + return streamJobWithSSE( + workspace, + jobId, + reqId, + ws, + baseUrl, + token, + lastOffset, + ); } continue; } @@ -2108,6 +2170,9 @@ async function streamJobWithSSE( return; } + if (update.stream_offset !== undefined) { + lastOffset = update.stream_offset; + } // Send stream update if there's new stream data if (update.new_result_stream !== undefined) { ws.send( diff --git a/cli/src/commands/app/metadata.ts b/cli/src/commands/app/metadata.ts index 1981949404..5f16e84220 100644 --- a/cli/src/commands/app/metadata.ts +++ b/cli/src/commands/app/metadata.ts @@ -14,7 +14,7 @@ export type Runnable = } | { type: "path" | "runnableByPath"; - runType: "script" | "hubscript" | "flow"; + runType: "script" | "hubscript" | "flow" | "agent"; path: string; fields?: Record; }; diff --git a/cli/src/commands/app/raw_apps.ts b/cli/src/commands/app/raw_apps.ts index ec526f2af2..570b03f949 100644 --- a/cli/src/commands/app/raw_apps.ts +++ b/cli/src/commands/app/raw_apps.ts @@ -230,7 +230,8 @@ export async function loadRunnablesFromBackend( } else if ( runnable?.type === "script" || runnable?.type === "hubscript" || - runnable?.type === "flow" + runnable?.type === "flow" || + runnable?.type === "agent" ) { // For path-based runnables, convert from file format to API format // { type: "script" } -> { type: "path", runType: "script" } diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 7d0cf5c1cc..d932957a20 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -6839,7 +6839,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`@windmill-labs/chat-sdk\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. @@ -6852,9 +6852,31 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) \`@windmill-labs/chat-sdk/ai-sdk\` gives a \`ChatTransport\` for the Vercel AI SDK's \`useChat\`, \`@windmill-labs/chat-sdk/assistant-ui\` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs \`jobs:run\` in its frontend SDK scopes, plus \`flow_conversations:write\` for the conversation sidebar; without them the chat keeps history in the browser. +#### A saved agent: an \`agent\` runnable + +Chat with a saved AI agent (an \`ai_agent\` resource) through an \`agent\` runnable, a path runnable whose \`path\` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not: + +In \`raw_app.yaml\`: + +\`\`\`yaml +runnables: + chat: + type: agent + path: f/support/agent +\`\`\` + +\`\`\`tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +\`\`\` + +\`runnable\` is the runnable's key; each runnable keeps its own conversations. The runnable takes \`user_message\` and \`memory_id\`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as \`backend.({ user_message })\` without \`memory_id\`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes \`previous_messages\` (chat messages) instead of \`memory_id\`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. \`chat.stop()\` stops following without cancelling the turn, and a message sent while it still runs is refused with \`TurnRunningError\`. Attachments are not supported this way. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -6862,6 +6884,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | \`script\` | Reference to an existing workspace script by path. | | \`flow\` | Reference to an existing workspace flow by path. | | \`hubscript\` | Reference to a hub script by path. | +| \`agent\` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -6903,9 +6926,9 @@ An inline runnable runs as an ordinary Windmill job. \`import * as wmill from 'w Use only \`wmill\` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (\`JobService\`, \`ScriptService\`, ...) are importable from \`windmill-client\`. What is not available is a name you guessed at: \`getBaseUrl\` and \`getWorkspaceToken\` are inventions, not API. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When \`type\` is \`script\`, \`flow\`, or \`hubscript\`, the runnable just stores a \`path\` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface. +When \`type\` is \`script\`, \`flow\`, \`hubscript\` or \`agent\`, the runnable just stores a \`path\` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is \`user_message\` and \`user_attachments\`, plus \`memory_id\` when the agent keeps managed memory or \`previous_messages\` when its memory is off. Before writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at \`hub///\`) for a third-party service, and reference it instead of copying its logic. @@ -6914,7 +6937,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed. -- **Path runnables (\`script\` / \`flow\` / \`hubscript\`) run the DEPLOYED item at that path.** So do \`wmill.runFlow\`, \`wmill.runFlowAsync\` and \`wmill.runScriptByPath\` called from inside a runnable. A draft — including a draft you just created — does not exist for them. +- **Path runnables (\`script\` / \`flow\` / \`hubscript\` / \`agent\`) run the DEPLOYED item at that path.** So do \`wmill.runFlow\`, \`wmill.runFlowAsync\` and \`wmill.runScriptByPath\` called from inside a runnable. A draft — including a draft you just created — does not exist for them. So an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed. @@ -7024,7 +7047,7 @@ def main(user_id: str): 7. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an \`agent\` runnable passed as \`{ wmill, runnable }\`. `, "triggers": `--- name: triggers diff --git a/docs/operator-builder-rights.md b/docs/operator-builder-rights.md index 44a012131f..8445fa0dde 100644 --- a/docs/operator-builder-rights.md +++ b/docs/operator-builder-rights.md @@ -66,7 +66,8 @@ resolves the runnable it runs on the root handle, so `validate_operator_composed referenced path under the caller's RLS and refuses hub ones. For a script it checks the version a run would pick: grants are per version, and a path reused after its versions were archived starts with none while the archived ones keep theirs. But it has to check **two** surfaces, -because they are not the same list: the policy's `script/` and `flow/` triggerables, +because they are not the same list: the policy's `script/`, `flow/` and +`agent/` triggerables (an agent is checked as an `ai_agent` resource the caller can read), and the by-path entries of the app value's `runnables` map, which is what the editor resolves a `runnable_id` against and sends. Read only that map, and refuse an entry whose `type`, `path` or `runType` is not text. @@ -77,8 +78,8 @@ at run time for `component = "a:b"`. Every colon is a possible split, so the che suffix that parses as a runnable rather than guessing which one a request will use. What makes those checks bind is that **`ExecutionMode::Viewer` is refused for a builder app**. In -Viewer mode `execute_component` falls back to a default triggerable for any `script/`/`flow/` -path, so the policy stops being the list of what the app may invoke, and the job runs as the +Viewer mode `execute_component` falls back to a default triggerable for any `script/`/`flow/`/ +`agent/` path, so the policy stops being the list of what the app may invoke, and the job runs as the *viewer*: an admin who merely opened the app would run anything in the workspace as themselves. `Publisher`, `Guest` and `Anonymous` have no such fallback; all three run as the publisher. If you ever relax the Viewer refusal, the deploy-time path checks above stop being an authorization boundary. diff --git a/frontend/src/lib/components/DeployWorkspace.svelte b/frontend/src/lib/components/DeployWorkspace.svelte index daf944ff37..4c7fae7ccd 100644 --- a/frontend/src/lib/components/DeployWorkspace.svelte +++ b/frontend/src/lib/components/DeployWorkspace.svelte @@ -283,6 +283,8 @@ result.push({ kind: 'script', path: runnable.path }) } else if (runnable.runType == 'flow') { result.push({ kind: 'flow', path: runnable.path }) + } else if (runnable.runType == 'agent') { + result.push({ kind: 'resource', path: runnable.path }) } } } diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte index b7521372f8..ff15d6a4fc 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte @@ -101,14 +101,14 @@ - +
    - + {#if !composeOnlyApps} - + {/if}
    diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte index 02f4524830..e3552d0e79 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte @@ -2,7 +2,7 @@ import { createBubbler, stopPropagation } from 'svelte/legacy' const bubble = createBubbler() - import { Button, Drawer, DrawerContent } from '$lib/components/common' + import { Alert, Button, Drawer, DrawerContent } from '$lib/components/common' import FlowGraphViewer from '$lib/components/FlowGraphViewer.svelte' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import FlowModuleScript from '$lib/components/flows/content/FlowModuleScript.svelte' @@ -32,7 +32,11 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import ScriptEditorDrawer from '$lib/components/flows/content/ScriptEditorDrawer.svelte' import FlowEditorDrawer from '$lib/components/flows/content/FlowEditorDrawer.svelte' - import { FlowService, ScriptService, type OpenFlow } from '$lib/gen' + import { FlowService, ResourceService, ScriptService, type OpenFlow } from '$lib/gen' + import Badge from '$lib/components/common/badge/Badge.svelte' + import { summarizeAgentBrain, type AgentTool } from '$lib/components/flows/agentResourceUtils' + import { agentRunnableSchema } from '$lib/components/raw_apps/agentRunnable' + import { agentMemoryMode } from '$lib/components/flows/agentFormFields' import { replaceScriptPlaceholderWithItsValues } from '$lib/hub' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -149,6 +153,47 @@ } } + let agentInfo: + | { + description?: string + rows: { label: string; value: string }[] + tools: string[] + memoryOff: boolean + } + | undefined = $state() + + async function refreshAgent(runnable: RunnableByPath) { + hubFlowPreview = undefined + try { + const agent = await ResourceService.getResource({ + workspace: $operatingWorkspace ?? '', + path: runnable.path + }) + const config = agent.value as any + agentInfo = { + description: agent.description ?? undefined, + rows: summarizeAgentBrain(config), + tools: ((config?.tools ?? []) as AgentTool[]).map( + (t) => t.summary || t.value?.tool_type || t.id + ), + memoryOff: agentMemoryMode(config?.memory) === 'off' + } + const schema = agentRunnableSchema(config?.memory) + if (!deepEqual(runnable.schema, schema)) runnable.schema = schema + // Every input of a turn comes from its caller: a static one would be pinned by the + // deployed policy, answering every viewer's message with the same one. + if ( + Object.values(fields ?? {}).some((f) => f?.type !== 'user') || + !deepEqual(Object.keys(fields ?? {}).sort(), Object.keys(schema.properties).sort()) + ) { + fields = computeFields(schema, true, {}) + } + } catch (e) { + notFound = true + console.error(e) + } + } + async function fork(path: string) { let { content, language, schema } = await getScriptByPath(path) if (!schema || typeof schema == 'string' || Object.keys(schema).length == 0) { @@ -205,6 +250,8 @@ refreshScript(runnable) } else if (runnable.runType == 'flow') { refreshFlow(runnable) + } else if (runnable.runType == 'agent') { + refreshAgent(runnable) } else { hubFlowPreview = undefined } @@ -352,6 +399,17 @@ Details {/if} + {:else if runnable.runType == 'agent'} + {:else} - {/snippet} - {#snippet content()} - {#if runnable.runType == 'flow' && isHubFlowPath(runnable.path)} - Since this is a reference to a hub flow, cache settings are managed from the flow after - you fork it into your workspace. - {:else} - Since this is a reference to a workspace {runnable.runType}, set the cache in the - {runnable.runType} settings directly by editing it. The cache will be shared by any app or - flow that uses this {runnable.runType}. - {/if} - {/snippet} - + {#if runnable.runType != 'agent'} + + {#snippet trigger()} + + {/snippet} + {#snippet content()} + {#if runnable.runType == 'flow' && isHubFlowPath(runnable.path)} + Since this is a reference to a hub flow, cache settings are managed from the flow after + you fork it into your workspace. + {:else} + Since this is a reference to a workspace {runnable.runType}, set the cache in the + {runnable.runType} settings directly by editing it. The cache will be shared by any app or + flow that uses this {runnable.runType}. + {/if} + {/snippet} + + {/if} {/if} + {:else if runnable.runType == 'agent'} +
    + {#if agentInfo?.memoryOff} + + Each call is answered on its own inputs, so a chat would forget every turn. Pass + previous_messages to give it the history. + + {/if} + {#if agentInfo?.description} +

    {agentInfo.description}

    + {/if} +
    + {#each agentInfo?.rows ?? [] as row (row.label)} +
    +
    {row.label}
    +
    {row.value}
    +
    + {/each} + {#if agentInfo?.tools.length} +
    +
    Tools
    +
    + {#each agentInfo.tools as tool, i (i)} + {tool} + {/each} +
    +
    + {/if} +
    +
    {:else} Unrecognized runType {runnable.runType} {/if} diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte index 5845965198..f741f5511d 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte @@ -2,11 +2,17 @@ import { Button, Drawer, DrawerContent, Tab, Tabs } from '$lib/components/common' import PickHubScript from '$lib/components/flows/pickers/PickHubScript.svelte' import PickHubFlow from '$lib/components/flows/pickers/PickHubFlow.svelte' - import { Building, Globe2, MousePointer, Plus } from 'lucide-svelte' + import { Bot, Building, Globe2, MousePointer, Plus } from 'lucide-svelte' import InlineScriptList from './InlineScriptList.svelte' - import type { InlineScript, Runnable, StaticAppInput } from '$lib/components/apps/inputType' + import type { + InlineScript, + PathRunType, + Runnable, + StaticAppInput + } from '$lib/components/apps/inputType' import WorkspaceScriptList from './WorkspaceScriptList.svelte' import WorkspaceFlowList from './WorkspaceFlowList.svelte' + import WorkspaceAgentList from './WorkspaceAgentList.svelte' import { createEventDispatcher, untrack } from 'svelte' import type { Schema } from '$lib/common' import { emptySchema } from '$lib/utils' @@ -18,7 +24,13 @@ const roleCaps = useRoleCapabilities() import { buildPathRunnableSelection } from './runnableSelectorUtils' - type TabType = 'hubscripts' | 'hubflows' | 'workspacescripts' | 'workspaceflows' | 'inlinescripts' + type TabType = + | 'hubscripts' + | 'hubflows' + | 'workspacescripts' + | 'workspaceflows' + | 'workspaceagents' + | 'inlinescripts' interface Props { defaultUserInput?: boolean @@ -47,6 +59,13 @@ ) let filter: string = $state('') let picker: Drawer | undefined = $state() + const selectLabel = $derived( + onlyFlow + ? 'Select a flow' + : rawApps + ? 'Select a script, flow or agent' + : 'Select a script or flow' + ) const dispatch = createEventDispatcher<{ pick: { @@ -57,7 +76,7 @@ async function loadSchemaFromTriggerable( path: string, - runType: 'script' | 'flow' | 'hubscript' + runType: PathRunType ): Promise<{ schema: Schema; summary: string | undefined }> { const schema = await loadSchema($operatingWorkspace!, path, runType) if (!schema.schema.order) { @@ -94,6 +113,20 @@ }) } + async function pickAgent(path: string) { + const selection = buildPathRunnableSelection( + path, + 'agent', + await loadSchemaFromTriggerable(path, 'agent'), + defaultUserInput, + rawApps + ) + dispatch('pick', { + runnable: selection.runnable, + fields: selection.fields + }) + } + async function pickHubScript(path: string) { const selection = buildPathRunnableSelection( path, @@ -154,22 +187,25 @@ - +
    {#if !onlyFlow} {#if !rawApps} - + {/if} - + + {/if} + + {#if rawApps && !onlyFlow} + {/if} - {#if $roleCaps.apps !== 'compose'} {#if !onlyFlow} - + {/if} - + {/if}
    @@ -186,6 +222,8 @@ pickScript(e.detail)} /> {:else if tab == 'workspaceflows'} pickFlow(e.detail)} /> + {:else if tab == 'workspaceagents'} + pickAgent(e.detail)} /> {:else if tab == 'hubscripts'} pickHubScript(e.detail.path)} /> {:else if tab == 'hubflows'} @@ -218,6 +256,6 @@ startIcon={{ icon: MousePointer }} btnClasses="truncate w-full" > - {#if onlyFlow}Select a flow{:else}Select a script or flow{/if} + {selectLabel}
    diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceAgentList.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceAgentList.svelte new file mode 100644 index 0000000000..4335fedaf8 --- /dev/null +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceAgentList.svelte @@ -0,0 +1,83 @@ + + + (emptyString(x.description) ? x.path : x.description + ' (' + x.path + ')')} +/> +
    + e.stopPropagation() + }} + /> +
    + +{#if agents} + {#if filteredItems.length == 0} + + {:else} +
      + {#each filteredItems as item (item)} +
    • + +
    • + {/each} +
    + {/if} +{:else} + {#each Array(10).fill(0) as _} + + {/each} +{/if} diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts index 44e989e925..66eb1e21cf 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/runnableSelectorUtils.ts @@ -1,5 +1,5 @@ import type { Schema } from '$lib/common' -import type { Runnable, StaticAppInput } from '$lib/components/apps/inputType' +import type { PathRunType, Runnable, StaticAppInput } from '$lib/components/apps/inputType' import { schemaToInputsSpec } from '$lib/components/apps/utils' import { defaultIfEmptyString } from '$lib/utils' @@ -10,7 +10,7 @@ export type LoadedRunnableSchema = { export function buildPathRunnableSelection( path: string, - runType: 'script' | 'flow' | 'hubscript', + runType: PathRunType, loadedSchema: LoadedRunnableSchema, defaultUserInput: boolean, rawApps: boolean diff --git a/frontend/src/lib/components/apps/inputType.ts b/frontend/src/lib/components/apps/inputType.ts index 8501372216..99aa5d8418 100644 --- a/frontend/src/lib/components/apps/inputType.ts +++ b/frontend/src/lib/components/apps/inputType.ts @@ -136,11 +136,14 @@ export type TemplateV2Input = { connections: InputConnectionEval[] } +/** `agent` (a saved AI agent run as one chat turn) exists in raw apps only. */ +export type PathRunType = 'script' | 'flow' | 'hubscript' | 'agent' + export type RunnableByPath = { name: string path: string schema: any - runType: 'script' | 'flow' | 'hubscript' + runType: PathRunType type: 'runnableByPath' | 'path' } diff --git a/frontend/src/lib/components/copilot/chat/app/core.ts b/frontend/src/lib/components/copilot/chat/app/core.ts index 166df65a16..5a0ff5cc6d 100644 --- a/frontend/src/lib/components/copilot/chat/app/core.ts +++ b/frontend/src/lib/components/copilot/chat/app/core.ts @@ -22,7 +22,7 @@ import { appDatatableRole, sdkDatatableCall } from '$lib/components/raw_apps/dat import { RAW_APP_BASE } from '$system_prompts' // Backend runnable types -export type BackendRunnableType = 'script' | 'flow' | 'hubscript' | 'inline' +export type BackendRunnableType = 'script' | 'flow' | 'hubscript' | 'agent' | 'inline' export interface InlineScript { language: 'bun' | 'python3' @@ -311,9 +311,9 @@ const getSetBackendRunnableSchema = memo(() => ), name: z.string().describe('A short summary/description of what the runnable does'), type: z - .enum(['script', 'flow', 'hubscript', 'inline']) + .enum(['script', 'flow', 'hubscript', 'agent', 'inline']) .describe( - 'The type of runnable: "inline" for custom code, "script" for workspace script, "flow" for workspace flow, "hubscript" for hub script' + 'The type of runnable: "inline" for custom code, "script" for workspace script, "flow" for workspace flow, "hubscript" for hub script, "agent" for a saved AI agent (one chat turn)' ), staticInputs: z .record(z.string(), z.any()) @@ -328,7 +328,7 @@ const getSetBackendRunnableSchema = memo(() => .string() .optional() .describe( - 'Required when type is "script", "flow", or "hubscript". The fully qualified path to the workspace script/flow or hub script.' + 'Required when type is "script", "flow", "hubscript" or "agent". The fully qualified path to the workspace script/flow, hub script or AI agent.' ), viewerDataAccess: z .boolean() @@ -723,6 +723,11 @@ export const getAppTools = memo((): Tool[] => [ } const parsedArgs = getSetBackendRunnableSchema().parse(cleanedArgs) + if (parsedArgs.type === 'agent' && Object.keys(parsedArgs.staticInputs ?? {}).length > 0) { + const errorMsg = `An "agent" runnable takes no staticInputs: each turn's inputs come from the app.` + toolCallbacks.setToolStatus(toolId, { content: errorMsg, error: errorMsg }) + return errorMsg + } toolCallbacks.setToolStatus(toolId, { content: `Setting backend runnable '${parsedArgs.key}'...` }) @@ -1087,6 +1092,16 @@ When creating a backend runnable with \`set_backend_runnable\`: } \`\`\` +5. **For saved AI agents** (type: "agent"), one chat turn per call, taking \`user_message\` and either \`memory_id\` (the conversation id, for an agent with managed memory) or \`previous_messages\` (the history, for one whose memory is off); no staticInputs: + \`\`\` + { + key: "chat", + name: "Chat with the support agent", + type: "agent", + path: "f/support/agent" + } + \`\`\` + ## Instructions 1. Use the smallest context needed. If the target file or runnable is clear, inspect only that item with \`get_frontend_file(path)\` or \`get_backend_runnable(key)\`. diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index 546459cee2..61bdea9dc9 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -2548,6 +2548,38 @@ describe('global AI tools', () => { expect(asPath.inlineScript).toBeUndefined() }) + // A static input is pinned by the deployed policy: carried into an agent runnable, it would + // replace every viewer's message. + it('drops inherited static inputs when a runnable becomes an agent', async () => { + seedBackendDraft( + 'raw_app', + 'u/admin/agent_conv_app', + { summary: 'Converted', files: {}, runnables: {}, data: { tables: [] } }, + { workspace: WORKSPACE } + ) + await callGlobalTool('write_app_runnable', { + path: 'u/admin/agent_conv_app', + key: 'chat', + runnable: { + name: 'Run the flow', + type: 'flow', + path: 'u/admin/hello_flow', + staticInputs: { user_message: 'pinned' } + } + }) + await callGlobalTool('write_app_runnable', { + path: 'u/admin/agent_conv_app', + key: 'chat', + runnable: { name: 'Chat', type: 'agent', path: 'u/admin/assistant' } + }) + + const asAgent = getBackendDraft('raw_app', 'u/admin/agent_conv_app', { + workspace: WORKSPACE + }).runnables.chat + expect(asAgent.runType).toBe('agent') + expect(asAgent.fields).toEqual({}) + }) + it("resets a path runnable's schema when it is retargeted, and keeps it when it is not", async () => { // The editor populates `schema` from the item the runnable points at, and // genWmillTs types `backend.(args)` from it — so it must not outlive the target. diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 03356a51f0..66af4ab332 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -180,7 +180,7 @@ import { fileTools } from '../files/fileTools' import type { AttachedFilesStore } from '../files/attachedFiles.svelte' import { artifactTools } from '../artifacts/artifactTools' import type { SessionArtifactsStore } from '../artifacts/artifactsState.svelte' -import type { Runnable } from '$lib/components/apps/inputType' +import type { PathRunType, Runnable } from '$lib/components/apps/inputType' import { UserDraft } from '$lib/userDraft.svelte' import { emptySchema } from '$lib/utils' import type { Schema } from '$lib/common' @@ -1076,9 +1076,9 @@ const backendRunnableSchema = z .object({ name: z.string().describe('Short summary/description of what the runnable does.'), type: z - .enum(['inline', 'script', 'flow', 'hubscript']) + .enum(['inline', 'script', 'flow', 'hubscript', 'agent']) .describe( - 'Runnable kind: "inline" for custom code stored on the app; "script"/"flow" for a workspace runnable; "hubscript" for a hub script.' + 'Runnable kind: "inline" for custom code stored on the app; "script"/"flow" for a workspace runnable; "hubscript" for a hub script; "agent" for a saved AI agent, run as one chat turn.' ), staticInputs: z .record(z.string(), z.any()) @@ -1097,7 +1097,7 @@ const backendRunnableSchema = z .string() .optional() .describe( - 'Required when type is "script", "flow", or "hubscript". Workspace path of the runnable.' + 'Required when type is "script", "flow", "hubscript" or "agent". Workspace path of the runnable.' ), viewerDataAccess: z .boolean() @@ -2008,7 +2008,7 @@ type BackendRunnableInput = z.infer type PersistedRunnable = { name: string type: 'inline' | 'path' | 'runnableByName' | 'runnableByPath' - runType?: 'script' | 'flow' | 'hubscript' + runType?: PathRunType path?: string inlineScript?: { language: string; content: string } fields?: Record @@ -2041,6 +2041,7 @@ function convertPersistedToBackendRunnable( } else if (persisted.type === 'path' || persisted.type === 'runnableByPath') { if (persisted.runType === 'flow') out.type = 'flow' else if (persisted.runType === 'hubscript') out.type = 'hubscript' + else if (persisted.runType === 'agent') out.type = 'agent' else out.type = 'script' out.path = persisted.path } @@ -2062,14 +2063,19 @@ function buildPersistedRunnable( input: BackendRunnableInput, existing: PersistedRunnable | undefined ): PersistedRunnable { - const fields = input.staticInputs - ? Object.fromEntries( - Object.entries(input.staticInputs).map(([k, v]) => [ - k, - { type: 'static', value: v, fieldType: 'object' } - ]) - ) - : (existing?.fields ?? {}) + // An agent runnable takes every input from the app: a static one inherited from the kind it was + // converted from would be pinned by the deployed policy over every viewer's message. + const fields = + input.type === 'agent' + ? {} + : input.staticInputs + ? Object.fromEntries( + Object.entries(input.staticInputs).map(([k, v]) => [ + k, + { type: 'static', value: v, fieldType: 'object' } + ]) + ) + : (existing?.fields ?? {}) // Converting between kinds must drop the other kind's fields. Every consumer dispatches on // `type` (isRunnableByName / isRunnableByPath), so a leftover does not change which code @@ -2110,7 +2116,15 @@ function buildPersistedRunnable( } if (!input.path) { - throw new Error('path is required when runnable type is "script", "flow", or "hubscript".') + throw new Error( + 'path is required when runnable type is "script", "flow", "hubscript" or "agent".' + ) + } + // A static input is pinned by the deployed policy: every viewer's turn would send the same one. + if (input.type === 'agent' && Object.keys(input.staticInputs ?? {}).length > 0) { + throw new Error( + 'An "agent" runnable takes no staticInputs: each turn\'s inputs come from the app.' + ) } return { ...carried, @@ -9425,9 +9439,16 @@ async function undeployedRunnableTargets( ? runnable?.runType : runnable?.type const path = runnable?.path - if ((type !== 'script' && type !== 'flow') || !path) continue + if ((type !== 'script' && type !== 'flow' && type !== 'agent') || !path) continue try { - if (await deployedItemExists(workspace, type, path, undefined)) continue + if (type === 'agent') { + // A saved agent is an `ai_agent` resource; another resource at the path runs nothing. + const found = await ResourceService.getResource({ workspace, path }).catch((e) => { + if ((e as { status?: number } | null | undefined)?.status === 404) return undefined + throw e + }) + if (found?.resource_type === 'ai_agent') continue + } else if (await deployedItemExists(workspace, type, path, undefined)) continue } catch { // The probe is advisory: a lookup failure must never block the write or // the deploy it annotates. diff --git a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte index b902b69bfa..cdec419e5a 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte @@ -47,7 +47,8 @@ AGENT_EDITOR_RUN_INPUTS, AGENT_TOOLS_ROW, DEFAULT_AGENT_MEMORY, - keepsManagedMemory + keepsManagedMemory, + agentMemoryMode } from '../agentFormFields' import { toolDisplayName, type AgentTool } from '../agentToolUtils' import { useAgentDraft, type AgentRunAs } from '../agentDraft.svelte' @@ -243,6 +244,23 @@ // apart from the echo of their own write. let lastArgs = $state(undefined) + // With memory off a run keeps no history of its own, so the form also takes the one to answer + // from; managed memory and an older setting would ignore one. + let formSchema = $derived( + agentMemoryMode((agentValue?.input_transforms?.memory as any)?.value) !== 'off' + ? AGENT_CHAT_SCHEMA + : { + ...AGENT_CHAT_SCHEMA, + properties: { + ...AGENT_CHAT_SCHEMA.properties, + previous_messages: { + type: 'array', + items: { type: 'object' }, + description: 'The conversation so far, as chat messages, for the agent to answer from' + } + } + } + ) // Picked on the first load, after which it is the reader's: following the memory setting live // would pull them out of a chat for switching memory off in the form. let testMode = $state<'form' | 'chat' | undefined>(undefined) @@ -603,7 +621,7 @@
    {@render viewForm?.({ - schema: AGENT_CHAT_SCHEMA, + schema: formSchema, run: runOnce, loading: runLoading, actions: onOpenConfig ? configurationButton : undefined diff --git a/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte b/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte index 8c07ad1506..ff926c0c5d 100644 --- a/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte +++ b/frontend/src/lib/components/flows/pickers/PickHubFlow.svelte @@ -60,7 +60,7 @@ {@render children?.()} + import { onDestroy } from 'svelte' import { executeRunnable } from '../apps/components/helpers/executeRunnable' import { userStore } from '$lib/stores' import { waitJob } from '../waitJob' @@ -54,6 +55,9 @@ // Job ids launched by this app instance — see `gateJobIds`. const launchedJobs = new Set() + // A stream resumed on every server timeout would otherwise outlive the app it answers. + let destroyed = false + onDestroy(() => (destroyed = true)) /** For a host that loads this component after the bundle may already have sent requests. */ export function handleMessage(event: MessageEvent) { @@ -124,48 +128,64 @@ args[key] = `$ctx:${field.ctx}` } } - const uuid = await executeRunnable( - runnable, - workspace, - undefined, - $userStore?.username, - path, - runnable_id, - { - component: runnable_id, - args, - force_viewer_allow_user_resources: editor - ? undefinedIfEmpty( - Object.keys(runnable?.fields ?? {}).filter( - (k) => - runnable?.fields?.[k]?.type == 'user' && - runnable?.fields?.[k]?.allowUserResources + let uuid: string + try { + uuid = await executeRunnable( + runnable, + workspace, + undefined, + $userStore?.username, + path, + runnable_id, + { + component: runnable_id, + args, + force_viewer_allow_user_resources: editor + ? undefinedIfEmpty( + Object.keys(runnable?.fields ?? {}).filter( + (k) => + runnable?.fields?.[k]?.type == 'user' && + runnable?.fields?.[k]?.allowUserResources + ) ) - ) - : undefined, - force_viewer_one_of_fields: undefined, - force_viewer_static_fields: editor - ? Object.fromEntries( - Object.entries(runnable?.fields ?? {}) - .filter(([k, v]) => v.type == 'static') - .map(([k, v]) => [k, v?.['value']]) - ) - : undefined, - force_viewer_sensitive_inputs: editor - ? undefinedIfEmpty( - Object.keys(runnable?.fields ?? {}).filter( - (k) => runnable?.fields?.[k]?.type == 'user' && runnable?.fields?.[k]?.sensitive + : undefined, + force_viewer_one_of_fields: undefined, + force_viewer_static_fields: editor + ? Object.fromEntries( + Object.entries(runnable?.fields ?? {}) + .filter(([k, v]) => v.type == 'static') + .map(([k, v]) => [k, v?.['value']]) ) - ) - : undefined, - force_viewer_delete_after_secs: editor ? runnable?.delete_after_secs : undefined, - on_behalf_of: editor ? previewOnBehalfOf : undefined, - viewer_data_access: editor ? runnable?.viewer_data_access || undefined : undefined - }, - undefined, - undefined, - editor ? rawAppPreviewModules(runnables, runnable_id) : undefined - ) + : undefined, + force_viewer_sensitive_inputs: editor + ? undefinedIfEmpty( + Object.keys(runnable?.fields ?? {}).filter( + (k) => + runnable?.fields?.[k]?.type == 'user' && runnable?.fields?.[k]?.sensitive + ) + ) + : undefined, + force_viewer_delete_after_secs: editor ? runnable?.delete_after_secs : undefined, + on_behalf_of: editor ? previewOnBehalfOf : undefined, + viewer_data_access: editor ? runnable?.viewer_data_access || undefined : undefined + }, + undefined, + undefined, + editor ? rawAppPreviewModules(runnables, runnable_id) : undefined + ) + } catch (e) { + // A run refused before it started still answers the app, which would otherwise + // wait for ever; the refusal's body says why (a 409 names the turn still running). + const body = (e as { body?: unknown })?.body + const message = + typeof body === 'string' + ? body + : body + ? JSON.stringify(body) + : String((e as Error)?.message ?? e) + respond({ result: { message }, error: true }) + return + } launchedJobs.add(uuid) let job: JobById = { component: runnable_id, created_at: Date.now(), job: uuid } if (data.type == 'backendAsync') { @@ -209,97 +229,105 @@ ) return } - const params = new URLSearchParams() - params.set('fast', 'true') - params.set('only_result', 'true') + let lastOffset: number | undefined + const connect = (streamOffset?: number) => { + const params = new URLSearchParams() + params.set('fast', 'true') + params.set('only_result', 'true') + if (streamOffset !== undefined) params.set('stream_offset', String(streamOffset)) - const sseUrl = `/api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?${params.toString()}` - const eventSource = new EventSource(sseUrl) + const sseUrl = `/api/w/${workspace}/jobs_u/getupdate_sse/${jobId}?${params.toString()}` + const eventSource = new EventSource(sseUrl) - eventSource.onmessage = (sseEvent) => { - try { - const update = JSON.parse(sseEvent.data) - const type = update.type + eventSource.onmessage = (sseEvent) => { + try { + const update = JSON.parse(sseEvent.data) + const type = update.type - if (type === 'ping' || type === 'timeout') { - if (type === 'timeout') { - eventSource.close() + if (type === 'ping' || type === 'timeout') { + if (type === 'timeout') { + // The server ends every stream after a while; the job goes on, so it is resumed. + eventSource.close() + if (!destroyed) connect(lastOffset) + } + return } - return - } - if (type === 'error') { - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: true, - result: { message: update.error || 'SSE error' } - }, - '*' - ) - return - } + if (type === 'error') { + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: true, + result: { message: update.error || 'SSE error' } + }, + '*' + ) + return + } - if (type === 'not_found') { - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: true, - result: { message: 'Job not found' } - }, - '*' - ) - return - } + if (type === 'not_found') { + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: true, + result: { message: 'Job not found' } + }, + '*' + ) + return + } - // Send stream update if there's new stream data - if (update.new_result_stream !== undefined) { - sourceWindow?.postMessage( - { - type: 'streamJobUpdate', - reqId, - new_result_stream: update.new_result_stream, - stream_offset: update.stream_offset - }, - '*' - ) - } + // Send stream update if there's new stream data + if (update.stream_offset !== undefined) lastOffset = update.stream_offset + if (update.new_result_stream !== undefined) { + sourceWindow?.postMessage( + { + type: 'streamJobUpdate', + reqId, + new_result_stream: update.new_result_stream, + stream_offset: update.stream_offset + }, + '*' + ) + } - // Check if job is completed - if (update.completed) { - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: false, - result: update.only_result - }, - '*' - ) + // Check if job is completed + if (update.completed) { + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: false, + result: update.only_result + }, + '*' + ) + } + } catch (parseErr) { + console.warn('Failed to parse SSE data:', parseErr) } - } catch (parseErr) { - console.warn('Failed to parse SSE data:', parseErr) + } + + eventSource.onerror = (error) => { + console.warn('SSE stream error:', error) + eventSource.close() + sourceWindow?.postMessage( + { + type: 'streamJobRes', + reqId, + error: true, + result: { message: 'SSE connection error' } + }, + '*' + ) } } - - eventSource.onerror = (error) => { - console.warn('SSE stream error:', error) - eventSource.close() - sourceWindow?.postMessage( - { - type: 'streamJobRes', - reqId, - error: true, - result: { message: 'SSE connection error' } - }, - '*' - ) - } + connect() } } diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index eec6fc3b0e..3d22087317 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -40,7 +40,7 @@ import { getAppliedDarkModeVariant, type DarkModeVariant } from '$lib/darkModeVariant' import RawAppSidebar from './RawAppSidebar.svelte' import type { Modules } from './RawAppModules.svelte' - import { isRunnableByName, isRunnableByPath } from '../apps/inputType' + import { isRunnableByName, isRunnableByPath, type PathRunType } from '../apps/inputType' import { aiChatManager, AIMode } from '../copilot/chat/AIChatManager.svelte' import { onMount, onDestroy, untrack } from 'svelte' import type { @@ -917,6 +917,8 @@ addEventListener('message', function (e) { backendRunnable.type = 'flow' } else if (runnable.runType === 'hubscript') { backendRunnable.type = 'hubscript' + } else if (runnable.runType === 'agent') { + backendRunnable.type = 'agent' } else { backendRunnable.type = 'script' } @@ -1230,7 +1232,7 @@ addEventListener('message', function (e) { runnables[key] = { name: runnable.name, type: 'path', - runType: runnable.type as 'script' | 'flow' | 'hubscript', + runType: runnable.type as PathRunType, path: runnable.path, fields: runnable.staticInputs ? Object.fromEntries( @@ -1861,7 +1863,7 @@ addEventListener('message', function (e) { // 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 }) + return $state.snapshot({ ctx: operatingUser.current, workspace: opWorkspace, path }) } // A build fed before the viewer is known keeps that viewer until the next one. Outside diff --git a/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte b/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte index 86b2ea57ed..71a3dae951 100644 --- a/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte @@ -21,7 +21,7 @@ import SchemaForm from '../SchemaForm.svelte' import RunnableJobPanelInner from '../apps/editor/RunnableJobPanelInner.svelte' import JobLoader from '../JobLoader.svelte' - import { FlowService, type Job, type OpenFlow, type ScriptLang } from '$lib/gen' + import { FlowService, JobService, type Job, type OpenFlow, type ScriptLang } from '$lib/gen' import { getScriptByPath } from '$lib/scripts' import { slide } from 'svelte/transition' import { DebugToolbar, DebugPanel, debugState } from '$lib/components/debug' @@ -224,6 +224,22 @@ } else { await jobLoader.runFlowByPath(runnable.path, args) } + } else if (runnable.runType == 'agent') { + // A turn of the agent as it is deployed, as the editor: the direct run has no way + // to ask for the app's identity. + const path = runnable.path + const { user_message, memory_id, user_attachments, previous_messages } = args as Record< + string, + any + > + await jobLoader.abstractRun(() => + JobService.runAgent({ + workspace: opWs!, + path, + memoryId: memory_id || undefined, + requestBody: { user_message, user_attachments, previous_messages } + }) + ) } else if (runnable.runType == 'script' || runnable.runType == 'hubscript') { if (previewOnBehalfOf) { const script = await getScriptByPath(runnable.path, opWs) diff --git a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte index 36c3fb360c..1c82cdcd33 100644 --- a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte @@ -134,7 +134,7 @@ const html = unsandboxedRawAppHtml( workspace, secret, - { ctx: u, workspace }, + { ctx: u, workspace, path }, window.location.origin, pageHash() ) @@ -207,7 +207,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 }, + ctx: { ctx: $state.snapshot(user), workspace, path }, initialHash, storage: { local: bundleStorage ?? {}, session: {} }, // The wrapper turns this into `window.process.env` before it injects the diff --git a/frontend/src/lib/components/raw_apps/agentRunnable.ts b/frontend/src/lib/components/raw_apps/agentRunnable.ts new file mode 100644 index 0000000000..cca1964197 --- /dev/null +++ b/frontend/src/lib/components/raw_apps/agentRunnable.ts @@ -0,0 +1,43 @@ +import type { Schema, SchemaProperty } from '$lib/common' +import { agentMemoryMode, keepsManagedMemory } from '$lib/components/flows/agentFormFields' + +/** + * The inputs of a raw app's agent runnable, after the agent's memory as its own page reads it: a + * chat (`memory_id`, the conversation and memory key) when it keeps managed memory, single runs + * answered from the history the app passes (`previous_messages`) when it is off, and neither for an + * older `manual` setting (`memory_id` is the run's, which an older `auto` one keeps memory under). + * The server accepts both either way (see `execute_component`), so a schema gone stale only + * mistypes the inputs. + */ +export function agentRunnableSchema(memory: unknown): Schema { + const history: Record = {} + if (keepsManagedMemory(memory)) { + history.memory_id = { + type: 'string', + description: + 'The conversation the message belongs to: reuse it to continue one, or omit it for a single run' + } + } + if (agentMemoryMode(memory) === 'off') { + history.previous_messages = { + type: 'array', + description: 'The history to answer from, as chat messages: this agent keeps no memory', + items: { type: 'object' } + } + } + return { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties: { + user_message: { type: 'string', description: 'The message to answer' }, + ...history, + user_attachments: { + type: 'array', + description: 'Files the message carries, as object storage references', + items: { type: 'object', resourceType: 's3object' } + } + }, + required: ['user_message'], + order: ['user_message', ...Object.keys(history), 'user_attachments'] + } +} diff --git a/frontend/src/lib/components/workspaceSettings/projectBundle.ts b/frontend/src/lib/components/workspaceSettings/projectBundle.ts index 8adedeb559..047f7ee7fa 100644 --- a/frontend/src/lib/components/workspaceSettings/projectBundle.ts +++ b/frontend/src/lib/components/workspaceSettings/projectBundle.ts @@ -148,6 +148,8 @@ function runnableRef(node: Record): Ref | undefined { if (!isRunnableByPath(node as any) || typeof node.path !== 'string') return undefined if (node.runType === 'flow') return { kind: 'flow', path: node.path } if (node.runType === 'script') return { kind: 'script', path: node.path } + // A saved agent is an `ai_agent` resource. + if (node.runType === 'agent') return { kind: 'resource', path: node.path } return undefined // hubscript -> external hub, ignored } diff --git a/frontend/src/lib/infer.ts b/frontend/src/lib/infer.ts index 9e9cddeb00..3c1d30bc87 100644 --- a/frontend/src/lib/infer.ts +++ b/frontend/src/lib/infer.ts @@ -1,11 +1,14 @@ import { ScriptService, + ResourceService, type MainArgSignature, FlowService, type Script, type AssetUsageAccessType } from '$lib/gen' import { get, writable } from 'svelte/store' +import type { PathRunType } from './components/apps/inputType.js' +import { agentRunnableSchema } from './components/raw_apps/agentRunnable.js' import type { Schema, SupportedLanguage } from './common.js' import { type DynamicInput, @@ -658,9 +661,15 @@ async function inferSchemaIfNecessary(script: Script) { export async function loadSchema( workspace: string, path: string, - runType: 'script' | 'flow' | 'hubscript' + runType: PathRunType ): Promise<{ schema: Schema; summary: string | undefined }> { - if (runType === 'script') { + if (runType === 'agent') { + const agent = await ResourceService.getResource({ workspace, path }) + return { + schema: agentRunnableSchema((agent.value as any)?.memory), + summary: agent.description || undefined + } + } else if (runType === 'script') { const script = await ScriptService.getScriptByPath({ workspace, path diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 5b8c3cbe8c..b97fc5c3d9 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1054,7 +1054,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`@windmill-labs/chat-sdk\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. @@ -1067,9 +1067,26 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) \`@windmill-labs/chat-sdk/ai-sdk\` gives a \`ChatTransport\` for the Vercel AI SDK's \`useChat\`, \`@windmill-labs/chat-sdk/assistant-ui\` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs \`jobs:run\` in its frontend SDK scopes, plus \`flow_conversations:write\` for the conversation sidebar; without them the chat keeps history in the browser. +#### A saved agent: an \`agent\` runnable + +Chat with a saved AI agent (an \`ai_agent\` resource) through an \`agent\` runnable, a path runnable whose \`path\` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not: + +\`\`\`json +{ "chat": { "type": "agent", "path": "f/support/agent" } } +\`\`\` + +\`\`\`tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +\`\`\` + +\`runnable\` is the runnable's key; each runnable keeps its own conversations. The runnable takes \`user_message\` and \`memory_id\`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as \`backend.({ user_message })\` without \`memory_id\`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes \`previous_messages\` (chat messages) instead of \`memory_id\`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. \`chat.stop()\` stops following without cancelling the turn, and a message sent while it still runs is refused with \`TurnRunningError\`. Attachments are not supported this way. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -1077,6 +1094,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | \`script\` | Reference to an existing workspace script by path. | | \`flow\` | Reference to an existing workspace flow by path. | | \`hubscript\` | Reference to a hub script by path. | +| \`agent\` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -1117,9 +1135,9 @@ An inline runnable runs as an ordinary Windmill job. \`import * as wmill from 'w Use only \`wmill\` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (\`JobService\`, \`ScriptService\`, ...) are importable from \`windmill-client\`. What is not available is a name you guessed at: \`getBaseUrl\` and \`getWorkspaceToken\` are inventions, not API. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When \`type\` is \`script\`, \`flow\`, or \`hubscript\`, the runnable just stores a \`path\` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface. +When \`type\` is \`script\`, \`flow\`, \`hubscript\` or \`agent\`, the runnable just stores a \`path\` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is \`user_message\` and \`user_attachments\`, plus \`memory_id\` when the agent keeps managed memory or \`previous_messages\` when its memory is off. Before writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at \`hub///\`) for a third-party service, and reference it instead of copying its logic. @@ -1128,7 +1146,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed. -- **Path runnables (\`script\` / \`flow\` / \`hubscript\`) run the DEPLOYED item at that path.** So do \`wmill.runFlow\`, \`wmill.runFlowAsync\` and \`wmill.runScriptByPath\` called from inside a runnable. A draft — including a draft you just created — does not exist for them. +- **Path runnables (\`script\` / \`flow\` / \`hubscript\` / \`agent\`) run the DEPLOYED item at that path.** So do \`wmill.runFlow\`, \`wmill.runFlowAsync\` and \`wmill.runScriptByPath\` called from inside a runnable. A draft — including a draft you just created — does not exist for them. So an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed. @@ -1227,7 +1245,7 @@ def main(user_id: str): 7. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an \`agent\` runnable passed as \`{ wmill, runnable }\`. `; export const PIPELINE_BASE = `# Data pipeline authoring diff --git a/system_prompts/auto-generated/skills/raw-app/SKILL.md b/system_prompts/auto-generated/skills/raw-app/SKILL.md index df5e7ece6a..f45b85402d 100644 --- a/system_prompts/auto-generated/skills/raw-app/SKILL.md +++ b/system_prompts/auto-generated/skills/raw-app/SKILL.md @@ -380,7 +380,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential. @@ -393,9 +393,31 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) `@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser. +#### A saved agent: an `agent` runnable + +Chat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not: + +In `raw_app.yaml`: + +```yaml +runnables: + chat: + type: agent + path: f/support/agent +``` + +```tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +``` + +`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -403,6 +425,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | `script` | Reference to an existing workspace script by path. | | `flow` | Reference to an existing workspace flow by path. | | `hubscript` | Reference to a hub script by path. | +| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -444,9 +467,9 @@ An inline runnable runs as an ordinary Windmill job. `import * as wmill from 'wi Use only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When `type` is `script`, `flow`, or `hubscript`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface. +When `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off. Before writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub///`) for a third-party service, and reference it instead of copying its logic. @@ -455,7 +478,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed. -- **Path runnables (`script` / `flow` / `hubscript`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them. +- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them. So an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed. @@ -565,4 +588,4 @@ def main(user_id: str): 7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`. diff --git a/system_prompts/base/raw-app.md b/system_prompts/base/raw-app.md index dc70d0b94d..69c03594db 100644 --- a/system_prompts/base/raw-app.md +++ b/system_prompts/base/raw-app.md @@ -139,7 +139,7 @@ An app can be demoed by recording a session: every interaction becomes a step ca Apply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded. -### Chat UIs over a flow in chat mode +### Chat UIs over a flow in chat mode or a saved agent A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential. @@ -152,9 +152,38 @@ const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) `@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser. +#### A saved agent: an `agent` runnable + +Chat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not: + + +In `raw_app.yaml`: + +```yaml +runnables: + chat: + type: agent + path: f/support/agent +``` + + +```json +{ "chat": { "type": "agent", "path": "f/support/agent" } } +``` + + +```tsx +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' +import * as wmill from './wmill' + +const chat = useWindmillChat({ wmill, runnable: 'chat' }) +``` + +`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way. + ## Backend runnables -Each runnable has a unique key (used to call it from the frontend) and one of four types: +Each runnable has a unique key (used to call it from the frontend) and one of five types: | Type | What it is | |---|---| @@ -162,6 +191,7 @@ Each runnable has a unique key (used to call it from the frontend) and one of fo | `script` | Reference to an existing workspace script by path. | | `flow` | Reference to an existing workspace flow by path. | | `hubscript` | Reference to a hub script by path. | +| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). | ### Inline runnables @@ -205,9 +235,9 @@ An inline runnable runs as an ordinary Windmill job. `import * as wmill from 'wi Use only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API. -### Path runnables (script / flow / hubscript) +### Path runnables (script / flow / hubscript / agent) -When `type` is `script`, `flow`, or `hubscript`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface. +When `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off. Before writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub///`) for a third-party service, and reference it instead of copying its logic. @@ -216,7 +246,7 @@ Before writing an inline runnable, look for a workspace script or flow that alre This decides whether an app works before anything is deployed: - **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed. -- **Path runnables (`script` / `flow` / `hubscript`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them. +- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them. So an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed. @@ -345,4 +375,4 @@ def main(user_id: str): 7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`. From ca13eb225a1c8d6be2439fea7096abcd71d26deb Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 22 Oct 2026 23:29:21 +0200 Subject: [PATCH 047/101] chore: upgrade bun to 1.4.4 (#11961) Co-authored-by: Claude Opus 5.5 --- .github/DockerfileBackendTests | 2 +- .github/workflows/ai-agent-tests.yml | 2 +- .github/workflows/ai-evals-scheduled.yml | 4 ++-- .github/workflows/ai-evals-test.yml | 2 +- .github/workflows/backend-test-windows.yml | 2 +- .github/workflows/backend-test.yml | 2 +- .github/workflows/git-sync-test.yml | 2 +- Dockerfile | 2 +- debugger/Dockerfile | 2 +- docker/DockerfileSlim | 2 +- docker/DockerfileSlimEe | 2 +- 11 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/DockerfileBackendTests b/.github/DockerfileBackendTests index 0ece318198..e41a7bbff9 100644 --- a/.github/DockerfileBackendTests +++ b/.github/DockerfileBackendTests @@ -42,7 +42,7 @@ RUN wget https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VER RUN /usr/local/bin/python3 -m pip install pip-tools # Bun -COPY --from=oven/bun:1.4.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI RUN bun install -g windmill-cli \ diff --git a/.github/workflows/ai-agent-tests.yml b/.github/workflows/ai-agent-tests.yml index 8a3e9e6dbc..255f07e253 100644 --- a/.github/workflows/ai-agent-tests.yml +++ b/.github/workflows/ai-agent-tests.yml @@ -61,7 +61,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/ai-evals-scheduled.yml b/.github/workflows/ai-evals-scheduled.yml index 580a757c21..2bd8cdb181 100644 --- a/.github/workflows/ai-evals-scheduled.yml +++ b/.github/workflows/ai-evals-scheduled.yml @@ -46,7 +46,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - id: matrix env: @@ -93,7 +93,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/ai-evals-test.yml b/.github/workflows/ai-evals-test.yml index 84b488ae46..4dd266c364 100644 --- a/.github/workflows/ai-evals-test.yml +++ b/.github/workflows/ai-evals-test.yml @@ -75,7 +75,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/backend-test-windows.yml b/.github/workflows/backend-test-windows.yml index f926a7c153..8bbb73d379 100644 --- a/.github/workflows/backend-test-windows.yml +++ b/.github/workflows/backend-test-windows.yml @@ -73,7 +73,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/backend-test.yml b/.github/workflows/backend-test.yml index 0018c37144..f2dedd8c69 100644 --- a/.github/workflows/backend-test.yml +++ b/.github/workflows/backend-test.yml @@ -58,7 +58,7 @@ jobs: go-version: 1.21.5 - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: actions/setup-node@v7 with: node-version: "24" diff --git a/.github/workflows/git-sync-test.yml b/.github/workflows/git-sync-test.yml index b19f899a20..7d26392dee 100644 --- a/.github/workflows/git-sync-test.yml +++ b/.github/workflows/git-sync-test.yml @@ -135,7 +135,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.4.0 + bun-version: 1.4.4 - uses: denoland/setup-deno@v2 with: diff --git a/Dockerfile b/Dockerfile index ef37868d0d..ad3a79a2b6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -293,7 +293,7 @@ COPY --from=builder /windmill/target/release/windmill ${APP}/windmill # DuckDB jobs run in this binary, which the worker looks for next to its own. COPY --from=windmill_duckdb_ffi_internal_builder /windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner ${APP}/windmill_duckdb_runner -COPY --from=oven/bun:1.4.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI RUN bun install -g windmill-cli \ diff --git a/debugger/Dockerfile b/debugger/Dockerfile index 6b423920a0..be30570425 100644 --- a/debugger/Dockerfile +++ b/debugger/Dockerfile @@ -19,7 +19,7 @@ FROM ghcr.io/windmill-labs/windmill-ee:main AS windmill-source # Stage 2: Build the debug service -FROM oven/bun:1.4.0 AS runtime +FROM oven/bun:1.4.4 AS runtime # Install Python and required system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ diff --git a/docker/DockerfileSlim b/docker/DockerfileSlim index 9e3908e2a9..0a1e5a0c42 100644 --- a/docker/DockerfileSlim +++ b/docker/DockerfileSlim @@ -77,7 +77,7 @@ RUN mkdir -p /tmp/windmill/cache && \ rm -rf /tmp/build_cache && \ mkdir -p -m 777 /tmp/windmill/cache/uv -COPY --from=oven/bun:1.4.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI (node symlink needed for bun install) RUN ln -s /usr/bin/bun /usr/bin/node \ diff --git a/docker/DockerfileSlimEe b/docker/DockerfileSlimEe index b933823103..46d0d2d98f 100644 --- a/docker/DockerfileSlimEe +++ b/docker/DockerfileSlimEe @@ -77,7 +77,7 @@ RUN mkdir -p /tmp/windmill/cache && \ rm -rf /tmp/build_cache && \ mkdir -p -m 777 /tmp/windmill/cache/uv -COPY --from=oven/bun:1.4.0 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI (node symlink needed for bun install) RUN ln -s /usr/bin/bun /usr/bin/node \ From 8a7b1481bd270df3a98c9db5e7824d13b8cd37b6 Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:32:08 +0200 Subject: [PATCH 048/101] fix: compare a null resource description as empty (#11947) --- .../tests/workspace_comparison.rs | 65 +++++++++++++++++++ .../windmill-api-workspaces/src/workspaces.rs | 10 ++- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs index 1aa2bc8df2..a8ab80c7b7 100644 --- a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs +++ b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs @@ -2570,3 +2570,68 @@ async fn test_rename_records_the_vacated_path(db: Pool) -> anyhow::Res Ok(()) } + +/// Regression: a resource or resource type can be stored with a NULL description while deploy +/// writes "", so the comparison must read the two as equal or the item never settles. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_compare_null_description_equals_empty(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base_url = format!("http://localhost:{port}/api"); + let client = windmill_api_client::create_client( + &format!("http://localhost:{port}"), + "SECRET_TOKEN".to_string(), + ); + + for q in [ + "INSERT INTO workspace (id, name, owner, parent_workspace_id) + VALUES ('wm-fork-test-workspace', 'Fork', 'test-user', 'test-workspace')", + "INSERT INTO workspace_settings (workspace_id) VALUES ('wm-fork-test-workspace')", + "INSERT INTO workspace_key(workspace_id, kind, key) + VALUES ('wm-fork-test-workspace', 'cloud', 'test-key')", + "INSERT INTO resource (workspace_id, path, value, resource_type, description, created_by) VALUES + ('test-workspace', 'u/test-user/null_desc', '{}', 'generic', NULL, 'test-user'), + ('wm-fork-test-workspace', 'u/test-user/null_desc', '{}', 'generic', '', 'test-user'), + ('test-workspace', 'u/test-user/other_desc', '{}', 'generic', NULL, 'test-user'), + ('wm-fork-test-workspace', 'u/test-user/other_desc', '{}', 'generic', 'x', 'test-user')", + "INSERT INTO resource_type (workspace_id, name, schema, description, created_by) VALUES + ('test-workspace', 'null_desc_rt', '{}', NULL, 'test-user'), + ('wm-fork-test-workspace', 'null_desc_rt', '{}', '', 'test-user'), + ('test-workspace', 'other_desc_rt', '{}', NULL, 'test-user'), + ('wm-fork-test-workspace', 'other_desc_rt', '{}', 'x', 'test-user')", + "INSERT INTO workspace_diff + (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes) VALUES + ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/null_desc', 'resource', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/other_desc', 'resource', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'null_desc_rt', 'resource_type', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'other_desc_rt', 'resource_type', 1, 1, NULL)", + ] { + sqlx::query(q).execute(&db).await?; + } + + let comparison: serde_json::Value = client + .client() + .get(&format!( + "{base_url}/w/test-workspace/workspaces/compare/wm-fork-test-workspace" + )) + .send() + .await? + .json() + .await?; + let mut paths: Vec<&str> = comparison["diffs"] + .as_array() + .unwrap_or_else(|| panic!("no diffs: {comparison}")) + .iter() + .map(|d| d["path"].as_str().unwrap()) + .collect(); + paths.sort(); + assert_eq!( + paths, + ["other_desc_rt", "u/test-user/other_desc"], + "{comparison}" + ); + + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 3d3a52739e..ac1d0d1300 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -14372,6 +14372,12 @@ async fn compare_two_apps( }); } +// Resources and resource types can be stored with a NULL description, but deploy writes "", +// so the two must compare equal or the item never settles after a deploy. +fn description_differs(a: &Option, b: &Option) -> bool { + a.as_deref().unwrap_or("") != b.as_deref().unwrap_or("") +} + async fn compare_two_resources( db: &DB, source_workspace_id: &str, @@ -14440,7 +14446,7 @@ async fn compare_two_resources( source.value != target.value }; if values_differ - || source.description != target.description + || description_differs(&source.description, &target.description) || source.resource_type != target.resource_type { has_changes = true; @@ -14568,7 +14574,7 @@ async fn compare_two_resource_types( // Check metadata differences if let (Some(source), Some(target)) = (&source_resource_type, &target_resource_type) { if source.schema != target.schema - || source.description != target.description + || description_differs(&source.description, &target.description) || source.format_extension != target.format_extension || source.is_fileset != target.is_fileset { From 0dd131b38074423de5c769cae478c6ea0ae365c2 Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:50:32 +0200 Subject: [PATCH 049/101] fix: compare fork secret variables by decrypted value (#11952) * fix: compare fork secret variables by decrypted value * test: restore MIN_VERSION even when the secret compare test fails * fix: re-evaluate cached variable diffs once after the secret compare fix * refactor: decrypt already-loaded secret rows when comparing variables * docs: state the authorization contract of decrypt_secret_value * fix: compare external-backend secrets by their resolved values --------- Co-authored-by: Ruben Fiszel --- ...29ac1a2714b78cc88969604dbd6c44984831f.json | 12 ++ ...666e83c6ccdea5087eb194d1de17086c58952.json | 12 ++ ...83cbaf7676cbed2f0c3a433699578da88e8ae.json | 20 ++++ ...t_cached_variable_workspace_diffs.down.sql | 1 + ...set_cached_variable_workspace_diffs.up.sql | 3 + .../tests/workspace_comparison.rs | 111 ++++++++++++++++++ .../windmill-api-workspaces/src/workspaces.rs | 25 +++- backend/windmill-common/src/variables.rs | 44 +++---- 8 files changed, 202 insertions(+), 26 deletions(-) create mode 100644 backend/.sqlx/query-e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f.json create mode 100644 backend/.sqlx/query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json create mode 100644 backend/.sqlx/query-ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae.json create mode 100644 backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.down.sql create mode 100644 backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.up.sql diff --git a/backend/.sqlx/query-e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f.json b/backend/.sqlx/query-e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f.json new file mode 100644 index 0000000000..90a3f9c7f2 --- /dev/null +++ b/backend/.sqlx/query-e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM workspace_diff WHERE fork_workspace_id = 'wm-fork-secrets'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "e1d7ca4dfbc5eeb6eb60e48a13029ac1a2714b78cc88969604dbd6c44984831f" +} diff --git a/backend/.sqlx/query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json b/backend/.sqlx/query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json new file mode 100644 index 0000000000..c9507b7f22 --- /dev/null +++ b/backend/.sqlx/query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_diff\n (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes)\n VALUES\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/same', 'variable', 1, 1, NULL),\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL)", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952" +} diff --git a/backend/.sqlx/query-ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae.json b/backend/.sqlx/query-ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae.json new file mode 100644 index 0000000000..db600a495e --- /dev/null +++ b/backend/.sqlx/query-ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(DISTINCT value) FROM variable WHERE path = 'u/test-user/same'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "ecd08125821a21842bad7d328ea83cbaf7676cbed2f0c3a433699578da88e8ae" +} diff --git a/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.down.sql b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.down.sql new file mode 100644 index 0000000000..d2f607c5b8 --- /dev/null +++ b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.down.sql @@ -0,0 +1 @@ +-- Add down migration script here diff --git a/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.up.sql b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.up.sql new file mode 100644 index 0000000000..c531389793 --- /dev/null +++ b/backend/migrations/20261022163514_reset_cached_variable_workspace_diffs.up.sql @@ -0,0 +1,3 @@ +-- Secrets compared by ciphertext were cached as changed even when both sides held the same value, +-- and a cached verdict is trusted until the next write. Re-evaluate every variable row once. +UPDATE workspace_diff SET has_changes = NULL WHERE kind = 'variable'; diff --git a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs index a8ab80c7b7..c3cb9ff190 100644 --- a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs +++ b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs @@ -2635,3 +2635,114 @@ async fn test_compare_null_description_equals_empty(db: Pool) -> anyho Ok(()) } + +/// Runs its closure when dropped, so process-wide state is put back even when an assertion +/// fails. +struct OnDrop(F); +impl Drop for OnDrop { + fn drop(&mut self) { + (self.0)() + } +} + +/// Secrets are encrypted with a fresh nonce on every write, so a secret holding the same value on +/// both sides must compare by plaintext, not ciphertext. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_compare_secret_variables_by_value(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let client = windmill_api_client::create_client( + &format!("http://localhost:{port}"), + "SECRET_TOKEN".to_string(), + ); + let base_url = format!("http://localhost:{port}/api"); + + let resp = client + .client() + .post(&format!( + "{base_url}/w/test-workspace/workspaces/create_fork" + )) + .json(&json!({ "id": "wm-fork-secrets", "name": "Secrets Fork" })) + .send() + .await?; + assert!( + resp.status().is_success(), + "fork creation failed: {}", + resp.status() + ); + + // Secrets are written in CBC, which is deterministic, until every worker reads AES-GCM. + use windmill_common::min_version::{MIN_VERSION, MIN_VERSION_SUPPORTS_AEAD_SECRETS}; + let before = MIN_VERSION.load_full(); + let _restore = OnDrop(move || MIN_VERSION.store(before.clone())); + MIN_VERSION.store(std::sync::Arc::new( + MIN_VERSION_SUPPORTS_AEAD_SECRETS.version().clone(), + )); + + for (ws, path, value) in [ + ("test-workspace", "u/test-user/same", "s3cret"), + ("wm-fork-secrets", "u/test-user/same", "s3cret"), + ("test-workspace", "u/test-user/different", "one"), + ("wm-fork-secrets", "u/test-user/different", "two"), + ] { + let resp = client + .client() + .post(&format!("{base_url}/w/{ws}/variables/create")) + .json(&json!({ "path": path, "value": value, "is_secret": true, "description": "" })) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + } + let stored = sqlx::query_scalar!( + "SELECT COUNT(DISTINCT value) FROM variable WHERE path = 'u/test-user/same'" + ) + .fetch_one(&db) + .await?; + assert_eq!( + stored, + Some(2), + "the same secret must be stored as two different ciphertexts" + ); + + sqlx::query!("DELETE FROM workspace_diff WHERE fork_workspace_id = 'wm-fork-secrets'") + .execute(&db) + .await?; + sqlx::query!( + "INSERT INTO workspace_diff + (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes) + VALUES + ('test-workspace', 'wm-fork-secrets', 'u/test-user/same', 'variable', 1, 1, NULL), + ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL)" + ) + .execute(&db) + .await?; + + let comparison: serde_json::Value = client + .client() + .get(&format!( + "{base_url}/w/test-workspace/workspaces/compare/wm-fork-secrets" + )) + .send() + .await? + .json() + .await?; + let diffs = comparison["diffs"].as_array().unwrap(); + let listed = |path: &str| { + diffs + .iter() + .any(|d| d["path"] == path && d["kind"] == "variable") + }; + + assert!( + !listed("u/test-user/same"), + "equal secrets must compare as unchanged: {comparison}" + ); + assert!( + listed("u/test-user/different"), + "different secrets must compare as changed: {comparison}" + ); + + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index ac1d0d1300..e2027c3e9b 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -39,7 +39,7 @@ use windmill_common::global_settings::HTTP_ROUTE_WORKSPACED_ROUTE; use windmill_common::query_builders::{render_db_quoted_identifier, DbType}; use windmill_common::users::username_to_permissioned_as; use windmill_common::variables::{ - crypt_from_key_with_suffix, decrypt, encrypt, WORKSPACE_CRYPT_CACHE, + crypt_from_key_with_suffix, decrypt, decrypt_secret_value, encrypt, WORKSPACE_CRYPT_CACHE, }; use windmill_common::worker::{to_raw_value, CLOUD_HOSTED}; use windmill_common::workspaces::GitRepositorySettings; @@ -76,7 +76,9 @@ use hyper::StatusCode; use serde::{Deserialize, Serialize}; use sqlx::{FromRow, Postgres, Row, Transaction}; use windmill_common::oauth2::InstanceEvent; -use windmill_common::secret_backend::{get_secret_backend, is_vault_backend_configured}; +use windmill_common::secret_backend::{ + get_secret_backend, is_external_stored_value, is_vault_backend_configured, +}; use windmill_common::utils::not_found_if_none; lazy_static::lazy_static! { @@ -14524,11 +14526,22 @@ async fn compare_two_variables( // Check metadata differences if let (Some(source), Some(target)) = (&source_variable, &target_variable) { - if source.is_secret != target.is_secret - || source.value != target.value - || source.description != target.description - { + if source.is_secret != target.is_secret || source.description != target.description { has_changes = true; + } else if source.value != target.value + || (source.is_secret && is_external_stored_value(&source.value)) + { + // A secret's ciphertext is randomized on every write, so equal secrets are compared + // by plaintext, each decrypted with its own workspace's key. An external backend + // reference is the same text on both sides but names a per-workspace entry. + has_changes = !source.is_secret + || !matches!( + tokio::try_join!( + decrypt_secret_value(db, source_workspace_id, path, source.value.clone()), + decrypt_secret_value(db, fork_workspace_id, path, target.value.clone()), + ), + Ok((a, b)) if a == b + ); } } else if source_variable.is_some() || target_variable.is_some() { // The variable exists in one of source or target, but not the other, this is considered as a change diff --git a/backend/windmill-common/src/variables.rs b/backend/windmill-common/src/variables.rs index 82039d71f5..512bd555f0 100644 --- a/backend/windmill-common/src/variables.rs +++ b/backend/windmill-common/src/variables.rs @@ -465,28 +465,32 @@ pub async fn get_secret_value_as_admin( ))); }; - let r = if variable.is_secret { - let value = variable.value; - if !value.is_empty() { - if is_external_stored_value(&value) { - get_secret_value(db, w_id, &variable.path, &value).await? - } else { - let mc = build_crypt(db, w_id).await?; - decrypt(&mc, value).map_err(|e| { - crate::error::Error::internal_err(format!( - "Error decrypting variable {}: {}", - variable.path, e - )) - })? - } - } else { - "".to_string() - } + if variable.is_secret { + decrypt_secret_value(db, w_id, &variable.path, variable.value).await } else { - variable.value - }; + Ok(variable.value) + } +} - Ok(r) +/// Plaintext of a secret variable's stored `value`, read from the external secret backend when it +/// holds a reference to one. Bypasses variable permissions: callers MUST have authorized the +/// reader before returning the plaintext to them. +pub async fn decrypt_secret_value( + db: &DB, + w_id: &str, + path: &str, + value: String, +) -> crate::error::Result { + if value.is_empty() { + Ok(value) + } else if is_external_stored_value(&value) { + get_secret_value(db, w_id, path, &value).await + } else { + let mc = build_crypt(db, w_id).await?; + decrypt(&mc, value).map_err(|e| { + crate::error::Error::internal_err(format!("Error decrypting variable {}: {}", path, e)) + }) + } } /// Marks a workspace setting's secret written into the settings document encrypted with the From 8a0318a28f5cfda7557b0f94db20ef17b0664ee4 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Fri, 23 Oct 2026 00:47:12 +0200 Subject: [PATCH 050/101] feat: worker group toggle to keep the worker's proxy out of jobs (#11958) * feat: worker group setting to strip env vars from the nsjail sandbox Co-Authored-By: Claude Opus 5.5 * fix: apply the nsjail env denylist to profile envar directives too Co-Authored-By: Claude Opus 5.5 * refactor: drop the nsjail env denylist spawn hook Co-Authored-By: Claude Opus 5.5 * feat: replace the nsjail env denylist with a worker group toggle for the job proxy Co-Authored-By: Claude Opus 5.5 * fix: honor the job proxy toggle in duckdb and drop the env var fallback Co-Authored-By: Claude Opus 5.5 * fix: pre-install duckdb extensions with the proxy when jobs run without it Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to 5cfc0dc6760ea7f631fc98ea1edd39adfc55bf11 This commit updates the EE repository reference after PR #914 was merged in windmill-ee-private. Previous ee-repo-ref: 8394f2d1b67765ba854205836185342e62df841e New ee-repo-ref: 5cfc0dc6760ea7f631fc98ea1edd39adfc55bf11 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- backend/src/monitor.rs | 1 + backend/windmill-api-configs/src/lib.rs | 6 +- .../windmill-common/src/instance_config.rs | 2 + backend/windmill-common/src/worker.rs | 10 ++- .../windmill-worker/src/ansible_executor.rs | 2 +- backend/windmill-worker/src/dbt_executor.rs | 7 +- backend/windmill-worker/src/duckdb_runner.rs | 77 +++++++++++-------- backend/windmill-worker/src/java_executor.rs | 12 +-- backend/windmill-worker/src/pwsh_executor.rs | 4 +- backend/windmill-worker/src/r_executor.rs | 8 +- backend/windmill-worker/src/ruby_executor.rs | 12 ++- backend/windmill-worker/src/worker.rs | 25 ++++-- .../src/lib/components/WorkerGroup.svelte | 27 +++++++ 14 files changed, 141 insertions(+), 54 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 669983e362..f8c8a245eb 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -06b2eb32cd7d40fd93078285d8b6150648384602 +5cfc0dc6760ea7f631fc98ea1edd39adfc55bf11 diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 827c092529..fbadfa4269 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -441,6 +441,7 @@ pub async fn initial_load( cache_clear: None, additional_python_paths: None, pip_local_dependencies: None, + disable_job_proxy: false, native_mode, // an agent worker never reads its group's config, only its token object_store_cache_config: None, diff --git a/backend/windmill-api-configs/src/lib.rs b/backend/windmill-api-configs/src/lib.rs index 890a561679..cfa74bd2f0 100644 --- a/backend/windmill-api-configs/src/lib.rs +++ b/backend/windmill-api-configs/src/lib.rs @@ -224,13 +224,15 @@ async fn update_config( #[cfg(not(feature = "enterprise"))] let config = if name.starts_with("worker__") { - // In CE, only allow setting worker_tags, cache_clear, init_bash, native_mode and paused + // In CE, only allow setting worker_tags, cache_clear, init_bash, native_mode, paused and + // disable_job_proxy serde_json::json!({ "worker_tags": config.get("worker_tags"), "cache_clear": config.get("cache_clear"), "init_bash": config.get("init_bash"), "native_mode": config.get("native_mode"), - "paused": config.get("paused") + "paused": config.get("paused"), + "disable_job_proxy": config.get("disable_job_proxy") }) } else { config diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index b90645c2b9..9fe43e0fe0 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -1006,6 +1006,8 @@ pub struct WorkerGroupConfig { #[serde(skip_serializing_if = "Option::is_none")] pub env_vars_allowlist: Option>, #[serde(skip_serializing_if = "Option::is_none")] + pub disable_job_proxy: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub min_alive_workers_alert_threshold: Option, #[serde(skip_serializing_if = "Option::is_none")] pub autoscaling: Option, diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index 41d437c30a..e6a44054d9 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -484,6 +484,7 @@ lazy_static::lazy_static! { additional_python_paths: Default::default(), pip_local_dependencies: Default::default(), env_vars: Default::default(), + disable_job_proxy: false, native_mode: false, object_store_cache_config: Default::default(), paused: false, @@ -2767,6 +2768,7 @@ pub async fn load_worker_config( .additional_python_paths .or_else(|| load_additional_python_paths_from_env()), env_vars: resolved_env_vars, + disable_job_proxy: config.disable_job_proxy.unwrap_or(false), native_mode, object_store_cache_config: config.object_store_cache_config, paused: config.paused.unwrap_or(false), @@ -2945,6 +2947,7 @@ pub struct WorkerConfigOpt { pub pip_local_dependencies: Option>, pub env_vars_static: Option>, pub env_vars_allowlist: Option>, + pub disable_job_proxy: Option, pub native_mode: Option, pub object_store_cache_config: Option, pub paused: Option, @@ -2966,6 +2969,7 @@ impl Default for WorkerConfigOpt { pip_local_dependencies: Default::default(), env_vars_static: Default::default(), env_vars_allowlist: Default::default(), + disable_job_proxy: Default::default(), native_mode: Default::default(), object_store_cache_config: Default::default(), paused: Default::default(), @@ -2987,6 +2991,8 @@ pub struct WorkerConfig { pub additional_python_paths: Option>, pub pip_local_dependencies: Option>, pub env_vars: HashMap, + /// Job runs get none of the worker's `HTTP(S)_PROXY`/`NO_PROXY`; dependency installs keep them. + pub disable_job_proxy: bool, pub native_mode: bool, /// Object store this group's dependency cache uses instead of the instance one, as stored /// in the group config. Raw JSON: `windmill-common` cannot depend on the object store crate @@ -2999,8 +3005,8 @@ pub struct WorkerConfig { impl std::fmt::Debug for WorkerConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "WorkerConfig {{ worker_tags: {:?}, priority_tags_sorted: {:?}, dedicated_worker: {:?}, dedicated_workers: {:?}, init_bash: {:?}, periodic_script_bash: {:?}, periodic_script_interval_seconds: {:?}, cache_clear: {:?}, additional_python_paths: {:?}, pip_local_dependencies: {:?}, env_vars: {:?}, native_mode: {:?}, paused: {:?}, object_store_cache_config: {} }}", - self.worker_tags, self.priority_tags_sorted, self.dedicated_worker, self.dedicated_workers, self.init_bash, self.periodic_script_bash, self.periodic_script_interval_seconds, self.cache_clear, self.additional_python_paths, self.pip_local_dependencies, self.env_vars.iter().map(|(k, v)| format!("{}: {}{} ({} chars)", k, &v[..3.min(v.len())], "***", v.len())).collect::>().join(", "), self.native_mode, self.paused, + write!(f, "WorkerConfig {{ worker_tags: {:?}, priority_tags_sorted: {:?}, dedicated_worker: {:?}, dedicated_workers: {:?}, init_bash: {:?}, periodic_script_bash: {:?}, periodic_script_interval_seconds: {:?}, cache_clear: {:?}, additional_python_paths: {:?}, pip_local_dependencies: {:?}, env_vars: {:?}, disable_job_proxy: {:?}, native_mode: {:?}, paused: {:?}, object_store_cache_config: {} }}", + self.worker_tags, self.priority_tags_sorted, self.dedicated_worker, self.dedicated_workers, self.init_bash, self.periodic_script_bash, self.periodic_script_interval_seconds, self.cache_clear, self.additional_python_paths, self.pip_local_dependencies, self.env_vars.iter().map(|(k, v)| format!("{}: {}{} ({} chars)", k, &v[..3.min(v.len())], "***", v.len())).collect::>().join(", "), self.disable_job_proxy, self.native_mode, self.paused, // holds bucket credentials self.object_store_cache_config.as_ref().map(|_| "***").unwrap_or("None")) } diff --git a/backend/windmill-worker/src/ansible_executor.rs b/backend/windmill-worker/src/ansible_executor.rs index b577097c9d..0613032678 100644 --- a/backend/windmill-worker/src/ansible_executor.rs +++ b/backend/windmill-worker/src/ansible_executor.rs @@ -2098,7 +2098,7 @@ fi nsjail_cmd .current_dir(job_dir) .env_clear() - .envs(PROXY_ENVS.clone()) + .envs(crate::job_proxy_envs()) // inject PYTHONPATH here - for some reason I had to do it in nsjail conf .envs(reserved_variables) .env("PATH", PATH_ENV.as_str()) diff --git a/backend/windmill-worker/src/dbt_executor.rs b/backend/windmill-worker/src/dbt_executor.rs index 28db2753e1..4db8201e9b 100644 --- a/backend/windmill-worker/src/dbt_executor.rs +++ b/backend/windmill-worker/src/dbt_executor.rs @@ -2343,7 +2343,12 @@ pub(crate) fn dbt_command(p: &PreparedProject, args: &[&str]) -> Command { } cmd.current_dir(&p.project_dir) .env_clear() - .envs(PROXY_ENVS.clone()) + // `deps` is a dependency install, which keeps the proxy whatever the group says. + .envs(if args == ["deps"] { + PROXY_ENVS.clone() + } else { + crate::job_proxy_envs() + }) .env("PATH", PATH_ENV.as_str()) .env("TZ", TZ_ENV.as_str()) .env("GIT_PATH", GIT_PATH.as_str()) diff --git a/backend/windmill-worker/src/duckdb_runner.rs b/backend/windmill-worker/src/duckdb_runner.rs index b7c0bc6321..56b3c1f5cc 100644 --- a/backend/windmill-worker/src/duckdb_runner.rs +++ b/backend/windmill-worker/src/duckdb_runner.rs @@ -167,28 +167,37 @@ fn needed_extensions(blocks: &[String]) -> Vec { static INSTALLED: LazyLock>> = LazyLock::new(Default::default); -/// Installs, outside the jail, what the job will load inside it. The runner only runs -/// `INSTALL` here, and only of statements built above, so no script SQL and no extension -/// code runs unjailed. Once per extension per worker process. -async fn install_missing_extensions(blocks: &[String], job_dir: &str) -> Result<()> { +/// Installs, ahead of the job and with the worker's proxy, what the job will load: into the +/// jail's cache for a jailed run, or into the runner's default one for a run that does not get +/// the proxy and so could not download them itself. The runner only runs `INSTALL` here, and +/// only of statements built above, so no script SQL and no extension code runs unjailed. Once +/// per extension per cache per worker process. +async fn install_missing_extensions( + blocks: &[String], + job_dir: &str, + jail_cache: bool, +) -> Result<()> { + let key = |s: &String| format!("{jail_cache}:{s}"); let missing: Vec = { let installed = INSTALLED.lock().unwrap(); needed_extensions(blocks) .into_iter() - .filter(|s| s.starts_with("FORCE ") || !installed.contains(s)) + .filter(|s| s.starts_with("FORCE ") || !installed.contains(&key(s))) .collect() }; if missing.is_empty() { return Ok(()); } - let ext_dir = extension_dir(); - tokio::fs::create_dir_all(&ext_dir).await?; - let blocks: Vec = std::iter::once(format!( - "SET extension_directory='{}';", - ext_dir.replace('\'', "''") - )) - .chain(missing.iter().cloned()) - .collect(); + let mut blocks = Vec::with_capacity(missing.len() + 1); + if jail_cache { + let ext_dir = extension_dir(); + tokio::fs::create_dir_all(&ext_dir).await?; + blocks.push(format!( + "SET extension_directory='{}';", + ext_dir.replace('\'', "''") + )); + } + blocks.extend(missing.iter().cloned()); let out = spawn_runner( RunnerMode::Plain, &RunnerRequest { @@ -210,10 +219,13 @@ async fn install_missing_extensions(blocks: &[String], job_dir: &str) -> Result< if let Some(raw) = out.result.strip_prefix("ERROR ") { let msg = serde_json::from_str::(raw).unwrap_or_else(|_| raw.to_string()); return Err(Error::ExecutionErr(format!( - "Installing DuckDB extensions for the jailed runner failed: {msg}" + "Installing DuckDB extensions ahead of the job failed: {msg}" ))); } - INSTALLED.lock().unwrap().extend(missing.into_iter().filter(|s| !s.starts_with("FORCE "))); + INSTALLED + .lock() + .unwrap() + .extend(missing.iter().filter(|s| !s.starts_with("FORCE ")).map(key)); Ok(()) } @@ -289,10 +301,10 @@ pub(crate) async fn run( let spill_dir = format!("{}/spill", work_dir(job_dir)); tokio::fs::create_dir_all(&spill_dir).await?; let req = RunnerRequest { temp_directory: &spill_dir, ..*req }; - if mode != RunnerMode::Jailed { + if mode != RunnerMode::Jailed && crate::passes_proxy_to_jobs() { return spawn_runner(mode, &req, job_dir).await; } - install_missing_extensions(req.blocks, job_dir).await?; + install_missing_extensions(req.blocks, job_dir, mode == RunnerMode::Jailed).await?; let blocks = unforce_installs(req.blocks); spawn_runner(mode, &RunnerRequest { blocks: &blocks, ..req }, job_dir).await } @@ -438,19 +450,24 @@ async fn spawn_runner( if let Some(cap) = &spill_cap { cmd.env("DUCKDB_MAX_TEMP_DIRECTORY_SIZE", cap); } - for var in [ - "GOOGLE_APPLICATION_CREDENTIALS", - "HTTP_PROXY", - "HTTPS_PROXY", - "NO_PROXY", - "ALL_PROXY", - "http_proxy", - "https_proxy", - "no_proxy", - "all_proxy", - ] { - if let Ok(v) = std::env::var(var) { - cmd.env(var, v); + if let Ok(v) = std::env::var("GOOGLE_APPLICATION_CREDENTIALS") { + cmd.env("GOOGLE_APPLICATION_CREDENTIALS", v); + } + // An `Install` request only fetches extensions, a dependency install that keeps the proxy. + if matches!(req.mode, RequestMode::Install) || crate::passes_proxy_to_jobs() { + for var in [ + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "ALL_PROXY", + "http_proxy", + "https_proxy", + "no_proxy", + "all_proxy", + ] { + if let Ok(v) = std::env::var(var) { + cmd.env(var, v); + } } } diff --git a/backend/windmill-worker/src/java_executor.rs b/backend/windmill-worker/src/java_executor.rs index 39c8804cd5..c4678cfe83 100644 --- a/backend/windmill-worker/src/java_executor.rs +++ b/backend/windmill-worker/src/java_executor.rs @@ -252,7 +252,7 @@ pub async fn resolve<'a>( // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(PROXY_ENVS.clone())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -417,7 +417,7 @@ async fn install<'a>( .envs(PROXY_ENVS.clone()); // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(PROXY_ENVS.clone())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -803,7 +803,7 @@ async fn run<'a>( } // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(crate::job_proxy_envs())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -882,7 +882,7 @@ async fn run<'a>( } // Configure proxies { - let jps = parse_proxy()?; + let jps = parse_proxy(crate::job_proxy_envs())?; if let Some(val) = jps.https_host { cmd.arg(&format!("-Dhttps.proxyHost={}", val)); } @@ -943,9 +943,9 @@ struct JavaProxySettings { https_port: Option, no_proxy: Option, } -fn parse_proxy() -> anyhow::Result { +fn parse_proxy(proxy_envs: Vec<(&'static str, String)>) -> anyhow::Result { let mut jps = JavaProxySettings::default(); - for (ident, mut val) in PROXY_ENVS.clone() { + for (ident, mut val) in proxy_envs { match ident { "HTTPS_PROXY" => { if !val.contains("://") { diff --git a/backend/windmill-worker/src/pwsh_executor.rs b/backend/windmill-worker/src/pwsh_executor.rs index c089930b42..f1baf9d5aa 100644 --- a/backend/windmill-worker/src/pwsh_executor.rs +++ b/backend/windmill-worker/src/pwsh_executor.rs @@ -36,7 +36,7 @@ use crate::{ handle_child::handle_child, is_sandboxing_enabled, read_ee_registry_with_workspace_override, DISABLE_NUSER, HOME_ENV, NSJAIL_PATH, PATH_ENV, POWERSHELL_CACHE_DIR, POWERSHELL_PATH, POWERSHELL_REPO_PAT, - POWERSHELL_REPO_URL, PROXY_ENVS, TZ_ENV, + POWERSHELL_REPO_URL, TZ_ENV, }; fn val_to_pwsh_param(v: serde_json::Value) -> String { @@ -728,7 +728,7 @@ $env:PSModulePath = \"{};$PSModulePathBackup\"", let mut cmd = Command::new(NSJAIL_PATH.as_str()); cmd.current_dir(job_dir) .env_clear() - .envs(PROXY_ENVS.clone()) + .envs(crate::job_proxy_envs()) .envs(reserved_variables) .env("TZ", TZ_ENV.as_str()) .env("PATH", PATH_ENV.as_str()) diff --git a/backend/windmill-worker/src/r_executor.rs b/backend/windmill-worker/src/r_executor.rs index 214cf35525..4220feba91 100644 --- a/backend/windmill-worker/src/r_executor.rs +++ b/backend/windmill-worker/src/r_executor.rs @@ -627,7 +627,7 @@ async fn run<'a>( .env("PATH", PATH_ENV.as_str()) .env("BASE_INTERNAL_URL", base_internal_url) .envs(&reserved_variables) - .envs(if no_network { + .envs(if no_network || !crate::passes_proxy_to_jobs() { vec![] } else { R_PROXY_ENVS.clone() @@ -703,7 +703,11 @@ async fn run<'a>( .env("PATH", PATH_ENV.as_str()) .env("BASE_INTERNAL_URL", base_internal_url) .envs(reserved_variables) - .envs(R_PROXY_ENVS.clone()) + .envs(if crate::passes_proxy_to_jobs() { + R_PROXY_ENVS.clone() + } else { + vec![] + }) .envs( get_proxy_envs_for_lang( &ScriptLang::Rlang, diff --git a/backend/windmill-worker/src/ruby_executor.rs b/backend/windmill-worker/src/ruby_executor.rs index 1cd477e1fd..c5828f192a 100644 --- a/backend/windmill-worker/src/ruby_executor.rs +++ b/backend/windmill-worker/src/ruby_executor.rs @@ -825,7 +825,11 @@ mount {{ .env("BASE_INTERNAL_URL", base_internal_url) .env("RUBYLIB", rubylib.as_str()) .envs(&reserved_variables) - .envs(RUBY_PROXY_ENVS.clone()) + .envs(if crate::passes_proxy_to_jobs() { + RUBY_PROXY_ENVS.clone() + } else { + vec![] + }) .envs( get_proxy_envs_for_lang( &ScriptLang::Ruby, @@ -900,7 +904,11 @@ mount {{ .env("RUBYLIB", rubylib.as_str()) .env("BASE_INTERNAL_URL", base_internal_url) .envs(reserved_variables) - .envs(RUBY_PROXY_ENVS.clone()) + .envs(if crate::passes_proxy_to_jobs() { + RUBY_PROXY_ENVS.clone() + } else { + vec![] + }) .envs( get_proxy_envs_for_lang( &ScriptLang::Ruby, diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index f6e1fc7f61..aa742bfdf5 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -1199,6 +1199,21 @@ pub fn nsjail_clone_newnet(no_network: bool) -> &'static str { } } +/// Whether job runs get the worker's proxy settings. Dependency installs always do: they read +/// [`PROXY_ENVS`] directly, so a group that turns the proxy off for jobs still installs through it. +pub fn passes_proxy_to_jobs() -> bool { + !WORKER_CONFIG.load().disable_job_proxy +} + +/// [`PROXY_ENVS`] as a job run sees them; see [`passes_proxy_to_jobs`]. +pub fn job_proxy_envs() -> Vec<(&'static str, String)> { + if passes_proxy_to_jobs() { + PROXY_ENVS.clone() + } else { + vec![] + } +} + /// [`get_proxy_envs_for_lang`] for a run step. A `no_network` one reaches no proxy, the /// OTel tracing proxy included, so it gets only the trace context. pub async fn get_run_proxy_envs( @@ -1372,12 +1387,12 @@ pub async fn get_proxy_envs_for_lang( { envs = get_otel_tracing_proxy_envs(job_id, w_id, conn).await?; } else { - envs = PROXY_ENVS.clone(); + envs = job_proxy_envs(); } #[cfg(not(all(feature = "private", feature = "enterprise")))] { let _ = (lang, job_kind, w_id, conn); - envs = PROXY_ENVS.clone(); + envs = job_proxy_envs(); } envs.extend(get_otel_context_envs(job_id)); Ok(envs) @@ -1399,7 +1414,7 @@ async fn get_otel_tracing_proxy_envs( This job's HTTP requests will not be traced."; tracing::warn!("{}", reason); append_logs(job_id, w_id, format!("\n[warning] {reason}\n"), conn).await; - return Ok(PROXY_ENVS.clone()); + return Ok(job_proxy_envs()); } }; let proxy_url = format!("http://127.0.0.1:{}", port); @@ -5440,8 +5455,8 @@ pub fn build_envs( hm }; - for (k, v) in PROXY_ENVS.iter() { - envs.insert(k.to_string(), v.clone()); + for (k, v) in job_proxy_envs() { + envs.insert(k.to_string(), v); } Ok(envs) diff --git a/frontend/src/lib/components/WorkerGroup.svelte b/frontend/src/lib/components/WorkerGroup.svelte index 1f6b271602..584d3bf2d5 100644 --- a/frontend/src/lib/components/WorkerGroup.svelte +++ b/frontend/src/lib/components/WorkerGroup.svelte @@ -105,6 +105,7 @@ periodic_script_interval_seconds?: number env_vars_static?: Map env_vars_allowlist?: string[] + disable_job_proxy?: boolean additional_python_paths?: string[] pip_local_dependencies?: string[] min_alive_workers_alert_threshold?: number @@ -212,6 +213,7 @@ init_bash?: string env_vars_static?: Map env_vars_allowlist?: string[] + disable_job_proxy?: boolean additional_python_paths?: string[] pip_local_dependencies?: string[] min_alive_workers_alert_threshold?: number @@ -327,6 +329,7 @@ 'priority_tags', 'additional_python_paths', 'pip_local_dependencies', + 'disable_job_proxy', 'object_store_cache_config', 'serves_dev_workspaces' ] as const @@ -909,6 +912,30 @@ disabled={!canEditConfig} /> +
    + {/if}
    From 4c97368c9d7661b553fcf4a29b729862f0cb3d29 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Fri, 23 Oct 2026 01:37:44 +0200 Subject: [PATCH 051/101] perf: keep unchanged transcript rows stable while a chat reply streams (#11962) Co-authored-by: Claude Opus 5.5 --- .../copilot/chat/AIChatDisplay.svelte | 5 ++- .../copilot/chat/toolGroups.test.ts | 42 +++++++++++++++++- .../lib/components/copilot/chat/toolGroups.ts | 43 +++++++++++++++++++ 3 files changed, 87 insertions(+), 3 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index 5f31bd4272..c5fede3162 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -48,7 +48,7 @@ import { getAiChatManager } from './aiChatManagerContext' import ChatTypingIndicator from './ChatTypingIndicator.svelte' import ToolGroupDisplay from './ToolGroupDisplay.svelte' - import { chatItemKey, groupToolRuns } from './toolGroups' + import { chatItemKey, createChatItemGrouper } from './toolGroups' import AIChatInput from './AIChatInput.svelte' import { STARTER_PLACEHOLDER, type ComposerSelection } from './composerBox' import AttachedFilesBar from './files/AttachedFilesBar.svelte' @@ -189,7 +189,8 @@ const mcpMenu = new McpMenu(aiChatManager, () => assistantSettings?.open('mcp')) let plusMenuOpen = $state(false) let editingMessageIndex = $state(null) - const chatItems = $derived(groupToolRuns(messages)) + const groupChatItems = createChatItemGrouper() + const chatItems = $derived(groupChatItems(messages)) // Escape stops the generation when focus is on the chat (or parked on // body), but stays with other widgets (e.g. the session's Monaco editor). diff --git a/frontend/src/lib/components/copilot/chat/toolGroups.test.ts b/frontend/src/lib/components/copilot/chat/toolGroups.test.ts index 4dd3b376fe..d0f14e1f52 100644 --- a/frontend/src/lib/components/copilot/chat/toolGroups.test.ts +++ b/frontend/src/lib/components/copilot/chat/toolGroups.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from 'vitest' import type { DisplayMessage } from './shared' -import { groupHeader, groupToolRuns, type GroupState, type ToolGroup } from './toolGroups' +import { + createChatItemGrouper, + groupHeader, + groupToolRuns, + type GroupState, + type ToolGroup +} from './toolGroups' let nextId = 0 function tool( @@ -274,3 +280,37 @@ describe('groupToolRuns', () => { expect(header([mcp('list_issues'), other])).toBe('List issues, get issue') }) }) + +describe('createChatItemGrouper', () => { + it('keeps the history rows while only the live answer changes', () => { + const group = createChatItemGrouper() + const history = [ + assistant('done'), + tool('read_workspace_item'), + tool('list_runs'), + assistant('more') + ] + const first = group([...history, assistant('a', { streaming: true })]) + const second = group([...history, assistant('ab', { streaming: true })]) + expect(second).toHaveLength(first.length) + second.slice(0, -1).forEach((item, i) => expect(item).toBe(first[i])) + expect(second.at(-1)).toMatchObject({ kind: 'message', index: 4, message: { content: 'ab' } }) + expect(shape([...history, assistant('ab', { streaming: true })])).toEqual( + second.map((item) => + item.kind === 'group' ? { [item.groupKind]: item.entries.map((e) => e.index) } : item.index + ) + ) + }) + + it('keeps every row but the one a tool status change replaced', () => { + const group = createChatItemGrouper() + const history = [assistant('done'), tool('run_script'), assistant('more')] + const first = group(history) + const updated = [history[0], { ...history[1], isLoading: false }, history[2]] + const second = group(updated) + expect(second[0]).toBe(first[0]) + expect(second[1]).not.toBe(first[1]) + expect(second[1]).toMatchObject({ message: updated[1] }) + expect(second[2]).toBe(first[2]) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/toolGroups.ts b/frontend/src/lib/components/copilot/chat/toolGroups.ts index f3e3ad0aa9..5c0a8c2e1e 100644 --- a/frontend/src/lib/components/copilot/chat/toolGroups.ts +++ b/frontend/src/lib/components/copilot/chat/toolGroups.ts @@ -295,6 +295,49 @@ export function groupToolRuns(messages: DisplayMessage[]): ChatItem[] { return items } +function sameChatItem(a: ChatItem, b: ChatItem): boolean { + if (a.kind === 'message') { + return b.kind === 'message' && a.message === b.message && a.index === b.index + } + return ( + b.kind === 'group' && + a.groupKind === b.groupKind && + a.key === b.key && + a.target === b.target && + a.entries.length === b.entries.length && + a.entries.every((e, i) => e.message === b.entries[i].message && e.index === b.entries[i].index) + ) +} + +/** `groupToolRuns` for a transcript that is re-sent whole on every streamed chunk and on every + * tool status change: a row whose messages did not change keeps its previous item object. A + * fresh item per row re-renders the whole history each time (every answer re-parsing its + * markdown, every tool row its result), which freezes the tab on long sessions. + * + * A changed message is told apart by identity alone, so a row must be replaced, never mutated + * in place, for its grouping to update. */ +export function createChatItemGrouper(): (messages: DisplayMessage[]) => ChatItem[] { + let settled: DisplayMessage[] = [] + let settledItems: ChatItem[] = [] + return (messages) => { + // The live answer only ever comes last, and it can neither join nor end a group + // differently than the end of the transcript does, so it is grouped on its own and the + // rows before it are not regrouped while it streams. + const last = messages.at(-1) + const live = last?.role === 'assistant' && last.streaming ? last : undefined + const n = live ? messages.length - 1 : messages.length + if (n !== settled.length || settled.some((m, i) => m !== messages[i])) { + const previous = new Map(settledItems.map((item) => [chatItemKey(item), item])) + settled = messages.slice(0, n) + settledItems = groupToolRuns(settled).map((item) => { + const before = previous.get(chatItemKey(item)) + return before && sameChatItem(before, item) ? before : item + }) + } + return live ? [...settledItems, { kind: 'message', message: live, index: n }] : settledItems + } +} + // The server's full resource path: two servers can share a last segment (u/alice/github, // f/team/github), so only the display shortens it. function mcpServerPath(call: ToolDisplayMessage): string | undefined { From 39cacd71aecd3b408c885377c71f0c2a0465d4a9 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Fri, 23 Oct 2026 01:38:08 +0200 Subject: [PATCH 052/101] chore(main): release 1.847.0 (#11937) * chore(main): release 1.847.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++ backend/Cargo.lock | 235 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 ++-- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 185 insertions(+), 164 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7339eafd50..ef65812b73 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.846.1" + ".": "1.847.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e97b73451..12e61b56bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## [1.847.0](https://github.com/windmill-labs/windmill/compare/v1.846.1...v1.847.0) (2026-10-22) + + +### Features + +* add job_id and flow_path to flow step error objects ([#11941](https://github.com/windmill-labs/windmill/issues/11941)) ([eeb48f0](https://github.com/windmill-labs/windmill/commit/eeb48f0c26ccc5162430eddec24adc2601eb5f99)) +* chat with a saved agent from a raw app through an agent runnable ([#11921](https://github.com/windmill-labs/windmill/issues/11921)) ([c6a93a9](https://github.com/windmill-labs/windmill/commit/c6a93a9b565752da6c8b55d383e5bee88f00f229)) +* let native triggers act through per-user or shared connections ([#11352](https://github.com/windmill-labs/windmill/issues/11352)) ([dc1fb50](https://github.com/windmill-labs/windmill/commit/dc1fb5087be7169045aad57e955dabe3e29de82e)) +* slack agents through a workspace's own slack app ([#11912](https://github.com/windmill-labs/windmill/issues/11912)) ([34de8bc](https://github.com/windmill-labs/windmill/commit/34de8bc06d2b04f7929bb8cf35f9a34d0e0071fa)) +* worker group toggle to keep the worker's proxy out of jobs ([#11958](https://github.com/windmill-labs/windmill/issues/11958)) ([8a0318a](https://github.com/windmill-labs/windmill/commit/8a0318a28f5cfda7557b0f94db20ef17b0664ee4)) + + +### Bug Fixes + +* compare a null resource description as empty ([#11947](https://github.com/windmill-labs/windmill/issues/11947)) ([8a7b148](https://github.com/windmill-labs/windmill/commit/8a7b1481bd270df3a98c9db5e7824d13b8cd37b6)) +* compare fork secret variables by decrypted value ([#11952](https://github.com/windmill-labs/windmill/issues/11952)) ([0dd131b](https://github.com/windmill-labs/windmill/commit/0dd131b38074423de5c769cae478c6ea0ae365c2)) +* hold home's ai composer space with a matching placeholder ([#11936](https://github.com/windmill-labs/windmill/issues/11936)) ([9202a74](https://github.com/windmill-labs/windmill/commit/9202a74071ba424ad6cfc1cfded518ee7db002dc)) +* link a variable to its OAuth account only in the connect flow ([#11361](https://github.com/windmill-labs/windmill/issues/11361)) ([d6adac8](https://github.com/windmill-labs/windmill/commit/d6adac8b7579ad6c3df5caab9a735451c1ddd896)) +* stop audit inserts from silently rolling back saves ([#11938](https://github.com/windmill-labs/windmill/issues/11938)) ([5ef19a8](https://github.com/windmill-labs/windmill/commit/5ef19a88a90b3a4fe05a78547416082dc51763f5)) + ## [1.846.1](https://github.com/windmill-labs/windmill/compare/v1.846.0...v1.846.1) (2026-10-21) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 13928f21cb..97626ab116 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -6859,9 +6859,9 @@ dependencies = [ [[package]] name = "icu_calendar" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +checksum = "a68ffb801cc7acb8dcae62da7c692c47934698d2dd4f479ddee1eb442763dea1" dependencies = [ "calendrical_calculations", "displaydoc", @@ -6875,15 +6875,15 @@ dependencies = [ [[package]] name = "icu_calendar_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc00caaa3fb3201ff7a18aa458e8c3ab042b9da154cfdf948bdde3936c31c36e" +checksum = "514da54e79efa36b5976232d5b3d1d8ee1b47b19ab658f1b1ebe39221696c2d8" [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -6895,9 +6895,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -6909,9 +6909,9 @@ dependencies = [ [[package]] name = "icu_locale_fallback" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" dependencies = [ "icu_locale_core", "icu_locale_fallback_data", @@ -6923,15 +6923,15 @@ dependencies = [ [[package]] name = "icu_locale_fallback_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -6943,15 +6943,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -6964,15 +6964,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -6987,9 +6987,9 @@ dependencies = [ [[package]] name = "icu_segmenter" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" dependencies = [ "icu_collections", "icu_locale_fallback", @@ -6998,14 +6998,15 @@ dependencies = [ "potential_utf", "smallvec", "utf8_iter", + "zerotrie", "zerovec", ] [[package]] name = "icu_segmenter_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" [[package]] name = "ident_case" @@ -7223,9 +7224,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "ixdtf" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d3667095d64c3ecffc96463a21157b04bf3e252f6e8d5750b20c02e33c194e3" +checksum = "4754a1731458af0443709c9667302793d3f63cc90ec4ba4c8259f2b9515478e5" [[package]] name = "jiff" @@ -11101,9 +11102,9 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "3.6.0" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f55ef2d84752d676d735604548fcb65811504e23330d85670b0eff5f8735144" +checksum = "967fa7f7935d7d6217d593df0e8e5c9307bcaf256974a5a9ee64476c97735389" dependencies = [ "darling 0.24.1", "proc-macro2", @@ -13965,9 +13966,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "serde_core", @@ -15486,7 +15487,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-nats", @@ -15576,7 +15577,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.846.1" +version = "1.847.0" dependencies = [ "async-stream", "async-trait", @@ -15611,7 +15612,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15624,7 +15625,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "argon2", @@ -15767,7 +15768,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15791,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15808,7 +15809,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "axum", @@ -15834,7 +15835,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.846.1" +version = "1.847.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15844,7 +15845,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15861,7 +15862,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "base64 0.22.1", @@ -15883,7 +15884,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "axum", @@ -15906,7 +15907,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15922,7 +15923,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15944,7 +15945,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15966,7 +15967,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -15980,7 +15981,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-nats", @@ -16016,7 +16017,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "axum", @@ -16042,7 +16043,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -16070,7 +16071,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "axum", @@ -16092,7 +16093,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -16112,7 +16113,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "axum", @@ -16154,7 +16155,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "axum", @@ -16184,7 +16185,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.846.1" +version = "1.847.0" dependencies = [ "lazy_static", "serde", @@ -16196,7 +16197,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.846.1" +version = "1.847.0" dependencies = [ "argon2", "axum", @@ -16220,7 +16221,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -16235,7 +16236,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.846.1" +version = "1.847.0" dependencies = [ "axum", "chrono", @@ -16274,7 +16275,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.846.1" +version = "1.847.0" dependencies = [ "chrono", "lazy_static", @@ -16289,7 +16290,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "axum", @@ -16308,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.846.1" +version = "1.847.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16426,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.846.1" +version = "1.847.0" dependencies = [ "chrono", "futures", @@ -16446,7 +16447,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.846.1" +version = "1.847.0" dependencies = [ "regex", "serde", @@ -16463,7 +16464,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16490,7 +16491,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "futures", @@ -16507,7 +16508,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.846.1" +version = "1.847.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16523,7 +16524,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -16545,7 +16546,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -16576,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "arc-swap", @@ -16601,7 +16602,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-stream", @@ -16637,7 +16638,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "futures", @@ -16656,7 +16657,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.846.1" +version = "1.847.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16665,7 +16666,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -16677,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde_json", @@ -16689,7 +16690,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "gosyn", @@ -16701,7 +16702,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -16713,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde_json", @@ -16725,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "nu-parser", @@ -16736,7 +16737,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16747,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16759,7 +16760,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16770,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-recursion", @@ -16793,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde_json", @@ -16805,7 +16806,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -16819,7 +16820,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16836,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -16849,7 +16850,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde", @@ -16861,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -16879,7 +16880,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16895,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16912,7 +16913,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -16926,7 +16927,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-recursion", @@ -16965,7 +16966,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "const_format", @@ -17003,7 +17004,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.846.1" +version = "1.847.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17014,7 +17015,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-recursion", @@ -17049,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17073,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17106,7 +17107,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17133,7 +17134,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17166,7 +17167,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17186,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17220,7 +17221,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17257,7 +17258,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17280,7 +17281,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17304,7 +17305,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-nats", @@ -17328,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17363,7 +17364,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17391,7 +17392,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-trait", @@ -17416,7 +17417,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17435,7 +17436,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-once-cell", @@ -17553,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.846.1" +version = "1.847.0" dependencies = [ "bytes", "futures", @@ -18256,9 +18257,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -18352,9 +18353,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "serde", "yoke", @@ -18364,9 +18365,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 3f77228280..d2d4678718 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.846.1" +version = "1.847.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.846.1" +version = "1.847.0" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 6c1adc33e8..a73343f8b9 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.846.1" +version = "1.847.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.846.1" +version = "1.847.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.846.1" +version = "1.847.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.846.1" +version = "1.847.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 5424540fca..6955752a98 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.846.1" +version = "1.847.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 6996562aac..fd5e02bed4 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.846.1 + version: 1.847.0 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 895e35e45f..6be8a4523e 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.846.1"; +export const VERSION = "v1.847.0"; export async function login(email: string, password: string): Promise { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 0bc4161402..56e888035e 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.846.1", + "version": "1.847.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.846.1", + "version": "1.847.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 9804654954..74fb87fc20 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.846.1", + "version": "1.847.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index b0b201d5c9..e02c5a2217 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.846.1"; +export const VERSION = "1.847.0"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index c550f2d978..e1fa01dbaa 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.846.1", + "version": "1.847.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.846.1", + "version": "1.847.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 98d33e5fb3..d417cee0a4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.846.1", + "version": "1.847.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index f6a8ef64fe..cab32152b8 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.846.1" +wmill = ">=1.847.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 963b1a040f..489888ee60 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.846.1 + version: 1.847.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 74c899cee5..713e75f667 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.846.1' + ModuleVersion = '1.847.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index ab2395d8f5..2ef9c5923b 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.846.1" +version = "1.847.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 149c16ad26..2a1a7b3c15 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.846.1", + "version": "1.847.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 21b26faad1..5f7b4f3fef 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.846.1", + "version": "1.847.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index 70e64b51a1..44bc59b37f 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.846.1 +1.847.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 1dbd1e6d9b..fe642da3da 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.846.1", + "version": "1.847.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.846.1", + "version": "1.847.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index 17e6f6fdab..43d8faa83f 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.846.1", + "version": "1.847.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 6d1e3952bedc59346ddd05befd54d8c2d9d36cd0 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 22 Oct 2026 20:11:01 -0700 Subject: [PATCH 053/101] settle async diff tallies in workspace comparison tests (#11963) test_compare_secret_variables_by_value planted workspace_diff rows with a plain INSERT after a DELETE, but the variable creates tally those rows from a spawned git-sync task that can land between the two, failing with a workspace_diff_pkey violation. Upsert the plant instead. test_rename_records_the_vacated_path could read the inline create's `write` event, or have it overwrite `rename_from`, since both deploys tally from their own spawned task. Wait for the create's tally before the rename and poll for the event that replaces it. Co-authored-by: Claude Opus 5.5 --- ...d3b4382f863d7c84f18af64e1d3930890a210.json | 20 +++++++++++++ ...28d5c5aac9608e8f60e5b76be177e4e105b1.json} | 4 +-- ...bef3389884cdde284ed3eb3b8d6979761b98.json} | 4 +-- .../tests/workspace_comparison.rs | 28 +++++++++++++++++-- 4 files changed, 50 insertions(+), 6 deletions(-) create mode 100644 backend/.sqlx/query-420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210.json rename backend/.sqlx/{query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json => query-6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1.json} (65%) rename backend/.sqlx/{query-f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807.json => query-df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98.json} (81%) diff --git a/backend/.sqlx/query-420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210.json b/backend/.sqlx/query-420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210.json new file mode 100644 index 0000000000..2b0a574473 --- /dev/null +++ b/backend/.sqlx/query-420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM workspace_diff\n WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script'\n AND path = 'u/admin/inline' AND fork_last_event_kind = 'write')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "420707b82c44c7a30719c4419bdd3b4382f863d7c84f18af64e1d3930890a210" +} diff --git a/backend/.sqlx/query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json b/backend/.sqlx/query-6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1.json similarity index 65% rename from backend/.sqlx/query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json rename to backend/.sqlx/query-6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1.json index c9507b7f22..8cfd36abd6 100644 --- a/backend/.sqlx/query-e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952.json +++ b/backend/.sqlx/query-6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO workspace_diff\n (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes)\n VALUES\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/same', 'variable', 1, 1, NULL),\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL)", + "query": "INSERT INTO workspace_diff\n (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes)\n VALUES\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/same', 'variable', 1, 1, NULL),\n ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL)\n ON CONFLICT (source_workspace_id, fork_workspace_id, path, kind)\n DO UPDATE SET ahead = 1, behind = 1, has_changes = NULL", "describe": { "columns": [], "parameters": { @@ -8,5 +8,5 @@ }, "nullable": [] }, - "hash": "e57039a483e96afa69f96e36be7666e83c6ccdea5087eb194d1de17086c58952" + "hash": "6d856cdf841aa6fb95d82841da3b28d5c5aac9608e8f60e5b76be177e4e105b1" } diff --git a/backend/.sqlx/query-f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807.json b/backend/.sqlx/query-df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98.json similarity index 81% rename from backend/.sqlx/query-f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807.json rename to backend/.sqlx/query-df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98.json index 912db1a932..ed386844d4 100644 --- a/backend/.sqlx/query-f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807.json +++ b/backend/.sqlx/query-df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT fork_last_event_kind, fork_last_event_origin FROM workspace_diff\n WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script'\n AND path = 'u/admin/inline' AND fork_last_event_kind IS NOT NULL", + "query": "SELECT fork_last_event_kind, fork_last_event_origin FROM workspace_diff\n WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script'\n AND path = 'u/admin/inline' AND fork_last_event_kind <> 'write'", "describe": { "columns": [ { @@ -22,5 +22,5 @@ true ] }, - "hash": "f0d8ebbf62a1d92f39c2f86a70236cece6d6c9e28cce9aff7fe5496bba569807" + "hash": "df8f616f7ace1d45cb9022d70e53bef3389884cdde284ed3eb3b8d6979761b98" } diff --git a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs index c3cb9ff190..bef3b5dd78 100644 --- a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs +++ b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs @@ -2549,6 +2549,26 @@ async fn test_rename_records_the_vacated_path(db: Pool) -> anyhow::Res "script deploy failed: {status} — {hash}" ); parent_hash = Some(hash.trim().trim_matches('"').to_string()); + // Each deploy tallies from its own spawned task: let the create's `write` land + // before the rename, or it can overwrite the `rename_from` asserted below. + if path == "u/admin/inline" { + let mut written = false; + for _ in 0..40 { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + written = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM workspace_diff + WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script' + AND path = 'u/admin/inline' AND fork_last_event_kind = 'write')" + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if written { + break; + } + } + assert!(written, "the inline create should be tallied"); + } } let mut vacated = None; for _ in 0..40 { @@ -2556,7 +2576,7 @@ async fn test_rename_records_the_vacated_path(db: Pool) -> anyhow::Res vacated = sqlx::query!( "SELECT fork_last_event_kind, fork_last_event_origin FROM workspace_diff WHERE fork_workspace_id = 'wm-fork-renamed' AND kind = 'script' - AND path = 'u/admin/inline' AND fork_last_event_kind IS NOT NULL" + AND path = 'u/admin/inline' AND fork_last_event_kind <> 'write'" ) .fetch_optional(&db) .await?; @@ -2706,6 +2726,8 @@ async fn test_compare_secret_variables_by_value(db: Pool) -> anyhow::R "the same secret must be stored as two different ciphertexts" ); + // The creates above tally these rows from a spawned task that can land after the + // DELETE, so the plant must upsert. sqlx::query!("DELETE FROM workspace_diff WHERE fork_workspace_id = 'wm-fork-secrets'") .execute(&db) .await?; @@ -2714,7 +2736,9 @@ async fn test_compare_secret_variables_by_value(db: Pool) -> anyhow::R (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes) VALUES ('test-workspace', 'wm-fork-secrets', 'u/test-user/same', 'variable', 1, 1, NULL), - ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL)" + ('test-workspace', 'wm-fork-secrets', 'u/test-user/different', 'variable', 1, 1, NULL) + ON CONFLICT (source_workspace_id, fork_workspace_id, path, kind) + DO UPDATE SET ahead = 1, behind = 1, has_changes = NULL" ) .execute(&db) .await?; From f94ec301562aebf5718b0cb5ba884289b9f3d44d Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 22 Oct 2026 20:15:45 -0700 Subject: [PATCH 054/101] ci: extract release binaries one image at a time to fit runner disk (#11964) --- .github/workflows/docker-image.yml | 64 ++++++++++++++---------------- 1 file changed, 29 insertions(+), 35 deletions(-) diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 51da953ab0..c046a7d101 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -197,47 +197,41 @@ jobs: ARCH: amd64 steps: - uses: actions/checkout@v4 - - run: | - # pulling docker image with desired arch so that actions-docker-extract doesn't do it - docker pull --platform "linux/$ARCH" ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - docker pull --platform "linux/$ARCH" ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} - - run: | - # Checks the image is in docker prior to running actions-docker-extract. It fails if not - # Also useful to visually check that the arch is the right opencontainers - docker image inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - docker image inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} - - - uses: shrink/actions-docker-extract@v3 - id: extract - with: - image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - path: "/usr/src/app/windmill" - - - uses: shrink/actions-docker-extract@v3 - id: extract-duckdb-ffi-internal - with: - image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - path: "/usr/src/app/windmill_duckdb_runner" - - - uses: shrink/actions-docker-extract@v3 - id: extract-ee - with: - image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} - path: "/usr/src/app/windmill" - - - name: Rename binary with corresponding architecture + # The runner disk cannot hold the CE and EE images at once, so each image + # is pulled, extracted from and removed before the next one is pulled. + - name: Extract binaries + env: + CE_IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} + EE_IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} run: | - mv "${{ steps.extract.outputs.destination }}/windmill" "${{ steps.extract.outputs.destination }}/windmill-${ARCH}" - mv "${{ steps.extract-ee.outputs.destination }}/windmill" "${{ steps.extract-ee.outputs.destination }}/windmill-ee-${ARCH}" + set -euo pipefail + mkdir -p release + # extract ( )... + extract() { + local image=$1 cid + shift + docker pull --platform "linux/$ARCH" "$image" + docker image inspect --format '{{.Os}}/{{.Architecture}}' "$image" + cid=$(docker create --platform "linux/$ARCH" "$image") + while [ $# -gt 0 ]; do + docker cp "$cid:$1" "release/$2" + shift 2 + done + docker rm "$cid" + docker rmi "$image" + df -h / + } + extract "$CE_IMAGE" \ + /usr/src/app/windmill "windmill-$ARCH" \ + /usr/src/app/windmill_duckdb_runner windmill_duckdb_runner + extract "$EE_IMAGE" /usr/src/app/windmill "windmill-ee-$ARCH" + ls -la release - name: Attach binary to release uses: softprops/action-gh-release@v2 with: - files: | - ${{ steps.extract.outputs.destination }}/* - ${{ steps.extract-ee.outputs.destination }}/* - ${{ steps.extract-duckdb-ffi-internal.outputs.destination }}/* + files: release/* upload_ee_debug_to_s3: needs: [build_ee] From fb193d7a816ae97fa8fc60608270296e159dfd3c Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Fri, 23 Oct 2026 04:51:05 -0700 Subject: [PATCH 055/101] fix: list usr columns explicitly in whoami's user lookup (#11970) Co-authored-by: Claude Opus 5.5 --- ...92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json} | 8 ++++---- backend/windmill-api-users/src/users.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) rename backend/.sqlx/{query-1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1.json => query-bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json} (78%) diff --git a/backend/.sqlx/query-1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1.json b/backend/.sqlx/query-bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json similarity index 78% rename from backend/.sqlx/query-1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1.json rename to backend/.sqlx/query-bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json index e6233b6d9f..af2c944342 100644 --- a/backend/.sqlx/query-1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1.json +++ b/backend/.sqlx/query-bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT usr.*, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2\n ", + "query": "SELECT usr.workspace_id, usr.email, usr.username, usr.is_admin, usr.created_at, usr.operator, usr.disabled, usr.role, usr.added_via, usr.is_service_account, usr.workspace_role, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2\n ", "describe": { "columns": [ { @@ -10,12 +10,12 @@ }, { "ordinal": 1, - "name": "username", + "name": "email", "type_info": "Varchar" }, { "ordinal": 2, - "name": "email", + "name": "username", "type_info": "Varchar" }, { @@ -91,5 +91,5 @@ true ] }, - "hash": "1cf8597b9d37ec5a924aff8cbc0a05768ed9a679ba908ab16497a9bd55578ba1" + "hash": "bbc38059207753bd92cc543e5d850abe6dd3b66e87d4827c98cbaa5950f4def4" } diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index c0e48083dc..dbc883305e 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -956,7 +956,7 @@ pub struct User2 { async fn get_user(w_id: &str, username: &str, db: &DB) -> Result> { let user = sqlx::query_as!( User2, - "SELECT usr.*, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2 + "SELECT usr.workspace_id, usr.email, usr.username, usr.is_admin, usr.created_at, usr.operator, usr.disabled, usr.role, usr.added_via, usr.is_service_account, usr.workspace_role, COALESCE(password.super_admin, false) as \"super_admin!\", password.name FROM usr LEFT JOIN password ON usr.email = password.email Where usr.username = $1 AND workspace_id = $2 ", username, w_id From 72c6b10821cfa35ff3deb3a3ecc729ed75a9dbc6 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Fri, 23 Oct 2026 05:43:36 -0700 Subject: [PATCH 056/101] fix: make the autoscaling Test scaling button run the integration (#11972) * fix: make the autoscaling Test scaling button run the integration Co-Authored-By: Claude Opus 5.5 * chore: bump ee ref Co-Authored-By: Claude Opus 5.5 * fix: bound the test scaling worker input at zero Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to a2a23aebcf91985778fb632a415a6990d022f7c8 This commit updates the EE repository reference after PR #917 was merged in windmill-ee-private. Previous ee-repo-ref: c9e8c8853e2042a11797e322e1e4bb4be241380c New ee-repo-ref: a2a23aebcf91985778fb632a415a6990d022f7c8 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- backend/windmill-api-configs/src/lib.rs | 43 ++++++++++ backend/windmill-api/openapi.yaml | 50 ++++++++++++ .../components/AutoscalingConfigEditor.svelte | 80 +++++++++++++++---- .../src/lib/components/WorkerGroup.svelte | 1 + 5 files changed, 159 insertions(+), 17 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index f8c8a245eb..56e4ba0689 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -5cfc0dc6760ea7f631fc98ea1edd39adfc55bf11 +a2a23aebcf91985778fb632a415a6990d022f7c8 diff --git a/backend/windmill-api-configs/src/lib.rs b/backend/windmill-api-configs/src/lib.rs index cfa74bd2f0..8336888088 100644 --- a/backend/windmill-api-configs/src/lib.rs +++ b/backend/windmill-api-configs/src/lib.rs @@ -35,6 +35,7 @@ pub fn global_service() -> Router { "/list_autoscaling_events/{worker_group}", get(list_autoscaling_events), ) + .route("/test_autoscaling/{worker_group}", post(test_autoscaling)) .route( "/native_kubernetes_autoscaling_healthcheck", get(native_kubernetes_autoscaling_healthcheck), @@ -419,6 +420,48 @@ async fn native_kubernetes_autoscaling_healthcheck() -> Result<(), error::Error> )) } +#[derive(Serialize)] +struct TestAutoscalingResponse { + job_id: Option, +} + +#[cfg(all(feature = "enterprise", feature = "private"))] +async fn test_autoscaling( + authed: ApiAuthed, + Extension(db): Extension, + Path(worker_group): Path, + Json(test): Json, +) -> error::JsonResult { + require_devops_role(&db, &authed).await?; + audit_log( + &db, + &authed, + "worker_config.test_autoscaling", + ActionKind::Execute, + "global", + Some(&worker_group), + None, + ) + .await?; + let job_id = windmill_autoscaling::autoscaling_ee::test_autoscaling( + &db, + &worker_group, + test, + &authed.email, + ) + .await?; + Ok(Json(TestAutoscalingResponse { + job_id: job_id.map(|id| id.to_string()), + })) +} + +#[cfg(not(all(feature = "enterprise", feature = "private")))] +async fn test_autoscaling() -> error::JsonResult { + Err(error::Error::BadRequest( + "Autoscaling available only in the enterprise version".to_string(), + )) +} + async fn list_available_python_versions() -> error::JsonResult> { #[cfg(not(all(feature = "python", feature = "run_inline")))] return Err(error::Error::BadRequest( diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index fd5e02bed4..777209eda7 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -24649,6 +24649,56 @@ paths: items: $ref: "#/components/schemas/AutoscalingEvent" + /configs/test_autoscaling/{worker_group}: + post: + summary: Run an autoscaling integration once for a worker group, without recording an autoscaling event + operationId: testAutoscaling + tags: + - config + parameters: + - name: worker_group + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + desired_workers: + type: integer + minimum: 0 + integration: + description: The integration to run, as in the worker group's autoscaling config + type: object + properties: + type: + type: string + enum: [script, kubernetes, dryrun] + path: + type: string + tag: + type: string + required: + - type + required: + - desired_workers + - integration + responses: + "200": + description: The job queued for a script integration + content: + application/json: + schema: + type: object + properties: + job_id: + type: string + nullable: true + /configs/native_kubernetes_autoscaling_healthcheck: get: summary: Check Kubernetes autoscaling health for a worker group diff --git a/frontend/src/lib/components/AutoscalingConfigEditor.svelte b/frontend/src/lib/components/AutoscalingConfigEditor.svelte index 885b6dd55c..a8884657cd 100644 --- a/frontend/src/lib/components/AutoscalingConfigEditor.svelte +++ b/frontend/src/lib/components/AutoscalingConfigEditor.svelte @@ -16,8 +16,12 @@ import ScriptPicker from './ScriptPicker.svelte' import { sendUserToast } from '$lib/toast' import { untrack } from 'svelte' + import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte' + import { createAsyncConfirmationModal } from './common/confirmationModal/asyncConfirmationModal.svelte' + import Portal from './Portal.svelte' interface Props { + worker_group: string config: AutoscalingConfig | undefined worker_tags: string[] | undefined /** Whether the draft config gives the group any tags (worker_tags or dedicated workers). */ @@ -29,6 +33,7 @@ } let { + worker_group, config = $bindable(), worker_tags, group_has_tags, @@ -66,6 +71,54 @@ } } + const confirmationModal = createAsyncConfirmationModal() + + async function testScaling() { + const integration = config?.integration + if (!integration) return + if (integration.type === 'script' && !integration['path']) { + sendUserToast('Please select a script before testing scaling', true) + return + } + const desired_workers = test_input + let job_id: string | null | undefined + let failed = false + const confirmed = await confirmationModal.ask({ + title: `Scale ${worker_group} to ${desired_workers} workers?`, + confirmationText: 'Scale now', + type: 'reload', + children: + integration.type === 'kubernetes' + ? `This sets the worker group's replica count to ${desired_workers} now. If autoscaling is enabled, it adjusts the count again on its next pass.` + : `This runs the integration script once with desired_workers set to ${desired_workers}, and it scales the group if the script does. If autoscaling is enabled, it adjusts the count again on its next pass.`, + onConfirmed: async () => { + try { + job_id = ( + await ConfigService.testAutoscaling({ + workerGroup: worker_group, + requestBody: { desired_workers, integration: $state.snapshot(integration) } + }) + ).job_id + } catch (e: any) { + failed = true + sendUserToast('Test scaling failed', true, [], e?.body ?? e?.message) + } + } + }) + if (!confirmed || failed) return + if (job_id) { + const id = job_id + sendUserToast('Autoscaling script queued in the admins workspace', false, [ + { + label: 'See job', + callback: () => window.open('/run/' + id + '?workspace=admins', '_blank') + } + ]) + } else { + sendUserToast(`Scaled ${worker_group} to ${desired_workers} workers`) + } + } + let noTagsToCount = $derived(!!config?.enabled && !group_has_tags && !config.custom_tags?.length) let collapsed: boolean = $state(untrack(() => !noTagsToCount)) @@ -266,22 +319,11 @@ />
    - Test scaling
    - + workers
    @@ -317,9 +359,11 @@
    - +
    - + workers
    @@ -547,3 +591,7 @@ + + + + diff --git a/frontend/src/lib/components/WorkerGroup.svelte b/frontend/src/lib/components/WorkerGroup.svelte index 584d3bf2d5..3ee0807c50 100644 --- a/frontend/src/lib/components/WorkerGroup.svelte +++ b/frontend/src/lib/components/WorkerGroup.svelte @@ -1078,6 +1078,7 @@
    0 From 6b56656bd650f2db5fbd74e23b55b926c6f69dd7 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Fri, 23 Oct 2026 14:47:03 +0200 Subject: [PATCH 057/101] fix: keep a staged flow path across reloads and follow moves in session tabs (#11967) Co-authored-by: Claude Opus 5.5 (1M context) --- .../src/lib/components/FlowBuilder.svelte | 21 +++++++++---------- frontend/src/lib/components/flow_builder.ts | 6 +++--- .../components/sessions/FlowEditorView.svelte | 4 ++-- .../sessions/RawAppEditorView.svelte | 10 ++++++++- .../sessions/ScriptEditorView.svelte | 2 +- .../flows/edit/[...path]/+page.svelte | 21 ++++++++++++------- 6 files changed, 38 insertions(+), 26 deletions(-) diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index a919fc82f5..86fa1d5864 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -135,8 +135,8 @@ let { initialPath = $bindable(''), /** The draft row's own path (the URL path). Unlike `initialPath`, which the - * route re-seeds from `draft_path` so the topbar shows the pending name, - * this stays where the item actually is. */ + * route re-seeds from a draft-only flow's `draft_path` so the topbar shows + * the pending name, this stays where the item actually is. */ userDraftPath = '', onTakeLatest = undefined, pathStoreInit = undefined, @@ -1436,18 +1436,17 @@ readFieldsRecursively(flowStore.val) } }) - // Sync `$pathStore` from `flowStore.val.path` (which `initFlow` populates - // from the loaded flow — including the draft's rename, when there is one). - // This effect only tracks `flowStore.val.path`, so popover edits that go - // straight to `$pathStore` don't trigger it and aren't overwritten. - // Replaces the previous `$pathStore = initialPath` push (added in #2536 for - // the VSCode extension), which silently dropped any draft-renamed path - // because `initialPath` is the URL, not the loaded path. + // Sync `$pathStore` from the loaded flow: its staged `draft_path` when the + // draft has one, else its `path`. Seeding from `path` alone would make the + // effect below drop a staged move on every reload, and deploy would then + // create at a taken path. Only `flowStore.val.path` is tracked, so popover + // edits that go straight to `$pathStore` aren't overwritten. $effect.pre(() => { // `flowStore.val` is typed `OpenFlow` here but `initFlow` actually puts a // `Flow` (with `path`) in it. - const p = (flowStore.val as Flow | undefined)?.path - if (p) untrack(() => ($pathStore = p)) + const flow = flowStore.val as (Flow & { draft_path?: string }) | undefined + const p = flow?.path + if (p) untrack(() => ($pathStore = flow?.draft_path || p)) }) // Persist the user-typed path into the draft JSON as `draft_path` diff --git a/frontend/src/lib/components/flow_builder.ts b/frontend/src/lib/components/flow_builder.ts index 1a4b7e5c26..8f2f634643 100644 --- a/frontend/src/lib/components/flow_builder.ts +++ b/frontend/src/lib/components/flow_builder.ts @@ -10,9 +10,9 @@ import type { WorkspaceItem } from './workspacePicker' export type FlowBuilderProps = { initialPath?: string - /** The draft row's own path (the URL path). `initialPath` is re-seeded from the - * draft's `draft_path` so the topbar shows the pending name, so it can't be used - * to resolve what is actually deployed. */ + /** The draft row's own path (the URL path). For a draft-only flow `initialPath` is + * re-seeded from the draft's `draft_path` so the topbar shows the pending name, so + * it can't be used to resolve what is actually deployed. */ userDraftPath?: string /** Moves the draft's base to the head and keeps its content; offered in the diff * drawer while the draft is behind, and called with the version the drawer shows diff --git a/frontend/src/lib/components/sessions/FlowEditorView.svelte b/frontend/src/lib/components/sessions/FlowEditorView.svelte index 9e34b1f7a4..ae5e25097d 100644 --- a/frontend/src/lib/components/sessions/FlowEditorView.svelte +++ b/frontend/src/lib/components/sessions/FlowEditorView.svelte @@ -131,10 +131,10 @@ onDetails={onSeeDetails} condensedHeader={true} customUi={{ topBar: { aiBuilder: false } }} - onDeploy={() => { + onDeploy={(e) => { // FlowBuilder has no deploy toast and the session stays put, so toast here. sendUserToast('Deployed') - runtime.itemDeployed(workspaceId, 'flow', path) + runtime.itemDeployed(workspaceId, 'flow', path, e.path) }} /> {/snippet} diff --git a/frontend/src/lib/components/sessions/RawAppEditorView.svelte b/frontend/src/lib/components/sessions/RawAppEditorView.svelte index 8bff98802c..81e219f7f4 100644 --- a/frontend/src/lib/components/sessions/RawAppEditorView.svelte +++ b/frontend/src/lib/components/sessions/RawAppEditorView.svelte @@ -148,7 +148,15 @@ if (dp !== undefined) { surfacedDraftPath = true if (val.draft_path !== dp) val.draft_path = dp - } else if (surfacedDraftPath && val.draft_path !== undefined) { + } else if ( + surfacedDraftPath && + val.draft_path !== undefined && + // Equal to the saved path, it is not stale: a deploy just moved the app + // there. Clearing it would schedule a save of this cell at the old path + // that lands after the deploy discarded it, and the moved draft row + // would come back on the new path. + val.draft_path !== cell.saved.val?.path + ) { val.draft_path = undefined } }) diff --git a/frontend/src/lib/components/sessions/ScriptEditorView.svelte b/frontend/src/lib/components/sessions/ScriptEditorView.svelte index ab1bac52c9..5248f14164 100644 --- a/frontend/src/lib/components/sessions/ScriptEditorView.svelte +++ b/frontend/src/lib/components/sessions/ScriptEditorView.svelte @@ -124,7 +124,7 @@ // Fires on every deploy (primary, "Deploy & Stay here", and lib — we // ignore e.stay since the session always stays). sendUserToast('Deployed') - runtime.itemDeployed(workspaceId, 'script', e.path) + runtime.itemDeployed(workspaceId, 'script', path, e.path) }} /> {/if} diff --git a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte index cbaf2fd935..8f2ae0b65c 100644 --- a/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/flows/edit/[...path]/+page.svelte @@ -339,7 +339,6 @@ v = undefined } if (tok !== loadFlowToken) return - version = v const backendFlow = await FlowService.getFlowByPath({ workspace: $workspaceStore!, @@ -376,6 +375,9 @@ // Layer the draft (`.draft`, if any) over the deployed payload at the field // level. See /scripts/edit's loader for the rationale. const { draft: draftFromBackend, ...deployedFlow } = backendFlow as any + // Set together with the base below: across the await above, a new head beside + // the previous load's base reads as stale, and the stale prompt latches open. + version = v // The flow_version the draft forked from; undefined when editing the deployed // flow directly (no draft) or for a draft never forked from a deploy. draftBaseVersion = backendFlow.draft_base @@ -395,13 +397,16 @@ deployedBaseline = backendFlow.no_deployed ? undefined : (structuredClone($state.snapshot(deployedFlow)) as Flow) - // Surface the saved `draft_path` to the Path widget so the topbar shows the - // pending name, not the `draft_{uuid}` URL. Else the widget seeds from the - // URL, the first edit clobbers `draft_path`, and the friendly name is lost. - // Otherwise the URL, set on every load: this route instance is reused when the - // editor follows its draft to a moved item, and the path it opened on is where - // deploy would look for the flow. - const renderedDraftPath = (effectiveFlow as any).draft_path as string | undefined + // A draft-only flow surfaces its saved `draft_path` to the Path widget so the + // topbar shows the pending name, not the `draft_{uuid}` URL. Else the widget + // seeds from the URL, the first edit clobbers `draft_path`, and the friendly + // name is lost. A deployed flow keeps the URL even with a staged move: it is + // where deploy updates the flow and where its triggers live (FlowBuilder shows + // the staged path). Set on every load: this route instance is reused when the + // editor follows its draft to a moved item. + const renderedDraftPath = backendFlow.no_deployed + ? ((effectiveFlow as any).draft_path as string | undefined) + : undefined flowInitialPath = renderedDraftPath || (page.params.path ?? '') // "Load another user's draft" handoff: render their value over the deployed From 28d2556c941f66cad353eca3809f43e8d8cf3c05 Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:47:34 +0200 Subject: [PATCH 058/101] fix: send app editor inspector picks to a new AI session as a chip (#11966) --- .../copilot/chat/AIChatManager.svelte.ts | 21 ++- .../copilot/chat/AIChatManager.test.ts | 20 +++ .../raw_apps/InlineElementPrompt.svelte | 25 ++- .../components/raw_apps/RawAppEditor.svelte | 145 +++++++++++++----- .../components/sessions/SessionWrapper.svelte | 4 +- .../components/sessions/sessionMirrorPlan.ts | 4 +- .../sessions/sessionState.svelte.ts | 14 +- .../sessions/sessionSwitch.svelte.ts | 19 ++- .../components/sessions/sessionSwitch.test.ts | 27 ++++ 9 files changed, 219 insertions(+), 60 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 72928ec7df..cf63cb420c 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -2467,12 +2467,12 @@ export class AIChatManager implements ChatViewHost { * * Gated on `sendInFlight` as well as `loading`: `loading` only rises after a * send's attachment upkeep, so between the two a click would slip past. */ - sendOrQueue(text: string) { + sendOrQueue(text: string, context?: ContextElement[]) { if (this.loading || this.sendInFlight || this.sendPending) { - this.queueMessage(text) + this.queueMessage(text, [], context) return } - void this.sendRequest({ instructions: text }) + void this.sendRequest({ instructions: text, contextOverride: context }) } /** Remove the queued message and put it back into the input, images included. */ @@ -3731,7 +3731,10 @@ export class AIChatManager implements ChatViewHost { options.images ?? [], options.files ?? [] ) === true - if (taken) this.#restoreMentionContext(options.contextOverride, requestedMode) + if (taken) { + this.#restoreDomContext(options.contextOverride, true) + this.#restoreMentionContext(options.contextOverride, requestedMode) + } } return false } @@ -3841,7 +3844,10 @@ export class AIChatManager implements ChatViewHost { // mentions on that draft and every turn after it. const taken = this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) this.#restoreMentionContext(options.contextOverride, requestedMode) + if (taken) { + this.#restoreDomContext(options.contextOverride, true) + this.#restoreMentionContext(options.contextOverride, requestedMode) + } } sendUserToast( `Could not prepare the session before sending: ${ @@ -3891,7 +3897,10 @@ export class AIChatManager implements ChatViewHost { // text, only if the composer took it. const taken = this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) this.#restoreMentionContext(options.contextOverride, requestedMode) + if (taken) { + this.#restoreDomContext(options.contextOverride, true) + this.#restoreMentionContext(options.contextOverride, requestedMode) + } } return true } diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 1fd92aa67d..874a147026 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -2891,6 +2891,26 @@ describe('AIChatManager queued messages', () => { expect(manager.contextManager.getSelectedContext()).toEqual([mention]) }) + // A hand-off's chip only ever lived in contextOverride, never in the selection. + it('restores a DOM chip carried only by contextOverride when the preflight is cancelled', async () => { + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + const chip = { + type: 'app_dom_selector' as const, + selector: 'h1', + appPath: 'f/app', + tagName: 'h1' + } + manager.contextManager.setSelectedContext([]) + manager.beforeSend = vi.fn().mockImplementation(async () => { + manager.cancel('user_cancelled') + }) + + await manager.sendRequest({ instructions: 'make this bigger', contextOverride: [chip] }) + + expect(manager.contextManager.getSelectedContext()).toMatchObject([{ selector: 'h1' }]) + }) + // The gate, and the reason the restore is not unconditional: an occupied // composer declines the dead draft's text, and its mentions would then ride the // draft the user is writing now and every turn after it. diff --git a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte b/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte index 33a6617ace..721b3b4bfe 100644 --- a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte +++ b/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte @@ -7,6 +7,7 @@ x, y, label, + inNewSession = false, onSend, onClose }: { @@ -15,11 +16,15 @@ y: number /** Short element label shown as the placeholder hint (e.g. "button.btn"). */ label: string - onSend: (prompt: string) => void + /** Sending leaves this page for a new AI session, so the hint says so. */ + inNewSession?: boolean + /** Resolving to `false` keeps the box open with its text. */ + onSend: (prompt: string) => void | Promise onClose: () => void } = $props() let value = $state('') + let sending = $state(false) let textarea = $state(undefined) // Focus when the anchor first appears (the element was just selected). @@ -27,16 +32,20 @@ textarea?.focus() }) - function submit() { + async function submit() { const v = value.trim() - if (!v) return - onSend(v) - value = '' + if (!v || sending) return + sending = true + try { + if ((await onSend(v)) !== false) value = '' + } finally { + sending = false + } } + the prompt to the session chat (or a new session) with that element as context. -->
    { if (e.key === 'Enter' && !e.shiftKey) { @@ -67,7 +76,7 @@ variant="accent" iconOnly startIcon={{ icon: ArrowUp }} - disabled={value.trim().length === 0} + disabled={sending || value.trim().length === 0} on:click={submit} title="Send" /> diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 3d22087317..67a3ccbf6a 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -48,10 +48,15 @@ LintResult, InspectorElementInfo } from '../copilot/chat/app/core' - import { createAppSelectedContext, type AppCodeSelectionElement } from '../copilot/chat/context' + import { + createAppDomSelectorElement, + createAppSelectedContext, + type AppCodeSelectionElement + } from '../copilot/chat/context' import { captureScale, MAX_IMAGE_EDGE } from '../copilot/chat/imageUtils' import { rawAppLintStore } from './lintStore' import { dbSchemas, userStore } from '$lib/stores' + import { copilotInfo } from '$lib/aiStore' import { useActingUser } from '$lib/actingUser.svelte' import { appPreviewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' import RawAppSdkConsent from './RawAppSdkConsent.svelte' @@ -77,6 +82,8 @@ import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { UserDraft } from '$lib/userDraft.svelte' import { setOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext' + import { prefersSessionHandoff } from '$lib/components/copilot/chat/global/gate' + import { openSourceInSession } from '$lib/components/sessions/sessionSwitch.svelte' import { buildDataTableWhitelist, parseDataTableRef, @@ -478,6 +485,12 @@ addEventListener('message', function (e) { } let previewIframe: HTMLIFrameElement | undefined = $state(undefined) let previewIframeLoaded = $state(false) + // The shell answers every build with `inspectorClear`, and the UI Builder + // rebuilds unchanged code (twice on load). Only a changed build can move what a + // chip points at, so the clears of the others are skipped: they would drop a + // chip handed in from the editor before it is sent. + let previewShellBuild: { css: string; js: string } | undefined = undefined + let previewClearsToSkip = 0 // Sandboxed only: the handshake's port, the one channel to the preview that // can't reach a document app code navigated the frame to. let previewPort: MessagePort | undefined = undefined @@ -1544,7 +1557,7 @@ addEventListener('message', function (e) { // Escape inside the preview exits inspect mode, and also dismisses a lingering // green "selected" overlay after a pick (which auto-disables hover). if (fromPreview && e.data.type === 'previewEscape') { - if (inspectorEnabled || inspectorElement || selectedDomSelectors.length > 0) { + if (inspectorEnabled || inspectorElement || previewSelectors.length > 0) { disableInspector() } return @@ -1581,15 +1594,28 @@ addEventListener('message', function (e) { // picking (the chip list, not the harness, holds the selection). Shift // held → add to the selection; a plain click replaces it. if (onInspectorSelect) onInspectorSelect(inspectorElement, !!e.data.additive) - else inspectorEnabled = false + else { + inspectorEnabled = false + // The preview keeps picking until told to stop. + postToPreview({ type: 'inspectorDisable' }) + } return } if (fromPreview && e.data.type === 'inspectorDeselect') { // User clicked × on a selected overlay in the preview — drop that chip. if (typeof e.data.selector === 'string') onInspectorDeselect?.(e.data.selector) + if (!onInspectorSelect && e.data.selector === inspectorElement?.path) { + inspectorElement = undefined + } return } if (fromPreview && e.data.type === 'inspectorClear') { + if (previewClearsToSkip > 0) { + previewClearsToSkip-- + // The shell dropped its outlines along with the old DOM. + postToPreview({ type: 'inspectorSetSelection', selectors: [...previewSelectors] }) + return + } inspectorElement = undefined // A rebuild invalidates the selection — clear all session chips. onInspectorClearAll?.() @@ -1851,6 +1877,13 @@ addEventListener('message', function (e) { if (previewSdkPending || previewUserPending || !previewIframeLoaded) return runtimeError = undefined emptyRender = false + if ( + !previewShellBuild || + (previewShellBuild.css === build.css && previewShellBuild.js === build.js) + ) { + previewClearsToSkip++ + } + previewShellBuild = build postToPreview({ type: 'preview', css: build.css, @@ -2106,19 +2139,56 @@ addEventListener('message', function (e) { return { text } } - // ---- Inline "prompt this element" mini-composer (session preview only) ---- + // What the preview outlines as selected: the session's chips when a session + // drives the inspector, else this editor's single pick. + const previewSelectors = $derived.by(() => + onInspectorSelect ? selectedDomSelectors : inspectorElement ? [inspectorElement.path] : [] + ) + + // ---- Inline "prompt this element" mini-composer ---- // Anchored over the most-recently selected element in the live preview. It's a // host overlay (position: fixed in the top document) computed from the element's // rect inside the preview iframe, repositioned as the preview scrolls. let inlinePromptDismissed = $state(false) let inlinePromptPos = $state<{ x: number; y: number } | undefined>(undefined) let inlinePromptLabel = $state('') + // Outside a session, with sessions on, there is no docked chat to take the pick: + // the prompt opens a new session instead, carrying the element as its chip. + const inlinePrompt: ((selector: string, prompt: string) => void | Promise) | undefined = + $derived( + onInlinePrompt ?? + (!onInspectorSelect && sessionOpen && prefersSessionHandoff(!$roleCaps.code) + ? sendPickToNewSession + : undefined) + ) const inlinePromptSelector = $derived( - onInlinePrompt && selectedDomSelectors.length > 0 - ? selectedDomSelectors[selectedDomSelectors.length - 1] + inlinePrompt && previewSelectors.length > 0 + ? previewSelectors[previewSelectors.length - 1] : undefined ) + async function sendPickToNewSession(selector: string, prompt: string) { + const el = inspectorElement + if (!sessionOpen || !el) return false + try { + await openSourceInSession(sessionOpen, { + seedPrompt: prompt, + autoSend: true, + seedDomElement: createAppDomSelectorElement({ + selector, + appPath: sessionOpen.target.path, + tagName: el.tagName, + id: el.id, + className: el.className + }) + }) + return true + } catch (e) { + sendUserToast(e instanceof Error ? e.message : String(e), true) + return false + } + } + function shortElementLabel(el: { tagName: string; id: string; className: string }): string { const tag = el.tagName.toLowerCase() const id = el.id ? `#${el.id}` : '' @@ -2181,7 +2251,7 @@ addEventListener('message', function (e) { // overlay pinned as the host scrolls/resizes. The preview's own scrolls arrive // as `previewScroll` messages. inlinePromptSelector - selectedDomSelectors + previewSelectors previewIframeLoaded inlinePromptDismissed updateInlinePromptPos() @@ -2299,6 +2369,8 @@ addEventListener('message', function (e) { }) function onPreviewShellReady() { previewIframeLoaded = true + previewShellBuild = undefined + previewClearsToSkip = 0 // Replay the last build so the preview repopulates without // waiting for the user to trigger another bundle. if (lastBuild) { @@ -2342,7 +2414,7 @@ addEventListener('message', function (e) { // Push the chat's DOM-selector chips into the preview (source of truth): // the harness renders one highlight per selector. Re-posts on every // selection change and on preview (re)load. - const selectors = selectedDomSelectors + const selectors = previewSelectors if (previewIframeLoaded) { postToPreview({ type: 'inspectorSetSelection', selectors: [...selectors] }) } @@ -2491,7 +2563,7 @@ addEventListener('message', function (e) { // selection (highlights + the inline prompt), so a chip-only selection // (picking already toggled off) must still be dismissable. Bail only // when there is genuinely nothing to dismiss. - if (!inspectorEnabled && !inspectorElement && selectedDomSelectors.length === 0) return + if (!inspectorEnabled && !inspectorElement && previewSelectors.length === 0) return inspectorEnabled = false // `inspectorDisable` only stops hover/click; the green "selected" // overlay from a prior pick persists until we explicitly clear it. @@ -2514,7 +2586,7 @@ addEventListener('message', function (e) { const onEscapeCapture = (e: KeyboardEvent) => { if ( e.key === 'Escape' && - (inspectorEnabled || inspectorElement || selectedDomSelectors.length > 0) + (inspectorEnabled || inspectorElement || previewSelectors.length > 0) ) { disableInspector() e.stopImmediatePropagation() @@ -2873,28 +2945,30 @@ addEventListener('message', function (e) { {bundlerType} {/if} -
    -{#if inlinePromptPos && inlinePromptSelector && onInlinePrompt} +{#if inlinePromptPos && inlinePromptSelector && inlinePrompt} @@ -3063,8 +3137,9 @@ addEventListener('message', function (e) { x={inlinePromptPos.x} y={inlinePromptPos.y} label={inlinePromptLabel} - onSend={(prompt) => { - onInlinePrompt?.(inlinePromptSelector!, prompt) + inNewSession={!onInlinePrompt} + onSend={async (prompt) => { + if ((await inlinePrompt?.(inlinePromptSelector!, prompt)) === false) return false inlinePromptDismissed = true }} onClose={() => (inlinePromptDismissed = true)} diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index d26dd76c3b..a27682011a 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -61,6 +61,7 @@ getSessionDraftAttachments, setSessionDraftAttachments, peekSessionAutoSend, + getSessionAutoSendDomElement, takeSessionAutoSend, reconcileAfterWorkspaceChange, renameSession, @@ -158,13 +159,14 @@ if (!session?.autoSendDraftAt || !runtime) return untrack(() => { const prompt = getSessionDraftPrompt(sessionId) + const domElement = getSessionAutoSendDomElement(sessionId) // takeSessionAutoSend clears the intent whether or not it is still // fresh, so this cannot re-enter on the next dependency change. if (!takeSessionAutoSend(sessionId) || !prompt) return // sendOrQueue, not sendRequest: a reused session may already be mid-turn. // The runtime's beforeSend awaits loadCopilot for the committed // workspace, so this cannot race the model config on a cold session. - runtime.manager.sendOrQueue(prompt) + runtime.manager.sendOrQueue(prompt, domElement ? [domElement] : undefined) }) }) diff --git a/frontend/src/lib/components/sessions/sessionMirrorPlan.ts b/frontend/src/lib/components/sessions/sessionMirrorPlan.ts index 5d40c35e3b..1aa970aa47 100644 --- a/frontend/src/lib/components/sessions/sessionMirrorPlan.ts +++ b/frontend/src/lib/components/sessions/sessionMirrorPlan.ts @@ -79,8 +79,8 @@ export function isFallbackStorage(name: string): boolean { /** * The part of a session record the backup keeps. Left out on purpose: `name` (a * per-browser legacy label), the unsent-draft fields (`pending_*`, `draftPrompt`, - * `autoSendDraftAt`), `workspace_root_id` (derived on import), `transient`, `restoredAt` - * (this browser's clock), and the two fields reading a session bumps (`lastSeenCount`, + * `autoSendDraftAt`, `autoSendDomElement`), `workspace_root_id` (derived on import), + * `transient`, `restoredAt` (this browser's clock), and the two fields reading a session bumps (`lastSeenCount`, * `lastActivityAt`) — so opening a session and reading its new messages never costs a push. */ export type SessionHead = Pick< diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index 4a3abebb4f..b6dd7d7d54 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -29,6 +29,7 @@ import { deleteItemsForSession } from '../copilot/chat/files/attachedFilesDB' import { deleteArtifactsForSession } from '../copilot/chat/artifacts/artifactsDB' import { deleteSessionChats } from '../copilot/chat/HistoryManager.svelte' import type { DraftAttachments } from '../copilot/chat/messageDraft.svelte' +import type { AppDomSelectorElement } from '../copilot/chat/context' import { markSessionDirty, markSessionRemoved, @@ -170,6 +171,10 @@ export type Session = { // would otherwise leave a session armed forever and fire on some later visit. // Consumed exactly once, by takeSessionAutoSend. autoSendDraftAt?: number + // The element a preview pick hands over with the auto-sent prompt, sent as its + // chip. Lives and dies with `autoSendDraftAt`: a prompt like "make this bigger" + // must never go out without the element it names. + autoSendDomElement?: AppDomSelectorElement } // One preview tab: `url` is the URL we command the iframe to load, `loc` the @@ -421,13 +426,19 @@ const AUTO_SEND_TTL_MS = 5 * 60_000 // Mark this session's draft prompt for sending on arrival. Written straight to // the record (not via setSessionDraftPrompt's debounce) because the navigation // that follows must not outrun it. -export function setSessionAutoSend(sessionId: string): void { +export function setSessionAutoSend(sessionId: string, domElement?: AppDomSelectorElement): void { const s = sessionState.sessions.find((x) => x.id === sessionId) if (!s) return s.autoSendDraftAt = Date.now() + s.autoSendDomElement = domElement persistTouched(s) } +// The element armed with the auto-send intent; read before takeSessionAutoSend clears both. +export function getSessionAutoSendDomElement(sessionId: string): AppDomSelectorElement | undefined { + return sessionState.sessions.find((x) => x.id === sessionId)?.autoSendDomElement +} + function autoSendIsFresh(s: Session | undefined): boolean { return !!s?.autoSendDraftAt && Date.now() - s.autoSendDraftAt < AUTO_SEND_TTL_MS } @@ -448,6 +459,7 @@ export function takeSessionAutoSend(sessionId: string): boolean { if (!s?.autoSendDraftAt) return false const fresh = autoSendIsFresh(s) delete s.autoSendDraftAt + delete s.autoSendDomElement persistTouched(s) return fresh } diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index 30b7792487..fc99c963b3 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -20,6 +20,10 @@ import { findMountedOpenInSessionSource } from './openInSessionContext' // Type-only: erased at compile time, so the component graph stays out of this // navigation seam (see the dynamic import in openEditorInSession). import type { OpenInSessionSource } from './OpenInSessionButton.svelte' +import type { AppDomSelectorElement } from '../copilot/chat/context' + +// `seedDomElement` rides only with `autoSend`: it is the chip of the prompt being sent. +type SeedOpts = { seedPrompt?: string; autoSend?: boolean; seedDomElement?: AppDomSelectorElement } // The session/navigation switch turns the global rail into either the workspace // navigation (navigation mode) or the sessions sidebar (session mode). Session @@ -171,7 +175,7 @@ export async function openEditorInSession( target: SessionTarget, workspaceId?: string, previewParams?: Record, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise { await openInSession( withPreviewParams(sessionTargetHref(target), previewParams), @@ -186,7 +190,7 @@ export async function openEditorInSession( export async function openPageInSession( href: string, workspaceId?: string, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise { await openInSession(href, workspaceId, opts) } @@ -194,7 +198,7 @@ export async function openPageInSession( async function openInSession( url: string | undefined, workspaceId?: string, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise { await goto(await sessionHrefFor(url, workspaceId, opts)) } @@ -212,7 +216,7 @@ export function editorSessionHref( async function sessionHrefFor( url: string | undefined, workspaceId?: string, - opts?: { seedPrompt?: string; autoSend?: boolean } + opts?: SeedOpts ): Promise { // Seed the fresh session's preview with a single tab on `url` so it opens // straight onto what the caller wants (resetSessionPreviewTabs also writes @@ -221,7 +225,7 @@ async function sessionHrefFor( if (workspaceId) setSessionPendingWorkspace(session.id, workspaceId) if (opts?.seedPrompt) { setSessionDraftPrompt(session.id, opts.seedPrompt) - if (opts.autoSend) setSessionAutoSend(session.id) + if (opts.autoSend) setSessionAutoSend(session.id, opts.seedDomElement) } if (url) { // Dynamic import: a static one would drag the runtime's heavy graph @@ -243,12 +247,13 @@ async function sessionHrefFor( // step; `OpenInSessionButton` is the declarative equivalent. export async function openSourceInSession( source: OpenInSessionSource, - overrides?: { previewParams?: Record; seedPrompt?: string; autoSend?: boolean } + overrides?: { previewParams?: Record } & SeedOpts ): Promise { await source.beforeOpen?.() const opts = { seedPrompt: overrides?.seedPrompt ?? source.seedPrompt, - autoSend: overrides?.autoSend ?? source.autoSend + autoSend: overrides?.autoSend ?? source.autoSend, + seedDomElement: overrides?.seedDomElement } if (source.target) { await openEditorInSession( diff --git a/frontend/src/lib/components/sessions/sessionSwitch.test.ts b/frontend/src/lib/components/sessions/sessionSwitch.test.ts index 497e3cbad9..afacf41d51 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.test.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.test.ts @@ -9,12 +9,14 @@ import { takeNewSessionSeed } from './sessionSwitch.svelte' import { + getSessionAutoSendDomElement, peekSessionAutoSend, sessionState, takeSessionAutoSend, type Session } from './sessionState.svelte' import { usersWorkspaceStore, workspaceStore, type UserWorkspace } from '$lib/stores' +import { createAppDomSelectorElement } from '../copilot/chat/context' vi.mock('$lib/navigation', () => ({ goto: vi.fn().mockResolvedValue(undefined) })) import { goto } from '$lib/navigation' @@ -176,6 +178,31 @@ describe('auto-send intent', () => { } }) + // A picked element names what the prompt is about ("make this bigger"): it must + // arrive with the prompt and be consumed with it, never outlive the intent. + it('carries a picked element with the prompt and clears it on claim', async () => { + const prevCurrent = sessionState.currentSessionId + let createdId: string | undefined + const el = createAppDomSelectorElement({ + selector: 'main > h1', + appPath: 'u/me/app', + tagName: 'H1' + }) + try { + await openSourceInSession( + { target: { kind: 'raw_app', path: 'u/me/app' } }, + { seedPrompt: 'make this bigger', autoSend: true, seedDomElement: el } + ) + createdId = sessionState.currentSessionId! + expect(getSessionAutoSendDomElement(createdId)).toEqual(el) + expect(takeSessionAutoSend(createdId)).toBe(true) + expect(getSessionAutoSendDomElement(createdId)).toBeUndefined() + } finally { + sessionState.sessions = sessionState.sessions.filter((s) => s.id !== createdId) + sessionState.currentSessionId = prevCurrent + } + }) + // `goto` resolves even when a beforeNavigate cancels it, so an abandoned // hand-off leaves the session armed. The claim must go stale rather than fire // a turn at whatever the user is doing whenever that session next opens. From 725b15f546cf20c2e5908acffb105d73fe907558 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Fri, 23 Oct 2026 14:49:05 +0200 Subject: [PATCH 059/101] fix: change an app's access mode under the deploy row lock (#11965) * fix: change an app's access mode under the deploy row lock Co-Authored-By: Claude Opus 5.5 (1M context) * fix: defer a mode change to deploy on an app run as another user Co-Authored-By: Claude Opus 5.5 (1M context) * fix: hold the access toggle while its change is in flight Co-Authored-By: Claude Opus 5.5 (1M context) * revert: leave the deploy panel's access toggle to the settings drawer PR Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep the caller's draft on a mode-only app update Co-Authored-By: Claude Opus 5.5 (1M context) * fix: refuse a builder's mode-only change on an unsandboxed app Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- backend/tests/app_access_mode_only.rs | 311 ++++++++++++++++++++++++++ backend/tests/dependency_map.rs | 1 + backend/windmill-api/openapi.yaml | 4 + backend/windmill-api/src/apps.rs | 145 +++++++++--- docs/operator-builder-rights.md | 11 +- 5 files changed, 434 insertions(+), 38 deletions(-) create mode 100644 backend/tests/app_access_mode_only.rs diff --git a/backend/tests/app_access_mode_only.rs b/backend/tests/app_access_mode_only.rs new file mode 100644 index 0000000000..b113e9de9a --- /dev/null +++ b/backend/tests/app_access_mode_only.rs @@ -0,0 +1,311 @@ +//! `EditApp.execution_mode`: changing who may open an app without sending its policy. +//! +//! The change is applied to the deployed policy under the row lock a deploy takes, so it keeps +//! every other field a concurrent deploy wrote. It is held to the rules a policy write is held +//! to, and it is refused to a caller who could not keep the app's run-as user, since a policy +//! write from them would rebind it. +//! +//! One test: the protection rules and the workspace roles are cached per workspace id across +//! the process, and every test here uses `test-workspace`. +//! +//! Users from the `base` fixture: +//! test-user (admin, token SECRET_TOKEN) +//! test-user-2 (non-admin, token SECRET_TOKEN_2) +//! test-user-3 (made a compose-only operator below, token SECRET_TOKEN_3) + +use reqwest::multipart; +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_common::workspaces::invalidate_protection_rules_cache; +use windmill_test_utils::*; + +const ADMIN: &str = "SECRET_TOKEN"; +const USER: &str = "SECRET_TOKEN_2"; +const BUILDER: &str = "SECRET_TOKEN_3"; + +fn client() -> reqwest::Client { + reqwest::Client::new() +} + +async fn update(ws: &str, path: &str, token: &str, body: Value) -> anyhow::Result<(u16, String)> { + let resp = client() + .post(format!("{ws}/apps/update/{path}")) + .bearer_auth(token) + .json(&body) + .send() + .await?; + Ok((resp.status().as_u16(), resp.text().await?)) +} + +async fn create(ws: &str, token: &str, path: &str, policy: Value) -> anyhow::Result<()> { + let resp = client() + .post(format!("{ws}/apps/create")) + .bearer_auth(token) + .json(&json!({ "path": path, "summary": "", "value": {}, "policy": policy })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create {path}: {}", resp.text().await?); + Ok(()) +} + +/// An anonymous, sandboxed raw app with no runnables, as a builder may deploy one. +async fn create_raw(ws: &str, token: &str, path: &str) -> anyhow::Result<()> { + let app = json!({ + "path": path, + "summary": "", + "value": { "files": {}, "runnables": {} }, + "policy": { "execution_mode": "anonymous", "sandbox": true, "triggerables_v2": {} }, + }); + let form = multipart::Form::new() + .part( + "app", + multipart::Part::text(app.to_string()).mime_str("application/json")?, + ) + .part("js", multipart::Part::text("console.log('app')")); + let resp = client() + .post(format!("{ws}/apps/create_raw")) + .bearer_auth(token) + .multipart(form) + .send() + .await?; + assert_eq!( + resp.status(), + 201, + "create_raw {path}: {}", + resp.text().await? + ); + Ok(()) +} + +async fn policy(db: &Pool, path: &str) -> anyhow::Result { + Ok(sqlx::query_scalar( + "SELECT policy FROM app WHERE path = $1 AND workspace_id = 'test-workspace'", + ) + .bind(path) + .fetch_one(db) + .await?) +} + +fn triggerable(key: &str) -> Value { + json!({ key: { "static_inputs": {}, "one_of_inputs": {} } }) +} + +#[sqlx::test(fixtures("base"))] +async fn test_access_mode_only_update(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + invalidate_protection_rules_cache("test-workspace"); + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + + // ======================================== + // 1. The mode alone changes; every other field of the deployed policy stays. + // ======================================== + const SHARED: &str = "u/test-user-2/shared"; + create( + &ws, + ADMIN, + SHARED, + json!({ + "execution_mode": "publisher", + "triggerables_v2": triggerable("c:script/u/test-user/noop"), + "sandbox": true, + "allowed_s3_keys": [{ "s3_path": "a/b.txt" }], + }), + ) + .await?; + let before = policy(&db, SHARED).await?; + assert_eq!(before["on_behalf_of"], "u/test-user"); + + let (status, body) = + update(&ws, SHARED, ADMIN, json!({ "execution_mode": "anonymous" })).await?; + assert_eq!(status, 200, "{body}"); + let mut after = policy(&db, SHARED).await?; + assert_eq!(after["execution_mode"], "anonymous"); + after["execution_mode"] = before["execution_mode"].clone(); + assert_eq!( + after, before, + "a mode-only change must keep every other policy field" + ); + + // Sending a policy too is ambiguous about which mode wins. + let (status, _) = update( + &ws, + SHARED, + ADMIN, + json!({ "execution_mode": "publisher", "policy": { "execution_mode": "anonymous" } }), + ) + .await?; + assert_eq!(status, 400); + + // ======================================== + // 2. Someone who cannot keep the run-as user cannot change the mode of an app that runs + // as someone else, even with write access to it. + // ======================================== + let (status, body) = + update(&ws, SHARED, USER, json!({ "execution_mode": "publisher" })).await?; + assert_eq!(status, 403, "{body}"); + assert!(body.contains("wm_deployers"), "{body}"); + assert_eq!(policy(&db, SHARED).await?["execution_mode"], "anonymous"); + + // ======================================== + // 3. A policy without a mode keeps the deployed one. + // ======================================== + const OWN: &str = "u/test-user-2/own"; + create(&ws, USER, OWN, json!({ "execution_mode": "publisher" })).await?; + sqlx::query( + "INSERT INTO draft (workspace_id, path, typ, value, email) + VALUES ('test-workspace', $1, 'app', '{}', 'test2@windmill.dev')", + ) + .bind(OWN) + .execute(&db) + .await?; + let (status, body) = update(&ws, OWN, USER, json!({ "execution_mode": "anonymous" })).await?; + assert_eq!(status, 200, "{body}"); + let drafts: i64 = sqlx::query_scalar( + "SELECT count(*) FROM draft WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(OWN) + .fetch_one(&db) + .await?; + assert_eq!(drafts, 1, "a mode-only change must keep the caller's draft"); + let (status, body) = update( + &ws, + OWN, + USER, + json!({ "value": { "v": 2 }, "policy": { "triggerables_v2": triggerable("c:script/f/x/new") } }), + ) + .await?; + assert_eq!(status, 200, "{body}"); + let p = policy(&db, OWN).await?; + assert_eq!(p["execution_mode"], "anonymous"); + assert!( + p["triggerables_v2"].get("c:script/f/x/new").is_some(), + "{p}" + ); + + // ======================================== + // 4. A compose-only operator: an omitted mode inherits the deployed one unless it is Viewer. + // ======================================== + sqlx::query("UPDATE usr SET operator = true WHERE workspace_id = 'test-workspace' AND username = 'test-user-3'") + .execute(&db) + .await?; + sqlx::query( + r#"UPDATE workspace_settings SET role_overrides = '{"operator": {"capabilities": {"apps": "compose"}}}' + WHERE workspace_id = 'test-workspace'"#, + ) + .execute(&db) + .await?; + // In wm_deployers, so the refusal in the last step below holds for a builder who may keep + // another user's identity on deploy. + sqlx::query( + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('test-workspace', 'wm_deployers', '', '{}')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO usr_to_group (workspace_id, group_, usr) VALUES ('test-workspace', 'wm_deployers', 'test-user-3')", + ) + .execute(&db) + .await?; + windmill_common::roles::invalidate_workspace_roles_cache("test-workspace"); + windmill_common::roles::invalidate_member_role_cache("test-workspace", "test-user-3"); + + const BUILT: &str = "u/test-user-3/built"; + create_raw(&ws, BUILDER, BUILT).await?; + + let settings_only = json!({ "policy": { "sandbox": true, "triggerables_v2": {} } }); + let (status, body) = update(&ws, BUILT, BUILDER, settings_only.clone()).await?; + assert_eq!(status, 200, "{body}"); + assert_eq!( + policy(&db, BUILT).await?["execution_mode"], + "anonymous", + "a builder's policy without a mode must keep a non-Viewer deployed mode" + ); + + // Viewer stays refused to a builder, alone as in a policy. + let (status, body) = update(&ws, BUILT, BUILDER, json!({ "execution_mode": "viewer" })).await?; + assert_eq!(status, 403, "{body}"); + + // An admin may put the builder's app in Viewer; the builder's next policy without a mode + // then cannot inherit it. + let (status, body) = update(&ws, BUILT, ADMIN, json!({ "execution_mode": "viewer" })).await?; + assert_eq!(status, 200, "{body}"); + let (status, body) = update(&ws, BUILT, BUILDER, settings_only).await?; + assert_eq!(status, 200, "{body}"); + assert_eq!(policy(&db, BUILT).await?["execution_mode"], "publisher"); + + let (status, body) = update( + &ws, + BUILT, + BUILDER, + json!({ "execution_mode": "anonymous" }), + ) + .await?; + assert_eq!( + status, 200, + "a builder may change the mode of its own app: {body}" + ); + assert_eq!(policy(&db, BUILT).await?["execution_mode"], "anonymous"); + + // A builder's deploy would sandbox an app whose policy leaves it unset, which a mode-only + // change must not do. + sqlx::query( + "UPDATE app SET policy = policy - 'sandbox' WHERE path = $1 AND workspace_id = 'test-workspace'", + ) + .bind(BUILT) + .execute(&db) + .await?; + let (status, body) = update( + &ws, + BUILT, + BUILDER, + json!({ "execution_mode": "publisher" }), + ) + .await?; + assert_eq!(status, 403, "{body}"); + let p = policy(&db, BUILT).await?; + assert!(p.get("sandbox").is_none(), "{p}"); + assert_eq!(p["execution_mode"], "anonymous"); + + // Changing the mode alone skips the check of the triggerables against the builder's RLS, so + // it stays refused on an app that runs as someone else; deploying it is the way. + const ADMIN_RUN: &str = "u/test-user-3/admin_run"; + create_raw(&ws, ADMIN, ADMIN_RUN).await?; + let (status, body) = update( + &ws, + ADMIN_RUN, + BUILDER, + json!({ "execution_mode": "publisher" }), + ) + .await?; + assert_eq!(status, 403, "{body}"); + assert!(body.contains("by deploying it"), "{body}"); + + // ======================================== + // 5. Widening is gated by the protection rule; narrowing is not. + // ======================================== + let resp = client() + .post(format!("{ws}/workspaces/protection_rules")) + .bearer_auth(ADMIN) + .json(&json!({ + "name": "no-public-apps", + "rules": ["RestrictAnonymousAppDeployment"], + "bypass_users": [], + "bypass_groups": [] + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let (status, body) = update(&ws, OWN, USER, json!({ "execution_mode": "publisher" })).await?; + assert_eq!(status, 200, "narrowing stays open: {body}"); + let (status, body) = update(&ws, OWN, USER, json!({ "execution_mode": "anonymous" })).await?; + assert_eq!(status, 403, "{body}"); + assert!(body.contains("no-public-apps"), "{body}"); + assert_eq!(policy(&db, OWN).await?["execution_mode"], "publisher"); + + Ok(()) +} diff --git a/backend/tests/dependency_map.rs b/backend/tests/dependency_map.rs index dad6c86aa3..e68828fe24 100644 --- a/backend/tests/dependency_map.rs +++ b/backend/tests/dependency_map.rs @@ -511,6 +511,7 @@ def main(): ) .unwrap(), policy: None, + execution_mode: None, deployment_message: None, custom_path: None, preserve_on_behalf_of: None, diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 777209eda7..2398eb368a 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -15741,6 +15741,10 @@ paths: value: {} policy: $ref: "#/components/schemas/Policy" + execution_mode: + type: string + enum: [viewer, publisher, guest, anonymous] + description: "Changes who may open the app and leaves the rest of the deployed policy, its run-as user included, as it is. Applied under the same lock as a deploy, so neither overwrites the other. Cannot be sent with `policy`, which states its own mode. When the app runs as another user, refused to a caller who is neither an admin nor in 'wm_deployers', and to an operator with builder rights even in 'wm_deployers'; they change the mode by deploying." deployment_message: type: string custom_path: diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index bc0124b685..773e407372 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -602,6 +602,11 @@ pub struct EditApp { pub summary: Option, pub value: Option>>, pub policy: Option, + /// Changes only who may open the app: applied to the deployed policy under the row lock a + /// deploy takes, so it neither reverts a concurrent deploy's policy nor is reverted by it. + /// Exclusive with `policy`, which states its own mode. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub execution_mode: Option, pub deployment_message: Option, pub custom_path: Option, pub preserve_on_behalf_of: Option, @@ -2366,18 +2371,12 @@ fn check_operator_composed_app( // Viewer mode would make the triggerables collected above non-exhaustive (see the docs), and // the deploy panel shows it as members-only, so an admin deploying a draft would not see it. - // Pin an omitted mode on deploy: `update_app_internal` resolves it to the deployed app's, so a - // redeploy over an admin's viewer-mode app would otherwise inherit `Viewer`. - match policy.stated_execution_mode() { - Some(ExecutionMode::Viewer) => { - return Err(Error::PermissionDenied(format!( - "Operators with builder rights cannot {verb} an app that runs as its viewer" - ))) - } - None if write == BuilderAppWrite::Deploy => { - policy.set_execution_mode(ExecutionMode::Publisher) - } - _ => {} + // An omitted mode is resolved by the deploy: create's default, or on update the deployed mode, + // which `update_app_internal` turns into `Publisher` for a builder when it is `Viewer`. + if policy.stated_execution_mode() == Some(ExecutionMode::Viewer) { + return Err(Error::PermissionDenied(format!( + "Operators with builder rights cannot {verb} an app that runs as its viewer" + ))); } referenced.sort(); @@ -2473,15 +2472,7 @@ pub(crate) async fn validate_operator_composed_app( // docs/operator-builder-rights.md); a draft keeps whatever it names, which an admin's // one-click draft deploy preserves without showing it. if let (BuilderAppWrite::Draft, Some(policy)) = (write, policy.as_deref()) { - let names_another = policy - .on_behalf_of - .as_deref() - .is_some_and(|p| p != username_to_permissioned_as(&authed.username)) - || policy - .on_behalf_of_email - .as_deref() - .is_some_and(|e| e != authed.email); - if names_another { + if policy_runs_as_another(policy, authed) { return Err(Error::PermissionDenied( "Operators with builder rights cannot save an app that runs as someone else" .to_string(), @@ -2492,6 +2483,17 @@ pub(crate) async fn validate_operator_composed_app( require_runnables_readable(authed, db, user_db, w_id, referenced).await } +fn policy_runs_as_another(policy: &Policy, authed: &ApiAuthed) -> bool { + policy + .on_behalf_of + .as_deref() + .is_some_and(|p| p != username_to_permissioned_as(&authed.username)) + || policy + .on_behalf_of_email + .as_deref() + .is_some_and(|e| e != authed.email) +} + async fn require_runnables_readable( authed: &ApiAuthed, db: &DB, @@ -3809,10 +3811,22 @@ async fn update_app_internal<'a>( } } - if caller_capabilities(&db, w_id, &authed).await?.apps == AuthorLevel::Compose { + if ns.policy.is_some() && ns.execution_mode.is_some() { + return Err(Error::BadRequest( + "Send execution_mode either inside the policy or alone, not both".to_string(), + )); + } + // The policy a mode-only change writes is only known under the row lock, so a builder's + // check on it runs there. + let mode_only = ns.policy.is_none() && ns.value.is_none() && ns.execution_mode.is_some(); + + let composes_only = caller_capabilities(&db, w_id, &authed).await?.apps == AuthorLevel::Compose; + if composes_only { // Restoring a full-code version always sends allow_kind_change. A builder converts // nothing, so drop it and let the locked kind check below refuse an actual conversion. ns.allow_kind_change = None; + } + if composes_only && !mode_only { validate_operator_composed_app( &authed, &db, @@ -3890,6 +3904,7 @@ async fn update_app_internal<'a>( || ns.summary.is_some() || ns.custom_path.is_some() || ns.labels.is_some() + || ns.execution_mode.is_some() // A source deploy may send nothing but the value, and its runnables are // what the derived grants describe: skipping the UPDATE here would keep // the grants keyed to the sources this deploy just replaced. @@ -3907,7 +3922,12 @@ async fn update_app_internal<'a>( // that carries no policy keeps the deployed mode, read under the row // lock so a policy update landing alongside cannot slip a guest app // onto a path it cannot be scoped to. - let mode = match ns.policy.as_ref().and_then(|p| p.stated_execution_mode()) { + let stated = ns + .policy + .as_ref() + .and_then(|p| p.stated_execution_mode()) + .or(ns.execution_mode); + let mode = match stated { Some(mode) => mode, None => sqlx::query_scalar::<_, Option>( "SELECT policy->>'execution_mode' FROM app @@ -3987,12 +4007,13 @@ async fn update_app_internal<'a>( // no policy at all, in which case the rest of the deployed one carries // over. Either way a policy is about to be written wholesale. let caller_sent_policy = ns.policy.is_some(); - if caller_sent_policy || derived_triggerables.is_some() { + if caller_sent_policy || derived_triggerables.is_some() || ns.execution_mode.is_some() { // One locked read serving everything below: the mode an omitted one // inherits, the already-anonymous check, and the policy a source - // deploy carries over. FOR UPDATE holds the row until this - // transaction's UPDATE commits, so a policy edit landing between the - // read and the write cannot be clobbered by this stale snapshot. + // deploy or a mode-only change carries over. FOR UPDATE holds the row + // until this transaction's UPDATE commits, so a policy edit landing + // between the read and the write cannot be clobbered by this stale + // snapshot. let deployed = sqlx::query_scalar!( "SELECT policy FROM app WHERE path = $1 AND workspace_id = $2 FOR UPDATE", path, @@ -4006,30 +4027,81 @@ async fn update_app_internal<'a>( let mut npolicy = match ns.policy.take() { Some(npolicy) => npolicy, + None if deployed.is_none() => { + return Err(Error::NotFound(format!("App {path} not found"))) + } // Carrying the deployed policy forward is only safe if all of it // survived the round trip; a partial one would silently drop // `on_behalf_of`, sandboxing or S3 rules. None => deployed_policy.clone().ok_or_else(|| { - Error::internal_err(format!( - "app {path} has no readable policy to deploy its new sources under" - )) + Error::internal_err(format!("app {path} has no readable policy to update")) })?, }; if let Some(triggerables) = derived_triggerables { npolicy.triggerables = None; npolicy.triggerables_v2 = Some(triggerables); } + if let Some(mode) = ns.execution_mode { + // A policy write from someone who cannot keep the run-as user rebinds it + // to them, so the mode alone must not let them open an app running as + // someone else to a new audience. A builder who may keep it is refused too: + // its deploy checks the triggerables against its own RLS, which needs a + // second pool connection and so cannot run under this lock. + if policy_runs_as_another(&npolicy, &authed) + && (composes_only || !windmill_common::can_preserve_on_behalf_of(&authed)) + { + let runs_as = npolicy + .on_behalf_of_email + .as_deref() + .or(npolicy.on_behalf_of.as_deref()) + .unwrap_or("another user"); + return Err(Error::PermissionDenied(if composes_only { + format!( + "app {path} runs as {runs_as}: change who can open it by deploying it" + ) + } else { + format!( + "app {path} runs as {runs_as}: only admins and members of \ + wm_deployers can change who can open it without deploying it, and a \ + deploy from you makes it run as you" + ) + })); + } + npolicy.set_execution_mode(mode); + if composes_only { + // The check below sandboxes an app whose policy leaves `sandbox` unset; a + // mode-only change keeps every other field, so that is left to a deploy. + if npolicy.sandbox != Some(true) { + return Err(Error::PermissionDenied(format!( + "app {path} is not sandboxed: change who can open it by deploying it" + ))); + } + check_operator_composed_app( + BuilderAppWrite::Deploy, + raw_app, + None, + Some(&mut npolicy), + )?; + } + } validate_frontend_sdk_scopes(&npolicy)?; // The policy is written wholesale, so one that states no mode would // otherwise re-permission the app to the create-time default: a // `viewer` app would start running on the publisher's identity. Keep - // the deployed mode instead, and make the stored policy state it. + // the deployed mode instead, and make the stored policy state it. A + // builder may not deploy `Viewer` (see `check_operator_composed_app`), + // so a builder's redeploy over a viewer-mode app makes it `Publisher`. if npolicy.stated_execution_mode().is_none() { + let deployed_mode = deployed_policy + .as_ref() + .map(|d| d.execution_mode()) + .unwrap_or_default(); npolicy.set_execution_mode( - deployed_policy - .as_ref() - .map(|d| d.execution_mode()) - .unwrap_or_default(), + if composes_only && deployed_mode == ExecutionMode::Viewer { + ExecutionMode::Publisher + } else { + deployed_mode + }, ); } refuse_unscopable_guest_app( @@ -4155,7 +4227,8 @@ async fn update_app_internal<'a>( // CLI / git-sync deploys ask us to preserve any existing user draft at this // path instead of wiping it as part of the deploy. Only wipe the deployer's // own draft (plus the legacy NULL-email row) — see create_app_internal. - if !ns.skip_draft_deletion.unwrap_or(false) { + // A mode-only change publishes nothing from the draft, so it keeps it. + if !ns.skip_draft_deletion.unwrap_or(false) && !mode_only { sqlx::query!( "DELETE FROM draft WHERE path = $1 AND workspace_id = $2 AND typ IN ('app', 'raw_app') \ AND (email = $3 OR email IS NULL)", diff --git a/docs/operator-builder-rights.md b/docs/operator-builder-rights.md index 8445fa0dde..8b99401d32 100644 --- a/docs/operator-builder-rights.md +++ b/docs/operator-builder-rights.md @@ -104,12 +104,19 @@ ignored into `inlineScript`. `update_app` takes a builder too, but settings only: the deploy panel saves a deployed full-code app's access and frontend scopes through it with no value. It reaches the same check, so a builder -can no more switch the sandbox off there than on deploy. +can no more switch the sandbox off there than on deploy. A change of `execution_mode` alone runs +`check_operator_composed_app` on the deployed policy under the row lock, but not the readability +check, which resolves script versions on a second pool connection. It is therefore refused when +the app runs as anyone but the builder, `wm_deployers` or not: what an app running as its builder +invokes runs as that builder, who can already run it as themselves by opening the app. It is also +refused on an app whose stored policy is not sandboxed: the check would fill in the sandbox, and a +change of the mode alone keeps every other field of the policy. A builder's **draft** goes through the same `check_operator_composed_app` as its deploy, with `BuilderAppWrite::Draft`: an admin may open it in the editor or deploy it as it stands, so any rule added for deploys must hold for drafts too. Where the two differ, `write` decides: a deploy -fills in an omitted sandbox or mode, since it stores the policy it checked, while a draft skips +fills in an omitted sandbox, since it stores the policy it checked, and an omitted mode inherits the +deployed one, except that `Viewer` becomes `Publisher`, while a draft skips `triggerables_v2` and must not name another user's run identity. Every frontend writer of a builder draft must conform the policy first with `conformBuilderAppPolicy`, since a policy loaded from someone else's app breaks these rules: the raw-app editor component does, which covers both From 91bf9b67a74afb419659719949484f1cfd5338c0 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Fri, 23 Oct 2026 14:50:01 +0200 Subject: [PATCH 060/101] feat: group home row menus and open them at their final height (#11949) --- frontend/src/lib/components/DropdownV2.svelte | 24 +- .../src/lib/components/DropdownV2Inner.svelte | 20 +- .../components/common/table/AgentRow.svelte | 8 +- .../lib/components/common/table/AppRow.svelte | 282 +++++++------ .../components/common/table/FlowRow.svelte | 274 ++++++------ .../components/common/table/RawAppRow.svelte | 8 +- .../components/common/table/ScriptRow.svelte | 389 +++++++++--------- .../lib/components/common/table/menuGroups.ts | 25 ++ frontend/src/lib/components/home/deploy_ui.ts | 53 ++- 9 files changed, 600 insertions(+), 483 deletions(-) create mode 100644 frontend/src/lib/components/common/table/menuGroups.ts diff --git a/frontend/src/lib/components/DropdownV2.svelte b/frontend/src/lib/components/DropdownV2.svelte index 1d86519293..e9fbf71ab8 100644 --- a/frontend/src/lib/components/DropdownV2.svelte +++ b/frontend/src/lib/components/DropdownV2.svelte @@ -99,7 +99,10 @@ } = createDropdownMenu({ portal: untrack(() => hostPortal()), positioning: { - placement: untrack(() => placement) + placement: untrack(() => placement), + // Caps the menu at the room the viewport has left, so a list taller than that scrolls + // instead of flipping past the screen edge. A custom menu sizes itself. + fitViewport: untrack(() => !customMenu) }, closeOnItemClick: untrack(() => closeOnItemClick), loop: true, @@ -137,13 +140,12 @@ if (afterClose) setTimeout(afterClose, 10) } - async function computeItems(): Promise { - if (typeof items === 'function') { - const result = await items() - return Array.isArray(result) ? result.filter((item) => !item.hide) : [] - } else { - return items.filter((item) => !item.hide) - } + function visible(result: Item[] | undefined): Item[] { + return Array.isArray(result) ? result.filter((item) => !item.hide) : [] + } + function computeItems(): Item[] | Promise { + const result = typeof items === 'function' ? items() : items + return result instanceof Promise ? result.then(visible) : visible(result) } async function getMenuElements(): Promise { // Runs on every pointerdown anywhere, for every mounted dropdown. Skip the @@ -200,15 +202,15 @@
    {#if customMenu} {@render menu?.({ item, close, builders })} {:else}
    diff --git a/frontend/src/lib/components/DropdownV2Inner.svelte b/frontend/src/lib/components/DropdownV2Inner.svelte index 5a18a09157..30b6865da8 100644 --- a/frontend/src/lib/components/DropdownV2Inner.svelte +++ b/frontend/src/lib/components/DropdownV2Inner.svelte @@ -7,10 +7,11 @@ import type { MenubarMenuElements, createDropdownMenu } from '@melt-ui/svelte' import type { Item } from '$lib/utils' import { Tooltip } from './meltComponents' + import { untrack } from 'svelte' interface Props { aiId?: string - items?: Item[] | (() => Item[]) | (() => Promise) + items?: Item[] | (() => Item[] | Promise) meltItem: MenubarMenuElements['item'] builders?: ReturnType['builders'] close?: (afterClose?: () => void) => void @@ -18,16 +19,17 @@ let { aiId, items = [], meltItem, builders, close }: Props = $props() - let computedItems: Item[] | undefined = $state(undefined) - async function computeItems() { - if (typeof items === 'function') { - computedItems = ((await items()) ?? []).filter((item) => !item.hide) - } else { - computedItems = items.filter((item) => !item.hide) - } + function visible(result: Item[] | undefined): Item[] { + return (result ?? []).filter((item) => !item.hide) } - computeItems() + // Items returned synchronously render on the first frame: awaiting them would show the + // spinner first, the popover would be placed for the spinner's height, then flip. + const initial = untrack(() => (typeof items === 'function' ? items() : items)) + let computedItems: Item[] | undefined = $state( + initial instanceof Promise ? undefined : visible(initial) + ) + if (initial instanceof Promise) initial.then((result) => (computedItems = visible(result))) {#snippet menuItem(item: Item)} diff --git a/frontend/src/lib/components/common/table/AgentRow.svelte b/frontend/src/lib/components/common/table/AgentRow.svelte index 20421ac514..061112dec4 100644 --- a/frontend/src/lib/components/common/table/AgentRow.svelte +++ b/frontend/src/lib/components/common/table/AgentRow.svelte @@ -14,7 +14,7 @@ import { keepsManagedMemory } from '$lib/components/flows/agentFormFields' import { agentMenuItems, deleteAgent } from '$lib/components/flows/agentActions' import AgentHistory from '$lib/components/flows/AgentHistory.svelte' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' import Row from './Row.svelte' import { selectMenuItems, type RowSelection } from './rowSelection' @@ -48,6 +48,8 @@ const dispatch = createEventDispatcher() + warmDeployUiSettings() + async function remove(path: string) { if (await deleteAgent($workspaceStore!, path)) dispatch('change') } @@ -106,10 +108,10 @@ {/if} [ + items={() => [ ...selectMenuItems(rowSelection), ...agentMenuItems({ - deployUiSettings: await getDeployUiSettings(), + deployUiSettings: cachedDeployUiSettings(), path: agent.path, canWrite: agent.canWrite, draftOnly: Boolean(agent.draft_only), diff --git a/frontend/src/lib/components/common/table/AppRow.svelte b/frontend/src/lib/components/common/table/AppRow.svelte index 812c06284b..7553b61870 100644 --- a/frontend/src/lib/components/common/table/AppRow.svelte +++ b/frontend/src/lib/components/common/table/AppRow.svelte @@ -35,7 +35,8 @@ import { copyToClipboard } from '$lib/utils' import AppDeploymentHistory from '$lib/components/apps/editor/AppDeploymentHistory.svelte' import { isDeployable } from '$lib/utils_deployable' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' + import { menuGroups } from './menuGroups' import { editInForkAllowed, editInForkLabel, onEditInForkClick } from '$lib/utils/editInFork' import EditInForkButton from './EditInForkButton.svelte' import { isCloudHosted } from '$lib/cloud' @@ -69,6 +70,8 @@ }: Props = $props() const dispatch = createEventDispatcher() + + warmDeployUiSettings() // A compose-only app role authors full-code apps, never low-code ones. const canAuthorApp = $derived(roleCanAuthor(app.raw_app ? 'raw_app' : 'app', $roleCapabilities)) const fullApps = $derived($roleCapabilities.apps === 'full') @@ -167,27 +170,155 @@ size="sm" aiId={`app-row-dropdown-${app.summary?.length > 0 ? app.summary : app.path}`} aiDescription={`Open dropdown for app ${app.summary?.length > 0 ? app.summary : app.path} options`} - items={async () => { + items={() => { let { draft_only, canWrite, summary, execution_mode, path } = app const canEdit = canWrite && showEditButton if (draft_only) { - return [ - ...selectMenuItems(rowSelection), + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: fullApps ? 'View/Edit JSON' : 'View JSON', + icon: File, + action: () => { + loadAppJson() + } + }, + { + displayName: 'Move/Rename', + icon: FolderOpen, + action: () => { + // Addressed by the generated path its draft row sits at, but + // named by the path typed in the editor. + moveDrawer.openDrawer((app as any).draft_path ?? path, summary, 'app', { + storagePath: path, + rawApp: !!app.raw_app + }) + }, + disabled: !showEditButton, + hide: !fullApps + } + ], + [ + { + displayName: 'Delete', + icon: Trash, + action: async (event) => { + // TODO + // @ts-ignore + if (event?.shiftKey) { + await deleteApp(path) + dispatch('change') + } else { + deleteConfirmedCallback = async () => { + await deleteApp(path) + dispatch('change') + } + } + }, + type: 'delete', + // A draft-only row is always the authed user's own draft (the + // list endpoint only surfaces own/legacy draft-only rows), so + // discarding it never requires write permission on the path. The server + // lets one's own draft go without authoring rights; only a legacy one needs them. + disabled: !showEditButton, + hide: + !canAuthorApp && + app.draft_users?.length === 1 && + app.draft_users[0]?.username == null + } + ] + ) + } + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: fullApps ? 'View/Edit JSON' : 'View JSON', + icon: FileJson, + action: () => { + loadAppJson() + } + }, + { + displayName: 'Go to public page', + icon: ExternalLink, + action: async () => { + let secretUrl = await AppService.getPublicSecretOfApp({ + workspace: $workspaceStore ?? '', + path + }) + let url = + page.url.protocol + + '//' + + `${page.url.hostname}/public/${$workspaceStore}/${secretUrl}` + gotoUrl(url) + }, + hide: execution_mode != 'anonymous' + }, + { + displayName: 'Versions', + icon: History, + action: () => appDeploymentHistory?.open(), + hide: !canAuthorApp + } + ], + [ + { + displayName: 'Duplicate/Fork', + icon: GitFork, + href: `/apps${app.raw_app ? '_raw' : ''}/add?template=${path}`, + disabled: !showEditButton, + hide: !fullApps + }, + { + displayName: editInForkLabel($workspaceStore, $userWorkspaces), + icon: Pen, + // No `href`: the handler resolves the destination asynchronously, and a melt + // menu item's anchor navigates before a delegated onclick can preventDefault it. + action: (e) => onEditInForkClick(e, app.raw_app ? 'raw_app' : 'app', path), + hide: + !$roleCapabilities.code || + isCloudHosted() || + !editInForkAllowed($workspaceStore, $userWorkspaces) + }, + { + displayName: 'Copy path', + icon: Copy, + action: () => { + copyToClipboard(path) + } + } + ], + [ { displayName: 'Move/Rename', icon: FolderOpen, action: () => { - // Addressed by the generated path its draft row sits at, but - // named by the path typed in the editor. - moveDrawer.openDrawer((app as any).draft_path ?? path, summary, 'app', { - storagePath: path, - rawApp: !!app.raw_app - }) + moveDrawer.openDrawer(path, summary, 'app') }, - disabled: !showEditButton, + disabled: !canEdit, hide: !fullApps }, + { + displayName: 'Permissions', + icon: Shield, + action: () => { + shareModal.openDrawer && shareModal.openDrawer(path, 'app') + }, + hide: !canAuthorApp + }, + { + displayName: 'Deploy to staging/prod', + icon: ChevronUpSquare, + action: () => { + deploymentDrawer.openDrawer(path, 'app') + }, + hide: !fullApps || !isDeployable('app', path, cachedDeployUiSettings()) + } + ], + [ { displayName: 'Delete', icon: Trash, @@ -205,134 +336,11 @@ } }, type: 'delete', - // A draft-only row is always the authed user's own draft (the - // list endpoint only surfaces own/legacy draft-only rows), so - // discarding it never requires write permission on the path. The server - // lets one's own draft go without authoring rights; only a legacy one needs them. - disabled: !showEditButton, - hide: - !canAuthorApp && - app.draft_users?.length === 1 && - app.draft_users[0]?.username == null - }, - { - displayName: fullApps ? 'View/Edit JSON' : 'View JSON', - icon: File, - action: () => { - loadAppJson() - } + disabled: !canEdit, + hide: !canAuthorApp } ] - } - return [ - ...selectMenuItems(rowSelection), - { - displayName: 'Duplicate/Fork', - icon: GitFork, - href: `/apps${app.raw_app ? '_raw' : ''}/add?template=${path}`, - disabled: !showEditButton, - hide: !fullApps - }, - { - displayName: editInForkLabel($workspaceStore, $userWorkspaces), - icon: Pen, - // No `href`: the handler resolves the destination asynchronously, and a melt - // menu item's anchor navigates before a delegated onclick can preventDefault it. - action: (e) => onEditInForkClick(e, app.raw_app ? 'raw_app' : 'app', path), - hide: - !$roleCapabilities.code || - isCloudHosted() || - !editInForkAllowed($workspaceStore, $userWorkspaces) - }, - { - displayName: 'Move/Rename', - icon: FolderOpen, - action: () => { - moveDrawer.openDrawer(path, summary, 'app') - }, - disabled: !canEdit, - hide: !fullApps - }, - ...(isDeployable('app', path, await getDeployUiSettings()) - ? [ - { - displayName: 'Deploy to staging/prod', - icon: ChevronUpSquare, - action: () => { - deploymentDrawer.openDrawer(path, 'app') - }, - hide: !fullApps - } - ] - : []), - { - displayName: fullApps ? 'View/Edit JSON' : 'View JSON', - icon: FileJson, - action: () => { - loadAppJson() - } - }, - { - displayName: 'Deployments', - icon: History, - action: () => appDeploymentHistory?.open(), - hide: !canAuthorApp - }, - { - displayName: 'Permissions', - icon: Shield, - action: () => { - shareModal.openDrawer && shareModal.openDrawer(path, 'app') - }, - hide: !canAuthorApp - }, - { - displayName: 'Copy path', - icon: Copy, - action: () => { - copyToClipboard(path) - } - }, - ...(execution_mode == 'anonymous' - ? [ - { - displayName: 'Go to public page', - icon: ExternalLink, - action: async () => { - let secretUrl = await AppService.getPublicSecretOfApp({ - workspace: $workspaceStore ?? '', - path - }) - let url = - page.url.protocol + - '//' + - `${page.url.hostname}/public/${$workspaceStore}/${secretUrl}` - gotoUrl(url) - } - } - ] - : []), - { - displayName: 'Delete', - icon: Trash, - action: async (event) => { - // TODO - // @ts-ignore - if (event?.shiftKey) { - await deleteApp(path) - dispatch('change') - } else { - deleteConfirmedCallback = async () => { - await deleteApp(path) - dispatch('change') - } - } - }, - type: 'delete', - disabled: !canEdit, - hide: !canAuthorApp - } - ] + ) }} on:open={() => { menuOpen = true diff --git a/frontend/src/lib/components/common/table/FlowRow.svelte b/frontend/src/lib/components/common/table/FlowRow.svelte index ccbdb9de3e..eb58ecbc3f 100644 --- a/frontend/src/lib/components/common/table/FlowRow.svelte +++ b/frontend/src/lib/components/common/table/FlowRow.svelte @@ -32,13 +32,15 @@ Archive, Copy, Eye, - HistoryIcon + HistoryIcon, + Clock } from 'lucide-svelte' import FlowHistory from '$lib/components/flows/FlowHistory.svelte' import ChatFlowBadge from '$lib/components/flows/ChatFlowBadge.svelte' import RowLabels from './RowLabels.svelte' import AskAiRowButton from './AskAiRowButton.svelte' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' + import { menuGroups, submenu } from './menuGroups' import { editInForkAllowed, editInForkLabel, onEditInForkClick } from '$lib/utils/editInFork' import EditInForkButton from './EditInForkButton.svelte' import { isCloudHosted } from '$lib/cloud' @@ -86,6 +88,8 @@ const dispatch = createEventDispatcher() + warmDeployUiSettings() + async function archiveFlow(path: string, archived: boolean): Promise { try { await FlowService.archiveFlowByPath({ @@ -199,24 +203,152 @@ size="sm" aiId={`flow-row-dropdown-${flow.summary?.length > 0 ? flow.summary : flow.path}`} aiDescription={`Open dropdown for flow ${flow.summary?.length > 0 ? flow.summary : flow.path} options`} - items={async () => { + items={() => { let { draft_only, path, archived } = flow let owner = isOwner(path, $userStore, $workspaceStore) const canEdit = flow.canWrite && showEditButton if (draft_only) { - return [ - ...selectMenuItems(rowSelection), + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: 'Move/Rename', + icon: FolderOpen, + action: () => { + // Addressed by the generated path its draft row sits at, but + // named by the path typed in the editor. + moveDrawer.openDrawer((flow as any).draft_path ?? path, flow.summary, 'flow', { + storagePath: path + }) + }, + disabled: !showEditButton, + hide: hideForOperator + } + ], + [ + { + displayName: 'Delete', + icon: Trash, + action: (event) => { + // @ts-ignore + if (event?.shiftKey) { + deleteFlow(path) + } else { + deleteConfirmedCallback = () => { + deleteFlow(path) + } + } + }, + type: 'delete', + // A draft-only row is always the authed user's own draft (the + // list endpoint only surfaces own/legacy draft-only rows), so + // discarding it never requires write permission on the path. + disabled: !showEditButton, + hide: hideForOperator + } + ] + ) + } + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: 'View runs', + icon: List, + href: `/runs/${path}` + }, + submenu('History', Clock, [ + { + displayName: 'Versions', + icon: HistoryIcon, + action: () => { + flowHistory?.open() + }, + hide: hideForOperator + }, + { + displayName: 'Audit logs', + icon: Eye, + href: `/audit_logs?resource=${path}`, + hide: !$roleCapabilities.code || !$roleCapabilities.visibility.audit_logs + } + ]) + ], + [ + { + displayName: 'Duplicate/Fork', + icon: GitFork, + href: `/flows/add?template=${path}`, + disabled: !showEditButton, + hide: hideForOperator + }, + { + displayName: editInForkLabel($workspaceStore, $userWorkspaces), + icon: Pen, + // No `href`: the handler resolves the destination asynchronously, and a melt + // menu item's anchor navigates before a delegated onclick can preventDefault it. + action: (e) => onEditInForkClick(e, 'flow', path), + hide: + !$roleCapabilities.code || + isCloudHosted() || + !editInForkAllowed($workspaceStore, $userWorkspaces) + }, + { + displayName: 'Copy path', + icon: Copy, + action: () => { + copyToClipboard(path) + } + } + ], + [ { displayName: 'Move/Rename', icon: FolderOpen, action: () => { - // Addressed by the generated path its draft row sits at, but - // named by the path typed in the editor. - moveDrawer.openDrawer((flow as any).draft_path ?? path, flow.summary, 'flow', { - storagePath: path - }) + moveDrawer.openDrawer(path, flow.summary, 'flow') }, - disabled: !showEditButton, + disabled: !owner || archived || !canEdit, + hide: hideForOperator + }, + { + displayName: 'Schedule', + icon: Calendar, + action: () => { + scheduleEditor?.openNew(true, path) + }, + disabled: archived, + hide: hideForOperator || !$roleCapabilities.manage_schedules + }, + { + displayName: 'Permissions', + icon: Shield, + action: () => { + shareModal.openDrawer && shareModal.openDrawer(path, 'flow') + }, + hide: hideForOperator + }, + { + displayName: 'Deploy to staging/prod', + icon: ChevronUpSquare, + action: () => { + deploymentDrawer.openDrawer(path, 'flow') + }, + disabled: archived, + hide: + $roleCapabilities.flows !== 'full' || + !isDeployable('flow', path, cachedDeployUiSettings()) + } + ], + [ + { + displayName: archived ? 'Unarchive' : 'Archive', + icon: Archive, + action: () => { + path && archiveFlow(path, !archived) + }, + type: 'delete', + disabled: !owner || !canEdit, hide: hideForOperator }, { @@ -233,127 +365,11 @@ } }, type: 'delete', - // A draft-only row is always the authed user's own draft (the - // list endpoint only surfaces own/legacy draft-only rows), so - // discarding it never requires write permission on the path. - disabled: !showEditButton, + disabled: !owner || !canEdit, hide: hideForOperator } ] - } - return [ - ...selectMenuItems(rowSelection), - { - displayName: 'View runs', - icon: List, - href: `/runs/${path}` - }, - { - displayName: 'Duplicate/Fork', - icon: GitFork, - href: `/flows/add?template=${path}`, - disabled: !showEditButton, - hide: hideForOperator - }, - { - displayName: editInForkLabel($workspaceStore, $userWorkspaces), - icon: Pen, - // No `href`: the handler resolves the destination asynchronously, and a melt - // menu item's anchor navigates before a delegated onclick can preventDefault it. - action: (e) => onEditInForkClick(e, 'flow', path), - hide: - !$roleCapabilities.code || - isCloudHosted() || - !editInForkAllowed($workspaceStore, $userWorkspaces) - }, - { - displayName: 'Audit logs', - icon: Eye, - href: `/audit_logs?resource=${path}`, - hide: !$roleCapabilities.code || !$roleCapabilities.visibility.audit_logs - }, - { - displayName: 'Move/Rename', - icon: FolderOpen, - action: () => { - moveDrawer.openDrawer(path, flow.summary, 'flow') - }, - disabled: !owner || archived || !canEdit, - hide: hideForOperator - }, - { - displayName: 'Copy path', - icon: Copy, - action: () => { - copyToClipboard(path) - } - }, - ...(isDeployable('flow', path, await getDeployUiSettings()) - ? [ - { - displayName: 'Deploy to staging/prod', - icon: ChevronUpSquare, - action: () => { - deploymentDrawer.openDrawer(path, 'flow') - }, - disabled: archived, - hide: $roleCapabilities.flows !== 'full' - } - ] - : []), - { - displayName: 'Deployments', - icon: HistoryIcon, - action: () => { - flowHistory?.open() - }, - hide: hideForOperator - }, - { - displayName: 'Schedule', - icon: Calendar, - action: () => { - scheduleEditor?.openNew(true, path) - }, - disabled: archived, - hide: hideForOperator || !$roleCapabilities.manage_schedules - }, - { - displayName: 'Permissions', - icon: Shield, - action: () => { - shareModal.openDrawer && shareModal.openDrawer(path, 'flow') - }, - hide: hideForOperator - }, - { - displayName: archived ? 'Unarchive' : 'Archive', - icon: Archive, - action: () => { - path && archiveFlow(path, !archived) - }, - type: 'delete', - disabled: !owner || !canEdit, - hide: hideForOperator - }, - { - displayName: 'Delete', - icon: Trash, - action: (event) => { - // @ts-ignore - if (event?.shiftKey) { - deleteFlow(path) - } else { - deleteConfirmedCallback = () => { - deleteFlow(path) - } - } - }, - type: 'delete', - disabled: !owner || !canEdit, - hide: hideForOperator - } - ] + ) }} on:open={() => { menuOpen = true diff --git a/frontend/src/lib/components/common/table/RawAppRow.svelte b/frontend/src/lib/components/common/table/RawAppRow.svelte index 1740566bdc..c1feaa2a38 100644 --- a/frontend/src/lib/components/common/table/RawAppRow.svelte +++ b/frontend/src/lib/components/common/table/RawAppRow.svelte @@ -8,7 +8,7 @@ import type DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' import { Globe, Shield } from 'lucide-svelte' import { isDeployable } from '$lib/utils_deployable' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' interface Props { app: ListableRawApp & { canWrite: boolean } @@ -29,6 +29,8 @@ menuOpen = $bindable(false), keyboardSelected = false }: Props = $props() + + warmDeployUiSettings() { + items={() => { let { path } = app return [ - ...(isDeployable('app', path, await getDeployUiSettings()) + ...(isDeployable('app', path, cachedDeployUiSettings()) ? [ { displayName: 'Deploy to prod/staging', diff --git a/frontend/src/lib/components/common/table/ScriptRow.svelte b/frontend/src/lib/components/common/table/ScriptRow.svelte index 9c300b9477..5044cf4339 100644 --- a/frontend/src/lib/components/common/table/ScriptRow.svelte +++ b/frontend/src/lib/components/common/table/ScriptRow.svelte @@ -45,7 +45,9 @@ Shield, Trash, History, - FileText + FileText, + Clock, + Send } from 'lucide-svelte' import ScriptVersionHistory from '$lib/components/ScriptVersionHistory.svelte' import WacExportDrawer from '$lib/components/scripts/WacExportDrawer.svelte' @@ -55,7 +57,8 @@ import AskAiRowButton from './AskAiRowButton.svelte' import Popover from '$lib/components/Popover.svelte' import Tooltip from '$lib/components/Tooltip.svelte' - import { getDeployUiSettings } from '$lib/components/home/deploy_ui' + import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' + import { menuGroups, submenu } from './menuGroups' import { claimTab, editInForkAllowed, @@ -105,6 +108,8 @@ const dispatch = createEventDispatcher() + warmDeployUiSettings() + async function archiveScript(path: string): Promise { await ScriptService.archiveScriptByPath({ workspace: $workspaceStore!, path }) dispatch('change') @@ -262,12 +267,66 @@ size="sm" aiId={`script-row-dropdown-${script.summary?.length > 0 ? script.summary : script.path}`} aiDescription={`Open dropdown for script ${script.summary?.length > 0 ? script.summary : script.path} options`} - items={async () => { + items={() => { let owner = isOwner(script.path, $userStore, $workspaceStore) const canEdit = script.canWrite && showEditButton if (script.draft_only) { - return [ - ...selectMenuItems(rowSelection), + return menuGroups( + selectMenuItems(rowSelection), + [ + { + displayName: 'View code', + icon: Code, + action: () => { + showCode(script.path, script.summary) + } + }, + { + displayName: 'Move/Rename', + icon: FolderOpen, + action: () => { + // Addressed by the generated path its draft row sits at, but + // named by the path typed in the editor. + moveDrawer.openDrawer( + script.draft_path ?? script.path, + script.summary, + 'script', + { + storagePath: script.path + } + ) + }, + disabled: !showEditButton, + hide: !$roleCapabilities.code + } + ], + [ + { + displayName: 'Delete', + icon: Trash, + action: (event) => { + // TODO + // @ts-ignore + if (event?.shiftKey) { + deleteScript(script.path) + } else { + deleteConfirmedCallback = () => { + deleteScript(script.path) + } + } + }, + type: dlt, + // A draft-only row is always the authed user's own draft (the + // list endpoint only surfaces own/legacy draft-only rows), so + // discarding it never requires write permission on the path. + disabled: !showEditButton + } + ] + ) + } + return menuGroups( + selectMenuItems(rowSelection), + [ { displayName: 'View code', icon: Code, @@ -275,25 +334,154 @@ showCode(script.path, script.summary) } }, + { + displayName: 'View JSON/YAML', + icon: FileText, + action: async () => { + const fullScript = await ScriptService.getScriptByPath({ + workspace: $workspaceStore!, + path: script.path + }) + wacExportDrawer?.open(fullScript) + }, + hide: script.auto_kind !== 'wac' + }, + { + displayName: 'View runs', + icon: List, + href: `/runs/${script.path}` + }, + submenu('History', Clock, [ + { + displayName: 'Versions', + icon: History, + action: () => { + versionsDrawerOpen = true + } + }, + { + displayName: 'Audit logs', + icon: Eye, + href: `/audit_logs?resource=${script.path}`, + hide: !$roleCapabilities.code || !$roleCapabilities.visibility.audit_logs + } + ]) + ], + [ + { + displayName: 'Duplicate/Fork', + icon: GitFork, + href: `/scripts/add?template=${script.path}`, + disabled: !showEditButton, + hide: !$roleCapabilities.code + }, + { + displayName: editInForkLabel($workspaceStore, $userWorkspaces), + icon: Pen, + // No `href`: the handler resolves the destination asynchronously, and a melt + // menu item's anchor navigates before a delegated onclick can preventDefault it. + action: (e) => onEditInForkClick(e, 'script', script.path), + hide: + !$roleCapabilities.code || + isCloudHosted() || + !editInForkAllowed($workspaceStore, $userWorkspaces) + }, + { + displayName: 'Copy path', + icon: Copy, + action: () => { + copyToClipboard(script.path) + } + } + ], + [ { displayName: 'Move/Rename', icon: FolderOpen, action: () => { - // Addressed by the generated path its draft row sits at, but - // named by the path typed in the editor. - moveDrawer.openDrawer(script.draft_path ?? script.path, script.summary, 'script', { - storagePath: script.path - }) + moveDrawer.openDrawer(script.path, script.summary, 'script') }, - disabled: !showEditButton, + disabled: !owner || script.archived || !canEdit, + hide: !$roleCapabilities.code + }, + { + displayName: 'Schedule', + icon: Calendar, + action: () => { + scheduleEditor?.openNew(false, script.path) + }, + disabled: script.archived, + hide: !$roleCapabilities.code || !$roleCapabilities.manage_schedules + }, + { + displayName: 'Permissions', + icon: Shield, + action: () => { + shareModal.openDrawer && shareModal.openDrawer(script.path, 'script') + }, + disabled: script.archived, + hide: !$roleCapabilities.code + }, + submenu('Deploy & publish', Send, [ + { + displayName: 'Deploy to staging/prod', + icon: ChevronUpSquare, + action: () => { + deploymentDrawer.openDrawer(script.path, 'script') + }, + disabled: script.archived, + hide: + !$roleCapabilities.code || + !isDeployable('script', script.path, cachedDeployUiSettings()) + }, + { + displayName: 'Publish to Hub', + icon: Globe2, + action: async () => { + // The row only carries metadata, so the code has to be fetched first; the tab is + // claimed before that, since Safari won't open one after an await. + const tab = claimTab() + try { + const fullScript = await ScriptService.getScriptByPath({ + workspace: $workspaceStore!, + path: script.path + }) + const url = scriptToHubUrl(fullScript, $hubBaseUrlStore).toString() + if (tab) { + tab.show(url) + } else if (!window.open(url)) { + sendUserToast('Allow popups to publish this script to the Hub', true) + } + } catch (e: any) { + tab?.discard() + sendUserToast( + `Could not load ${script.path}: ${e?.body ?? e?.message ?? e}`, + true + ) + } + }, + // Operators can't write scripts, so they have nothing to publish. + hide: $disableHubStore || !$roleCapabilities.code + } + ]) + ], + [ + { + displayName: script.archived ? 'Unarchive' : 'Archive', + icon: Archive, + action: () => { + script.archived + ? script.path && unarchiveScript(script.path) + : script.path && archiveScript(script.path) + }, + type: 'delete', + disabled: !owner || !canEdit, hide: !$roleCapabilities.code }, { displayName: 'Delete', icon: Trash, action: (event) => { - // TODO - // @ts-ignore if (event?.shiftKey) { deleteScript(script.path) } else { @@ -303,180 +491,11 @@ } }, type: dlt, - // A draft-only row is always the authed user's own draft (the - // list endpoint only surfaces own/legacy draft-only rows), so - // discarding it never requires write permission on the path. - disabled: !showEditButton + disabled: !canEdit, + hide: !$roleCapabilities.code || !($userStore?.is_admin || $userStore?.is_super_admin) } ] - } - return [ - ...selectMenuItems(rowSelection), - { - displayName: 'View code', - icon: Code, - action: () => { - showCode(script.path, script.summary) - } - }, - ...(script.auto_kind === 'wac' - ? [ - { - displayName: 'View JSON/YAML', - icon: FileText, - action: async () => { - const fullScript = await ScriptService.getScriptByPath({ - workspace: $workspaceStore!, - path: script.path - }) - wacExportDrawer?.open(fullScript) - } - } - ] - : []), - { - displayName: 'Duplicate/Fork', - icon: GitFork, - href: `/scripts/add?template=${script.path}`, - disabled: !showEditButton, - hide: !$roleCapabilities.code - }, - { - displayName: editInForkLabel($workspaceStore, $userWorkspaces), - icon: Pen, - // No `href`: the handler resolves the destination asynchronously, and a melt - // menu item's anchor navigates before a delegated onclick can preventDefault it. - action: (e) => onEditInForkClick(e, 'script', script.path), - hide: - !$roleCapabilities.code || - isCloudHosted() || - !editInForkAllowed($workspaceStore, $userWorkspaces) - }, - { - displayName: 'Move/Rename', - icon: FolderOpen, - action: () => { - moveDrawer.openDrawer(script.path, script.summary, 'script') - }, - disabled: !owner || script.archived || !canEdit, - hide: !$roleCapabilities.code - }, - ...(isDeployable('script', script.path, await getDeployUiSettings()) - ? [ - { - displayName: 'Deploy to staging/prod', - icon: ChevronUpSquare, - action: () => { - deploymentDrawer.openDrawer(script.path, 'script') - }, - disabled: script.archived, - hide: !$roleCapabilities.code - } - ] - : []), - { - displayName: 'View runs', - icon: List, - href: `/runs/${script.path}` - }, - { - displayName: 'Versions', - icon: History, - action: () => { - versionsDrawerOpen = true - } - }, - { - displayName: 'Audit logs', - icon: Eye, - href: `/audit_logs?resource=${script.path}`, - hide: !$roleCapabilities.code || !$roleCapabilities.visibility.audit_logs - }, - { - displayName: 'Schedule', - icon: Calendar, - action: () => { - scheduleEditor?.openNew(false, script.path) - }, - disabled: script.archived, - hide: !$roleCapabilities.code || !$roleCapabilities.manage_schedules - }, - { - displayName: 'Permissions', - icon: Shield, - action: () => { - shareModal.openDrawer && shareModal.openDrawer(script.path, 'script') - }, - disabled: script.archived, - hide: !$roleCapabilities.code - }, - { - displayName: 'Copy path', - icon: Copy, - action: () => { - copyToClipboard(script.path) - } - }, - { - displayName: 'Publish to Hub', - icon: Globe2, - action: async () => { - // The row only carries metadata, so the code has to be fetched first; the tab is - // claimed before that, since Safari won't open one after an await. - const tab = claimTab() - try { - const fullScript = await ScriptService.getScriptByPath({ - workspace: $workspaceStore!, - path: script.path - }) - const url = scriptToHubUrl(fullScript, $hubBaseUrlStore).toString() - if (tab) { - tab.show(url) - } else if (!window.open(url)) { - sendUserToast('Allow popups to publish this script to the Hub', true) - } - } catch (e: any) { - tab?.discard() - sendUserToast(`Could not load ${script.path}: ${e?.body ?? e?.message ?? e}`, true) - } - }, - // Operators can't write scripts, so they have nothing to publish. - hide: $disableHubStore || !$roleCapabilities.code - }, - { - displayName: script.archived ? 'Unarchive' : 'Archive', - icon: Archive, - action: () => { - script.archived - ? script.path && unarchiveScript(script.path) - : script.path && archiveScript(script.path) - }, - type: 'delete', - disabled: !owner || !canEdit, - hide: !$roleCapabilities.code - }, - - ...($userStore?.is_admin || $userStore?.is_super_admin - ? [ - { - displayName: 'Delete', - icon: Trash, - action: (event) => { - if (event?.shiftKey) { - deleteScript(script.path) - } else { - deleteConfirmedCallback = () => { - deleteScript(script.path) - } - } - }, - type: dlt, - disabled: !canEdit, - hide: !$roleCapabilities.code - } - ] - : []) - ] + ) }} on:open={() => { menuOpen = true diff --git a/frontend/src/lib/components/common/table/menuGroups.ts b/frontend/src/lib/components/common/table/menuGroups.ts new file mode 100644 index 0000000000..7071b6f11e --- /dev/null +++ b/frontend/src/lib/components/common/table/menuGroups.ts @@ -0,0 +1,25 @@ +import type { Item } from '$lib/utils' + +/** + * Joins a row menu's groups into one list with a divider above each group. The divider rides on + * the group's first visible item, so a group whose items are all hidden leaves no stray line. + */ +export function menuGroups(...groups: Item[][]): Item[] { + const out: Item[] = [] + for (const group of groups) { + const visible = group.filter((item) => !item.hide) + if (visible.length === 0) continue + out.push({ ...visible[0], separatorTop: out.length > 0 }, ...visible.slice(1)) + } + return out +} + +/** + * A submenu for actions that share a heading. With a single visible child the child is shown + * in place, since a submenu of one is an extra hover for nothing. + */ +export function submenu(displayName: string, icon: any, children: Item[]): Item { + const visible = children.filter((item) => !item.hide) + if (visible.length === 1) return visible[0] + return { displayName, icon, submenuItems: visible, hide: visible.length === 0 } +} diff --git a/frontend/src/lib/components/home/deploy_ui.ts b/frontend/src/lib/components/home/deploy_ui.ts index 1134789e76..ea51129347 100644 --- a/frontend/src/lib/components/home/deploy_ui.ts +++ b/frontend/src/lib/components/home/deploy_ui.ts @@ -4,14 +4,55 @@ import { ALL_DEPLOYABLE } from '$lib/utils_deployable' import { get, writable } from 'svelte/store' const deployUiStore = writable>({}) +let pending: Record> = {} +let generation = 0 + +// Until the license loads, a load reads as CE and resolves to ALL_DEPLOYABLE. Rows warm the cache +// on mount, often before then, so a license arriving drops whatever was loaded without it. +enterpriseLicense.subscribe((license) => { + if (!license) return + const hadSettings = Object.keys(get(deployUiStore)).length > 0 || Object.keys(pending).length > 0 + generation++ + pending = {} + deployUiStore.set({}) + if (hadSettings) warmDeployUiSettings() +}) + export async function getDeployUiSettings(): Promise { - let deployUiSettings = get(deployUiStore) - let workspace = get(workspaceStore) - if (!deployUiSettings[workspace!]) { - deployUiSettings[workspace!] = await getDeployUiSettingsInner() - deployUiStore.set(deployUiSettings) + const workspace = get(workspaceStore)! + const cached = get(deployUiStore)[workspace] + if (cached) return cached + const gen = generation + const load = (pending[workspace] ??= getDeployUiSettingsInner()) + let settings: WorkspaceDeployUISettings + try { + settings = await load + } finally { + if (pending[workspace] === load) delete pending[workspace] } - return deployUiSettings[workspace!] + if (gen !== generation) return getDeployUiSettings() + deployUiStore.update((s) => ({ ...s, [workspace]: settings })) + return settings +} + +/** + * Starts loading the settings without waiting for them. Every row on a page calls this, so a + * failed fetch must not reject: the root layout toasts each unhandled rejection, once per row. + */ +export function warmDeployUiSettings(): void { + getDeployUiSettings().catch(() => {}) +} + +/** + * The current workspace's settings if a load has already resolved. Row menus read this so they + * can build their items synchronously: a menu whose items arrive after it opens is positioned for + * its loading spinner and then flips once the real list is taller. A miss starts a new load, so a + * fetch that failed is retried on the next open. + */ +export function cachedDeployUiSettings(): WorkspaceDeployUISettings | undefined { + const settings = get(deployUiStore)[get(workspaceStore)!] + if (!settings) warmDeployUiSettings() + return settings } async function getDeployUiSettingsInner(): Promise { From da443d2fb263ecaf90320809b1bb2fc8a4f65b20 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Fri, 23 Oct 2026 14:50:31 +0200 Subject: [PATCH 061/101] feat: manage and create folders from the home tree view (#11943) * feat: manage and create folders from the home tree view * fix: drop empty folders under a kind filter, gate manage on visibility * fix: show the tree in a folders-only workspace, record created folder * fix: address review nits on the home folder menu * fix: record created folder ownership, offer folder in empty-state menu --- .../components/home/CreateActionsMenu.svelte | 34 +++++++++++++-- .../src/lib/components/home/ItemsList.svelte | 41 ++++++++++++++++++- .../lib/components/home/TreeOwnerRow.svelte | 32 +++++++++++++-- .../src/lib/components/home/TreeView.svelte | 35 +++++++++++++++- .../lib/components/home/TreeViewRoot.svelte | 25 ++++++++--- .../home/WorkspaceEmptyState.svelte | 12 +++++- 6 files changed, 161 insertions(+), 18 deletions(-) diff --git a/frontend/src/lib/components/home/CreateActionsMenu.svelte b/frontend/src/lib/components/home/CreateActionsMenu.svelte index 72b75b82e1..9b8db55066 100644 --- a/frontend/src/lib/components/home/CreateActionsMenu.svelte +++ b/frontend/src/lib/components/home/CreateActionsMenu.svelte @@ -16,8 +16,10 @@ Workflow, Import, Store, - PanelLeftClose + PanelLeftClose, + Folder } from 'lucide-svelte' + import MenuItem from '$lib/components/meltComponents/MenuItem.svelte' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import DbtIcon from '$lib/components/icons/DbtIcon.svelte' import { PythonIcon, TypeScriptIcon } from '$lib/components/common/languageIcons' @@ -48,9 +50,17 @@ * serve both this menu and the empty state's own link. */ onImportHubProject?: () => void + /** Opens the host's folder drawer. The entry is offered only when this is set. */ + onCreateFolder?: () => void } - let { trigger, triggerElement, source = 'toolbar', onImportHubProject }: Props = $props() + let { + trigger, + triggerElement, + source = 'toolbar', + onImportHubProject, + onCreateFolder + }: Props = $props() type Variant = { label: string @@ -713,8 +723,26 @@ {/if} {/each} - +
    + {#if onCreateFolder} + + highlightOption(undefined)} + onClick={() => onCreateFolder()} + > +
    + +
    + + Folder + +
    + {/if}
    @@ -2033,7 +2065,7 @@ have scrolled away. -->
    {/if} - {#if filteredItems?.length == 0 && !workspaceEmpty} + {#if filteredItems?.length == 0 && !workspaceEmpty && !treeShowsFolders}
    {/if} @@ -29,7 +40,7 @@ onclick={onToggle} class="px-4 py-2 {rowRule( unruled - )} w-full flex flex-row items-center justify-between cursor-pointer hover:bg-surface-hover" + )} group/row w-full flex flex-row items-center justify-between cursor-pointer hover:bg-surface-hover" >
    - {name} +
    + {name} + {#if actions} + + + +
    e.stopPropagation()} + > + {@render actions()} +
    + {/if} +
    {@render detail()}
    diff --git a/frontend/src/lib/components/home/TreeView.svelte b/frontend/src/lib/components/home/TreeView.svelte index 7331318727..f7b99ae5d7 100644 --- a/frontend/src/lib/components/home/TreeView.svelte +++ b/frontend/src/lib/components/home/TreeView.svelte @@ -3,7 +3,9 @@ import { createEventDispatcher, onDestroy, untrack, type Snippet } from 'svelte' import ResizeTransitionWrapper from '$lib/components/common/ResizeTransitionWrapper.svelte' - import { Folder, FolderTree, User } from 'lucide-svelte' + import { Eye, Folder, FolderTree, Pen, User } from 'lucide-svelte' + import { userStore } from '$lib/stores' + import Dropdown from '$lib/components/DropdownV2.svelte' import TreeOwnerRow from './TreeOwnerRow.svelte' import PipelineRow from '../common/table/PipelineRow.svelte' import Item from './Item.svelte' @@ -56,6 +58,9 @@ // Remembers which nodes the user opened by hand, so they reopen on the next visit // while expand/collapse-all is in its collapsed state. openMemory?: TreeOpenMemory + // Adds a "Manage folder" menu ("View folder" for a non-owner) to top-level folder rows. + // Subfolders are path segments, not folders with permissions of their own, so get none. + onManageFolder?: (folderName: string) => void } let { @@ -75,7 +80,8 @@ ancestorHasMore = false, indent = 0, leaf, - openMemory + openMemory, + onManageFolder }: Props = $props() const unruled = inUnruledList() @@ -270,6 +276,29 @@ } +{#snippet manageFolderMenu()} + {#if isFolder(item)} + {@const folderName = item.folderName} + + {@const canWrite = + $userStore?.is_admin || + $userStore?.is_super_admin || + $userStore?.folders_owners.includes(folderName)} + onManageFolder?.(folderName) + } + ]} + /> + {/if} +{/snippet} + {#if isFolder(item) || isUser(item)}
    {#snippet detail()} {#if ownerCount != undefined} @@ -331,6 +361,7 @@ depth={depth + 1} {indent} {leaf} + {onManageFolder} /> {/each} {#if effectiveMax < item.items.length} diff --git a/frontend/src/lib/components/home/TreeViewRoot.svelte b/frontend/src/lib/components/home/TreeViewRoot.svelte index 86c1984254..d5023176b5 100644 --- a/frontend/src/lib/components/home/TreeViewRoot.svelte +++ b/frontend/src/lib/components/home/TreeViewRoot.svelte @@ -53,6 +53,11 @@ leaf?: Snippet<[ItemType, number]> // See TreeView's `openMemory`. openMemory?: TreeOpenMemory + // See TreeView's `onManageFolder`. + onManageFolder?: (folderName: string) => void + // Inject folders `ownerCounts` calls empty, as "0 items". Off under a kind filter, + // where those counts are per kind and every folder lacking that kind would show. + keepEmptyFolders?: boolean } let { @@ -76,7 +81,9 @@ framed = true, groupOtherUsers = false, leaf, - openMemory + openMemory, + onManageFolder, + keepEmptyFolders = false }: Props = $props() const unruled = inUnruledList() @@ -127,15 +134,20 @@ .filter((g) => 'folderName' in g) .map((g) => (g as { folderName: string }).folderName) ) - // Once counts are in, an owner holding nothing the user can see is dropped - // rather than injected — a workspace's folder list is mostly noise in the - // tree otherwise. Pipeline folders are exempt: their entry is the pipeline - // itself, whose member scripts are folded out of the runnable count. + // Once counts are in, a user space holding nothing the user can see is dropped + // rather than injected — the member list is mostly noise in the tree otherwise. + // Empty folders are dropped too unless `keepEmptyFolders`. Pipeline folders are + // exempt: their entry is the pipeline, whose scripts the count folds out. const isEmptyOwner = (prefix: string) => ownerCounts != undefined && !ownerCounts[prefix] const missingFolders: { folderName: string; items: [] }[] = [] for (const folderName of [...(pipelineFolders ?? []), ...allFolders]) { if (presentFolders.has(folderName)) continue - if (!pipelineFolders?.has(folderName) && isEmptyOwner(`f/${folderName}`)) continue + if ( + !keepEmptyFolders && + !pipelineFolders?.has(folderName) && + isEmptyOwner(`f/${folderName}`) + ) + continue presentFolders.add(folderName) missingFolders.push({ folderName, items: [] }) } @@ -276,6 +288,7 @@ {showEditButton} {leaf} {openMemory} + {onManageFolder} /> {/snippet} diff --git a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte index 813cb3a265..5014e2842b 100644 --- a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte +++ b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte @@ -26,9 +26,17 @@ * take — the archived link stays, since reading archived items is not a write. */ canCreate?: boolean + /** See CreateActionsMenu's `onCreateFolder`. */ + onCreateFolder?: () => void } - let { onPick, archivedOnly = false, onShowArchived, canCreate = true }: Props = $props() + let { + onPick, + archivedOnly = false, + onShowArchived, + canCreate = true, + onCreateFolder + }: Props = $props() // Row opacities: the list fading out of existence. Static on purpose — motion is what // makes a skeleton mean "loading", and this state means "empty". @@ -136,7 +144,7 @@ or {/if} - + {#snippet trigger()} From e5dedd147e1db0c4f36796ba292188bcdb0efc5a Mon Sep 17 00:00:00 2001 From: hugocasa Date: Fri, 23 Oct 2026 15:05:20 +0200 Subject: [PATCH 062/101] feat: let flow builder operators build AI agents (#11898) * feat: let flow builder operators build AI agents Co-Authored-By: Claude Opus 5.5 * fix: check linked agents' bound tools and type, validate on the write's transaction Co-Authored-By: Claude Opus 5.5 * fix: bound the linked-agent walk by sorting bound tool ids Co-Authored-By: Claude Opus 5.5 * fix: let builders bind only the agent tool inputs left to the model Co-Authored-By: Claude Opus 5.5 * fix: check every agent tool sharing a bound id Co-Authored-By: Claude Opus 5.5 * feat: show builders the agent's own tool inputs read-only and name agents in the setting Co-Authored-By: Claude Opus 5.5 * refactor: show the agent's own tool inputs with the read-only step viewer Co-Authored-By: Claude Opus 5.5 * style: give the agent-set inputs heading the input label style Co-Authored-By: Claude Opus 5.5 * style: label the agent's fixed tool inputs static inputs Co-Authored-By: Claude Opus 5.5 * fix: address cubic review on agent builder rights Co-Authored-By: Claude Opus 5.5 * fix: check agent writes against the role's flows capability Co-Authored-By: Claude Opus 5.5 * docs: name the flows capability as the agent builder right Co-Authored-By: Claude Opus 5.5 * fix: gate agent evals on the role's code capability Co-Authored-By: Claude Opus 5.5 * refactor: move the composed-flow check into windmill-api-auth Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 2 +- ...6c752ea54871db71a8859311e18bf6b6da82c.json | 23 +++ backend/tests/ai_agent_linked.rs | 55 ++++++ backend/windmill-api-auth/src/composed.rs | 171 ++++++++++++++++++ backend/windmill-api-auth/src/lib.rs | 1 + backend/windmill-api-flows/src/flows.rs | 86 +-------- .../tests/operator_builder_flows.rs | 150 +++++++++++++++ backend/windmill-api/src/drafts.rs | 37 ++++ backend/windmill-common/src/client.rs | 24 +++ backend/windmill-common/src/flows.rs | 134 ++++++++++++-- backend/windmill-store/src/resources.rs | 6 + backend/windmill-types/src/flows.rs | 13 ++ backend/windmill-worker/src/ai/tools.rs | 6 +- backend/windmill-worker/src/ai/utils.rs | 20 +- backend/windmill-worker/src/ai_executor.rs | 26 +-- docs/operator-builder-rights.md | 37 +++- docs/workspace-roles.md | 2 +- .../components/copilot/chat/global/core.ts | 8 +- .../src/lib/components/flows/agentActions.ts | 3 +- .../flows/content/AgentEditorModal.svelte | 13 +- .../flows/content/AgentSettings.svelte | 11 +- .../flows/content/AgentToolBindings.svelte | 47 ++++- .../flows/map/InsertModuleInner.svelte | 13 +- .../settings/RoleCapabilitiesEditor.svelte | 5 +- frontend/src/lib/editRights.test.ts | 5 +- frontend/src/lib/editRights.ts | 6 +- .../agents/get/[...path]/+page.svelte | 26 ++- 27 files changed, 763 insertions(+), 167 deletions(-) create mode 100644 backend/.sqlx/query-56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c.json create mode 100644 backend/tests/ai_agent_linked.rs create mode 100644 backend/windmill-api-auth/src/composed.rs diff --git a/AGENTS.md b/AGENTS.md index c2aae7159d..835c8a4edb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,7 @@ Open-source platform for internal tools, workflows, API integrations, background enforced rather than cosmetic, and why a right that is granted-unless-withdrawn needs `Option` fields and a jsonb merge rather than a serde default - **Operator builder rights**: `docs/operator-builder-rights.md` — the workspace settings that let - operators compose flows and full-code apps, what the composition check must cover, which + operators compose flows, AI agents and full-code apps, what the composition check must cover, which raw-app endpoint stays closed on purpose, and why either right costs a full seat - **Auth surface**: `docs/auth-surface.md` — credential precedence, session/cache invalidation scope, which token labels email their owner at expiry, how OAuth login matches `login_type`, and diff --git a/backend/.sqlx/query-56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c.json b/backend/.sqlx/query-56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c.json new file mode 100644 index 0000000000..17a9650d3e --- /dev/null +++ b/backend/.sqlx/query-56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value AS \"value: sqlx::types::Json\"\n FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value: sqlx::types::Json", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "56bb398d53c1c54b27fe3b61b866c752ea54871db71a8859311e18bf6b6da82c" +} diff --git a/backend/tests/ai_agent_linked.rs b/backend/tests/ai_agent_linked.rs new file mode 100644 index 0000000000..8b7f328213 --- /dev/null +++ b/backend/tests/ai_agent_linked.rs @@ -0,0 +1,55 @@ +use serde_json::json; +use sqlx::{Pool, Postgres}; +use std::time::Duration; +use windmill_common::{flows::FlowValue, jobs::JobPayload}; +use windmill_test_utils::{ + completed_job, in_test_worker, listen_for_completed_jobs, ApiServer, RunJob, StreamFind, +}; + +/// Only writes of an agent are checked for operators, so a linked step must refuse a path whose +/// resource is no longer an agent rather than run the `tools` it now holds. +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn linked_agent_step_refuses_a_resource_of_another_type( + db: Pool, +) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type) + VALUES ('test-workspace', 'u/test-user/agent', $1, 'object')", + ) + .bind( + json!({"tools": [{"id": "t", "value": {"tool_type": "flowmodule", + "type": "rawscript", "language": "bun", "input_transforms": {}, + "content": "export async function main() { return 1 }"}}]}), + ) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let flow: FlowValue = serde_json::from_value(json!({"modules": [{"id": "agent", "value": { + "type": "aiagent", "tools": [], "agent": "$res:u/test-user/agent", + "input_transforms": {"user_message": {"type": "static", "value": "hi"}} + }}]}))?; + let id = RunJob::from(JobPayload::RawFlow { + value: flow, + path: Some("u/test-user/linked".into()), + restarted_from: None, + }) + .push(&db) + .await; + let notifications = listen_for_completed_jobs(&db).await; + tokio::time::timeout( + Duration::from_secs(45), + in_test_worker(&db, notifications.find(&id), server.addr.port()), + ) + .await?; + let job = completed_job(id, &db).await; + server.close().await?; + assert!(!job.success); + assert!( + format!("{:?}", job.result).contains("not an AI agent"), + "{:?}", + job.result + ); + Ok(()) +} diff --git a/backend/windmill-api-auth/src/composed.rs b/backend/windmill-api-auth/src/composed.rs new file mode 100644 index 0000000000..e9d79240dd --- /dev/null +++ b/backend/windmill-api-auth/src/composed.rs @@ -0,0 +1,171 @@ +//! Authorizing what a restricted role composes: the references a value-only walk +//! (`check_flow_is_composition_only`) collects, checked against the caller's own permissions. + +use sqlx::{Postgres, Transaction}; +use windmill_common::{ + error::{self, Error}, + flows::FlowValue, + roles::AuthorLevel, + workspaces::{check_operator_can_build, BuilderKind}, + DB, +}; + +use crate::{get_scope_tags, is_super_admin_authed, ApiAuthed}; + +/// `validate_operator_composed_flow` on a transaction the caller already holds, so a write that +/// has one open does not wait on a second connection. It must have been begun as the caller +/// (`UserDB::begin`): its row-level security is the check. +pub async fn authorize_composed_flow( + value: &FlowValue, + flow_tag: &Option, + authed: &ApiAuthed, + db: &DB, + tx: &mut Transaction<'_, Postgres>, + w_id: &str, +) -> error::Result<()> { + let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?; + + // A builder links only an agent it can read, and binds only the tool inputs it leaves open. + for agent in &refs.agents { + let path = &agent.path; + let value = sqlx::query_scalar!( + "SELECT value AS \"value: sqlx::types::Json\" + FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + w_id, + path, + ) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| { + Error::PermissionDenied(format!( + "Agent {path} does not exist or is not readable by you" + )) + })?; + if agent.bound_inputs.is_empty() { + continue; + } + let tools: Vec = value + .and_then(|v| v.0.get("tools").cloned()) + .map(serde_json::from_value) + .transpose() + .map_err(|e| Error::BadRequest(format!("Invalid tools in agent {path}: {e}")))? + .unwrap_or_default(); + windmill_common::flows::check_bound_agent_inputs_are_open( + path, + &tools, + &agent.bound_inputs, + )?; + } + + // A tag is how a step picks the worker group it runs on: unauthorized, a builder could route + // a job onto a privileged one. + refs.tags.extend(flow_tag.clone().filter(|t| !t.is_empty())); + if !refs.tags.is_empty() { + // Job-aware: a WM_TOKEN running as a superadmin must not unlock restricted tags. + let is_super_admin = is_super_admin_authed(db, authed).await?; + for tag in &refs.tags { + windmill_common::jobs::check_tag_available_for_workspace_internal( + db, + w_id, + tag, + None, + std::future::ready(w_id.to_string()), + is_super_admin, + get_scope_tags(authed), + ) + .await?; + } + } + + if refs.runnables.is_empty() && refs.pinned_scripts.is_empty() { + return Ok(()); + } + // A flow can step through the same script thirty times; this runs on every write, preview and + // dependency job. + refs.runnables.sort(); + refs.runnables.dedup(); + refs.pinned_scripts + .sort_by_key(|(path, hash)| (path.clone(), hash.0)); + refs.pinned_scripts + .dedup_by_key(|(path, hash)| (path.clone(), hash.0)); + // The worker resolves a step's path with the root DB handle and runs it as that runnable's + // `on_behalf_of`, so composing an unreadable path would run code the builder cannot see. RLS + // on this transaction is the check. + for (is_flow, path) in &refs.runnables { + let readable = if *is_flow { + sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2)", + w_id, + path, + ) + } else { + sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2)", + w_id, + path, + ) + } + .fetch_one(&mut **tx) + .await? + .unwrap_or(false); + if !readable { + return Err(Error::PermissionDenied(format!( + "{} {path} does not exist or is not readable by you", + if *is_flow { "Flow" } else { "Script" } + ))); + } + } + // A pinned step is dispatched by its hash alone, ignoring the path beside it, so a readable + // path paired with another script's hash would still run that other script. + for (path, hash) in &refs.pinned_scripts { + let exists = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND hash = $3)", + w_id, + path, + hash.0, + ) + .fetch_one(&mut **tx) + .await? + .unwrap_or(false); + if !exists { + return Err(Error::PermissionDenied(format!( + "Version {hash} is not a readable version of {path}" + ))); + } + } + Ok(()) +} + +/// What a restricted role must pass to store an `ai_agent` resource, deployed or as a draft. Its +/// tools run in the agent's own runs and in every flow step linking it, so it is held to the rules +/// of a composed flow, under the same capability. `tx` is the write's own, begun as the caller. +pub async fn validate_operator_agent( + value: &serde_json::Value, + authed: &ApiAuthed, + db: &DB, + tx: &mut Transaction<'_, Postgres>, + w_id: &str, +) -> error::Result<()> { + if check_operator_can_build(db, w_id, authed, BuilderKind::Flows, "write AI agents").await? + == AuthorLevel::Full + { + return Ok(()); + } + let tools = value + .get("tools") + .cloned() + .unwrap_or_else(|| serde_json::json!([])); + let flow: FlowValue = serde_json::from_value(serde_json::json!({"modules": [{ + "id": "agent", + "value": {"type": "aiagent", "input_transforms": {}, "tools": tools} + }]})) + .map_err(|e| Error::BadRequest(format!("Invalid agent tools: {e}")))?; + authorize_composed_flow(&flow, &None, authed, db, tx, w_id) + .await + .map_err(|e| match e { + Error::PermissionDenied(msg) => { + Error::PermissionDenied(msg.replace("edit this flow", "edit this agent")) + } + e => e, + }) +} diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index bfbd4470c8..82a40377a0 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -7,6 +7,7 @@ */ pub mod auth; +pub mod composed; #[cfg(feature = "private")] pub mod ee; pub mod ee_oss; diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index 3ef3de7a33..4c0ecaf4c4 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -16,8 +16,8 @@ use axum::{ }; use windmill_api_auth::{ auth::{list_tokens_internal, TruncatedTokenWithEmail}, - build_scope_path_predicate, check_scopes, get_scope_tags, maybe_refresh_folders, - require_owner_of_path, ApiAuthed, + build_scope_path_predicate, check_scopes, maybe_refresh_folders, require_owner_of_path, + ApiAuthed, }; use windmill_common::roles::AuthorLevel; use windmill_common::workspaces::{ @@ -643,85 +643,11 @@ pub async fn validate_operator_composed_flow( user_db: &UserDB, w_id: &str, ) -> error::Result<()> { - let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?; - - // A tag is how a step picks the worker group it runs on: unauthorized, a builder could route - // a job onto a privileged one. - refs.tags.extend(flow_tag.clone().filter(|t| !t.is_empty())); - if !refs.tags.is_empty() { - // Job-aware: a WM_TOKEN running as a superadmin must not unlock restricted tags. - let is_super_admin = windmill_api_auth::is_super_admin_authed(db, authed).await?; - for tag in &refs.tags { - windmill_common::jobs::check_tag_available_for_workspace_internal( - db, - w_id, - tag, - None, - std::future::ready(w_id.to_string()), - is_super_admin, - get_scope_tags(authed), - ) - .await?; - } - } - - if refs.runnables.is_empty() && refs.pinned_scripts.is_empty() { - return Ok(()); - } - // A flow can step through the same script thirty times; this runs on every write, preview and - // dependency job. - refs.runnables.sort(); - refs.runnables.dedup(); - refs.pinned_scripts - .sort_by_key(|(path, hash)| (path.clone(), hash.0)); - refs.pinned_scripts - .dedup_by_key(|(path, hash)| (path.clone(), hash.0)); - // The worker resolves a step's path with the root DB handle and runs it as that runnable's - // `on_behalf_of`, so composing an unreadable path would run code the builder cannot see. RLS - // on this transaction is the check. let mut tx = user_db.clone().begin(authed).await?; - for (is_flow, path) in &refs.runnables { - let readable = if *is_flow { - sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2)", - w_id, - path, - ) - } else { - sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2)", - w_id, - path, - ) - } - .fetch_one(&mut *tx) - .await? - .unwrap_or(false); - if !readable { - return Err(Error::PermissionDenied(format!( - "{} {path} does not exist or is not readable by you", - if *is_flow { "Flow" } else { "Script" } - ))); - } - } - // A pinned step is dispatched by its hash alone, ignoring the path beside it, so a readable - // path paired with another script's hash would still run that other script. - for (path, hash) in &refs.pinned_scripts { - let exists = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND hash = $3)", - w_id, - path, - hash.0, - ) - .fetch_one(&mut *tx) - .await? - .unwrap_or(false); - if !exists { - return Err(Error::PermissionDenied(format!( - "Version {hash} is not a readable version of {path}" - ))); - } - } + windmill_api_auth::composed::authorize_composed_flow( + value, flow_tag, authed, db, &mut tx, w_id, + ) + .await?; tx.commit().await?; Ok(()) } diff --git a/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs index b9c4e60800..6bed27eca5 100644 --- a/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs +++ b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs @@ -325,5 +325,155 @@ async fn test_operator_builder_flows_boundary(db: Pool) -> anyhow::Res resp.text().await? ); + check_builder_agents(&db, &api, &c).await +} + +/// An agent is a resource an operator may otherwise write, and its stored tools run as they are, +/// so only the flow right opens it, and every write of one, drafts included, is checked like a +/// composed flow. Part of the boundary test: the right is read through a process-global cache +/// keyed by workspace id, which a second test in this binary would race. +async fn check_builder_agents( + db: &Pool, + api: &str, + c: &reqwest::Client, +) -> anyhow::Result<()> { + let tool = |mut value: serde_json::Value| { + value["tool_type"] = json!("flowmodule"); + value["input_transforms"] = json!({}); + json!({"tools": [{"id": "t", "summary": "t", "value": value}]}) + }; + let composed = tool(json!({"type": "script", "path": "u/operator/some_script"})); + let inline = tool(json!({"type": "rawscript", "content": "echo x", "language": "bash"})); + let agent = |path: &str, value: &serde_json::Value| json!({"path": path, "resource_type": "ai_agent", "value": value}); + + set_builder(db, false).await?; + let resp = c + .post(format!("{api}/resources/create")) + .json(&agent("u/operator/a1", &composed)) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "an operator without the builder right must not write an agent" + ); + + set_builder(db, true).await?; + let resp = c + .post(format!("{api}/resources/create")) + .json(&agent("u/operator/a1", &inline)) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not save an agent with an inline tool" + ); + let resp = c + .post(format!("{api}/resources/create")) + .json(&agent("u/operator/a1", &composed)) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + let resp = c + .post(format!("{api}/resources/update_value/u/operator/a1")) + .json(&json!({"value": inline})) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not swap an agent's tools for inline code" + ); + // A draft of a deployed agent may leave its type to the deployed row. + let resp = c + .post(format!("{api}/drafts/update/resource/u/operator/a1")) + .json(&json!({"value": {"args": inline, "description": ""}, "force": true})) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not draft an agent with an inline tool" + ); + // Deploying a draft over an agent keeps the row's type, whatever type the draft names. + let resp = c + .post(format!("{api}/drafts/update/resource/u/operator/a1")) + .json(&json!({"value": {"args": inline, "description": "", "resource_type": "object"}, + "force": true})) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not draft inline tools over an agent under another type" + ); + + let linking = |path: &str, agent: &str| { + json!({"path": path, "summary": "", "description": "", "schema": {}, + "value": {"modules": [{"id": "a", "value": {"type": "aiagent", + "input_transforms": {}, "tools": [], "agent": format!("$res:{agent}")}}]}}) + }; + let resp = c + .post(format!("{api}/flows/create")) + .json(&linking("u/operator/agent_f1", "u/operator/a1")) + .send() + .await?; + assert!( + resp.status().is_success(), + "a builder must be able to link a readable agent: {}", + resp.text().await? + ); + let resp = c + .post(format!("{api}/flows/create")) + .json(&linking("u/operator/agent_f2", "u/alice/agent")) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not link an agent it cannot read" + ); + + // A developer's agent may run inline code, and linking it runs it as authored. A step may bind + // the inputs the agent leaves to the model, never one its author set. + let mut dev_agent = inline.clone(); + dev_agent["tools"][0]["value"]["input_transforms"] = json!({ + "set": {"type": "static", "value": "fixed"}, "open": {"type": "ai"}}); + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, created_by) + VALUES ($1, 'u/operator/dev_agent', $2, 'ai_agent', 'alice')", + ) + .bind(WS) + .bind(&dev_agent) + .execute(db) + .await?; + let binding = |path: &str, input: &str| { + let mut flow = linking(path, "u/operator/dev_agent"); + flow["value"]["modules"][0]["value"]["tool_inputs"] = + json!({"t": {input: {"type": "static", "value": "bound"}}}); + flow + }; + let resp = c + .post(format!("{api}/flows/create")) + .json(&binding("u/operator/agent_f4", "open")) + .send() + .await?; + assert!( + resp.status().is_success(), + "a builder must be able to bind an input the agent leaves open: {}", + resp.text().await? + ); + let resp = c + .post(format!("{api}/flows/create")) + .json(&binding("u/operator/agent_f3", "set")) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a builder must not override an input the agent's author set" + ); + Ok(()) } diff --git a/backend/windmill-api/src/drafts.rs b/backend/windmill-api/src/drafts.rs index 018fc43d54..31a7bea2c5 100644 --- a/backend/windmill-api/src/drafts.rs +++ b/backend/windmill-api/src/drafts.rs @@ -499,6 +499,43 @@ async fn update_draft( } } + // An agent draft is held to the rules of its deploy, as a flow draft is: a developer who + // tests it in the agent editor runs its tools as themselves. + if caps.flows != AuthorLevel::Full && kind == UserDraftItemKind::Resource { + if let Some(value) = &req.value { + #[derive(Deserialize)] + struct ResourceDraft { + #[serde(default)] + args: serde_json::Value, + resource_type: Option, + } + let draft: ResourceDraft = serde_json::from_str(&strip_json_nul(value.0.get())) + .map_err(|e| Error::BadRequest(format!("Invalid resource draft: {e}")))?; + // Whatever type the draft names, deploying it over a deployed agent keeps the row's type. + let is_agent = draft.resource_type.as_deref() == Some("ai_agent") + || sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent')", + &w_id, + path, + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if is_agent { + let mut tx = user_db.clone().begin(&authed).await?; + windmill_api_auth::composed::validate_operator_agent( + &draft.args, + &authed, + &db, + &mut tx, + &w_id, + ) + .await?; + tx.commit().await?; + } + } + } + // A raw-app draft carries the app value and its policy side by side. if caps.apps == AuthorLevel::Compose && kind == UserDraftItemKind::RawApp { if let Some(value) = &req.value { diff --git a/backend/windmill-common/src/client.rs b/backend/windmill-common/src/client.rs index 985d3bbbfc..8edcdc64fe 100644 --- a/backend/windmill-common/src/client.rs +++ b/backend/windmill-common/src/client.rs @@ -110,6 +110,30 @@ impl AuthedClient { make_basic_get_request(self, &url, None, Some("decoding resource value as json")).await } + /// The value of the `ai_agent` resource at `path`, refused when the resource there is of another + /// type. Only writes of an agent are checked for operators, so a step linking a path must not run + /// tools from a resource retyped, or recreated as another type, since the link was approved. + pub async fn get_agent_value(&self, path: &str) -> anyhow::Result { + #[derive(serde::Deserialize)] + struct Resource { + resource_type: String, + value: Option, + } + let url = format!( + "{}/api/w/{}/resources/get/{}", + self.base_internal_url, self.workspace, path + ); + let resource: Resource = + make_basic_get_request(self, &url, None, Some("decoding the agent resource")).await?; + if resource.resource_type != "ai_agent" { + anyhow::bail!( + "{path} is a {} resource, not an AI agent", + resource.resource_type + ); + } + Ok(resource.value.unwrap_or_default()) + } + pub async fn get_variable_value(&self, path: &str) -> anyhow::Result { let url = format!( "{}/api/w/{}/variables/get_value/{}", diff --git a/backend/windmill-common/src/flows.rs b/backend/windmill-common/src/flows.rs index 222694aeac..500549c549 100644 --- a/backend/windmill-common/src/flows.rs +++ b/backend/windmill-common/src/flows.rs @@ -252,8 +252,8 @@ pub async fn resolve_modules( /// modules, every branch, and the `tools` of an AI agent step. /// /// Returns what the caller still has to authorize against its own permissions, which this -/// value-only walk cannot: every runnable the steps reference, the worker tags they pin, and the -/// `(path, hash)` pairs of version-pinned steps. See [`ComposedFlowRefs`] for why each one is not +/// value-only walk cannot: every runnable and linked agent the steps reference, the worker tags +/// they pin, and the `(path, hash)` pairs of version-pinned steps. See [`ComposedFlowRefs`] for why each one is not /// already settled by the walk. pub fn check_flow_is_composition_only(value: &FlowValue) -> Result { let mut refs = ComposedFlowRefs::default(); @@ -276,6 +276,65 @@ pub struct ComposedFlowRefs { pub runnables: Vec<(bool, String)>, /// Version-pinned script steps, as `(path, hash)`. pub pinned_scripts: Vec<(String, ScriptHash)>, + /// The `ai_agent` resources that agent steps link. + pub agents: Vec, +} + +/// An agent step's link, with the tool inputs the step binds, keyed by tool id. +pub struct LinkedAgent { + pub path: String, + pub bound_inputs: Vec<(String, Vec)>, +} + +/// A builder's step may bind only the tool inputs its linked agent leaves open, passing them what +/// it could pass a deployed runnable's inputs. An input the agent fills is part of what its author +/// wrote, and the step's binding would replace it at run time. Every tool sharing an id is +/// checked, as the overlay binds them all. +pub fn check_bound_agent_inputs_are_open( + agent: &str, + tools: &[AgentTool], + bound_inputs: &[(String, Vec)], +) -> Result<(), Error> { + for (tool_id, keys) in bound_inputs { + for tool in tools.iter().filter(|t| &t.id == tool_id) { + check_tool_inputs_are_open(agent, tool_id, &tool.value, keys)?; + } + } + Ok(()) +} + +fn check_tool_inputs_are_open( + agent: &str, + tool_id: &str, + value: &ToolValue, + keys: &[String], +) -> Result<(), Error> { + let ToolValue::FlowModule(value) = value else { + return Ok(()); + }; + let input_transforms = match value { + FlowModuleValue::Script { input_transforms, .. } + | FlowModuleValue::RawScript { input_transforms, .. } + | FlowModuleValue::FlowScript { input_transforms, .. } + | FlowModuleValue::AIAgent { input_transforms, .. } + | FlowModuleValue::AIDecision { input_transforms, .. } => input_transforms, + // Fail closed on any other kind, as the worker's `overlay_tool_inputs` skips them. + _ => { + return Err(Error::PermissionDenied(format!( + "Tool {tool_id} of agent {agent} takes no inputs a builder can set" + ))) + } + }; + match keys + .iter() + .find(|k| input_transforms.get(*k).is_some_and(|t| t.is_completed())) + { + Some(key) => Err(Error::PermissionDenied(format!( + "Input {key} of tool {tool_id} is set by agent {agent}, so a builder cannot \ + change it. Bind only the inputs the agent leaves to the model." + ))), + None => Ok(()), + } } fn check_module_is_composition_only( @@ -343,12 +402,20 @@ fn check_module_value_is_composition_only( FlowModuleValue::BranchAll { branches, .. } => { check_branches_are_composition_only(branches, id, refs)? } - FlowModuleValue::AIAgent { tools, tag, agent, .. } => { - // A linked agent resolves its tools from an `ai_agent` resource at run time, and - // operators may write resources, so those tools are outside this check: the list can - // be swapped for a raw script after the flow is deployed. - if agent.is_some() { - return refuse("links an AI agent resource, whose tools live outside the flow"); + FlowModuleValue::AIAgent { tools, tag, agent, tool_inputs, .. } => { + // A linked agent's tools are resolved from its resource at run time, outside this + // walk. That is safe only because an operator's every write of an agent passes this + // same check (`validate_operator_agent`), as a developer's agent is code they wrote. + if let Some(agent) = agent { + let path = agent + .trim_start_matches("$res:") + .trim_start_matches("res://"); + let bound_inputs = tool_inputs + .iter() + .map(|(tool, inputs)| (tool.clone(), inputs.keys().cloned().collect())) + .collect(); + refs.agents + .push(LinkedAgent { path: path.to_string(), bound_inputs }); } push_tag(tag); for tool in tools { @@ -477,15 +544,48 @@ mod tests { #[test] fn composition_check_rejects_code_reachable_through_an_ai_agent() { - for value in [ - serde_json::json!({"modules": [{"id": "a", "value": {"type": "aiagent", - "input_transforms": {}, "tools": [{"id": "t", "value": {"tool_type": "flowmodule", - "type": "rawscript", "content": "x", "language": "bun"}}]}}]}), - serde_json::json!({"modules": [{"id": "a", "value": {"type": "aiagent", - "input_transforms": {}, "tools": [], "agent": "$res:f/x/agent"}}]}), - ] { - assert!(check_flow_is_composition_only(&flow(value)).is_err()); - } + let value = serde_json::json!({"modules": [{"id": "a", "value": {"type": "aiagent", + "input_transforms": {}, "tools": [{"id": "t", "value": {"tool_type": "flowmodule", + "type": "rawscript", "content": "x", "language": "bun"}}]}}]}); + assert!(check_flow_is_composition_only(&flow(value)).is_err()); + } + + /// A builder may link only an agent they can read, which the walk cannot know: it has to + /// surface the path for the caller to check. + #[test] + fn composition_check_reports_linked_agents() { + let refs = check_flow_is_composition_only(&flow(serde_json::json!({"modules": [{ + "id": "a", "value": {"type": "aiagent", "input_transforms": {}, "tools": [], + "agent": "$res:f/x/agent", "tool_inputs": {"t": {}}}}]}))) + .unwrap(); + assert_eq!(refs.agents[0].path, "f/x/agent"); + assert_eq!(refs.agents[0].bound_inputs, vec![("t".to_string(), vec![])]); + } + + #[test] + fn bound_agent_inputs_must_be_left_to_the_model() { + // Two tools share the id: the overlay binds both, so the second's `query` counts. + let tools: Vec = serde_json::from_value(serde_json::json!([ + {"id": "t", "value": {"tool_type": "flowmodule", "type": "rawscript", "content": "x", + "language": "bun", "input_transforms": {}}}, + {"id": "t", "value": {"tool_type": "flowmodule", "type": "rawscript", "content": "x", + "language": "bun", "input_transforms": { + "query": {"type": "static", "value": "SELECT 1"}, + "limit": {"type": "ai"}, + "note": {"type": "static", "value": null}}}}])) + .unwrap(); + let bind = |keys: &[&str]| { + check_bound_agent_inputs_are_open( + "f/x/agent", + &tools, + &[( + "t".to_string(), + keys.iter().map(|k| k.to_string()).collect(), + )], + ) + }; + assert!(bind(&["limit", "note", "absent"]).is_ok()); + assert!(bind(&["limit", "query"]).is_err()); } #[test] diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index a384351911..5aa8823012 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -2489,6 +2489,9 @@ async fn update_resource_value( /// `run_on_behalf_of` is set: then the writer's own, unless one allowed to keep the one the value /// names asks to, and a folder's default for a new agent. The value is written by anyone who can /// write the agent, so the key it arrives with is only a request. +/// +/// Every write of an agent passes here, so this is also where an operator's is held to the +/// composed-flow rules: a flow step linking the agent runs its tools unchecked. async fn resolve_agent_on_behalf_of( tx: &mut Transaction<'_, Postgres>, authed: &ApiAuthed, @@ -2499,6 +2502,9 @@ async fn resolve_agent_on_behalf_of( preserve: bool, created: bool, ) -> Result<()> { + if authed.is_operator { + windmill_api_auth::composed::validate_operator_agent(value, authed, db, tx, w_id).await?; + } let Some(obj) = value.as_object_mut() else { return Ok(()); }; diff --git a/backend/windmill-types/src/flows.rs b/backend/windmill-types/src/flows.rs index 890318b8aa..59f06ae4e9 100644 --- a/backend/windmill-types/src/flows.rs +++ b/backend/windmill-types/src/flows.rs @@ -843,6 +843,19 @@ impl InputTransform { pub fn new_javascript_expr(expr: &str) -> InputTransform { InputTransform::Javascript { expr: expr.to_owned() } } + + /// Whether this transform fills its input. On an agent tool, an input it does not fill is + /// left to the model, which sees only those. + pub fn is_completed(&self) -> bool { + match self { + InputTransform::Static { value } => { + let val = value.get().trim(); + !val.is_empty() && val != "null" + } + InputTransform::Javascript { expr } => !expr.trim().is_empty(), + InputTransform::Ai => false, + } + } } impl TryFrom for InputTransform { diff --git a/backend/windmill-worker/src/ai/tools.rs b/backend/windmill-worker/src/ai/tools.rs index 01b90922ff..35075566b7 100644 --- a/backend/windmill-worker/src/ai/tools.rs +++ b/backend/windmill-worker/src/ai/tools.rs @@ -1,8 +1,8 @@ use crate::ai::stream_event_processor::StreamEventProcessor; use crate::ai::utils::{ add_message_to_conversation, execute_mcp_tool, get_step_name_from_flow, - is_completed_input_transform, update_flow_status_module_with_actions, - update_flow_status_module_with_actions_success, FlowContext, + update_flow_status_module_with_actions, update_flow_status_module_with_actions_success, + FlowContext, }; use crate::common::{get_root_job_id, OccupancyMetrics}; use crate::result_processor::handle_non_flow_job_error; @@ -444,7 +444,7 @@ async fn enqueue_windmill_tool( // Evaluate each input transform and merge with AI-provided args for (key, transform) in input_transforms.iter() { // We skip static empty / null values, those are the one the AI will fill in - if !is_completed_input_transform(transform) { + if !transform.is_completed() { continue; } let result = evaluate_input_transform::>( diff --git a/backend/windmill-worker/src/ai/utils.rs b/backend/windmill-worker/src/ai/utils.rs index 44513c806e..ccf2e0ef88 100644 --- a/backend/windmill-worker/src/ai/utils.rs +++ b/backend/windmill-worker/src/ai/utils.rs @@ -62,17 +62,6 @@ pub async fn parse_raw_script_schema( Ok(to_raw_value(&schema)) } -pub fn is_completed_input_transform(transform: &InputTransform) -> bool { - match transform { - InputTransform::Static { value } => { - let val = value.get().trim(); - !val.is_empty() && val != "null" - } - InputTransform::Javascript { expr } => !expr.trim().is_empty(), - InputTransform::Ai => false, - } -} - /// Filters out properties from a JSON schema that have completed input transforms. /// This allows AI agents to only see and fill parameters that don't have user-configured values. pub fn filter_schema_by_input_transforms( @@ -88,7 +77,7 @@ pub fn filter_schema_by_input_transforms( let keys_to_remove: HashSet = input_transforms .iter() .filter_map(|(key, transform)| { - let is_completed = is_completed_input_transform(transform); + let is_completed = transform.is_completed(); if is_completed { Some(key.clone()) } else { @@ -779,7 +768,12 @@ mod tests { .unwrap(); let preset = ["a", "c", "f"] .iter() - .map(|k| (k.to_string(), InputTransform::Static { value: to_raw_value(&1) })) + .map(|k| { + ( + k.to_string(), + InputTransform::Static { value: to_raw_value(&1) }, + ) + }) .collect(); let filtered = filter_schema_by_input_transforms(schema, &preset).unwrap(); diff --git a/backend/windmill-worker/src/ai_executor.rs b/backend/windmill-worker/src/ai_executor.rs index 6456a85bdf..bf5c3e4f9f 100644 --- a/backend/windmill-worker/src/ai_executor.rs +++ b/backend/windmill-worker/src/ai_executor.rs @@ -467,14 +467,11 @@ async fn find_ai_agent_tool_module_in_parent_agent( .trim_start_matches("$res:") .trim_start_matches("res://"); // Definitions only: resolving their defaults here would hit the same inaccessible resources. - let resource_value = client - .get_resource_value::(agent_path) - .await - .map_err(|e| { - Error::internal_err(format!( - "failed to load ai_agent resource {agent_path}: {e}" - )) - })?; + let resource_value = client.get_agent_value(agent_path).await.map_err(|e| { + Error::internal_err(format!( + "failed to load ai_agent resource {agent_path}: {e}" + )) + })?; match resource_value { serde_json::Value::Object(mut map) => match map.remove("tools") { Some(t) => serde_json::from_value::>(t).map_err(|e| { @@ -819,14 +816,11 @@ pub async fn handle_ai_agent_job( // Read raw and interpolate only the brain below. Interpolating the whole resource would also // resolve each tool's default `$res:`/`$var:`, which a host flow may be overriding and which // may be unreadable to whoever runs this flow — an unused tool could then fail the agent. - let resource_value = client - .get_resource_value::(agent_path) - .await - .map_err(|e| { - Error::internal_err(format!( - "failed to load ai_agent resource {agent_path}: {e}" - )) - })?; + let resource_value = client.get_agent_value(agent_path).await.map_err(|e| { + Error::internal_err(format!( + "failed to load ai_agent resource {agent_path}: {e}" + )) + })?; let mut config = match resource_value { serde_json::Value::Object(map) => map, _ => { diff --git a/docs/operator-builder-rights.md b/docs/operator-builder-rights.md index 8b99401d32..d4dc42b2d3 100644 --- a/docs/operator-builder-rights.md +++ b/docs/operator-builder-rights.md @@ -1,8 +1,8 @@ # Operator builder rights Two workspace settings, `operator_settings.builder_flows` and `operator_settings.builder_apps`, -that let every operator of that workspace compose flows and full-code apps out of runnables that -already exist. Neither lets them author backend code or run arbitrary code on a worker, the +that let every operator of that workspace compose flows (and AI agents, under the flow right) and +full-code apps out of runnables that already exist. Neither lets them author backend code or run arbitrary code on a worker, the boundary the operator role draws. The app right does let them write the app's frontend code, which runs in the viewer's browser and is why that right rests on sandbox isolation. @@ -32,13 +32,24 @@ anything that carries code. Three of its rules exist because the obvious walk mi past it. - **An AI agent step's `tools`.** `ToolValue::FlowModule` wraps a whole `FlowModuleValue`, so a tool can be a raw script. -- **An AI agent step's `agent` link.** A linked agent resolves its tools from an `ai_agent` - resource at run time, and operators may write resources, so the tool list is outside this check - and can be swapped for a raw script after the flow is approved. - It also returns what a value-only walk cannot authorize, for the caller to check against its own permissions: +- **every agent a step links**. A linked agent resolves its tools from its `ai_agent` resource at + run time, outside this walk, so the link is allowed only to an agent the builder can read. That + is safe because of the agent rule below: an agent's tools are either a developer's code or + passed this same check when an operator saved them. Two things keep it safe: + - The step's `tool_inputs` replace a tool's inputs at run time, including the ones the agent's + author set. A builder's step may bind only the inputs the agent leaves open + (`check_bound_agent_inputs_are_open`, on `InputTransform::is_completed`), and the flow editor + lets a builder edit only those, showing the rest read-only. What it binds there, a `$var:` or + a JavaScript expression included, is what its own steps may already pass a deployed runnable; an input the author set + stays theirs. The check runs on the flow's write, so a tool or input the agent gains later is + open to a binding written before it, like the retyped path below. + - The worker refuses a linked path whose resource is no longer an `ai_agent` + (`get_agent_value`). Only writes of an agent are checked, so a path retyped, or recreated as + another type, after the link was approved would otherwise run whatever `tools` it now holds. + - **the worker tags the steps pin**, or a builder routes a job onto a privileged worker group; - **every runnable a step references**. `script_to_payload` resolves a step's path with the root DB handle (`db_authed = None`) and returns the referenced runnable's `on_behalf_of`, which @@ -61,6 +72,20 @@ Call it on every write **and** every preview: `run_preview_flow_job` and it the way to run what the write path refuses. A flow draft goes through `validate_operator_flow` too: a developer who loads a builder's draft in the editor runs its code as themselves. +## Agents + +An agent is an `ai_agent` resource, and operators may write resources, so the `flows` capability +is also the right to build agents. Without it a restricted role writes no agent at all. Its tools run in the +agent's own runs, which take only inputs and run what is stored, and in every flow step linking +it. So `validate_operator_agent` holds an operator's agent to the composed-flow rules by checking +its tools as the tools of a one-step flow. It is called from `resolve_agent_on_behalf_of`, which +every write of an agent's value passes through: create, update, retype, update-value and version +restore. An operator's resource draft is checked the same way when it names `ai_agent` **or** an +agent is deployed at its path, whatever type the draft names: deploying a draft from the resource +editor keeps the row's type. A draft saved before an agent is created at its path is not +re-checked when someone else deploys it. A new route that writes an agent's value must go through +that function. + The same reasoning applies to a builder-authored app, with one extra step. `execute_component` resolves the runnable it runs on the root handle, so `validate_operator_composed_app` checks every referenced path under the caller's RLS and refuses hub ones. For a script it checks the version a diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md index 953b4c023c..9ce3294c54 100644 --- a/docs/workspace-roles.md +++ b/docs/workspace-roles.md @@ -16,7 +16,7 @@ code is `windmill_common::roles`. | Capability | Values | Enforced | |---|---|---| | `code` | bool | yes: scripts, previews, dependency jobs, dynamic selects, resolving jobs, data table migrations, eval datasets | -| `flows` | `none` / `compose` / `full` | yes | +| `flows` | `none` / `compose` / `full` | yes; also AI agents, whose tools are checked as composed steps | | `apps` | `none` / `compose` / `full` | yes; low-code apps and worker-built apps need `full` | | `manage_schedules`, `manage_triggers` | bool | yes, see `docs/operator-write-rights.md` | | `visibility.*` | bool per page | no, UI only | diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 66af4ab332..24273cece4 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -1656,7 +1656,7 @@ ${ ' To make something recur, they can schedule a deployed script or flow themselves; only when none does the job is there something to ask an admin for, and it is that script.' )} When you decline something, give the reason stated here and keep to it.${when( buildsFlows, - '\n\nFlows are the exception: this workspace lets them compose flows out of scripts and flows that are already deployed. Write flow drafts with write_flow and patch_flow_json, using only steps that call a deployed script or flow by path. The server refuses inline code anywhere in the flow, so never add a rawscript step or inline code; when the flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.' + '\n\nFlows are the exception: this workspace lets them compose flows out of scripts and flows that are already deployed. Write flow drafts with write_flow and patch_flow_json, using only steps that call a deployed script or flow by path. The server refuses inline code anywhere in the flow, so never add a rawscript step or inline code; when the flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An AI agent step may link a saved agent they can read, which runs its tools as the agent defines them. Its `tool_inputs` may only fill tool inputs the agent leaves for the AI to fill: the server refuses a step that changes an input the agent sets.' )}${when( buildsApps, `\n\nRaw apps are ${buildsFlows ? 'an exception too' : 'the exception'}: this workspace lets them build raw apps whose backend calls scripts and flows that are already deployed. Call get_instructions with subject "app" first, then write app drafts with init_app and the app file and runnable tools, making every backend runnable a path runnable to a deployed script or flow. The server refuses inline and hub runnables, so never write one; when the app needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An app this user deploys always runs sandboxed, and runs its runnables as the user who deployed it: turning the sandbox off or running them as the viewer is refused. If asked, say operators cannot, because the app's code would then run with the permissions of whoever opens it.` @@ -1707,8 +1707,12 @@ ${findItemsRule}${deployRule}${when(canWriteDraft, `\n${instructionsRule}`)}${wh ${external ? 'More rules:' : `Rules:${draftsOnlyRule}\n${findItemsRule}`} ${groupMembershipRule}- Listings and reads return only what this user can see: items in folders they cannot read are hidden from you both. When an item the user names is missing, say it is not among what they can see and may be in a folder they cannot read, where someone with access can run it — never state that it does not exist or is not deployed. - An agent, as the Agents page lists it, is a resource of type \`ai_agent\`: read it with read_workspace_item type "resource".${when( - canDraftResources, + // An agent draft is a resource draft that the server checks under the flow builder right. + canDraftResources && canWriteFlowDraft, " You may draft a change to an agent, but never deploy or rename one here: the user reviews and deploys it from the agent's page, `/agents/edit/`, so point them there." + )}${when( + buildsFlows, + ' Its tools, like flow steps, may only reference deployed scripts and flows by path: the server refuses inline code and hub scripts.' )}${when( !external, ` diff --git a/frontend/src/lib/components/flows/agentActions.ts b/frontend/src/lib/components/flows/agentActions.ts index f80a6e4343..b99229d4d3 100644 --- a/frontend/src/lib/components/flows/agentActions.ts +++ b/frontend/src/lib/components/flows/agentActions.ts @@ -25,7 +25,7 @@ export function agentMenuItems(agent: { /** Never deployed: no resource yet to hold permissions or to deploy onward. */ draftOnly?: boolean wsSpecific?: boolean - /** Hides what a role that cannot code has no page for, as on a flow's menu. */ + /** Hides what a role that cannot code has no page or right for, as on a flow's menu. */ noCode?: boolean /** Undefined until loaded, when nothing is offered for deploy. */ deployUiSettings: WorkspaceDeployUISettings | undefined @@ -35,6 +35,7 @@ export function agentMenuItems(agent: { onDelete: (event?: MouseEvent) => void }): Item[] { const deployable = + !agent.noCode && !agent.wsSpecific && !agent.draftOnly && isDeployable('resource', agent.path, agent.deployUiSettings) diff --git a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte index f3ee578050..7fde7a56f4 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte @@ -35,6 +35,7 @@ import PathEditPopover from '$lib/components/PathEditPopover.svelte' import { emptyString } from '$lib/utils' import Tooltip from '$lib/components/Tooltip.svelte' + import { useEditRights } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() @@ -134,9 +135,17 @@ let draftOnly = $derived(draft?.noDeployed ?? false) // Evals run against the deployed agent, and a draft-only one has none: the backend's // `require_agent` would reject every run. Evaluating is authoring, so it is for those who can - // edit the agent. Unknown until the load answers, and warming the pane loads it. + // edit the agent, except a role without `code`: eval datasets are refused to it + // (`check_role_can_code`) whatever its flows right. Unknown until the load answers, and warming + // the pane loads it. + const editRights = useEditRights(() => ws) let canEvaluate = $derived( - draft != undefined && !draft.loading && !draftOnly && !readOnly && !refused + draft != undefined && + !draft.loading && + !draftOnly && + !readOnly && + !refused && + editRights.capabilities.code ) // The draft's path, so a rename shows where it is typed — including a never-deployed agent, // stored at a minted `draft_` path and named by the path its first deploy will create, diff --git a/frontend/src/lib/components/flows/content/AgentSettings.svelte b/frontend/src/lib/components/flows/content/AgentSettings.svelte index 9d02183812..5ed0799df3 100644 --- a/frontend/src/lib/components/flows/content/AgentSettings.svelte +++ b/frontend/src/lib/components/flows/content/AgentSettings.svelte @@ -11,6 +11,7 @@ import AgentSlackSettings from './AgentSlackSettings.svelte' import { WorkspaceService } from '$lib/gen' import { userStore } from '$lib/stores' + import { useActingUser } from '$lib/actingUser.svelte' import type { AgentDraftHandle, AgentRunAs } from '../agentDraft.svelte' /** An agent's own settings, laid out as the top of the resource editor: what it is saved as @@ -27,6 +28,7 @@ } let { draft, path, workspace, error = $bindable(), onRunAsChange = undefined }: Props = $props() + const acting = useActingUser(() => workspace) let readOnly = $derived(!draft.canWrite) // As the deploy resolves it: the deployer, unless one who may keep another picked them. @@ -130,8 +132,11 @@ {/if}
    -
    - -
    + + {#if acting.current?.operator === false} +
    + +
    + {/if}
    {/if} diff --git a/frontend/src/lib/components/flows/content/AgentToolBindings.svelte b/frontend/src/lib/components/flows/content/AgentToolBindings.svelte index dc3fad1ea7..b3c956b7fc 100644 --- a/frontend/src/lib/components/flows/content/AgentToolBindings.svelte +++ b/frontend/src/lib/components/flows/content/AgentToolBindings.svelte @@ -4,6 +4,7 @@ import type { InputTransform, ScriptLang } from '$lib/gen' import InputTransformSchemaForm from '$lib/components/InputTransformSchemaForm.svelte' import HighlightCode from '$lib/components/HighlightCode.svelte' + import InputTransformsViewer from '$lib/components/InputTransformsViewer.svelte' import { Button } from '$lib/components/common' import { ChevronDown, ChevronRight, Wrench } from 'lucide-svelte' import type { PickableProperties } from '../previousResults' @@ -16,6 +17,7 @@ } from '../agentToolUtils' import { flowLocalAgentSchema, toolInputOverrides } from '../agentResourceUtils' import { loadSchemaFromModule } from '../flowInfers' + import { useRoleCapabilities } from '$lib/operatorWriteRights' let { tools, @@ -35,6 +37,42 @@ } = $props() let flowTools = $derived(tools.filter(isFlowModuleTool)) + const roleCaps = useRoleCapabilities() + // The server checks bindings only below `full` (`check_operator_can_build`). + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') + + /** Mirrors the backend's `InputTransform::is_completed`: an input the agent fills is hidden from + * the model, and the server refuses a builder's binding of it. */ + function isSetByAgent(transform: InputTransform | undefined): boolean { + if (transform?.type === 'static') { + return transform.value !== undefined && transform.value !== null + } + return transform?.type === 'javascript' && !!transform.expr?.trim() + } + + /** A builder binds only the inputs the agent leaves to the model. */ + function shownSchema(tool: FlowModuleTool): any { + const schema = schemas[tool.id] + if (!composeOnlyFlows || !schema?.properties) return schema + const base = baseInputs(tool) + const keep = Object.keys(schema.properties).filter((k) => !isSetByAgent(base[k])) + return { + ...schema, + properties: Object.fromEntries(keep.map((k) => [k, schema.properties[k]])), + required: (schema.required ?? []).filter((k: string) => keep.includes(k)) + } + } + + /** The inputs `shownSchema` hides, shown read-only so the tool code reads in context. */ + function agentSetInputs(tool: FlowModuleTool): Record { + if (!composeOnlyFlows) return {} + const base = baseInputs(tool) + return Object.fromEntries( + Object.keys(schemas[tool.id]?.properties ?? {}) + .filter((k) => isSetByAgent(base[k])) + .map((k) => [k, base[k]]) + ) + } function baseInputs(tool: FlowModuleTool): Record { return ((tool.value as { input_transforms?: Record }) @@ -182,7 +220,7 @@ {:else if schemas[tool.id] !== undefined && localArgs[tool.id] !== undefined} + {@const setInputs = agentSetInputs(tool)} + {#if Object.keys(setInputs).length > 0} +
    + Static inputs + +
    + {/if} {:else}
    Loading inputs...
    {/if} diff --git a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte index 2b08653d28..b4228ea0a3 100644 --- a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte +++ b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte @@ -84,19 +84,20 @@ let savedAgentsLoading = $state(false) let savedAgentsWs: string | undefined = undefined async function loadSavedAgents() { - // The backend refuses a linked agent in a builder's flow. - if (!ws || savedAgentsWs === ws || composeOnlyFlows) { + const requested = ws + if (!requested || savedAgentsWs === requested) { return } savedAgentsLoading = true try { const rs = await ResourceService.listResource({ - workspace: ws, + workspace: requested, resourceType: 'ai_agent', perPage: 1000 }) + if (requested !== ws) return savedAgents = rs.map((r) => ({ path: r.path, description: r.description })) - savedAgentsWs = ws + savedAgentsWs = requested } catch { savedAgents = [] } finally { @@ -386,9 +387,7 @@ ↵ {/if} - {#if composeOnlyFlows} - - {:else if savedAgentsLoading} + {#if savedAgentsLoading}
    Loading saved agents
    diff --git a/frontend/src/lib/components/settings/RoleCapabilitiesEditor.svelte b/frontend/src/lib/components/settings/RoleCapabilitiesEditor.svelte index e9823aecde..a9fc0e9911 100644 --- a/frontend/src/lib/components/settings/RoleCapabilitiesEditor.svelte +++ b/frontend/src/lib/components/settings/RoleCapabilitiesEditor.svelte @@ -93,8 +93,9 @@ }, { key: 'flows', - label: 'Flows', - description: 'Compose assembles deployed scripts and flows without code of their own.' + label: 'Flows and AI agents', + description: + 'Compose builds flows and AI agents out of deployed scripts and flows, without code of their own.' }, { key: 'apps', diff --git a/frontend/src/lib/editRights.test.ts b/frontend/src/lib/editRights.test.ts index fa3366a284..ef344d7d6d 100644 --- a/frontend/src/lib/editRights.test.ts +++ b/frontend/src/lib/editRights.test.ts @@ -28,9 +28,12 @@ const role = (overrides: Partial): RoleCapabilities => ({ }) describe('edit rights', () => { - it('lets a compose-only flow role author flows and nothing else', () => { + it('lets a compose-only flow role author flows and agents and nothing else', () => { const builder = role({ flows: 'compose' }) expect(roleCanAuthor('flow', builder)).toBe(true) + expect(roleCanAuthor('agent', builder)).toBe(true) + expect(roleCanDraft('agent', builder)).toBe(true) + expect(roleCanAuthor('agent', role({ apps: 'compose' }))).toBe(false) expect(roleCanAuthor('script', builder)).toBe(false) expect(roleCanAuthor('raw_app', builder)).toBe(false) expect(roleCanDraft('raw_app', builder)).toBe(false) diff --git a/frontend/src/lib/editRights.ts b/frontend/src/lib/editRights.ts index 48ec6c3ee2..025b77a157 100644 --- a/frontend/src/lib/editRights.ts +++ b/frontend/src/lib/editRights.ts @@ -30,8 +30,9 @@ export type EditKind = * Whether a role with `caps` lets its member author items of `kind` (create, edit, deploy or * delete one): the role half of every check against the item handlers. Saving a draft is * `roleCanDraft`'s rule, and which items they may write is `canEditItem`'s other half. - * - code (scripts, agents, pipelines): `code`; - * - flows and full-code apps: `compose` or above (`check_operator_can_build`); + * - code (scripts, pipelines): `code`; + * - flows, agents and full-code apps: `compose` or above (`check_operator_can_build`). An + * agent's tools are checked as a composed flow's steps are, under the flows right; * - low-code apps: `full` apps only (apps.rs `require_full_apps`); * - schedules and triggers: the matching manage right; * - resources, variables and groups: always, their permissions alone decide. @@ -39,6 +40,7 @@ export type EditKind = export function roleCanAuthor(kind: EditKind, caps: RoleCapabilities): boolean { switch (kind) { case 'flow': + case 'agent': return caps.flows !== 'none' case 'raw_app': return caps.apps !== 'none' diff --git a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte index 0fcb6174e2..f05203e231 100644 --- a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte @@ -24,7 +24,8 @@ import AgentHistory from '$lib/components/flows/AgentHistory.svelte' import { getDeployUiSettings } from '$lib/components/home/deploy_ui' import { recentItems } from '$lib/components/home/recentItems.svelte' - import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' + import { userStore, workspaceStore } from '$lib/stores' + import { useEditRights } from '$lib/operatorWriteRights' import { sendUserToast } from '$lib/toast' /** @@ -41,9 +42,10 @@ let testPane = $derived(host?.testPaneHandle()) let config = $derived(agent?.state?.args) let chatAvailable = $derived(keepsManagedMemory(config?.memory)) - let canEdit = $derived( - config != undefined && (agent?.canWrite ?? false) && $roleCapabilities.code - ) + const editRights = useEditRights() + let canAuthor = $derived(editRights.roleCanAuthor('agent')) + let canCode = $derived(editRights.capabilities.code) + let canEdit = $derived(config != undefined && (agent?.canWrite ?? false) && canAuthor) // Recorded once the agent is in: a path with nothing deployed never loads one. let loaded = $derived(config != undefined) @@ -100,12 +102,13 @@ () => ws, () => getDeployUiSettings() ) - // A role that cannot code gets no menu, as on a flow's or a script's page. + // A role that cannot build agents gets no menu, as on a flow's page. let menuItems = $derived( - config != undefined && $roleCapabilities.code + config != undefined && canAuthor ? agentMenuItems({ path, canWrite: canEdit, + noCode: !canCode, wsSpecific: agent?.state?.wsSpecific, deployUiSettings: deployUiSettings.current, onPermissions: () => shareModal?.openDrawer?.(path, 'resource'), @@ -161,8 +164,9 @@ } : undefined} mainButtons={[ - // Evaluating an agent builds datasets and runs against it: authoring, as editing is. - ...(canEdit + // Evaluating an agent builds datasets and runs against it: authoring, as editing is, and + // eval datasets are refused to a role without `code` whatever its flows right. + ...(canEdit && canCode ? [ { label: 'Evals', @@ -173,7 +177,11 @@ title: 'Run this agent against a dataset of cases', onClick: () => evalsModal?.openModal() } - }, + } + ] + : []), + ...(canEdit + ? [ { label: 'Edit', buttonProps: { From ebeea514926f60295f3f11f516f4ccda3448f829 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Fri, 23 Oct 2026 15:06:37 +0200 Subject: [PATCH 063/101] feat: composer pills that teach Windmill from the workspace (#11889) * feat: open empty ai sessions with the home build-with-ai composer * feat: vertically center the empty session composer * fix: drop the stray indent on the session composer's rotating placeholder * fix: give the starter composer a stable accessible name * feat: pick workspace, fork and permission mode from the home composer * fix: hand off the workspace home displays, not only an explicit pick * feat: drop the starter prompt chips from the empty session * feat: home and empty ai sessions share one session composer * fix: keep session draft attachments across home and session page Co-Authored-By: Claude Opus 5.5 (1M context) * fix: drop superseded home ai-hidden responses Co-Authored-By: Claude Opus 5.5 (1M context) * fix: load home session starter lazily to keep monaco out of home Co-Authored-By: Claude Opus 5.5 (1M context) * feat: redesign home composer and items list Co-Authored-By: Claude Opus 5.5 (1M context) * feat: align the composer chat icon, share the folder row, add a home preview page Co-Authored-By: Claude Opus 5.5 (1M context) * refactor: drop home tech debt, fix phone layout and keyboard access, remove the home preview page Co-Authored-By: Claude Opus 5.5 (1M context) * feat: suggest composer prompts from workspace signals Co-Authored-By: Claude Opus 5.5 (1M context) * fix: pass dev page placeholders through inputProps, key settled signals by role Co-Authored-By: Claude Opus 5.5 (1M context) * perf: read filter chip positions before hiding any in clampRows Co-Authored-By: Claude Opus 5.5 (1M context) * fix: scope composer signal caches to the account, drop stale workspace answers Co-Authored-By: Claude Opus 5.5 (1M context) * chore: update ee-repo-ref to dd0c7087f9b2453260f3d73b0d589042b4393a1d This commit updates the EE repository reference after PR #900 was merged in windmill-ee-private. Previous ee-repo-ref: e922599943c472a6d0f736f629ae04081f866686 New ee-repo-ref: dd0c7087f9b2453260f3d73b0d589042b4393a1d Automated by sync-ee-ref workflow. * chore: update ee-repo-ref to dd0c7087f9b2453260f3d73b0d589042b4393a1d This commit updates the EE repository reference after PR #900 was merged in windmill-ee-private. Previous ee-repo-ref: e922599943c472a6d0f736f629ae04081f866686 New ee-repo-ref: dd0c7087f9b2453260f3d73b0d589042b4393a1d Automated by sync-ee-ref workflow. * feat: name workspace items and connections in composer pills Co-Authored-By: Claude Opus 5.5 (1M context) * feat: teach one Windmill concept per composer pill from the workspace Co-Authored-By: Claude Opus 5.5 (1M context) * fix: drop the failed-deploy pill, which reports a run outcome Co-Authored-By: Claude Opus 5.5 (1M context) * fix: read favorites from the workspace's own item list Co-Authored-By: Claude Opus 5.5 (1M context) * chore: regenerate mcp session guidance for the data table row Co-Authored-By: Claude Opus 5.5 (1M context) * fix: address cubic review of the composer signals and data table guidance Co-Authored-By: Claude Opus 5.5 (1M context) * test: make the billing fixture's receipt step send what its summary says Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep loaded item kinds and drop stale loads in the composer playground Co-Authored-By: Claude Opus 5.5 (1M context) * fix: preview an instance admin who is a plain member in the composer playground Co-Authored-By: Claude Opus 5.5 (1M context) * fix: scope the enterprise note to external_instance and check receipt sends Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Diego Imbert Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: windmill-internal-app[bot] --- ai_evals/adapters/frontend/mockBackend.ts | 326 ++++++++- .../adapters/frontend/vitestAdapter.test.ts | 86 ++- ai_evals/cases/global.yaml | 623 ++++++++++++++++++ .../initial/composer_connected_workspace.json | 313 +++++++++ .../initial/composer_fresh_workspace.json | 22 + .../global/initial/composer_incidents.json | 83 +++ .../src/mcp/session/gen/instructions.json | 2 +- .../src/mcp/session/gen/tools.json | 2 +- cli/src/guidance/skills.gen.ts | 2 +- .../chat/starter/composerSuggestions.test.ts | 110 ++++ .../chat/starter/composerSuggestions.ts | 387 +++++++++++ .../chat/starter/starterPrompts.svelte.ts | 324 ++++++--- .../chat/starter/starterPrompts.test.ts | 73 ++ .../src/lib/components/home/HomeAIChat.svelte | 9 +- .../dev/composer-suggestions/+page.svelte | 364 ++++++++++ system_prompts/auto-generated/prompts.ts | 2 +- .../skills/workspace-settings/SKILL.md | 2 +- system_prompts/base/workspace-settings.md | 2 +- 18 files changed, 2601 insertions(+), 131 deletions(-) create mode 100644 ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json create mode 100644 ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json create mode 100644 ai_evals/fixtures/frontend/global/initial/composer_incidents.json create mode 100644 frontend/src/lib/components/copilot/chat/starter/composerSuggestions.test.ts create mode 100644 frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts create mode 100644 frontend/src/lib/components/copilot/chat/starter/starterPrompts.test.ts create mode 100644 frontend/src/routes/(root)/(logged)/dev/composer-suggestions/+page.svelte diff --git a/ai_evals/adapters/frontend/mockBackend.ts b/ai_evals/adapters/frontend/mockBackend.ts index 69398555f0..1de463690b 100644 --- a/ai_evals/adapters/frontend/mockBackend.ts +++ b/ai_evals/adapters/frontend/mockBackend.ts @@ -11,8 +11,13 @@ import type { ListableApp, ListableResource, ListableVariable, + Folder, + Group, + QueuedJob, Resource, - Script + Schedule, + Script, + WorkerPing } from '../../../frontend/src/lib/gen' import type { DataMetric, @@ -97,6 +102,14 @@ export interface BenchmarkWorkspaceResource { resource_type: string value?: Record description?: string + /** A database's tables, as `get_db_schema` reads them: schema, table, then column. */ + dbSchema?: Record>> +} + +export interface BenchmarkDbColumn { + type: string + required: boolean + default?: string } /** A resource type the instance holds. */ @@ -117,6 +130,48 @@ export interface BenchmarkWorkspaceJob { logs?: string args?: Record result?: unknown + /** Defaults to `completed`. `suspended` is a running flow parked on an approval step. */ + state?: 'completed' | 'queued' | 'running' | 'suspended' + tag?: string + schedulePath?: string + /** When the run was created, relative to the case start. Unset = now. */ + createdMinutesAgo?: number + /** Completed runs only: how long the run took. */ + durationMs?: number +} + +/** A worker of the instance, as `list_workers` reports it. */ +export interface BenchmarkWorkspaceWorker { + worker: string + worker_group: string + custom_tags?: string[] + lastPingSecondsAgo?: number + jobs_executed?: number +} + +/** A folder of the benchmark workspace, as `read_workspace_item` reads it. */ +export interface BenchmarkWorkspaceFolder { + name: string + summary?: string + owners?: string[] + /** Who else may use the folder, as `u/` or `g/`: `true` grants write. */ + extra_perms?: Record +} + +export interface BenchmarkWorkspaceGroup { + name: string + summary?: string + members?: string[] +} + +export interface BenchmarkWorkspaceSchedule { + path: string + /** Six-field cron. */ + schedule: string + script_path: string + is_flow?: boolean + enabled?: boolean + summary?: string } export interface BenchmarkWorkspaceRunnables { @@ -133,15 +188,28 @@ export interface BenchmarkWorkspaceRunnables { ducklakes?: string[] dataMetrics?: DataMetric[] jobs?: BenchmarkWorkspaceJob[] + /** The instance's workers. Unset falls through to the real backend's; `[]` is none. */ + workers?: BenchmarkWorkspaceWorker[] + schedules?: BenchmarkWorkspaceSchedule[] + folders?: BenchmarkWorkspaceFolder[] + groups?: BenchmarkWorkspaceGroup[] + /** The workspace settings document (`get_workspace_settings` reads it). */ + workspaceSettings?: Record } type BenchmarkCompletedJob = CompletedJob & { type: 'CompletedJob' } +type BenchmarkQueuedJob = QueuedJob & { type: 'QueuedJob' } const benchmarkWorkspaces = new Set() const benchmarkWorkspaceRunnables = new Map() // Keyed by `${workspace}::${jobId}` so concurrent attempts (or distinct cases) // can seed the same fixed job id without clobbering each other's entry. -const benchmarkJobs = new Map() +const benchmarkJobs = new Map< + string, + { workspace: string; job: BenchmarkCompletedJob | BenchmarkQueuedJob } +>() +// What set_workspace_settings applied, per workspace, so get_workspace_settings reads it back. +const benchmarkWorkspaceSettings = new Map>() function benchmarkJobKey(workspace: string, jobId: string): string { return `${workspace}::${jobId}` @@ -152,11 +220,12 @@ export function resetBenchmarkMockBackend(): void { benchmarkWorkspaceRunnables.clear() benchmarkJobs.clear() benchmarkDrafts.clear() + benchmarkWorkspaceSettings.clear() } // Stand-in for FolderService.createFolder so the global create_folder tool runs in -// memory instead of mutating the real backend. Folders aren't otherwise modelled -// (no folder-listing in evals), so this just echoes the created name. +// memory instead of mutating the real backend. It echoes the name without adding the +// folder to the fixture folders that `listBenchmarkFolders` reads. export function createBenchmarkFolder(_workspace: string, name: string): string { return name } @@ -180,6 +249,14 @@ export function registerBenchmarkWorkspaceRunnables( }) // Seed any fixture jobs so list_runs / get_run have data to return. for (const seed of runnables.jobs ?? []) { + const createdAt = + seed.createdMinutesAgo === undefined + ? undefined + : new Date(Date.now() - seed.createdMinutesAgo * 60_000).toISOString() + if (seed.state && seed.state !== 'completed') { + createBenchmarkQueuedJob(workspace, seed, createdAt) + continue + } createBenchmarkCompletedJob({ workspace, id: seed.id, @@ -190,14 +267,24 @@ export function registerBenchmarkWorkspaceRunnables( label: seed.label, logs: seed.logs, args: seed.args, - result: seed.result + result: seed.result, + tag: seed.tag, + schedulePath: seed.schedulePath, + createdAt, + durationMs: seed.durationMs }) } + if (runnables.workspaceSettings) { + benchmarkWorkspaceSettings.set(workspace, structuredClone(runnables.workspaceSettings)) + } else { + benchmarkWorkspaceSettings.delete(workspace) + } } export function unregisterBenchmarkWorkspace(workspace: string): void { benchmarkWorkspaces.delete(workspace) benchmarkWorkspaceRunnables.delete(workspace) + benchmarkWorkspaceSettings.delete(workspace) clearBenchmarkDrafts(workspace) for (const [jobId, entry] of benchmarkJobs.entries()) { if (entry.workspace === workspace) { @@ -389,6 +476,15 @@ export function queryBenchmarkResourceTypes( .slice(0, limit) } +/** The tables a fixture seeds for a database resource; `null` when it seeds none. */ +export function getBenchmarkDbSchemaSeed( + workspace: string, + path: string +): { resourceType: string; schema: NonNullable } | null { + const seed = benchmarkWorkspaceRunnables.get(workspace)?.resources?.find((r) => r.path === path) + return seed?.dbSchema ? { resourceType: seed.resource_type, schema: seed.dbSchema } : null +} + /** A seeded resource with its value, as `ResourceService.getResource` returns it. Covers both * seed kinds, so it agrees with `existsResource` and `listResource` — both of those report AI * providers too, and a case that lists resources and then reads one by path would otherwise get @@ -481,18 +577,24 @@ export function createBenchmarkCompletedJob(input: { id?: string createdBy?: string label?: string + tag?: string + schedulePath?: string + createdAt?: string + durationMs?: number }): string { const jobId = input.id ?? `benchmark-job-${randomUUID()}` - const now = new Date().toISOString() + const createdAt = input.createdAt ?? new Date().toISOString() + const durationMs = input.durationMs ?? 0 const job: BenchmarkCompletedJob = { type: 'CompletedJob', id: jobId, workspace_id: input.workspace, created_by: input.createdBy ?? 'ai-evals', - created_at: now, - started_at: now, - completed_at: now, - duration_ms: 0, + created_at: createdAt, + started_at: createdAt, + completed_at: new Date(Date.parse(createdAt) + durationMs).toISOString(), + duration_ms: durationMs, + schedule_path: input.schedulePath, success: input.success ?? true, script_path: input.scriptPath, script_hash: input.scriptHash, @@ -506,7 +608,7 @@ export function createBenchmarkCompletedJob(input: { is_skipped: false, email: 'ai-evals@local', visible_to_owner: true, - tag: 'benchmark', + tag: input.tag ?? 'benchmark', labels: input.label ? [input.label] : undefined } @@ -517,17 +619,58 @@ export function createBenchmarkCompletedJob(input: { return jobId } +/** A run still in the queue: waiting for a worker, running, or a flow parked on an + * approval step (running with a suspend outstanding, as the backend reports it). */ +function createBenchmarkQueuedJob( + workspace: string, + seed: BenchmarkWorkspaceJob, + createdAt = new Date().toISOString() +): string { + const jobId = seed.id ?? `benchmark-job-${randomUUID()}` + const started = seed.state === 'running' || seed.state === 'suspended' + const job: BenchmarkQueuedJob = { + type: 'QueuedJob', + id: jobId, + workspace_id: workspace, + created_by: seed.createdBy ?? 'ai-evals', + created_at: createdAt, + scheduled_for: createdAt, + started_at: started ? createdAt : undefined, + running: started, + suspend: seed.state === 'suspended' ? 1 : undefined, + script_path: seed.scriptPath, + schedule_path: seed.schedulePath, + args: seed.args, + logs: seed.logs, + canceled: false, + job_kind: seed.jobKind ?? 'script', + permissioned_as: 'u/ai-evals', + is_flow_step: false, + email: 'ai-evals@local', + visible_to_owner: true, + tag: seed.tag ?? 'benchmark' + } + benchmarkJobs.set(benchmarkJobKey(workspace, jobId), { workspace, job }) + return jobId +} + export function getBenchmarkCompletedJob( workspace: string, jobId: string ): BenchmarkCompletedJob | null { const entry = benchmarkJobs.get(benchmarkJobKey(workspace, jobId)) - if (!entry) { + if (!entry || entry.job.type !== 'CompletedJob') { return null } return structuredClone(entry.job) } +/** Any seeded run, finished or not, as `JobService.getJob` returns it. */ +export function getBenchmarkJob(workspace: string, jobId: string): Job | null { + const entry = benchmarkJobs.get(benchmarkJobKey(workspace, jobId)) + return entry ? (structuredClone(entry.job) as Job) : null +} + /** * List seeded/recorded jobs for a benchmark workspace, most recent first — * the shape `JobService.listJobs` returns. Returns `null` for a non-benchmark @@ -550,7 +693,7 @@ export function listBenchmarkJobs(workspace: string): Job[] | null { * "not found" error for an unknown id, matching the backend 404. */ export function getBenchmarkJobLogs(workspace: string, jobId: string): string { - const job = getBenchmarkCompletedJob(workspace, jobId) + const job = getBenchmarkJob(workspace, jobId) if (!job) { throw new Error(`Job Logs not found for "${jobId}"`) } @@ -562,7 +705,7 @@ export function getBenchmarkJobLogs(workspace: string, jobId: string): string { * tree. Fixture jobs are single runs with no steps, so only the root entry. */ export function getBenchmarkFlowAllResults(workspace: string, jobId: string) { - const job = getBenchmarkCompletedJob(workspace, jobId) + const job = getBenchmarkJob(workspace, jobId) if (!job) { throw new Error(`Job "${jobId}" not found in benchmark workspace`) } @@ -575,8 +718,9 @@ export function getBenchmarkFlowAllResults(workspace: string, jobId: string) { depth: 0, sibling_index: 1, sibling_count: 1, - status: job.success ? 'success' : 'failure', - success: job.success + ...('success' in job + ? { status: job.success ? 'success' : 'failure', success: job.success } + : { status: job.suspend ? 'suspended' : job.running ? 'running' : 'queued' }) } ], truncated: false, @@ -584,6 +728,156 @@ export function getBenchmarkFlowAllResults(workspace: string, jobId: string) { } } +// ============= Workers, schedules ============= + +/** Mirror `WorkerService.listWorkers`; `null` when no case seeded workers. Workers name no + * workspace, so this answers from whichever case seeded them: run cases whose worker seeds + * differ one at a time. */ +export function listBenchmarkWorkers(): WorkerPing[] | null { + let workers: BenchmarkWorkspaceWorker[] | undefined + for (const workspace of benchmarkWorkspaces) { + workers ??= benchmarkWorkspaceRunnables.get(workspace)?.workers + } + if (!workers) return null + return workers.map((w) => ({ + worker: w.worker, + worker_instance: `${w.worker}-instance`, + worker_group: w.worker_group, + custom_tags: w.custom_tags, + last_ping: w.lastPingSecondsAgo ?? 2, + started_at: BENCHMARK_TIMESTAMP, + ip: '10.0.0.1', + jobs_executed: w.jobs_executed ?? 0, + wm_version: 'benchmark' + })) +} + +function buildBenchmarkSchedule(workspace: string, s: BenchmarkWorkspaceSchedule): Schedule { + return { + path: s.path, + edited_by: 'benchmark', + edited_at: BENCHMARK_TIMESTAMP, + schedule: s.schedule, + timezone: 'Etc/UTC', + enabled: s.enabled ?? true, + script_path: s.script_path, + is_flow: s.is_flow ?? false, + extra_perms: {}, + email: 'ai-evals@local', + summary: s.summary, + workspace_id: workspace + } as unknown as Schedule +} + +export function listBenchmarkSchedules(workspace: string): Schedule[] { + return (benchmarkWorkspaceRunnables.get(workspace)?.schedules ?? []).map((s) => + buildBenchmarkSchedule(workspace, s) + ) +} + +export function getBenchmarkSchedule(workspace: string, path: string): Schedule | null { + const s = benchmarkWorkspaceRunnables.get(workspace)?.schedules?.find((e) => e.path === path) + return s ? buildBenchmarkSchedule(workspace, s) : null +} + +// ============= Folders, groups, workspace settings ============= + +function buildBenchmarkFolder(workspace: string, f: BenchmarkWorkspaceFolder): Folder { + return { + workspace_id: workspace, + name: f.name, + summary: f.summary, + owners: f.owners ?? [], + extra_perms: f.extra_perms ?? {} + } as Folder +} + +export function listBenchmarkFolders(workspace: string): Folder[] { + return (benchmarkWorkspaceRunnables.get(workspace)?.folders ?? []).map((f) => + buildBenchmarkFolder(workspace, f) + ) +} + +export function getBenchmarkFolder(workspace: string, name: string): Folder | null { + const f = benchmarkWorkspaceRunnables.get(workspace)?.folders?.find((e) => e.name === name) + return f ? buildBenchmarkFolder(workspace, f) : null +} + +export function listBenchmarkGroups(workspace: string): Group[] { + return (benchmarkWorkspaceRunnables.get(workspace)?.groups ?? []).flatMap((g) => { + const group = getBenchmarkGroup(workspace, g.name) + return group ? [group] : [] + }) +} + +export function getBenchmarkGroup(workspace: string, name: string): Group | null { + const g = benchmarkWorkspaceRunnables.get(workspace)?.groups?.find((e) => e.name === name) + return g + ? ({ + workspace_id: workspace, + name: g.name, + summary: g.summary, + members: g.members ?? [], + extra_perms: {} + } as Group) + : null +} + +const DATA_TABLE_DATABASE_TYPES = ['postgresql', 'instance', 'external_instance'] + +/** Refuse a data table entry the backend's `DataTableDatabase` would not deserialize. */ +function assertBenchmarkDataTables(value: unknown): void { + if (value === undefined || value === null) return + const datatables = (value as { datatables?: Record }).datatables ?? {} + for (const [name, entry] of Object.entries(datatables)) { + const { database, reference } = (entry ?? {}) as { + database?: { resource_type?: unknown; resource_path?: unknown } + reference?: unknown + } + // A fork's pointer at its parent's entry owns no database. + if (reference && !database) continue + if (!DATA_TABLE_DATABASE_TYPES.includes(String(database?.resource_type))) { + throw new Error( + `datatable.datatables.${name}.database.resource_type must be one of ${DATA_TABLE_DATABASE_TYPES.join(', ')}` + ) + } + if (typeof database?.resource_path !== 'string' || database.resource_path === '') { + throw new Error(`datatable.datatables.${name}.database.resource_path is required`) + } + } +} + +/** Mirror `WorkspaceService.getWorkspaceSettingsDocument`; an unseeded workspace has an + * empty document. */ +export function getBenchmarkWorkspaceSettingsDocument(workspace: string): Record { + return structuredClone(benchmarkWorkspaceSettings.get(workspace) ?? {}) +} + +/** Mirror `WorkspaceService.applyWorkspaceSettingsDocument` for a partial document: each + * top-level key replaces the stored one, `null` clears it. */ +export function applyBenchmarkWorkspaceSettingsDocument(input: { + workspace: string + requestBody: { document: Record; dry_run?: boolean } +}): { + changes: Array<{ key: string; before: unknown; after: unknown }> + applied: boolean +} { + assertBenchmarkDataTables(input.requestBody.document.datatable) + const current = benchmarkWorkspaceSettings.get(input.workspace) ?? {} + const changes = Object.entries(input.requestBody.document) + .filter(([key, after]) => JSON.stringify(current[key] ?? null) !== JSON.stringify(after ?? null)) + .map(([key, after]) => ({ key, before: current[key] ?? null, after: after ?? null })) + if (!input.requestBody.dry_run) { + const next = { ...current } + for (const { key, after } of changes) { + if (after === null) delete next[key] + else next[key] = structuredClone(after) + } + benchmarkWorkspaceSettings.set(input.workspace, next) + } + return { changes, applied: !input.requestBody.dry_run } +} + // ============= Drafts (per-user, DB-backed in production) ============= /** diff --git a/ai_evals/adapters/frontend/vitestAdapter.test.ts b/ai_evals/adapters/frontend/vitestAdapter.test.ts index b24ccbe5e4..754de224ac 100644 --- a/ai_evals/adapters/frontend/vitestAdapter.test.ts +++ b/ai_evals/adapters/frontend/vitestAdapter.test.ts @@ -85,12 +85,52 @@ vi.mock('@codingame/monaco-vscode-languages-service-override', () => ({ vi.mock('$lib/components/vscode', () => ({})) +// get_db_schema reads a database's tables by running a query job; a benchmark database +// answers with the tables its fixture seeds instead. +vi.mock('$lib/components/apps/components/display/dbtable/metadata', async () => { + const actual = await vi.importActual( + '$lib/components/apps/components/display/dbtable/metadata' + ) + const { getBenchmarkDbSchemaSeed } = await import('./mockBackend') + const { stringifySchema } = await import('$lib/components/copilot/lib') + const { resourceTypeToLang } = await import( + '$lib/components/apps/components/display/dbtable/utils' + ) + return { + ...actual, + getDbSchemas: async ( + resourceType: string, + resourcePath: string, + workspace: string | undefined, + ...rest: unknown[] + ) => { + const seed = workspace ? getBenchmarkDbSchemaSeed(workspace, resourcePath) : null + if (!seed) return actual.getDbSchemas(resourceType, resourcePath, workspace, ...rest) + const dbSchema = { + lang: resourceTypeToLang(seed.resourceType), + schema: seed.schema, + publicOnly: !!seed.schema.public + } + return { ...dbSchema, stringified: stringifySchema(dbSchema) } + } + } +}) + vi.mock('$lib/gen', async () => { const actual = await vi.importActual('$lib/gen') const { getBenchmarkAppByPath, - getBenchmarkCompletedJob, + getBenchmarkJob, getBenchmarkCompletedJobResultMaybe, + listBenchmarkWorkers, + listBenchmarkSchedules, + getBenchmarkSchedule, + listBenchmarkFolders, + getBenchmarkFolder, + getBenchmarkGroup, + listBenchmarkGroups, + getBenchmarkWorkspaceSettingsDocument, + applyBenchmarkWorkspaceSettingsDocument, getBenchmarkDatatableSchema, getBenchmarkDatatableMigrationsStatus, createBenchmarkDatatableMigration, @@ -175,7 +215,29 @@ vi.mock('$lib/gen', async () => { createFolder: async (data: { workspace: string; requestBody: { name: string } }) => hasBenchmarkWorkspace(data.workspace) ? createBenchmarkFolder(data.workspace, data.requestBody.name) - : actual.FolderService.createFolder(data) + : actual.FolderService.createFolder(data), + listFolders: async (data: { workspace: string }) => + hasBenchmarkWorkspace(data.workspace) + ? listBenchmarkFolders(data.workspace) + : actual.FolderService.listFolders(data), + getFolder: async (data: { workspace: string; name: string }) => { + if (!hasBenchmarkWorkspace(data.workspace)) return actual.FolderService.getFolder(data) + const folder = getBenchmarkFolder(data.workspace, data.name) + if (!folder) throw new Error(`Folder "${data.name}" not found in benchmark workspace`) + return folder + } + }), + GroupService: wrapService(actual.GroupService, { + listGroups: async (data: { workspace: string }) => + hasBenchmarkWorkspace(data.workspace) + ? listBenchmarkGroups(data.workspace) + : actual.GroupService.listGroups(data), + getGroup: async (data: { workspace: string; name: string }) => { + if (!hasBenchmarkWorkspace(data.workspace)) return actual.GroupService.getGroup(data) + const group = getBenchmarkGroup(data.workspace, data.name) + if (!group) throw new Error(`Group "${data.name}" not found in benchmark workspace`) + return group + } }), ScriptService: wrapService(actual.ScriptService, { listScripts: async (data: { workspace: string }) => @@ -357,7 +419,7 @@ vi.mock('$lib/gen', async () => { : actual.JobService.runFlowByPath(data), getJob: async (data: { workspace: string; id: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { - const job = getBenchmarkCompletedJob(data.workspace, data.id) + const job = getBenchmarkJob(data.workspace, data.id) if (!job) { throw new Error(`Job "${data.id}" not found in benchmark workspace`) } @@ -383,6 +445,14 @@ vi.mock('$lib/gen', async () => { : actual.JobService.getFlowAllResults(data) }), WorkspaceService: wrapService(actual.WorkspaceService, { + getWorkspaceSettingsDocument: async (data: { workspace: string }) => + hasBenchmarkWorkspace(data.workspace) + ? getBenchmarkWorkspaceSettingsDocument(data.workspace) + : actual.WorkspaceService.getWorkspaceSettingsDocument(data), + applyWorkspaceSettingsDocument: async (data: any) => + hasBenchmarkWorkspace(data.workspace) + ? applyBenchmarkWorkspaceSettingsDocument(data) + : actual.WorkspaceService.applyWorkspaceSettingsDocument(data), getCopilotInfo: async (data: { workspace: string }) => hasBenchmarkWorkspace(data.workspace) ? (getBenchmarkAiConfig(data.workspace) ?? {}) @@ -436,13 +506,21 @@ vi.mock('$lib/gen', async () => { ? { metrics: listBenchmarkDataMetrics(data.workspace) ?? [] } : actual.DataMetricService.listDataMetrics(data) }), + WorkerService: wrapService(actual.WorkerService, { + listWorkers: async (data: Record) => + listBenchmarkWorkers() ?? actual.WorkerService.listWorkers(data) + }), ScheduleService: wrapService(actual.ScheduleService, { existsSchedule: async (data: { workspace: string; path: string }) => hasBenchmarkWorkspace(data.workspace) ? false : actual.ScheduleService.existsSchedule(data), listSchedules: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.ScheduleService.listSchedules(data), + hasBenchmarkWorkspace(data.workspace) + ? listBenchmarkSchedules(data.workspace) + : actual.ScheduleService.listSchedules(data), getSchedule: async (data: { workspace: string; path: string }) => { if (hasBenchmarkWorkspace(data.workspace)) { + const schedule = getBenchmarkSchedule(data.workspace, data.path) + if (schedule) return schedule throw new Error(`Schedule "${data.path}" not found in benchmark workspace`) } return actual.ScheduleService.getSchedule(data) diff --git a/ai_evals/cases/global.yaml b/ai_evals/cases/global.yaml index 136f125e59..426fa54013 100644 --- a/ai_evals/cases/global.yaml +++ b/ai_evals/cases/global.yaml @@ -3283,3 +3283,626 @@ - Agents page - agent editor skipJudge: true + +# --- Composer suggestions --- +# The prompts the pills under Home's composer put in the box +# (frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts), word for word. +# A pill is only worth offering if the session chat can act on its prompt, so each one is +# pinned here against a workspace where the prompt has something to find. + +- id: global-composer-run-queue + prompt: |- + Is anything stuck in this workspace's queue? Which jobs are waiting or suspended, and why? + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 10 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_runs + - list_workers + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - gpu-renderer + - - refund_approval + - approval + - approve + skipJudge: true + judgeChecklist: + - finds the 12 gpu_render runs queued on the gpu-renderer tag that no connected worker serves + - finds the refund_approval flow suspended on its approval step, and says approving it unblocks it + +- id: global-composer-worker-health + prompt: |- + Are the workers healthy and keeping up with the queue? Compare how long jobs wait before they start with how busy each worker group is. + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 10 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_workers + - list_runs + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - gpu-renderer + skipJudge: true + judgeChecklist: + - reads the connected workers and the queued runs instead of guessing + - points out that the gpu-renderer runs wait because no worker serves that tag + +- id: global-composer-schedules + prompt: |- + Do any schedules in this workspace keep failing? If so, which ones and why? + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 10 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_runs + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - charge_cards_every_minute + - - insufficient funds + - declined + skipJudge: true + judgeChecklist: + - names f/billing/charge_cards_every_minute as the failing schedule, not import_orders_hourly + - gives the cause from its runs' logs (card declined, insufficient funds) + +- id: global-composer-recent-runs + prompt: |- + Look at the recent runs in this workspace: did any fail, and why? Is anything getting slower? + initial: ai_evals/fixtures/frontend/global/initial/composer_incidents.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_runs + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - charge_cards + - - insufficient funds + - declined + skipJudge: true + judgeChecklist: + - names charge_cards as the failing script and gives the cause from its logs + - does not invent a slowdown the run durations do not show + +# The empty-workspace examples, sent as the composer sends them. The workspace holds nothing, +# so the model has to stage what it needs; one answer covers a question about the Slack setup. +- id: global-composer-example-daily-metrics + prompt: |- + Every weekday at 9am, query postgres for yesterday's signups and revenue and post a summary to the #metrics Slack channel + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Use placeholders for the postgres and Slack connections, I'll fill them in later + validate: + draftCountAtLeast: 1 + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - stages a script or flow that queries postgres for the previous day's signups and revenue + - posts the summary to the #metrics Slack channel + - runs it on a schedule at 9am on weekdays only + +- id: global-composer-example-refund-approval + prompt: |- + Build a flow that asks for approval in Slack before issuing a refund in Stripe, and only refunds if someone approves + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Use placeholders for the Stripe and Slack connections, I'll fill them in later + validate: + requiredDrafts: + - type: flow + valueIncludes: + - suspend + toolExpect: + requiredToolsUsed: + - write_flow + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - posts an approval request to Slack before any refund is issued + - suspends the flow on an approval step and continues only once someone approves + - issues the refund through Stripe only on approval, never when it is rejected + +- id: global-composer-example-ticket-triage + prompt: |- + When a support ticket arrives by webhook, classify its urgency with an LLM and post the urgent ones to the #support Slack channel + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Use placeholders for the LLM and Slack connections, I'll fill them in later + validate: + draftCountAtLeast: 1 + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - stages a script or flow that takes the ticket as the input a webhook delivers + - classifies the ticket's urgency with an LLM call; an `aidecision` step (Windmill's built-in LLM decision, with `choice` or `noul` questions) counts + - posts only the urgent tickets to the #support Slack channel + +# The pills that name what an established workspace holds: a teammate's flow, a starred +# script, a connected database and channel. +- id: global-composer-walk-through-flow + prompt: |- + Walk me through what the flow f/billing/charge_customers does, step by step. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - read_workspace_item + forbiddenToolsUsed: + - write_flow + - patch_flow_json + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - due today + - invoices due + - fetch_due + - - receipt + skipJudge: true + judgeChecklist: + - reads the flow and describes its three steps in order + +- id: global-composer-run-favorite + prompt: |- + Run the script f/ops/check_ssl_expiry for me. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + userAnswers: + - windmill.dev + validate: + draftCountExactly: 0 + # The script needs a domain the prompt does not give. Opening the run form for the user to + # fill and asking for the domain in chat are both right, so neither is pinned; what is pinned + # is that the deployed script is read and nothing is previewed or written. + toolExpect: + requiredToolsUsed: + - read_workspace_item + forbiddenToolsUsed: + - test_run_script + - write_script + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - domain + # Running produces no draft, and the judge cannot observe runs; validate via tool use. + skipJudge: true + judgeChecklist: + - reads the deployed script and either opens its run form or asks for the domain it needs + +- id: global-composer-daily-summary + prompt: |- + Every weekday at 9am, summarize yesterday's activity in the Postgres database f/data/warehouse and post it to Slack with the resource f/team/slack + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 16 + sessionChat: true + userAnswers: + - Post it in #metrics, with new signups, new invoices and what they add up to + validate: + draftCountAtLeast: 1 + toolExpect: + # "Yesterday's activity" means whatever the tables hold, so they are read first. + requiredToolsUsed: + - get_db_schema + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - queries the warehouse's real tables (signups, invoices) for the previous day through f/data/warehouse + - posts the summary to Slack through the resource f/team/slack; a channel parameter with a default is fine, since the prompt names none + - runs on a schedule at 9am on weekdays only + +# Pills that teach the piece a workspace is missing. +- id: global-composer-setup-datatable + prompt: |- + This workspace has no data table yet. Walk me through setting one up in the workspace settings, then show me how a script writes to it. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 20 + sessionChat: true + userAnswers: + - Back it with the Postgres resource f/data/warehouse and call it main + # Opening the data table settings for the admin and writing them after a confirmation are + # both a way through; either way the script example is what teaches the concept. + toolExpect: + requiredToolsAnyOf: + - - open_page + - set_workspace_settings + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - datatable( + - datatable() + skipJudge: true + judgeChecklist: + - shows where data tables are set up and a script writing to one with wmill.datatable() + +- id: global-composer-store-data + prompt: |- + How should my scripts store data in Windmill? Explain data tables and show me how a script reads and writes one. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + # The pill is for developers: an admin is offered "Set up a data table" instead. + profile: + operator: false + toolExpect: + forbiddenToolsUsed: + - set_workspace_settings + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - datatable( + - datatable() + skipJudge: true + judgeChecklist: + - explains data tables and shows a script reading and writing one with wmill.datatable() + +- id: global-composer-connect-slack + prompt: |- + Help me connect Slack to this workspace so my scripts can post messages. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 12 + sessionChat: true + userAnswers: + - Use a bot token, I will paste it myself + # A Slack resource whose token is a secret variable, or the workspace's own Slack connection + # in settings: both connect Slack, so either path is accepted. + toolExpect: + requiredToolsAnyOf: + - - write_resource + - open_page + forbiddenToolsUsed: + - deploy_workspace_item + skipJudge: true + judgeChecklist: + - stages a Slack resource with its token in a secret variable, or opens the workspace's Slack settings + +- id: global-composer-store-secret + prompt: |- + I have an API key my scripts need. Store it as a secret and show me how a script reads it with wmill.getVariable. + initial: ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json + runtime: + maxTurns: 10 + sessionChat: true + userAnswers: + - It is for the Stripe API; I will paste the value myself + validate: + requiredDrafts: + - type: variable + valueIncludes: + - '"is_secret": true' + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - getVariable + - get_variable + - "$var:" + judgeChecklist: + - stages a secret variable with a placeholder value instead of inventing the key + - any example script reads the variable rather than embedding the key; an example given only in the chat is checked separately, so do not score its absence here + +# Pills that name what an established workspace holds, read from composer_connected_workspace. +- id: global-composer-explore-datatable + prompt: |- + List the tables in the data table main and tell me what each one holds. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsAnyOf: + - - list_datatables + - get_datatable_table_schema + assistantExpect: + requiredMentionsAnyOf: + - - feedback + - - onboarding_tasks + skipJudge: true + judgeChecklist: + - names the feedback and onboarding_tasks tables and what each holds + +- id: global-composer-app-on-datatable + prompt: |- + Build a full-code app to browse and edit the rows of a table in the data table main. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 30 + sessionChat: true + userAnswers: + - The feedback table + validate: + requiredDrafts: + - type: app + toolExpect: + requiredToolsUsed: + - init_app + forbiddenToolsUsed: + - deploy_workspace_item + judgeChecklist: + - builds a full-code app whose backend reads the rows of a table in the main data table through wmill.datatable(); `sql.raw` is the documented way to inline a table or column name + - lets the user edit a row and saves the change back to the table + +- id: global-composer-add-app-page + prompt: |- + Add a page to the app f/ops/console, and ask me what it should show. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 24 + sessionChat: true + userAnswers: + - A page listing the latest feedback from the main data table + # The pill asks the chat to ask: in chat or through askUserQuestion. A question in chat ends + # the run before the page is written, so the page itself is not pinned. + toolExpect: + requiredToolsAnyOf: + - - read_app_file + - read_workspace_item + forbiddenToolsUsed: + - init_app + - deploy_workspace_item + skipJudge: true + judgeChecklist: + - reads the app, then asks what the new page should show before writing it + +- id: global-composer-walk-through-agent + prompt: |- + Walk me through what the AI agent f/support/triage_agent does and which tools it can use. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - read_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - billing + - - no tools + - any tools + - no tool + skipJudge: true + judgeChecklist: + - explains that the agent labels tickets as billing, bug or question and has no tools + +- id: global-composer-channel-in-script + prompt: |- + Show me how a script uses the resource f/team/slack to post a Slack message, with a short example. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - chat.postMessage + skipJudge: true + judgeChecklist: + - shows a script that takes the f/team/slack resource and posts a message with chat.postMessage + +- id: global-composer-postgres-trigger + prompt: |- + Run a script whenever a row is inserted into a table of the Postgres database f/data/warehouse, and explain how Postgres triggers work. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 20 + sessionChat: true + userAnswers: + - The signups table + validate: + requiredDrafts: + - type: trigger + triggerKind: postgres + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - publication + - replication + judgeChecklist: + - stages a Postgres trigger on f/data/warehouse that fires on inserts, limited to one table rather than every table + - the triggered script takes the inserted row as its input + +- id: global-composer-http-endpoint + prompt: |- + Expose the script f/ops/check_ssl_expiry as an HTTP API endpoint that requires a Windmill token, and show me how to call it. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 12 + sessionChat: true + # "Expose" asks for a live route, so deploying it, behind the user's confirmation, is right. + validate: + requiredDrafts: + - type: trigger + triggerKind: http + valueIncludes: + - f/ops/check_ssl_expiry + assistantExpect: + requiredMentionsAnyOf: + - - curl + - fetch( + judgeChecklist: + - stages an HTTP route that runs f/ops/check_ssl_expiry and passes it the domain + - the route requires a Windmill token (authentication_method windmill), so it is not public + - how to call it is explained in the chat, which is checked separately; do not score it + +- id: global-composer-schedule-script + prompt: |- + Run the script f/ops/check_ssl_expiry every weekday at 9am. Ask me for any input it needs, and explain how schedules work. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 12 + sessionChat: true + userAnswers: + - windmill.dev + # The script needs a domain the prompt does not give, so the chat reads the script and asks + # for it: in chat, which ends the run, or with askUserQuestion, which goes on to the schedule. + toolExpect: + requiredToolsUsed: + - read_workspace_item + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - domain + - - cron + - schedule + skipJudge: true + judgeChecklist: + - reads the script, asks for the domain it needs, and explains how schedules work + +- id: global-composer-webhook + prompt: |- + How do I start the flow f/billing/charge_customers from another app with its webhook? Show me the URL and an example request. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + assistantExpect: + requiredMentionsAnyOf: + - - jobs/run + - - token + - Authorization + skipJudge: true + judgeChecklist: + - gives the flow's webhook URL and an example request with a token + +- id: global-composer-who-can-see + prompt: |- + Who can see and edit the flow f/billing/charge_customers, and why? + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - read_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - finance + - - bob + skipJudge: true + judgeChecklist: + - explains that access comes from the billing folder - its owner ada, bob with write, the finance group with read + +- id: global-composer-operator-what-can-i-run + prompt: |- + Which scripts and flows can I run in this workspace, and what does each one do? + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 6 + sessionChat: true + profile: + operator: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - list_workspace_items + assistantExpect: + requiredMentionsAnyOf: + - - list_open_orders + - List open orders + skipJudge: true + judgeChecklist: + - lists the runnable scripts and flows with what each does + +- id: global-composer-hub-scripts + prompt: |- + Find scripts on the Windmill Hub for Slack that I could use with the resource f/team/slack. + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsAnyOf: + - - search_hub_scripts + - get_hub_integration + skipJudge: true + judgeChecklist: + - lists Slack scripts from the Hub that take a Slack resource + +- id: global-composer-mcp + prompt: |- + How do I connect Claude to this workspace with MCP so it can run my scripts and flows? + initial: ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsAnyOf: + - - search_docs + - read_docs_page + assistantExpect: + requiredMentionsAnyOf: + - - token + - MCP URL + skipJudge: true + judgeChecklist: + - explains the MCP setup from the docs: the MCP URL with a token, added to Claude diff --git a/ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json b/ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json new file mode 100644 index 0000000000..db30ec00e8 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/composer_connected_workspace.json @@ -0,0 +1,313 @@ +{ + "user": { + "username": "admin", + "is_admin": true + }, + "workspace": { + "flows": [ + { + "path": "f/billing/charge_customers", + "summary": "Charge customers with due invoices", + "description": "Every night, charges each customer whose invoice is due and emails a receipt.", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "dry_run": { + "type": "boolean", + "default": false + } + }, + "required": [] + }, + "value": { + "modules": [ + { + "id": "fetch_due", + "summary": "Fetch invoices due today from the warehouse", + "value": { + "type": "rawscript", + "language": "postgresql", + "content": "-- database f/data/warehouse\nSELECT id, customer_id, amount_cents FROM invoices WHERE due_date = current_date AND paid = false;", + "input_transforms": { + "database": { + "type": "static", + "value": "$res:f/data/warehouse" + } + } + } + }, + { + "id": "charge", + "summary": "Charge each invoice", + "value": { + "type": "forloopflow", + "iterator": { + "type": "javascript", + "expr": "results.fetch_due" + }, + "skip_failures": false, + "modules": [ + { + "id": "charge_one", + "summary": "Charge one invoice through the payment API", + "value": { + "type": "rawscript", + "language": "bun", + "content": "export async function main(invoice: { id: number; amount_cents: number }) {\n const res = await fetch('https://payments.example.com/charge', { method: 'POST', body: JSON.stringify(invoice) })\n if (!res.ok) throw new Error(`charge failed for invoice ${invoice.id}`)\n return await res.json()\n}\n", + "input_transforms": { + "invoice": { + "type": "javascript", + "expr": "flow_input.iter.value" + } + } + } + } + ] + } + }, + { + "id": "email_receipts", + "summary": "Email a receipt to each charged customer", + "value": { + "type": "rawscript", + "language": "bun", + "content": "// Each charge is what the payment API answered, which carries the customer to email.\nexport async function main(charges: { id: string; customer_id: number }[]) {\n for (const charge of charges) {\n const res = await fetch('https://mail.example.com/receipts', { method: 'POST', body: JSON.stringify(charge) })\n if (!res.ok) throw new Error(`receipt failed for charge ${charge.id}`)\n }\n return { sent: charges.length }\n}\n", + "input_transforms": { + "charges": { + "type": "javascript", + "expr": "results.charge" + } + } + } + } + ] + } + } + ], + "scripts": [ + { + "path": "f/ops/check_ssl_expiry", + "summary": "Check SSL certificate expiry", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": "The domain whose certificate to check" + } + }, + "required": [ + "domain" + ] + }, + "content": "export async function main(domain: string) {\n const res = await fetch(`https://ssl-check.example.com/${domain}`)\n return await res.json()\n}\n" + } + ], + "resources": [ + { + "path": "f/data/warehouse", + "resource_type": "postgresql", + "description": "Production warehouse", + "value": { + "host": "db.internal", + "port": 5432, + "dbname": "warehouse", + "user": "windmill", + "password": "$var:f/data/warehouse_password" + }, + "dbSchema": { + "public": { + "customers": { + "id": { + "type": "integer", + "required": true + }, + "email": { + "type": "text", + "required": true + }, + "plan": { + "type": "text", + "required": false + }, + "created_at": { + "type": "timestamp", + "required": true, + "default": "now()" + } + }, + "invoices": { + "id": { + "type": "integer", + "required": true + }, + "customer_id": { + "type": "integer", + "required": true + }, + "amount_cents": { + "type": "integer", + "required": true + }, + "due_date": { + "type": "date", + "required": true + }, + "paid": { + "type": "boolean", + "required": true, + "default": "false" + }, + "created_at": { + "type": "timestamp", + "required": true, + "default": "now()" + } + }, + "signups": { + "id": { + "type": "integer", + "required": true + }, + "email": { + "type": "text", + "required": true + }, + "source": { + "type": "text", + "required": false + }, + "created_at": { + "type": "timestamp", + "required": true, + "default": "now()" + } + } + } + } + }, + { + "path": "f/team/slack", + "resource_type": "slack", + "description": "Team Slack bot", + "value": { + "token": "$var:f/team/slack_token" + } + }, + { + "path": "f/support/triage_agent", + "resource_type": "ai_agent", + "description": "Labels incoming support tickets", + "value": { + "provider": { + "kind": "anthropic", + "model": "claude-sonnet-5", + "resource": "" + }, + "output_type": "text", + "system_prompt": "Read the support ticket and answer with one label: billing, bug or question.", + "memory": { + "kind": "off" + }, + "tools": [] + } + } + ], + "apps": [ + { + "path": "f/ops/console", + "summary": "Ops console", + "value": { + "files": { + "/App.tsx": "import { useState } from 'react'\nimport { backend } from './wmill'\n\nexport default function App() {\n\tconst [domain, setDomain] = useState('')\n\tconst [result, setResult] = useState()\n\treturn (\n\t\t
    \n\t\t\t

    Ops console

    \n\t\t\t setDomain(e.target.value)} />\n\t\t\t\n\t\t\t
    {JSON.stringify(result, null, 2)}
    \n\t\t
    \n\t)\n}\n" + }, + "runnables": { + "check_ssl": { + "type": "path", + "runType": "script", + "path": "f/ops/check_ssl_expiry", + "fields": {} + } + } + } + } + ], + "datatables": [ + { + "datatable_name": "main", + "schemas": { + "public": { + "feedback": { + "columns": { + "id": "int4", + "customer_email": "text", + "rating": "int4", + "comment": "text", + "created_at": "timestamptz" + }, + "rows": [ + { + "id": 1, + "customer_email": "ada@example.com", + "rating": 5, + "comment": "Fast support", + "created_at": "2026-10-01T09:00:00Z" + } + ] + }, + "onboarding_tasks": { + "columns": { + "id": "int4", + "customer_email": "text", + "task": "text", + "done": "bool" + }, + "rows": [ + { + "id": 1, + "customer_email": "ada@example.com", + "task": "Connect billing", + "done": false + } + ] + } + } + } + } + ], + "folders": [ + { + "name": "billing", + "summary": "Billing jobs", + "owners": [ + "u/ada" + ], + "extra_perms": { + "g/finance": false, + "u/bob": true + } + }, + { + "name": "ops", + "summary": "Operations", + "owners": [ + "u/admin" + ], + "extra_perms": {} + } + ], + "groups": [ + { + "name": "finance", + "summary": "Finance team", + "members": [ + "carol", + "dan" + ] + } + ] + } +} diff --git a/ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json b/ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json new file mode 100644 index 0000000000..b719ba0751 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/composer_fresh_workspace.json @@ -0,0 +1,22 @@ +{ + "user": { + "username": "admin", + "is_admin": true + }, + "workspace": { + "resources": [ + { + "path": "f/data/warehouse", + "resource_type": "postgresql", + "description": "Production warehouse", + "value": { + "host": "db.internal", + "port": 5432, + "dbname": "warehouse", + "user": "windmill", + "password": "$var:f/data/warehouse_password" + } + } + ] + } +} diff --git a/ai_evals/fixtures/frontend/global/initial/composer_incidents.json b/ai_evals/fixtures/frontend/global/initial/composer_incidents.json new file mode 100644 index 0000000000..4799b895ea --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/composer_incidents.json @@ -0,0 +1,83 @@ +{ + "workspace": { + "scripts": [ + { + "path": "f/billing/charge_cards", + "summary": "Charge cards", + "language": "bash", + "content": "echo \"charging card for customer $1\"\ncurl -sf https://payments.example.com/charge || { echo \"card declined: insufficient funds\" >&2; exit 1; }\n" + }, + { + "path": "f/sales/import_orders", + "summary": "Import orders", + "language": "bash", + "content": "echo \"imported $(date +%s) orders\"\n" + }, + { + "path": "f/media/gpu_render", + "summary": "GPU render", + "language": "bash", + "content": "echo \"rendering frame\"\n" + } + ], + "flows": [ + { + "path": "f/billing/refund_approval", + "summary": "Refund approval", + "value": { + "modules": [ + { + "id": "a", + "summary": "Ask a manager to approve the refund", + "value": { "type": "rawscript", "language": "bash", "content": "echo \"refund requested\"", "input_transforms": {} }, + "suspend": { "required_events": 1, "timeout": 86400 } + }, + { + "id": "b", + "summary": "Issue the refund", + "value": { "type": "rawscript", "language": "bash", "content": "echo \"refunded\"", "input_transforms": {} } + } + ] + } + } + ], + "schedules": [ + { "path": "f/billing/charge_cards_every_minute", "schedule": "0 * * * * *", "script_path": "f/billing/charge_cards", "summary": "Charge pending cards every minute" }, + { "path": "f/sales/import_orders_hourly", "schedule": "0 0 * * * *", "script_path": "f/sales/import_orders", "summary": "Import orders every hour" } + ], + "workers": [ + { + "worker": "wk-default-7f3a2", + "worker_group": "default", + "custom_tags": ["bash", "python3", "bun", "deno", "go", "flow", "dependency"], + "lastPingSecondsAgo": 3, + "jobs_executed": 214 + } + ], + "jobs": [ + { "id": "01930000-0000-7000-8000-00000000c001", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 1, "durationMs": 41, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c002", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 2, "durationMs": 38, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c003", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 3, "durationMs": 44, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c004", "scriptPath": "f/billing/charge_cards", "schedulePath": "f/billing/charge_cards_every_minute", "createdBy": "schedule", "success": false, "createdMinutesAgo": 4, "durationMs": 40, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c005", "scriptPath": "f/billing/charge_cards", "createdBy": "alice", "success": false, "createdMinutesAgo": 30, "durationMs": 52, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000c006", "scriptPath": "f/billing/charge_cards", "createdBy": "alice", "success": false, "createdMinutesAgo": 31, "durationMs": 47, "tag": "bash", "logs": "charging card for customer 4412\ncard declined: insufficient funds\nexit code 1" }, + { "id": "01930000-0000-7000-8000-00000000d001", "scriptPath": "f/sales/import_orders", "schedulePath": "f/sales/import_orders_hourly", "createdBy": "schedule", "success": true, "createdMinutesAgo": 10, "durationMs": 820, "tag": "bash", "logs": "imported 112 orders" }, + { "id": "01930000-0000-7000-8000-00000000d002", "scriptPath": "f/sales/import_orders", "schedulePath": "f/sales/import_orders_hourly", "createdBy": "schedule", "success": true, "createdMinutesAgo": 70, "durationMs": 790, "tag": "bash", "logs": "imported 98 orders" }, + { "id": "01930000-0000-7000-8000-00000000d003", "scriptPath": "f/sales/import_orders", "schedulePath": "f/sales/import_orders_hourly", "createdBy": "schedule", "success": true, "createdMinutesAgo": 130, "durationMs": 805, "tag": "bash", "logs": "imported 104 orders" }, + { "id": "01930000-0000-7000-8000-00000000d004", "scriptPath": "f/sales/import_orders", "createdBy": "bob", "success": true, "createdMinutesAgo": 45, "durationMs": 811, "tag": "bash", "logs": "imported 3 orders" }, + { "id": "01930000-0000-7000-8000-00000000e001", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 22, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e002", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 22, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e003", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 22, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e004", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 21, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e005", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 21, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e006", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 21, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e007", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 20, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e008", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 20, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e009", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 20, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e010", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 19, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e011", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 19, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000e012", "scriptPath": "f/media/gpu_render", "createdBy": "alice", "state": "queued", "createdMinutesAgo": 19, "tag": "gpu-renderer" }, + { "id": "01930000-0000-7000-8000-00000000f001", "scriptPath": "f/billing/refund_approval", "jobKind": "flow", "createdBy": "bob", "state": "suspended", "createdMinutesAgo": 40, "tag": "flow", "logs": "refund requested" } + ] + } +} diff --git a/backend/windmill-api/src/mcp/session/gen/instructions.json b/backend/windmill-api/src/mcp/session/gen/instructions.json index 796bdb7ffd..df6f1f6917 100644 --- a/backend/windmill-api/src/mcp/session/gen/instructions.json +++ b/backend/windmill-api/src/mcp/session/gen/instructions.json @@ -232,6 +232,6 @@ "datatable.python3": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "datatable.go": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch(\n params?: FetchParams // The union is for auto-completion\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit, \"resultCollection\">\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit, \"resultCollection\">\n ): Promise;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n (strings: TemplateStringsArray, ...values: any[]): SqlStatement;\n query(sql: string, ...params: any[]): SqlStatement;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake:///` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO
    SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/
    `. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `wmill.ducklake(\"\")` targets a non-default catalog; `wmill.datatable(\"\")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on ` — declares an execution-DAG **input** (what triggers/feeds this node). `` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $ (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize `.\n- Optional badges: `// partitioned `, `// freshness ` (e.g. `1h`), `// tag `, `// retry [delay]`, `// data_test ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure = [where ]` and `// dimension = ` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3:///` (**double** slash, non-empty first segment) = a **named secondary** storage called `` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"\"), data)` (or the import-free dict `{\"s3\": \"\"}`), TS `wmill.writeS3File({ s3: \"\" }, data)`. That records the default-storage asset `/`, which a downstream `s3:///` reader connects to (same key both sides). A bare `write_s3_file(\"\", ...)` records **no** asset and produces **no** edge. Add `storage=\"\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake:///
    `). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see \"Ingesting from Python / TypeScript\") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes.\n\nA managed `// materialize ducklake:///
    ` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.) Write strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize append` → INSERT-append rows (incremental);\n- `// materialize key=` → merge/upsert on ``.\n\n`// materialize manual ` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned ` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition() = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure = [where ]` names the canonical way to aggregate that table (e.g. `// measure revenue = sum(amount) where not is_refund`), and `// dimension = ` names a way to slice it (e.g. `// dimension region = region`, `// dimension month = date_trunc('month', ordered_at)`). They execute nothing: they are catalogued at deploy so the editor and other agents reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as ` FILTER (WHERE )`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f//`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. Don't deploy nodes unless the user asks to. A pipeline only \"runs\" once its scripts are deployed and their triggers exist.\n\n## Example (DuckDB → DuckLake, scheduled ingest + downstream transform)\n\nNode `f/sales/orders_ingest` (runs on a schedule, materializes a DuckLake table):\n\n```sql\n-- pipeline\n-- on schedule\n-- materialize ducklake://main/orders\nSELECT * FROM read_csv('s3:///raw/orders/*.csv')\n```\n\nNode `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup):\n\n```sql\n-- pipeline\n-- on ducklake://main/orders\n-- materialize ducklake://main/orders_daily\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM ducklake.main.orders GROUP BY 1\n```\n", - "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`slack_oauth_client_secret` is the one secret. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }`, `path` being `script/` or `flow/`. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path? } } } }`. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `operator_settings` | What operators see and do: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). A write right the value omits keeps its stored value. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_access_enabled`, `guest_jwt_public_key`, `guest_jwt_jwks_url` | Guest access to public apps and the key that signs guest JWTs. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n" + "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`slack_oauth_client_secret` is the one secret. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }`, `path` being `script/` or `flow/`. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `operator_settings` | What operators see and do: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). A write right the value omits keeps its stored value. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_access_enabled`, `guest_jwt_public_key`, `guest_jwt_jwks_url` | Guest access to public apps and the key that signs guest JWTs. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n" } } diff --git a/backend/windmill-api/src/mcp/session/gen/tools.json b/backend/windmill-api/src/mcp/session/gen/tools.json index 4db0f3e4a4..ffab17090a 100644 --- a/backend/windmill-api/src/mcp/session/gen/tools.json +++ b/backend/windmill-api/src/mcp/session/gen/tools.json @@ -1372,7 +1372,7 @@ }, { "name": "rebase_draft", - "description": "Discard a stale script, flow, or app draft and return your changes as a diff to re-apply on the latest deployed version. Use when deploy_workspace_item reports the draft was started from an older deployed version.", + "description": "Discard a stale script, flow, or app draft and return your changes as a diff to re-apply on the latest deployed version. Use when a deploy reports the draft was started from an older deployed version.", "parameters": { "type": "object", "properties": { diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index d932957a20..6a0d6f47f4 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -8364,7 +8364,7 @@ write a secret you were not given: keep the placeholder. | \`ai_config\` | Providers, default and completion models, custom prompts, \`copilot_disabled\`. | | \`large_file_storage\` | Workspace object storage: \`{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }\`. | | \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | -| \`datatable\` | \`{ datatables: { : { database: { resource_type, resource_path? } } } }\`. Role permissions are \`datatable_permissions\`. | +| \`datatable\` | \`{ datatables: { : { database: { resource_type, resource_path } } } }\`, both required: \`resource_type: postgresql\` with \`resource_path\` a Postgres resource's path, or \`instance\`, or \`external_instance\` (Enterprise only), with \`resource_path\` the name of a database a superadmin set up. A fork's entry can instead be \`{ reference: { workspace_id, datatable } }\`, pointing at its parent's data table; keep it as is. \`main\` is the one scripts use by default. Role permissions are \`datatable_permissions\`. | | \`datatable_permissions\` | \`{ : { default_role, roles: { : [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/\`, \`g/\`, \`f/\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | | \`protection_rules\` | \`{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { : { catalog, storage, ... } } }\`. | diff --git a/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.test.ts b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.test.ts new file mode 100644 index 0000000000..1c74750a43 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest' +import { composerSuggestions, type ComposerRole } from './composerSuggestions' + +const developer: ComposerRole = { operator: false, workspaceAdmin: false, instanceAdmin: false } +const operator: ComposerRole = { ...developer, operator: true } +const workspaceAdmin: ComposerRole = { ...developer, workspaceAdmin: true } + +const myDraft = { kind: 'flow', path: 'f/a/sync', name: 'Sync' } +const sharedFlow = { kind: 'flow', path: 'f/billing/charge', name: 'Charge customers' } +const favorite = { kind: 'script', path: 'f/ops/check_ssl', name: 'Check SSL expiry' } +const script = favorite +const app = { kind: 'app', path: 'f/ops/console', name: 'Ops console' } +const folderItem = sharedFlow +const database = { type: 'postgresql', path: 'f/data/main_db', name: 'main_db' } +const slack = { type: 'slack', path: 'f/team/slack', name: 'slack' } + +const labels = (...args: Parameters) => + composerSuggestions(...args).map((s) => s.label) + +describe('composerSuggestions', () => { + it('offers the build examples in an empty workspace, but not to an operator', () => { + expect(labels({ itemCount: 0 }, developer)).toEqual([ + 'Daily metrics to Slack', + 'Approve refunds in Slack', + 'Triage tickets to Slack' + ]) + expect(labels({ itemCount: 0 }, operator)).toEqual([]) + }) + + it("teaches the piece a workspace is missing first, as the reader's role allows", () => { + const fresh = { itemCount: 0, dataTables: [], database: null, channel: null } + expect(labels(fresh, workspaceAdmin)).toEqual([ + 'Set up a data table', + 'Daily metrics to Slack', + 'Approve refunds in Slack', + 'Triage tickets to Slack' + ]) + expect(labels(fresh, developer)[0]).toBe('How do I store data?') + expect(labels({ ...fresh, dataTables: ['main'] }, developer)[0]).toBe('Connect Slack') + // Past its first items a workspace may keep data and Slack where these lists don't look. + const established = { ...fresh, itemCount: 25 } + expect(labels(established, workspaceAdmin)[0]).toBe('Set up a data table') + expect(labels(established, developer)).not.toContain('How do I store data?') + expect(labels(established, developer)).not.toContain('Connect Slack') + }) + + it('builds a new workspace from its own connections, naming their paths', () => { + const s = composerSuggestions( + { itemCount: 0, dataTables: ['main'], database, channel: slack }, + developer + ) + expect(s.map((x) => [x.mode, x.label])).toEqual([ + ['build', 'Daily main_db summary to Slack'], + ['use', "What's in the main data table?"], + ['build', 'Build an app on the main data table'], + ['use', 'Post a Slack message from a script'] + ]) + expect(s[0].prompt).toContain('f/data/main_db') + expect(s[0].prompt).toContain('f/team/slack') + }) + + it("ranks the reader's own work first, then what the workspace holds, once per concept", () => { + const established = { + itemCount: 25, + sharedFlow, + favorite, + script, + app, + folderItem, + database, + channel: slack, + dataTables: ['main'] + } + expect(labels({ ...established, myDraft }, workspaceAdmin)).toEqual([ + 'Finish my draft: Sync', + "What's in the main data table?", + 'Walk me through Charge customers', + 'Run Check SSL expiry' + ]) + expect(labels(established, developer)).toEqual([ + "What's in the main data table?", + 'Walk me through Charge customers', + 'Run Check SSL expiry', + 'Add a page to Ops console' + ]) + }) + + it('keeps an operator to running and reading', () => { + expect( + labels( + { itemCount: 25, myDraft, sharedFlow, favorite, folderItem, dataTables: [], channel: null }, + operator + ) + ).toEqual([ + 'Run Check SSL expiry', + 'Walk me through Charge customers', + 'What can I run here?', + 'Who can see Charge customers?' + ]) + }) + + it('fills with the checks for the role', () => { + expect(labels({ itemCount: 10 }, workspaceAdmin)).toEqual([ + 'Check the schedules', + 'Check recent runs', + 'Check the run queue', + 'Use my scripts from Claude' + ]) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts new file mode 100644 index 0000000000..a6a6a00c90 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/composerSuggestions.ts @@ -0,0 +1,387 @@ +import type { StarterPrompt } from '$lib/onboardingProfile' + +/** A prompt offered under the composer: `label` is the pill, `prompt` what it puts in the + * box. `use` looks at, asks about or runs what exists; `build` creates or changes things. */ +export type ComposerSuggestion = StarterPrompt & { mode: 'use' | 'build' } + +/** What the reader may do where the session acts. An instance admin is not assumed to be an + * admin of the workspace. */ +export type ComposerRole = { operator: boolean; workspaceAdmin: boolean; instanceAdmin: boolean } + +export type ComposerItem = { kind: string; path: string; name: string } + +/** A connection the workspace holds; `type` is its resource type. */ +export type ComposerResource = { type: string; path: string; name: string } + +/** Below this many items the workspace is new enough that building leads. */ +export const FEW_ITEMS = 10 + +/** The databases whose tables the chat can read (`get_db_schema`), by resource type. */ +export const DATABASE_TYPES: Record = { + postgresql: 'Postgres', + mysql: 'MySQL', + ms_sql_server: 'SQL Server', + snowflake: 'Snowflake', + bigquery: 'BigQuery' +} + +/** Where a job can send a message, by resource type, most preferred first. */ +export const CHANNEL_TYPES: Record< + string, + { name: string; to: string; send: string; message: string } +> = { + slack: { + name: 'Slack', + to: 'to Slack', + send: 'post it to Slack', + message: 'post a Slack message' + }, + ms_teams_webhook: { + name: 'Microsoft Teams', + to: 'to Teams', + send: 'post it to Microsoft Teams', + message: 'post a Teams message' + }, + discord_webhook: { + name: 'Discord', + to: 'to Discord', + send: 'post it to Discord', + message: 'post a Discord message' + }, + telegram: { + name: 'Telegram', + to: 'to Telegram', + send: 'send it on Telegram', + message: 'send a Telegram message' + }, + gmail: { name: 'Gmail', to: 'by email', send: 'email it', message: 'send an email' }, + smtp: { name: 'email', to: 'by email', send: 'email it', message: 'send an email' } +} + +/** What the workspace looks like now: read from the composer's item, resource and data table + * lists. An absent field fires no rule. A `null` channel and an + * empty `dataTables` mean the list answered and holds none, which fires the pills that teach + * the missing piece. */ +export type ComposerSignals = { + /** Capped at the page the list call reads. */ + itemCount?: number + /** The reader's draft among the items the list call reads, the most recently updated. */ + myDraft?: ComposerItem + /** Among the same items, the most recently updated flow outside the reader's user folder. */ + sharedFlow?: ComposerItem + /** Among the same items, the most recently updated deployed script with a main function. */ + script?: ComposerItem + /** Among the same items the reader may edit, the most recently updated full-code app. */ + app?: ComposerItem + /** Among the same items, the most recently updated AI agent. */ + agent?: ComposerItem + /** Among the same items, the most recently updated one in a folder. */ + folderItem?: ComposerItem + /** Among the same items, a script or flow the reader starred. The sidebar's favorites are + * not used: they name no workspace, so after a switch they can still be the last one's. */ + favorite?: ComposerItem + /** Among the connections the resource list reads (one page, ordered by path), the most + * recently edited database. */ + database?: ComposerResource + /** Among the same connections, the one a job would send a message through, the most + * preferred type first. */ + channel?: ComposerResource | null + /** The workspace's data tables, `main` first. */ + dataTables?: string[] +} + +/** Each example shows a different piece of Windmill: a schedule, an approval step, a webhook. */ +const BUILD_EXAMPLES: ComposerSuggestion[] = [ + { + mode: 'build', + label: 'Daily metrics to Slack', + prompt: + "Every weekday at 9am, query postgres for yesterday's signups and revenue and post a summary to the #metrics Slack channel" + }, + { + mode: 'build', + label: 'Approve refunds in Slack', + prompt: + 'Build a flow that asks for approval in Slack before issuing a refund in Stripe, and only refunds if someone approves' + }, + { + mode: 'build', + label: 'Triage tickets to Slack', + prompt: + 'When a support ticket arrives by webhook, classify its urgency with an LLM and post the urgent ones to the #support Slack channel' + } +] + +const MAX_SUGGESTIONS = 4 +const MAX_NAME = 32 + +/** Up to four suggestions that each teach one Windmill concept on the reader's own workspace, + * most pressing first: their unfinished work, the next piece the workspace is missing, then + * what it already holds, the build examples while it is empty, and checks for the role. A + * concept is offered once. A prompt names the exact item or connection path: the chat cannot + * list resources by type, so "our database" would leave it guessing. A pill reads what the + * workspace holds, never how its runs went: one that names a failure would announce it and + * offer the fix at once. The checks claim nothing, so they read the same whether or not + * anything is wrong. */ +export function composerSuggestions( + signals: ComposerSignals, + role: ComposerRole +): ComposerSuggestion[] { + const out: ComposerSuggestion[] = [] + const taught = new Set() + const add = ( + concept: string, + mode: ComposerSuggestion['mode'], + label: string, + prompt: string + ) => { + if (taught.has(concept)) return + taught.add(concept) + out.push({ mode, label, prompt }) + } + const empty = signals.itemCount === 0 + const few = signals.itemCount !== undefined && signals.itemCount < FEW_ITEMS + const { database, channel, dataTables, script, sharedFlow } = signals + const dataTable = dataTables?.[0] + // Operators run what others built and author nothing. + const builder = !role.operator + + if (builder) { + const draft = signals.myDraft + if (draft) + add( + 'draft', + 'build', + `Finish my draft: ${shortName(draft.name)}`, + `Help me finish my draft of the ${draft.kind} ${draft.path}` + ) + + // The next piece the workspace is missing, one at a time: where data lives, then a + // channel to send messages through. Past its first items a workspace may keep its data + // in its own database and reach Slack through workspace settings, neither of which these + // lists see, so only the admin's data table setup is offered there. + if (dataTables?.length === 0) { + // Only an admin can set up a data table. + if (role.workspaceAdmin) + add( + 'next', + 'build', + 'Set up a data table', + 'This workspace has no data table yet. Walk me through setting one up in the workspace settings, then show me how a script writes to it.' + ) + else if (few) + add( + 'next', + 'use', + 'How do I store data?', + 'How should my scripts store data in Windmill? Explain data tables and show me how a script reads and writes one.' + ) + } + if (channel === null && few) + add( + 'next', + 'build', + 'Connect Slack', + 'Help me connect Slack to this workspace so my scripts can post messages.' + ) + } + + const send = channel ? CHANNEL_TYPES[channel.type] : undefined + const summary = () => { + if (!few || !builder || !database || !channel || !send) return + add( + 'summary', + 'build', + `Daily ${shortName(database.name)} summary ${send.to}`, + `Every weekday at 9am, summarize yesterday's activity in the ${DATABASE_TYPES[database.type]} database ${database.path} and ${send.send} with the resource ${channel.path}` + ) + } + const exploreTable = () => { + if (!dataTable) return + add( + 'datatable', + 'use', + `What's in the ${shortName(dataTable)} data table?`, + `List the tables in the data table ${dataTable} and tell me what each one holds.` + ) + } + const walkThrough = () => { + const flow = sharedFlow + if (flow) + add( + 'walk', + 'use', + `Walk me through ${shortName(flow.name)}`, + `Walk me through what the flow ${flow.path} does, step by step.` + ) + const agent = signals.agent + if (agent) + add( + 'walk', + 'use', + `Walk me through ${shortName(agent.name)}`, + `Walk me through what the AI agent ${agent.path} does and which tools it can use.` + ) + } + const run = () => { + const favorite = signals.favorite + if (favorite) + add( + 'run', + 'use', + `Run ${shortName(favorite.name)}`, + `Run the ${favorite.kind} ${favorite.path} for me.` + ) + } + const access = () => { + const item = signals.folderItem + if (item) + add( + 'access', + 'use', + `Who can see ${shortName(item.name)}?`, + `Who can see and edit the ${item.kind} ${item.path}, and why?` + ) + } + + if (role.operator) { + run() + walkThrough() + exploreTable() + if (!empty) + add( + 'operator', + 'use', + 'What can I run here?', + 'Which scripts and flows can I run in this workspace, and what does each one do?' + ) + access() + } else { + summary() + exploreTable() + walkThrough() + run() + const app = signals.app + if (app) + add( + 'app', + 'build', + `Add a page to ${shortName(app.name)}`, + `Add a page to the app ${app.path}, and ask me what it should show.` + ) + else if (dataTable) + add( + 'app', + 'build', + `Build an app on the ${shortName(dataTable)} data table`, + `Build a full-code app to browse and edit the rows of a table in the data table ${dataTable}.` + ) + if (channel && send) + add( + 'channel', + 'use', + `${capitalize(send.message)} from a script`, + `Show me how a script uses the resource ${channel.path} to ${send.message}, with a short example.` + ) + if (database?.type === 'postgresql') + add( + 'postgres', + 'build', + `React to new rows in ${shortName(database.name)}`, + `Run a script whenever a row is inserted into a table of the Postgres database ${database.path}, and explain how Postgres triggers work.` + ) + if (script) { + add( + 'endpoint', + 'build', + `Make ${shortName(script.name)} an API endpoint`, + `Expose the script ${script.path} as an HTTP API endpoint that requires a Windmill token, and show me how to call it.` + ) + if (few) + add( + 'schedule', + 'build', + `Run ${shortName(script.name)} every morning`, + `Run the script ${script.path} every weekday at 9am. Ask me for any input it needs, and explain how schedules work.` + ) + } + if (sharedFlow) + add( + 'webhook', + 'use', + `Call ${shortName(sharedFlow.name)} by webhook`, + `How do I start the flow ${sharedFlow.path} from another app with its webhook? Show me the URL and an example request.` + ) + access() + // While the workspace is new; an empty one needs its build examples more. + if (few && !empty) + add( + 'secret', + 'build', + 'Store an API key as a secret', + 'I have an API key my scripts need. Store it as a secret and show me how a script reads it with wmill.getVariable.' + ) + if (channel && send) + add( + 'hub', + 'use', + `Find Hub scripts for ${send.name}`, + `Find scripts on the Windmill Hub for ${send.name} that I could use with the resource ${channel.path}.` + ) + } + + if (empty && builder) { + const [dailyMetrics, ...others] = BUILD_EXAMPLES + out.push(...(taught.has('summary') ? others : [dailyMetrics, ...others])) + } + + // A workspace with nothing in it has nothing to check yet. Keep these to what the chat's + // tools can answer: its run listing has no date filter and stops at 100 runs, so a prompt + // naming a period ("today", "this week") gets a guess. + if (!empty) { + if (role.instanceAdmin) + add( + 'workers', + 'use', + 'Check worker health', + 'Are the workers healthy and keeping up with the queue? Compare how long jobs wait before they start with how busy each worker group is.' + ) + if (role.workspaceAdmin) + add( + 'schedules', + 'use', + 'Check the schedules', + 'Do any schedules in this workspace keep failing? If so, which ones and why?' + ) + add( + 'runs', + 'use', + 'Check recent runs', + 'Look at the recent runs in this workspace: did any fail, and why? Is anything getting slower?' + ) + add( + 'queue', + 'use', + 'Check the run queue', + "Is anything stuck in this workspace's queue? Which jobs are waiting or suspended, and why?" + ) + } + + if (builder && !empty) + add( + 'mcp', + 'use', + 'Use my scripts from Claude', + 'How do I connect Claude to this workspace with MCP so it can run my scripts and flows?' + ) + + return out.slice(0, MAX_SUGGESTIONS) +} + +function shortName(name: string): string { + return name.length > MAX_NAME ? `${name.slice(0, MAX_NAME - 1)}…` : name +} + +function capitalize(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1) +} diff --git a/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts index 9bb9341a0b..b02ce5c558 100644 --- a/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts @@ -1,80 +1,46 @@ import { onboardingProfile, type StarterPrompt } from '$lib/onboardingProfile' -import { roleCapabilities } from '$lib/stores' -import { fromStore } from 'svelte/store' +import { roleCapabilities, userStore } from '$lib/stores' +import { canEditItem } from '$lib/editRights' +import { scopedKey } from '$lib/userScopedStorage' +import { fromStore, get } from 'svelte/store' import { resource } from 'runed' -import { ScriptService } from '$lib/gen' +import { + ResourceService, + ScriptService, + WorkspaceService, + type ListableResource, + type RunnableItem +} from '$lib/gen' +import { + CHANNEL_TYPES, + composerSuggestions, + DATABASE_TYPES, + FEW_ITEMS, + type ComposerItem, + type ComposerResource, + type ComposerRole, + type ComposerSignals, + type ComposerSuggestion +} from './composerSuggestions' -/** A prompt offered under the composer: `label` is the pill, `prompt` what it puts in the - * box. `use` looks at, asks about or runs what exists; `build` creates or changes things. */ -export type ComposerSuggestion = StarterPrompt & { mode: 'use' | 'build' } +export type { ComposerSuggestion } -const USE_EXAMPLES: ComposerSuggestion[] = [ - { - mode: 'use', - label: 'What failed today?', - prompt: 'Which runs failed in this workspace today, and why?' - }, - { - mode: 'use', - label: 'Which schedules run the most?', - prompt: - 'Which schedules ran the most today, and does any of them run more often than it should?' - } -] - -const BUILD_EXAMPLES: ComposerSuggestion[] = [ - { - mode: 'build', - label: 'Sync Salesforce', - prompt: 'Sync new Salesforce leads into a postgres table every hour' - }, - { - mode: 'build', - label: 'Weekly Slack report', - prompt: 'Generate a weekly sales report from postgres and post it to Slack every Monday' - }, - { - mode: 'build', - label: 'Ban Discord users', - prompt: - 'Build a workflow that triggers on a Discord message, checks for offensive language using an LLM, and possibly block them' - } -] - -/** A session for a role that cannot code can run what is deployed, read runs and call MCP - * servers, but cannot author scripts, so none of these asks it to build anything. */ -const OPERATOR_EXAMPLES: ComposerSuggestion[] = [ - USE_EXAMPLES[0], - { - mode: 'use', - label: 'Rerun failed jobs', - prompt: 'List the jobs that failed today, tell me why, and rerun the ones that timed out' - }, - { - mode: 'use', - label: 'Run a flow', - prompt: 'Find the flow that onboards a new employee and run it for Jane Doe, starting Monday' - }, - { - mode: 'use', - label: 'Summarize GitHub issues', - prompt: "Read this week's open GitHub issues and summarize the ones that mention billing" - } -] - -/** From this many items on, Home's composer rests collapsed: below it the workspace is new - * enough that the composer is the page's main way in. */ -const FEW_ITEMS = 10 +/** The newest items read: enough to find a shared flow beside the reader's own work. */ +const ITEMS_READ = 25 +/** The connections read. A full page may have cut the channel off, so only a page shorter + * than this proves the workspace has none. */ +const RESOURCES_READ = 20 /** The suggestions for the reader's role and the workspace the session acts on, and whether * that workspace is still small. An invite that wrote prompts for this person replaces the - * examples outright: a prompt written for someone's own stack next to "Ban Discord users" - * reads as the generic one. */ + * suggestions outright: a prompt written for someone's own stack next to "Approve refunds in + * Slack" reads as the generic one. */ export class StarterPrompts { #invite = $state() + #user = fromStore(userStore) #capabilities = fromStore(roleCapabilities) #workspace: () => string | undefined - #itemCount: { readonly current: number | undefined } + #signals: { readonly current: Tagged | undefined } /** `workspace`: where the session acts. */ constructor(workspace: () => string | undefined) { @@ -82,66 +48,222 @@ export class StarterPrompts { void onboardingProfile().then((p) => { if (p?.starter_prompts?.length) this.#invite = p.starter_prompts }) - this.#itemCount = resource(workspace, async (ws) => (ws ? workspaceItemCount(ws) : undefined)) + // runed keeps whichever fetch settles last, so after a workspace or account switch an + // earlier fetch can land on top of the current one: each answer carries what it is for. + this.#signals = resource( + () => this.#tag, + async (tag) => { + const ws = this.#workspace() + return ws ? { tag, value: await readComposerSignals(ws) } : undefined + } + ) } - /** At most `FEW_ITEMS`; undefined until the workspace has answered. A count already read - * this page load stands in while it is asked again, so a remount does not wait on it. */ - get #count(): number | undefined { + get #tag(): string { + return `${this.#workspace()}\0${this.#user.current?.email}` + } + + /** Undefined until the user is known. The user is read for Home's workspace, so a session + * acting on another one (a fork) keeps only what is instance-wide. */ + get #role(): ComposerRole | undefined { + const user = this.#user.current + if (!user) return undefined + const own = user.workspace_id === this.#workspace() + return { + operator: own && !this.#capabilities.current.code, + workspaceAdmin: own && user.is_admin, + instanceAdmin: user.is_super_admin + } + } + + /** Signals already read this page load stand in while they are asked again, so a remount + * does not wait on them. */ + get #currentSignals(): ComposerSignals | undefined { + const current = this.#signals.current + if (current?.tag === this.#tag) return current.value const ws = this.#workspace() - return this.#itemCount.current ?? (ws ? itemCounts.get(ws) : undefined) + const key = ws && signalsKey(ws) + return key ? settled.get(key) : undefined } - /** Up to four: two Use then two Build. An empty workspace has nothing to ask about yet. */ readonly suggestions: ComposerSuggestion[] = $derived.by(() => { if (this.#invite) return this.#invite.map((p) => ({ ...p, mode: 'build' as const })) - if (!this.#capabilities.current.code) return OPERATOR_EXAMPLES - if (this.#count === 0) return BUILD_EXAMPLES - return [...USE_EXAMPLES, ...BUILD_EXAMPLES.slice(0, 2)] + const signals = this.#currentSignals + const role = this.#role + return signals && role ? composerSuggestions(signals, role) : [] }) - /** Whether the workspace holds fewer than `FEW_ITEMS`; undefined until known. */ + /** Whether the workspace holds fewer than `FEW_ITEMS`, below which Home's composer rests + * open as the page's main way in; undefined until known. */ get fewItems(): boolean | undefined { - const count = this.#count + const count = this.#currentSignals?.itemCount return count === undefined ? undefined : count < FEW_ITEMS } } -const itemCounts = new Map() -const itemCountRequests = new Map>() +type Tagged = { tag: string; value: T } -/** Starts the count for a page about to mount the starter; the starter then takes this - * request rather than sending its own. */ -export function prefetchItemCount(workspace: string): void { - void workspaceItemCount(workspace) +/** Per account: the signals name the reader's private draft. A key is taken when a request + * starts, so one that settles after an account switch cannot answer for the next account; with + * no account known yet, nothing is cached. */ +const signalsKey = (workspace: string) => scopedKey(`composerSignals:${workspace}`) + +const settled = new Map() +const requests = new Map }>() +/** How long an answer is reused before a mount asks again: long enough to cover the prefetch + * that preceded the mount, short enough that returning to Home sees what changed. */ +const REUSE_MS = 30_000 + +/** Starts the reads for a page about to mount the starter; the starter then takes these + * requests rather than sending its own. */ +export function prefetchComposerSignals(workspace: string): void { + void readComposerSignals(workspace) } -function workspaceItemCount(workspace: string): Promise { - let request = itemCountRequests.get(workspace) - if (!request) { - request = fetchItemCount(workspace).finally(() => itemCountRequests.delete(workspace)) - itemCountRequests.set(workspace, request) - } - return request -} - -async function fetchItemCount(workspace: string): Promise { - let count = FEW_ITEMS +/** What the starter reads for `workspace`: one set of requests, shared by every caller and + * reused for `REUSE_MS`; a failure is not kept. */ +export async function readComposerSignals(workspace: string): Promise { + const key = signalsKey(workspace) try { + let request: Promise + const kept = key && requests.get(key) + if (kept && Date.now() - kept.at < REUSE_MS) request = kept.request + else { + request = fetchSignals(workspace) + if (key) { + requests.set(key, { at: Date.now(), request }) + request.catch(() => { + if (requests.get(key)?.request === request) requests.delete(key) + }) + } + } + const signals = await request + if (!key) return signals + // A request that outlived the reuse window can settle after the one that replaced it. + if (requests.get(key)?.request === request) settled.set(key, signals) + return settled.get(key) ?? signals + } catch (e) { + // Unknown reads as a full workspace: a collapsed composer is the quieter mistake. + console.error(`Could not list the items of workspace ${workspace}:`, e) + return { itemCount: FEW_ITEMS } + } +} + +async function fetchSignals(workspace: string): Promise { + // Read before the requests: a workspace switch while they are pending moves the user store + // to the next workspace's membership. + const member = get(userStore) + const user = member?.workspace_id === workspace ? member : undefined + const capabilities = get(roleCapabilities) + const [res, resources, dataTables] = await Promise.all([ // What Home's list counts: library scripts and the user's own drafts included. - const res = await ScriptService.listRunnables({ + ScriptService.listRunnables({ workspace, includeWithoutMain: true, includeDraftOnly: true, - perPage: FEW_ITEMS + orderBy: 'updated', + orderDesc: true, + perPage: ITEMS_READ + }), + readConnections(workspace), + readDataTables(workspace) + ]) + const items = res.items ?? [] + const deployed = items.filter((i) => !i.draft_only) + const username = user?.username + const draft = items.find( + (i) => + i.is_draft || + i.draft_only || + (username && i.draft_users?.some((u) => u['username'] === username)) + ) + const editable = (i: RunnableItem) => + canEditItem( + i.type === 'app' && i.raw_app ? 'raw_app' : i.type, + i.path, + i.extra_perms, + user, + capabilities + ) + const shared = deployed.find( + (i) => i.type === 'flow' && !(username && i.path.startsWith(`u/${username}/`)) + ) + // Only plain scripts run on their own: a library has no main function, a pipeline script + // runs as its pipeline, and test and preprocessor scripts serve another runnable. + const script = deployed.find( + (i) => + i.type === 'script' && (!i.auto_kind || i.auto_kind === 'script' || i.auto_kind === 'wac') + ) + const starred = deployed.find((i) => i.starred && (i.type === 'script' || i.type === 'flow')) + const pick = (item: RunnableItem | undefined) => item && composerItem(item) + const complete = resources !== undefined && resources.length < RESOURCES_READ + return { + itemCount: items.length, + myDraft: draft && composerItem(draft, draft.draft_path), + sharedFlow: pick(shared), + script: pick(script), + app: pick(deployed.find((i) => i.type === 'app' && i.raw_app && editable(i))), + agent: pick(deployed.find((i) => i.type === 'agent')), + folderItem: pick(deployed.find((i) => i.path.startsWith('f/'))), + favorite: pick(starred), + database: + resources && newest(resources.filter((r) => Object.hasOwn(DATABASE_TYPES, r.resource_type))), + channel: resources && (preferredChannel(resources) ?? (complete ? null : undefined)), + dataTables + } +} + +/** The workspace's databases and channels; unknown when the list fails, which fires none of + * the pills that read them. */ +async function readConnections(workspace: string): Promise { + try { + return await ResourceService.listResource({ + workspace, + resourceType: [...Object.keys(DATABASE_TYPES), ...Object.keys(CHANNEL_TYPES)].join(','), + perPage: RESOURCES_READ }) - count = res.items?.length ?? 0 } catch (e) { - // Unknown reads as a full workspace: a collapsed composer is the quieter mistake. - console.error(`Could not count the items of workspace ${workspace}:`, e) + console.error(`Could not list the connections of workspace ${workspace}:`, e) + return undefined + } +} + +/** The workspace's data table names, `main` (the one scripts use by default) first; unknown + * when the list fails. */ +async function readDataTables(workspace: string): Promise { + try { + const names = (await WorkspaceService.listDataTables({ workspace })).map((d) => d.name) + return names.includes('main') ? ['main', ...names.filter((n) => n !== 'main')] : names + } catch (e) { + console.error(`Could not list the data tables of workspace ${workspace}:`, e) + return undefined + } +} + +function preferredChannel(resources: ListableResource[]): ComposerResource | undefined { + for (const type of Object.keys(CHANNEL_TYPES)) { + const channel = newest(resources.filter((r) => r.resource_type === type)) + if (channel) return channel + } + return undefined +} + +function newest(resources: ListableResource[]): ComposerResource | undefined { + const r = resources.reduce( + (a, b) => (!a || (b.edited_at ?? '') > (a.edited_at ?? '') ? b : a), + undefined + ) + return r?.path && r.resource_type + ? { type: r.resource_type, path: r.path, name: r.path.split('/').pop() || r.path } + : undefined +} + +function composerItem(item: RunnableItem, path = item.path): ComposerItem { + return { + kind: item.type, + path, + name: item.summary || path.split('/').pop() || path } - itemCounts.set(workspace, count) - return count } /** What turns an empty chat into the block that starts a session. */ diff --git a/frontend/src/lib/components/copilot/chat/starter/starterPrompts.test.ts b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.test.ts new file mode 100644 index 0000000000..62713dccd9 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const account = vi.hoisted(() => ({ email: 'ada@example.com' as string | undefined })) +const listRunnables = vi.hoisted(() => vi.fn()) +const listResource = vi.hoisted(() => vi.fn()) +const listDataTables = vi.hoisted(() => vi.fn()) + +vi.mock('$lib/userScopedStorage', () => ({ + scopedKey: (base: string) => (account.email ? `${base}::${account.email}` : undefined) +})) +vi.mock('$lib/onboardingProfile', () => ({ onboardingProfile: async () => undefined })) +vi.mock('$lib/gen', () => ({ + ScriptService: { listRunnables }, + ResourceService: { listResource }, + WorkspaceService: { listDataTables } +})) + +import { readComposerSignals } from './starterPrompts.svelte' + +const draftOf = (owner: string) => ({ + items: [{ type: 'flow', path: `u/${owner}/secret_plan`, summary: '', is_draft: true }] +}) + +beforeEach(() => { + listRunnables.mockReset() + listResource.mockReset() + listResource.mockResolvedValue([]) + listDataTables.mockReset() + listDataTables.mockResolvedValue([]) +}) + +describe('readComposerSignals', () => { + it("never answers one account's signals for another", async () => { + listRunnables.mockResolvedValueOnce(draftOf('ada')) + expect((await readComposerSignals('acme')).myDraft?.path).toBe('u/ada/secret_plan') + + // Another account in the same browser, well inside the reuse window. + account.email = 'bob@example.com' + listRunnables.mockResolvedValueOnce({ items: [] }) + expect((await readComposerSignals('acme')).myDraft).toBeUndefined() + expect(listRunnables).toHaveBeenCalledTimes(2) + }) + + it('picks the newest database and the preferred channel', async () => { + listRunnables.mockResolvedValueOnce({ items: [] }) + listResource.mockResolvedValueOnce([ + { path: 'f/mail/smtp', resource_type: 'smtp', edited_at: '2026-10-03' }, + { path: 'f/data/old_db', resource_type: 'postgresql', edited_at: '2026-01-01' }, + { path: 'f/team/slack', resource_type: 'slack', edited_at: '2026-02-01' }, + { path: 'f/data/main_db', resource_type: 'mysql', edited_at: '2026-09-01' } + ]) + listDataTables.mockResolvedValueOnce([{ name: 'analytics' }, { name: 'main' }]) + const signals = await readComposerSignals('globex') + expect(signals.database).toEqual({ type: 'mysql', path: 'f/data/main_db', name: 'main_db' }) + expect(signals.channel?.path).toBe('f/team/slack') + expect(signals.dataTables).toEqual(['main', 'analytics']) + }) + + it('tells a list that holds nothing from one that failed or was cut off', async () => { + listRunnables.mockResolvedValueOnce({ items: [] }) + listDataTables.mockRejectedValueOnce(new Error('offline')) + const signals = await readComposerSignals('initech') + expect(signals.channel).toBeNull() + expect(signals.dataTables).toBeUndefined() + + // A full page of databases may have pushed the channel past it. + listRunnables.mockResolvedValueOnce({ items: [] }) + listResource.mockResolvedValueOnce( + Array.from({ length: 20 }, (_, i) => ({ path: `u/ada/db_${i}`, resource_type: 'postgresql' })) + ) + expect((await readComposerSignals('hooli')).channel).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/home/HomeAIChat.svelte b/frontend/src/lib/components/home/HomeAIChat.svelte index 0aad0adb1a..9d5247081e 100644 --- a/frontend/src/lib/components/home/HomeAIChat.svelte +++ b/frontend/src/lib/components/home/HomeAIChat.svelte @@ -32,7 +32,7 @@ import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' - import { prefetchItemCount } from '../copilot/chat/starter/starterPrompts.svelte' + import { prefetchComposerSignals } from '../copilot/chat/starter/starterPrompts.svelte' import { useWorkspaceAiHidden } from '../copilot/workspaceAiHidden.svelte' import { homeQuickAccessSettings } from './homeQuickAccessSettings.svelte' @@ -98,9 +98,10 @@ let HomeSessionStarter = $state(loadedStarter) if (!loadedStarter) void loadStarter().then((c) => (HomeSessionStarter = c)) - // The starter waits on the workspace's item count before it mounts; asked alongside its code - // rather than once the code has loaded, it is no extra wait. - if ($workspaceStore) prefetchItemCount($workspaceStore) + // The starter waits on the workspace's item count before it mounts, and its suggestions on + // the other signals; asked alongside its code rather than once the code has loaded, they + // are no extra wait. + if ($workspaceStore) prefetchComposerSignals($workspaceStore) // Whether Home's own workspace hides the assistant, read for that workspace: once the block // shows, the shared copilot config is the draft's, so a draft acting on a workspace that hides diff --git a/frontend/src/routes/(root)/(logged)/dev/composer-suggestions/+page.svelte b/frontend/src/routes/(root)/(logged)/dev/composer-suggestions/+page.svelte new file mode 100644 index 0000000000..7053fa8d3f --- /dev/null +++ b/frontend/src/routes/(root)/(logged)/dev/composer-suggestions/+page.svelte @@ -0,0 +1,364 @@ + + +{#if import.meta.env.DEV} +
    +
    +

    Composer suggestions

    +

    + The pills composerSuggestions(signals, role) returns. A blank path means no such + item. Invitation prompts, which replace all of these, are not simulated. +

    +
    + +
    +
    +
    +

    Role

    + + {#snippet children({ item })} + + + + + + {/snippet} + +

    An instance admin here is also a workspace admin.

    +
    + +
    +

    Load a real workspace

    +
    + + +
    +
    +
    + Channel (type and path) +
    + \n\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of four types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript)\n\nWhen `type` is `script`, `flow`, or `hubscript`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub///`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream.\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable): Promise\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step(name: string, fn: () => T | Promise,): Promise>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow(fn: (...args: any[]) => Promise): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel(items: T[], fn: (item: T) => PromiseLike | R, options?: { concurrency?: number },): Promise\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit,): SqlStatement\n", - "app.python3": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u//` for bare names; only use `f//` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend//main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the Python SDK, for `python3` inline runnables. For a `bun` runnable, call `get_instructions` again with `subject: \"app\"` and no language.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `
    ` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render()\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**Set the browser tab title with `document.title = '...'`** (or a `` 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.\n\n**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.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of four types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript)\n\nWhen `type` is `script`, `flow`, or `hubscript`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream.\n\n\n# Python SDK (wmill)\n\nImport: import wmill\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe functions below are the surface to prefer. For an endpoint none of them covers,\nwmill.Windmill().get(endpoint) and .post(endpoint) issue an authenticated request against this\ninstance. What does not exist is a function name you guessed at: if it is not listed below, do\nnot call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`os.environ.get(\"WM_END_USER_EMAIL\") or os.environ.get(\"WM_EMAIL\")`. WM_END_USER_EMAIL is the app\nviewer when the run was triggered from an app and empty otherwise (both variables are always\ndefined), WM_EMAIL is the user the job is permissioned as. WM_USERNAME is the matching username.\n\ndef worker_has_internal_server() -> bool\n\ndef get_mocked_api() -> Optional[dict]\n\n# Get the HTTP client instance.\n# \n# Returns:\n# Configured httpx.Client for API requests\ndef get_client() -> httpx.Client\n\n# Make an HTTP GET request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Make an HTTP POST request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.post\n# \n# Returns:\n# HTTP response object\ndef post(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Create a new authentication token.\n# \n# Args:\n# duration: Token validity duration (default: 1 day)\n# \n# Returns:\n# New authentication token string\ndef create_token(duration = dt.timedelta(days=1)) -> str\n\n# Create a script job by path and return its job id.\n# \n# ``retry`` re-runs the job when it fails, with the policy a schedule takes,\n# e.g. ``{\"constant\": {\"attempts\": 3, \"seconds\": 10}}``. The returned id is\n# the first attempt's; each retry is a job of its own, recorded as a child of it.\ndef run_script_by_path_async(path: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a script job by hash and return its job id. See ``run_script_by_path_async`` for ``retry``.\ndef run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a flow job and return its job id.\ndef run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str\n\n# Run script by path synchronously and return its result.\ndef run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run script by hash synchronously and return its result.\ndef run_script_by_hash(hash_: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run a script on the current worker without creating a job.\n# \n# On agent workers (no internal server), falls back to running a normal\n# preview job and waiting for the result.\ndef run_inline_script_preview(content: str, language: str, args: dict = None) -> Any\n\n# Wait for a job to complete and return its result.\n# \n# Args:\n# job_id: ID of the job to wait for\n# timeout: Maximum time to wait (seconds or timedelta)\n# verbose: Enable verbose logging\n# cleanup: Register cleanup handler to cancel job on exit\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result when completed\n# \n# Raises:\n# TimeoutError: If timeout is reached\n# Exception: If job fails\ndef wait_job(job_id, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False)\n\n# Cancel a specific job by ID.\n# \n# Args:\n# job_id: UUID of the job to cancel\n# reason: Optional reason for cancellation\n# \n# Returns:\n# Response message from the cancel endpoint\ndef cancel_job(job_id: str, reason: str = None) -> str\n\n# Cancel currently running executions of the same script.\ndef cancel_running() -> dict\n\n# Get job details by ID.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job details dictionary\ndef get_job(job_id: str) -> dict\n\n# Get the root job ID for a flow hierarchy.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Root job ID\ndef get_root_job_id(job_id: str | None = None) -> dict\n\n# Get an OIDC JWT token for authentication to external services.\n# \n# Args:\n# audience: Token audience (e.g., \"vault\", \"aws\")\n# expires_in: Optional expiration time in seconds\n# \n# Returns:\n# JWT token string\ndef get_id_token(audience: str, expires_in: int | None = None) -> str\n\n# Get the status of a job.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job status: \"RUNNING\", \"WAITING\", or \"COMPLETED\"\ndef get_job_status(job_id: str) -> JobStatus\n\n# Get the result of a completed job.\n# \n# Args:\n# job_id: UUID of the completed job\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result\ndef get_result(job_id: str, assert_result_is_not_none: bool = True) -> Any\n\n# Get a variable value by path.\n# \n# Args:\n# path: Variable path in Windmill\n# \n# Returns:\n# Variable value as string\ndef get_variable(path: str) -> str\n\n# Set a variable value by path, creating it if it doesn't exist.\n# \n# Args:\n# path: Variable path in Windmill\n# value: Variable value to set\n# is_secret: Whether the variable should be secret (default: False)\ndef set_variable(path: str, value: str, is_secret: bool = False) -> None\n\n# Get a resource value by path.\n# \n# Args:\n# path: Resource path in Windmill\n# none_if_undefined: Return None instead of raising if not found\n# interpolated: if variables and resources are fully unrolled\n# \n# Returns:\n# Resource value dictionary or None\ndef get_resource(path: str, none_if_undefined: bool = False, interpolated: bool = True) -> dict | None\n\n# Set a resource value by path, creating it if it doesn't exist.\n# \n# Args:\n# value: Resource value to set\n# path: Resource path in Windmill\n# resource_type: Resource type for creation\ndef set_resource(value: Any, path: str, resource_type: str)\n\n# List resources from Windmill workspace.\n# \n# Args:\n# resource_type: Optional resource type to filter by (e.g., \"postgresql\", \"mysql\", \"s3\")\n# page: Optional page number for pagination\n# per_page: Optional number of results per page\n# \n# Returns:\n# List of resource dictionaries\ndef list_resources(resource_type: str = None, page: int = None, per_page: int = None) -> list[dict]\n\n# Set the workflow state.\n# \n# Args:\n# value: State value to set\n# path: Optional state resource path override.\ndef set_state(value: Any, path: str | None = None) -> None\n\n# Get the workflow state.\n# \n# Args:\n# path: Optional state resource path override.\n# \n# Returns:\n# State value or None if not set\ndef get_state(path: str | None = None) -> Any\n\n# Set job progress percentage (0-99).\n# \n# Args:\n# value: Progress percentage\n# job_id: Job ID (defaults to current WM_JOB_ID)\ndef set_progress(value: int, job_id: Optional[str] = None)\n\n# Get job progress percentage.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Progress value (0-100) or None if not set\ndef get_progress(job_id: Optional[str] = None) -> Any\n\n# Whether the worker running the job has received its shutdown signal.\n# \n# A draining worker waits for its current job to finish before exiting. A long-running\n# script can poll this and return early so the worker can be replaced.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# True if the worker running the job is draining\ndef worker_is_draining(job_id: Optional[str] = None) -> bool\n\n# Set the user state of a flow at a given key\ndef set_flow_user_state(key: str, value: Any) -> None\n\n# Get the user state of a flow at a given key\ndef get_flow_user_state(key: str) -> Any\n\n# Get the Windmill server version.\n# \n# Returns:\n# Version string\ndef version()\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy\n# serves object reads, writes, deletes, listing and multipart uploads of that bucket only;\n# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials,\n# which passing the resource path returns.\ndef get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Load a file from the workspace s3 bucket and returns its content as bytes.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# my_obj_content = client.load_s3_file(s3_obj)\n# file_content = my_obj_content.decode(\"utf-8\")\n# '''\ndef load_s3_file(s3object: S3Object | str, s3_resource_path: str | None) -> bytes\n\n# Load a file from the workspace s3 bucket and returns the bytes stream.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# with wmill.load_s3_file_reader(s3object, s3_resource_path) as file_reader:\n# print(file_reader.read())\n# '''\ndef load_s3_file_reader(s3object: S3Object | str, s3_resource_path: str | None) -> BufferedReader\n\n# Write a file to the workspace S3 bucket\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# \n# # for an in memory bytes array:\n# file_content = b'Hello Windmill!'\n# client.write_s3_file(s3_obj, file_content)\n# \n# # for a file:\n# with open(\"my_file.txt\", \"rb\") as my_file:\n# client.write_s3_file(s3_obj, my_file)\n# '''\ndef write_s3_file(s3object: S3Object | str | None, file_content: BufferedReader | bytes, s3_resource_path: str | None, content_type: str | None = None, content_disposition: str | None = None) -> S3Object\n\n# Permanently delete a file from the workspace S3 bucket.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# client.delete_s3_object(s3_obj)\n# '''\ndef delete_s3_object(s3object: S3Object | str, s3_resource_path: str | None = None) -> None\n\n# Sign S3 objects for use by anonymous users in public apps.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed S3 objects\ndef sign_s3_objects(s3_objects: list[S3Object | str], expiry_secs: int | None = None) -> list[S3Object]\n\n# Sign a single S3 object for use by anonymous users in public apps.\n# \n# Args:\n# s3_object: S3 object to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed S3 object\ndef sign_s3_object(s3_object: S3Object | str, expiry_secs: int | None = None) -> S3Object\n\n# Generate presigned public URLs for an array of S3 objects.\n# If an S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# base_url: Optional base URL for the presigned URLs (defaults to WM_BASE_URL)\n# expiry_secs: How long the signatures stay valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed public URLs\n# \n# Example:\n# >>> s3_objs = [S3Object(s3=\"/path/to/file1.txt\"), S3Object(s3=\"/path/to/file2.txt\")]\n# >>> urls = client.get_presigned_s3_public_urls(s3_objs)\ndef get_presigned_s3_public_urls(s3_objects: list[S3Object | str], base_url: str | None = None, expiry_secs: int | None = None) -> list[str]\n\n# Generate a presigned public URL for an S3 object.\n# If the S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_object: S3 object to sign\n# base_url: Optional base URL for the presigned URL (defaults to WM_BASE_URL)\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed public URL\n# \n# Example:\n# >>> s3_obj = S3Object(s3=\"/path/to/file.txt\")\n# >>> url = client.get_presigned_s3_public_url(s3_obj)\ndef get_presigned_s3_public_url(s3_object: S3Object | str, base_url: str | None = None, expiry_secs: int | None = None) -> str\n\n# Get the current user information.\n# \n# Returns:\n# User details dictionary\ndef whoami() -> dict\n\n# Get the current user information (alias for whoami).\n# \n# Returns:\n# User details dictionary\ndef user() -> dict\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef state_path() -> str\n\n# Get the workflow state.\n# \n# Returns:\n# State value or None if not set\ndef state() -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state_pickle(value: Any, path: str = 'state.pickle') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state_pickle(path: str = 'state.pickle') -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state(value: Any, path: str = 'state.json') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state(path: str = 'state.json') -> None\n\n# Get URLs needed for resuming a flow after suspension.\n# \n# Args:\n# approver: Optional approver name\n# flow_level: If True, generate resume URLs for the parent flow instead of the\n# specific step. This allows pre-approvals that can be consumed by any later\n# suspend step in the same flow.\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_resume_urls(approver: str = None, flow_level: bool = None) -> dict\n\n# Get the resume URLs bound to one ``wait_for_approval`` step of this workflow.\n# \n# Args:\n# step_key: Checkpoint key of the approval step, as passed to\n# ``wait_for_approval(key=...)``\n# approver: Optional approver name\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_approval_urls(step_key: str = 'approval', approver: str = None) -> dict\n\n# Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n# \n# **[Enterprise Edition Only]** To include form fields in the Slack approval request, use the \"Advanced -> Suspend -> Form\" functionality.\n# Learn more at: https://www.windmill.dev/docs/flows/flow_approval#form\n# \n# :param slack_resource_path: The path to the Slack resource in Windmill.\n# :type slack_resource_path: str\n# :param channel_id: The Slack channel ID where the approval request will be sent.\n# :type channel_id: str\n# :param message: Optional custom message to include in the Slack approval request.\n# :type message: str, optional\n# :param approver: Optional user ID or name of the approver for the request.\n# :type approver: str, optional\n# :param default_args_json: Optional dictionary defining or overriding the default arguments for form fields.\n# :type default_args_json: dict, optional\n# :param dynamic_enums_json: Optional dictionary overriding the enum default values of enum form fields.\n# :type dynamic_enums_json: dict, optional\n# \n# :raises Exception: If the function is not called within a flow or flow preview.\n# :raises Exception: If the required flow job or flow step environment variables are not set.\n# \n# :return: None\n# \n# **Usage Example:**\n# >>> client.request_interactive_slack_approval(\n# ... slack_resource_path=\"/u/alex/my_slack_resource\",\n# ... channel_id=\"admins-slack-channel\",\n# ... message=\"Please approve this request\",\n# ... approver=\"approver123\",\n# ... default_args_json={\"key1\": \"value1\", \"key2\": 42},\n# ... dynamic_enums_json={\"foo\": [\"choice1\", \"choice2\"], \"bar\": [\"optionA\", \"optionB\"]},\n# ... )\n# \n# **Notes:**\n# - This function must be executed within a Windmill flow or flow preview.\n# - The function checks for required environment variables (`WM_FLOW_JOB_ID`, `WM_FLOW_STEP_ID`) to ensure it is run in the appropriate context.\ndef request_interactive_slack_approval(slack_resource_path: str, channel_id: str, message: str = None, approver: str = None, default_args_json: dict = None, dynamic_enums_json: dict = None) -> None\n\n# Send a message to a Microsoft Teams conversation with conversation_id, where success is used to style the message\ndef send_teams_message(conversation_id: str, text: str, success: bool = True, card_block: dict = None)\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# Only meaningful on a data table under roles, and only for a role you are a\n# tenant of.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None)\n\n# Get a DuckLake client for DuckDB queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# \n# Returns:\n# DucklakeClient instance\ndef ducklake(name: str = 'main')\n\ndef init_global_client(f)\n\ndef deprecate(in_favor_of: str)\n\n# Get the current workspace ID.\n# \n# Returns:\n# Workspace ID string\ndef get_workspace() -> str\n\ndef get_version() -> str\n\n# Create a script job and return its job ID.\n# \n# Args:\n# hash_or_path: Script hash or path (determined by presence of '/')\n# args: Script arguments\n# scheduled_in_secs: Delay before execution in seconds\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Job ID string\ndef run_script_async(hash_or_path: str, args: Dict[str, Any] = None, scheduled_in_secs: int = None, tag: str = None) -> str\n\n# Run a script synchronously by hash and return its result.\n# \n# Args:\n# hash: Script hash\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_sync(hash: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Run a script synchronously by path and return its result.\n# \n# Args:\n# path: Script path\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_by_path_sync(path: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB\ndef duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars\ndef polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3\ndef boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef get_state_path() -> str\n\n# Parse resource syntax from string.\ndef parse_resource_syntax(s: str) -> Optional[str]\n\n# Parse S3 object from a `s3://<storage>/<key>` URI string (`s3:///<key>`\n# for the default storage) or S3Object format. Any other string raises\n# rather than falling back to an auto-generated key: an auto key is\n# requested by omitting the object, and a fallback would silently misplace\n# the upload on any typo.\ndef parse_s3_object(s3_object: S3Object | str) -> S3Object\n\n# Parse variable syntax from string.\ndef parse_variable_syntax(s: str) -> Optional[str]\n\n# Append a text to the result stream.\n# \n# Args:\n# text: text to append to the result stream\ndef append_to_result_stream(text: str) -> None\n\n# Stream to the result stream.\n# \n# Args:\n# stream: stream to stream to the result stream\ndef stream_result(stream) -> None\n\n# Execute a SQL query against the DataTable.\n# \n# Args:\n# sql: SQL query string with $1, $2, etc. placeholders\n# *args: Positional arguments to bind to query placeholders\n# \n# Returns:\n# SqlQuery instance for fetching results\ndef query(sql: str, *args) -> SqlQuery\n\n# Idempotently materialize the rows of `select_sql` into ducklake\n# `table` for one `partition` (or the whole table when `partition` is\n# None). Client-side equivalent of the `// materialize` engine: with\n# `unique_key` it upserts within the slice (delete-by-key + insert);\n# without it, it replaces (whole table → CREATE OR REPLACE; partition →\n# delete the partition + insert). Re-running the same slice is safe — the\n# backfill / failure-recovery contract.\n# \n# The partition value is bound as a DuckDB arg (never string-interpolated)\n# so it cannot inject SQL. `select_sql` is trusted (your own query).\ndef upsert_partition(table: str, select_sql: str, partition: str = None, unique_key: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# INSERT-only materialization (no dedup / no replace) for an immutable\n# event-log table — for one `partition`, or the whole table when\n# `partition` is None. NOTE: unlike `upsert_partition`, re-running the same\n# slice duplicates rows — use only for append-only sources.\ndef append_partition(table: str, select_sql: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Read a materialized ducklake table, optionally a single partition.\ndef read(table: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Execute query and fetch results.\n# \n# Args:\n# result_collection: Optional result collection mode\n# \n# Returns:\n# Query results\ndef fetch(result_collection: str | None = None)\n\n# Execute query and fetch first row of results.\n# \n# Returns:\n# First row of query results\ndef fetch_one()\n\n# Execute query and fetch first row of results. Return result as a scalar value.\n# \n# Returns:\n# First row of query result as a scalar value\ndef fetch_one_scalar()\n\n# Execute query and don't return any results.\n# \ndef execute()\n\n# DuckDB executor requires explicit argument types at declaration\n# These types exist in both DuckDB and Postgres\n# Check that the types exist if you plan to extend this function for other SQL engines.\ndef infer_sql_type(value) -> str\n\ndef parse_sql_client_name(name: str) -> tuple[str, Optional[str]]\n\n# Decorator that marks a function as a workflow task.\n# \n# Works in both WAC v1 (sync, HTTP-based dispatch) and WAC v2\n# (async, checkpoint/replay) modes:\n# \n# - **v2 (inside @workflow)**: dispatches as a checkpoint step.\n# - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API.\n# - **Standalone, or called from inside another v2 task**: executes the\n# function body directly. A task runs as a single job, so the tasks it\n# calls run in that same job, without their own options.\n# \n# A task runs as its own job, so its result is always encoded as JSON and\n# decoded back before the caller sees it: a ``datetime`` comes back as a\n# string, a tuple as a list.\n# \n# ``retry`` re-dispatches the task after a failure, inside ``@workflow`` only.\n# Every attempt is a step of its own (``call_api``, ``call_api#2``, ...) and\n# the wait between two of them is a durable sleep, so a retrying task holds no\n# worker while it backs off. Keys: ``attempts`` (retries after the first\n# failure, a whole number from 0 to 100), ``delay`` (seconds before the first\n# retry, sub-second delays dropped), ``multiplier`` (applied to the delay\n# after each attempt, 1 keeps it constant), ``max_delay`` (ceiling in\n# seconds). ``attempts`` is required, and an out-of-range or unknown key is\n# rejected where the policy is written.\n# \n# A workflow sleeps once per round, so tasks backing off in the same fan-out\n# wait one after another rather than together: the delay before a fan-out\n# retries is the sum of every backoff pending in it, not the longest one, and\n# it grows with both the width of the fan-out and ``attempts``. Retries with\n# no ``delay`` all go out in a single round.\n# \n# ``cache_ttl`` serves a previous result of the task for that many seconds\n# instead of running it again. A task is keyed on its step key (its name and\n# call order) and the workflow's input, not on the arguments it is called\n# with, so cache one only when whether it runs, and what it receives, follow\n# from the workflow's input alone. A ``task_script`` target is keyed on the\n# arguments it is called with. It has no effect on a ``task_flow`` target,\n# which keeps its flow's own cache policy.\n# \n# Usage::\n# \n# @task\n# async def extract_data(url: str): ...\n# \n# @task(path=\"f/external_script\", timeout=600, tag=\"gpu\")\n# async def run_external(x: int): ...\n# \n# @task(retry={\"attempts\": 3, \"delay\": 30, \"multiplier\": 2})\n# async def call_api(payload: dict): ...\ndef task(_func = None, *, path: Optional[str] = None, tag: Optional[str] = None, timeout: Optional[int] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill script.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# extract = task_script(\"f/data/extract\", timeout=600)\n# \n# @workflow\n# async def main():\n# data = await extract(url=\"https://...\")\ndef task_script(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill flow.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# pipeline = task_flow(\"f/etl/pipeline\", priority=10)\n# \n# @workflow\n# async def main():\n# result = await pipeline(input=data)\ndef task_flow(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Decorator marking an async function as a workflow-as-code entry point.\n# \n# The function must be **deterministic**: given the same inputs it must call\n# tasks in the same order on every replay. Branching on task results is fine\n# (results are replayed from checkpoint), but branching on external state\n# (current time, random values, external API calls) must use ``step()`` to\n# checkpoint the value so replays see the same result.\ndef workflow(func)\n\n# Execute ``fn`` inline and checkpoint the result.\n# \n# On replay the cached value is returned without re-executing ``fn``.\n# Use for lightweight deterministic operations (timestamps, random IDs,\n# config reads) that should not incur the overhead of a child job.\n# \n# ``fn``'s result is encoded as JSON and decoded back before it is returned,\n# so the round that runs the body sees the same types every replay sees:\n# a ``datetime`` comes back as a string, a tuple as a list.\n# \n# Called from inside a task body, ``fn`` runs in place and nothing is\n# checkpointed: a task is a single job and is never replayed.\nasync def step(name: str, fn)\n\n# Server-side sleep — suspend the workflow for the given duration without holding a worker.\n# \n# Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``.\n# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``.\nasync def sleep(seconds: int)\n\n# Suspend the workflow and wait for an external approval.\n# \n# Pass ``key`` to name the step, then ``get_approval_urls(key)`` yields the URLs\n# that resume exactly this approval — route them through your own channel.\n# Without a key the steps are named ``approval``, ``approval_2``, ...\n# \n# Returns a dict with ``value`` (form data), ``approver``, and ``approved``.\n# \n# Args:\n# timeout: Approval timeout in seconds (default 1800).\n# form: Optional form schema for the approval page.\n# self_approval: Whether the user who triggered the flow can approve it (default True).\n# key: Optional checkpoint key naming this approval step.\n# skin: ``\"minimal\"`` shows approvers only the request (form and approve/reject)\n# instead of the detailed page with the workflow's details.\n# description: Shown to approvers above the form: a string, or a rich value such as\n# ``{\"markdown\": \"...\"}``.\n# \n# Example::\n# \n# urls = await step(\"urls\", lambda: get_approval_urls(\"manager\"))\n# await step(\"notify\", lambda: send_email(urls[\"resume\"], urls[\"cancel\"]))\n# result = await wait_for_approval(key=\"manager\", timeout=3600)\nasync def wait_for_approval(timeout: int = 1800, form: dict | None = None, self_approval: bool = True, key: str | None = None, skin: Literal['detailed', 'minimal'] | None = None, description: str | dict | None = None) -> dict\n\n# Process items in parallel with optional concurrency control.\n# \n# Each item is processed by calling ``fn(item)``, which should be a @task.\n# Items are dispatched in batches of ``concurrency`` (default: all at once).\n# \n# Example::\n# \n# @task\n# async def process(item: str):\n# ...\n# \n# results = await parallel(items, process, concurrency=5)\nasync def parallel(items, fn, *, concurrency: Optional[int] = None)\n\n# Commit Kafka offsets for a trigger with auto_commit disabled.\n# \n# Args:\n# trigger_path: Path to the Kafka trigger (from event['wm_trigger']['trigger_path'])\n# topic: Kafka topic name (from event['topic'])\n# partition: Partition number (from event['partition'])\n# offset: Message offset to commit (from event['offset'])\ndef commit_kafka_offsets(trigger_path: str, topic: str, partition: int, offset: int) -> None\n\n", + "resource": "# Global draft resource & variable instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- A resource draft is a workspace item: `{ type: 'resource', path, summary?, value, isDraft }`. `value` is a CreateResource body: `{ path, value, description?, resource_type, labels? }` where the inner `value` is the resource type's data shape.\n- Reading a variable returns `{ type: 'variable', path, summary?, isSecret, isDraft }` — never its value, secret or not. `isSecret` tells you whether the value is encrypted.\n- `write_variable` takes `{ path, value?, is_secret?, description?, is_oauth?, expires_at?, labels? }`. Creating a variable needs `value` and `is_secret`; editing one needs only the fields you are changing. Omitting `value` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any `value` you did not get from the user destroys it.\n- For secret fields in a resource value, create the variable with `write_variable` and `is_secret: true`, and deploy it before the resource (see \"Secrets\" in the reference below).\n- Reference formats inside resource values: `$var:g/all/name` (global), `$var:u/user/name` (user), `$var:f/folder/name` (folder). Reference another resource with `$res:path/to/resource`. The same strings are also how a resource or variable is passed as a run argument (see the run-argument rule in the resource reference below); what they are never valid as is a variable's own value.\n- Use `search_resource_types` to discover valid `resource_type` names and their JSON Schemas. Match the resource value to that schema.\n- For OAuth resources, the `is_oauth: true` flag is managed by Windmill's OAuth flow; global mode generally creates manual resources, not OAuth ones.\n\n# Windmill resource & variable reference\n\n# Windmill Resources\n\nResources store credentials and configuration for external services.\n\n## Resource Structure\n\n```json\n{\n \"value\": {\n \"host\": \"db.example.com\",\n \"port\": 5432,\n \"user\": \"admin\",\n \"password\": \"$var:g/all/db_password\",\n \"dbname\": \"production\"\n },\n \"description\": \"Production PostgreSQL database\",\n \"resource_type\": \"postgresql\"\n}\n```\n\n## Required Fields\n\n- `value` - Object containing the resource configuration\n- `resource_type` - Name of the resource type (e.g., \"postgresql\", \"slack\")\n\n## Agents\n\nAn agent, as the Agents page lists it, is a resource of type `ai_agent`. Its value holds the\nagent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by\nlinking its path.\n\n## Variable References\n\nReference variables in resource values:\n\n```json\n{\n \"value\": {\n \"api_key\": \"$var:g/all/api_key\",\n \"secret\": \"$var:u/admin/secret\"\n }\n}\n```\n\n**Reference formats:**\n- `$var:g/all/name` - Global variable\n- `$var:u/username/name` - User variable\n- `$var:f/folder/name` - Folder variable\n\n## Secrets\n\nNever put a secret (password, API key, token) inline in a resource value. Store it in a secret variable and reference that variable as `$var:<path>`.\n\n- `$var:<path>` is a reference, not a value: it resolves to the variable's value at run time. Never invent a value for a variable.\n- A resource that references a variable needs the variable to exist first, so create or deploy the variable before the resource.\n\n## Resource References\n\nReference other resources:\n\n```json\n{\n \"value\": {\n \"database\": \"$res:f/databases/postgres\"\n }\n}\n```\n\n## Passing a Resource or Variable as a Run Argument\n\nA script or flow argument typed as a resource (schema `format: resource-<type>`) is passed as\nthe **bare string** `$res:<path>` — the whole argument value. Same for a variable, with\n`$var:<path>`. This applies everywhere job arguments are supplied: `wmill script run/preview`,\n`wmill flow run/preview`, the `runScriptByPath` / `runFlowByPath` API, a schedule's `args`, a\ntrigger's configured static args.\n\n```json\n{\n \"db\": \"$res:f/databases/postgres_prod\",\n \"api_token\": \"$var:g/all/api_token\"\n}\n```\n\nThe reference is resolved when the job runs, under the job's run-as identity — the caller for an\nordinary run, but the configured principal for a schedule, a trigger, or a runnable set to run on\nbehalf of someone else. The run fails if that identity cannot read the referenced resource or\nvariable.\n\n**Never wrap it in an object.** The resolver only rewrites a JSON value that *is* a string\nstarting with `$res:` / `$var:`; keys are never inspected. These are all wrong and are passed\nthrough to the script unchanged:\n\n```json\n{ \"db\": { \"$res\": \"f/databases/postgres_prod\" } }\n{ \"db\": { \"resource\": \"f/databases/postgres_prod\" } }\n{ \"db\": \"f/databases/postgres_prod\" }\n```\n\nThe string may sit anywhere a string can — a top-level argument, a nested object field\n(`{ \"gh_auth\": { \"token\": \"$var:g/all/gh_token\" } }`), or an array element (array elements are\nwalked only while nested at most two levels deep, and only for arrays of at most 1000 items).\nThe prefix must be on the string itself.\n\n## Common Resource Types\n\n### PostgreSQL\n```json\n{\n \"resource_type\": \"postgresql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"user\": \"postgres\",\n \"password\": \"$var:g/all/pg_password\",\n \"dbname\": \"windmill\",\n \"sslmode\": \"prefer\"\n }\n}\n```\n\n### MySQL\n```json\n{\n \"resource_type\": \"mysql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"$var:g/all/mysql_password\",\n \"database\": \"myapp\"\n }\n}\n```\n\n### Slack\n```json\n{\n \"resource_type\": \"slack\",\n \"value\": {\n \"token\": \"$var:g/all/slack_token\"\n }\n}\n```\n\n### AWS S3\n```json\n{\n \"resource_type\": \"s3\",\n \"value\": {\n \"bucket\": \"my-bucket\",\n \"region\": \"us-east-1\",\n \"accessKeyId\": \"$var:g/all/aws_access_key\",\n \"secretAccessKey\": \"$var:g/all/aws_secret_key\"\n }\n}\n```\n\n### HTTP/API\n```json\n{\n \"resource_type\": \"http\",\n \"value\": {\n \"baseUrl\": \"https://api.example.com\",\n \"headers\": {\n \"Authorization\": \"Bearer $var:g/all/api_token\"\n }\n }\n}\n```\n\n### Kafka\n```json\n{\n \"resource_type\": \"kafka\",\n \"value\": {\n \"brokers\": \"broker1:9092,broker2:9092\",\n \"sasl_mechanism\": \"PLAIN\",\n \"security_protocol\": \"SASL_SSL\",\n \"username\": \"$var:g/all/kafka_user\",\n \"password\": \"$var:g/all/kafka_password\"\n }\n}\n```\n\n### NATS\n```json\n{\n \"resource_type\": \"nats\",\n \"value\": {\n \"servers\": [\"nats://localhost:4222\"],\n \"user\": \"$var:g/all/nats_user\",\n \"password\": \"$var:g/all/nats_password\"\n }\n}\n```\n\n### MQTT\n```json\n{\n \"resource_type\": \"mqtt\",\n \"value\": {\n \"host\": \"mqtt.example.com\",\n \"port\": 8883,\n \"username\": \"$var:g/all/mqtt_user\",\n \"password\": \"$var:g/all/mqtt_password\",\n \"tls\": true\n }\n}\n```\n\n## When No Resource Type Fits\n\nThe Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service:\n\n- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both.\n- Otherwise, or when the user prefers it to syncing, propose a custom resource type named `c_<name>` holding the service's connection fields (base URL, account or region identifiers, credentials), as in \"Custom Resource Types\" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields.\n- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references.\n\n## Custom Resource Types\n\nA custom type's name starts with `c_`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: `format: resource-c_custom_api`, `RT.CCustomApi` in TypeScript, a `c_custom_api` TypedDict in Python.\n\nCreate custom resource types with JSON Schema:\n\n```json\n{\n \"name\": \"c_custom_api\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"base_url\": {\"type\": \"string\", \"format\": \"uri\"},\n \"api_key\": {\"type\": \"string\"},\n \"timeout\": {\"type\": \"integer\", \"default\": 30}\n },\n \"required\": [\"base_url\", \"api_key\"]\n },\n \"description\": \"Custom API connection\"\n}\n```\n\nSave as: `c_custom_api.resource-type.json`\n\n## OAuth Resources\n\nOAuth resources are managed through the Windmill UI and marked:\n\n```json\n{\n \"is_oauth\": true,\n \"account\": 123\n}\n```\n\nOAuth tokens are automatically refreshed by Windmill.\n\n## Using Resources in Scripts\n\n### TypeScript (Bun/Deno)\n```typescript\nexport async function main(db: RT.Postgresql) {\n // db contains the resource values\n const { host, port, user, password, dbname } = db;\n}\n```\n\n### Python\n```python\nclass postgresql(TypedDict):\n host: str\n port: int\n user: str\n password: str\n dbname: str\n\ndef main(db: postgresql):\n # db contains the resource values\n pass\n```\n\n", + "app": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u/<current-user>/<name>` for bare names; only use `f/<folder>/<name>` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend/<key>/main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the TypeScript SDK. For a `python3` runnable, call `get_instructions` again with `subject: \"app\"` and `language: \"python3\"`.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id=\"root\">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**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.\n\n**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.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise<string>\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable<string>): Promise<void>\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise<any>\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise<any>\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise<any>\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise<string>\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string>\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise<any>\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise<void>\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise<void>\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise<void>\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise<number | null>\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise<boolean>\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise<void>\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise<any>\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise<any>\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise<string>\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise<void>\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise<string>\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise<DenoS3LightClientSettings>\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Uint8Array | undefined>\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Blob | undefined>\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise<S3Object>\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise<void>\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object[]>\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object>\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string[]>\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string>\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise<string>\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise<void>} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise<void>\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise<void>} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise<void>\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise<void>\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow<T>(fn: (...args: any[]) => Promise<T>): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel<T, R>(items: T[], fn: (item: T) => PromiseLike<R> | R, options?: { concurrency?: number },): Promise<R[]>\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise<void>\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement<any>\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit<DucklakeMaterializeOptions, \"uniqueKey\">,): SqlStatement<any>\n", + "app.python3": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u/<current-user>/<name>` for bare names; only use `f/<folder>/<name>` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend/<key>/main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the Python SDK, for `python3` inline runnables. For a `bun` runnable, call `get_instructions` again with `subject: \"app\"` and no language.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id=\"root\">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**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.\n\n**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.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# Python SDK (wmill)\n\nImport: import wmill\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe functions below are the surface to prefer. For an endpoint none of them covers,\nwmill.Windmill().get(endpoint) and .post(endpoint) issue an authenticated request against this\ninstance. What does not exist is a function name you guessed at: if it is not listed below, do\nnot call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`os.environ.get(\"WM_END_USER_EMAIL\") or os.environ.get(\"WM_EMAIL\")`. WM_END_USER_EMAIL is the app\nviewer when the run was triggered from an app and empty otherwise (both variables are always\ndefined), WM_EMAIL is the user the job is permissioned as. WM_USERNAME is the matching username.\n\ndef worker_has_internal_server() -> bool\n\ndef get_mocked_api() -> Optional[dict]\n\n# Get the HTTP client instance.\n# \n# Returns:\n# Configured httpx.Client for API requests\ndef get_client() -> httpx.Client\n\n# Make an HTTP GET request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Make an HTTP POST request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.post\n# \n# Returns:\n# HTTP response object\ndef post(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Create a new authentication token.\n# \n# Args:\n# duration: Token validity duration (default: 1 day)\n# \n# Returns:\n# New authentication token string\ndef create_token(duration = dt.timedelta(days=1)) -> str\n\n# Create a script job by path and return its job id.\n# \n# ``retry`` re-runs the job when it fails, with the policy a schedule takes,\n# e.g. ``{\"constant\": {\"attempts\": 3, \"seconds\": 10}}``. The returned id is\n# the first attempt's; each retry is a job of its own, recorded as a child of it.\ndef run_script_by_path_async(path: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a script job by hash and return its job id. See ``run_script_by_path_async`` for ``retry``.\ndef run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a flow job and return its job id.\ndef run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str\n\n# Run script by path synchronously and return its result.\ndef run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run script by hash synchronously and return its result.\ndef run_script_by_hash(hash_: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run a script on the current worker without creating a job.\n# \n# On agent workers (no internal server), falls back to running a normal\n# preview job and waiting for the result.\ndef run_inline_script_preview(content: str, language: str, args: dict = None) -> Any\n\n# Wait for a job to complete and return its result.\n# \n# Args:\n# job_id: ID of the job to wait for\n# timeout: Maximum time to wait (seconds or timedelta)\n# verbose: Enable verbose logging\n# cleanup: Register cleanup handler to cancel job on exit\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result when completed\n# \n# Raises:\n# TimeoutError: If timeout is reached\n# Exception: If job fails\ndef wait_job(job_id, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False)\n\n# Cancel a specific job by ID.\n# \n# Args:\n# job_id: UUID of the job to cancel\n# reason: Optional reason for cancellation\n# \n# Returns:\n# Response message from the cancel endpoint\ndef cancel_job(job_id: str, reason: str = None) -> str\n\n# Cancel currently running executions of the same script.\ndef cancel_running() -> dict\n\n# Get job details by ID.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job details dictionary\ndef get_job(job_id: str) -> dict\n\n# Get the root job ID for a flow hierarchy.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Root job ID\ndef get_root_job_id(job_id: str | None = None) -> dict\n\n# Get an OIDC JWT token for authentication to external services.\n# \n# Args:\n# audience: Token audience (e.g., \"vault\", \"aws\")\n# expires_in: Optional expiration time in seconds\n# \n# Returns:\n# JWT token string\ndef get_id_token(audience: str, expires_in: int | None = None) -> str\n\n# Get the status of a job.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job status: \"RUNNING\", \"WAITING\", or \"COMPLETED\"\ndef get_job_status(job_id: str) -> JobStatus\n\n# Get the result of a completed job.\n# \n# Args:\n# job_id: UUID of the completed job\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result\ndef get_result(job_id: str, assert_result_is_not_none: bool = True) -> Any\n\n# Get a variable value by path.\n# \n# Args:\n# path: Variable path in Windmill\n# \n# Returns:\n# Variable value as string\ndef get_variable(path: str) -> str\n\n# Set a variable value by path, creating it if it doesn't exist.\n# \n# Args:\n# path: Variable path in Windmill\n# value: Variable value to set\n# is_secret: Whether the variable should be secret (default: False)\ndef set_variable(path: str, value: str, is_secret: bool = False) -> None\n\n# Get a resource value by path.\n# \n# Args:\n# path: Resource path in Windmill\n# none_if_undefined: Return None instead of raising if not found\n# interpolated: if variables and resources are fully unrolled\n# \n# Returns:\n# Resource value dictionary or None\ndef get_resource(path: str, none_if_undefined: bool = False, interpolated: bool = True) -> dict | None\n\n# Set a resource value by path, creating it if it doesn't exist.\n# \n# Args:\n# value: Resource value to set\n# path: Resource path in Windmill\n# resource_type: Resource type for creation\ndef set_resource(value: Any, path: str, resource_type: str)\n\n# List resources from Windmill workspace.\n# \n# Args:\n# resource_type: Optional resource type to filter by (e.g., \"postgresql\", \"mysql\", \"s3\")\n# page: Optional page number for pagination\n# per_page: Optional number of results per page\n# \n# Returns:\n# List of resource dictionaries\ndef list_resources(resource_type: str = None, page: int = None, per_page: int = None) -> list[dict]\n\n# Set the workflow state.\n# \n# Args:\n# value: State value to set\n# path: Optional state resource path override.\ndef set_state(value: Any, path: str | None = None) -> None\n\n# Get the workflow state.\n# \n# Args:\n# path: Optional state resource path override.\n# \n# Returns:\n# State value or None if not set\ndef get_state(path: str | None = None) -> Any\n\n# Set job progress percentage (0-99).\n# \n# Args:\n# value: Progress percentage\n# job_id: Job ID (defaults to current WM_JOB_ID)\ndef set_progress(value: int, job_id: Optional[str] = None)\n\n# Get job progress percentage.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Progress value (0-100) or None if not set\ndef get_progress(job_id: Optional[str] = None) -> Any\n\n# Whether the worker running the job has received its shutdown signal.\n# \n# A draining worker waits for its current job to finish before exiting. A long-running\n# script can poll this and return early so the worker can be replaced.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# True if the worker running the job is draining\ndef worker_is_draining(job_id: Optional[str] = None) -> bool\n\n# Set the user state of a flow at a given key\ndef set_flow_user_state(key: str, value: Any) -> None\n\n# Get the user state of a flow at a given key\ndef get_flow_user_state(key: str) -> Any\n\n# Get the Windmill server version.\n# \n# Returns:\n# Version string\ndef version()\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy\n# serves object reads, writes, deletes, listing and multipart uploads of that bucket only;\n# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials,\n# which passing the resource path returns.\ndef get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Load a file from the workspace s3 bucket and returns its content as bytes.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# my_obj_content = client.load_s3_file(s3_obj)\n# file_content = my_obj_content.decode(\"utf-8\")\n# '''\ndef load_s3_file(s3object: S3Object | str, s3_resource_path: str | None) -> bytes\n\n# Load a file from the workspace s3 bucket and returns the bytes stream.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# with wmill.load_s3_file_reader(s3object, s3_resource_path) as file_reader:\n# print(file_reader.read())\n# '''\ndef load_s3_file_reader(s3object: S3Object | str, s3_resource_path: str | None) -> BufferedReader\n\n# Write a file to the workspace S3 bucket\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# \n# # for an in memory bytes array:\n# file_content = b'Hello Windmill!'\n# client.write_s3_file(s3_obj, file_content)\n# \n# # for a file:\n# with open(\"my_file.txt\", \"rb\") as my_file:\n# client.write_s3_file(s3_obj, my_file)\n# '''\ndef write_s3_file(s3object: S3Object | str | None, file_content: BufferedReader | bytes, s3_resource_path: str | None, content_type: str | None = None, content_disposition: str | None = None) -> S3Object\n\n# Permanently delete a file from the workspace S3 bucket.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# client.delete_s3_object(s3_obj)\n# '''\ndef delete_s3_object(s3object: S3Object | str, s3_resource_path: str | None = None) -> None\n\n# Sign S3 objects for use by anonymous users in public apps.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed S3 objects\ndef sign_s3_objects(s3_objects: list[S3Object | str], expiry_secs: int | None = None) -> list[S3Object]\n\n# Sign a single S3 object for use by anonymous users in public apps.\n# \n# Args:\n# s3_object: S3 object to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed S3 object\ndef sign_s3_object(s3_object: S3Object | str, expiry_secs: int | None = None) -> S3Object\n\n# Generate presigned public URLs for an array of S3 objects.\n# If an S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# base_url: Optional base URL for the presigned URLs (defaults to WM_BASE_URL)\n# expiry_secs: How long the signatures stay valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed public URLs\n# \n# Example:\n# >>> s3_objs = [S3Object(s3=\"/path/to/file1.txt\"), S3Object(s3=\"/path/to/file2.txt\")]\n# >>> urls = client.get_presigned_s3_public_urls(s3_objs)\ndef get_presigned_s3_public_urls(s3_objects: list[S3Object | str], base_url: str | None = None, expiry_secs: int | None = None) -> list[str]\n\n# Generate a presigned public URL for an S3 object.\n# If the S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_object: S3 object to sign\n# base_url: Optional base URL for the presigned URL (defaults to WM_BASE_URL)\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed public URL\n# \n# Example:\n# >>> s3_obj = S3Object(s3=\"/path/to/file.txt\")\n# >>> url = client.get_presigned_s3_public_url(s3_obj)\ndef get_presigned_s3_public_url(s3_object: S3Object | str, base_url: str | None = None, expiry_secs: int | None = None) -> str\n\n# Get the current user information.\n# \n# Returns:\n# User details dictionary\ndef whoami() -> dict\n\n# Get the current user information (alias for whoami).\n# \n# Returns:\n# User details dictionary\ndef user() -> dict\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef state_path() -> str\n\n# Get the workflow state.\n# \n# Returns:\n# State value or None if not set\ndef state() -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state_pickle(value: Any, path: str = 'state.pickle') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state_pickle(path: str = 'state.pickle') -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state(value: Any, path: str = 'state.json') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state(path: str = 'state.json') -> None\n\n# Get URLs needed for resuming a flow after suspension.\n# \n# Args:\n# approver: Optional approver name\n# flow_level: If True, generate resume URLs for the parent flow instead of the\n# specific step. This allows pre-approvals that can be consumed by any later\n# suspend step in the same flow.\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_resume_urls(approver: str = None, flow_level: bool = None) -> dict\n\n# Get the resume URLs bound to one ``wait_for_approval`` step of this workflow.\n# \n# Args:\n# step_key: Checkpoint key of the approval step, as passed to\n# ``wait_for_approval(key=...)``\n# approver: Optional approver name\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_approval_urls(step_key: str = 'approval', approver: str = None) -> dict\n\n# Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n# \n# **[Enterprise Edition Only]** To include form fields in the Slack approval request, use the \"Advanced -> Suspend -> Form\" functionality.\n# Learn more at: https://www.windmill.dev/docs/flows/flow_approval#form\n# \n# :param slack_resource_path: The path to the Slack resource in Windmill.\n# :type slack_resource_path: str\n# :param channel_id: The Slack channel ID where the approval request will be sent.\n# :type channel_id: str\n# :param message: Optional custom message to include in the Slack approval request.\n# :type message: str, optional\n# :param approver: Optional user ID or name of the approver for the request.\n# :type approver: str, optional\n# :param default_args_json: Optional dictionary defining or overriding the default arguments for form fields.\n# :type default_args_json: dict, optional\n# :param dynamic_enums_json: Optional dictionary overriding the enum default values of enum form fields.\n# :type dynamic_enums_json: dict, optional\n# \n# :raises Exception: If the function is not called within a flow or flow preview.\n# :raises Exception: If the required flow job or flow step environment variables are not set.\n# \n# :return: None\n# \n# **Usage Example:**\n# >>> client.request_interactive_slack_approval(\n# ... slack_resource_path=\"/u/alex/my_slack_resource\",\n# ... channel_id=\"admins-slack-channel\",\n# ... message=\"Please approve this request\",\n# ... approver=\"approver123\",\n# ... default_args_json={\"key1\": \"value1\", \"key2\": 42},\n# ... dynamic_enums_json={\"foo\": [\"choice1\", \"choice2\"], \"bar\": [\"optionA\", \"optionB\"]},\n# ... )\n# \n# **Notes:**\n# - This function must be executed within a Windmill flow or flow preview.\n# - The function checks for required environment variables (`WM_FLOW_JOB_ID`, `WM_FLOW_STEP_ID`) to ensure it is run in the appropriate context.\ndef request_interactive_slack_approval(slack_resource_path: str, channel_id: str, message: str = None, approver: str = None, default_args_json: dict = None, dynamic_enums_json: dict = None) -> None\n\n# Send a message to a Microsoft Teams conversation with conversation_id, where success is used to style the message\ndef send_teams_message(conversation_id: str, text: str, success: bool = True, card_block: dict = None)\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# Only meaningful on a data table under roles, and only for a role you are a\n# tenant of.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None)\n\n# Get a DuckLake client for DuckDB queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# \n# Returns:\n# DucklakeClient instance\ndef ducklake(name: str = 'main')\n\ndef init_global_client(f)\n\ndef deprecate(in_favor_of: str)\n\n# Get the current workspace ID.\n# \n# Returns:\n# Workspace ID string\ndef get_workspace() -> str\n\ndef get_version() -> str\n\n# Create a script job and return its job ID.\n# \n# Args:\n# hash_or_path: Script hash or path (determined by presence of '/')\n# args: Script arguments\n# scheduled_in_secs: Delay before execution in seconds\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Job ID string\ndef run_script_async(hash_or_path: str, args: Dict[str, Any] = None, scheduled_in_secs: int = None, tag: str = None) -> str\n\n# Run a script synchronously by hash and return its result.\n# \n# Args:\n# hash: Script hash\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_sync(hash: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Run a script synchronously by path and return its result.\n# \n# Args:\n# path: Script path\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_by_path_sync(path: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB\ndef duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars\ndef polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3\ndef boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef get_state_path() -> str\n\n# Parse resource syntax from string.\ndef parse_resource_syntax(s: str) -> Optional[str]\n\n# Parse S3 object from a `s3://<storage>/<key>` URI string (`s3:///<key>`\n# for the default storage) or S3Object format. Any other string raises\n# rather than falling back to an auto-generated key: an auto key is\n# requested by omitting the object, and a fallback would silently misplace\n# the upload on any typo.\ndef parse_s3_object(s3_object: S3Object | str) -> S3Object\n\n# Parse variable syntax from string.\ndef parse_variable_syntax(s: str) -> Optional[str]\n\n# Append a text to the result stream.\n# \n# Args:\n# text: text to append to the result stream\ndef append_to_result_stream(text: str) -> None\n\n# Stream to the result stream.\n# \n# Args:\n# stream: stream to stream to the result stream\ndef stream_result(stream) -> None\n\n# Execute a SQL query against the DataTable.\n# \n# Args:\n# sql: SQL query string with $1, $2, etc. placeholders\n# *args: Positional arguments to bind to query placeholders\n# \n# Returns:\n# SqlQuery instance for fetching results\ndef query(sql: str, *args) -> SqlQuery\n\n# Idempotently materialize the rows of `select_sql` into ducklake\n# `table` for one `partition` (or the whole table when `partition` is\n# None). Client-side equivalent of the `// materialize` engine: with\n# `unique_key` it upserts within the slice (delete-by-key + insert);\n# without it, it replaces (whole table → CREATE OR REPLACE; partition →\n# delete the partition + insert). Re-running the same slice is safe — the\n# backfill / failure-recovery contract.\n# \n# The partition value is bound as a DuckDB arg (never string-interpolated)\n# so it cannot inject SQL. `select_sql` is trusted (your own query).\ndef upsert_partition(table: str, select_sql: str, partition: str = None, unique_key: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# INSERT-only materialization (no dedup / no replace) for an immutable\n# event-log table — for one `partition`, or the whole table when\n# `partition` is None. NOTE: unlike `upsert_partition`, re-running the same\n# slice duplicates rows — use only for append-only sources.\ndef append_partition(table: str, select_sql: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Read a materialized ducklake table, optionally a single partition.\ndef read(table: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Execute query and fetch results.\n# \n# Args:\n# result_collection: Optional result collection mode\n# \n# Returns:\n# Query results\ndef fetch(result_collection: str | None = None)\n\n# Execute query and fetch first row of results.\n# \n# Returns:\n# First row of query results\ndef fetch_one()\n\n# Execute query and fetch first row of results. Return result as a scalar value.\n# \n# Returns:\n# First row of query result as a scalar value\ndef fetch_one_scalar()\n\n# Execute query and don't return any results.\n# \ndef execute()\n\n# DuckDB executor requires explicit argument types at declaration\n# These types exist in both DuckDB and Postgres\n# Check that the types exist if you plan to extend this function for other SQL engines.\ndef infer_sql_type(value) -> str\n\ndef parse_sql_client_name(name: str) -> tuple[str, Optional[str]]\n\n# Decorator that marks a function as a workflow task.\n# \n# Works in both WAC v1 (sync, HTTP-based dispatch) and WAC v2\n# (async, checkpoint/replay) modes:\n# \n# - **v2 (inside @workflow)**: dispatches as a checkpoint step.\n# - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API.\n# - **Standalone, or called from inside another v2 task**: executes the\n# function body directly. A task runs as a single job, so the tasks it\n# calls run in that same job, without their own options.\n# \n# A task runs as its own job, so its result is always encoded as JSON and\n# decoded back before the caller sees it: a ``datetime`` comes back as a\n# string, a tuple as a list.\n# \n# ``retry`` re-dispatches the task after a failure, inside ``@workflow`` only.\n# Every attempt is a step of its own (``call_api``, ``call_api#2``, ...) and\n# the wait between two of them is a durable sleep, so a retrying task holds no\n# worker while it backs off. Keys: ``attempts`` (retries after the first\n# failure, a whole number from 0 to 100), ``delay`` (seconds before the first\n# retry, sub-second delays dropped), ``multiplier`` (applied to the delay\n# after each attempt, 1 keeps it constant), ``max_delay`` (ceiling in\n# seconds). ``attempts`` is required, and an out-of-range or unknown key is\n# rejected where the policy is written.\n# \n# A workflow sleeps once per round, so tasks backing off in the same fan-out\n# wait one after another rather than together: the delay before a fan-out\n# retries is the sum of every backoff pending in it, not the longest one, and\n# it grows with both the width of the fan-out and ``attempts``. Retries with\n# no ``delay`` all go out in a single round.\n# \n# ``cache_ttl`` serves a previous result of the task for that many seconds\n# instead of running it again. A task is keyed on its step key (its name and\n# call order) and the workflow's input, not on the arguments it is called\n# with, so cache one only when whether it runs, and what it receives, follow\n# from the workflow's input alone. A ``task_script`` target is keyed on the\n# arguments it is called with. It has no effect on a ``task_flow`` target,\n# which keeps its flow's own cache policy.\n# \n# Usage::\n# \n# @task\n# async def extract_data(url: str): ...\n# \n# @task(path=\"f/external_script\", timeout=600, tag=\"gpu\")\n# async def run_external(x: int): ...\n# \n# @task(retry={\"attempts\": 3, \"delay\": 30, \"multiplier\": 2})\n# async def call_api(payload: dict): ...\ndef task(_func = None, *, path: Optional[str] = None, tag: Optional[str] = None, timeout: Optional[int] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill script.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# extract = task_script(\"f/data/extract\", timeout=600)\n# \n# @workflow\n# async def main():\n# data = await extract(url=\"https://...\")\ndef task_script(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill flow.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# pipeline = task_flow(\"f/etl/pipeline\", priority=10)\n# \n# @workflow\n# async def main():\n# result = await pipeline(input=data)\ndef task_flow(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Decorator marking an async function as a workflow-as-code entry point.\n# \n# The function must be **deterministic**: given the same inputs it must call\n# tasks in the same order on every replay. Branching on task results is fine\n# (results are replayed from checkpoint), but branching on external state\n# (current time, random values, external API calls) must use ``step()`` to\n# checkpoint the value so replays see the same result.\ndef workflow(func)\n\n# Execute ``fn`` inline and checkpoint the result.\n# \n# On replay the cached value is returned without re-executing ``fn``.\n# Use for lightweight deterministic operations (timestamps, random IDs,\n# config reads) that should not incur the overhead of a child job.\n# \n# ``fn``'s result is encoded as JSON and decoded back before it is returned,\n# so the round that runs the body sees the same types every replay sees:\n# a ``datetime`` comes back as a string, a tuple as a list.\n# \n# Called from inside a task body, ``fn`` runs in place and nothing is\n# checkpointed: a task is a single job and is never replayed.\nasync def step(name: str, fn)\n\n# Server-side sleep — suspend the workflow for the given duration without holding a worker.\n# \n# Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``.\n# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``.\nasync def sleep(seconds: int)\n\n# Suspend the workflow and wait for an external approval.\n# \n# Pass ``key`` to name the step, then ``get_approval_urls(key)`` yields the URLs\n# that resume exactly this approval — route them through your own channel.\n# Without a key the steps are named ``approval``, ``approval_2``, ...\n# \n# Returns a dict with ``value`` (form data), ``approver``, and ``approved``.\n# \n# Args:\n# timeout: Approval timeout in seconds (default 1800).\n# form: Optional form schema for the approval page.\n# self_approval: Whether the user who triggered the flow can approve it (default True).\n# key: Optional checkpoint key naming this approval step.\n# skin: ``\"minimal\"`` shows approvers only the request (form and approve/reject)\n# instead of the detailed page with the workflow's details.\n# description: Shown to approvers above the form: a string, or a rich value such as\n# ``{\"markdown\": \"...\"}``.\n# \n# Example::\n# \n# urls = await step(\"urls\", lambda: get_approval_urls(\"manager\"))\n# await step(\"notify\", lambda: send_email(urls[\"resume\"], urls[\"cancel\"]))\n# result = await wait_for_approval(key=\"manager\", timeout=3600)\nasync def wait_for_approval(timeout: int = 1800, form: dict | None = None, self_approval: bool = True, key: str | None = None, skin: Literal['detailed', 'minimal'] | None = None, description: str | dict | None = None) -> dict\n\n# Process items in parallel with optional concurrency control.\n# \n# Each item is processed by calling ``fn(item)``, which should be a @task.\n# Items are dispatched in batches of ``concurrency`` (default: all at once).\n# \n# Example::\n# \n# @task\n# async def process(item: str):\n# ...\n# \n# results = await parallel(items, process, concurrency=5)\nasync def parallel(items, fn, *, concurrency: Optional[int] = None)\n\n# Commit Kafka offsets for a trigger with auto_commit disabled.\n# \n# Args:\n# trigger_path: Path to the Kafka trigger (from event['wm_trigger']['trigger_path'])\n# topic: Kafka topic name (from event['topic'])\n# partition: Partition number (from event['partition'])\n# offset: Message offset to commit (from event['offset'])\ndef commit_kafka_offsets(trigger_path: str, topic: str, partition: int, offset: int) -> None\n\n", "datatable": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement<T> = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record<string, any>;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch<ResultCollectionT extends ResultCollection = \"last_statement_all_rows\">(\n params?: FetchParams<ResultCollectionT | ResultCollection> // The union is for auto-completion\n ): Promise<SqlResult<T, ResultCollectionT>>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<SqlResult<T, \"last_statement_first_row\">>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise<SqlResult<T, \"last_statement_first_row_scalar\">>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<void>;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n <T = any>(strings: TemplateStringsArray, ...values: any[]): SqlStatement<T>;\n query<T = any>(sql: string, ...params: any[]): SqlStatement<T>;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n", "datatable.python3": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "datatable.go": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement<T> = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record<string, any>;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch<ResultCollectionT extends ResultCollection = \"last_statement_all_rows\">(\n params?: FetchParams<ResultCollectionT | ResultCollection> // The union is for auto-completion\n ): Promise<SqlResult<T, ResultCollectionT>>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<SqlResult<T, \"last_statement_first_row\">>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise<SqlResult<T, \"last_statement_first_row_scalar\">>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<void>;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n <T = any>(strings: TemplateStringsArray, ...values: any[]): SqlStatement<T>;\n query<T = any>(sql: string, ...params: any[]): SqlStatement<T>;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", diff --git a/backend/windmill-api/src/mcp/session/gen/tools.json b/backend/windmill-api/src/mcp/session/gen/tools.json index ffab17090a..1cc1f19e97 100644 --- a/backend/windmill-api/src/mcp/session/gen/tools.json +++ b/backend/windmill-api/src/mcp/session/gen/tools.json @@ -1670,7 +1670,7 @@ "type": "string" }, "account": { - "description": "The account identifier", + "description": "Ignored. A variable is linked to an OAuth account only when `createAccount` creates both.", "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 @@ -2069,13 +2069,14 @@ "type": "string" }, "type": { - "description": "Runnable kind: \"inline\" for custom code stored on the app; \"script\"/\"flow\" for a workspace runnable; \"hubscript\" for a hub script.", + "description": "Runnable kind: \"inline\" for custom code stored on the app; \"script\"/\"flow\" for a workspace runnable; \"hubscript\" for a hub script; \"agent\" for a saved AI agent, run as one chat turn.", "type": "string", "enum": [ "inline", "script", "flow", - "hubscript" + "hubscript", + "agent" ] }, "staticInputs": { @@ -2110,7 +2111,7 @@ "additionalProperties": false }, "path": { - "description": "Required when type is \"script\", \"flow\", or \"hubscript\". Workspace path of the runnable.", + "description": "Required when type is \"script\", \"flow\", \"hubscript\" or \"agent\". Workspace path of the runnable.", "type": "string" }, "viewerDataAccess": { diff --git a/frontend/src/lib/components/ContextualVariableEditor.svelte b/frontend/src/lib/components/ContextualVariableEditor.svelte index 9adde76e74..f09b52b571 100644 --- a/frontend/src/lib/components/ContextualVariableEditor.svelte +++ b/frontend/src/lib/components/ContextualVariableEditor.svelte @@ -9,9 +9,14 @@ import autosize from '$lib/autosize' import Label from './Label.svelte' import TextInput from './text_input/TextInput.svelte' - import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { + useOperatingWorkspace, + useReadOnlyWorkspace + } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() + // An editor opened in Build stays open when the session switches to Use. + const readOnly = useReadOnlyWorkspace() const dispatch = createEventDispatcher() @@ -36,6 +41,7 @@ let drawer: Drawer | undefined = $state() async function updateVariable(): Promise<void> { + if (readOnly($operatingWorkspace)) return await WorkspaceService.setEnvironmentVariable({ workspace: $operatingWorkspace!, requestBody: { @@ -79,7 +85,7 @@ {#snippet actions()} <Button on:click={() => updateVariable()} - disabled={value === '' || name === ''} + disabled={value === '' || name === '' || readOnly($operatingWorkspace)} startIcon={{ icon: Save }} variant="accent" unifiedSize="md" diff --git a/frontend/src/lib/components/DropdownV2Inner.svelte b/frontend/src/lib/components/DropdownV2Inner.svelte index 30b6865da8..138fd072b6 100644 --- a/frontend/src/lib/components/DropdownV2Inner.svelte +++ b/frontend/src/lib/components/DropdownV2Inner.svelte @@ -106,6 +106,11 @@ {#if item.separatorTop} <div class="my-1 border-t border-border-light"></div> {/if} + {#if item.sectionTitle} + <p class="px-4 pt-1.5 pb-1 text-2xs uppercase tracking-wide text-secondary"> + {item.sectionTitle} + </p> + {/if} {#if (item.submenuItems || item.customSubmenu) && builders} <DropdownSubmenuItem {item} {builders} {meltItem} close={close ?? (() => {})} /> {:else if item.disabled && item.tooltip} diff --git a/frontend/src/lib/components/NoDirectDeployAlert.svelte b/frontend/src/lib/components/NoDirectDeployAlert.svelte index 8ddf5c760a..1e1256241e 100644 --- a/frontend/src/lib/components/NoDirectDeployAlert.svelte +++ b/frontend/src/lib/components/NoDirectDeployAlert.svelte @@ -23,13 +23,15 @@ import { GitFork, Lock, ShieldOff } from 'lucide-svelte' import { useOperatingWorkspace, - useOperatingUser + useOperatingUser, + useReadOnlyWorkspace } from '$lib/components/operatingWorkspace.svelte' import { useRoleCapabilities } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() const roleCaps = useRoleCapabilities() + const readOnly = useReadOnlyWorkspace() // The shared rules state holds the navigation workspace's rules, so a host acting on another // workspace (an AI session's fork) has to ask for that one's. @@ -61,12 +63,16 @@ ? 'You will need to either fork the workspace, or make your changes locally and submit a PR to an authorized user.' : 'You will need to make your changes locally and submit a PR to an authorized user.' ) + // A session in Use edits nothing, so no rule or bypass opens the lists' create, edit and + // delete actions there. + let sessionReadOnly = $derived(readOnly($operatingWorkspace)) let overrideChecked = $state(false) // The toggle is only offered to a user who can bypass, but the answer can change under a // workspace switch, so the checked flag alone never grants the edit. - let bypassActive = $derived(canBypass && overrideChecked) + let bypassActive = $derived(canBypass && !sessionReadOnly && overrideChecked) let canEdit = $derived( - !isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment') || bypassActive + !sessionReadOnly && + (!isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment') || bypassActive) ) let { @@ -146,7 +152,7 @@ {editAdvice} </p> {/if} - {#if canBypass} + {#if canBypass && !sessionReadOnly} <Toggle size="xs" bind:checked={overrideChecked} diff --git a/frontend/src/lib/components/ShareModal.svelte b/frontend/src/lib/components/ShareModal.svelte index dfb5892b03..082fbcce2e 100644 --- a/frontend/src/lib/components/ShareModal.svelte +++ b/frontend/src/lib/components/ShareModal.svelte @@ -25,13 +25,15 @@ import { useScheduleLock, useTriggerLock } from '$lib/operatorWriteRights' import { useOperatingWorkspace, - useOperatingUser + useOperatingUser, + useReadOnlyWorkspace } from '$lib/components/operatingWorkspace.svelte' const scheduleLock = useScheduleLock() const triggerLock = useTriggerLock() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const readOnly = useReadOnlyWorkspace() const dispatch = createEventDispatcher() @@ -170,7 +172,9 @@ } } - let own = $state(false) + let ownsItem = $state(false) + // A session can switch to Use while the drawer is open, so read-only is read live. + const own = $derived(ownsItem && !readOnly($operatingWorkspace)) export async function openDrawer(newPath: string, kind_l: Kind, isOwnerOverride?: boolean) { path = newPath kind = kind_l @@ -181,7 +185,7 @@ loadLinkedVarPaths() loadDefaultPerms() if (isOwnerOverride !== undefined) { - own = isOwnerOverride + ownsItem = isOwnerOverride } else { loadOwner() } @@ -189,7 +193,7 @@ } async function loadOwner() { - own = isOwner(path, operatingUser.current!, $operatingWorkspace!) + ownsItem = isOwner(path, operatingUser.current!, $operatingWorkspace!) } async function loadAcls() { @@ -292,9 +296,15 @@ </div> {/if} {#if !own} - <Alert type="warning" title="Not owner" - >Since you do not own this item, you cannot modify its permission</Alert - > + {#if readOnly($operatingWorkspace)} + <Alert type="info" title="Use mode"> + This session cannot change permissions while it is in Use mode. + </Alert> + {:else} + <Alert type="warning" title="Not owner" + >Since you do not own this item, you cannot modify its permission</Alert + > + {/if} {/if} <div> {#if own && sharingDisabled} diff --git a/frontend/src/lib/components/copilot/chat/AIChat.svelte b/frontend/src/lib/components/copilot/chat/AIChat.svelte index a9312bc5fb..51a8dfa55b 100644 --- a/frontend/src/lib/components/copilot/chat/AIChat.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChat.svelte @@ -24,6 +24,7 @@ onSent = undefined, inputPreface, actingOn, + workModeLock = undefined, initialInstructions = undefined, onDraftChange = undefined, initialAttachments = undefined, @@ -49,6 +50,7 @@ inputPreface?: import('svelte').Snippet /** Forwarded to AIChatDisplay: where the session acts, first among the controls. */ actingOn?: import('svelte').Snippet + workModeLock?: import('./workMode').WorkModeLock // Seed / observe the composer's draft (forwarded to AIChatDisplay). initialInstructions?: string onDraftChange?: (text: string) => void @@ -224,6 +226,7 @@ {onSent} {inputPreface} {actingOn} + {workModeLock} {initialInstructions} {onDraftChange} {initialAttachments} diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index c5fede3162..a740c5fb5f 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -29,7 +29,6 @@ import { pendingUserAction, pendingUserActionDetail, type DisplayMessage } from './shared' import AutonomyModePicker from './AutonomyModePicker.svelte' import { availableAutonomyModeOptions, resolveAutonomyMode } from './autonomyModes' - import { PLAN_MODE_MESSAGES } from './planModeMessages' import type { ContextElement } from './context' import ChatQuickActions from './ChatQuickActions.svelte' import ContextUsageIndicator from './ContextUsageIndicator.svelte' @@ -44,13 +43,18 @@ import Markdown from 'svelte-exmarkdown' import { twMerge } from 'tailwind-merge' import { AIAutonomyMode, AIMode } from './AIChatManager.svelte' + import { AIWorkMode, type WorkModeLock } from './workMode' import { getChatViewHost } from './chatViewHost' import { getAiChatManager } from './aiChatManagerContext' import ChatTypingIndicator from './ChatTypingIndicator.svelte' import ToolGroupDisplay from './ToolGroupDisplay.svelte' import { chatItemKey, createChatItemGrouper } from './toolGroups' import AIChatInput from './AIChatInput.svelte' - import { STARTER_PLACEHOLDER, type ComposerSelection } from './composerBox' + import { + STARTER_PLACEHOLDER, + USE_STARTER_PLACEHOLDER, + type ComposerSelection + } from './composerBox' import AttachedFilesBar from './files/AttachedFilesBar.svelte' import QueuedMessageChip from './QueuedMessageChip.svelte' import JobsSegment from './JobsSegment.svelte' @@ -118,6 +122,7 @@ onSent = undefined, inputPreface, actingOn, + workModeLock = undefined, footerSettings, initialInstructions = undefined, onDraftChange = undefined, @@ -165,6 +170,8 @@ inputPreface?: Snippet /** Where the session acts: first among the controls after the attach button. */ actingOn?: Snippet + /** Holds a session chat in Use, and says why in the picker. */ + workModeLock?: WorkModeLock /** The settings control at the footer's right edge, where the copilot puts its * model picker. A host that configures its turn elsewhere replaces it here. */ footerSettings?: Snippet @@ -569,14 +576,14 @@ } const autonomyAvailability = $derived({ autoAcceptEditsAvailable: chatHost.autoAcceptEditsAvailable, - autoAcceptToolConfirmationsAvailable: chatHost.autoAcceptToolConfirmationsAvailable, - planModeAvailable: chatHost.planModeAvailable + autoAcceptToolConfirmationsAvailable: chatHost.autoAcceptToolConfirmationsAvailable }) const effectiveAutonomyMode = $derived( resolveAutonomyMode(chatHost.autonomyMode, autonomyAvailability) ) const showAutonomyModeSelector = $derived( - !disabled && availableAutonomyModeOptions(autonomyAvailability).length > 1 + !disabled && + (chatHost.workModesAvailable || availableAutonomyModeOptions(autonomyAvailability).length > 1) ) // The typing-dots indicator implies the AI is busy, which is misleading while @@ -588,6 +595,9 @@ // The block's layout holds while the chat is empty, usable or not; only the taller box // and the suggestions need a composer that can send. const starterLayout = $derived(!!starter && messages.length === 0) + const heldInUse = $derived( + chatHost.workModesAvailable && (!!workModeLock || chatHost.workMode === AIWorkMode.USE) + ) // Home is a page, not a pane: nothing there to centre in. const centreComposer = $derived(starterLayout && starter?.where === 'session') @@ -1057,7 +1067,11 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> bind:this={aiChatInput} bind:selectedContext {availableContext} - placeholder={starterLayout ? STARTER_PLACEHOLDER : placeholder} + placeholder={starterLayout + ? heldInUse + ? USE_STARTER_PLACEHOLDER + : STARTER_PLACEHOLDER + : placeholder} {initialInstructions} {onDraftChange} {initialAttachments} @@ -1274,11 +1288,16 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> mode={chatHost.autonomyMode} availability={autonomyAvailability} onChange={chatHost.setAutonomyMode} + work={chatHost.workModesAvailable + ? { + mode: chatHost.workMode, + planAvailable: chatHost.planModeAvailable, + lock: workModeLock, + onChange: chatHost.setWorkMode + } + : undefined} /> {/if} - {#if effectiveAutonomyMode === AIAutonomyMode.PLAN} - <span class="text-2xs text-secondary">{PLAN_MODE_MESSAGES.modeNote}</span> - {/if} {#if effectiveAutonomyMode === AIAutonomyMode.YOLO && chatHost.autoAcceptToolConfirmationsAvailable} <Tooltip small placement="top"> <AlertTriangle class="w-3 h-3 text-red-500" /> diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index 13aaccec94..ac6f21844e 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -162,7 +162,10 @@ const toolbarInBox = $derived(!!toolbar && hero) // Picked at mount-time so each new session lands on a different prompt. - const permissions = useSessionPermissions(() => chatHost.operatingWorkspace) + const permissions = useSessionPermissions( + () => chatHost.operatingWorkspace, + () => chatHost + ) const suggestionPick = Math.random() const globalSuggestion = $derived( globalComposerSuggestion(suggestionPick, permissions.canOpenEditor) diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index cf63cb420c..89a00c06bc 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -139,8 +139,23 @@ import { } from '$lib/aiStore' import type { WorkspaceMutationTarget } from './workspaceTools' import { resolveSessionAccess } from './global/sessionAccess' -import type { SessionAccess } from './sessionCapabilities' -import { filterSessionTools } from './global/sessionToolset' +import { + canBuild, + isReadOnlyAccess, + USE_MODE_ACCESS, + type SessionAccess, + type SessionTool +} from './sessionCapabilities' +import { + AIWorkMode, + ENTER_BUILD_MODE_TOOL, + ENTER_USE_MODE_TOOL, + isWorkModeSwitchTool, + WORK_MODE_SWITCH_TARGET, + type WorkModeSwitchTool +} from './workMode' +import { workModeSwitchTools } from './workModeSwitch' +import { filterSessionTools, sessionToolAllowed } from './global/sessionToolset' import { listFolderInstructions, type FolderInstruction, @@ -269,7 +284,6 @@ export enum AIMode { } export enum AIAutonomyMode { - PLAN = 'plan', DEFAULT = 'default', ACCEPT_EDIT = 'acceptedit', YOLO = 'yolo' @@ -332,7 +346,7 @@ function getPersistedAutonomyMode(): AIAutonomyMode { return AIAutonomyMode.ACCEPT_EDIT } const persistedMode = getLocalSetting(key) - if (isAIAutonomyMode(persistedMode) && persistedMode !== AIAutonomyMode.PLAN) { + if (isAIAutonomyMode(persistedMode)) { return persistedMode } // No stored preference: default to auto-accepting edits (tool calls still @@ -345,11 +359,6 @@ function getPersistedAutonomyMode(): AIAutonomyMode { } function persistAutonomyMode(mode: AIAutonomyMode) { - // Plan is session-only: persisting it would re-block a later session where the - // picker never offered Plan. The stored pre-plan baseline is what a reload restores. - if (mode === AIAutonomyMode.PLAN) { - return - } const key = scopedKey(AI_AUTONOMY_MODE_STORAGE_KEY) if (!BROWSER || !key) { return @@ -466,8 +475,8 @@ function planModeHostFor(m: AIChatManager): PlanModeHost { return m.artifacts }, openArtifact: (id, name, version) => m.openArtifact?.(id, name, version), - enter: () => m.setAutonomyMode(AIAutonomyMode.PLAN), - restore: () => m.setAutonomyMode(m.prePlanAutonomyMode ?? AIAutonomyMode.DEFAULT) + enter: () => m.setWorkMode(AIWorkMode.PLAN), + build: () => m.setWorkMode(AIWorkMode.BUILD) } } @@ -761,12 +770,48 @@ export class AIChatManager implements ChatViewHost { this.autonomyMode === AIAutonomyMode.YOLO) ) autoAcceptToolConfirmationsAvailable = $derived(supportsAutoAcceptToolConfirmations(this.mode)) + /** Use, Plan or Build. A session keeps its own: the runtime seeds it from the session record + * and stores each change through `onWorkModeChanged`. */ + workMode = $state<AIWorkMode>(AIWorkMode.BUILD) + onWorkModeChanged: ((mode: AIWorkMode) => void) | undefined = undefined + workModesAvailable = $derived(this.isSessionChat && supportsPlanMode(this.mode)) + /** Use is the only mode: the workspace is protected, or the user's role builds nothing in it. */ + #useOnly = $derived(this.workModesAvailable && !canBuild(this.sessionAccess)) + // A plan ends in edits, which neither case allows. The user's own Use mode leaves Plan open: + // it is one click away from Build anyway. + planModeAvailable = $derived(this.workModesAvailable && !this.#useOnly) + planModeActive = $derived(this.workMode === AIWorkMode.PLAN && this.planModeAvailable) + // Not while planning: approving the plan is the user's to do, and Yolo applies once they have. autoAcceptToolConfirmationsActive = $derived( - this.autonomyMode === AIAutonomyMode.YOLO && this.autoAcceptToolConfirmationsAvailable + this.autonomyMode === AIAutonomyMode.YOLO && + this.autoAcceptToolConfirmationsAvailable && + !this.planModeActive ) - planModeAvailable = $derived(this.isSessionChat && supportsPlanMode(this.mode)) - planModeActive = $derived(this.autonomyMode === AIAutonomyMode.PLAN && this.planModeAvailable) - prePlanAutonomyMode = $state<AIAutonomyMode | undefined>(undefined) + /** The chat is in Use, by the user's pick or because Use is the only mode. */ + useModeActive = $derived( + this.workModesAvailable && (this.workMode === AIWorkMode.USE || this.#useOnly) + ) + /** Why the chat is in Use; undefined in Plan and Build. A protected workspace's access builds + * nothing too, so it is told apart from the role first. */ + #useReason = $derived.by((): 'protected' | 'role' | 'chosen' | undefined => { + if (!this.useModeActive) return undefined + if (isReadOnlyAccess(this.sessionAccess)) return 'protected' + return this.#useOnly ? 'role' : 'chosen' + }) + #workModeSwitches: Record<WorkModeSwitchTool, SessionTool<any>> = workModeSwitchTools({ + offers: (tool) => this.workModeSwitchOffered === tool, + setWorkMode: (mode) => this.setWorkMode(mode) + }) + /** The switch the current mode offers between Use and Use & build. None from Plan, which + * leaves through its plan's approval, from a session held in Use, or while confirmations are + * auto-accepted: the switch is the user's answer, which that posture would give for them. */ + workModeSwitchOffered = $derived.by((): WorkModeSwitchTool | undefined => { + if (!this.workModesAvailable || this.autoAcceptToolConfirmationsActive) return undefined + if (this.#useReason === 'chosen') return ENTER_BUILD_MODE_TOOL + return this.useModeActive || this.planModeActive ? undefined : ENTER_USE_MODE_TOOL + }) + /** What the tools and the prompt are built for. */ + #toolAccess = $derived(this.useModeActive ? USE_MODE_ACCESS : this.sessionAccess) // The posture's own state — its two tools, the plan document and the planning round. // Everything it needs from this manager goes through the host above. planMode = new PlanModeController(planModeHostFor(this)) @@ -783,15 +828,33 @@ export class AIChatManager implements ChatViewHost { /** Both views narrow the same way — concatenate every source, then filter — so a tool * reaching either one can never arrive unfiltered. A session withholds what its user's * capabilities do not cover; elsewhere `sessionAccess` is unset and nothing is dropped. */ - #shipped = (planTools: Tool<any>[]): Tool<any>[] => - filterSessionTools([...this.#assembledTools, ...planTools], this.sessionAccess) - /** What the request carries: the assembled tools plus the plan-mode transition the current + #shipped = (modeTools: Tool<any>[]): Tool<any>[] => + filterSessionTools([...this.#assembledTools, ...modeTools], this.#toolAccess) + /** What the request carries: the assembled tools plus the mode transitions the current * posture offers. Read by the request path and by the YOLO disclosure. */ - tools: Tool<any>[] = $derived(this.#shipped(this.planMode.tools)) + tools: Tool<any>[] = $derived( + this.#shipped([ + ...this.planMode.tools, + ...(this.workModeSwitchOffered ? [this.#workModeSwitches[this.workModeSwitchOffered]] : []) + ]) + ) /** What the assistant can call in this session, posture-independent: both plan-mode - * transitions, whichever one is offered right now. A reference answer, so flipping the - * autonomy picker must not change it. */ - availableTools: Tool<any>[] = $derived(this.#shipped(this.planMode.availableTools)) + * transitions and both switches, whichever one is offered right now. A reference answer, so + * flipping the autonomy picker must not change it. */ + availableTools: Tool<any>[] = $derived( + this.#shipped([ + ...this.planMode.availableTools, + ...(this.workModesAvailable && !this.#useOnly ? Object.values(this.#workModeSwitches) : []) + ]) + ) + /** Whether a tool the call was made with is no longer shipped: a switch to Use withdraws + * every write while its card waits. The mode transitions are not assembled, so never are. */ + isToolWithdrawn = (toolName: string): boolean => { + const access = this.#toolAccess + if (!access) return false + const tool = this.#assembledTools.find((t) => t.def.function.name === toolName) + return !!tool && !sessionToolAllowed(tool, access) + } #copilotInfo = fromStore(copilotInfo) #sessionModel = fromStore(copilotSessionModel) /** Capabilities the provider runs on its own servers, attached by the adapter at send @@ -1964,8 +2027,10 @@ export class AIChatManager implements ChatViewHost { } /** enter_plan_mode never qualifies: YOLO means "stop asking and run it", and a research - * posture inverts that. Every accept path asks here rather than carrying its own copy. */ - private autoAcceptsTool = (toolName: string | undefined) => toolName !== ENTER_PLAN_MODE_TOOL + * posture inverts that. Nor does a switch between Use and Use & build, which only the user + * picks. Every accept path asks here rather than carrying its own copy. */ + private autoAcceptsTool = (toolName: string | undefined) => + toolName !== ENTER_PLAN_MODE_TOOL && !isWorkModeSwitchTool(toolName) /** Asked before the confirmation wait is skipped, so a tool the posture will not answer * for still gets a card rather than running unasked. */ @@ -2005,7 +2070,7 @@ export class AIChatManager implements ChatViewHost { } } - private resolvePendingPlanCard = (toolName: string, confirmed: boolean) => { + private resolvePendingModeCard = (toolName: string, confirmed: boolean) => { for (const [toolId, cb] of this.confirmationCallbacks) { if (cb.toolName === toolName) { cb.resolve(confirmed) @@ -2015,24 +2080,8 @@ export class AIChatManager implements ChatViewHost { } setAutonomyMode = (mode: AIAutonomyMode) => { - const enteringPlan = mode === AIAutonomyMode.PLAN && this.autonomyMode !== AIAutonomyMode.PLAN - const leavingPlan = mode !== AIAutonomyMode.PLAN && this.autonomyMode === AIAutonomyMode.PLAN - if (enteringPlan) { - this.prePlanAutonomyMode = this.autonomyMode - this.planMode.startRound() - } else if (mode !== AIAutonomyMode.PLAN) { - this.prePlanAutonomyMode = undefined - this.planMode.resetBlocks() - } this.autonomyMode = mode persistAutonomyMode(mode) - - if (enteringPlan) { - this.resolvePendingPlanCard(ENTER_PLAN_MODE_TOOL, true) - } else if (leavingPlan) { - // Opting into YOLO means "run it"; leaving plan mode any other way is not a sign-off. - this.resolvePendingPlanCard(EXIT_PLAN_MODE_TOOL, mode === AIAutonomyMode.YOLO) - } if (this.autoAcceptToolConfirmationsActive) { this.acceptPendingToolConfirmations() } @@ -2041,6 +2090,40 @@ export class AIChatManager implements ChatViewHost { } } + setWorkMode = (mode: AIWorkMode) => { + const enteringPlan = mode === AIWorkMode.PLAN && this.workMode !== AIWorkMode.PLAN + const leavingPlan = mode !== AIWorkMode.PLAN && this.workMode === AIWorkMode.PLAN + const useChanges = (mode === AIWorkMode.USE) !== (this.workMode === AIWorkMode.USE) + if (enteringPlan) { + this.planMode.startRound() + } else if (mode !== AIWorkMode.PLAN) { + this.planMode.resetBlocks() + } + this.workMode = mode + this.onWorkModeChanged?.(mode) + + if (enteringPlan) { + this.resolvePendingModeCard(ENTER_PLAN_MODE_TOOL, true) + } else if (leavingPlan) { + // Building under Yolo means "run it"; leaving plan mode any other way is not a sign-off. + this.resolvePendingModeCard( + EXIT_PLAN_MODE_TOOL, + mode === AIWorkMode.BUILD && this.autonomyMode === AIAutonomyMode.YOLO + ) + } + // A switch card the picker answered: accepted when the picker went where the card asked. + for (const tool of [ENTER_BUILD_MODE_TOOL, ENTER_USE_MODE_TOOL] as const) { + this.resolvePendingModeCard(tool, mode === WORK_MODE_SWITCH_TARGET[tool]) + } + if (this.autoAcceptToolConfirmationsActive) { + this.acceptPendingToolConfirmations() + } + // The helpers and the system prompt are built for one access; the tool list follows alone. + if (useChanges && this.mode === AIMode.GLOBAL) { + this.configureGlobalMode() + } + } + setAutoAcceptToolConfirmations = (enabled: boolean) => { this.setAutonomyMode(enabled ? AIAutonomyMode.YOLO : AIAutonomyMode.DEFAULT) } @@ -2054,7 +2137,6 @@ export class AIChatManager implements ChatViewHost { hydrateUserScopedAutonomy = () => { migrateLegacyAutonomyKeys() this.autonomyMode = getPersistedAutonomyMode() - this.prePlanAutonomyMode = undefined this.planMode.resetRound() } @@ -2687,7 +2769,7 @@ export class AIChatManager implements ChatViewHost { sessionId: this.sessionId, operatingWorkspace: this.operatingWorkspace, artifacts: this.artifacts, - access: this.sessionAccess, + access: this.#toolAccess, getChatId: () => this.historyManager.getCurrentChatId(), openArtifact: this.openArtifact } @@ -2726,11 +2808,19 @@ export class AIChatManager implements ChatViewHost { skills: this.globalSkills, folderInstructions: this.globalFolderInstructions, mcpServers: this.mcpServers, - access: this.sessionAccess, - sessionContext: this.sessionContextResolver?.(), + access: this.#toolAccess, + sessionContext: this.#sessionPromptContext(), pipelineFolders: this.#pipelineFolders() }) + #sessionPromptContext = (): SessionPromptContext | undefined => { + const ctx = this.sessionContextResolver?.() + const reason = this.#useReason + // A protected workspace needs no reason here: the prompt's own read-only line names it. + if (!ctx || !reason || reason === 'protected') return ctx + return { ...ctx, useMode: reason } + } + // Fetch the workspace's AI skills and, if GLOBAL mode is still active, rebuild // the system message so the next chat-loop iteration advertises them. Ignore // stale resolves so workspace changes cannot overwrite newer skills. @@ -4050,10 +4140,24 @@ export class AIChatManager implements ChatViewHost { workspace: this.operatingWorkspace }) logFeatureUsage('ai_session', 'autonomy', { - key: this.autonomyMode, + // Planning keeps its own key, `plan`, so the series still tells it apart. + key: this.planModeActive ? AIWorkMode.PLAN : this.autonomyMode, entityId: this.sessionId, workspace: this.operatingWorkspace }) + if (this.workModesAvailable) { + // Keyed by the mode the message runs in, not `workMode`, which a held session keeps. + // Held Use has its own keys, so `use_chosen` counts only sessions that could build. + logFeatureUsage('ai_session', 'work_mode', { + key: this.#useReason + ? `use_${this.#useReason}` + : this.planModeActive + ? AIWorkMode.PLAN + : AIWorkMode.BUILD, + entityId: this.sessionId, + workspace: this.operatingWorkspace + }) + } } if (this.mode === AIMode.FLOW && !this.flowAiChatHelpers) { @@ -4317,6 +4421,7 @@ export class AIChatManager implements ChatViewHost { shouldAutoAcceptToolConfirmations: this.shouldAutoAcceptTool, isPlanModeActive: () => this.planModeActive, onToolBlockedByPlanMode: this.planMode.noteBlockedTool, + isToolWithdrawn: this.isToolWithdrawn, requestUserQuestion: this.requestUserQuestion, requestRunArgs: this.requestRunArgs, markRunFormStarted: this.markRunFormStarted, diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 874a147026..582e789cf7 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -8,6 +8,7 @@ import type { ChatCompletionMessageParam } from 'openai/resources/chat/completio import type { DisplayMessage } from './shared' import type { AttachedImage } from './imageUtils' import { AIChatManager, AIMode, AIAutonomyMode } from './AIChatManager.svelte' +import { AIWorkMode, USE_MODE_WITHDRAWN } from './workMode' import { makePasteToken } from './pasteTokens' import { chatState } from './sharedChatState.svelte' import { PLAN_MODE_MESSAGES } from './planModeMessages' @@ -51,9 +52,12 @@ vi.mock('monaco-editor', () => ({ vi.mock('$lib/utils/featureUsage', () => ({ logFeatureUsage: vi.fn() })) vi.mock('$lib/gen', () => ({ - WorkspaceService: {}, + WorkspaceService: { + listProtectionRules: vi.fn(async () => []) + }, ResourceService: { - listResource: mocks.listResource + listResource: mocks.listResource, + listResourceTypeNames: vi.fn(async () => []) }, ScriptService: {}, FlowService: {}, @@ -986,13 +990,11 @@ describe('AIChatManager autonomy mode', () => { }) // The posture's own behaviour lives in planModeController.test.ts. What is left here is the -// wiring only the manager owns: which pending confirmation cards a change of autonomy mode -// answers, and with what. +// wiring only the manager owns: which pending confirmation cards a change of work mode or of +// autonomy mode answers, and with what. describe('AIChatManager plan mode posture', () => { beforeEach(() => { localStorage.clear() - // Plan mode is never the persisted posture, so a case starts from the one it is - // entered from and hands back to. localStorage.setItem(`ai-chat-autonomy-mode::${TEST_EMAIL}`, AIAutonomyMode.DEFAULT) vi.clearAllMocks() }) @@ -1005,7 +1007,7 @@ describe('AIChatManager plan mode posture', () => { return manager } - it('enters plan mode through the tool and remembers the posture to hand back to', async () => { + it('enters plan mode through the tool and leaves the confirmations setting alone', async () => { const manager = sessionManager(AIAutonomyMode.ACCEPT_EDIT) await manager.planMode.enterTool.fn({ @@ -1017,12 +1019,12 @@ describe('AIChatManager plan mode posture', () => { }) expect(manager.planModeActive).toBe(true) - expect(manager.prePlanAutonomyMode).toBe(AIAutonomyMode.ACCEPT_EDIT) + expect(manager.autonomyMode).toBe(AIAutonomyMode.ACCEPT_EDIT) }) it('refuses to move a session chat out of GLOBAL, so the gate cannot lift under it', () => { const manager = sessionManager(AIAutonomyMode.ACCEPT_EDIT) - manager.setAutonomyMode(AIAutonomyMode.PLAN) + manager.setWorkMode(AIWorkMode.PLAN) expect(manager.planModeActive).toBe(true) // Without a configured model changeMode returns early on SCRIPT, and the case would pass // against the very guard it is meant to pin. @@ -1083,21 +1085,74 @@ describe('AIChatManager plan mode posture', () => { it('answers a pending plan card the way the picker was moved', async () => { const entering = sessionManager() const enterPending = entering.requestConfirmation('call_enter', 'enter_plan_mode') - entering.setAutonomyMode(AIAutonomyMode.PLAN) + entering.setWorkMode(AIWorkMode.PLAN) expect(await enterPending).toBe(true) // Leaving plan mode any other way is not a sign-off on the plan on the card. - const leaving = sessionManager(AIAutonomyMode.PLAN) + const leaving = sessionManager() + leaving.setWorkMode(AIWorkMode.PLAN) const exitPending = leaving.requestConfirmation('call_exit', 'exit_plan_mode') - leaving.setAutonomyMode(AIAutonomyMode.DEFAULT) + leaving.setWorkMode(AIWorkMode.BUILD) expect(await exitPending).toBe(false) - // Opting into YOLO does mean "run it". - const yolo = sessionManager(AIAutonomyMode.PLAN) + // Building under YOLO does mean "run it". + const yolo = sessionManager(AIAutonomyMode.YOLO) + yolo.setWorkMode(AIWorkMode.PLAN) const yoloPending = yolo.requestConfirmation('call_exit', 'exit_plan_mode') - yolo.setAutonomyMode(AIAutonomyMode.YOLO) + yolo.setWorkMode(AIWorkMode.BUILD) expect(await yoloPending).toBe(true) }) + + it('waits for the user on a plan card while planning under YOLO', async () => { + // YOLO is the posture an approved plan is carried out in; the approval itself is not its + // to give, or a plan no card ever showed would be run. + const manager = sessionManager() + manager.setWorkMode(AIWorkMode.PLAN) + manager.setAutonomyMode(AIAutonomyMode.YOLO) + let settled = false + void manager.requestConfirmation('call_exit', 'exit_plan_mode').then(() => (settled = true)) + await Promise.resolve() + expect(settled).toBe(false) + expect(manager.planMode.tools.map((t) => t.def.function.name)).toEqual(['exit_plan_mode']) + }) + + // The call was made with Build's tools; approving its card after the switch to Use must not + // run the write the session no longer ships. + it('does not run a write approved after the session switched to Use', async () => { + const { processToolCall } = await import('./shared') + const manager = sessionManager() + manager.configureGlobalMode() + const write = manager.availableTools.find((t) => t.def.function.name === 'write_script')! + const fn = vi.fn(async () => 'written') + let asked = false + const result = processToolCall({ + tools: [{ ...write, fn, requiresConfirmation: true }] as any, + toolCall: { + id: 'call_write', + type: 'function', + function: { name: 'write_script', arguments: '{}' } + } as any, + helpers: {}, + workspace: 'test-workspace', + toolCallbacks: { + setToolStatus: vi.fn(), + removeToolStatus: vi.fn(), + requestConfirmation: (id: string, name?: string) => { + asked = true + return manager.requestConfirmation(id, name) + }, + shouldAutoAcceptToolConfirmations: manager.shouldAutoAcceptTool, + isToolWithdrawn: manager.isToolWithdrawn + } as any + }) + await vi.waitFor(() => expect(asked).toBe(true)) + + manager.setWorkMode(AIWorkMode.USE) + manager.handleToolConfirmation('call_write', true) + + expect((await result).content).toBe(USE_MODE_WITHDRAWN.result) + expect(fn).not.toHaveBeenCalled() + }) }) describe('AIChatManager persisted autonomy default', () => { @@ -4947,6 +5002,26 @@ describe('AIChatManager tool views', () => { expect(manager.systemMessage.content).not.toContain('write_script') }) + // Use is the user's own pick, so no profile resolves for it: the switch alone has to strip + // the writes from the tools and the prompt, and hand them back on Build. + it('ships only reads and runs in Use, and the writes again in Build', () => { + const manager = new AIChatManager() + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + manager.configureGlobalMode() + const names = () => manager.availableTools.map((t) => t.def.function.name) + expect(names()).toContain('write_script') + + manager.setWorkMode(AIWorkMode.USE) + expect(names()).toEqual(expect.arrayContaining(['list_workspace_items', 'run_script'])) + expect(names()).not.toContain('write_script') + expect(manager.systemMessage.content).not.toContain('write_script') + + manager.setWorkMode(AIWorkMode.BUILD) + expect(names()).toContain('write_script') + expect(manager.systemMessage.content).toContain('write_script') + }) + // Which transition each posture offers is planModeController.test.ts's; what this pins is // that only `tools` follows the picker. `isSessionChat` is what offers plan mode at all. it('holds availableTools steady across the autonomy picker', async () => { @@ -4963,4 +5038,56 @@ describe('AIChatManager tool views', () => { expect(names(manager.tools)).not.toContain('enter_plan_mode') expect(names(manager.availableTools)).toEqual(before) }) + + it('offers the switch out of the mode the session is in, and switches only once called', async () => { + const manager = new AIChatManager() + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + manager.configureGlobalMode() + // The posture is persisted, and the test above leaves it on Yolo. + manager.setAutonomyMode(AIAutonomyMode.DEFAULT) + const shipped = () => manager.tools.map((t) => t.def.function.name) + expect(shipped()).toContain('enter_use_mode') + expect(shipped()).not.toContain('enter_build_mode') + + // Plan leaves through its plan's approval, and Yolo would answer the card for the user. + manager.setWorkMode(AIWorkMode.PLAN) + expect(shipped()).not.toContain('enter_use_mode') + expect(shipped()).not.toContain('enter_build_mode') + manager.setWorkMode(AIWorkMode.USE) + manager.setAutonomyMode(AIAutonomyMode.YOLO) + expect(shipped()).not.toContain('enter_build_mode') + manager.setAutonomyMode(AIAutonomyMode.DEFAULT) + + const enterBuild = manager.tools.find((t) => t.def.function.name === 'enter_build_mode') + expect(manager.workMode).toBe(AIWorkMode.USE) + await enterBuild?.fn({} as any) + expect(manager.workMode).toBe(AIWorkMode.BUILD) + expect(manager.systemMessage.content).toContain('write_script') + }) + + // The card is the only consent the switch has: the picker can answer it by going where it + // asked, and turning on Yolo must not approve it. + it('resolves a pending switch card from the picker, and never from Yolo', async () => { + const manager = new AIChatManager() + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + manager.configureGlobalMode() + manager.setAutonomyMode(AIAutonomyMode.DEFAULT) + manager.setWorkMode(AIWorkMode.USE) + + const toPlan = manager.requestConfirmation('a', 'enter_build_mode') + manager.setWorkMode(AIWorkMode.PLAN) + await expect(toPlan).resolves.toBe(false) + + manager.setWorkMode(AIWorkMode.USE) + const toBuild = manager.requestConfirmation('b', 'enter_build_mode') + manager.setWorkMode(AIWorkMode.BUILD) + await expect(toBuild).resolves.toBe(true) + + manager.setWorkMode(AIWorkMode.USE) + const underYolo = manager.requestConfirmation('c', 'enter_build_mode') + manager.setAutonomyMode(AIAutonomyMode.YOLO) + await expect(underYolo).resolves.toBe(false) + }) }) diff --git a/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte b/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte index f63db32d0e..e236e4a4c0 100644 --- a/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte +++ b/frontend/src/lib/components/copilot/chat/AutonomyModePicker.svelte @@ -1,51 +1,110 @@ <script lang="ts"> - import { ChevronDown } from 'lucide-svelte' + import { ArrowRight, ChevronDown } from 'lucide-svelte' import { Button } from '$lib/components/common' import DropdownV2 from '$lib/components/DropdownV2.svelte' + import type { Item } from '$lib/utils' import type { AIAutonomyMode } from './AIChatManager.svelte' + import { AIWorkMode, type WorkModeLock } from './workMode' import { autonomyModeOption, availableAutonomyModeOptions, resolveAutonomyMode, + workModeOption, + workModeOptions, type AutonomyAvailability } from './autonomyModes' let { mode, availability, - onChange + onChange, + work = undefined }: { mode: AIAutonomyMode availability: AutonomyAvailability onChange: (mode: AIAutonomyMode) => void + /** A session chat's Use / Plan / Build, shown as the picker's first section. */ + work?: { + mode: AIWorkMode + planAvailable: boolean + /** Holds the chat in Use, and says why. */ + lock?: WorkModeLock + onChange: (mode: AIWorkMode) => void + } } = $props() const effective = $derived(resolveAutonomyMode(mode, availability)) const option = $derived(autonomyModeOption(effective)) -</script> + // Plan where the chat no longer offers it falls back to Build, as the manager does. + const workOption = $derived( + !work + ? undefined + : workModeOption( + work.lock + ? AIWorkMode.USE + : work.mode === AIWorkMode.PLAN && !work.planAvailable + ? AIWorkMode.BUILD + : work.mode + ) + ) + const postureLabel = $derived(option.shortLabel ?? option.label) -<DropdownV2 - items={() => - availableAutonomyModeOptions(availability).map((o) => ({ + function items(): Item[] { + const sections = !!work + const postures: Item[] = availableAutonomyModeOptions(availability).map((o, i) => ({ displayName: o.label, + sectionTitle: sections && i === 0 ? 'Confirmations' : undefined, + separatorTop: sections && i === 0, selected: effective === o.mode, action: () => onChange(o.mode) - }))} - placement="bottom-start" - fixedHeight={false} - customWidth={240} -> + })) + const w = work + if (!w) return postures + const lockedOut = (m: AIWorkMode) => !!w.lock && m !== AIWorkMode.USE + const workItems: Item[] = workModeOptions + .filter((o) => o.mode !== AIWorkMode.PLAN || w.planAvailable || w.lock) + .map((o, i) => { + const locked = lockedOut(o.mode) + return { + displayName: o.label, + description: o.description, + icon: o.icon, + // `iconColor` takes a color value; these are text classes. A locked row's icon + // keeps the disabled color its label has. + iconProps: { class: locked ? 'shrink-0' : `shrink-0 ${o.iconColor}` }, + sectionTitle: i === 0 ? 'What the chat can do' : undefined, + selected: workOption?.mode === o.mode, + disabled: locked, + tooltip: locked ? w.lock?.reason : undefined, + action: () => w.onChange(o.mode) + } + }) + const escape = w.lock?.escape + return [ + ...workItems, + ...(escape ? [{ displayName: escape.label, icon: ArrowRight, action: escape.action }] : []), + ...postures + ] + } +</script> + +<DropdownV2 {items} placement="bottom-start" fixedHeight={false} customWidth={work ? 260 : 240}> {#snippet buttonReplacement()} <Button nonCaptureEvent unifiedSize="2xs" variant="subtle" - title={option.tooltip(availability)} - btnClasses={option.triggerClass ?? ''} - startIcon={{ icon: option.icon, classes: option.iconColor }} + title={workOption + ? (work?.lock?.reason ?? `${workOption.description} ${option.tooltip(availability)}`) + : option.tooltip(availability)} + btnClasses={workOption?.triggerClass ?? ''} + startIcon={{ + icon: (workOption ?? option).icon, + classes: (workOption ?? option).iconColor + }} endIcon={{ icon: ChevronDown }} > - {option.shortLabel ?? option.label} + {workOption ? `${workOption.label} · ${postureLabel}` : postureLabel} </Button> {/snippet} </DropdownV2> diff --git a/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte b/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte index 6072b6e341..20e9b1df91 100644 --- a/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/RunArgsFormDisplay.svelte @@ -9,6 +9,7 @@ import { sendUserToast } from '$lib/utils' import { getAiChatManager } from './aiChatManagerContext' import { PLAN_MODE_MESSAGES } from './planModeMessages' + import { USE_MODE_WITHDRAWN } from './workMode' import { scrollFades } from './scrollFades.svelte' import type { RunFormDisplay } from './shared' @@ -54,6 +55,14 @@ // off the entrypoint a `dynselect-` argument runs, which does not wait for Run. A password // field mints at mount, too early to hold off here, so `runThroughForm` gates that instead. const planMode = $derived(aiChatManager.planModeActive) + // A test run previews undeployed code, which Use withholds as plan mode withholds every run. + const refusal = $derived( + planMode + ? PLAN_MODE_MESSAGES.runFormRefused + : runForm.kind === 'test' && aiChatManager.useModeActive + ? USE_MODE_WITHDRAWN.testRunRefused + : undefined + ) onMount(() => { void tick().then(() => cardNode?.scrollIntoView({ block: 'nearest' })) @@ -79,10 +88,10 @@ return } // Ahead of processSecretArgs, which writes ephemeral variables to the workspace: the - // autonomy picker moves while a form sits pending, and the re-gate on the other side - // of the callback runs too late to unmake a write plan mode promised not to do. - if (aiChatManager.planModeActive) { - sendUserToast(PLAN_MODE_MESSAGES.runFormRefused, true) + // mode picker moves while a form sits pending, and the re-gate on the other side of the + // callback runs too late to unmake a write plan mode or Use promised not to do. + if (refusal) { + sendUserToast(refusal, true) return } if (!aiChatManager.beginRunFormSubmit(toolCallId)) return @@ -145,18 +154,19 @@ {#if hasArgs} <!-- Passing `helperScript` is what lets DynamicInput run a job before Run: it executes the `dynselect-` entrypoint on mount, carrying the other args as proposed, - and Cancel does not undo it. Withheld under plan mode, which promised no writes. + and Cancel does not undo it. Withheld under plan mode, which promised no writes, and from + a test run in Use, whose helper is undeployed code too. A test run names its draft by code: `deployed` resolves a stale version, or none. --> <SchemaForm bind:schema={draft.schema} - helperScript={planMode + helperScript={refusal ? undefined : runForm.kind === 'test' ? runForm.code && runForm.lang ? { source: 'inline', code: runForm.code, lang: runForm.lang } : undefined : { source: 'deployed', path: runForm.path, runnable_kind: runnableKind }} - disabled={planMode} + disabled={!!refusal} {workspace} prettifyHeader bind:isValid @@ -210,8 +220,8 @@ <span class="font-mono">{runForm.strippedKeys.join(', ')}</span> </p> {/if} - {#if planMode} - <p class="text-2xs text-secondary">{PLAN_MODE_MESSAGES.runFormRefused}</p> + {#if refusal} + <p class="text-2xs text-secondary">{refusal}</p> {/if} <!-- Reject then confirm at the end of the row, as ToolConfirmationFooter puts them: this @@ -232,7 +242,7 @@ variant="accent" unifiedSize="sm" startIcon={{ icon: Play }} - disabled={!isValid || submitting || planMode} + disabled={!isValid || submitting || !!refusal} onClick={run} > Run diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 2b09d75332..1b267472c8 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -21,6 +21,12 @@ PLAN_CARD_COPY, PLAN_MODE_TEXT_COLOR } from './planMode' + import { + isWorkModeSwitchTool, + WORK_MODE_SWITCH_CARD_COPY, + WORK_MODE_SWITCH_TARGET + } from './workMode' + import { workModeOption } from './autonomyModes' import { Button } from '$lib/components/common' import { markdownProse } from '$lib/components/markdownProse' import { getChatViewHost } from './chatViewHost' @@ -61,9 +67,17 @@ const mcpServer = $derived(message.mcpServer) const isPlanReview = $derived(message.toolName === EXIT_PLAN_MODE_TOOL) - const isPlanCard = $derived(isPlanCardTool(message.toolName)) + // A switch between Use and Use & build renders as enter_plan_mode's card, with its own copy + // and the icon of the mode it leads to. + const switchTool = $derived(isWorkModeSwitchTool(message.toolName) ? message.toolName : undefined) + const isPlanCard = $derived(isPlanCardTool(message.toolName) || switchTool !== undefined) const planCopy = $derived( - isPlanCardTool(message.toolName) ? PLAN_CARD_COPY[message.toolName] : undefined + isPlanCardTool(message.toolName) + ? PLAN_CARD_COPY[message.toolName] + : switchTool && WORK_MODE_SWITCH_CARD_COPY[switchTool] + ) + const CardIcon = $derived( + switchTool ? workModeOption(WORK_MODE_SWITCH_TARGET[switchTool]).icon : ClipboardList ) // exit_plan_mode carries the plan, enter_plan_mode the one-line justification. const planBody = $derived(isPlanReview ? message.parameters?.summary : message.parameters?.reason) @@ -225,13 +239,18 @@ {#if message.isLoading && !message.needsConfirmation} <Loader2 class="w-3.5 h-3.5 animate-spin text-blue-500 shrink-0" /> {:else if planState === 'settled'} - <Check class={twMerge('w-3.5 h-3.5 shrink-0', PLAN_MODE_TEXT_COLOR)} /> + <Check + class={twMerge( + 'w-3.5 h-3.5 shrink-0', + switchTool ? 'text-secondary' : PLAN_MODE_TEXT_COLOR + )} + /> {:else if planState === 'declined'} <!-- Muted and not red: declining a plan is an outcome, not a failure, and this state also covers a card resolved by leaving plan mode. --> <CircleMinus class="w-3.5 h-3.5 text-tertiary shrink-0" /> {:else} - <ClipboardList class="w-3.5 h-3.5 text-secondary shrink-0" /> + <CardIcon class="w-3.5 h-3.5 text-secondary shrink-0" /> {/if} <span class="text-primary font-medium text-2xs">{planLabel}</span> {#if planBodyText} @@ -264,7 +283,7 @@ toolCallId={message.tool_call_id} rejectLabel={planCopy?.reject} confirmLabel={planCopy?.confirm ?? ''} - confirmIcon={isPlanReview ? undefined : ClipboardList} + confirmIcon={isPlanReview ? undefined : CardIcon} class={extraClass} /> {/snippet} diff --git a/frontend/src/lib/components/copilot/chat/autonomyModes.ts b/frontend/src/lib/components/copilot/chat/autonomyModes.ts index 1cc43c1f2d..b514635911 100644 --- a/frontend/src/lib/components/copilot/chat/autonomyModes.ts +++ b/frontend/src/lib/components/copilot/chat/autonomyModes.ts @@ -1,11 +1,11 @@ -import { ChevronsRight, ClipboardList, Hand } from 'lucide-svelte' +import { ChevronsRight, ClipboardList, Hammer, Hand, Play } from 'lucide-svelte' import { AIAutonomyMode } from './AIChatManager.svelte' import { PLAN_MODE_TEXT_COLOR, PLAN_MODE_TRIGGER_CLASS } from './planMode' +import { AIWorkMode } from './workMode' export type AutonomyAvailability = { autoAcceptEditsAvailable: boolean autoAcceptToolConfirmationsAvailable: boolean - planModeAvailable: boolean } export type AutonomyModeOption = { @@ -14,8 +14,6 @@ export type AutonomyModeOption = { shortLabel?: string icon: typeof Hand iconColor: string - /** Tints the whole trigger, not just its icon. Only plan mode needs it. */ - triggerClass?: string tooltip: (a: AutonomyAvailability) => string isAvailable: (a: AutonomyAvailability) => boolean } @@ -38,17 +36,6 @@ const askPermissionOption: AutonomyModeOption = { // table. `isAvailable` hides the postures that would do nothing in the current AI // mode, which is why the picker can be shorter than this list. const autonomyModeOptions: AutonomyModeOption[] = [ - { - mode: AIAutonomyMode.PLAN, - label: 'Plan (read-only)', - shortLabel: 'Plan', - icon: ClipboardList, - iconColor: PLAN_MODE_TEXT_COLOR, - triggerClass: PLAN_MODE_TRIGGER_CLASS, - tooltip: () => - 'Read-only: the assistant researches and drafts a plan for your approval before it can change anything.', - isAvailable: (a) => a.planModeAvailable - }, askPermissionOption, { mode: AIAutonomyMode.ACCEPT_EDIT, @@ -88,3 +75,44 @@ export function resolveAutonomyMode(mode: AIAutonomyMode, a: AutonomyAvailabilit ? mode : AIAutonomyMode.DEFAULT } + +export type WorkModeOption = { + mode: AIWorkMode + label: string + description: string + icon: typeof Hand + iconColor: string + /** Tints the whole trigger, not just its icon. Only plan mode needs it. */ + triggerClass?: string +} + +/** A session chat's first section, above the postures: what the chat may do. */ +export const workModeOptions: WorkModeOption[] = [ + { + mode: AIWorkMode.USE, + label: 'Use', + description: 'Reads and runs. No changes.', + icon: Play, + iconColor: 'text-secondary' + }, + { + mode: AIWorkMode.PLAN, + label: 'Plan', + description: 'Proposes a plan first.', + icon: ClipboardList, + iconColor: PLAN_MODE_TEXT_COLOR, + triggerClass: PLAN_MODE_TRIGGER_CLASS + }, + { + mode: AIWorkMode.BUILD, + // Named for both halves: building does not take away running what is deployed. + label: 'Use & build', + description: 'Edits, tests and deploys.', + icon: Hammer, + iconColor: 'text-secondary' + } +] + +export function workModeOption(mode: AIWorkMode): WorkModeOption { + return workModeOptions.find((o) => o.mode === mode) ?? workModeOptions[2] +} diff --git a/frontend/src/lib/components/copilot/chat/chatViewHost.ts b/frontend/src/lib/components/copilot/chat/chatViewHost.ts index fc52b67449..5e94f39311 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -1,5 +1,6 @@ import { getContext, setContext } from 'svelte' import type { AIMode, AIAutonomyMode } from './AIChatManager.svelte' +import type { AIWorkMode } from './workMode' import { getAiChatManager } from './aiChatManagerContext' import type { DisplayMessage, Tool } from './shared' import type { ContextElement } from './context' @@ -160,6 +161,10 @@ export interface ChatViewHost { readonly tools: readonly Tool<any>[] autonomyMode: AIAutonomyMode setAutonomyMode: (mode: AIAutonomyMode) => void + /** Use, Plan or Build: offered by a session chat only. */ + readonly workModesAvailable: boolean + workMode: AIWorkMode + setWorkMode: (mode: AIWorkMode) => void readonly autoAcceptEditsActive: boolean readonly autoAcceptEditsAvailable: boolean readonly autoAcceptToolConfirmationsAvailable: boolean diff --git a/frontend/src/lib/components/copilot/chat/composerBox.ts b/frontend/src/lib/components/copilot/chat/composerBox.ts index 09dcf04764..3326e58274 100644 --- a/frontend/src/lib/components/copilot/chat/composerBox.ts +++ b/frontend/src/lib/components/copilot/chat/composerBox.ts @@ -33,6 +33,9 @@ export const COMPOSER_FIELD_RESET = /** The placeholder of a composer that opens a session. */ export const STARTER_PLACEHOLDER = 'Ask about this workspace, or describe what to build…' +/** The same, for a session held in Use, which builds nothing. */ +export const USE_STARTER_PLACEHOLDER = 'Ask about this workspace, or run what it holds…' + /** A caret or selected range in the composer's text. */ export type ComposerSelection = { start: number; end: number } diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 24273cece4..81f1169386 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -73,6 +73,7 @@ import { import { processSecretArgs } from '$lib/components/secretArgUtils' import { parsePipelineAnnotations } from '$lib/components/assets/AssetGraph/parsePipelineAnnotations' import { PLAN_MODE_MESSAGES } from '../planModeMessages' +import { USE_MODE_WITHDRAWN } from '../workMode' import { DEFAULT_DATA as DEFAULT_RAW_APP_DATA, formatDataTableRef @@ -80,7 +81,7 @@ import { import { appSourceToDraftValue } from '$lib/components/raw_apps/rawAppDraftValue' import { conformBuilderAppPolicy } from '$lib/components/raw_apps/builderAppPolicy' import { capabilitiesInWorkspace } from '$lib/operatorWriteRights' -import { capabilitiesIn } from '$lib/roleCapabilities' +import { capabilitiesIn, withoutBuilding } from '$lib/roleCapabilities' import type { RoleCapabilities } from '$lib/gen' import type { RawAppDomQuery } from '$lib/components/raw_apps/rawAppDom' import { dataUrlToImagePart, normalizeImageDataUrl, type AttachedImage } from '../imageUtils' @@ -231,6 +232,7 @@ import type { UserDraftItemKind } from '$lib/gen' import { bundleRawAppDraft } from './rawAppBundlerBridge' import { canOpenEditor, + isReadOnlyAccess, DEPLOY, NONE, RUN_FLOW_PREVIEW, @@ -1518,6 +1520,9 @@ const buildGlobalSystemPrompt = ( canDraftResources || canDraftVariables const canDeploy = !access || access.has('deploy') + // Holds none of the capabilities below, so every `can*` reads false; the blocks that blame + // the user's role for that check this first. + const readOnly = isReadOnlyAccess(access) // Whether deploy_workspace_item and delete_workspace_item keep any kind: only schedules and // triggers skip the deploy rules, and an admin passes them. const canDeployAnyKind = @@ -1651,31 +1656,33 @@ The current user's workspace username is "${username}".${instanceLine} ${ canWriteDraft ? 'Use tools to inspect workspace items and create per-user drafts (saved server-side, visible only to this user — not deployed) for scripts, flows, schedules, triggers, resources, variables, and raw apps.' - : `Use tools to inspect workspace items and the workspace's run history, and to run items that are already deployed. You cannot create or edit ${listJoin(refusedKinds, 'disjunction')} here — this user's role does not allow it — so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had. Their role is refused ${listJoin(refusedCode)} outside this chat too, so for those suggest asking a workspace admin, who can grant their role more in ${OPERATOR_SETTINGS_LOCATION}, rather than creating them in the editor.${when( - canManageSchedules, - ' To make something recur, they can schedule a deployed script or flow themselves; only when none does the job is there something to ask an admin for, and it is that script.' - )} When you decline something, give the reason stated here and keep to it.${when( - buildsFlows, - '\n\nFlows are the exception: this workspace lets them compose flows out of scripts and flows that are already deployed. Write flow drafts with write_flow and patch_flow_json, using only steps that call a deployed script or flow by path. The server refuses inline code anywhere in the flow, so never add a rawscript step or inline code; when the flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An AI agent step may link a saved agent they can read, which runs its tools as the agent defines them. Its `tool_inputs` may only fill tool inputs the agent leaves for the AI to fill: the server refuses a step that changes an input the agent sets.' - )}${when( - buildsApps, - `\n\nRaw apps are ${buildsFlows ? 'an exception too' : 'the exception'}: this workspace lets them build raw apps whose backend calls scripts and flows that are already deployed. Call get_instructions with subject "app" first, then write app drafts with init_app and the app file and runnable tools, making every backend runnable a path runnable to a deployed script or flow. The server refuses inline and hub runnables, so never write one; when the app needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An app this user deploys always runs sandboxed, and runs its runnables as the user who deployed it: turning the sandbox off or running them as the viewer is refused. If asked, say operators cannot, because the app's code would then run with the permissions of whoever opens it.` - )}${when( - !!draftedOperatorKinds, - `\n\nThis workspace lets them create and edit ${draftedOperatorKinds}: write them as drafts with ${listJoin( - [ - canDraftResources && 'write_resource (call search_resource_types first)', - canDraftVariables && 'write_variable', - canDraftSchedules && 'write_schedule', - canDraftTriggers && - 'write_trigger (call get_trigger_schema first: the config fields differ per kind)' - ] - )}${ - deployableKinds.length - ? `, then deploy ${deployableKinds.length === draftedKinds.length ? 'them' : listJoin(deployableKinds)} with deploy_workspace_item once the user asks` - : '' - }.` - )}` + : readOnly + ? "Use tools to inspect workspace items, the workspace's run history and its data, and to run items that are already deployed. This session is read-only: you cannot create, edit, deploy or delete anything here, nor test-run code that is not deployed. When the user asks for such a change, say plainly that it cannot be made in this session, and tell them how to make it as the session context below says, rather than describing steps as if you had made it." + : `Use tools to inspect workspace items and the workspace's run history, and to run items that are already deployed. You cannot create or edit ${listJoin(refusedKinds, 'disjunction')} here — this user's role does not allow it — so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had. Their role is refused ${listJoin(refusedCode)} outside this chat too, so for those suggest asking a workspace admin, who can grant their role more in ${OPERATOR_SETTINGS_LOCATION}, rather than creating them in the editor.${when( + canManageSchedules, + ' To make something recur, they can schedule a deployed script or flow themselves; only when none does the job is there something to ask an admin for, and it is that script.' + )} When you decline something, give the reason stated here and keep to it.${when( + buildsFlows, + '\n\nFlows are the exception: this workspace lets them compose flows out of scripts and flows that are already deployed. Write flow drafts with write_flow and patch_flow_json, using only steps that call a deployed script or flow by path. The server refuses inline code anywhere in the flow, so never add a rawscript step or inline code; when the flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An AI agent step may link a saved agent they can read, which runs its tools as the agent defines them. Its `tool_inputs` may only fill tool inputs the agent leaves for the AI to fill: the server refuses a step that changes an input the agent sets.' + )}${when( + buildsApps, + `\n\nRaw apps are ${buildsFlows ? 'an exception too' : 'the exception'}: this workspace lets them build raw apps whose backend calls scripts and flows that are already deployed. Call get_instructions with subject "app" first, then write app drafts with init_app and the app file and runnable tools, making every backend runnable a path runnable to a deployed script or flow. The server refuses inline and hub runnables, so never write one; when the app needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An app this user deploys always runs sandboxed, and runs its runnables as the user who deployed it: turning the sandbox off or running them as the viewer is refused. If asked, say operators cannot, because the app's code would then run with the permissions of whoever opens it.` + )}${when( + !!draftedOperatorKinds, + `\n\nThis workspace lets them create and edit ${draftedOperatorKinds}: write them as drafts with ${listJoin( + [ + canDraftResources && 'write_resource (call search_resource_types first)', + canDraftVariables && 'write_variable', + canDraftSchedules && 'write_schedule', + canDraftTriggers && + 'write_trigger (call get_trigger_schema first: the config fields differ per kind)' + ] + )}${ + deployableKinds.length + ? `, then deploy ${deployableKinds.length === draftedKinds.length ? 'them' : listJoin(deployableKinds)} with deploy_workspace_item once the user asks` + : '' + }.` + )}` }` const paths = `${when( canWriteAnyDraft, @@ -1725,11 +1732,11 @@ ${groupMembershipRule}- Listings and reads return only what this user can see: i ' Use delete_workspace_item only to remove an item that is already deployed in the workspace; it mutates the workspace and fails if nothing is deployed at that path.' )}` )}${when( - !canWriteAnyDraft, + !canWriteAnyDraft && !readOnly, ` - Three changes are still open to you where the server allows them: discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes an item already deployed in the workspace — each only for the kinds its type lists. You cannot create or edit one.` )}${when( - !canManageSchedules || !canManageTriggers, + (!canManageSchedules || !canManageTriggers) && !readOnly, ` - This workspace does not let this user change ${ !canManageSchedules && !canManageTriggers @@ -2953,6 +2960,11 @@ export type SessionPromptContext = { forkParentUnknown?: boolean /** Pre-send intent: a staged fork of this workspace is created at first send. */ pendingForkOf?: string + /** The family's dev workspace, where a read-only session sends the user to make changes. */ + devWorkspace?: { id: string; name: string } + /** Why the session is in Use mode, where the workspace itself is not protected: the user + * picked it, or their role builds nothing there. */ + useMode?: 'chosen' | 'role' } /** Session-state guidance appended to the global system prompt so the model @@ -2979,9 +2991,17 @@ export function getSessionContextPromptSection( (!access || access.has('manage_schedules')) && 'schedules', (!access || access.has('manage_triggers')) && 'triggers' ].filter((k): k is string => !!k) + const readOnly = isReadOnlyAccess(access) + // Read-only either because the user chose Use or because the workspace forces it. + const protectedWorkspace = readOnly && !ctx.useMode // With no kind left to deploy, the deploy tool is not shipped, so the lines below cannot name it. - const deployer = canDeploy || unruledKinds.length ? 'deploy_workspace_item' : 'A deploy' - const targets = ['reads', canWriteDraft && 'drafts', canRunPreview && 'test runs', 'deploys'] + const deployer = + !readOnly && (canDeploy || unruledKinds.length) ? 'deploy_workspace_item' : 'A deploy' + const targets = ( + readOnly + ? ['reads', 'runs'] + : ['reads', canWriteDraft && 'drafts', canRunPreview && 'test runs', 'deploys'] + ) .filter(Boolean) .join(', ') const lines = [ @@ -2994,6 +3014,14 @@ export function getSessionContextPromptSection( lines.push( `- No workspace is committed yet: a staged fork of workspace "${ctx.pendingForkOf}" is created automatically when the first message is sent, and all work lands in that fork.` ) + } else if (protectedWorkspace) { + const dev = ctx.devWorkspace?.id !== ctx.workspaceId ? ctx.devWorkspace : undefined + const elsewhere = dev + ? `start a new session in the dev workspace "${dev.id}", which the "New session in ${dev.name} (dev)" entry of the composer's mode picker opens` + : 'start a new session in a fork of this workspace, or, where forking is refused too, make the change in git and open a pull request' + lines.push( + `- Operating workspace: "${ctx.workspaceId}" — a production workspace protected against direct changes, so this session is READ-ONLY whatever the user's role. To make a change, the user needs to ${elsewhere}. This session's mode picker shows Plan and Use & build greyed out and its workspace cannot change once it has started, so never suggest picking Use & build or switching this session.` + ) } else if (ctx.parentWorkspaceId && ctx.isDevWorkspace) { lines.push( `- Operating workspace: "${ctx.workspaceId}" — the user's persistent DEV WORKSPACE, forked from workspace "${ctx.parentWorkspaceId}". ${deployer} publishes into the dev workspace only; the user reviews & promotes changes into "${ctx.parentWorkspaceId}" from the session's deploy panel. Never present a change as live in "${ctx.parentWorkspaceId}".` @@ -3015,9 +3043,18 @@ export function getSessionContextPromptSection( '- No operating workspace is set yet; the user picks one (or a new staged fork) before the first message is sent.' ) } + if (readOnly && ctx.useMode === 'chosen') { + lines.push( + "- The user put this session in Use mode with the composer's mode picker, so it is READ-ONLY until they switch. To make a change, call `enter_build_mode`, which asks them to switch to Use & build, or `enter_plan_mode` to agree on the change first; without those tools, ask them to switch the picker." + ) + } else if (readOnly && ctx.useMode === 'role') { + lines.push( + `- This user's workspace role cannot create or change scripts, flows, apps, schedules or triggers, neither through you nor by hand anywhere in the workspace. That role, not this session, is why the session is held in Use mode and is READ-ONLY. When they ask for one, say that their role does not allow it, and that a workspace admin can create it for them or grant their role more in ${OPERATOR_SETTINGS_LOCATION}. Do not write its code or give steps: they can use neither. Their mode picker shows Plan and Use & build greyed out, so never suggest switching modes. Resources and variables are the exception: every role creates and edits those by hand, outside this session, on the workspace's own Resources and Variables pages.` + ) + } // The kind enum already withholds what the rules refuse; this says why, and where the user // promotes the rest instead. The rules gate deletes too, so it is owed to every such profile. - if (!canDeploy) { + if (!canDeploy && !readOnly) { lines.push( `- This workspace refuses direct deployment for this user${ unruledKinds.length === 2 @@ -3030,7 +3067,7 @@ export function getSessionContextPromptSection( } lines.push( '- Sessions are saved: the sidebar lists them under AI Sessions, and the user can reopen any of them.', - '- The composer has a permission mode picker: Ask permission, Auto-accept edits, Yolo (bypass permissions: tool confirmations are accepted without asking) and Plan (read-only). Some modes are hidden where they do not apply.', + `- The composer has a mode picker in two parts. What you may do: Use (read and run deployed items, change nothing), Plan (research, then propose a plan for approval) and Use & build (everything Use does, plus changes). How tool confirmations work: Ask permission, Auto-accept edits, or Yolo (bypass permissions: tool confirmations are accepted without asking). Some options are hidden where they do not apply${protectedWorkspace ? ', and this workspace locks the picker to Use' : ctx.useMode === 'role' ? ", and this user's role locks the picker to Use" : ''}.`, "- The sliders button next to the model picker opens Assistant settings. Its Permissions section shows what the user's role lets them change and what you can change for them; point them there when they ask what they are allowed to do." ) return lines.join('\n') @@ -3262,7 +3299,9 @@ export async function resolveGlobalPromptIdentity( // for the global side-panel chat. The tool only ever advertises, and only ever acts on, // `pages`. async function allowedOpenPages( - workspaceId: string | undefined = get(workspaceStore) + workspaceId: string | undefined = get(workspaceStore), + /** A read-only session reaches what an operator reaches: never workspace settings. */ + readOnly = false ): Promise<{ pages: OpenPageName[]; roleUnverified: boolean }> { const role = await roleForWorkspace(workspaceId) // A failed lookup says nothing about the role, so guessing a page set can offer one the @@ -3280,7 +3319,9 @@ async function allowedOpenPages( { ...u, is_admin: isAdmin }, get(userWorkspaces).find((w) => w.id === workspaceId) ) - return { pages: roleOpenPages(caps, isAdmin), roleUnverified: false } + return readOnly + ? { pages: roleOpenPages(withoutBuilding(caps), false), roleUnverified: false } + : { pages: roleOpenPages(caps, isAdmin), roleUnverified: false } } // The Runs page only offers its cross-workspace filter to a superadmin or devops user in @@ -3762,7 +3803,10 @@ export const openPageTool: SessionTool<{}> = { // Re-narrow the advertised `page` enum to this user's permissions each iteration, so // the model never sees (or suggests) a page the user can't reach. schemaFor: async (helpers) => { - const access = await allowedOpenPages(operatingWorkspaceFromHelpers(helpers)) + const access = await allowedOpenPages( + operatingWorkspaceFromHelpers(helpers), + isReadOnlyAccess((helpers as GlobalToolHelpers | undefined)?.access) + ) return createToolDef( buildOpenPageDefSchema( access.pages, @@ -3783,7 +3827,10 @@ export const openPageTool: SessionTool<{}> = { // requests one outside the advertised enum. An unverified role means the lookup // failed, not that access was denied — reporting it as denied states a falsehood // about the user's permissions. - const access = await allowedOpenPages(workspaceId) + const access = await allowedOpenPages( + workspaceId, + isReadOnlyAccess((ctx.helpers as GlobalToolHelpers | undefined)?.access) + ) if (!access.pages.includes(page)) { const label = OPEN_PAGE_LABELS[page] ?? page return access.roleUnverified @@ -3975,6 +4022,8 @@ export const globalTools: SessionTool<{}>[] = [ 'update_user_instructions', 'Modify your own persistent personal instructions for the Global assistant. Use when the user asks you to remember a preference, always/never do something, or change/stop a behavior. Edits only the user-level instructions (the USER INSTRUCTIONS block, not workspace-level); changes persist in this browser and take effect on your next message.' ), + // Writes this browser's preference, not the workspace. + readOnlySafe: true, showDetails: true, fn: async ({ args, toolId, toolCallbacks, helpers }) => { const parsed = updateUserInstructionsSchema.parse(args) @@ -4425,6 +4474,7 @@ export const globalTools: SessionTool<{}>[] = [ // permissions, the one run an operator's token allows. `run_flow` likewise. requires: NONE, def: runScriptToolDef, + readOnlySafe: true, fn: async (ctx) => { const parsed = runScriptSchema.parse(ctx.args) return runDeployedScript(parsed, ctx) @@ -4457,6 +4507,7 @@ export const globalTools: SessionTool<{}>[] = [ { requires: NONE, def: runFlowToolDef, + readOnlySafe: true, fn: async (ctx) => { const parsed = runFlowSchema.parse(ctx.args) return runDeployedFlow(parsed, ctx) @@ -4594,6 +4645,8 @@ export const globalTools: SessionTool<{}>[] = [ 'cancel_job', 'Cancel a running or queued job by its id (e.g. a background test run you started that is no longer needed).' ), + // A run the session may start, it may also stop. + readOnlySafe: true, showDetails: true, fn: async ({ args, workspace, toolId, toolCallbacks }) => { const parsed = cancelJobSchema.parse(args) @@ -5032,6 +5085,8 @@ export const globalTools: SessionTool<{}>[] = [ { requires: NONE, def: createToolDef(openPreviewSchema, 'open_preview', OPEN_PREVIEW_DESCRIPTION), + // A read-only session holds no draft capability, so the schema below offers it viewers. + readOnlySafe: true, // Withhold the editors a session cannot save, so the model never offers the user a // panel it would not get. schemaFor: async (helpers) => { @@ -5080,6 +5135,7 @@ export const globalTools: SessionTool<{}>[] = [ 'close_page', 'Close one or more preview tabs in the side panel of this AI session. Pass `match` to close the tab(s) whose page name or item path contains that text, or `all: true` to clear the panel. Use this when the user asks to close/dismiss a tab they no longer need. Only works inside a session.' ), + readOnlySafe: true, fn: async (ctx) => { const parsed = closePageSchema.parse(ctx.args) return closeSessionPreviewTabs(parsed, sessionIdFromCtx(ctx)) @@ -6750,6 +6806,17 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st } const blockedBeforeForm = blockedByPlanMode() if (blockedBeforeForm) return blockedBeforeForm + // The form is this call's confirmation, and a session can switch to Use while it waits. + const withdrawnByUseMode = (): string | undefined => { + if (!toolCallbacks.isToolWithdrawn?.(spec.toolName)) return undefined + toolCallbacks.setToolStatus(toolId, { + content: USE_MODE_WITHDRAWN.label, + isLoading: false, + isStreamingArguments: false, + error: USE_MODE_WITHDRAWN.result + }) + return USE_MODE_WITHDRAWN.result + } const schema = spec.schema // Whether to ask is the only question decided here. What a mounted field would hold — a @@ -6844,7 +6911,7 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st const adopted = answer.kind === 'job' ? answer : undefined const submitted = answer.args - const blockedBeforeRun = adopted ? undefined : blockedByPlanMode() + const blockedBeforeRun = adopted ? undefined : (blockedByPlanMode() ?? withdrawnByUseMode()) if (blockedBeforeRun) { toolCallbacks.markRunFormEnded?.(toolId) return blockedBeforeRun diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts index e1da0fb624..0898837658 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts @@ -365,6 +365,8 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo ...(isRead ? { planModeSafe: true } : { + // Changes the external system, never the workspace, like a deployed run does. + readOnlySafe: true, requiresConfirmation: true, confirmAction: 'run', confirmationMessage: (args: any) => `Call ${args?.tool ?? ''} on ${args?.server ?? ''}` diff --git a/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts b/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts index 89a13403f0..46d744fb10 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts @@ -1,12 +1,18 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -const { whoami, deployRules } = vi.hoisted(() => ({ +const { whoami, deployRules, protectionRules } = vi.hoisted(() => ({ whoami: vi.fn(), - deployRules: vi.fn() + deployRules: vi.fn(), + protectionRules: vi.fn() })) vi.mock('$lib/gen', () => ({ UserService: { whoami } })) vi.mock('$lib/utils_workspace_deploy', () => ({ checkDeployRules: deployRules })) +vi.mock('$lib/workspaceProtectionRules.svelte', () => ({ + readProtectionRulesForWorkspace: protectionRules, + isRuleActiveInRulesets: (rulesets: { rules: string[] }[], kind: string) => + rulesets.some((r) => r.rules.includes(kind)) +})) import { capabilitiesForRole, resolveSessionAccess } from './sessionAccess' import { clearWorkspaceRoleCache } from '$lib/user' @@ -41,6 +47,7 @@ describe('resolveSessionAccess', () => { beforeEach(() => { vi.clearAllMocks() deployRules.mockResolvedValue({ ok: true }) + protectionRules.mockResolvedValue([]) // The role memo is app-wide, so without this each case answers from the previous one. clearWorkspaceRoleCache() }) @@ -54,6 +61,7 @@ describe('resolveSessionAccess', () => { 'manage_flows', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'run_flow_preview', 'run_preview', 'write_app_draft', @@ -76,6 +84,7 @@ describe('resolveSessionAccess', () => { 'deploy', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'write_resource_draft', 'write_schedule_draft', 'write_trigger_draft', @@ -89,6 +98,7 @@ describe('resolveSessionAccess', () => { expect([...caps].sort()).toEqual([ 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'write_resource_draft', 'write_schedule_draft', 'write_trigger_draft', @@ -110,6 +120,7 @@ describe('resolveSessionAccess', () => { 'manage_flows', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'run_flow_preview', 'run_preview', 'write_app_draft', @@ -125,6 +136,26 @@ describe('resolveSessionAccess', () => { } ) + // A production workspace: the session reads and runs, and holds nothing that writes, even + // for an admin the rule would let through. + it('makes the session read-only in a workspace protected by DisableDirectDeployment', async () => { + protectionRules.mockResolvedValue([{ rules: ['DisableDirectDeployment'] }]) + const caps = await capabilitiesFor({ is_admin: true }) + expect([...caps]).toEqual([]) + }) + + // The server holds deploys to the rule but not drafts, so neither failure may hand a + // production session its writes. + it('stays read-only when the rules cannot be read, or the role of a protected workspace', async () => { + protectionRules.mockResolvedValue(undefined) + expect([...(await capabilitiesFor({ is_admin: true }))]).toEqual([]) + + // Another workspace: the role memo answers for the first one. + protectionRules.mockResolvedValue([{ rules: ['DisableDirectDeployment'] }]) + whoami.mockRejectedValueOnce(new Error('network')) + expect([...(await resolveSessionAccess('prod'))]).toEqual([]) + }) + it('keeps drafting when a rule refuses deploy', async () => { deployRules.mockResolvedValue({ ok: false, @@ -149,6 +180,7 @@ describe('resolveSessionAccess', () => { 'manage_flows', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'run_flow_preview', 'write_flow_draft', 'write_resource_draft', @@ -170,6 +202,7 @@ describe('resolveSessionAccess', () => { 'manage_apps', 'manage_schedules', 'manage_triggers', + 'modify_workspace', 'write_app_draft', 'write_resource_draft', 'write_schedule_draft', diff --git a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts index 8d4527091a..6c58900eab 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts @@ -1,11 +1,15 @@ import { get } from 'svelte/store' import { userWorkspaces } from '$lib/stores' -import type { RoleCapabilities } from '$lib/gen' +import type { ProtectionRuleset, RoleCapabilities } from '$lib/gen' import { getWorkspaceRole } from '$lib/user' import { roleCanAuthor, roleCanDraft } from '$lib/editRights' import { capabilitiesIn, FULL_CAPABILITIES } from '$lib/roleCapabilities' import { checkDeployRules } from '$lib/utils_workspace_deploy' -import type { SessionAccess, SessionCapability } from '../sessionCapabilities' +import { + isRuleActiveInRulesets, + readProtectionRulesForWorkspace +} from '$lib/workspaceProtectionRules.svelte' +import { USE_MODE_ACCESS, type SessionAccess, type SessionCapability } from '../sessionCapabilities' const ALL_CAPABILITIES: SessionCapability[] = [ 'write_draft', @@ -25,13 +29,15 @@ const ALL_CAPABILITIES: SessionCapability[] = [ 'manage_apps', 'manage_schedules', 'manage_triggers', - 'admin' + 'admin', + 'modify_workspace' ] -/** Fail open, here and at every resolution failure below: blanking a toolset on a +/** Fail open, here and at every role resolution failure below: blanking a toolset on a * transient error tells a developer mid-session that they cannot author anything, * which is worse and far less legible than the 403 they get by trying. Matches - * `checkDeployPermission`, which fails open for the same reason. */ + * `checkDeployPermission`, which fails open for the same reason. The protection rule is + * the exception (`protects`). */ export function fullSessionAccess(): SessionAccess { return new Set(ALL_CAPABILITIES) } @@ -45,7 +51,7 @@ export function capabilitiesForRole(role: { deployRulesPass: boolean capabilities: RoleCapabilities }): SessionAccess { - const capabilities = new Set<SessionCapability>() + const capabilities = new Set<SessionCapability>(['modify_workspace']) const caps = role.isAdmin ? FULL_CAPABILITIES : role.capabilities if (roleCanDraft('script', caps)) { capabilities.add('write_draft') @@ -102,12 +108,53 @@ export function capabilitiesForRole(role: { return capabilities } +/** 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. */ +function protects(rulesets: ProtectionRuleset[] | undefined): boolean { + return !rulesets || isRuleActiveInRulesets(rulesets, 'DisableDirectDeployment') +} + +// The session UI asks this from every preview tab, the composer and the picker, and the rules +// fetch behind it is not cached, so they share one verdict per workspace for a minute. +const READ_ONLY_TTL_MS = 60_000 +const readOnlyVerdicts = new Map<string, { at: number; verdict: Promise<boolean> }>() +const settledVerdicts = new Map<string, { at: number; readOnly: boolean }>() + +/** The read-only verdict alone, for the UI around a session. Fails closed as the chat does; a + * failed read is not kept, so the next ask reads the rules again. */ +export function isReadOnlySessionWorkspace(workspace: string): Promise<boolean> { + const cached = readOnlyVerdicts.get(workspace) + if (cached && Date.now() - cached.at < READ_ONLY_TTL_MS) return cached.verdict + const at = Date.now() + const verdict = readProtectionRulesForWorkspace(workspace).then((rulesets) => { + if (!rulesets) readOnlyVerdicts.delete(workspace) + else settledVerdicts.set(workspace, { at, readOnly: protects(rulesets) }) + return protects(rulesets) + }) + readOnlyVerdicts.set(workspace, { at, verdict }) + return verdict +} + +/** The verdict read for `workspace` within the minute, without asking: what the UI stands on + * while a fresh component waits for its own ask. */ +export function settledReadOnlyVerdict(workspace: string): boolean | undefined { + const settled = settledVerdicts.get(workspace) + return settled && Date.now() - settled.at < READ_ONLY_TTL_MS ? settled.readOnly : undefined +} + export async function resolveSessionAccess(workspace: string): Promise<SessionAccess> { - // Shares the 5-minute memo with the identity the same pre-flight resolves beside this - // one, so a send costs one `whoami` rather than two, at the cost of a role changed - // elsewhere landing within that window rather than on the very next message. - // `lookup_failed` covers a rejected request AND a body too malformed to map. - const lookup = await getWorkspaceRole(workspace) + const [rulesets, lookup] = await Promise.all([ + // Not the memoized verdict above: the chat's toolset follows a rule change on the next send. + readProtectionRulesForWorkspace(workspace), + // Shares the 5-minute memo with the identity the same pre-flight resolves beside this + // one, so a send costs one `whoami` rather than two, at the cost of a role changed + // elsewhere landing within that window rather than on the very next message. + // `lookup_failed` covers a rejected request AND a body too malformed to map. + getWorkspaceRole(workspace) + ]) + if (protects(rulesets)) return USE_MODE_ACCESS if (lookup.kind !== 'resolved') { return fullSessionAccess() } @@ -115,7 +162,7 @@ export async function resolveSessionAccess(workspace: string): Promise<SessionAc return capabilitiesForRole({ isAdmin: !!me.is_admin || !!me.is_super_admin, - deployRulesPass: (await checkDeployRules(workspace, me)).ok, + deployRulesPass: (await checkDeployRules(workspace, me, rulesets)).ok, capabilities: capabilitiesIn( me, get(userWorkspaces).find((w) => w.id === workspace) diff --git a/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts b/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts index dda1483c50..15f5e7a246 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts @@ -28,8 +28,15 @@ import { pipelineTools } from '../pipeline/core' import { assembleGlobalSystemMessage, assembleGlobalTools } from './globalAssembly' import { filterSessionTools, sessionToolAllowed } from './sessionToolset' import { capabilitiesForRole, fullSessionAccess } from './sessionAccess' -import type { SessionAccess, SessionCapability, SessionTool } from '../sessionCapabilities' +import { + canBuild, + USE_MODE_ACCESS, + type SessionAccess, + type SessionCapability, + type SessionTool +} from '../sessionCapabilities' import { FULL_CAPABILITIES, legacyOperatorCapabilities } from '$lib/roleCapabilities' +import { buildsAnything } from '$lib/editRights' import type { AuthorLevel, OperatorSettings, RoleCapabilities } from '$lib/gen' const ASSEMBLY_OPTS = { @@ -70,8 +77,9 @@ function shippedSessionTools(access: SessionAccess) { return filterSessionTools(assembleGlobalTools(ASSEMBLY_OPTS), access) } +/** A session that can change the workspace, holding `capabilities` besides. */ function accessWith(capabilities: SessionCapability[]): SessionAccess { - return new Set(capabilities) + return new Set<SessionCapability>(['modify_workspace', ...capabilities]) } const LEVELS: AuthorLevel[] = ['none', 'compose', 'full'] @@ -98,8 +106,8 @@ const ROLES: RoleCapabilities[] = [false, true] .filter((c) => c.code || (c.flows !== 'full' && c.apps !== 'full')) /** The profiles a real session can hold, keyed for the test name, over every combination - * of the role facts `capabilitiesForRole` reads. */ -const REACHABLE_PROFILES = [ + * of the role facts `capabilitiesForRole` reads, and the read-only one. */ +const REACHABLE_PROFILES: [string, SessionAccess][] = [ ...new Map( [false, true].flatMap((isAdmin) => // `checkDeployRules` bypasses on admin, so an admin has only the one outcome. @@ -110,7 +118,8 @@ const REACHABLE_PROFILES = [ }) ) ) - ).entries() + ).entries(), + ['read-only', USE_MODE_ACCESS] ] /** One per branch of getSessionContextPromptSection — each words the deploy target @@ -134,6 +143,15 @@ describe('session tool policies', () => { filtered.forEach((tool, i) => expect(tool).toBe(tools[i])) }) + // The mode picker reads the role and the toolset reads the access built from it: if they + // disagree, the picker offers Build while the chat holds only Use's tools, or the reverse. + it('agrees with the role on whether the session can build', () => { + for (const capabilities of ROLES) { + const access = capabilitiesForRole({ isAdmin: false, deployRulesPass: true, capabilities }) + expect(canBuild(access)).toBe(buildsAnything(capabilities)) + } + }) + it('withholds a tool that arrives without a policy', () => { expect(sessionToolAllowed({ def: globalTools[0].def }, fullSessionAccess())).toBe(false) }) @@ -212,6 +230,17 @@ describe('session tool policies', () => { expect((original.def.function.parameters as any).properties.type.enum).toContain('script') }) + // Keyed on the tags, so a tool added untagged stays out of a production workspace. + it('ships a read-only session the reads and the deployed runs, and nothing that writes', () => { + const shipped = shippedSessionTools(USE_MODE_ACCESS) + expect(shipped.filter((t) => !t.planModeSafe && !t.readOnlySafe)).toEqual([]) + const names = shipped.map((t) => t.def.function.name) + expect(names).toEqual(expect.arrayContaining(['read_workspace_item', 'list_runs', 'run_flow'])) + for (const write of ['write_script', 'test_run_script', 'deploy_workspace_item']) { + expect(names).not.toContain(write) + } + }) + it('offers the workspace settings tools to admins only', () => { const settingsTools = ['get_workspace_settings', 'set_workspace_settings'] for (const [, access] of REACHABLE_PROFILES) { diff --git a/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts b/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts index 0d8f8753a2..7a867f0c01 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts @@ -1,10 +1,12 @@ import type { ChatCompletionFunctionTool } from 'openai/resources/index.mjs' -import type { SessionAccess, SessionToolPolicy } from '../sessionCapabilities' +import { isReadOnlyAccess, type SessionAccess, type SessionToolPolicy } from '../sessionCapabilities' type FilterableTool = { def: ChatCompletionFunctionTool requires?: SessionToolPolicy kindRequires?: Readonly<Partial<Record<string, SessionToolPolicy>>> + planModeSafe?: boolean + readOnlySafe?: boolean } const satisfies = (policy: SessionToolPolicy, access: SessionAccess) => @@ -13,7 +15,15 @@ const satisfies = (policy: SessionToolPolicy, access: SessionAccess) => /** Fails closed: every array that feeds a session is typed to declare `requires`, so a tool * without one arrived some other way, and leaking it is the worse of the two answers. */ export function sessionToolAllowed(tool: FilterableTool, access: SessionAccess): boolean { - return tool.requires ? satisfies(tool.requires, access) : false + if (!tool.requires || !satisfies(tool.requires, access)) return false + return !isReadOnlyAccess(access) || readOnlyToolAllowed(tool) +} + +/** A read-only session keeps the reads `planModeSafe` already marks, plus what opts in with + * `readOnlySafe`. Keyed on the tags rather than a list of writes, so a tool added untagged + * stays out of a production workspace until someone decides it belongs there. */ +function readOnlyToolAllowed(tool: FilterableTool): boolean { + return tool.planModeSafe === true || tool.readOnlySafe === true } /** Filter an assembled toolset, and cut each kind-taking tool's `type` enum to the kinds diff --git a/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts b/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts index 01e5040040..c4f4ab6355 100644 --- a/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/planModeController.svelte.ts @@ -21,8 +21,8 @@ import { normalizeChangeNote } from './artifacts/artifactLimits' import { currentVersion } from './artifacts/artifactsDB' import { type SessionArtifactsStore } from './artifacts/artifactsState.svelte' -/** What plan mode needs from the chat it runs in: it reads the autonomy state and asks for - * the two changes it can cause, rather than owning any of it. */ +/** What plan mode needs from the chat it runs in: it reads the work mode and the autonomy + * state and asks for the two changes it can cause, rather than owning any of it. */ export interface PlanModeHost { /** Offered in this chat *and* selected. */ readonly active: boolean @@ -36,8 +36,8 @@ export interface PlanModeHost { readonly artifacts: SessionArtifactsStore openArtifact(id: string, name: string, version: ArtifactVersionTarget): void enter(): void - /** Hand the posture back to whatever preceded plan mode. */ - restore(): void + /** Move to Build, where the approved plan is carried out. */ + build(): void } /** Read off the write that proposed the plan, so nothing re-reads and races a later one. */ @@ -162,7 +162,7 @@ export class PlanModeController { } // Only to the round this approval belongs to: ending a re-entered round would drop the // user out of a planning posture they just chose. - if (this.#host.active && epoch === this.#epoch) this.#host.restore() + if (this.#host.active && epoch === this.#epoch) this.#host.build() return PLAN_MODE_MESSAGES.approvedWithDoc } } diff --git a/frontend/src/lib/components/copilot/chat/planModeController.test.ts b/frontend/src/lib/components/copilot/chat/planModeController.test.ts index 4e5438b906..0b6f1e5c5e 100644 --- a/frontend/src/lib/components/copilot/chat/planModeController.test.ts +++ b/frontend/src/lib/components/copilot/chat/planModeController.test.ts @@ -26,7 +26,7 @@ describe('PlanModeController', () => { let sessionId: string let docs: Doc[] let openArtifact: ReturnType<typeof vi.fn> - let restore: ReturnType<typeof vi.fn> + let build: ReturnType<typeof vi.fn> let artifacts: any let controller: PlanModeController @@ -36,7 +36,7 @@ describe('PlanModeController', () => { sessionId = 'session-1' docs = [] openArtifact = vi.fn() - restore = vi.fn(() => { + build = vi.fn(() => { active = false }) artifacts = { @@ -89,7 +89,7 @@ describe('PlanModeController', () => { enter: () => { active = true }, - restore + build } controller = new PlanModeController(host) controller.startRound() @@ -140,7 +140,7 @@ describe('PlanModeController', () => { expect(docs[0]).toMatchObject({ version: 2, approvedVersion: 1 }) }) - it('restores posture only after proposal and approval pointer are durable', async () => { + it('moves to Build only after proposal and approval pointer are durable', async () => { await propose('# Durable\n\nBuild it.') const result = await controller.exitTool.fn({ args: { summary: '# Durable\n\nBuild it.' }, @@ -151,7 +151,7 @@ describe('PlanModeController', () => { }) expect(docs[0].approvedVersion).toBe(1) - expect(restore).toHaveBeenCalledOnce() + expect(build).toHaveBeenCalledOnce() expect(result).toBe(PLAN_MODE_MESSAGES.approvedWithDoc) }) @@ -167,7 +167,7 @@ describe('PlanModeController', () => { }) expect(active).toBe(true) - expect(restore).not.toHaveBeenCalled() + expect(build).not.toHaveBeenCalled() expect(result).toBe(PLAN_MODE_MESSAGES.persistenceFailed) }) @@ -214,7 +214,7 @@ describe('PlanModeController', () => { it('refuses a second hand-over from the batch that already ended plan mode', async () => { // One response can carry two exit_plan_mode calls, and the tool list they run against is - // snapshotted before the first one restores the posture. Under YOLO nothing asks, so the + // snapshotted before the first one moves the session to Build. Under YOLO nothing asks, so the // stale call would write its own summary and stamp the user's approval on a plan no card // ever showed them. const frozenTools = [controller.exitTool] @@ -294,6 +294,6 @@ describe('PlanModeController', () => { controller.startRound() await approval expect(active).toBe(true) - expect(restore).not.toHaveBeenCalled() + expect(build).not.toHaveBeenCalled() }) }) diff --git a/frontend/src/lib/components/copilot/chat/planModeMessages.ts b/frontend/src/lib/components/copilot/chat/planModeMessages.ts index 85710d0c54..dff3ec1c13 100644 --- a/frontend/src/lib/components/copilot/chat/planModeMessages.ts +++ b/frontend/src/lib/components/copilot/chat/planModeMessages.ts @@ -9,12 +9,9 @@ export const PLAN_MODE_MESSAGES = { blockedLabel: 'Blocked in plan mode', blockedResult: 'Blocked: plan mode is active. Put this change in your plan; call exit_plan_mode when ready for approval.', - /** Sits beside the autonomy picker while plan mode holds. The picker's tooltip carries - * the rest, so this states only the constraint. */ - modeNote: 'Read-only', /** Refuses a pending run form. Its own string because nothing is settled: the form stays * live, so this names the way out rather than telling the user their run was blocked. */ - runFormRefused: 'Plan mode is read-only — switch it off to run this script.', + runFormRefused: 'Plan mode runs nothing — switch to Use, or Use & build, to run this script.', // One pair for both artifact tools: the fact and the way forward are the same whether the // model tried to mint the plan or to rewrite it, and the generic refusal above ("put this // change in your plan") reads as nonsense for a call that writes a document. @@ -46,7 +43,7 @@ export const PLAN_MODE_MESSAGES = { `The plan is too large to save (${bytes} bytes, limit ${MAX_ARTIFACT_BYTES}) and was not shown to the user. Cut it to the decisions and the steps — name the files you will touch instead of quoting them — and call exit_plan_mode again.`, // What the version picker shows for a revision the model did not label. revisionNote: 'Revised the plan', - // States the outcome, not a decision: pressing Stop and moving the autonomy picker out of + // States the outcome, not a decision: pressing Stop and moving the mode picker out of // plan mode both land here too, and this text persists in the transcript — asserting a // rejection would open the next turn interrogating a user who never made one. exitDeclined: diff --git a/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts index d3c58af681..7e80854a01 100644 --- a/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts @@ -1,4 +1,5 @@ import { AIAutonomyMode } from './AIChatManager.svelte' +import { AIWorkMode } from './workMode' import type { ChatViewHost } from './chatViewHost' import type { DisplayMessage } from './shared' import { AttachedFilesStore } from './files/attachedFiles.svelte' @@ -75,6 +76,9 @@ export function readOnlyChatViewHost(options: { tools: [], autonomyMode: AIAutonomyMode.DEFAULT, setAutonomyMode: noop, + workModesAvailable: false, + workMode: AIWorkMode.BUILD, + setWorkMode: noop, autoAcceptEditsActive: false, autoAcceptEditsAvailable: false, autoAcceptToolConfirmationsAvailable: false, diff --git a/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts b/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts index 8291a62085..1afe78bcfe 100644 --- a/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts +++ b/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts @@ -50,9 +50,40 @@ export type SessionCapability = | 'manage_triggers' /** Passes `require_admin`. */ | 'admin' + /** Held by every role. A read-only session, in a protected workspace or in Use mode, lacks it + * and ships only the tools `readOnlyToolAllowed` admits. */ + | 'modify_workspace' export type SessionAccess = ReadonlySet<SessionCapability> +/** Whether `access` is a read-only session. `undefined` access answers false, as the toolset + * filter does. */ +export function isReadOnlyAccess(access: SessionAccess | undefined): boolean { + return !!access && !access.has('modify_workspace') +} + +/** What a session in Use mode holds whatever the user's role: nothing, as in a protected + * workspace. Fixed rather than narrowed from the resolved access, so Use ships no write while + * that check is still in flight. */ +export const USE_MODE_ACCESS: SessionAccess = new Set() + +/** `buildsAnything`, read off a session's access. `undefined` access answers true, as the + * toolset filter does. */ +export function canBuild(access: SessionAccess | undefined): boolean { + return ( + !access || + ( + [ + 'write_draft', + 'write_flow_draft', + 'write_app_draft', + 'write_schedule_draft', + 'write_trigger_draft' + ] as const + ).some((c) => access.has(c)) + ) +} + /** * The capabilities without which a tool's call cannot succeed — usually because the * backend refuses it, occasionally because only that capability produces the tool's @@ -97,4 +128,7 @@ export type SessionTool<T> = Tool<T> & { * tool is either too strict or too loose: what each kind's handler needs. A session is * offered only the kinds it can land, and the rest never appear in the schema it sees. */ kindRequires?: Readonly<Partial<Record<string, SessionToolPolicy>>> + /** Ships in a read-only session although it is not `planModeSafe`: a view tool that opens + * no editor there, or a run of a deployed item, which a production workspace is for. */ + readOnlySafe?: boolean } diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index 71ef91a0b7..13623dc73e 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -8,6 +8,7 @@ import type { UserDraftItemKind } from '$lib/gen' // The gate's two refusals, from a module that holds prose and one size limit: under the // shallow-import rule below, the rest of plan mode is not reachable from here. import { PLAN_MODE_MESSAGES } from './planModeMessages' +import { USE_MODE_WITHDRAWN } from './workMode' import { NONE, type SessionTool } from './sessionCapabilities' import { integrationDisplayName } from '$lib/components/resourceTypeDisplay' // Import-free leaf, so it satisfies the shallow-import rule below. @@ -955,6 +956,7 @@ type ToolCallStatus = | 'declined' | 'rejected' | 'blocked_plan_mode' + | 'withdrawn' | 'held_for_instructions' /** Re-reads the chat loop's current tools and helpers. A call earlier in the same @@ -1038,6 +1040,27 @@ export async function processToolCall<T>({ } } + const withdrawnBlock = (): ChatCompletionMessageParam | undefined => { + if (!tool || !toolCallbacks.isToolWithdrawn?.(tool.def.function.name)) return undefined + logToolOutcome('withdrawn') + toolCallbacks.setToolStatus(toolCall.id, { + content: USE_MODE_WITHDRAWN.label, + parameters: args, + isLoading: false, + isQueued: false, + isStreamingArguments: false, + error: USE_MODE_WITHDRAWN.result, + needsConfirmation: false, + showDetails: tool.showDetails, + autoCollapseDetails: tool.autoCollapseDetails + }) + return { + role: 'tool' as const, + tool_call_id: toolCall.id, + content: USE_MODE_WITHDRAWN.result + } + } + const preConfirmationBlock = planModeBlock() if (preConfirmationBlock) { return preConfirmationBlock @@ -1157,7 +1180,7 @@ export async function processToolCall<T>({ } } - const postConfirmationBlock = planModeBlock() + const postConfirmationBlock = planModeBlock() ?? withdrawnBlock() if (postConfirmationBlock) { return postConfirmationBlock } @@ -1456,6 +1479,10 @@ export interface ToolCallbacks { shouldAutoAcceptToolConfirmations?: (toolName?: string) => boolean isPlanModeActive?: () => boolean onToolBlockedByPlanMode?: () => void + /** Whether the session has stopped shipping this tool since the call was made, as a switch to + * Use does to every write. Asked once a confirmation or a run form has been answered, since + * the switch can land while either waits. */ + isToolWithdrawn?: (toolName: string) => boolean requestUserQuestion?: ( toolId: string, question: UserQuestionDisplay diff --git a/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts index b02ce5c558..11ce754710 100644 --- a/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/starter/starterPrompts.svelte.ts @@ -40,11 +40,13 @@ export class StarterPrompts { #user = fromStore(userStore) #capabilities = fromStore(roleCapabilities) #workspace: () => string | undefined + #builds: () => boolean #signals: { readonly current: Tagged<ComposerSignals> | undefined } - /** `workspace`: where the session acts. */ - constructor(workspace: () => string | undefined) { + /** `workspace`: where the session acts. `builds`: false while the session is held in Use. */ + constructor(workspace: () => string | undefined, builds: () => boolean = () => true) { this.#workspace = workspace + this.#builds = builds void onboardingProfile().then((p) => { if (p?.starter_prompts?.length) this.#invite = p.starter_prompts }) @@ -87,10 +89,14 @@ export class StarterPrompts { } readonly suggestions: ComposerSuggestion[] = $derived.by(() => { - if (this.#invite) return this.#invite.map((p) => ({ ...p, mode: 'build' as const })) + const builds = this.#builds() + // Not while held in Use: the invite's prompts are written to be built. + if (this.#invite && builds) return this.#invite.map((p) => ({ ...p, mode: 'build' as const })) const signals = this.#currentSignals const role = this.#role - return signals && role ? composerSuggestions(signals, role) : [] + if (!signals || !role) return [] + // A session held in Use authors nothing, so it gets an operator's suggestions. + return composerSuggestions(signals, builds ? role : { ...role, operator: true }) }) /** Whether the workspace holds fewer than `FEW_ITEMS`, below which Home's composer rests diff --git a/frontend/src/lib/components/copilot/chat/workMode.ts b/frontend/src/lib/components/copilot/chat/workMode.ts new file mode 100644 index 0000000000..ffedf912b5 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/workMode.ts @@ -0,0 +1,63 @@ +// A leaf: the chat hosts and the session UI around them read these without loading the manager. + +/** What a session chat may do, picked in the composer beside the confirmations posture. */ +export enum AIWorkMode { + /** Reads and runs deployed items, and changes nothing. Locks the session's preview too. */ + USE = 'use', + /** Researches, then proposes a plan for the user's approval. Runs nothing. */ + PLAN = 'plan', + /** Shown as "Use & build": everything Use does, plus edits, tests and deploys. */ + BUILD = 'build' +} + +/** Why a session cannot leave Use, and where the user can build instead. */ +export type WorkModeLock = { + reason: string + escape?: { label: string; action: () => void } +} + +/** The answer to a call approved after its session switched to Use: the card or form it + * waited on was approved, but the mode the session is in now withholds the tool. */ +export const USE_MODE_WITHDRAWN = { + label: 'Not run: the session is in Use', + result: + 'Not run: the user switched this session to Use mode, which changes nothing, while this call waited for them. Do not retry it; it can run once they switch back to Use & build.', + /** On a test-run form left open across the switch. */ + testRunRefused: 'Use mode does not run undeployed code. Switch to Use & build to run this test.' +} + +/** The chat's tools that ask the user to move the session between Use and Use & build, each + * with the mode its card leads to. Named here because the card renderer and the picker resolve + * them by name. */ +export const ENTER_BUILD_MODE_TOOL = 'enter_build_mode' +export const ENTER_USE_MODE_TOOL = 'enter_use_mode' +export const WORK_MODE_SWITCH_TARGET = { + [ENTER_BUILD_MODE_TOOL]: AIWorkMode.BUILD, + [ENTER_USE_MODE_TOOL]: AIWorkMode.USE +} as const + +export type WorkModeSwitchTool = keyof typeof WORK_MODE_SWITCH_TARGET + +export function isWorkModeSwitchTool(name: string | undefined): name is WorkModeSwitchTool { + // hasOwn, not `in`: the name comes from the model, and `in` would accept `toString`. + return name !== undefined && Object.hasOwn(WORK_MODE_SWITCH_TARGET, name) +} + +/** In the shape of plan mode's card copy, whose card these render as. `declined` names the + * outcome: picking another mode in the picker resolves the card too. */ +export const WORK_MODE_SWITCH_CARD_COPY = { + [ENTER_BUILD_MODE_TOOL]: { + pending: 'Switch to Use & build?', + confirm: 'Switch to Use & build', + reject: 'Stay in Use', + settled: 'Switched to Use & build', + declined: 'Not switched to Use & build' + }, + [ENTER_USE_MODE_TOOL]: { + pending: 'Switch to Use?', + confirm: 'Switch to Use', + reject: 'Stay in Use & build', + settled: 'Switched to Use', + declined: 'Not switched to Use' + } +} as const diff --git a/frontend/src/lib/components/copilot/chat/workModeSwitch.ts b/frontend/src/lib/components/copilot/chat/workModeSwitch.ts new file mode 100644 index 0000000000..1752ee4cdf --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/workModeSwitch.ts @@ -0,0 +1,84 @@ +import { z } from 'zod' +import { createToolDef } from './shared' +import { NONE, type SessionTool } from './sessionCapabilities' +import { + ENTER_BUILD_MODE_TOOL, + ENTER_USE_MODE_TOOL, + WORK_MODE_SWITCH_CARD_COPY, + WORK_MODE_SWITCH_TARGET, + type AIWorkMode, + type WorkModeSwitchTool +} from './workMode' + +const switchArgs = z.object({ + reason: z + .string() + .describe('One concise sentence on why, shown to the user on the card that asks them.') +}) + +const DESCRIPTIONS: Record<WorkModeSwitchTool, string> = { + [ENTER_BUILD_MODE_TOOL]: + 'Asks the user to switch this session from Use to Use & build, the mode that also edits, tests and deploys. Call it when they ask for a change, which Use cannot make: the switch, and the tools that change the workspace, come only if they accept. Not for questions or for running deployed items, which Use already does.', + [ENTER_USE_MODE_TOOL]: + 'Asks the user to switch this session to Use, which reads and runs deployed items and changes nothing. Call it only when they ask you to stop changing the workspace in this session, never for a single question. The switch happens only if they accept.' +} + +// `declined` names the switch, not a mode: picking another mode in the picker declines the card too. +const RESULTS: Record<WorkModeSwitchTool, { switched: string; declined: string }> = { + [ENTER_BUILD_MODE_TOOL]: { + switched: + 'The user switched this session to Use & build. The tools that change the workspace are available from your next step: go on with the change they asked for.', + declined: + 'The user did not switch this session to Use & build. Do not make the change: carry on in the mode the session is in now, and say they can pick Use & build in the mode picker whenever they want it.' + }, + [ENTER_USE_MODE_TOOL]: { + switched: + 'The user switched this session to Use: from your next step you read and run deployed items, and change nothing.', + declined: + 'The user did not switch this session to Use. Carry on in the mode the session is in now.' + } +} + +const NO_LONGER_APPLIES = { + label: 'Switch no longer applies', + result: + 'Not run: the session changed mode before the user saw this switch. Carry on in the mode it is in now.' +} + +/** What a switch needs from the chat it runs in. */ +export interface WorkModeSwitchHost { + /** Whether the chat offers this switch now, from the mode the session is in. */ + offers(tool: WorkModeSwitchTool): boolean + setWorkMode(mode: AIWorkMode): void +} + +export function workModeSwitchTools( + host: WorkModeSwitchHost +): Record<WorkModeSwitchTool, SessionTool<any>> { + return { + [ENTER_BUILD_MODE_TOOL]: workModeSwitchTool(ENTER_BUILD_MODE_TOOL, host), + [ENTER_USE_MODE_TOOL]: workModeSwitchTool(ENTER_USE_MODE_TOOL, host) + } +} + +/** The switch happens in `fn`, so only once the user accepted the card: the chat stops offering + * the switches while confirmations are auto-accepted, and that posture never answers one. */ +function workModeSwitchTool(tool: WorkModeSwitchTool, host: WorkModeSwitchHost): SessionTool<any> { + return { + requires: NONE, + def: createToolDef(switchArgs, tool, DESCRIPTIONS[tool]), + // It changes no workspace item, only this session's mode. Not planModeSafe: a call left + // over from Use must not take a session out of Plan past its plan's approval. + readOnlySafe: true, + requiresConfirmation: true, + // A card queued behind another call can come up after the picker moved on. + validateBeforeConfirmation: () => (host.offers(tool) ? undefined : NO_LONGER_APPLIES), + confirmationMessage: WORK_MODE_SWITCH_CARD_COPY[tool].pending, + cancellationMessage: RESULTS[tool].declined, + showDetails: true, + fn: async () => { + host.setWorkMode(WORK_MODE_SWITCH_TARGET[tool]) + return RESULTS[tool].switched + } + } +} diff --git a/frontend/src/lib/components/details/FlowDetail.svelte b/frontend/src/lib/components/details/FlowDetail.svelte index b700269e93..862435fb57 100644 --- a/frontend/src/lib/components/details/FlowDetail.svelte +++ b/frontend/src/lib/components/details/FlowDetail.svelte @@ -79,6 +79,7 @@ import { setOperatingWorkspace, useOperatingUser, + useReadOnlyWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' import FlowChat from '$lib/components/flows/conversations/FlowChat.svelte' @@ -139,13 +140,16 @@ const operatingHref = useOperatingWorkspaceHref() const actingUser = $derived(operatingUser.current) const editRights = useEditRights() + const readOnly = useReadOnlyWorkspace() let flow: Flow | undefined = $state() // Derived, not assigned during the load: in a fork the acting user is looked up // asynchronously, and a value read after `getFlowByPath` resolves can land before that // lookup does. Assigned once, that leaves the page permanently read-only — `canWrite` // refuses an unknown user — with nothing to recompute it. - const can_write = $derived(!!flow && canWrite(flow.path, flow.extra_perms!, actingUser)) + const can_write = $derived( + !!flow && !readOnly(workspace) && canWrite(flow.path, flow.extra_perms!, actingUser) + ) const promptForAi = $derived((flow?.schema?.prompt_for_ai as string | undefined) ?? '') let shareModal: ShareModal | undefined = $state() @@ -699,7 +703,8 @@ } } scriptOrFlowPath={flow?.path ?? ''} - errorHandlerKind="flow" + itemKind="flow" + errorHandlerKind={readOnly(workspace) ? undefined : 'flow'} tag={flow?.tag ?? ''} labels={flow?.labels} inheritedLabels={flow?.inherited_labels} diff --git a/frontend/src/lib/components/details/ScriptDetail.svelte b/frontend/src/lib/components/details/ScriptDetail.svelte index 618bafe3ab..160a8f49b8 100644 --- a/frontend/src/lib/components/details/ScriptDetail.svelte +++ b/frontend/src/lib/components/details/ScriptDetail.svelte @@ -103,6 +103,7 @@ import { setOperatingWorkspace, useOperatingUser, + useReadOnlyWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' import { useEditRights } from '$lib/operatorWriteRights' @@ -173,10 +174,12 @@ // lookup does. Assigned once, that leaves the page permanently read-only — `canWrite` // refuses an unknown user — with nothing to recompute it. A hub script is never writable. const promptForAi = $derived((script?.schema?.prompt_for_ai as string | undefined) ?? '') + const readOnly = useReadOnlyWorkspace() const can_write = $derived( !isHubScript && !!script && script.workspace_id == workspace && + !readOnly(workspace) && canWrite(script.path, script.extra_perms!, actingUser) ) const editRights = useEditRights() @@ -877,7 +880,8 @@ if (script !== undefined) script.ws_error_handler_muted = v } } - errorHandlerKind="script" + itemKind="script" + errorHandlerKind={readOnly(workspace) ? undefined : 'script'} scriptOrFlowPath={script?.path ?? ''} tag={script?.tag ?? ''} labels={script?.labels} diff --git a/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts b/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts index 1aba4c2d02..6009d73ccd 100644 --- a/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts +++ b/frontend/src/lib/components/flows/conversations/flowChatViewHost.svelte.ts @@ -20,6 +20,7 @@ import type { } from '$lib/components/copilot/chat/chatViewHost' import type { DisplayMessage, WebSearchResult } from '$lib/components/copilot/chat/shared' import type { AIAutonomyMode } from '$lib/components/copilot/chat/AIChatManager.svelte' +import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import { isPlanCardTool } from '$lib/components/copilot/chat/planMode' import { AttachedFilesStore } from '$lib/components/copilot/chat/files/attachedFiles.svelte' import { SessionArtifactsStore } from '$lib/components/copilot/chat/artifacts/artifactsState.svelte' @@ -737,6 +738,9 @@ export class FlowChatViewHost implements ChatViewHost, DraftSender<ComposerAttac // runtime: its unit test would otherwise load the manager and the editor it pulls in. autonomyMode = 'default' as AIAutonomyMode.DEFAULT setAutonomyMode = () => {} + workModesAvailable = false + workMode = AIWorkMode.BUILD + setWorkMode = () => {} autoAcceptEditsActive = false autoAcceptEditsAvailable = false autoAcceptToolConfirmationsAvailable = false diff --git a/frontend/src/lib/components/home/HomeAIChat.svelte b/frontend/src/lib/components/home/HomeAIChat.svelte index 9d5247081e..3816a18898 100644 --- a/frontend/src/lib/components/home/HomeAIChat.svelte +++ b/frontend/src/lib/components/home/HomeAIChat.svelte @@ -20,7 +20,6 @@ import { currentWorkspaceRootId } from '../sessions/sessionScope.svelte' import { HOME_SHOW_HUB } from '$lib/consts' import { getLocalSetting, storeLocalSetting } from '$lib/utils' - import { isRuleActive, protectionRulesState } from '$lib/workspaceProtectionRules.svelte' import { useReducedMotion } from '$lib/svelte5Utils.svelte' import { BROWSER } from 'esm-env' import HomeConnectDrawer from './HomeConnectDrawer.svelte' @@ -79,23 +78,6 @@ pulseEndTimer = setTimeout(() => (pulsing = false), PULSE_MS) } - // A workspace locked against direct deployment is run, not authored in, so its home page drops - // the composer and the button to reopen it. This is about the workspace, not the caller: - // `createSession` would steer a prompt into the paired dev workspace and an admin bypasses the - // lock outright, yet neither makes prod the place to start one. Unresolved rules read as - // unlocked, so the far commoner unlocked workspace never pops the composer in mid-load. - let runOnlyWorkspace = $derived(isRuleActive('DisableDirectDeployment')) - - // The draft is created when the block mounts, and a new draft steers to the dev workspace - // while the rules are unknown (a locked prod could not be edited), so the block waits for - // them: mounted earlier, an unlocked prod's draft would act on its dev. Once shown for a - // family it stays: switching to a fork resets the rules, and remounting would flash it. - let rulesReady = $derived( - protectionRulesState.rulesets !== undefined && - protectionRulesState.workspace === $workspaceStore - ) - let shownForRoot = $state<string>() - let HomeSessionStarter = $state(loadedStarter) if (!loadedStarter) void loadStarter().then((c) => (HomeSessionStarter = c)) // The starter waits on the workspace's item count before it mounts, and its suggestions on @@ -112,7 +94,7 @@ // of the sessions beta — so hide it from them (the prompt would be silently dropped) while the // AI-independent CLI/MCP row below stays. let showComposer = $derived( - prefersSessionHandoff(!$roleCapabilities.code) && !runOnlyWorkspace && !homeAiHidden.hidden + prefersSessionHandoff(!$roleCapabilities.code) && !homeAiHidden.hidden ) let hero = $derived(showComposer && !removed) @@ -135,10 +117,9 @@ <!-- The block is a session's chat, so it waits for the sessions it might reuse. Keyed on the workspace family, not the workspace: another family needs its own draft, but a fork shares its parent's, and remounting for it only flashes the block. --> - {#if HomeSessionStarter && sessionState.hydrated && (rulesReady || shownForRoot === $currentWorkspaceRootId)} + {#if HomeSessionStarter && sessionState.hydrated} {#key $currentWorkspaceRootId} <HomeSessionStarter - onShown={() => (shownForRoot = $currentWorkspaceRootId)} {placeholder} onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)} /> diff --git a/frontend/src/lib/components/operatingWorkspace.svelte.ts b/frontend/src/lib/components/operatingWorkspace.svelte.ts index 70f1c63c1c..f25fa1415a 100644 --- a/frontend/src/lib/components/operatingWorkspace.svelte.ts +++ b/frontend/src/lib/components/operatingWorkspace.svelte.ts @@ -22,6 +22,24 @@ export function setOperatingWorkspace(resolve: () => string | undefined): void { setContext(KEY, outer ? () => resolve() ?? outer() : resolve) } +const READ_ONLY_KEY = Symbol('readOnlyWorkspace') + +/** Declare which workspaces this subtree may not change: a session in Use mode. `useEditRights` + * refuses every check there, so each control gated on it, the operator gates included, follows. + * Reads context: call during component initialisation. */ +export function setReadOnlyWorkspace(isReadOnly: (workspace: string | undefined) => boolean): void { + setContext(READ_ONLY_KEY, isReadOnly) +} + +/** Whether this subtree may not change `workspace`. Reads context: call during component + * initialisation. */ +export function useReadOnlyWorkspace(): (workspace: string | undefined) => boolean { + return ( + getContext<((workspace: string | undefined) => boolean) | undefined>(READ_ONLY_KEY) ?? + (() => false) + ) +} + /** This subtree's operating workspace as an entry for a `ContextBridge` contexts map. A snippet * handed to the page header's band renders outside the subtree that declared the workspace, so * without this it would quietly act on the navigation workspace instead. Reads context: call diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte index 9ab68c3742..74171dfcdd 100644 --- a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -21,6 +21,8 @@ setSessionDraftPrompt } from './sessionState.svelte' import SessionWorkspaceBar from './SessionWorkspaceBar.svelte' + import { useWorkModeLock } from './workModeLock.svelte' + import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import { composerSentFromHome, takeComposerFocus } from './homeSessionsTransition.svelte' import { homeComposerContext } from './homeComposerContext.svelte' @@ -42,10 +44,15 @@ setContext<AIChatManager>('aiChatManager', runtime.manager) const session = $derived(sessionState.sessions.find((s) => s.id === sessionId)) + // Switches the page along with the session, as the workspace bar below does. + const workModeLock = useWorkModeLock(() => session, true) const actingWorkspaceId = $derived( (session ? getEffectiveWorkspaceId(session) : undefined) ?? $workspaceStore ?? undefined ) - const starterPrompts = new StarterPrompts(() => actingWorkspaceId) + const starterPrompts = new StarterPrompts( + () => actingWorkspaceId, + () => !workModeLock.current && runtime.manager.workMode !== AIWorkMode.USE + ) // The AI config (models, whether AI is hidden) of the workspace the draft acts on, as the // session page loads it, so a fork picked here shows its own models and the session page @@ -130,6 +137,7 @@ viewTransitionNames {onSent} {actingOn} + workModeLock={workModeLock.current} /> </div> {:else} diff --git a/frontend/src/lib/components/sessions/ItemViewerView.svelte b/frontend/src/lib/components/sessions/ItemViewerView.svelte index e9fa9b7768..d1adaa952f 100644 --- a/frontend/src/lib/components/sessions/ItemViewerView.svelte +++ b/frontend/src/lib/components/sessions/ItemViewerView.svelte @@ -64,7 +64,10 @@ untrack(() => runtime.manager) ) - const permissions = useSessionPermissions(() => workspaceId) + const permissions = useSessionPermissions( + () => workspaceId, + () => runtime.manager + ) const canEdit = $derived(permissions.canOpenEditor(kind)) // This reads the deployed version over the API rather than from the editor cell the diff --git a/frontend/src/lib/components/sessions/PageItemEditorView.svelte b/frontend/src/lib/components/sessions/PageItemEditorView.svelte index 73efd892d4..a77550a3ef 100644 --- a/frontend/src/lib/components/sessions/PageItemEditorView.svelte +++ b/frontend/src/lib/components/sessions/PageItemEditorView.svelte @@ -10,12 +10,15 @@ import { setOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { pageItemKindLabel, + pageItemPageHref, pageItemUrl, TRIGGER_PAGES, type PageItemRef, type TriggerKind } from './previewPaths' import type { SessionRuntime } from './sessionRuntime.svelte' + import { useSessionPermissions } from './sessionPermissions.svelte' + import { withWorkspaceParam } from './sessionMode.svelte' let { runtime, @@ -103,6 +106,13 @@ ) ) + // These editors save on click, and a schedule or trigger save passes a production + // workspace's deploy rules, so a read-only session mounts none of them. + const permissions = useSessionPermissions( + () => workspaceId, + () => runtime.manager + ) + function closeTab() { const tab = runtime.previewTabs.tabs.find((t) => t.url === pageItemUrl(item)) if (tab) runtime.previewTabs.close(tab.id) @@ -135,6 +145,21 @@ </p> <Button variant="default" unifiedSize="sm" onClick={closeTab}>Close tab</Button> </div> + {:else if permissions.readOnly} + <div class="flex flex-col items-start gap-3 p-4 text-sm text-secondary"> + <p> + {pageItemKindLabel(item)} <span class="font-mono">{item.path}</span> can't be edited while the + session is in Use mode. + </p> + <Button + variant="default" + unifiedSize="sm" + href={withWorkspaceParam(pageItemPageHref(item), workspaceId)} + target="_blank" + > + Open in workspace + </Button> + </div> {:else} {#key `${item.kind}:${triggerKey}:${item.path}:${workspaceId}:${reloadNonce}:${savedNonce}`} {#if item.kind === 'variable'} diff --git a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte index bc03272712..8fa6b465cc 100644 --- a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte +++ b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte @@ -50,6 +50,7 @@ section or the flat layout. type PreviewTarget } from './previewRouter' import { useSessionPermissions } from './sessionPermissions.svelte' + import type { AIWorkMode } from '$lib/components/copilot/chat/workMode' type Kind = WorkspaceItemKind type DrillPickerHandle = { @@ -75,6 +76,9 @@ section or the flat layout. // Session artifacts to surface as an "Artifacts" branch; omitted or empty // hides the branch (non-session consumers, sessions without artifacts). artifacts?: PersistedArtifact[] + /** The session chat, whose Use mode opens items in their viewer. Read from the + * `aiChatManager` context when omitted. */ + chat?: { readonly workMode: AIWorkMode } } let { @@ -86,12 +90,16 @@ section or the flat layout. autoFocus = true, flush = false, workspaceId, - artifacts + artifacts, + chat }: Props = $props() const kinds: Kind[] = ['flow', 'script', 'app'] const effectiveWorkspace = $derived(workspaceId ?? $workspaceStore) - const permissions = useSessionPermissions(() => effectiveWorkspace) + const permissions = useSessionPermissions( + () => effectiveWorkspace, + () => chat + ) const canEdit = (item: WorkspaceItem) => permissions.canEditItem(item) let inner = $state<DrillPickerHandle | undefined>(undefined) diff --git a/frontend/src/lib/components/sessions/PreviewTabHost.svelte b/frontend/src/lib/components/sessions/PreviewTabHost.svelte index c2adaf7688..33470fa261 100644 --- a/frontend/src/lib/components/sessions/PreviewTabHost.svelte +++ b/frontend/src/lib/components/sessions/PreviewTabHost.svelte @@ -22,6 +22,7 @@ import ArtifactViewer from '../copilot/chat/artifacts/ArtifactViewer.svelte' import RunFormPreviewSlot from './RunFormPreviewSlot.svelte' import { setOverlayHost } from '../common/overlayHost.svelte' + import { setReadOnlyWorkspace } from '../operatingWorkspace.svelte' let { tab, @@ -80,7 +81,11 @@ const workspaceId = $derived( session ? (getEffectiveWorkspaceId(session) ?? $workspaceStore ?? '') : '' ) - const permissions = useSessionPermissions(() => workspaceId || undefined) + const permissions = useSessionPermissions( + () => workspaceId || undefined, + () => runtime?.manager + ) + setReadOnlyWorkspace((ws) => !!ws && ws === workspaceId && permissions.readOnly) // Every route into an editor ends here, the breadcrumb and the chat's openers included, so // this is where an editor the user cannot save is turned into the deployed page. const mode = $derived( @@ -419,7 +424,9 @@ {:else} <!-- A pipeline has no deployed page, only its editor. --> <div class="flex-1 flex items-center justify-center p-8 text-center text-sm text-secondary"> - The pipeline editor saves drafts, which your role cannot do in this workspace. + {permissions.readOnly + ? 'The pipeline editor saves drafts, which a session in Use mode cannot do.' + : 'The pipeline editor saves drafts, which your role cannot do in this workspace.'} </div> {/if} </div> diff --git a/frontend/src/lib/components/sessions/SessionChangesBar.svelte b/frontend/src/lib/components/sessions/SessionChangesBar.svelte index c6272b8fc7..b7ee23034c 100644 --- a/frontend/src/lib/components/sessions/SessionChangesBar.svelte +++ b/frontend/src/lib/components/sessions/SessionChangesBar.svelte @@ -22,6 +22,7 @@ import { isCloudHosted } from '$lib/cloud' import { sessionState, type Session } from './sessionState.svelte' import { getRuntime } from './sessionRuntime.svelte' + import { useSessionPermissions } from './sessionPermissions.svelte' import SessionDiffDrawer from './SessionDiffDrawer.svelte' import { TOKEN_TRIGGER_CLASS } from './SessionStatusToken.svelte' import { useWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' @@ -69,10 +70,17 @@ // Same gate as the sidebar WorkspaceMenu / SessionWorkspaceBar. On cloud, // forking is a premium-only feature (backend caps it per paid seat). const forksAllowed = $derived( - (!isCloudHosted() || $maybePremium) && canCreateFork($userStore, $roleCapabilities) && $workspaceStore !== 'admins' + (!isCloudHosted() || $maybePremium) && + canCreateFork($userStore, $roleCapabilities) && + $workspaceStore !== 'admins' ) const runtime = $derived(getRuntime(session.id)) + // A session in Use deploys and discards nothing, as its chat does not. + const permissions = useSessionPermissions( + () => committedId, + () => runtime?.manager + ) // The chat's modified-items mask (`${UserDraftItemKind}:${storagePath}`). // undefined = legacy/untracked chat → fall back to showing every draft. @@ -387,8 +395,10 @@ onItemDiscarded={(item) => { void runtime?.manager.removeModifiedItem(item.draftKind, item.path) const folder = pipelineFolderFromBundlePath(item.path) - if (item.draftKind === PIPELINE_DRAFT_KIND && folder) void runtime?.forgetPipelineDrafts(folder) + if (item.draftKind === PIPELINE_DRAFT_KIND && folder) + void runtime?.forgetPipelineDrafts(folder) }} deployPipeline={runtime?.deployPipeline} + readOnly={permissions.readOnly} /> {/if} diff --git a/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte b/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte index d921e435b0..76d7f7e7ab 100644 --- a/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte +++ b/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte @@ -20,7 +20,8 @@ onDataChanged, onItemDeployed, onItemDiscarded, - deployPipeline + deployPipeline, + readOnly = false }: { workspaceId: string parentWorkspaceId?: string @@ -39,6 +40,8 @@ onItemDiscarded?: (item: DeployItem) => void /** Forwarded to the deploy model: deploys a pipeline folder's draft bundle. */ deployPipeline?: (folder: string) => Promise<DeployResult> + /** Forwarded to the deploy model: the session is in Use. */ + readOnly?: boolean } = $props() const isFork = $derived(!!parentWorkspaceId) @@ -55,7 +58,8 @@ onDataChanged, onItemDeployed, onItemDiscarded, - deployPipeline + deployPipeline, + readOnly })) // Editor URL for a row (every item lives in the session workspace). @@ -99,7 +103,11 @@ {ws?.name ?? workspaceId} </span> {#if ws?.is_dev_workspace} - <DevWorkspaceBadge label={ws.dev_workspace_label} color={ws.color} fallbackColor="indigo" /> + <DevWorkspaceBadge + label={ws.dev_workspace_label} + color={ws.color} + fallbackColor="indigo" + /> {/if} <ArrowRight class="w-3 h-3 shrink-0 text-tertiary" /> <span class="font-medium truncate" title={parentWs?.name ?? parentWorkspaceId}> diff --git a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte index 41cbb73a81..0df6004f34 100644 --- a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte +++ b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte @@ -1,16 +1,36 @@ -<script lang="ts"> +<script lang="ts" module> + import { get } from 'svelte/store' import { workspaceStore } from '$lib/stores' + import { setSessionPendingWorkspace } from './sessionState.svelte' + import { switchWorkspace } from '$lib/storeUtils' + import { workspaceAIClients } from '$lib/components/copilot/lib' + import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl' + + function followPick(id: string, switchesWorkspace: boolean) { + if (!switchesWorkspace || get(workspaceStore) === id) return + workspaceAIClients.init(id) + switchWorkspace(id) + void fixupUrlAfterWorkspaceSwitch(id) + } + + /** Point a session that has not sent yet at workspace `id`, as a pick in this bar does. */ + export function pickSessionWorkspace(sessionId: string, id: string, switchesWorkspace: boolean) { + // Pre-send only: writes the pending pick. workspace_id stays undefined until + // the user sends their first message. The chat targets this pending workspace + // via the manager's workspace resolver, not the global workspaceStore. + setSessionPendingWorkspace(sessionId, id) + followPick(id, switchesWorkspace) + } +</script> + +<script lang="ts"> import { getEffectiveWorkspaceId, setSessionPendingFork, - setSessionPendingWorkspace, type Session } from './sessionState.svelte' import WorkspaceFamilyPicker from './WorkspaceFamilyPicker.svelte' import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte' - import { switchWorkspace } from '$lib/storeUtils' - import { workspaceAIClients } from '$lib/components/copilot/lib' - import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl' // `switchesWorkspace`: a pick also moves the navigation workspace. For a host whose page // shows the navigation workspace around the composer (Home), where a pick that left it @@ -18,28 +38,17 @@ let { session, switchesWorkspace = false }: { session: Session; switchesWorkspace?: boolean } = $props() - function followPick(id: string) { - if (!switchesWorkspace || $workspaceStore === id) return - workspaceAIClients.init(id) - switchWorkspace(id) - void fixupUrlAfterWorkspaceSwitch(id) - } - // Effective workspace for display: committed → pending pick → active store. const effectiveId = $derived(getEffectiveWorkspaceId(session) ?? $workspaceStore ?? undefined) const pendingFork = $derived(session.pending_fork) function pick(id: string) { - // Pre-send only: writes the pending pick. workspace_id stays undefined until - // the user sends their first message. The chat targets this pending workspace - // via the manager's workspace resolver, not the global workspaceStore. - setSessionPendingWorkspace(session.id, id) - followPick(id) + pickSessionWorkspace(session.id, id, switchesWorkspace) } function stageFork(req: { parent_workspace_id: string; id: string; name: string }) { setSessionPendingFork(session.id, req) - followPick(req.parent_workspace_id) + followPick(req.parent_workspace_id, switchesWorkspace) } </script> diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index a27682011a..e51445deeb 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -18,9 +18,12 @@ import { globalComposerSuggestion, STARTER_PLACEHOLDER, + USE_STARTER_PLACEHOLDER, type ComposerSelection } from '$lib/components/copilot/chat/composerBox' import { useSessionPermissions } from './sessionPermissions.svelte' + import { useWorkModeLock } from './workModeLock.svelte' + import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import EditableInput from '$lib/components/common/EditableInput.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import { Button } from '$lib/components/common' @@ -106,8 +109,17 @@ // and an empty transcript would show the greeting and then glide the composer away. // The first send commits the workspace, so this flips only after the transcript has. const opensSession = $derived(!session?.workspace_id) - const starterPrompts = new StarterPrompts(() => - opensSession ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined + const permissions = useSessionPermissions( + () => runtime?.manager.operatingWorkspace, + () => runtime?.manager + ) + const workModeLock = useWorkModeLock(() => session) + // Whether the first message goes out in Use. Not `permissions.readOnly`: before that send a + // staged fork's session reads the workspace it forks, while the message builds in the fork. + const heldInUse = $derived(!!workModeLock.current || runtime?.manager.workMode === AIWorkMode.USE) + const starterPrompts = new StarterPrompts( + () => (opensSession ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined), + () => !heldInUse ) // Seed the composer with the unsent prompt a reload preserved on the session @@ -142,7 +154,6 @@ // Drawn once, and shared by the placeholder and the real composer so the text survives the swap. const suggestionPick = Math.random() - const permissions = useSessionPermissions(() => runtime?.manager.operatingWorkspace) const composerPlaceholder = $derived( globalComposerSuggestion(suggestionPick, permissions.canOpenEditor) ) @@ -586,6 +597,7 @@ emptyHint={sessionEmptyHint} {inputPreface} actingOn={hasFirstUserMessage ? undefined : actingOn} + workModeLock={workModeLock.current} /> {:else} <!-- AIChatDisplay's layout, so the composer stays put when the chat replaces it: @@ -611,7 +623,9 @@ bind:value={() => draftText, setPlaceholderText} toolbar={opensSession ? placeholderToolbar : undefined} placeholder={opensSession - ? STARTER_PLACEHOLDER + ? heldInUse + ? USE_STARTER_PLACEHOLDER + : STARTER_PLACEHOLDER : runtime.manager.displayMessages.length > 0 ? 'Ask followup' : composerPlaceholder} diff --git a/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte b/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte index c35ee5a2fc..11f3219155 100644 --- a/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte +++ b/frontend/src/lib/components/sessions/WorkspaceDiffDrawer.svelte @@ -1059,7 +1059,10 @@ variant="subtle" unifiedSize="sm" destructive - disabled={model.deploying || !!staged[d.key]} + disabled={model.deploying || !!staged[d.key] || model.readOnly} + title={model.readOnly + ? 'A session in Use mode discards nothing. Switch it to Use & build to discard.' + : undefined} onclick={() => confirmDiscard(d)} > {action.secondary[0].label} diff --git a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte index e6e27b0a13..1edd4f9376 100644 --- a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte +++ b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte @@ -20,14 +20,8 @@ import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte' import { canCreateFork } from '$lib/utils/editInFork' import { forkAccentStyle } from '$lib/utils/forkColor' - import { getUserExt } from '$lib/user' import { WorkspaceService } from '$lib/gen' - import { - fetchProtectionRulesForWorkspace, - isRuleActiveInRulesets, - canUserBypassRuleKindInRulesets - } from '$lib/workspaceProtectionRules.svelte' - import { resource } from 'runed' + import { useSessionReadOnly } from './sessionPermissions.svelte' import { isCloudHosted } from '$lib/cloud' import { random_adj } from '$lib/components/random_positive_adjetive' import DropdownV2 from '$lib/components/DropdownV2.svelte' @@ -142,35 +136,9 @@ return depth > 0 ? `padding-left: ${12 + depth * 16}px` : undefined } - // Judge the prod root off its OWN protection rules (fetched), not the active - // workspace's — so it reads correctly from a dev/fork too, the same way - // ParentWorkspaceProtectionAlert checks the parent. It's selectable when you - // can deploy to it, and "Fork from prod" shows when you can fork it. - const rootRulesetsResource = resource( - () => root?.id, - async (id) => (id ? await fetchProtectionRulesForWorkspace(id) : []) - ) - const rootRulesets = $derived(rootRulesetsResource.current ?? []) - // Bypass must be judged with the user's identity IN THE ROOT (is_admin/groups are per-workspace), - // not the active workspace's `$userStore` — otherwise an admin of the dev/active workspace who is a - // non-admin of the root would get a false bypass. `getUserExt` returns undefined for a non-member, - // which `canUserBypassRuleKindInRulesets` treats as no bypass. - const rootUserInfoResource = resource( - () => root?.id, - async (id) => (id ? await getUserExt(id) : undefined) - ) - const rootUserInfo = $derived(rootUserInfoResource.current) - const canDeployRoot = $derived( - !isRuleActiveInRulesets(rootRulesets, 'DisableDirectDeployment') || - canUserBypassRuleKindInRulesets(rootRulesets, 'DisableDirectDeployment', rootUserInfo) - ) - // A genuinely deploy-locked root (you can't deploy and can't bypass) is disabled regardless of - // whether a dev workspace exists to steer to — being deploy-locked is the gate, not dev presence. - // Roots with no rules resolve `canDeployRoot` to true, so ordinary families aren't affected. Kept - // disabled while either fetch is in flight (both default to the conservative locked state). - const rootDisabled = $derived( - rootRulesetsResource.loading || rootUserInfoResource.loading || !canDeployRoot - ) + // Judged off the root's OWN rules, so it reads correctly from a dev workspace or a fork too. + // A locked root stays selectable: its session is read-only. + const rootReadOnly = useSessionReadOnly(() => root?.id) // Structural gate: hidden in the admins workspace, or when the user can't fork; on cloud, forking // is premium-only (backend caps it per paid seat). DisableWorkspaceForking on the active workspace @@ -235,7 +203,7 @@ if (row.kind === 'create') { requestCreateFork() } else if (row.kind === 'root') { - if (!rootDisabled) void pick(row.id) + void pick(row.id) } else if (row.kind === 'fork') { void pick(row.id) } @@ -405,20 +373,19 @@ <div class="relative group shrink-0"> <button type="button" - disabled={rootDisabled} - title={rootDisabled - ? devOfRoot - ? `${root.name} is locked. Run in its ${devLabelNoun(devOfRoot.dev_workspace_label)} instead.` - : `${root.name} is locked for direct deploys.` + title={rootReadOnly.known + ? `Sessions in ${root.name} can read and run deployed items, but not edit. Pick ${ + devOfRoot ? `its ${devLabelNoun(devOfRoot.dev_workspace_label)}` : 'a fork' + } to make changes.` : undefined} - class={`${rowBase} pr-8 ${rootDisabled ? 'opacity-50 cursor-not-allowed' : ''} ${isSelected(root.id) && !pendingFork ? 'bg-surface-selected' : ''} ${!rootDisabled && keyArrowPos === rootIdx ? 'bg-surface-hover' : !rootDisabled ? 'hover:bg-surface-hover' : ''}`} - onmouseenter={() => !rootDisabled && (keyArrowPos = rootIdx)} - onclick={() => !rootDisabled && void pick(root.id)} + class={`${rowBase} pr-8 ${isSelected(root.id) && !pendingFork ? 'bg-surface-selected' : ''} ${keyArrowPos === rootIdx ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`} + onmouseenter={() => (keyArrowPos = rootIdx)} + onclick={() => void pick(root.id)} > <Building size={14} class="shrink-0 text-tertiary" /> <span class="truncate">{root.name}</span> <span class="text-2xs text-tertiary shrink-0 ml-auto" - >{rootDisabled ? 'locked' : 'root'}</span + >{rootReadOnly.known ? 'read-only' : 'root'}</span > {#if isSelected(root.id) && !pendingFork} <Check size={14} class="shrink-0 text-accent" /> diff --git a/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts b/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts index 50447d3e06..487f80aaf8 100644 --- a/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts @@ -60,6 +60,13 @@ export interface SessionDeployModelArgs { /** Deploys a pipeline folder's draft bundle, which no per-item deploy can: it * expands into the folder's scripts and triggers. */ deployPipeline?: (folder: string) => Promise<DeployResult> + /** The session is in Use: its edits still show, but nothing deploys or discards. */ + readOnly?: boolean +} + +const USE_MODE_REFUSAL: DeployPermission = { + ok: false, + reason: 'A session in Use mode deploys nothing. Switch it to Use & build to deploy.' } export interface DiffValues { @@ -258,6 +265,7 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { }) function permissionFor(kind: Kind): DeployPermission { + if (getArgs().readOnly) return USE_MODE_REFUSAL const caps = capabilitiesInWorkspace(getArgs().workspaceId) if (builder?.kinds.includes(kind)) return deployPermissionForKind(builder.perm, kind, caps) return deployPermissionForKind(deployPerm, kind, caps) @@ -305,7 +313,7 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { /** Deploy (or discard) a single item; returns whether it succeeded. */ async function deployOne(item: DeployItem, discard = false): Promise<boolean> { const plan = discard ? discardPlanFor(item) : deployPlanFor(item) - if (!plan) return false + if (!plan || getArgs().readOnly) return false // Snapshot before the await: the user may switch sessions while the // deploy runs, and the event belongs to the initiating session. const initiatingSessionId = sessionState.currentSessionId @@ -410,6 +418,10 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { deployPermissionForKind(kind: Kind): DeployPermission { return permissionFor(kind) }, + /** The session is in Use, so discarding is refused as deploying is. */ + get readOnly() { + return !!getArgs().readOnly + }, deployRow, discardRow } diff --git a/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts b/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts index caceb2e623..0db9ac09e7 100644 --- a/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts @@ -1,31 +1,89 @@ +import { getContext } from 'svelte' import { fromStore } from 'svelte/store' +import { resource } from 'runed' import { userWorkspaces } from '$lib/stores' import { useActingUser } from '$lib/actingUser.svelte' import { useEditRights } from '$lib/operatorWriteRights' +import { buildsAnything } from '$lib/editRights' +import { + isReadOnlySessionWorkspace, + settledReadOnlyVerdict +} from '$lib/components/copilot/chat/global/sessionAccess' +import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import type { WorkspaceItem } from '$lib/components/workspacePicker' import { previewPageAllowed, type PreviewPage } from './previewRouter' +/** Whether a session in `workspace` is read-only because the workspace is protected: the verdict + * `resolveSessionAccess` gives the chat, so the UI and the toolset agree. */ +export function useSessionReadOnly(workspace: () => string | undefined) { + const verdict = resource(workspace, async (ws) => + ws ? { workspace: ws, readOnly: await isReadOnlySessionWorkspace(ws) } : undefined + ) + // `resource` keeps the previous workspace's verdict while it asks about the next one. + const verdictFor = (ws: string): boolean | undefined => { + const landed = verdict.current + return landed?.workspace === ws ? landed.readOnly : settledReadOnlyVerdict(ws) + } + return { + /** Read-only, and also while the rules have not been read yet: the preview's writes wait + * for the lookup rather than race it. */ + get current() { + const ws = workspace() + return !!ws && (verdictFor(ws) ?? true) + }, + /** Read-only as far as is known, so false while the rules are read. For what only shows the + * verdict, the picker's lock or a label, which would otherwise flash a reason that is not + * true. */ + get known() { + const ws = workspace() + return !!ws && (verdictFor(ws) ?? false) + } + } +} + +/** The session chat whose work mode the session UI follows. */ +type WorkModeHost = { readonly workMode: AIWorkMode } + /** * What the session UI may offer in `workspace`. Its editors save drafts, so it reads * `roleCanDraft` / `canDraftItem` — the rule the chat's draft tools and `open_preview` follow — so * a control and the tool behind it never disagree. An unknown user reads as able to draft, as the toolset does before access * resolves: hiding every editor from a developer while `whoami` is in flight is the worse - * mistake, and the server refuses an operator anyway. Reads context and registers an effect: - * call during component initialisation. + * mistake, and the server refuses an operator anyway. A session held in Use opens no editor: one + * in a protected workspace, one whose role builds nothing there, or one whose chat is in Use + * mode — the chat `chat` returns, else the `aiChatManager` context's. + * Reads context and registers an effect: call during component initialisation. */ -export function useSessionPermissions(workspace: () => string | undefined) { +export function useSessionPermissions( + workspace: () => string | undefined, + chat?: () => WorkModeHost | undefined +) { + const contextChat = getContext<WorkModeHost | undefined>('aiChatManager') const rights = useEditRights(workspace) const user = useActingUser(workspace) + const protectedWorkspace = useSessionReadOnly(workspace) + const readOnly = $derived( + protectedWorkspace.current || + !buildsAnything(rights.capabilities) || + (chat?.() ?? contextChat)?.workMode === AIWorkMode.USE + ) const workspaces = fromStore(userWorkspaces) const entry = $derived(workspaces.current.find((w) => w.id === workspace())) return { + /** The session is read-only in this workspace. */ + get readOnly() { + return readOnly + }, /** Whether this user can save the drafts the `kind` editor writes. */ - canOpenEditor: (kind: string) => rights.roleCanDraft(kind), + canOpenEditor: (kind: string) => !readOnly && rights.roleCanDraft(kind), /** The same, and this item's own permissions let them write it. */ canEditItem: (item: Pick<WorkspaceItem, 'kind' | 'raw_app' | 'path' | 'extraPerms'>) => + !readOnly && rights.canDraftItem(item.raw_app ? 'raw_app' : item.kind, item.path, item.extraPerms), /** Whether the page loads for this user rather than refusing them. */ - pageAllowed: (page: PreviewPage) => previewPageAllowed(page, user.current, entry) + pageAllowed: (page: PreviewPage) => + // A read-only session reaches what an operator reaches: no admin page. + !(readOnly && page.adminOnly) && previewPageAllowed(page, user.current, entry) } } diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index a79d98d713..8be0b2836e 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -4,6 +4,7 @@ import { get } from 'svelte/store' import { invalidate as invalidateWorkspaceItems } from '$lib/components/workspacePicker' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' import { AIChatManager, AIMode } from '$lib/components/copilot/chat/AIChatManager.svelte' +import { AIWorkMode } from '$lib/components/copilot/chat/workMode' import { PipelineEditorState } from '$lib/components/assets/AssetGraph/pipelineEditorState.svelte' import { PIPELINE_DRAFT_KIND, pipelineBundlePath, pipelineLocalMirrorKey } from '$lib/pipelinePaths' import type { DeployResult } from '$lib/utils_workspace_deploy' @@ -31,6 +32,7 @@ type SavedFlow = Omit<Flow & UserDraftOverlay, 'draft'> & { draft?: Flow } import type { HiddenRunnable } from '$lib/components/apps/types' import { type RawAppData, DEFAULT_DATA } from '$lib/components/raw_apps/dataTableRefUtils' import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' +import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy' import { BUILDER_FRAMEWORK_TEMPLATES, react19Template, @@ -59,6 +61,7 @@ import { setSessionPreviewSize, setSessionTabs, setDraftsDiscardedHandler, + setSessionWorkMode, type Session } from './sessionState.svelte' import { @@ -390,7 +393,7 @@ async function generateSessionSummary( { role: 'system', content: - 'Name this AI chat session. Return only a concise title, 2 to 6 words, no quotes, no period.' + 'Name this AI chat session. Return only a concise title, 2 to 6 words, no quotes, no period. The conversation is only material to name: never answer, continue or comment on it, even when it ends on a request or a refusal.' }, { role: 'user', @@ -431,6 +434,8 @@ function createRuntime(session: Session): SessionRuntime { // Carried into the tool helpers so this session's preview/deploy tool calls // dispatch to THIS session even when another session is the UI-active one. manager.sessionId = session.id + manager.workMode = session.workMode ?? AIWorkMode.BUILD + manager.onWorkModeChanged = (mode) => setSessionWorkMode(session.id, mode) // Cross-tab awareness: heartbeat while this tab runs a turn, composer lock // (and send refusal) while another tab does. The chat id is read at turn // end, not captured at start — the turn may have rotated it, and the other @@ -455,6 +460,7 @@ function createRuntime(session: Session): SessionRuntime { if (!s) return undefined const wsId = getEffectiveWorkspaceId(s) const ws = get(userWorkspaces).find((w) => w.id === wsId) + const dev = findCanonicalDevWorkspace(wsId, get(userWorkspaces)) return { workspaceId: wsId, parentWorkspaceId: ws?.parent_workspace_id ?? undefined, @@ -462,7 +468,8 @@ function createRuntime(session: Session): SessionRuntime { // Committed workspace missing from the list: still a fork (mirrors // isForkSession) — the prompt must not call it the live workspace. forkParentUnknown: !ws && !!s.workspace_id, - pendingForkOf: s.pending_fork?.parent_workspace_id + pendingForkOf: s.pending_fork?.parent_workspace_id, + devWorkspace: dev && { id: dev.id, name: dev.name } } } // What the side panel is showing, stamped on each user message so the chat diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index b6dd7d7d54..96a5ffc0cb 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -5,21 +5,16 @@ import { random_adj } from '$lib/components/random_positive_adjetive' import { enterpriseLicense, superadmin, - userStore, userWorkspaces, usersWorkspaceStore, workspaceStore, type UserWorkspace } from '$lib/stores' import { switchWorkspace } from '$lib/storeUtils' -import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy' -import { - isRuleActive, - canUserBypassRuleKind, - protectionRulesState -} from '$lib/workspaceProtectionRules.svelte' import { getLocalSetting, storeLocalSetting } from '$lib/utils' import { logFeatureUsage } from '$lib/utils/featureUsage' +import { isReadOnlySessionWorkspace } from '../copilot/chat/global/sessionAccess' +import { AIWorkMode } from '../copilot/chat/workMode' import { workspaceRootId } from './sessionScope.svelte' import { clearSessionRecovered } from './sessionRecoveryNotice.svelte' import { type DBSchema, type IDBPDatabase } from 'idb' @@ -159,6 +154,8 @@ export type Session = { // Preview split size (preview pane %, 0-100) the user dragged for this session. // Per-session so each session restores its own layout. previewSize?: number + // Use or Build, as the chat's mode picker last left it. Absent reads as Build. + workMode?: AIWorkMode.USE | AIWorkMode.BUILD // Unsent composer text for a pending (uncommitted) session, persisted with // the record so each parallel draft restores its own typed-but-unsent prompt. // Only tracked while unsent; cleared once the workspace commits at first send. @@ -1127,24 +1124,9 @@ function newTransientSession(): Session { const discarded = sessionState.sessions.filter(isDiscardableDraft).map((s) => s.id) sessionState.sessions = sessionState.sessions.filter((s) => !isDiscardableDraft(s)) if (discarded.length > 0) onDraftsDiscarded?.(discarded) - // Start in the workspace you're in. The one exception: a root you can't - // deploy to (locked, no bypass) steers to its dev, since a session there - // couldn't edit anything. The picker lets you switch. - const currentWs = get(workspaceStore) - const devOfCurrent = currentWs - ? findCanonicalDevWorkspace(currentWs, get(userWorkspaces))?.id - : undefined - // Only trust the deploy check once the active workspace's rules have actually loaded: until then - // `isRuleActive` reads an empty ruleset and fails open, which would default a new session onto a - // locked prod. Treat "not yet loaded for currentWs" as not-deployable so we steer to the dev (always - // editable) when one exists; the picker still lets the user switch back once rules resolve. - const rulesLoadedForCurrent = - protectionRulesState.rulesets !== undefined && protectionRulesState.workspace === currentWs - const canDeployHere = - rulesLoadedForCurrent && - (!isRuleActive('DisableDirectDeployment') || - canUserBypassRuleKind('DisableDirectDeployment', get(userStore))) - const pending = devOfCurrent && !canDeployHere ? devOfCurrent : currentWs + // Start in the workspace you're in, a locked production root included: the session is then + // read-only, and points the user to a new session in the dev workspace for changes. + const pending = get(workspaceStore) // Friendly default summary so the header reads like "Zippy session" // rather than "Untitled session" — assigned at create time, the user // can still rename it (or it gets overwritten by an editor target). @@ -1295,12 +1277,16 @@ export async function commitSessionWorkspace( // The draft prompt has been consumed as the first message. delete s.draftPrompt await putSession(s) - // A picked workspace can itself be an existing fork — classify by root. - logFeatureUsage('ai_session', 'created', { - key: ws === s.workspace_root_id ? 'root' : 'fork', - entityId: s.id, - workspace: ws - }) + // A picked workspace can itself be an existing fork — classify by root. A read-only root is + // counted apart, to see whether production sessions are used. + const sessionId = s.id + void isReadOnlySessionWorkspace(ws).then((readOnly) => + logFeatureUsage('ai_session', 'created', { + key: readOnly ? 'read_only' : ws === s.workspace_root_id ? 'root' : 'fork', + entityId: sessionId, + workspace: ws + }) + ) // The global workspaceStore is intentionally left untouched (see the fork // branch above): the session chat reads its committed workspace through the // manager's workspace resolver, not the active workspaceStore. @@ -1339,6 +1325,16 @@ export function setSessionPreviewSize(id: string, size: number): void { persistTouched(s) } +// Persist the session's Use or Build choice (a touch). Plan is left out: a reload ends the +// planning round, and the session reopens in the mode it was entered from. +export function setSessionWorkMode(id: string, mode: AIWorkMode): void { + if (mode === AIWorkMode.PLAN) return + const s = sessionState.sessions.find((x) => x.id === id) + if (!s || (s.workMode ?? AIWorkMode.BUILD) === mode) return + s.workMode = mode + persistTouched(s) +} + export function selectSession(id: string) { sessionState.currentSessionId = id } diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index fc99c963b3..2ef63bacfc 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -272,15 +272,14 @@ export async function openSourceInSession( // composer. For entry points that carry a question rather than a target (the // global search's "Ask AI"). Always a new session rather than the most recent // one (`enterSessionMode`), so the seed cannot overwrite a prompt the user has -// already typed into a session they are mid-way through. +// already typed into a session they are mid-way through. `workspace` is the way +// out of a read-only session, whose workspace is fixed once it has started. export async function startSessionWithPrompt( prompt: string, - opts?: { autoSend?: boolean } + opts?: { autoSend?: boolean; workspace?: string } ): Promise<void> { - // No setSessionPendingWorkspace: createSession already picked the workspace, - // steering off a root the user cannot deploy to onto its dev. Overwriting it - // with the raw current workspace would land the session where it cannot edit. const session = createSession() + if (opts?.workspace) setSessionPendingWorkspace(session.id, opts.workspace) setSessionDraftPrompt(session.id, prompt) // An empty prompt has nothing to send; leave the composer focused instead. if (opts?.autoSend && prompt.trim()) setSessionAutoSend(session.id) diff --git a/frontend/src/lib/components/sessions/sessionSwitch.test.ts b/frontend/src/lib/components/sessions/sessionSwitch.test.ts index afacf41d51..3ee386a9ac 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.test.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.test.ts @@ -253,10 +253,9 @@ describe('startSessionWithPrompt', () => { vi.mocked(goto).mockClear() }) - // The hand-off must not re-pick the workspace: createSession already steers off - // a root the user cannot deploy to onto its dev, and overwriting that with the - // raw current workspace lands the session somewhere it cannot edit. - it('seeds the composer and keeps createSession’s workspace choice', async () => { + // A question asked on prod is answered against prod, in a read-only session, even + // when a dev workspace exists to make changes in. + it('seeds the composer and starts in the current workspace', async () => { const prevUsers = get(usersWorkspaceStore) const prevWs = get(workspaceStore) const prevCurrent = sessionState.currentSessionId @@ -271,7 +270,7 @@ describe('startSessionWithPrompt', () => { createdId = sessionState.currentSessionId const created = sessionState.sessions.find((s) => s.id === createdId) expect(created?.draftPrompt).toBe('list my flows') - expect(created?.pending_workspace_id).toBe('prod-dev') + expect(created?.pending_workspace_id).toBe('prod') } finally { sessionState.sessions = sessionState.sessions.filter((s) => s.id !== createdId) sessionState.currentSessionId = prevCurrent diff --git a/frontend/src/lib/components/sessions/workModeLock.svelte.ts b/frontend/src/lib/components/sessions/workModeLock.svelte.ts new file mode 100644 index 0000000000..e32645625b --- /dev/null +++ b/frontend/src/lib/components/sessions/workModeLock.svelte.ts @@ -0,0 +1,64 @@ +import { fromStore } from 'svelte/store' +import { userWorkspaces } from '$lib/stores' +import { useEditRights } from '$lib/operatorWriteRights' +import { buildsAnything } from '$lib/editRights' +import { findCanonicalDevWorkspace } from '$lib/utils/workspaceHierarchy' +import type { WorkModeLock } from '../copilot/chat/workMode' +import { pickSessionWorkspace } from './SessionWorkspaceBar.svelte' +import { useSessionReadOnly } from './sessionPermissions.svelte' +import { getEffectiveWorkspaceId, type Session } from './sessionState.svelte' +import { startSessionWithPrompt } from './sessionSwitch.svelte' + +/** + * What holds a session's chat in Use, for its mode picker: a protected workspace, whose way + * out is its dev workspace, or a role that builds nothing there. `switchesWorkspace` is the + * session's workspace bar's: on Home, moving the session to the dev workspace moves the page + * too. Reads context and registers an effect: call during component initialisation. + */ +export function useWorkModeLock(session: () => Session | undefined, switchesWorkspace = false) { + const workspace = () => { + const s = session() + return s ? getEffectiveWorkspaceId(s) : undefined + } + const protectedWorkspace = useSessionReadOnly(workspace) + const rights = useEditRights(workspace) + const workspaces = fromStore(userWorkspaces) + const lock = $derived.by((): WorkModeLock | undefined => { + const s = session() + const ws = workspace() + // A staged fork is created at the first send and the session builds there, so nothing + // about the workspace it forks holds the session in Use. + if (!s || !ws || s.pending_fork) return undefined + if (protectedWorkspace.known) { + const dev = findCanonicalDevWorkspace(ws, workspaces.current) + if (!dev) + return { reason: 'This workspace is protected against direct changes. Build in a fork.' } + const label = `${dev.name} (dev)` + return { + reason: `This workspace is protected against direct changes. Build in ${label}.`, + // Until its first message a session can still change workspace; after it, only a new + // one can act elsewhere. + escape: s.workspace_id + ? { + label: `New session in ${label}`, + action: () => void startSessionWithPrompt('', { workspace: dev.id }) + } + : { + label: `Switch to ${label}`, + action: () => pickSessionWorkspace(s.id, dev.id, switchesWorkspace) + } + } + } + if (!buildsAnything(rights.capabilities)) { + return { + reason: "Your role can't build in this workspace. A workspace admin can change that." + } + } + return undefined + }) + return { + get current() { + return lock + } + } +} diff --git a/frontend/src/lib/components/variables/VariablesList.svelte b/frontend/src/lib/components/variables/VariablesList.svelte index e3d996804e..6b40eda798 100644 --- a/frontend/src/lib/components/variables/VariablesList.svelte +++ b/frontend/src/lib/components/variables/VariablesList.svelte @@ -60,11 +60,13 @@ import { useHostedPage } from '$lib/components/hostedPage' import { useOperatingWorkspace, - useOperatingUser + useOperatingUser, + useReadOnlyWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const readOnly = useReadOnlyWorkspace() const editRights = useEditRights() const hosted = useHostedPage() @@ -694,8 +696,8 @@ headers={['Name', 'Value']} data={contextualVariables.filter((x) => x.is_custom)} keys={['name', 'value']} - getRowActions={operatingUser.current?.is_admin || - operatingUser.current?.is_super_admin + getRowActions={!readOnly($operatingWorkspace) && + (operatingUser.current?.is_admin || operatingUser.current?.is_super_admin) ? (row) => { return [ { diff --git a/frontend/src/lib/editRights.ts b/frontend/src/lib/editRights.ts index 025b77a157..24022cc680 100644 --- a/frontend/src/lib/editRights.ts +++ b/frontend/src/lib/editRights.ts @@ -69,6 +69,14 @@ export function roleCanDraft(kind: EditKind, caps: RoleCapabilities): boolean { return kind === 'group' ? false : roleCanAuthor(kind, caps) } +/** Whether the role builds anything: code, flows, apps, schedules or triggers. Resources and + * variables do not count, since every role edits them. */ +export function buildsAnything(caps: RoleCapabilities): boolean { + return (['script', 'flow', 'raw_app', 'schedule', 'trigger'] as const).some((kind) => + roleCanDraft(kind, caps) + ) +} + /** `roleCanDraft` for the item at `path`, with its own permissions as in `canEditItem`. */ export function canDraftItem( kind: EditKind, diff --git a/frontend/src/lib/operatorWriteRights.ts b/frontend/src/lib/operatorWriteRights.ts index 28a68784e6..5684a8ee56 100644 --- a/frontend/src/lib/operatorWriteRights.ts +++ b/frontend/src/lib/operatorWriteRights.ts @@ -1,10 +1,13 @@ -import { derived, fromStore, get, readable, type Readable } from 'svelte/store' +import { derived, fromStore, get, readable, toStore, type Readable } from 'svelte/store' import type { RoleCapabilities } from '$lib/gen' import { userStore, userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' -import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' +import { + useOperatingWorkspace, + useReadOnlyWorkspace +} from '$lib/components/operatingWorkspace.svelte' import { useActingUser } from '$lib/actingUser.svelte' import { canDraftItem, canEditItem, roleCanAuthor, roleCanDraft } from '$lib/editRights' -import { capabilitiesIn } from '$lib/roleCapabilities' +import { capabilitiesIn, withoutBuilding } from '$lib/roleCapabilities' /** * The `editRights` rules (`roleCanAuthor` / `canEditItem` for the item handlers, `roleCanDraft` / @@ -17,22 +20,29 @@ export function useEditRights(workspace?: () => string | undefined) { const operating = fromStore(useOperatingWorkspace()) const ws = workspace ?? (() => operating.current) const user = useActingUser(ws) + const readOnly = useReadOnlyWorkspace() const workspaces = fromStore(userWorkspaces) - const caps = () => - capabilitiesIn( + const open = () => !readOnly(ws()) + // A read-only workspace leaves the role building nothing, so a gate reading `capabilities` + // follows it as the four checks below do. Those keep their own guard: every role edits + // resources and variables. + const caps = () => { + const roleCaps = capabilitiesIn( user.current, workspaces.current.find((w) => w.id === ws()) ) + return open() ? roleCaps : withoutBuilding(roleCaps) + } return { get capabilities(): RoleCapabilities { return caps() }, - roleCanAuthor: (kind: string) => roleCanAuthor(kind, caps()), + roleCanAuthor: (kind: string) => open() && roleCanAuthor(kind, caps()), canEditItem: (kind: string, path: string, extraPerms: Record<string, boolean> | undefined) => - canEditItem(kind, path, extraPerms, user.current, caps()), - roleCanDraft: (kind: string) => roleCanDraft(kind, caps()), + open() && canEditItem(kind, path, extraPerms, user.current, caps()), + roleCanDraft: (kind: string) => open() && roleCanDraft(kind, caps()), canDraftItem: (kind: string, path: string, extraPerms: Record<string, boolean> | undefined) => - canDraftItem(kind, path, extraPerms, user.current, caps()), + open() && canDraftItem(kind, path, extraPerms, user.current, caps()), /** This hook looks the user up on its own, so an editor that retries a failed lookup on * its acting user (`forgetFailures`) must retry this one too, or it stays read-only. */ forgetFailures: () => user.forgetFailures() @@ -72,10 +82,17 @@ export const capabilitiesInWorkspace = (workspace: string | undefined) => * the shape `title` and `disabled` both want. See `docs/operator-write-rights.md`. */ function writeLock(kind: 'schedule' | 'trigger', noun: string) { - return derived(useRoleCapabilities(), (caps) => + const workspace = fromStore(useOperatingWorkspace()) + const readOnly = useReadOnlyWorkspace() + // A store, so a session switched to Use mid-page locks the toggles already shown. + const sessionReadOnly = toStore(() => readOnly(workspace.current)) + return derived([useRoleCapabilities(), sessionReadOnly], ([caps, inUse]) => { + if (inUse) return `A session in Use mode cannot manage ${noun}` // Worded as the server words its refusal of the same write. - roleCanAuthor(kind, caps) ? undefined : `Your role cannot manage ${noun} in this workspace` - ) + return roleCanAuthor(kind, caps) + ? undefined + : `Your role cannot manage ${noun} in this workspace` + }) } /** Reads context: call during component initialisation. */ diff --git a/frontend/src/lib/roleCapabilities.ts b/frontend/src/lib/roleCapabilities.ts index 55beec9ee0..1a9fc70a61 100644 --- a/frontend/src/lib/roleCapabilities.ts +++ b/frontend/src/lib/roleCapabilities.ts @@ -68,6 +68,19 @@ export function isRestricted(caps: RoleCapabilities): boolean { ) } +/** The role with nothing left to build and the same pages in view: what a session in Use mode + * acts as. */ +export function withoutBuilding(caps: RoleCapabilities): RoleCapabilities { + return { + ...caps, + code: false, + flows: 'none', + apps: 'none', + manage_schedules: false, + manage_triggers: false + } +} + /** Whether the role hides any page. */ export function hidesPages(caps: RoleCapabilities): boolean { return VISIBILITY.some((k) => !caps.visibility[k]) diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 7341baef49..cbc6b84503 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -1664,6 +1664,8 @@ export type Item = { id?: string tooltip?: string separatorTop?: boolean + /** A heading above the row, opening a section of the menu. */ + sectionTitle?: string /** Renders an on/off switch at the end of the row, so `icon` keeps the leading * slot. Presentational: the row's own click is what flips it, so `action` must * apply the change. */ diff --git a/frontend/src/lib/utils_workspace_deploy.ts b/frontend/src/lib/utils_workspace_deploy.ts index efa7f09115..272b2f1dad 100644 --- a/frontend/src/lib/utils_workspace_deploy.ts +++ b/frontend/src/lib/utils_workspace_deploy.ts @@ -26,7 +26,7 @@ import { get } from 'svelte/store' import { userWorkspaces } from '$lib/stores' import { capabilitiesIn } from '$lib/roleCapabilities' import { roleCanAuthor } from '$lib/editRights' -import type { RoleCapabilities } from '$lib/gen' +import type { ProtectionRuleset, RoleCapabilities } from '$lib/gen' import { fetchProtectionRulesForWorkspace, canUserBypassRuleKindInRulesets @@ -838,7 +838,9 @@ export async function checkDeployRules( workspace: string, /** Pre-fetched identity for `workspace`, to save a round trip. Narrowed to the fields * read so a caller holding a `UserExt` can pass it without a cast. */ - whoami?: Pick<User, 'is_admin' | 'is_super_admin' | 'username' | 'groups'> + whoami?: Pick<User, 'is_admin' | 'is_super_admin' | 'username' | 'groups'>, + /** Pre-fetched protection rules for `workspace`, to save another. */ + knownRulesets?: ProtectionRuleset[] ): Promise<DeployPermission> { try { const me = whoami ?? (await UserService.whoami({ workspace })) @@ -851,7 +853,7 @@ export async function checkDeployRules( // A superadmin who is only a plain member of the workspace still bypasses every rule, // so dropping either term here refuses a deploy the server accepts. if (!userInfo.is_admin && !userInfo.is_super_admin) { - const rulesets = await fetchProtectionRulesForWorkspace(workspace) + const rulesets = knownRulesets ?? (await fetchProtectionRulesForWorkspace(workspace)) if (!canUserBypassRuleKindInRulesets(rulesets, 'DisableDirectDeployment', userInfo)) { // The reserved dev-workspace lock carries DisableWorkspaceForking alongside this rule, // so suggesting a fork unconditionally would point at a second blocked action. diff --git a/frontend/src/lib/workspaceProtectionRules.svelte.ts b/frontend/src/lib/workspaceProtectionRules.svelte.ts index 01d122794d..af40138f7d 100644 --- a/frontend/src/lib/workspaceProtectionRules.svelte.ts +++ b/frontend/src/lib/workspaceProtectionRules.svelte.ts @@ -89,12 +89,19 @@ export async function loadProtectionRules(workspace: string): Promise<void> { export async function fetchProtectionRulesForWorkspace( workspace: string ): Promise<ProtectionRuleset[]> { + return (await readProtectionRulesForWorkspace(workspace)) ?? [] +} + +/** The same rules, but `undefined` when they cannot be read, for a caller that has to fail + * closed rather than read an error as "no rules". */ +export async function readProtectionRulesForWorkspace( + workspace: string +): Promise<ProtectionRuleset[] | undefined> { try { - const rulesets = await WorkspaceService.listProtectionRules({ workspace }) - return rulesets + return await WorkspaceService.listProtectionRules({ workspace }) } catch (error) { console.error(`Failed to fetch protection rules for workspace ${workspace}:`, error) - return [] + return undefined } } diff --git a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte index b648bd4212..ee1b95c765 100644 --- a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte @@ -1258,6 +1258,7 @@ <PreviewRouterPicker workspaceId={previewWorkspace} artifacts={sessionArtifacts} + chat={activeRuntime?.manager} onPick={(t) => { emptyStateNewTabOpen = false openInNewTab(t) @@ -1393,6 +1394,7 @@ {currentItem} workspaceId={previewWorkspace} artifacts={sessionArtifacts} + chat={activeRuntime?.manager} onPick={(t) => { activeTabPickerOpen = false navigatePreviewTo(t) @@ -1424,6 +1426,7 @@ <PreviewRouterPicker workspaceId={previewWorkspace} artifacts={sessionArtifacts} + chat={activeRuntime?.manager} onPick={(t) => { newTabOpen = false openInNewTab(t) diff --git a/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte b/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte index 327f64f962..32646b13f0 100644 --- a/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte +++ b/frontend/src/routes/(styled)/kitchen_sink/deploy_animation/+page.svelte @@ -113,6 +113,7 @@ ? { ok: true as const } : { ok: false as const, reason: 'Deploy disabled by the playground toggle' } }, + readOnly: false, async deployRow(item: DeployItem) { setStatus(item.key, { status: 'loading' }) deploying = true From f6f3a0a1f24cd9ea0d78207d6848147ebd73bea0 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Fri, 23 Oct 2026 07:10:12 -0700 Subject: [PATCH 066/101] fix: return variable.value as text so widening it changes no result type (#11976) * fix: return variable.value as text so widening it changes no result type Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to 16858ac4cf7326ed3d5a6fae1a97fcade5a97af7 This commit updates the EE repository reference after PR #920 was merged in windmill-ee-private. Previous ee-repo-ref: dcf6219b5635fc93f11dcb2fd0564c1c5f8407b3 New ee-repo-ref: 16858ac4cf7326ed3d5a6fae1a97fcade5a97af7 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> --- ...9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json | 23 --------------- ...84d2a06b9e55557757d407787078af1ecad7.json} | 10 +++---- ...402d5290b494dac690c9a11f121eeefeab8e.json} | 10 +++---- ...cb4db9e0c9aee05596a594f81975a0cdb74d1.json | 23 --------------- ...d4b51216ba05e2951ce045ff58112c1db361.json} | 10 +++---- ...fb944a54c1172ffa2b990ba157e676f66f51.json} | 10 +++---- ...c984000e12f33bc1cea460e8f5dd55ea59eec.json | 23 +++++++++++++++ ...d154f36986ee0da73725a40c860037b63310.json} | 10 +++---- ...609933e4363c11455709e1785228abd3366f.json} | 10 +++---- ...9f2e94c1c25b02bf324a730e4f734eb61c16.json} | 10 +++---- ...b82cd0127581ad831089231317af587bb25a.json} | 10 +++---- ...fa6b590cb357e19233318d2a2a31555dbc515.json | 23 +++++++++++++++ ...018dc033582642988ed7a3181989fef72fed.json} | 10 +++---- ...6538576b978a1083365b5a98fc4ca7ea9576.json} | 10 +++---- ...7c6bad7843f93d0a5780632b02fa215aa404b.json | 29 ------------------- ...b6bc5eca203bf02f46164db08580d128b860a.json | 29 ------------------- ...7398c1c11277e968af4acb9393ba2b340dd1e.json | 29 +++++++++++++++++++ backend/ee-repo-ref.txt | 2 +- .../src/datatable_clone.rs | 2 +- .../windmill-api-workspaces/src/workspaces.rs | 6 ++-- backend/windmill-api/src/offboarding.rs | 2 +- backend/windmill-api/src/users.rs | 2 +- backend/windmill-api/src/workspaces_export.rs | 4 +-- backend/windmill-common/src/min_version.rs | 8 +++-- .../src/secret_backend/database.rs | 2 +- backend/windmill-common/src/variables.rs | 17 ++++++----- backend/windmill-common/src/workspaces.rs | 2 +- backend/windmill-native-triggers/src/lib.rs | 2 +- .../windmill-store/src/oauth_refresh_oss.rs | 2 +- backend/windmill-store/src/resources.rs | 2 +- backend/windmill-store/src/variables.rs | 6 ++-- 31 files changed, 157 insertions(+), 181 deletions(-) delete mode 100644 backend/.sqlx/query-020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json rename backend/.sqlx/{query-7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71.json => query-08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7.json} (62%) rename backend/.sqlx/{query-146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e.json => query-1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e.json} (56%) delete mode 100644 backend/.sqlx/query-2c0ab7571e1a7c4290315bc3efccb4db9e0c9aee05596a594f81975a0cdb74d1.json rename backend/.sqlx/{query-b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd.json => query-3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361.json} (63%) rename backend/.sqlx/{query-71b410dbc6cdd0252de2f8646395903c9fa60a5435fa73c587da2b913203cf18.json => query-36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51.json} (50%) create mode 100644 backend/.sqlx/query-40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec.json rename backend/.sqlx/{query-2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e.json => query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json} (60%) rename backend/.sqlx/{query-1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4.json => query-5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f.json} (61%) rename backend/.sqlx/{query-0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13.json => query-698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16.json} (57%) rename backend/.sqlx/{query-61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08.json => query-a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a.json} (54%) create mode 100644 backend/.sqlx/query-a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515.json rename backend/.sqlx/{query-44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b.json => query-b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed.json} (63%) rename backend/.sqlx/{query-ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81.json => query-bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576.json} (58%) delete mode 100644 backend/.sqlx/query-bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b.json delete mode 100644 backend/.sqlx/query-c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a.json create mode 100644 backend/.sqlx/query-dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e.json diff --git a/backend/.sqlx/query-020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json b/backend/.sqlx/query-020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json deleted file mode 100644 index e8edd87bda..0000000000 --- a/backend/.sqlx/query-020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT value FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "value", - "type_info": "Varchar" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "020c031c3de6c85577e30421ada9d39a5a47ca1b6cf3dbfd6988aa0694d7364c" -} diff --git a/backend/.sqlx/query-7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71.json b/backend/.sqlx/query-08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7.json similarity index 62% rename from backend/.sqlx/query-7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71.json rename to backend/.sqlx/query-08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7.json index 331816c897..4031b62a9e 100644 --- a/backend/.sqlx/query-7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71.json +++ b/backend/.sqlx/query-08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, account, (now() > account.expires_at) as is_expired, is_secret, path from variable\n LEFT JOIN account ON variable.account = account.id WHERE variable.path = $1 AND variable.workspace_id = $2", + "query": "SELECT value::text AS \"value!\", account, (now() > account.expires_at) as is_expired, is_secret, path from variable\n LEFT JOIN account ON variable.account = account.id WHERE variable.path = $1 AND variable.workspace_id = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -36,12 +36,12 @@ ] }, "nullable": [ - false, + null, true, null, false, false ] }, - "hash": "7a92837ad2a1181580c1e0d059fd6bc0ece84d3c315635de52bd2b364c238a71" + "hash": "08af141e847f9bb6a4c26ccad3bd84d2a06b9e55557757d407787078af1ecad7" } diff --git a/backend/.sqlx/query-146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e.json b/backend/.sqlx/query-1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e.json similarity index 56% rename from backend/.sqlx/query-146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e.json rename to backend/.sqlx/query-1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e.json index 9fd6daded5..da40d27d9f 100644 --- a/backend/.sqlx/query-146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e.json +++ b/backend/.sqlx/query-1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + "query": "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -21,9 +21,9 @@ ] }, "nullable": [ - false, + null, false ] }, - "hash": "146f0e42ada3068a5cdae0ffdbb54b63f8c06c9143b16ce399170c1b5a6b911e" + "hash": "1cf81ee935e6e820463820519e3a402d5290b494dac690c9a11f121eeefeab8e" } diff --git a/backend/.sqlx/query-2c0ab7571e1a7c4290315bc3efccb4db9e0c9aee05596a594f81975a0cdb74d1.json b/backend/.sqlx/query-2c0ab7571e1a7c4290315bc3efccb4db9e0c9aee05596a594f81975a0cdb74d1.json deleted file mode 100644 index 9c4b3eb842..0000000000 --- a/backend/.sqlx/query-2c0ab7571e1a7c4290315bc3efccb4db9e0c9aee05596a594f81975a0cdb74d1.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT value FROM variable WHERE workspace_id = $1 AND path = $2", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "value", - "type_info": "Varchar" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "2c0ab7571e1a7c4290315bc3efccb4db9e0c9aee05596a594f81975a0cdb74d1" -} diff --git a/backend/.sqlx/query-b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd.json b/backend/.sqlx/query-3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361.json similarity index 63% rename from backend/.sqlx/query-b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd.json rename to backend/.sqlx/query-3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361.json index 6ad2fc0ae1..b7b2516d40 100644 --- a/backend/.sqlx/query-b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd.json +++ b/backend/.sqlx/query-3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT path, value, is_secret FROM variable WHERE workspace_id = $1", + "query": "SELECT path, value::text AS \"value!\", is_secret FROM variable WHERE workspace_id = $1", "describe": { "columns": [ { @@ -10,8 +10,8 @@ }, { "ordinal": 1, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 2, @@ -26,9 +26,9 @@ }, "nullable": [ false, - false, + null, false ] }, - "hash": "b656f38e5f1d6a0799767a775b8550027cf7a3bb202269e8dda92d31bc8789dd" + "hash": "3420c007c141c5d9e3748c18de03d4b51216ba05e2951ce045ff58112c1db361" } diff --git a/backend/.sqlx/query-71b410dbc6cdd0252de2f8646395903c9fa60a5435fa73c587da2b913203cf18.json b/backend/.sqlx/query-36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51.json similarity index 50% rename from backend/.sqlx/query-71b410dbc6cdd0252de2f8646395903c9fa60a5435fa73c587da2b913203cf18.json rename to backend/.sqlx/query-36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51.json index d74d5e6ba3..8d7e440538 100644 --- a/backend/.sqlx/query-71b410dbc6cdd0252de2f8646395903c9fa60a5435fa73c587da2b913203cf18.json +++ b/backend/.sqlx/query-36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT v.value, a.id AS account_id, a.refresh_token\n FROM variable v\n JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n WHERE v.workspace_id = $1 AND v.path = $2\n AND a.client = $3 AND a.is_workspace_integration = true", + "query": "SELECT v.value::text AS \"value!\", a.id AS account_id, a.refresh_token\n FROM variable v\n JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n WHERE v.workspace_id = $1 AND v.path = $2\n AND a.client = $3 AND a.is_workspace_integration = true", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -27,10 +27,10 @@ ] }, "nullable": [ - false, + null, false, false ] }, - "hash": "71b410dbc6cdd0252de2f8646395903c9fa60a5435fa73c587da2b913203cf18" + "hash": "36121d10cb03d45fc14aacd08750fb944a54c1172ffa2b990ba157e676f66f51" } diff --git a/backend/.sqlx/query-40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec.json b/backend/.sqlx/query-40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec.json new file mode 100644 index 0000000000..ab8bc4e241 --- /dev/null +++ b/backend/.sqlx/query-40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value::text AS \"value!\" FROM variable WHERE workspace_id = $1 AND path = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "40790b7f44b40b0c64bbabd3bc6c984000e12f33bc1cea460e8f5dd55ea59eec" +} diff --git a/backend/.sqlx/query-2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e.json b/backend/.sqlx/query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json similarity index 60% rename from backend/.sqlx/query-2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e.json rename to backend/.sqlx/query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json index 2939d5ac88..39dabb8fbb 100644 --- a/backend/.sqlx/query-2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e.json +++ b/backend/.sqlx/query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret, description\n FROM variable\n WHERE workspace_id = $1 AND path = $2", + "query": "SELECT value::text AS \"value!\", is_secret, description\n FROM variable\n WHERE workspace_id = $1 AND path = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -26,10 +26,10 @@ ] }, "nullable": [ - false, + null, false, false ] }, - "hash": "2d5ff8fc102ae0c452c1f9cd5cd30fd0a3b4e6e746c659da1767edafd139d45e" + "hash": "4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310" } diff --git a/backend/.sqlx/query-1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4.json b/backend/.sqlx/query-5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f.json similarity index 61% rename from backend/.sqlx/query-1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4.json rename to backend/.sqlx/query-5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f.json index 0ed678d485..386435e806 100644 --- a/backend/.sqlx/query-1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4.json +++ b/backend/.sqlx/query-5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", + "query": "SELECT value::text AS \"value!\", is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -26,10 +26,10 @@ ] }, "nullable": [ - false, + null, false, false ] }, - "hash": "1587639f13a1a3ad97bd324df38661f3e846f1992704c86ddad74dea151b0ec4" + "hash": "5d344853a65a2438c87f12124428609933e4363c11455709e1785228abd3366f" } diff --git a/backend/.sqlx/query-0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13.json b/backend/.sqlx/query-698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16.json similarity index 57% rename from backend/.sqlx/query-0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13.json rename to backend/.sqlx/query-698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16.json index 5c33539878..17e8d20bb5 100644 --- a/backend/.sqlx/query-0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13.json +++ b/backend/.sqlx/query-698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret FROM variable WHERE path = $1", + "query": "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -20,9 +20,9 @@ ] }, "nullable": [ - false, + null, false ] }, - "hash": "0c2e53960dc7786c848079b155e62994d4a861f1dbb9752c0a27428d83040e13" + "hash": "698758d7ef61b3f1de00088a36fe9f2e94c1c25b02bf324a730e4f734eb61c16" } diff --git a/backend/.sqlx/query-61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08.json b/backend/.sqlx/query-a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a.json similarity index 54% rename from backend/.sqlx/query-61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08.json rename to backend/.sqlx/query-a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a.json index f97d5e310a..5ac876fa73 100644 --- a/backend/.sqlx/query-61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08.json +++ b/backend/.sqlx/query-a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret\n FROM variable\n WHERE path = $1 AND workspace_id = $2", + "query": "SELECT value::text AS \"value!\", is_secret\n FROM variable\n WHERE path = $1 AND workspace_id = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -21,9 +21,9 @@ ] }, "nullable": [ - false, + null, false ] }, - "hash": "61f3627cbd2a50b745c4e491ed8ee71e58db22b7f53202c5360a01c92091fc08" + "hash": "a0f799d0211f0a7bd649747a6627b82cd0127581ad831089231317af587bb25a" } diff --git a/backend/.sqlx/query-a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515.json b/backend/.sqlx/query-a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515.json new file mode 100644 index 0000000000..828e5ba470 --- /dev/null +++ b/backend/.sqlx/query-a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value::text AS \"value!\" FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "a4badf66d2ae524d15925869c9bfa6b590cb357e19233318d2a2a31555dbc515" +} diff --git a/backend/.sqlx/query-44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b.json b/backend/.sqlx/query-b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed.json similarity index 63% rename from backend/.sqlx/query-44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b.json rename to backend/.sqlx/query-b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed.json index 18c572b1fb..44dcca2457 100644 --- a/backend/.sqlx/query-44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b.json +++ b/backend/.sqlx/query-b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed.json @@ -1,12 +1,12 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, is_secret, expires_at FROM variable WHERE path = $1", + "query": "SELECT value::text AS \"value!\", is_secret, expires_at FROM variable WHERE path = $1", "describe": { "columns": [ { "ordinal": 0, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" }, { "ordinal": 1, @@ -25,10 +25,10 @@ ] }, "nullable": [ - false, + null, false, true ] }, - "hash": "44a12919fb154055f1142cc078ef131f8a0c9cdb37cfba6283a6718480b02a4b" + "hash": "b2c35e00474b8fa335d9485c1f98018dc033582642988ed7a3181989fef72fed" } diff --git a/backend/.sqlx/query-ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81.json b/backend/.sqlx/query-bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576.json similarity index 58% rename from backend/.sqlx/query-ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81.json rename to backend/.sqlx/query-bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576.json index 3fe61f6f8e..09fa4b0b11 100644 --- a/backend/.sqlx/query-ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81.json +++ b/backend/.sqlx/query-bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT workspace_id, path, value FROM variable WHERE is_secret = true AND value IS NOT NULL AND value != ''", + "query": "SELECT workspace_id, path, value::text AS \"value!\" FROM variable WHERE is_secret = true AND value IS NOT NULL AND value != ''", "describe": { "columns": [ { @@ -15,8 +15,8 @@ }, { "ordinal": 2, - "name": "value", - "type_info": "Varchar" + "name": "value!", + "type_info": "Text" } ], "parameters": { @@ -25,8 +25,8 @@ "nullable": [ false, false, - false + null ] }, - "hash": "ade0696ec69bec2258d2e3ff86bfba6ed3b1d573c298f9d7fe8056ba7e32ed81" + "hash": "bc004ad060664cc75fc000229af16538576b978a1083365b5a98fc4ca7ea9576" } diff --git a/backend/.sqlx/query-bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b.json b/backend/.sqlx/query-bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b.json deleted file mode 100644 index 02a979f32f..0000000000 --- a/backend/.sqlx/query-bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT path, value FROM variable\n WHERE path LIKE ('u/' || $1 || '/%')\n AND workspace_id = $2\n AND is_secret = true\n AND (value LIKE '$vault:%' OR value LIKE '$azure_kv:%')", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "path", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "value", - "type_info": "Varchar" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - false, - false - ] - }, - "hash": "bda9fc0c6e41d8afebee538e6997c6bad7843f93d0a5780632b02fa215aa404b" -} diff --git a/backend/.sqlx/query-c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a.json b/backend/.sqlx/query-c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a.json deleted file mode 100644 index 74a9d24135..0000000000 --- a/backend/.sqlx/query-c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT value, account FROM variable WHERE workspace_id = $1 AND path = $2", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "value", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "account", - "type_info": "Int4" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - false, - true - ] - }, - "hash": "c0aff25f0cc3b71842b0ba9ae55b6bc5eca203bf02f46164db08580d128b860a" -} diff --git a/backend/.sqlx/query-dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e.json b/backend/.sqlx/query-dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e.json new file mode 100644 index 0000000000..6f1cc55c51 --- /dev/null +++ b/backend/.sqlx/query-dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT path, value::text AS \"value!\" FROM variable\n WHERE path LIKE ('u/' || $1 || '/%')\n AND workspace_id = $2\n AND is_secret = true\n AND (value LIKE '$vault:%' OR value LIKE '$azure_kv:%')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "value!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "dec3b1a5a743bfcee0c6a1efdfc7398c1c11277e968af4acb9393ba2b340dd1e" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 9c9efeeb1e..c7cffa7f07 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -6858e4cbd515b52713afea8dc32b23072af2248c +16858ac4cf7326ed3d5a6fae1a97fcade5a97af7 diff --git a/backend/windmill-api-workspaces/src/datatable_clone.rs b/backend/windmill-api-workspaces/src/datatable_clone.rs index 1e6c6b55c2..067a248aa7 100644 --- a/backend/windmill-api-workspaces/src/datatable_clone.rs +++ b/backend/windmill-api-workspaces/src/datatable_clone.rs @@ -104,7 +104,7 @@ pub(crate) async fn connection_snapshot( continue; } let row: Option<(String, bool)> = sqlx::query_as( - "SELECT value, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", + "SELECT value::text, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", ) .bind(w_id) .bind(var) diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index e2027c3e9b..4184af9779 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -6524,7 +6524,7 @@ async fn set_encryption_key( ); let all_variables = sqlx::query!( - "SELECT path, value, is_secret FROM variable WHERE workspace_id = $1", + "SELECT path, value::text AS \"value!\", is_secret FROM variable WHERE workspace_id = $1", w_id ) .fetch_all(&mut *tx) @@ -14503,7 +14503,7 @@ async fn compare_two_variables( // Get variable from each workspace let source_variable = sqlx::query!( - "SELECT value, is_secret, description + "SELECT value::text AS \"value!\", is_secret, description FROM variable WHERE workspace_id = $1 AND path = $2", source_workspace_id, @@ -14513,7 +14513,7 @@ async fn compare_two_variables( .await?; let target_variable = sqlx::query!( - "SELECT value, is_secret, description + "SELECT value::text AS \"value!\", is_secret, description FROM variable WHERE workspace_id = $1 AND path = $2", fork_workspace_id, diff --git a/backend/windmill-api/src/offboarding.rs b/backend/windmill-api/src/offboarding.rs index defaa05234..59305d96e3 100644 --- a/backend/windmill-api/src/offboarding.rs +++ b/backend/windmill-api/src/offboarding.rs @@ -1075,7 +1075,7 @@ async fn offboard_user_from_workspace<'c>( let new_var_prefix = format!("{}/", reassign_to); let vault_secrets: Vec<(String, String)> = sqlx::query!( - r#"SELECT path, value FROM variable + r#"SELECT path, value::text AS "value!" FROM variable WHERE path LIKE ('u/' || $1 || '/%') AND workspace_id = $2 AND is_secret = true diff --git a/backend/windmill-api/src/users.rs b/backend/windmill-api/src/users.rs index 8c742b6d64..ecf77b6d5f 100644 --- a/backend/windmill-api/src/users.rs +++ b/backend/windmill-api/src/users.rs @@ -632,7 +632,7 @@ async fn update_username_in_workpsace<'c>( // Fetch all externally-stored secret variables under this user's path let vault_secrets: Vec<(String, String)> = sqlx::query!( - r#"SELECT path, value FROM variable + r#"SELECT path, value::text AS "value!" FROM variable WHERE path LIKE ('u/' || $1 || '/%') AND workspace_id = $2 AND is_secret = true diff --git a/backend/windmill-api/src/workspaces_export.rs b/backend/windmill-api/src/workspaces_export.rs index 87496fed45..705c409621 100644 --- a/backend/windmill-api/src/workspaces_export.rs +++ b/backend/windmill-api/src/workspaces_export.rs @@ -972,9 +972,9 @@ pub(crate) async fn tarball_workspace( // would never match the variable it created and every sync would report it changed. let variables = sqlx::query_as::<_, ExportableListableVariable>(if !skip_secrets.unwrap_or(false) { - "SELECT workspace_id, path, value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" + "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" } else { - "SELECT workspace_id, path, value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" + "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" }) .bind(&w_id) .fetch_all(&mut *tx) diff --git a/backend/windmill-common/src/min_version.rs b/backend/windmill-common/src/min_version.rs index 3719abd31c..9005ab834a 100644 --- a/backend/windmill-common/src/min_version.rs +++ b/backend/windmill-common/src/min_version.rs @@ -27,9 +27,13 @@ pub const MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES: VC = vc(1, 822, 0, "Restricted // stored secret variables. Reading it ships one release earlier (1.831), so a rollback to // that release still reads every secret; below it, secrets written after the switch stay // unreadable until rolled forward. Only worker versions are seen here, not servers. -// Also gates widening `variable.value`, which needs every process to retire the connections -// the widening poisons (`db::retire_connections_opened_before_now`): that also ships in 1.832. pub const MIN_VERSION_SUPPORTS_AEAD_SECRETS: VC = vc(1, 832, 0, "AES-GCM secret encryption"); +// Gates widening `variable.value`. Every query returning that column casts it to text from +// this release, so the widening changes no result type: before it, each statement prepared on +// the column fails once per connection, and behind PgBouncer until its server connection +// closes. Must name the release this ships in. +pub const MIN_VERSION_SUPPORTS_VARIABLE_VALUE_WIDENING: VC = + vc(1, 848, 0, "variable.value widening"); // A renewed license key replaces the one every process reads, and a worker that predates // Ed25519 support rejects an Ed25519-signed key and stops pulling jobs, so renewal only offers // to accept one once this is met. Only worker versions are seen here, not servers. Must name diff --git a/backend/windmill-common/src/secret_backend/database.rs b/backend/windmill-common/src/secret_backend/database.rs index b450cc7e15..903ea85e24 100644 --- a/backend/windmill-common/src/secret_backend/database.rs +++ b/backend/windmill-common/src/secret_backend/database.rs @@ -39,7 +39,7 @@ impl DatabaseBackend { impl SecretBackend for DatabaseBackend { async fn get_secret(&self, workspace_id: &str, path: &str) -> Result<String> { let variable = sqlx::query!( - "SELECT value FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", + "SELECT value::text AS \"value!\" FROM variable WHERE path = $1 AND workspace_id = $2 AND is_secret = true", path, workspace_id ) diff --git a/backend/windmill-common/src/variables.rs b/backend/windmill-common/src/variables.rs index 512bd555f0..bc015ef022 100644 --- a/backend/windmill-common/src/variables.rs +++ b/backend/windmill-common/src/variables.rs @@ -451,7 +451,7 @@ pub async fn get_secret_value_as_admin( path: &str, ) -> crate::error::Result<String> { let variable_o = sqlx::query!( - "SELECT value, is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", path, w_id + "SELECT value::text AS \"value!\", is_secret, path from variable WHERE variable.path = $1 AND variable.workspace_id = $2", path, w_id ) .fetch_optional(db) .await?; @@ -542,9 +542,8 @@ pub fn variable_value_widen_pending() -> bool { /// Widen `variable.value` to [`VARIABLE_VALUE_WIDTH`], or `false` when it is too early to. /// Not a migration: changing a column's type, even its length, fails every statement a live -/// process prepared on it until its connection closes. It waits for v2 writes, gated on a -/// worker version that retires such connections on the first failure, so that no process too -/// old to recover is still running. +/// process prepared on it until its connection closes. It waits until no process returns the +/// column uncast. Any new query returning `variable.value` must select `value::text`. async fn widen_variable_value(db: &DB) -> error::Result<bool> { if VARIABLE_VALUE_WIDENED.load(Ordering::Relaxed) { return Ok(true); @@ -556,7 +555,9 @@ async fn widen_variable_value(db: &DB) -> error::Result<bool> { .fetch_one(db) .await?; if typmod >= 0 && typmod - 4 < VARIABLE_VALUE_WIDTH { - if crate::db::process_uptime() < crate::db::PREVIOUS_RELEASE_ROLLOUT_UPTIME { + if !crate::min_version::MIN_VERSION_SUPPORTS_VARIABLE_VALUE_WIDENING.met_conservatively() + || crate::db::process_uptime() < crate::db::PREVIOUS_RELEASE_ROLLOUT_UPTIME + { return Ok(false); } tracing::info!("widening variable.value to VARCHAR({VARIABLE_VALUE_WIDTH})"); @@ -669,7 +670,7 @@ async fn upgrade_workspace_secret_variables(db: &DB, w_id: &str) -> error::Resul }; let mc = crypt_from_key_with_suffix(&key, ""); let rows: Vec<(String, String)> = sqlx::query_as( - "SELECT path, value FROM variable WHERE workspace_id = $1 AND is_secret AND path > $2 \ + "SELECT path, value::text FROM variable WHERE workspace_id = $1 AND is_secret AND path > $2 \ ORDER BY path LIMIT $3", ) .bind(w_id) @@ -1009,7 +1010,7 @@ pub async fn get_variable_or_self( let path = path.strip_prefix("$var:").unwrap().to_string(); let record = sqlx::query!( - "SELECT value, is_secret + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", &path, @@ -1057,7 +1058,7 @@ pub async fn get_variable_or_self_as<T: Authable + Sync>( // Use an RLS-scoped transaction so the query respects row-level security let mut tx = user_db.clone().begin(authed).await?; let record = sqlx::query!( - "SELECT value, is_secret + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", &var_path, diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index 3b5d78c5b7..9132c51950 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -3805,7 +3805,7 @@ async fn transform_json_unchecked( serde_json::Value::String(s) if s.starts_with("$var:") => { let path = &s[5..]; let (value, is_secret): (String, bool) = sqlx::query_as( - "SELECT value, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", + "SELECT value::text, is_secret FROM variable WHERE workspace_id = $1 AND path = $2", ) .bind(&w_id) .bind(path) diff --git a/backend/windmill-native-triggers/src/lib.rs b/backend/windmill-native-triggers/src/lib.rs index c61a1ff335..4a8560d9f0 100644 --- a/backend/windmill-native-triggers/src/lib.rs +++ b/backend/windmill-native-triggers/src/lib.rs @@ -815,7 +815,7 @@ pub async fn decrypt_oauth_data<T: DeserializeOwned>( let mc = build_crypt(db, workspace_id).await?; let row = sqlx::query!( - "SELECT v.value, a.id AS account_id, a.refresh_token + "SELECT v.value::text AS \"value!\", a.id AS account_id, a.refresh_token FROM variable v JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account WHERE v.workspace_id = $1 AND v.path = $2 diff --git a/backend/windmill-store/src/oauth_refresh_oss.rs b/backend/windmill-store/src/oauth_refresh_oss.rs index 3d55b05167..a0d0926510 100644 --- a/backend/windmill-store/src/oauth_refresh_oss.rs +++ b/backend/windmill-store/src/oauth_refresh_oss.rs @@ -182,7 +182,7 @@ where async fn current_token(db: &DB, w_id: &str, path: &str) -> error::Result<String> { let value = sqlx::query_scalar!( - "SELECT value FROM variable WHERE workspace_id = $1 AND path = $2", + "SELECT value::text AS \"value!\" FROM variable WHERE workspace_id = $1 AND path = $2", w_id, path ) diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index 5aa8823012..9af92361f6 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -2189,7 +2189,7 @@ async fn update_resource( // Handle Vault secret rename if the linked variable is a Vault-stored secret let linked_var = sqlx::query!( - "SELECT value, is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", path, w_id ) diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index 352a411214..76e21908cd 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -337,7 +337,7 @@ async fn get_variable( let mut tx = user_db.begin(&authed).await?; let variable_o = sqlx::query_as::<_, ListableVariable>( - "SELECT variable.workspace_id, variable.path, variable.value, variable.is_secret, + "SELECT variable.workspace_id, variable.path, variable.value::text AS value, variable.is_secret, variable.description, variable.extra_perms, variable.account, variable.is_oauth, variable.expires_at, variable.labels, folder_labels(variable.workspace_id, variable.path) as inherited_labels, @@ -1243,7 +1243,7 @@ async fn update_variable( // Handle Vault secret rename if the variable is a secret stored in Vault let current_var = sqlx::query!( - "SELECT value, is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", path, w_id ) @@ -1537,7 +1537,7 @@ pub async fn get_value_internal<'a>( let mut tx = db_with_opt_authed.begin().await?; let variable_o = sqlx::query!( - "SELECT value, account, (now() > account.expires_at) as is_expired, is_secret, path from variable + "SELECT value::text AS \"value!\", account, (now() > account.expires_at) as is_expired, is_secret, path from variable LEFT JOIN account ON variable.account = account.id WHERE variable.path = $1 AND variable.workspace_id = $2", path, w_id ) .fetch_optional(&mut *tx) From fe38a1d3763a11f8b0bc4b07d61824d3a7b51850 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Fri, 23 Oct 2026 08:47:13 -0700 Subject: [PATCH 067/101] fix: share settings.yaml's git sync block between a fork and its parent (#11974) * fix: keep a fork's own auto-pull settings when applying settings.yaml The settings.yaml on a fork branch carries the parent's git_sync, so a pull into a fork failed with "Auto-pull cannot be configured on a fork workspace". The fork now keeps its own auto_pull and fork_open_prs and a throwaway fork drops promotion repos, matching fork creation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show the parent's git sync side in a fork's settings document A fork's settings.yaml is the parent's file, so exporting the fork's own git_sync (auto-pull off, no fork PRs, no promotion repos) and merging the fork back would turn off the parent's auto-pull. The fork's document now states the parent's values for the parts the parent owns, and applying one keeps the fork's own: the two are inverses, so a round trip is a no-op. Repos the fork does not carry are no longer added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: drop promotion repos on non-dev forks and keep the fork's repo order A dev workspace detached from dev keeps its promotion repo, which the validator refuses on a non-dev fork, so its pull still failed. And a fork whose own repo came before a shared one saw its document reorder the repos, so re-applying it was a change. The apply now drops promotion repos unless the fork is a dev workspace and emits repos in the fork's own order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply only a fork's synced git sync keys from settings.yaml Taking the parent's repo entry and restoring a few fork-owned fields let every unlisted field flow from the parent: a dev workspace lost its promotion mode, and a malformed repository list emptied the fork. The fork now starts from its own git_sync and takes only the item filters (settings, exclude_types_override, group_by_folder) of the repos it carries; the document is the parent's block with those keys from the fork. The parent's block is folded down the ancestor chain, so a fork of a dev workspace shows the root's auto-pull too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: sync a fork's legacy git sync filters and drop its stale promotion repos Repos without their own settings filter by the workspace-level include/exclude lists, which a fork now takes from settings.yaml while it stores them. A non-dev fork's apply drops the promotion repos it kept from a dev designation, so the write passes the save's check. An unset and a null key no longer count as a difference, so settings.yaml is not rewritten over the two spellings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: copy the filters a repo syncs by between a fork and settings.yaml A fork on per-repo settings applying a file still on workspace-level filters lost its repo settings and gained none, so it synced nothing. The copy now goes between each side's effective filters, the repo's settings with the workspace-level lists they fall back to filled in, so either layout maps onto the other. The workspace-level keys are no longer synced separately, and a null git_sync leaves them alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: sync a fork's filters only between per-repo settings on both sides The workspace-level filter layout reads an empty or missing per-repo list as "use the workspace's", so it cannot state some filters the per-repo layout can, and every mapping between the two widened or emptied a fork's filters on some round trip. Filters now cross only when neither the fork nor the file uses workspace-level filters; otherwise the fork keeps its own and its document keeps the parent's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: detect the legacy git sync layout by its fallback filters only exclude_path and extra_include_path are read only beside a fallback include_path, and the save leaves them behind once every repo has migrated, so they no longer mark a workspace as legacy. Rewraps the comment on the synced keys to say when settings crosses. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../src/workspace_settings_document.rs | 274 +++++++++++++++++- 1 file changed, 270 insertions(+), 4 deletions(-) diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index f83ffcb4e8..67243b361e 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -341,6 +341,11 @@ pub async fn load_settings_document( }; let datatable_permissions = datatable_permissions_document(row.datatable.as_ref(), &role_names); let protection_rules = protection_rules_document(&mut *conn, w_id).await?; + let git_sync = redact_git_sync(row.git_sync); + let git_sync = match fork_parent(&mut *conn, w_id).await? { + Some(parent) => fork_git_sync_document(git_sync, parent.git_sync), + None => git_sync, + }; // In the order `wmill sync pull` has always written settings.yaml. A key that predates the // document and is not marked `always` is written only when set, as it always was; a key @@ -352,7 +357,7 @@ pub async fn load_settings_document( ("success_handler", row.success_handler, true), ("ai_config", row.ai_config, false), ("large_file_storage", row.large_file_storage, false), - ("git_sync", redact_git_sync(row.git_sync), false), + ("git_sync", git_sync, false), ("default_app", row.default_app.map(Value::String), false), ("default_scripts", row.default_scripts, false), ("name", Some(json!(row.name.unwrap_or_default())), true), @@ -859,11 +864,36 @@ fn normalize_protection_rules(v: &Value, warnings: &mut Vec<String>) -> Result<V Ok(Value::Object(out)) } -async fn plan(db: &DB, w_id: &str, desired: Map<String, Value>, replace: bool) -> Result<Plan> { - let current = { +async fn plan(db: &DB, w_id: &str, mut desired: Map<String, Value>, replace: bool) -> Result<Plan> { + let (mut current, fork) = { let mut conn = db.acquire().await?; - load_settings_document(&mut conn, db, w_id, SecretMode::Plain).await? + let current = load_settings_document(&mut conn, db, w_id, SecretMode::Plain).await?; + (current, fork_parent(&mut conn, w_id).await?) }; + if let Some(fork) = fork { + // Diff against what the fork stores, not the parent's view the document shows it. + let own: Option<Value> = + sqlx::query_scalar("SELECT git_sync FROM workspace_settings WHERE workspace_id = $1") + .bind(w_id) + .fetch_optional(db) + .await? + .flatten(); + let own = redact_git_sync(own); + // A malformed value is left for the endpoint to refuse. + let stated = match desired.get("git_sync") { + Some(v) if v.is_object() || v.is_null() => Some(v), + Some(_) => None, + None => replace.then_some(&Value::Null), + }; + if let Some(stated) = stated { + let applied = fork_git_sync_to_apply(stated, own.as_ref(), fork.is_dev)?; + desired.insert("git_sync".to_string(), applied); + } + match own { + Some(own) => current.insert("git_sync".to_string(), own), + None => current.remove("git_sync"), + }; + } let mc = build_crypt(db, w_id).await?; let names = match desired.get("datatable_permissions") { Some(v) if !v.is_null() => DatatableNames::load(db, w_id, v).await?, @@ -872,6 +902,147 @@ async fn plan(db: &DB, w_id: &str, desired: Map<String, Value>, replace: bool) - plan_document(current, desired, replace, &mc, &names) } +/// A fork's parent, read for its `git_sync`. +struct ForkParent { + /// As the parent's own document states it: a fork of a fork shares the root's file too. + git_sync: Option<Value>, + /// Of the fork itself. + is_dev: bool, +} + +/// `Some` when `w_id` is a fork, by the same test as +/// `reject_parent_only_git_sync_settings_on_fork`. +async fn fork_parent(conn: &mut PgConnection, w_id: &str) -> Result<Option<ForkParent>> { + // The workspace itself, then its ancestors nearest first; the depth bound only guards + // against a cycle. + let mut chain: Vec<(bool, Option<Value>)> = sqlx::query_as( + "WITH RECURSIVE chain AS ( + SELECT id, parent_workspace_id, is_dev_workspace, 0 AS depth + FROM workspace WHERE id = $1 + UNION ALL + SELECT w.id, w.parent_workspace_id, w.is_dev_workspace, c.depth + 1 FROM workspace w + JOIN chain c ON w.id = c.parent_workspace_id WHERE c.depth < 32 + ) + SELECT c.is_dev_workspace, s.git_sync FROM chain c + LEFT JOIN workspace_settings s ON s.workspace_id = c.id + ORDER BY c.depth", + ) + .bind(w_id) + .fetch_all(&mut *conn) + .await?; + let is_dev = !chain.is_empty() && chain.remove(0).0; + if chain.is_empty() && !w_id.starts_with(windmill_common::workspaces::WM_FORK_PREFIX) { + return Ok(None); + } + let git_sync = chain.into_iter().rev().fold(None, |above, (_, own)| { + fork_git_sync_document(redact_git_sync(own), above) + }); + Ok(Some(ForkParent { git_sync, is_dev })) +} + +// A fork shares its parent's settings.yaml (the CLI maps `wm-fork/<branch>/<id>` to the parent's +// entry), so its `git_sync` there is the parent's. Of it, a fork applies only what selects the +// items synced, on the repos it carries: the keys listed here, and a repo's `settings` when +// neither side uses workspace-level filters. Auto-pull, fork PRs and promotion mode are not a +// fork's to take (`reject_parent_only_git_sync_settings_on_fork`), and any other field stays the +// fork's own. The fork's document is the parent's block with the fork's values for the same keys, +// the inverse of the apply, so a merge of the fork's branch changes only them in the parent. +const FORK_SYNCED_REPO_KEYS: [&str; 2] = ["exclude_types_override", "group_by_folder"]; + +fn repos(git_sync: Option<&Value>) -> &[Value] { + git_sync + .and_then(|g| g.get("repositories")) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +fn same_repo<'a>(repos: &'a [Value], repo: &Value) -> Option<&'a Value> { + let path = repo.get("git_repo_resource_path")?; + repos + .iter() + .find(|r| r.get("git_repo_resource_path") == Some(path)) +} + +/// Whether repos fall back to the workspace-level filters, where an empty or missing `settings` +/// list means "use the workspace's". A repo's filters cross only when neither side does, as +/// that layout cannot state some of what the other can. Only these two are fallen back to on +/// their own (`exclude_path`/`extra_include_path` only beside `include_path`), and the save +/// leaves the other two behind once every repo has migrated. +fn uses_workspace_filters(git_sync: &Value) -> bool { + ["include_path", "include_type"] + .iter() + .any(|k| !is_null(git_sync.get(*k))) +} + +/// An unset key and a null one are left as they are: stored blobs differ in which they write, and +/// swapping one for the other would show in settings.yaml as a change. +fn copy_keys(onto: &mut Map<String, Value>, from: &Value, keys: &[&str]) { + for key in keys { + if is_null(from.get(*key)) && is_null(onto.get(*key)) { + continue; + } + match from.get(*key) { + Some(v) => onto.insert(key.to_string(), v.clone()), + None => onto.remove(*key), + }; + } +} + +/// Sets `onto` to `from`'s values for the synced keys, on each repo `from` also lists. +fn copy_synced_keys(onto: &mut Value, from: &Value) { + let filters = !uses_workspace_filters(onto) && !uses_workspace_filters(from); + let from_repos = repos(Some(from)); + let Some(repos) = onto.get_mut("repositories").and_then(Value::as_array_mut) else { + return; + }; + for repo in repos { + let Some(src) = same_repo(from_repos, repo) else { + continue; + }; + if let Some(repo) = repo.as_object_mut() { + copy_keys(repo, src, &FORK_SYNCED_REPO_KEYS); + if filters { + copy_keys(repo, src, &["settings"]); + } + } + } +} + +/// The fork's `git_sync` as its settings.yaml states it. +fn fork_git_sync_document(own: Option<Value>, parent: Option<Value>) -> Option<Value> { + let Some(mut doc) = parent else { + return own; + }; + if let Some(own) = &own { + copy_synced_keys(&mut doc, own); + } + Some(doc) +} + +/// What a fork applies of the `git_sync` its settings.yaml states. Only a dev workspace may hold +/// a promotion repo, and one detached from dev still stores its own: it is dropped so the write +/// passes the save's check. +fn fork_git_sync_to_apply(stated: &Value, own: Option<&Value>, is_dev: bool) -> Result<Value> { + if stated.get("repositories").is_some_and(|r| !r.is_array()) { + return Err(Error::BadRequest( + "git_sync.repositories must be a list".to_string(), + )); + } + let Some(mut applied) = own.cloned() else { + return Ok(Value::Null); + }; + copy_synced_keys(&mut applied, stated); + if !is_dev { + if let Some(repos) = applied + .get_mut("repositories") + .and_then(Value::as_array_mut) + { + repos.retain(|r| r.get("use_individual_branch") != Some(&Value::Bool(true))); + } + } + Ok(applied) +} + fn plan_document( current: Map<String, Value>, mut desired: Map<String, Value>, @@ -1947,4 +2118,99 @@ mod tests { )); assert_eq!(p.warnings.len(), 1); } + + #[test] + fn a_fork_applies_only_the_synced_keys_of_the_repos_it_carries() { + let parent = json!({ "repositories": [ + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["f/**"] }, + "auto_pull": { "enabled": true, "sync_forks": true }, "fork_open_prs": true }, + { "git_repo_resource_path": "f/promo", "use_individual_branch": true }, + ] }); + // A dev workspace's promotion repo is the repo the parent syncs normally. + let fork = json!({ "repositories": [ + { "git_repo_resource_path": "f/own" }, + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["u/**"] }, + "use_individual_branch": true, "auto_pull": { "enabled": false } }, + ] }); + assert_eq!( + fork_git_sync_to_apply(&parent, Some(&fork), true).unwrap(), + json!({ "repositories": [ + { "git_repo_resource_path": "f/own" }, + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["f/**"] }, + "use_individual_branch": true, "auto_pull": { "enabled": false } }, + ] }) + ); + + // The fork's document is the parent's block with the fork's synced keys, and applying it + // back to the fork is a no-op. + let shown = fork_git_sync_document(Some(fork.clone()), Some(parent.clone())).unwrap(); + assert_eq!( + shown, + json!({ "repositories": [ + { "git_repo_resource_path": "f/r", "settings": { "include_path": ["u/**"] }, + "auto_pull": { "enabled": true, "sync_forks": true }, "fork_open_prs": true }, + { "git_repo_resource_path": "f/promo", "use_individual_branch": true }, + ] }) + ); + assert_eq!( + fork_git_sync_to_apply(&shown, Some(&fork), true).unwrap(), + fork + ); + + // Detached from dev, the fork may no longer hold its promotion repo. + assert_eq!( + fork_git_sync_to_apply(&parent, Some(&fork), false).unwrap(), + json!({ "repositories": [{ "git_repo_resource_path": "f/own" }] }) + ); + + // Filters cross only between two sides on per-repo settings: with workspace-level ones on + // either side, the fork keeps its own and the document keeps the parent's. + let legacy_parent = json!({ "include_path": ["f/**"], "include_type": ["script"], + "repositories": [{ "git_repo_resource_path": "f/r" }] }); + let migrated = json!({ "repositories": [{ "git_repo_resource_path": "f/r", + "settings": { "include_path": ["u/**"], "include_type": [] } }] }); + assert_eq!( + fork_git_sync_to_apply(&legacy_parent, Some(&migrated), false).unwrap(), + migrated + ); + let shown = + fork_git_sync_document(Some(migrated.clone()), Some(legacy_parent.clone())).unwrap(); + assert_eq!(shown, legacy_parent); + assert_eq!( + fork_git_sync_to_apply(&shown, Some(&migrated), false).unwrap(), + migrated + ); + let legacy_fork = json!({ "include_path": ["u/**"], "include_type": ["flow"], + "repositories": [{ "git_repo_resource_path": "f/r" }] }); + let migrated_parent = json!({ "repositories": [{ "git_repo_resource_path": "f/r", + "settings": { "include_path": ["f/**"], "include_type": ["script"] } }] }); + assert_eq!( + fork_git_sync_document(Some(legacy_fork.clone()), Some(migrated_parent.clone())), + Some(migrated_parent.clone()) + ); + assert_eq!( + fork_git_sync_to_apply(&migrated_parent, Some(&legacy_fork), false).unwrap(), + legacy_fork + ); + assert_eq!( + fork_git_sync_to_apply(&Value::Null, Some(&legacy_fork), false).unwrap(), + legacy_fork + ); + // An `exclude_path` the save leaves behind after migrating is no fallback. + let mut leftover = migrated.clone(); + leftover["exclude_path"] = json!(["x/**"]); + assert_eq!( + fork_git_sync_to_apply(&migrated_parent, Some(&leftover), false).unwrap() + ["repositories"][0]["settings"], + migrated_parent["repositories"][0]["settings"] + ); + + assert!( + fork_git_sync_to_apply(&json!({ "repositories": null }), Some(&fork), true).is_err() + ); + assert_eq!( + fork_git_sync_to_apply(&parent, None, true).unwrap(), + Value::Null + ); + } } From 79fe8ab03f6f052bf7fe763b6f8a0a23fe922611 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Fri, 23 Oct 2026 08:58:18 -0700 Subject: [PATCH 068/101] fix: keep the log indexer starting when a stored day chunk is broken (#11979) * fix: keep the log indexer starting when a stored day chunk is broken Bumps the EE ref to the companion change in windmill-ee-private. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to f806a793b07105417dd7a592fbfc93ec2f226d4e This commit updates the EE repository reference after PR #921 was merged in windmill-ee-private. Previous ee-repo-ref: 008b710eb0d92b382b9d20835c9fa8a41d867dad New ee-repo-ref: f806a793b07105417dd7a592fbfc93ec2f226d4e Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> --- backend/ee-repo-ref.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index c7cffa7f07..44b23b28b7 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -16858ac4cf7326ed3d5a6fae1a97fcade5a97af7 +f806a793b07105417dd7a592fbfc93ec2f226d4e From 3d6a2bcef2e284d64690db04db32a2326a4b0670 Mon Sep 17 00:00:00 2001 From: Guilhem <guilhemlemouel@gmail.com> Date: Fri, 23 Oct 2026 17:58:44 +0200 Subject: [PATCH 069/101] fix: fork a raw app into the raw app builder, in its session when there (#11978) * fix: fork a raw app into the raw app builder, in its session when there Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: keep the source's sandbox and sdk scopes on a forked raw app Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: fork a raw app from the editor's content, not the server's copy Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --- .../apps/editor/AppEditorHeader.svelte | 2 +- .../components/raw_apps/RawAppEditor.svelte | 4 ++ .../raw_apps/RawAppEditorHeader.svelte | 24 +++++++- .../components/raw_apps/forkRawApp.svelte.ts | 55 +++++++++++++++++++ .../sessions/RawAppEditorView.svelte | 12 +++- 5 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 frontend/src/lib/components/raw_apps/forkRawApp.svelte.ts diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte index e5613a71a1..f6f89b864f 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte @@ -1326,7 +1326,7 @@ { label: 'Fork', onClick: () => { - window.open(`/apps/add?template=${appPath}`) + window.open(`/apps/add?template=${encodeURIComponent($appPath)}`) } }, ...(!isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 67a3ccbf6a..55b211ecdd 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -173,6 +173,8 @@ // Threaded to the AutosaveIndicator's "Reset to deployed" button. /** `Exit & see details`: see RawAppEditorHeader. */ onDetails?: (e: { path: string }) => void + /** See RawAppEditorHeader. */ + onOpenFork?: (path: string) => void onResetToDeployed?: () => void | Promise<void> /** The app_version the draft forked from, for the deploy-time "new version * deployed" guard: deploying is refused with a confirmation while it is not @@ -244,6 +246,7 @@ compact = false, pendingDraftPath = $bindable(undefined), onDetails, + onOpenFork, onResetToDeployed, loadedFromDraft = false, othersDraftsCount = 0, @@ -2726,6 +2729,7 @@ addEventListener('message', function (e) { {onNavigate} {onDeploy} {onDetails} + {onOpenFork} {onResetToDeployed} {loadedFromDraft} {othersDraftsCount} diff --git a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte index bc14c298e9..fbc391ac78 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte @@ -51,6 +51,7 @@ import AppEditorHeaderDeploy from '../apps/editor/AppEditorHeaderDeploy.svelte' import type { Runnable } from './RawAppInlineScriptRunnable.svelte' import { updateRawAppPolicy } from './rawAppPolicy' + import { saveRawAppFork } from './forkRawApp.svelte' import { aiChatManager } from '../copilot/chat/AIChatManager.svelte' import { getContext } from 'svelte' @@ -188,6 +189,9 @@ /** `Exit & see details`: leaves the editor for the app's deployed page. A session hosts that * page itself, so it flips the tab there rather than navigating out of the session. */ onDetails?: (e: { path: string }) => void + /** Opens the draft `Fork` saved. Without it, the fork opens in a new browser tab; a + * session opens it as one of its own tabs instead. */ + onOpenFork?: (path: string) => void onResetToDeployed?: () => void | Promise<void> // See ScriptBuilderProps — same semantics for the raw-app editor's // indicator. @@ -239,6 +243,7 @@ onDeploy = undefined, pendingDraftPath = $bindable(undefined), onDetails, + onOpenFork, onResetToDeployed, loadedFromDraft = false, othersDraftsCount = 0, @@ -257,6 +262,21 @@ const opWorkspace = $derived(autosaveWorkspace ?? $operatingWorkspace) const indicatorPath = $derived(autosavePath ?? liveEditorDraftStoragePath) + async function forkApp() { + if (!opWorkspace || !files) return + const workspace = opWorkspace + // Opened before the save: a tab opened after an await is no longer tied to the + // click, and browsers block it as a popup. + const tab = onOpenFork ? undefined : window.open('', '_blank') + const forkPath = await saveRawAppFork(workspace, { files, runnables, data, policy }) + if (!forkPath) { + tab?.close() + return + } + if (onOpenFork) onOpenFork(forkPath) + else if (tab) tab.location.href = `/apps_raw/edit/${forkPath}?workspace=${workspace}` + } + $effect(() => { const typed = newEditedPath const baseline = savedApp?.path ?? '' @@ -1217,9 +1237,7 @@ ]), { label: 'Fork', - onClick: () => { - window.open(`/apps/add?template=${appPath}`) - } + onClick: forkApp }, ...(!isCloudHosted() && editInForkAllowed(opWorkspace, $userWorkspaces) ? [ diff --git a/frontend/src/lib/components/raw_apps/forkRawApp.svelte.ts b/frontend/src/lib/components/raw_apps/forkRawApp.svelte.ts new file mode 100644 index 0000000000..ffeab765da --- /dev/null +++ b/frontend/src/lib/components/raw_apps/forkRawApp.svelte.ts @@ -0,0 +1,55 @@ +import { get } from 'svelte/store' +import type { Policy } from '$lib/gen' +import { userStore } from '$lib/stores' +import { sendUserToast } from '$lib/toast' +import { UserDraft } from '$lib/userDraft.svelte' +import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' +import { mintDraftPath } from '$lib/mintDraftPath' +import { userPathPrefix } from '$lib/utils' +import { random_adj } from '$lib/components/random_positive_adjetive' +import type { RawAppDraft } from '$lib/components/sessions/appDraftCodec' +import type { RawAppData } from './dataTableRefUtils' + +/** + * Saves what the editor holds as a new raw-app draft under a fresh path and returns that + * path, or `undefined` when the save failed. The copy is taken from the editor rather than + * reloaded from the server, which would miss edits autosave has not written (or never will, + * with auto-save off). + */ +export async function saveRawAppFork( + workspace: string, + source: { + files: Record<string, string> + runnables: Record<string, any> + data: RawAppData + policy: Policy | undefined + } +): Promise<string | undefined> { + const user = get(userStore) + const forkPath = mintDraftPath() + const draft: RawAppDraft = { + summary: '', + files: $state.snapshot(source.files), + runnables: $state.snapshot(source.runnables), + data: $state.snapshot(source.data), + // The forker's identity, since the source's would publish as its owner, but the + // source's sandbox and SDK scopes: the copied code's SDK calls depend on them. + policy: { + on_behalf_of: user?.username.includes('@') ? user.username : `u/${user?.username}`, + on_behalf_of_email: user?.email, + execution_mode: 'publisher', + sandbox: source.policy?.sandbox ?? false, + frontend_sdk_scopes: $state.snapshot(source.policy?.frontend_sdk_scopes) + }, + // Without it the fork would deploy under its `draft_<uuid>` storage path. + draft_path: `${userPathPrefix(user?.username)}${random_adj()}_app` + } + UserDraft.save('raw_app', forkPath, draft, { workspace }) + await UserDraft.forcePersist('raw_app', forkPath, { workspace }) + const saved = UserDraftDbSyncer.getState({ workspace, itemKind: 'raw_app', path: forkPath }) + if (saved.state === 'failed') { + sendUserToast(`Could not save the fork: ${saved.failureMessage ?? 'unknown error'}`, true) + return undefined + } + return forkPath +} diff --git a/frontend/src/lib/components/sessions/RawAppEditorView.svelte b/frontend/src/lib/components/sessions/RawAppEditorView.svelte index 81e219f7f4..50ea1e054a 100644 --- a/frontend/src/lib/components/sessions/RawAppEditorView.svelte +++ b/frontend/src/lib/components/sessions/RawAppEditorView.svelte @@ -100,7 +100,9 @@ files: { ...result.files }, runnables: { ...result.runnables, - ...(capabilitiesInWorkspace(workspaceId).apps === 'compose' ? {} : structuredClone(STARTER_RUNNABLES)) + ...(capabilitiesInWorkspace(workspaceId).apps === 'compose' + ? {} + : structuredClone(STARTER_RUNNABLES)) }, data: result.data, policy: result.policy @@ -162,6 +164,13 @@ }) }) + function openFork(forkPath: string) { + runtime.previewTabs.open({ + type: 'item', + item: { kind: 'app', raw_app: true, path: forkPath, summary: '' } + }) + } + async function reloadDeployed() { await runtime.loadRawApp(workspaceId, path, true, true) } @@ -380,6 +389,7 @@ {diffDrawer} {onNavigate} onDetails={onSeeDetails} + onOpenFork={openFork} condensedHeader={true} onResetToDeployed={reloadDeployed} onDeploy={(e) => runtime.itemDeployed(workspaceId, 'raw_app', path, e.path)} From 11f2a4c7ffac980036f839759ae93da6ff3f22e4 Mon Sep 17 00:00:00 2001 From: hugocasa <hugo@casademont.ch> Date: Fri, 23 Oct 2026 18:01:13 +0200 Subject: [PATCH 070/101] feat: fill docusign, salesforce and quickbooks fields on connect (#11960) * feat: fill docusign account_id and base_uri on connect Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: fill salesforce and quickbooks connect fields through connect_fields Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: note connect_fields source trust and pin sandbox inheritance Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to 5517ff637a675aee66d4e417d3f37266045f0e0c This commit updates the EE repository reference after PR #913 was merged in windmill-ee-private. Previous ee-repo-ref: ba98803b236f018ed45199344f744ea1387afe2d New ee-repo-ref: 5517ff637a675aee66d4e417d3f37266045f0e0c Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> Co-authored-by: Ruben Fiszel <ruben@windmill.dev> --- backend/ee-repo-ref.txt | 2 +- backend/oauth_connect.json | 17 +++- backend/windmill-api/openapi.yaml | 12 +++ backend/windmill-oauth/src/lib.rs | 96 +++++++++++++++++++ .../src/lib/components/AppConnectInner.svelte | 6 +- .../oauth/callback/[client_name]/+page.svelte | 6 +- 6 files changed, 129 insertions(+), 10 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 44b23b28b7..20006c2a99 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -f806a793b07105417dd7a592fbfc93ec2f226d4e +5517ff637a675aee66d4e417d3f37266045f0e0c diff --git a/backend/oauth_connect.json b/backend/oauth_connect.json index 611e3f7c17..ecb4f95166 100644 --- a/backend/oauth_connect.json +++ b/backend/oauth_connect.json @@ -343,6 +343,10 @@ "quickbooks": { "auth_url": "https://appcenter.intuit.com/connect/oauth2", "token_url": "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer", + "connect_fields": { + "realmId": "callback.realmId" + }, + "resource_fields": ["realmId", "isSandBox"], "scopes": ["com.intuit.quickbooks.accounting"] }, "visma": { @@ -468,15 +472,26 @@ "docusign": { "auth_url": "https://account.docusign.com/oauth/auth", "token_url": "https://account.docusign.com/oauth/token", + "userinfo_url": "https://account.docusign.com/oauth/userinfo", + "connect_fields": { + "account_id": "userinfo.accounts[is_default=true].account_id", + "base_uri": "userinfo.accounts[is_default=true].base_uri" + }, + "resource_fields": ["account_id", "base_uri"], "scopes": ["signature"], "sandbox": { "auth_url": "https://account-d.docusign.com/oauth/auth", - "token_url": "https://account-d.docusign.com/oauth/token" + "token_url": "https://account-d.docusign.com/oauth/token", + "userinfo_url": "https://account-d.docusign.com/oauth/userinfo" } }, "salesforce": { "auth_url": "https://login.salesforce.com/services/oauth2/authorize", "token_url": "https://login.salesforce.com/services/oauth2/token", + "connect_fields": { + "instance_url": "token.instance_url" + }, + "resource_fields": ["instance_url"], "scopes": ["api", "refresh_token", "offline_access"], "sandbox": { "auth_url": "https://test.salesforce.com/services/oauth2/authorize", diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 2398eb368a..36b170b22d 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -8837,6 +8837,11 @@ paths: type: string state: type: string + params: + type: object + description: The callback URL's other query params, which the provider's `connect_fields` may read (QuickBooks' `realmId`) + additionalProperties: + type: string required: - code - state @@ -37929,6 +37934,13 @@ components: type: string grant_type: type: string + resource_fields: + type: object + additionalProperties: {} + description: > + Resource fields the provider's `connect_fields` picked on connect + (Salesforce's instance_url, Docusign's account_id and base_uri, + QuickBooks' realmId), for the connect dialog to prefill. required: - access_token diff --git a/backend/windmill-oauth/src/lib.rs b/backend/windmill-oauth/src/lib.rs index 3b32f0436f..57fe97eac2 100644 --- a/backend/windmill-oauth/src/lib.rs +++ b/backend/windmill-oauth/src/lib.rs @@ -66,6 +66,8 @@ pub struct ClientWithScopes { pub extra_params_callback: Option<HashMap<String, String>>, pub allowed_domains: Option<Vec<String>>, pub userinfo_url: Option<String>, + /// See [`OAuthConfig::connect_fields`]. + pub connect_fields: Option<HashMap<String, String>>, pub grant_types: Vec<String>, pub token_response_path: Option<String>, /// Resolved token endpoint, exposed so the connect dialog can prefill and @@ -88,6 +90,15 @@ pub struct OAuthConfig { #[serde(default = "empty_string")] pub token_url: String, pub userinfo_url: Option<String>, + /// Resource fields the connect callback fills from what the provider returns, + /// as field -> path (see [`connect_resource_fields`]). A path starts with its + /// source: `token.` (the raw token response, before `token_response_path` + /// unwraps it), `userinfo.` (`userinfo_url`'s response, fetched only when a + /// path needs it) or `callback.` (the callback URL's query params). The browser + /// relays `callback.` values, so they only prefill the user's own resource: + /// nothing server-side may trust them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub connect_fields: Option<HashMap<String, String>>, /// The registry JSON may also carry frontend-only keys for the connect /// dialog, deliberately not modelled here: `scope_options`, a scope pick /// list, `resource_fields`, the fields of the resource type the dialog @@ -353,6 +364,10 @@ pub struct SlackTeam { pub struct OAuthCallback { pub code: String, pub state: String, + /// The callback URL's other query params (QuickBooks' `realmId`), read by + /// `connect_fields` paths under `callback.`. + #[serde(default)] + pub params: HashMap<String, String>, } /// Build a basic OAuth client from configuration @@ -902,6 +917,48 @@ pub fn parse_token_response( }) } +/// What the connect callback returns: the token, and the resource fields its +/// `connect_fields` picked, which the connect dialog prefills. +#[derive(Debug, Serialize)] +pub struct ConnectCallbackResponse { + #[serde(flatten)] + pub token: TokenResponse, + #[serde(skip_serializing_if = "HashMap::is_empty")] + pub resource_fields: HashMap<String, serde_json::Value>, +} + +/// Picks each field's value out of `sources` (`{token, userinfo, callback}`). A path +/// is dot-separated keys, and a `key[k=v]` segment takes the element of array `key` +/// whose `k` is `v` (`userinfo.accounts[is_default=true].base_uri`). Only the listed +/// paths leave the server, and fields whose path misses are left out. +pub fn connect_resource_fields( + sources: &serde_json::Value, + fields: &HashMap<String, String>, +) -> HashMap<String, serde_json::Value> { + fn get<'a>(v: &'a serde_json::Value, path: &str) -> Option<&'a serde_json::Value> { + path.split('.') + .try_fold(v, |v, seg| match seg.split_once('[') { + Some((key, filter)) => { + let (k, want) = filter.strip_suffix(']')?.split_once('=')?; + v.get(key)?.as_array()?.iter().find(|e| match e.get(k) { + Some(serde_json::Value::String(s)) => s == want, + Some(other) => other.to_string() == want, + None => false, + }) + } + None => v.get(seg), + }) + } + fields + .iter() + .filter_map(|(field, path)| { + get(sources, path) + .filter(|v| !v.is_null()) + .map(|v| (field.clone(), v.clone())) + }) + .collect() +} + /// Pre-fetched account fields needed for token refresh. pub struct OAuthAccountInfo { pub client: String, @@ -1260,11 +1317,50 @@ mod tests { assert_eq!(&*token.access_token, "xoxe.xoxp-new"); } + #[test] + fn connect_fields_pick_from_each_source() { + let registry: HashMap<String, OAuthConfig> = + serde_json::from_str(include_str!("../../oauth_connect.json")).unwrap(); + let fields = |p: &str| registry[p].connect_fields.clone().unwrap(); + + let docusign = serde_json::json!({"userinfo": {"accounts": [ + {"account_id": "a1", "is_default": false, "base_uri": "https://na2.docusign.net"}, + {"account_id": "a2", "is_default": true, "base_uri": "https://demo.docusign.net"} + ]}}); + let got = connect_resource_fields(&docusign, &fields("docusign")); + assert_eq!(got["account_id"], "a2"); + assert_eq!(got["base_uri"], "https://demo.docusign.net"); + let no_account = serde_json::json!({"userinfo": {"accounts": []}}); + assert!(connect_resource_fields(&no_account, &fields("docusign")).is_empty()); + + let salesforce = serde_json::json!({"token": { + "access_token": "t", "instance_url": "https://acme.my.salesforce.com", "id_token": "x" + }}); + let want = HashMap::from([( + "instance_url".to_string(), + serde_json::json!("https://acme.my.salesforce.com"), + )]); + assert_eq!( + connect_resource_fields(&salesforce, &fields("salesforce")), + want + ); + let sandbox = registry["salesforce"].as_sandbox().unwrap(); + assert_eq!(sandbox.connect_fields, registry["salesforce"].connect_fields); + + let quickbooks = serde_json::json!({"callback": {"realmId": "9130"}}); + let got = connect_resource_fields(&quickbooks, &fields("quickbooks")); + assert_eq!( + got, + HashMap::from([("realmId".to_string(), serde_json::json!("9130"))]) + ); + } + fn sample_oauth_config(with_sandbox: bool) -> OAuthConfig { OAuthConfig { auth_url: "https://account.example.com/oauth/auth".to_string(), token_url: "https://account.example.com/oauth/token".to_string(), userinfo_url: Some("https://account.example.com/userinfo".to_string()), + connect_fields: None, scopes: Some(vec!["signature".to_string()]), cc_scopes: None, extra_params: None, diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index d29d97a1dc..81dd5225fb 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -185,7 +185,6 @@ * toggling back from client-credentials can restore them. */ let instanceScopes: string[] = $state([]) let extra_params: [string, string][] = [] - let responseExtra: Record<string, string> = $state({}) let path: string = $state('') let description = $state('') let labels: string[] | undefined = $state(undefined) @@ -672,7 +671,7 @@ resourceType = stripSandboxSuffix(connectClient) value = data.res.access_token! valueToken = data.res - responseExtra = data.extra ?? {} + Object.assign(args, data.res.resource_fields ?? {}) fillGeneratedDescription() step = 4 // `fillPath` decides the path as surely as express does, so neither stops here. @@ -959,9 +958,6 @@ } } } - if (resourceType === 'quickbooks' && responseExtra['realmId']) { - args['realmId'] = responseExtra['realmId'] - } let accountData: any = undefined if (valueToken?.expires_in != undefined) { diff --git a/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte b/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte index bfb6a9b10b..f91e26c976 100644 --- a/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte +++ b/frontend/src/routes/(styled)/oauth/callback/[client_name]/+page.svelte @@ -29,16 +29,16 @@ // goto('/resources') } else if (code && state) { try { - const extraParams = Object.fromEntries( + const params = Object.fromEntries( Array.from(Object.entries(urlParamsToObject(page.url.searchParams))).filter( ([key]) => key !== 'code' && key !== 'state' && key !== 'error' ) ) const res = await OauthService.connectCallback({ clientName: client_name ?? '', - requestBody: { code, state } + requestBody: { code, state, params } }) - const message = { type: 'success', res, resource_type: client_name, extra: extraParams } + const message = { type: 'success', res, resource_type: client_name } sendUserToast('successful', false) if (window.opener) { console.log('Sending oauth popup message') From 18c69360c9a8e9a9fe4c7c1d9e825a2b7be403a9 Mon Sep 17 00:00:00 2001 From: Guilhem <guilhemlemouel@gmail.com> Date: Fri, 23 Oct 2026 18:03:42 +0200 Subject: [PATCH 071/101] fix: home's acting-on follows the workspace home switches to (#11946) * fix: home's acting-on follows the workspace home switches to Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: say home's draft also follows its workspace on mount Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: home leaves a draft picked onto another workspace to the session page Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: home keeps its own draft across a workspace switch made on another page Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: home lets go of its draft once the session page takes it Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --- .../sessions/HomeSessionStarter.svelte | 14 +++++ .../sessions/SessionWorkspaceBar.svelte | 10 +++- .../sessions/sessionState.svelte.ts | 35 +++++++++-- .../components/sessions/sessionState.test.ts | 59 ++++++++++++++++++- 4 files changed, 110 insertions(+), 8 deletions(-) diff --git a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte index 74171dfcdd..942025c21c 100644 --- a/frontend/src/lib/components/sessions/HomeSessionStarter.svelte +++ b/frontend/src/lib/components/sessions/HomeSessionStarter.svelte @@ -16,8 +16,10 @@ homeStarterSession, setSessionDraftAttachments, selectSession, + sessionInCurrentFamily, sessionPageHref, sessionState, + setNewSessionWorkspace, setSessionDraftPrompt } from './sessionState.svelte' import SessionWorkspaceBar from './SessionWorkspaceBar.svelte' @@ -97,6 +99,18 @@ const wrapper = chatWrapper requestAnimationFrame(() => onSettled?.(wrapper.offsetHeight)) }) + // The draft acts on the workspace Home shows, whichever picker switched it: a switch within + // the family keeps this mount, so the draft's pick has to follow. A switch to another family + // remounts with that family's draft, so this one is left where it was. A staged fork of the + // shown workspace stays. On mount, a draft that differs is one that follows Home, moved off it + // by a switch made elsewhere (homeStarterSession). + onMount(() => + workspaceStore.subscribe((ws) => { + const s = sessionState.sessions.find((x) => x.id === sessionId) + if (!ws || !s || s.workspace_id || s.pending_workspace_id === ws) return + if (sessionInCurrentFamily(s)) setNewSessionWorkspace(sessionId, ws) + }) + ) onMount(() => { onShown?.() if (takeComposerFocus()) setTimeout(() => aiChat?.focusInput(), 0) diff --git a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte index 0df6004f34..768064576a 100644 --- a/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte +++ b/frontend/src/lib/components/sessions/SessionWorkspaceBar.svelte @@ -1,7 +1,7 @@ <script lang="ts" module> import { get } from 'svelte/store' import { workspaceStore } from '$lib/stores' - import { setSessionPendingWorkspace } from './sessionState.svelte' + import { setSessionPendingWorkspace, stopFollowingHome } from './sessionState.svelte' import { switchWorkspace } from '$lib/storeUtils' import { workspaceAIClients } from '$lib/components/copilot/lib' import { fixupUrlAfterWorkspaceSwitch } from '$lib/components/sidebar/workspaceSwitchUrl' @@ -13,8 +13,15 @@ void fixupUrlAfterWorkspaceSwitch(id) } + // Before the pick, which stores the session: Home would otherwise move a draft picked off + // Home back to the workspace it shows. + function releaseFromHome(sessionId: string, switchesWorkspace: boolean) { + if (!switchesWorkspace) stopFollowingHome(sessionId) + } + /** Point a session that has not sent yet at workspace `id`, as a pick in this bar does. */ export function pickSessionWorkspace(sessionId: string, id: string, switchesWorkspace: boolean) { + releaseFromHome(sessionId, switchesWorkspace) // Pre-send only: writes the pending pick. workspace_id stays undefined until // the user sends their first message. The chat targets this pending workspace // via the manager's workspace resolver, not the global workspaceStore. @@ -47,6 +54,7 @@ } function stageFork(req: { parent_workspace_id: string; id: string; name: string }) { + releaseFromHome(session.id, switchesWorkspace) setSessionPendingFork(session.id, req) followPick(req.parent_workspace_id, switchesWorkspace) } diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index 96a5ffc0cb..9f6bb07dd4 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -98,6 +98,10 @@ export type Session = { // deferred to first send (via commitSessionWorkspace) so cancelling // the draft doesn't leave an orphan fork behind. pending_fork?: PendingFork + // Home's draft: it acts on whatever workspace Home shows, so a switch made on another page + // moves it on Home's next mount. Cleared by a pick made on the session page, whose picker + // leaves the navigation workspace where it is. + followsHome?: boolean // Stable root workspace id used only for sidebar grouping. Lifecycle follows // workspace_id, not this field. Root sessions store the same id in both fields. workspace_root_id?: string @@ -1096,6 +1100,9 @@ export function createSession(): Session { (s) => isDiscardableDraft(s) && sessionInCurrentFamily(s) ) if (reusable) { + // It may be Home's draft; asked for here, it is the session page's now, and callers + // park it on a workspace of their own that Home must not move it off. + delete reusable.followsHome sessionState.currentSessionId = reusable.id // The blank recovery just landed on is exactly what this reuses, so `+` // would otherwise hand back a session still carrying the recovery notice: @@ -1149,22 +1156,31 @@ function newTransientSession(): Session { /** The unsent session Home's composer writes into, so a prompt half-typed on Home is the * one the empty session page shows, and the reverse. Never selects it: merely opening Home * must not change which session the AI Sessions switch resumes. A session opened on an - * item (it carries preview tabs) is about that item, so Home starts its own instead. */ + * item (it carries preview tabs) is about that item, and one the session page picked onto + * another workspace of the family is about that workspace: Home acts on the workspace it + * shows, so it starts its own instead of moving either. */ export function homeStarterSession(): Session { + const homeWs = get(workspaceStore) + const homes = (s: Session) => + (s.followsHome || s.pending_workspace_id === homeWs) && sessionInCurrentFamily(s) const unsent = (s: Session) => - !s.archived && !s.workspace_id && !s.previewTabs?.length && sessionInCurrentFamily(s) + !s.archived && !s.workspace_id && !s.previewTabs?.length && homes(s) const current = sessionState.sessions.find((s) => s.id === sessionState.currentSessionId) - if (current && unsent(current)) return current // Stored but never sent: a draft the user touched, by typing or by picking where it acts. // Either is theirs to come back to, and leaving it would strand it in the sidebar. const touched = sessionState.sessions .filter((s) => unsent(s) && !s.transient) .sort((a, b) => sessionLastActivityAt(b) - sessionLastActivityAt(a))[0] - return ( + const draft = + (current && unsent(current) ? current : undefined) ?? touched ?? - sessionState.sessions.find((s) => isDiscardableDraft(s) && sessionInCurrentFamily(s)) ?? + sessionState.sessions.find((s) => isDiscardableDraft(s) && homes(s)) ?? newTransientSession() - ) + if (!draft.followsHome) { + draft.followsHome = true + if (!draft.transient) void putSession(draft) + } + return draft } // Promote an in-memory transient session to a persisted IndexedDB record. @@ -1188,6 +1204,13 @@ export function setSessionPendingWorkspace(id: string, workspace_id: string) { if (changed) persistTouched(s) } +export function stopFollowingHome(id: string) { + const s = sessionState.sessions.find((x) => x.id === id) + if (!s?.followsHome) return + delete s.followsHome + if (!s.transient) void putSession(s) +} + // Park a just-created session on a workspace. Deliberately does not persist a // still-transient draft: picking where it will live is part of creating it, not a // user touch, so an unused draft still vanishes on reload (see `transient`). diff --git a/frontend/src/lib/components/sessions/sessionState.test.ts b/frontend/src/lib/components/sessions/sessionState.test.ts index 4c6666a349..5dd3570c6b 100644 --- a/frontend/src/lib/components/sessions/sessionState.test.ts +++ b/frontend/src/lib/components/sessions/sessionState.test.ts @@ -3,6 +3,7 @@ import { get } from 'svelte/store' import { commitSessionWorkspace, createSession, + setNewSessionWorkspace, decideSessionLifecycle, findEmptyLandingSession, getSessionDraftAttachments, @@ -714,7 +715,7 @@ describe('withOpenSessionTeardown — the gate that holds recovery off during a describe('homeStarterSession', () => { it("shows the family's stored draft, not the conversation in view, and selects nothing", () => { - const restore = withTwoFamilies('rootA') + const restore = withTwoFamilies('forkA') const prevCurrent = sessionState.currentSessionId const conversation = session({ id: 'conversation', workspace_id: 'rootA' }) // Touched only by picking where it acts: no text, but stored, so it is the user's draft. @@ -740,6 +741,62 @@ describe('homeStarterSession', () => { } }) + it('leaves a draft picked onto another workspace of the family to that workspace', () => { + const restore = withTwoFamilies('rootA') + const prevCurrent = sessionState.currentSessionId + const picked = session({ id: 'picked-fork-draft', pending_workspace_id: 'forkA' }) + sessionState.sessions.push(picked) + sessionState.currentSessionId = 'picked-fork-draft' + let createdId: string | undefined + try { + createdId = homeStarterSession().id + expect(createdId).not.toBe('picked-fork-draft') + expect(picked.pending_workspace_id).toBe('forkA') + } finally { + sessionState.sessions = sessionState.sessions.filter( + (s) => !['picked-fork-draft', createdId].includes(s.id) + ) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + + it('keeps its own draft when the workspace was switched on another page', () => { + const restore = withTwoFamilies('forkA') + const typed = session({ + id: 'home-draft', + pending_workspace_id: 'rootA', + draftPrompt: 'typed on Home', + followsHome: true + }) + sessionState.sessions.push(typed) + try { + expect(homeStarterSession().id).toBe('home-draft') + } finally { + sessionState.sessions = sessionState.sessions.filter((s) => s.id !== 'home-draft') + restore() + } + }) + + it('lets go of its draft once the session page reuses it for a new session', () => { + const restore = withTwoFamilies('forkA') + const prevCurrent = sessionState.currentSessionId + const ids: string[] = [] + try { + ids.push(homeStarterSession().id) + const reused = createSession() + expect(reused.id).toBe(ids[0]) + setNewSessionWorkspace(reused.id, 'rootA') + ids.push(homeStarterSession().id) + expect(ids[1]).not.toBe(ids[0]) + expect(reused.pending_workspace_id).toBe('rootA') + } finally { + sessionState.sessions = sessionState.sessions.filter((s) => !ids.includes(s.id)) + sessionState.currentSessionId = prevCurrent + restore() + } + }) + it('reports the never-touched drafts it drops, so their runtimes can be disposed', () => { const restore = withTwoFamilies('rootB') const prevCurrent = sessionState.currentSessionId From 7a29abc7eec491c35217445c1c08486ff030a22c Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:12:55 +0200 Subject: [PATCH 072/101] feat: run a workspace handler when a variable's value expires (#10837) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: run a workspace handler when a secret variable expires Secret variables gain an optional `value_expires_at`, and a workspace can point at a script or flow to run once that date passes, so a rotation is driven by the platform instead of tracked out of band. The secret never leaves the database. The sweep selects the path, description and expiry and nothing else, so the handler is given a reference to rotate rather than a value to handle. Job results are stored in cleartext and shown in Runs, which is what makes that a boundary rather than a preference; a test asserts the job's args never contain the value. Each row is claimed by writing `expiration_dispatched_for` in the same transaction as the push, so a failed push un-claims it and a lost race claims nothing. Moving the date re-arms the row; re-saving the same date does not. A pass takes at most 100 rows under a transaction-scoped advisory lock, and orders so that one broken workspace cannot starve the rest. Dispatch runs as `g/variable_expiration_handler`, exempt from the CE group limit and from non-premium exec metering the way the error and schedule handlers already are. A handler that keeps failing backs off and raises a critical alert instead of retrying every pass, and the back-off ends when the handler is repointed. The expiry travels with the variable through workspace clone, tarball export and workspace comparison. The dispatch marker deliberately does not, so a fork re-arms on its own copy. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(frontend): expose variable value expiration in the UI The variable drawer takes an optional expiry on a secret value, and the variables list badges it, turning red once the date has passed. A workspace settings tab picks the handler, its extra args, and whether variables under `u/` are skipped. That mute flag is stored inside the handler setting, so the toggle stays disabled until a handler is picked: saving it on its own would clear the setting it lives in and still report success. The expiry is carried as a tri-state through the draft deploy and copilot paths — absent leaves the remote value alone, an explicit null clears it — so deploying a draft cannot silently drop a date someone set elsewhere. The settings tab names the one case where the configured identity does not apply: a handler script carrying `on_behalf_of` runs as that user rather than as `g/variable_expiration_handler`, which matters because the same tab asks the admin to grant that group write access to the variables it rotates. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(cli): sync variable expiry and the workspace expiration handler `wmill sync` carries `value_expires_at` on variables in both directions, and pushes the workspace handler alongside the error and success handlers in the grouped settings format. Dropping the key from a variable's yaml clears the remote expiry, so the file stays canonical rather than accumulating fields that can only ever be added. The handler follows the same rule, with the caveat recorded where the type is declared: an omitted handler only reaches the clear when some other setting differs, because the push short-circuits on a comparison that walks the local object's keys and so never sees a missing one. That gate is shared with the two existing handlers and is left as it is here. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(frontend): open the variable expiration handler template in a new tab The "Create a handler" button hands its script template to /scripts/add through the URL hash, which `load` reads from `window.location`. A client-side navigation leaves the previous page's hash in place, so the payload was dropped and the editor opened on the default template at a `u/` path. `target="_blank"` forces a full page load, matching the success handler's "Create from template" button. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(frontend): make the variable expiry field state its own status The expiry field rendered a DateTimeInput whose time defaults to 12:00 when it holds no value, so a variable with no expiry looked like one already configured, and "cleared" looked identical to "never set". Setting an expiry is optional, so the field has to say which it is. Rebuild it on the shape ScriptAdvancedSettings already uses for Timeout, Cache and Concurrency limits: a toggle whose checked state is the stored value being present, seeding a date on enable rather than revealing an empty picker, with the input under its own label. Drop `clearable` with it, so the toggle is the single way to mean "no expiry" instead of competing with an X. Stop the surrounding copy promising a run that may not happen. A handler is only dispatched if the workspace has one configured and does not skip u/ paths, so the list tooltip now states the date alone, and the form hedges both conditions, naming the u/ mute only on personal paths where it can apply. Also anchor the mute toggle's tooltip: Popover's trigger is a span around a block-level label, which stretched to the full width of its SettingCard and left the popup floating beside the card rather than under the control. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(rust-client): initialize value_expires_at in the variable models The generated `CreateVariable` / `EditVariable` structs gain the field from openapi.yaml, and client.rs builds both with exhaustive literals. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(frontend): drop extra_args when the variable expiration handler is cleared Clearing the handler nulls the whole setting server-side, extra_args included, but the tab kept its loaded copy. A handler picked afterwards without reloading was persisted with the cleared one's arguments, which the tab does not display. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat: back the variable expiration handler's built-in Slack and Teams destinations Backfills the Slack bot token grant for g/variable_expiration_handler, mirroring 20231016142659 for g/error_handler: the slack_bot folder's extra_perms is written once at Slack connect and never refreshed, and disconnecting leaves the folder behind, so workspaces that already connected Slack cannot pick the grant up from the creation-time list alone. Adds run_variable_expiration_test_job so an admin can exercise the handler on demand rather than waiting for a real expiry, which may be months away. It goes through push_variable_expiration_handler so the test run proves what matters: the handler resolves, and the group can read what it needs, under the same identity and argument shape the sweep uses. Also covers extra_args on the edit endpoint, which the settings tab now writes for the built-ins' channel. The endpoint rebuilds the setting from the request, so an omitted extra_args erases it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * feat(frontend): offer Slack and Teams as variable expiration handlers Gives the variable expiration tab the same no-code destinations the workspace error handler has, so "tell #ops before this credential expires" no longer requires writing a script. A sibling component rather than a fourth mode of ErrorOrRecoveryHandler: that one is shared with the workspace error handler and the three schedule handlers, and its stripped-args list, hub path suffixes and Email tab are all error-shaped. This reuses the pieces that are already generic (SlackConnectionStatus, TeamsConnectionStatus, ChannelSelector, ScriptPicker, SchemaForm) and leaves those five call sites untouched. extra_args stops being an API/CLI-only escape hatch now that the built-ins write their channel into it, so it joins the unsaved-changes comparison and the discard path, normalised through the existing helper that drops the two auto-managed keys. The two hub ids are placeholders until the scripts are pushed to the hub. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * fix(frontend): scope the handler identity notice to the chosen destination The notice told every admin to grant g/variable_expiration_handler write access to the variables it rotates. That is right for a custom handler and wrong for the built-ins, which only post a message and are granted the Slack bot token by migration. Following it for a Slack handler would hand a group write access to the workspace's secrets for no reason. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * feat(frontend): flag the Slack and Teams handlers as EE Connecting a workspace to Slack or Teams is EE-only (oauth2_oss.rs returns "Slack only available on enterprise"), so on CE those two tabs can never be completed. Says so up front, the way the error/success handler tab does, instead of leaving the user at a "not connected" badge with no working path. Only on those two tabs: a custom script or flow handler is CE. Drops the "Connect Slack first" alert, now that the banner and the connection badge above it already say it twice. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * chore(backend): regenerate the sqlx cache after the merge The merged workspace_settings column list in change_workspace_id is a new query text, so it needs a new cached entry. Drops the two pre-merge entries it supersedes; both had been left with conflict markers by the merge, since rename/rename markers are eight characters and escape the usual scan. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * fix(cli): narrow the expiry-clear check to a variable that exists remotely Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * feat(frontend): point the built-in handlers at their published hub scripts Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(backend): regenerate the sqlx cache after the merge Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(frontend): disable the Slack and Teams handler controls without a license Matches the workspace error handler, which greys out its built-in destinations and hides the test button on an unlicensed instance. The custom destination stays editable: unlike the error handler, the variable expiration handler itself is not an EE feature. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: record which destination a variable expiration handler uses handler_configured now counts slack, teams, custom or cleared instead of set or cleared, so usage shows whether the built-in destinations are picked. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(frontend): let the variable expiration handler template run on any worker Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: guard the variable expiration test endpoint and correct its help text * fix: reuse the error handler's slack arg and built-in path helpers * docs: trim variable expiration sweep and backfill comments * feat: put the variable value expiration under an advanced section * fix: restrict the expiration test job to built-ins and keep expiry on conflict reload * fix: link the expiry hint to the variable's workspace and document built-in test paths * fix: give the expiration sweep its own lock id and reuse double_option * fix: pin the variable expiration presets so the hub-paths test accepts them * feat: let the variable expiration handler set how far ahead it runs * fix: give the notify before expiry setting its own card * feat: remind the variable expiration handler at a set interval * fix: tighten the gap between the Slack channel field and its test button * feat: refuse a value expiry on variables linked to an OAuth account * refactor: reuse the shared handler form for variable expiration * refactor: sweep expiring variables round-robin and check the handler exists * chore: trim comments to the constraints they record * fix: compare expiry dates by moment when deploying a variable draft * refactor: rename value_expires_at to value_valid_until * fix: neutralize variable fields in expiration handler args * fix: reserve the variable_expiration_handler group name for admins * fix: send first expiry notices before reminders * test: pin that a handler failing to start leaves its rows unclaimed * chore: say any hub handler path skips the existence check * fix: empty a pre-existing handler group before granting it the Slack token * docs: correct the registered feature usage counts * fix: let a workspace whose handler failed to start sit out for an hour * fix: send first notices before reminders across workspaces * fix: end a failed handler's wait as soon as it is redeployed * fix: show an expiry-only variable change in the AI fork diff * chore: regenerate workspace tool schemas * test: keep one variable expiration guard per behavior * fix: use the renamed hub expiration handlers and template * feat: carry the variable expiry in windmill-utils-internal 1.8.4 * fix: keep the variable expiry through MCP drafts * chore: bump windmill-utils-internal to 1.8.4 * fix: keep the variable expiry through mcp deploys * fix: disable saving a slack or teams expiry handler without ee * fix: skip the failure mark when the expiry handler was saved mid-sweep * fix: count expiry telemetry only where the expiry changed * test: assert the exact variable expiry in export and cli push tests * fix: stamp an expiry handler failure with the pass's read time * fix: wait for a pending handler lock instead of marking it failed * test: isolate expiry handler tests from the deployed-script cache * fix: retry a failing expiry handler every pass instead of waiting an hour * chore: update ee-repo-ref to b6e23d229966cf0019c0a1926a254fda658d8def This commit updates the EE repository reference after PR #744 was merged in windmill-ee-private. Previous ee-repo-ref: c52c06d145b13a6fb04459e85ca5818bf3c1bff4 New ee-repo-ref: b6e23d229966cf0019c0a1926a254fda658d8def Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> Co-authored-by: hugocasa <hugo@casademont.ch> --- ...69d6768972478def50010f680103d7c4281b.json} | 12 +- ...95bcfb8f9400809ade1b173bac05d61bfe77a.json | 24 + ...227a40a49d9435107e71033740f11cc8d2417.json | 15 - ...e4f5a2923cff642905c6410267be2eab24853.json | 23 + ...182b3ac165cb6a343ad616409fa80b4b93484.json | 22 + ...150c3ddc2fd4be3b8c682f6faa7b917387593.json | 214 +++++++ ...27c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json | 15 - ...e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json | 15 + ...129371c7c62e30d77ba6c5e74b575de635b30.json | 26 + ...73af0d18e3b4ce2eb7a20929f8c4c101141b6.json | 12 + ...e14e0f95b81c61241ffd0c9d633e562c4c4f6.json | 14 + ...7f41c3a72838c5d4c5f795638506084561894.json | 15 + ...189c7e0376ca1f0071ae8360183ed1300d2bb.json | 238 ++++++++ ...4c928d1e608ddd063d9d5ce3cea8ea62faca4.json | 12 + ...031d05da988837ce41d63a43d13c2018a57d3.json | 71 +++ ...3a4c216b4be67b68241461b42326d9d65256.json} | 4 +- ...220cb6f8346d2bfcd901371b480a16a70109c.json | 15 + ...9279396ed7213da4598034332bb0ba6ce271c.json | 22 + ...62122478424a36193254d5e00b8723ca28079.json | 20 + ...c4effa302380d4b434d8c74677bfbf895333c.json | 12 + backend/ee-repo-ref.txt | 2 +- ...180615_variable_value_valid_until.down.sql | 9 + ...24180615_variable_value_valid_until.up.sql | 30 + ...space_variable_expiration_handler.down.sql | 3 + ...rkspace_variable_expiration_handler.up.sql | 6 + ...le_expiration_handler_slack_perms.down.sql | 1 + ...able_expiration_handler_slack_perms.up.sql | 7 + backend/src/monitor.rs | 11 + backend/summarized_schema.txt | 4 +- backend/tests/variable_expiration.rs | 534 ++++++++++++++++++ backend/tests/workspace_export.rs | 42 ++ backend/windmill-api-groups/src/groups.rs | 5 +- .../tests/variables.rs | 68 +++ .../tests/workspace_comparison.rs | 80 +++ .../windmill-api-workspaces/src/workspaces.rs | 176 +++++- .../src/workspaces_extra.rs | 2 +- backend/windmill-api/openapi.yaml | 90 ++- .../src/mcp/auto_generated_endpoints.rs | 13 +- .../windmill-api/src/mcp/session/deploy.rs | 7 +- .../src/mcp/session/gen/instructions.json | 2 +- .../src/mcp/session/gen/tools.json | 15 +- backend/windmill-api/src/mcp/session/items.rs | 21 +- .../windmill-api/src/mcp/session/workspace.rs | 8 + .../src/workspace_settings_document.rs | 98 +++- backend/windmill-api/src/workspaces_export.rs | 4 +- backend/windmill-common/src/lib.rs | 8 +- backend/windmill-common/src/utils.rs | 7 + backend/windmill-common/src/variables.rs | 7 + backend/windmill-queue/src/jobs.rs | 101 +++- backend/windmill-queue/src/lib.rs | 1 + .../windmill-queue/src/variable_expiration.rs | 309 ++++++++++ backend/windmill-store/src/variables.rs | 33 +- cli/src/commands/variable/variable.ts | 11 +- cli/src/core/settings.ts | 10 + cli/test/deploy_variable_expiry_unit.test.ts | 60 ++ cli/test/variable_resource_push.test.ts | 64 +++ cli/windmill-utils-internal/package-lock.json | 4 +- cli/windmill-utils-internal/package.json | 2 +- cli/windmill-utils-internal/src/deploy.ts | 4 + docs/feature-telemetry.md | 8 +- frontend/package-lock.json | 8 +- frontend/package.json | 2 +- .../lib/components/CompareWorkspaces.svelte | 3 +- .../components/ErrorOrRecoveryHandler.svelte | 37 +- .../src/lib/components/VariableEditor.svelte | 66 ++- .../src/lib/components/VariableForm.svelte | 60 +- .../common/seconds/SecondsInput.svelte | 70 ++- .../copilot/chat/global/core.test.ts | 34 ++ .../components/copilot/chat/global/core.ts | 34 +- .../copilot/chat/global/diffSnapshot.test.ts | 14 + .../copilot/chat/global/diffSnapshot.ts | 1 + .../copilot/chat/global/userDraftAdapter.ts | 1 + .../copilot/chat/global/workspaceItems.ts | 1 + .../copilot/chat/workspaceToolsZod.gen.ts | 3 +- .../src/lib/components/handlerDraft.svelte.ts | 6 +- .../components/variables/VariablesList.svelte | 18 +- frontend/src/lib/hub.ts | 2 + frontend/src/lib/hubPaths.json | 2 + frontend/src/lib/mcpEndpointTools.ts | 13 +- frontend/src/lib/utils_draft_deploy.test.ts | 60 +- frontend/src/lib/utils_draft_deploy.ts | 19 +- .../(logged)/workspace_settings/+page.svelte | 268 ++++++++- rust-client/src/client.rs | 2 + 83 files changed, 3230 insertions(+), 162 deletions(-) rename backend/.sqlx/{query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json => query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json} (64%) create mode 100644 backend/.sqlx/query-32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a.json delete mode 100644 backend/.sqlx/query-37275b26b092ed3ae1a11b78da5227a40a49d9435107e71033740f11cc8d2417.json create mode 100644 backend/.sqlx/query-3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853.json create mode 100644 backend/.sqlx/query-4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484.json create mode 100644 backend/.sqlx/query-74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593.json delete mode 100644 backend/.sqlx/query-77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json create mode 100644 backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json create mode 100644 backend/.sqlx/query-9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30.json create mode 100644 backend/.sqlx/query-9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6.json create mode 100644 backend/.sqlx/query-9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6.json create mode 100644 backend/.sqlx/query-9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894.json create mode 100644 backend/.sqlx/query-af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb.json create mode 100644 backend/.sqlx/query-b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4.json create mode 100644 backend/.sqlx/query-cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3.json rename backend/.sqlx/{query-bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c.json => query-de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256.json} (74%) create mode 100644 backend/.sqlx/query-e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c.json create mode 100644 backend/.sqlx/query-eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c.json create mode 100644 backend/.sqlx/query-eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079.json create mode 100644 backend/.sqlx/query-ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c.json create mode 100644 backend/migrations/20260824180615_variable_value_valid_until.down.sql create mode 100644 backend/migrations/20260824180615_variable_value_valid_until.up.sql create mode 100644 backend/migrations/20260824180616_workspace_variable_expiration_handler.down.sql create mode 100644 backend/migrations/20260824180616_workspace_variable_expiration_handler.up.sql create mode 100644 backend/migrations/20260903161430_variable_expiration_handler_slack_perms.down.sql create mode 100644 backend/migrations/20260903161430_variable_expiration_handler_slack_perms.up.sql create mode 100644 backend/tests/variable_expiration.rs create mode 100644 backend/windmill-queue/src/variable_expiration.rs create mode 100644 cli/test/deploy_variable_expiry_unit.test.ts diff --git a/backend/.sqlx/query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json b/backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json similarity index 64% rename from backend/.sqlx/query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json rename to backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json index 39dabb8fbb..3933b5e6a2 100644 --- a/backend/.sqlx/query-4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310.json +++ b/backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT value::text AS \"value!\", is_secret, description\n FROM variable\n WHERE workspace_id = $1 AND path = $2", + "query": "SELECT value::text AS \"value!\", is_secret, description, value_valid_until\n FROM variable\n WHERE workspace_id = $1 AND path = $2", "describe": { "columns": [ { @@ -17,6 +17,11 @@ "ordinal": 2, "name": "description", "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "value_valid_until", + "type_info": "Timestamptz" } ], "parameters": { @@ -28,8 +33,9 @@ "nullable": [ null, false, - false + false, + true ] }, - "hash": "4ff75cdf9ee681cccb4b793704c9d154f36986ee0da73725a40c860037b63310" + "hash": "30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b" } diff --git a/backend/.sqlx/query-32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a.json b/backend/.sqlx/query-32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a.json new file mode 100644 index 0000000000..0e2bcbd955 --- /dev/null +++ b/backend/.sqlx/query-32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO variable\n (workspace_id, path, value, is_secret, description, account, is_oauth, expires_at, value_valid_until, labels, edited_by)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Bool", + "Varchar", + "Int4", + "Bool", + "Timestamptz", + "Timestamptz", + "TextArray", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "32c7dba63931c9bd35f82f145d095bcfb8f9400809ade1b173bac05d61bfe77a" +} diff --git a/backend/.sqlx/query-37275b26b092ed3ae1a11b78da5227a40a49d9435107e71033740f11cc8d2417.json b/backend/.sqlx/query-37275b26b092ed3ae1a11b78da5227a40a49d9435107e71033740f11cc8d2417.json deleted file mode 100644 index 7560df9dd2..0000000000 --- a/backend/.sqlx/query-37275b26b092ed3ae1a11b78da5227a40a49d9435107e71033740f11cc8d2417.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at FROM workspace_settings WHERE workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "37275b26b092ed3ae1a11b78da5227a40a49d9435107e71033740f11cc8d2417" -} diff --git a/backend/.sqlx/query-3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853.json b/backend/.sqlx/query-3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853.json new file mode 100644 index 0000000000..a41e413243 --- /dev/null +++ b/backend/.sqlx/query-3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND archived = false AND deleted = false)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "3c951e76bd0d86a488372e54fdfe4f5a2923cff642905c6410267be2eab24853" +} diff --git a/backend/.sqlx/query-4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484.json b/backend/.sqlx/query-4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484.json new file mode 100644 index 0000000000..8cead5cb8e --- /dev/null +++ b/backend/.sqlx/query-4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_failed_at = NULL\n WHERE workspace_id = $1 AND variable_expiration_failed_at IS NOT NULL\n RETURNING 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "4ba98c3b07a3bd2fa51e4ddf93c182b3ac165cb6a343ad616409fa80b4b93484" +} diff --git a/backend/.sqlx/query-74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593.json b/backend/.sqlx/query-74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593.json new file mode 100644 index 0000000000..5bf83d1b33 --- /dev/null +++ b/backend/.sqlx/query-74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593.json @@ -0,0 +1,214 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT\n workspace_id,\n slack_team_id,\n teams_team_id,\n teams_team_name,\n teams_team_guid,\n slack_name,\n slack_command_script,\n teams_command_script,\n slack_email,\n slack_oauth_client_id,\n slack_oauth_client_secret,\n customer_id,\n plan,\n webhook,\n ai_config,\n dbt_warehouses,\n large_file_storage,\n datatable,\n ducklake,\n git_sync,\n deploy_ui,\n default_app,\n default_scripts,\n mute_critical_alerts,\n color,\n operator_settings,\n git_app_installations,\n auto_invite,\n error_handler,\n success_handler,\n variable_expiration_handler,\n public_app_execution_limit_per_minute,\n error_handler_fallback_to_instance_alerts\n FROM\n workspace_settings\n WHERE\n workspace_id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "slack_team_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "teams_team_id", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "teams_team_name", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "teams_team_guid", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "slack_name", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "slack_command_script", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "teams_command_script", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "slack_email", + "type_info": "Varchar" + }, + { + "ordinal": 9, + "name": "slack_oauth_client_id", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "slack_oauth_client_secret", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "customer_id", + "type_info": "Varchar" + }, + { + "ordinal": 12, + "name": "plan", + "type_info": "Varchar" + }, + { + "ordinal": 13, + "name": "webhook", + "type_info": "Text" + }, + { + "ordinal": 14, + "name": "ai_config", + "type_info": "Jsonb" + }, + { + "ordinal": 15, + "name": "dbt_warehouses", + "type_info": "Jsonb" + }, + { + "ordinal": 16, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 17, + "name": "datatable", + "type_info": "Jsonb" + }, + { + "ordinal": 18, + "name": "ducklake", + "type_info": "Jsonb" + }, + { + "ordinal": 19, + "name": "git_sync", + "type_info": "Jsonb" + }, + { + "ordinal": 20, + "name": "deploy_ui", + "type_info": "Jsonb" + }, + { + "ordinal": 21, + "name": "default_app", + "type_info": "Varchar" + }, + { + "ordinal": 22, + "name": "default_scripts", + "type_info": "Jsonb" + }, + { + "ordinal": 23, + "name": "mute_critical_alerts", + "type_info": "Bool" + }, + { + "ordinal": 24, + "name": "color", + "type_info": "Varchar" + }, + { + "ordinal": 25, + "name": "operator_settings", + "type_info": "Jsonb" + }, + { + "ordinal": 26, + "name": "git_app_installations", + "type_info": "Jsonb" + }, + { + "ordinal": 27, + "name": "auto_invite", + "type_info": "Jsonb" + }, + { + "ordinal": 28, + "name": "error_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 29, + "name": "success_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 30, + "name": "variable_expiration_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 31, + "name": "public_app_execution_limit_per_minute", + "type_info": "Int4" + }, + { + "ordinal": 32, + "name": "error_handler_fallback_to_instance_alerts", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false + ] + }, + "hash": "74742f785888f280bf1d7e28793150c3ddc2fd4be3b8c682f6faa7b917387593" +} diff --git a/backend/.sqlx/query-77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json b/backend/.sqlx/query-77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json deleted file mode 100644 index f504d7a809..0000000000 --- a/backend/.sqlx/query-77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, teams_command_script, teams_team_id, teams_team_name, git_app_installations, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url FROM workspace_settings WHERE workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "77d599e4f7c574dffac4824f37127c7ae2ef5f27d665ad9018f5cdea0f6f2cb1" -} diff --git a/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json b/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json new file mode 100644 index 0000000000..cb33edacdf --- /dev/null +++ b/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until)\n SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until\n FROM variable\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8" +} diff --git a/backend/.sqlx/query-9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30.json b/backend/.sqlx/query-9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30.json new file mode 100644 index 0000000000..db0e11a62b --- /dev/null +++ b/backend/.sqlx/query-9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable SET expiration_dispatched_for = $3, expiration_notified_at = now()\n WHERE workspace_id = $1 AND path = $2 AND value_valid_until = $3\n AND expiration_dispatched_for IS NOT DISTINCT FROM $4\n AND expiration_notified_at IS NOT DISTINCT FROM $5\n RETURNING 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Timestamptz", + "Timestamptz", + "Timestamptz" + ] + }, + "nullable": [ + null + ] + }, + "hash": "9a3677f9bfc1b5b679578572302129371c7c62e30d77ba6c5e74b575de635b30" +} diff --git a/backend/.sqlx/query-9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6.json b/backend/.sqlx/query-9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6.json new file mode 100644 index 0000000000..ab555a2efd --- /dev/null +++ b/backend/.sqlx/query-9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until)\n VALUES ('test-workspace', 'u/admin/expiring', 'v', false, 'same', '2027-01-01T00:00:00Z')", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "9bbd373847d5cc8e0d84349dbea73af0d18e3b4ce2eb7a20929f8c4c101141b6" +} diff --git a/backend/.sqlx/query-9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6.json b/backend/.sqlx/query-9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6.json new file mode 100644 index 0000000000..ecb5eb2c4b --- /dev/null +++ b/backend/.sqlx/query-9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_handler = NULL WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "9c2b997126090a5bc191f8d7460e14e0f95b81c61241ffd0c9d633e562c4c4f6" +} diff --git a/backend/.sqlx/query-9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894.json b/backend/.sqlx/query-9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894.json new file mode 100644 index 0000000000..6557494459 --- /dev/null +++ b/backend/.sqlx/query-9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "9dabc87e05f72fbd4b586c80d9c7f41c3a72838c5d4c5f795638506084561894" +} diff --git a/backend/.sqlx/query-af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb.json b/backend/.sqlx/query-af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb.json new file mode 100644 index 0000000000..c832fdeeda --- /dev/null +++ b/backend/.sqlx/query-af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb.json @@ -0,0 +1,238 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT\n workspace_id,\n slack_team_id,\n teams_team_id,\n teams_team_name,\n teams_team_guid,\n slack_name,\n slack_command_script,\n teams_command_script,\n slack_email,\n slack_oauth_client_id,\n slack_oauth_client_secret,\n customer_id,\n plan,\n webhook,\n ai_config,\n dbt_warehouses,\n large_file_storage,\n datatable,\n ducklake,\n git_sync,\n deploy_ui,\n default_app,\n default_scripts,\n mute_critical_alerts,\n color,\n operator_settings,\n git_app_installations,\n auto_invite,\n error_handler,\n success_handler,\n variable_expiration_handler,\n public_app_execution_limit_per_minute,\n error_handler_fallback_to_instance_alerts,\n guest_access_enabled,\n guest_jwt_public_key,\n guest_jwt_jwks_url,\n add_admins_and_developers_to_forks\n FROM\n workspace_settings\n WHERE\n workspace_id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "slack_team_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "teams_team_id", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "teams_team_name", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "teams_team_guid", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "slack_name", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "slack_command_script", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "teams_command_script", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "slack_email", + "type_info": "Varchar" + }, + { + "ordinal": 9, + "name": "slack_oauth_client_id", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "slack_oauth_client_secret", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "customer_id", + "type_info": "Varchar" + }, + { + "ordinal": 12, + "name": "plan", + "type_info": "Varchar" + }, + { + "ordinal": 13, + "name": "webhook", + "type_info": "Text" + }, + { + "ordinal": 14, + "name": "ai_config", + "type_info": "Jsonb" + }, + { + "ordinal": 15, + "name": "dbt_warehouses", + "type_info": "Jsonb" + }, + { + "ordinal": 16, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 17, + "name": "datatable", + "type_info": "Jsonb" + }, + { + "ordinal": 18, + "name": "ducklake", + "type_info": "Jsonb" + }, + { + "ordinal": 19, + "name": "git_sync", + "type_info": "Jsonb" + }, + { + "ordinal": 20, + "name": "deploy_ui", + "type_info": "Jsonb" + }, + { + "ordinal": 21, + "name": "default_app", + "type_info": "Varchar" + }, + { + "ordinal": 22, + "name": "default_scripts", + "type_info": "Jsonb" + }, + { + "ordinal": 23, + "name": "mute_critical_alerts", + "type_info": "Bool" + }, + { + "ordinal": 24, + "name": "color", + "type_info": "Varchar" + }, + { + "ordinal": 25, + "name": "operator_settings", + "type_info": "Jsonb" + }, + { + "ordinal": 26, + "name": "git_app_installations", + "type_info": "Jsonb" + }, + { + "ordinal": 27, + "name": "auto_invite", + "type_info": "Jsonb" + }, + { + "ordinal": 28, + "name": "error_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 29, + "name": "success_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 30, + "name": "variable_expiration_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 31, + "name": "public_app_execution_limit_per_minute", + "type_info": "Int4" + }, + { + "ordinal": 32, + "name": "error_handler_fallback_to_instance_alerts", + "type_info": "Bool" + }, + { + "ordinal": 33, + "name": "guest_access_enabled", + "type_info": "Bool" + }, + { + "ordinal": 34, + "name": "guest_jwt_public_key", + "type_info": "Text" + }, + { + "ordinal": 35, + "name": "guest_jwt_jwks_url", + "type_info": "Text" + }, + { + "ordinal": 36, + "name": "add_admins_and_developers_to_forks", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + false, + true, + true, + false + ] + }, + "hash": "af37e5579b729a1aedcd63ab70d189c7e0376ca1f0071ae8360183ed1300d2bb" +} diff --git a/backend/.sqlx/query-b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4.json b/backend/.sqlx/query-b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4.json new file mode 100644 index 0000000000..aee28fd8b6 --- /dev/null +++ b/backend/.sqlx/query-b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable SET value_valid_until = '2029-12-31T00:00:00Z'\n WHERE workspace_id = 'wm-fork-expiry' AND path = 'u/admin/expiring'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "b4e9a0266f4112467f534826c664c928d1e608ddd063d9d5ce3cea8ea62faca4" +} diff --git a/backend/.sqlx/query-cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3.json b/backend/.sqlx/query-cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3.json new file mode 100644 index 0000000000..5abf2efb76 --- /dev/null +++ b/backend/.sqlx/query-cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3.json @@ -0,0 +1,71 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.workspace_id, v.path, v.description, v.value_valid_until AS \"value_valid_until!\",\n v.is_secret, v.expiration_dispatched_for, v.expiration_notified_at,\n ws.variable_expiration_handler->>'path' AS \"handler_path!\",\n (ws.variable_expiration_handler->'extra_args')::text::json\n AS \"extra_args: Json<Box<RawValue>>\"\n FROM variable v\n JOIN workspace_settings ws ON ws.workspace_id = v.workspace_id\n JOIN workspace w ON w.id = v.workspace_id\n WHERE NOT w.deleted\n AND v.value_valid_until IS NOT NULL\n AND (v.value_valid_until IS DISTINCT FROM v.expiration_dispatched_for\n OR (v.value_valid_until > now()\n AND v.expiration_notified_at <= now() - make_interval(secs =>\n NULLIF((ws.variable_expiration_handler->>'remind_every_secs')::bigint, 0) - $2)))\n AND v.value_valid_until <= now() + make_interval(secs =>\n COALESCE((ws.variable_expiration_handler->>'notify_before_secs')::bigint, $1))\n AND ws.variable_expiration_handler->>'path' IS NOT NULL\n AND (NOT COALESCE((ws.variable_expiration_handler->>'muted_on_user_path')::boolean, false)\n OR v.path NOT LIKE 'u/%')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "description", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "value_valid_until!", + "type_info": "Timestamptz" + }, + { + "ordinal": 4, + "name": "is_secret", + "type_info": "Bool" + }, + { + "ordinal": 5, + "name": "expiration_dispatched_for", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "expiration_notified_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 7, + "name": "handler_path!", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "extra_args: Json<Box<RawValue>>", + "type_info": "Json" + } + ], + "parameters": { + "Left": [ + "Int8", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + true, + true, + null, + null + ] + }, + "hash": "cc2dbdc132fe751c7e82445aae5031d05da988837ce41d63a43d13c2018a57d3" +} diff --git a/backend/.sqlx/query-bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c.json b/backend/.sqlx/query-de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256.json similarity index 74% rename from backend/.sqlx/query-bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c.json rename to backend/.sqlx/query-de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256.json index d77682a4ea..e2145fc10a 100644 --- a/backend/.sqlx/query-bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c.json +++ b/backend/.sqlx/query-de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers'", + "query": "SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers' AND name != 'variable_expiration_handler'", "describe": { "columns": [ { @@ -16,5 +16,5 @@ null ] }, - "hash": "bc6ebef9d41aba232f115f95404922c6054df01fa7f38f5d15d6d4af6c726a3c" + "hash": "de0d78bf28a5b6457e5568dce9823a4c216b4be67b68241461b42326d9d65256" } diff --git a/backend/.sqlx/query-e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c.json b/backend/.sqlx/query-e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c.json new file mode 100644 index 0000000000..b3dd32073d --- /dev/null +++ b/backend/.sqlx/query-e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_handler = $1 WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Text" + ] + }, + "nullable": [] + }, + "hash": "e8eaa80631362dee4d696e41abf220cb6f8346d2bfcd901371b480a16a70109c" +} diff --git a/backend/.sqlx/query-eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c.json b/backend/.sqlx/query-eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c.json new file mode 100644 index 0000000000..736b176227 --- /dev/null +++ b/backend/.sqlx/query-eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_failed_at = now()\n WHERE workspace_id = $1 AND variable_expiration_failed_at IS NULL\n RETURNING 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "eac25b9ce5df40a896687d2ba3f9279396ed7213da4598034332bb0ba6ce271c" +} diff --git a/backend/.sqlx/query-eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079.json b/backend/.sqlx/query-eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079.json new file mode 100644 index 0000000000..f0ced3e76b --- /dev/null +++ b/backend/.sqlx/query-eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET variable_expiration_failed_at = NULL\n WHERE variable_expiration_failed_at IS NOT NULL AND variable_expiration_handler IS NULL\n RETURNING workspace_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false + ] + }, + "hash": "eacce0ccde20eddc4aded69c35d62122478424a36193254d5e00b8723ca28079" +} diff --git a/backend/.sqlx/query-ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c.json b/backend/.sqlx/query-ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c.json new file mode 100644 index 0000000000..d101f5ec0a --- /dev/null +++ b/backend/.sqlx/query-ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_diff\n (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes)\n VALUES ('test-workspace', 'wm-fork-expiry', 'u/admin/expiring', 'variable', 0, 1, NULL)", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "ee8b92d51f220cac5a32f0edcb3c4effa302380d4b434d8c74677bfbf895333c" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 20006c2a99..d961a68842 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -5517ff637a675aee66d4e417d3f37266045f0e0c +b6e23d229966cf0019c0a1926a254fda658d8def diff --git a/backend/migrations/20260824180615_variable_value_valid_until.down.sql b/backend/migrations/20260824180615_variable_value_valid_until.down.sql new file mode 100644 index 0000000000..963fd00f8e --- /dev/null +++ b/backend/migrations/20260824180615_variable_value_valid_until.down.sql @@ -0,0 +1,9 @@ +ALTER TABLE variable DROP CONSTRAINT IF EXISTS variable_oauth_no_value_expiry; +DROP INDEX IF EXISTS idx_variable_expiration_due; + +COMMENT ON COLUMN variable.expires_at IS NULL; + +ALTER TABLE variable + DROP COLUMN IF EXISTS value_valid_until, + DROP COLUMN IF EXISTS expiration_dispatched_for, + DROP COLUMN IF EXISTS expiration_notified_at; diff --git a/backend/migrations/20260824180615_variable_value_valid_until.up.sql b/backend/migrations/20260824180615_variable_value_valid_until.up.sql new file mode 100644 index 0000000000..308394d7e0 --- /dev/null +++ b/backend/migrations/20260824180615_variable_value_valid_until.up.sql @@ -0,0 +1,30 @@ +-- `value_valid_until` is when the value stored in the variable stops working; the row itself +-- lives on. `expires_at` keeps its unrelated meaning — delete the row — so no existing writer +-- changes meaning under a rolling deploy and no data is rewritten here. +ALTER TABLE variable ADD COLUMN IF NOT EXISTS value_valid_until TIMESTAMP WITH TIME ZONE; + +COMMENT ON COLUMN variable.expires_at IS + 'Garbage collection deadline: the row is deleted once passed. Set by the ephemeral secret_arg mint. Not the value''s expiry — see value_valid_until.'; +COMMENT ON COLUMN variable.value_valid_until IS + 'When the value stops working. Drives the workspace variable expiration handler; never deletes the row.'; + +-- Holds the `value_valid_until` that was dispatched, rather than a plain "was dispatched" flag, +-- so that moving the date re-arms the handler by construction — no writer has to remember to +-- clear anything. +ALTER TABLE variable + ADD COLUMN IF NOT EXISTS expiration_dispatched_for TIMESTAMP WITH TIME ZONE; + +-- When the handler last ran for this variable, which paces its reminders. +ALTER TABLE variable + ADD COLUMN IF NOT EXISTS expiration_notified_at TIMESTAMP WITH TIME ZONE; + +-- Serves the sweep's due predicate. Partial so it stays the size of the opted-in set rather +-- than the whole variable table. Not partial on `expiration_dispatched_for`: reminders keep a +-- dispatched variable due until it expires. +CREATE INDEX IF NOT EXISTS idx_variable_expiration_due ON variable (value_valid_until) + WHERE value_valid_until IS NOT NULL; + +-- An OAuth-linked value is refreshed by Windmill itself, so a rotation date on it would only +-- announce an expiry that never comes. +ALTER TABLE variable ADD CONSTRAINT variable_oauth_no_value_expiry + CHECK (account IS NULL OR value_valid_until IS NULL); diff --git a/backend/migrations/20260824180616_workspace_variable_expiration_handler.down.sql b/backend/migrations/20260824180616_workspace_variable_expiration_handler.down.sql new file mode 100644 index 0000000000..92c048bd52 --- /dev/null +++ b/backend/migrations/20260824180616_workspace_variable_expiration_handler.down.sql @@ -0,0 +1,3 @@ +ALTER TABLE workspace_settings + DROP COLUMN IF EXISTS variable_expiration_handler, + DROP COLUMN IF EXISTS variable_expiration_failed_at; diff --git a/backend/migrations/20260824180616_workspace_variable_expiration_handler.up.sql b/backend/migrations/20260824180616_workspace_variable_expiration_handler.up.sql new file mode 100644 index 0000000000..8e6cb03938 --- /dev/null +++ b/backend/migrations/20260824180616_workspace_variable_expiration_handler.up.sql @@ -0,0 +1,6 @@ +-- Shape mirrors `error_handler` / `success_handler` as grouped by 20260124172000: +-- {"path": ..., "extra_args": ..., "muted_on_user_path": ...} +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS variable_expiration_handler JSONB; + +-- When the handler last failed to start; the sweep skips the workspace for a while after it. +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS variable_expiration_failed_at TIMESTAMP WITH TIME ZONE; diff --git a/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.down.sql b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.down.sql new file mode 100644 index 0000000000..40443fc999 --- /dev/null +++ b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.down.sql @@ -0,0 +1 @@ +UPDATE folder SET extra_perms = extra_perms - 'g/variable_expiration_handler' WHERE name = 'slack_bot'; diff --git a/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.up.sql b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.up.sql new file mode 100644 index 0000000000..25adde9d36 --- /dev/null +++ b/backend/migrations/20260903161430_variable_expiration_handler_slack_perms.up.sql @@ -0,0 +1,7 @@ +-- Windmill never created this group before this release, so one present now was made by a user, +-- who would otherwise keep it as it gains read on the Slack bot token below. +DELETE FROM usr_to_group WHERE group_ = 'variable_expiration_handler'; +UPDATE group_ SET extra_perms = '{}'::jsonb WHERE name = 'variable_expiration_handler'; + +-- Backfill for slack_bot folders created before this grant (see create_slack_workspace_artifacts). +UPDATE folder SET extra_perms = JSONB_SET(extra_perms, '{g/variable_expiration_handler}', 'false', true) WHERE name = 'slack_bot'; diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index fbadfa4269..868e558f8d 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -129,6 +129,7 @@ use windmill_object_store::reload_object_store_setting; use windmill_queue::{ add_completed_job_error, cancel_job, canceled_result, get_queued_job_v2, schedule::{find_unarmed_schedules, rearm_schedule, RearmOutcome}, + variable_expiration::dispatch_expiring_variables, CanceledBy, MiniCompletedJob, SameWorkerPayload, }; use windmill_store::resources::MAX_RESOURCE_VERSIONS; @@ -4411,6 +4412,15 @@ pub async fn monitor_db( } }; + // Run every 5 minutes (10 iterations * 30s) + let dispatch_expiring_variables_f = async { + if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(10) { + if let Some(db) = conn.as_sql() { + dispatch_expiring_variables(&db).await; + } + } + }; + // run every hour (120 iterations * 30s = 3600s) let cleanup_stale_server_heartbeats_f = async { if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(120) { @@ -4617,6 +4627,7 @@ pub async fn monitor_db( native_triggers_sync_f, cleanup_notify_events_f, check_expiring_tokens_f, + dispatch_expiring_variables_f, cleanup_stale_server_heartbeats_f, manage_audit_partitions_f, export_audit_logs_to_object_store_f, diff --git a/backend/summarized_schema.txt b/backend/summarized_schema.txt index 2bf6b0188f..418108cd30 100644 --- a/backend/summarized_schema.txt +++ b/backend/summarized_schema.txt @@ -220,7 +220,7 @@ v2_job_runtime: id(uuid), ping(ts), memory_peak(int) FK: (id) -> v2_job_queue(id) v2_job_status: id(uuid), flow_status(jsonb), flow_leaf_jobs(jsonb), workflow_as_code_status(jsonb) FK: (id) -> v2_job_queue(id) -variable: workspace_id(char), path(char), value(char), is_secret(bool), description(char), extra_perms(jsonb), account(int), is_oauth(bool), expires_at(ts), labels(text[]) +variable: workspace_id(char), path(char), value(char), is_secret(bool), description(char), extra_perms(jsonb), account(int), is_oauth(bool), expires_at(ts), labels(text[]), value_valid_until(timestamptz), expiration_dispatched_for(timestamptz), expiration_notified_at(timestamptz) FK: (workspace_id) -> workspace(id) websocket_trigger: path(char), url(char), script_path(char), is_flow(bool), workspace_id(char), edited_by(char), email(char), edited_at(ts), extra_perms(jsonb), server_id(char), last_server_ping(ts), error(text), filters(jsonb[]), initial_messages(jsonb[]), url_runnable_args(jsonb), can_return_message(bool), error_handler_path(char), error_handler_args(jsonb), retry(jsonb), can_return_error_result(bool), mode(trigger_mode), labels(text[]) windmill_migrations: name(text), created_at(ts) @@ -244,7 +244,7 @@ workspace_protection_rule: workspace_id(char), name(char), rules(int), bypass_gr FK: (workspace_id) -> workspace(id) workspace_runnable_dependencies: flow_path(char), runnable_path(char), script_hash(bigint), runnable_is_flow(bool), workspace_id(char), app_path(char), id(bigint), runnable_is_agent(bool) FK: (app_path, workspace_id) -> app(path, workspace_id) | (flow_path, workspace_id) -> flow(path, workspace_id) -workspace_settings: workspace_id(char), slack_team_id(char), slack_name(char), slack_command_script(char), slack_email(char), customer_id(char), plan(char), webhook(text), ai_config(jsonb), large_file_storage(jsonb), git_sync(jsonb), default_app(char), default_scripts(jsonb), deploy_ui(jsonb), mute_critical_alerts(bool), color(char), operator_settings(jsonb), teams_command_script(text), teams_team_id(text), teams_team_name(text), git_app_installations(jsonb), ducklake(jsonb), slack_oauth_client_id(char), slack_oauth_client_secret(char), datatable(jsonb), teams_team_guid(text), auto_invite(jsonb), error_handler(jsonb), success_handler(jsonb), public_app_execution_limit_per_minute(int), dbt_warehouses(jsonb), guest_access_enabled(bool), guest_jwt_public_key(text), guest_jwt_jwks_url(text), ai_sessions_backup_generation(int), add_admins_and_developers_to_forks(bool), remote_deploy_target(jsonb), remote_deploy_target_changed_at(ts) +workspace_settings: workspace_id(char), slack_team_id(char), slack_name(char), slack_command_script(char), slack_email(char), customer_id(char), plan(char), webhook(text), ai_config(jsonb), large_file_storage(jsonb), git_sync(jsonb), default_app(char), default_scripts(jsonb), deploy_ui(jsonb), mute_critical_alerts(bool), color(char), operator_settings(jsonb), teams_command_script(text), teams_team_id(text), teams_team_name(text), git_app_installations(jsonb), ducklake(jsonb), slack_oauth_client_id(char), slack_oauth_client_secret(char), datatable(jsonb), teams_team_guid(text), auto_invite(jsonb), error_handler(jsonb), success_handler(jsonb), public_app_execution_limit_per_minute(int), dbt_warehouses(jsonb), guest_access_enabled(bool), guest_jwt_public_key(text), guest_jwt_jwks_url(text), ai_sessions_backup_generation(int), add_admins_and_developers_to_forks(bool), remote_deploy_target(jsonb), remote_deploy_target_changed_at(ts), variable_expiration_handler(jsonb), variable_expiration_failed_at(ts) FK: (workspace_id) -> workspace(id) zombie_job_counter: job_id(uuid), counter(int) FK: (job_id) -> v2_job(id) diff --git a/backend/tests/variable_expiration.rs b/backend/tests/variable_expiration.rs new file mode 100644 index 0000000000..94a4ed3f78 --- /dev/null +++ b/backend/tests/variable_expiration.rs @@ -0,0 +1,534 @@ +//! Tests for the variable expiration sweep. No worker: the sweep ends at the push, and the +//! queued job is what the tests assert on. + +use sqlx::{Pool, Postgres}; +use windmill_queue::variable_expiration::dispatch_expiring_variables; +use windmill_test_utils::{initialize_tracing, ApiServer}; + +const WS: &str = "test-workspace"; + +async fn configure_handler(db: &Pool<Postgres>, handler: &str) -> anyhow::Result<()> { + sqlx::query("UPDATE workspace_settings SET variable_expiration_handler = $2::jsonb WHERE workspace_id = $1") + .bind(WS) + .bind(handler) + .execute(db) + .await?; + Ok(()) +} + +/// Seed a deployed script the handler setting can point at. +async fn seed_handler_script(db: &Pool<Postgres>, path: &str) -> anyhow::Result<()> { + sqlx::query( + r#"INSERT INTO script (workspace_id, hash, path, summary, description, content, created_by, language, lock) + VALUES ($1, $2, $3, '', '', 'export function main() {}', 'test-user', 'bun', '')"#, + ) + .bind(WS) + .bind(path.bytes().fold(0i64, |h, b| h.wrapping_mul(31).wrapping_add(b as i64))) + .bind(path) + .execute(db) + .await?; + Ok(()) +} + +async fn seed_variable(db: &Pool<Postgres>, path: &str, expires_in: &str) -> anyhow::Result<()> { + sqlx::query(&format!( + r#"INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until) + VALUES ($1, $2, 'MUST_NOT_LEAK', true, 'a credential', now() + interval '{expires_in}')"# + )) + .bind(WS) + .bind(path) + .execute(db) + .await?; + Ok(()) +} + +async fn queued_handler_jobs(db: &Pool<Postgres>, path: &str) -> anyhow::Result<i64> { + Ok( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM v2_job WHERE runnable_path = $1") + .bind(path) + .fetch_one(db) + .await?, + ) +} + +/// The sweep dispatches inside the handler's `notify_before_secs`, leaves everything outside it +/// alone, and does not fire twice for the same expiry. +#[sqlx::test(fixtures("base"))] +async fn test_dispatch_within_lead_time_once(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "notify_before_secs": 3600}"#, + ) + .await?; + + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + seed_variable(&db, "u/test-user/far", "2 hours").await?; + + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "exactly the variable inside the lead window should dispatch" + ); + + // Admins grant this group access to the secrets it rotates, so the job must run as it. + let (path, is_secret, permissioned_as, permissioned_as_email): (String, bool, String, String) = + sqlx::query_as( + "SELECT args->>'variable_path', (args->>'is_secret')::boolean, permissioned_as, + permissioned_as_email FROM v2_job WHERE runnable_path = $1", + ) + .bind("u/test-user/expiry_handler") + .fetch_one(&db) + .await?; + assert_eq!(path, "u/test-user/due"); + assert!(is_secret); + assert_eq!(permissioned_as, "g/variable_expiration_handler"); + assert_eq!( + permissioned_as_email, + "variable_expiration_handler@windmill.dev" + ); + + let args: String = sqlx::query_scalar("SELECT args::text FROM v2_job WHERE runnable_path = $1") + .bind("u/test-user/expiry_handler") + .fetch_one(&db) + .await?; + assert!( + !args.contains("MUST_NOT_LEAK"), + "handler args leaked the value: {args}" + ); + + // The claim is what makes concurrent replicas safe. + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "a dispatched variable must not fire again" + ); + + Ok(()) +} + +/// A variable's writer must not get the handler to resolve a reference as its own identity; +/// the admin's `extra_args` still resolve. +#[sqlx::test(fixtures("base"))] +async fn test_variable_fields_do_not_resolve_in_handler(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "extra_args": {"slack": "$res:f/slack_bot/bot_token"}}"#, + ) + .await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + sqlx::query( + "UPDATE variable SET description = '$var:u/test-user/other' WHERE path = 'u/test-user/due'", + ) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + + let (description, slack): (String, String) = sqlx::query_as( + "SELECT args->>'description', args->>'slack' FROM v2_job WHERE runnable_path = $1", + ) + .bind("u/test-user/expiry_handler") + .fetch_one(&db) + .await?; + assert!( + !description.starts_with("$var:"), + "description still resolves: {description}" + ); + assert_eq!(slack, "$res:f/slack_bot/bot_token"); + Ok(()) +} + +/// `remind_every_secs` runs the handler again once the interval has elapsed, and not before. +#[sqlx::test(fixtures("base"))] +async fn test_remind_every_repeats_the_notice(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "remind_every_secs": 600}"#, + ) + .await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + + dispatch_expiring_variables(&db).await; + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "no reminder before the interval has elapsed" + ); + + // A sweep landing a few seconds short of the interval must still remind. + sqlx::query( + "UPDATE variable SET expiration_notified_at = now() - interval '9 minutes 50 seconds'", + ) + .execute(&db) + .await?; + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2 + ); + + sqlx::query( + "UPDATE variable SET value_valid_until = now() - interval '1 minute', + expiration_dispatched_for = now() - interval '1 minute', + expiration_notified_at = now() - interval '11 minutes'", + ) + .execute(&db) + .await?; + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2 + ); + Ok(()) +} + +/// Moving `value_valid_until` re-arms the variable; re-writing the same date does not. +#[sqlx::test(fixtures("base"))] +async fn test_rearm_on_date_change(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}", server.addr.port()); + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler(&db, r#"{"path": "script/u/test-user/expiry_handler"}"#).await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + + // Through the real endpoint: writing the column directly would assert nothing. + let update = async |body: serde_json::Value| -> anyhow::Result<u16> { + Ok(reqwest::Client::new() + .post(format!( + "{base_url}/api/w/{WS}/variables/update/u/test-user/due" + )) + .bearer_auth("SECRET_TOKEN") + .json(&body) + .send() + .await? + .status() + .as_u16()) + }; + + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1 + ); + + let stored: chrono::DateTime<chrono::Utc> = sqlx::query_scalar( + "SELECT value_valid_until FROM variable WHERE workspace_id = $1 AND path = $2", + ) + .bind(WS) + .bind("u/test-user/due") + .fetch_one(&db) + .await?; + + // An unchanged `wmill sync push` rewrites the same date. + assert_eq!( + update(serde_json::json!({ "value_valid_until": stored })).await?, + 200 + ); + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "an unchanged expiry must not re-arm" + ); + + assert_eq!( + update(serde_json::json!({ "description": "touched" })).await?, + 200 + ); + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 1, + "an update that omits value_valid_until must not re-arm" + ); + + assert_eq!( + update(serde_json::json!({ "value_valid_until": stored + chrono::Duration::minutes(5) })) + .await?, + 200 + ); + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2, + "a moved expiry must re-arm the handler" + ); + + Ok(()) +} + +/// `muted_on_user_path` keeps personal-path variables out. +#[sqlx::test(fixtures("base"))] +async fn test_muted_user_paths(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + seed_variable(&db, "u/test-user/personal", "30 minutes").await?; + seed_variable(&db, "f/test_folder/shared", "30 minutes").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "muted_on_user_path": true}"#, + ) + .await?; + dispatch_expiring_variables(&db).await; + + let dispatched: Vec<String> = + sqlx::query_scalar("SELECT args->>'variable_path' FROM v2_job WHERE runnable_path = $1") + .bind("u/test-user/expiry_handler") + .fetch_all(&db) + .await?; + assert_eq!( + dispatched, + vec!["f/test_folder/shared".to_string()], + "a muted personal path must not dispatch" + ); + + Ok(()) +} + +/// Broken workspaces' due rows must not hold back anyone else's first notice or reminder: every +/// due row is tried each pass, and a broken handler only once per pass. The broken rows go in +/// first, so a cap on the pass would cut off the working workspace. +#[sqlx::test(fixtures("base"))] +async fn test_broken_handlers_do_not_hold_back_others(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#"INSERT INTO workspace (id, name, owner) SELECT 'broken-' || i, 'broken-' || i, 'test-user' FROM generate_series(1, 100) i; + INSERT INTO workspace_key (workspace_id, kind, key) SELECT 'broken-' || i, 'cloud', 'k' FROM generate_series(1, 100) i; + INSERT INTO workspace_settings (workspace_id, variable_expiration_handler) + SELECT 'broken-' || i, '{"path": "script/u/test-user/does_not_exist"}'::jsonb FROM generate_series(1, 100) i; + INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until) + SELECT 'broken-' || i, 'f/creds/v' || j, 'v', false, '', now() - interval '1 day' + FROM generate_series(1, 100) i, generate_series(1, 2) j;"#, + ) + .execute(&db) + .await?; + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + configure_handler( + &db, + r#"{"path": "script/u/test-user/expiry_handler", "remind_every_secs": 60}"#, + ) + .await?; + seed_variable(&db, "u/test-user/fresh", "30 minutes").await?; + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until, + expiration_dispatched_for, expiration_notified_at) + VALUES ($1, 'u/test-user/reminded', 'v', false, '', now() + interval '10 minutes', + now() + interval '10 minutes', now() - interval '2 minutes')", + ) + .bind(WS) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/expiry_handler").await?, + 2, + "the first notice and the reminder must both go out" + ); + assert_eq!( + queued_handler_jobs(&db, "u/test-user/does_not_exist").await?, + 0 + ); + Ok(()) +} + +/// A broken handler alerts once, however many passes it fails, runs on the first pass after +/// it is deployed, and that resolves its alert. +#[sqlx::test(fixtures("base"))] +async fn test_deploying_the_handler_ends_the_failure(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + configure_handler(&db, r#"{"path": "script/u/test-user/redeployed_handler"}"#).await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + let alerts = || async { + Ok::<_, anyhow::Error>(sqlx::query_as::<_, (i64, i64)>( + "SELECT count(*), count(*) FILTER (WHERE NOT acknowledged) FROM alerts + WHERE alert_type = 'critical_error' AND resource = 'variable_expiration_handler:test-workspace'", + ) + .fetch_one(&db) + .await?) + }; + + dispatch_expiring_variables(&db).await; + dispatch_expiring_variables(&db).await; + assert_eq!( + alerts().await?, + (1, 1), + "one alert per failure, not per pass" + ); + + seed_handler_script(&db, "u/test-user/redeployed_handler").await?; + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/redeployed_handler").await?, + 1, + "the deployed handler did not run on the next pass" + ); + assert_eq!(alerts().await?, (1, 0), "starting again resolves the alert"); + Ok(()) +} + +/// A handler script still waiting on its dependency job runs on the first pass after its lock +/// lands, though nothing about the script changes but the lock. +#[sqlx::test(fixtures("base"))] +async fn test_handler_runs_once_its_lock_lands(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + configure_handler( + &db, + r#"{"path": "script/u/test-user/pending_lock_handler"}"#, + ) + .await?; + seed_variable(&db, "u/test-user/due", "30 minutes").await?; + seed_handler_script(&db, "u/test-user/pending_lock_handler").await?; + sqlx::query("UPDATE script SET lock = NULL WHERE workspace_id = $1") + .bind(WS) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + assert_eq!( + queued_handler_jobs(&db, "u/test-user/pending_lock_handler").await?, + 0 + ); + sqlx::query("UPDATE script SET lock = '' WHERE workspace_id = $1") + .bind(WS) + .execute(&db) + .await?; + dispatch_expiring_variables(&db).await; + + assert_eq!( + queued_handler_jobs(&db, "u/test-user/pending_lock_handler").await?, + 1, + "the handler did not run once its lock landed" + ); + Ok(()) +} + +/// A removed handler has nothing left to retry, so the next pass ends its failure and resolves +/// its alert. +#[sqlx::test(fixtures("base"))] +async fn test_removing_a_failing_handler_resolves_its_alert( + db: Pool<Postgres>, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::query( + "UPDATE workspace_settings SET variable_expiration_handler = NULL, + variable_expiration_failed_at = now() WHERE workspace_id = $1", + ) + .bind(WS) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO alerts (alert_type, message, acknowledged, acknowledged_workspace, workspace_id, resource) + VALUES ('critical_error', 'failed', false, false, $1, 'variable_expiration_handler:' || $1)", + ) + .bind(WS) + .execute(&db) + .await?; + + dispatch_expiring_variables(&db).await; + + let (failing, open_alerts): (bool, i64) = sqlx::query_as( + "SELECT ws.variable_expiration_failed_at IS NOT NULL, + (SELECT count(*) FROM alerts WHERE alert_type = 'critical_error' AND NOT acknowledged + AND workspace_id = $1) + FROM workspace_settings ws WHERE ws.workspace_id = $1", + ) + .bind(WS) + .fetch_one(&db) + .await?; + assert!(!failing, "the removed handler's failure must end"); + assert_eq!( + open_alerts, 0, + "the removed handler's alert must be resolved" + ); + Ok(()) +} + +/// The handler endpoint: admin-only, existence-checked, and clearing by omission, which +/// `wmill sync push` relies on to propagate an absent handler. +#[sqlx::test(fixtures("base"))] +async fn test_edit_handler_endpoint(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}", server.addr.port()); + + let edit = async |token: &str, body: serde_json::Value| -> anyhow::Result<u16> { + Ok(reqwest::Client::new() + .post(format!( + "{base_url}/api/w/{WS}/workspaces/edit_variable_expiration_handler" + )) + .bearer_auth(token) + .json(&body) + .send() + .await? + .status() + .as_u16()) + }; + let stored = async || -> anyhow::Result<Option<serde_json::Value>> { + Ok(sqlx::query_scalar( + "SELECT variable_expiration_handler FROM workspace_settings WHERE workspace_id = $1", + ) + .bind(WS) + .fetch_one(&db) + .await?) + }; + + seed_handler_script(&db, "u/test-user/expiry_handler").await?; + let handler = serde_json::json!({ "path": "script/u/test-user/expiry_handler" }); + assert_eq!(edit("SECRET_TOKEN_2", handler.clone()).await?, 403); + assert!(stored().await?.is_none()); + + for path in [ + "u/test-user/expiry_handler", + "script/u/test-user/does_not_exist", + ] { + assert_eq!( + edit("SECRET_TOKEN", serde_json::json!({ "path": path })).await?, + 400, + "{path}" + ); + } + + // A recorded failure is the sweep's to end, so the endpoint leaves it alone either way. + sqlx::query("UPDATE workspace_settings SET variable_expiration_failed_at = now() WHERE workspace_id = $1") + .bind(WS) + .execute(&db) + .await?; + let failing = || async { + Ok::<_, anyhow::Error>(sqlx::query_scalar::<_, bool>( + "SELECT variable_expiration_failed_at IS NOT NULL FROM workspace_settings WHERE workspace_id = $1", + ) + .bind(WS) + .fetch_one(&db) + .await?) + }; + assert_eq!(edit("SECRET_TOKEN", handler).await?, 200); + assert_eq!( + stored() + .await? + .and_then(|h| h["path"].as_str().map(String::from)), + Some("script/u/test-user/expiry_handler".to_string()) + ); + assert!(failing().await?, "saving the handler must keep its failure"); + + assert_eq!(edit("SECRET_TOKEN", serde_json::json!({})).await?, 200); + assert!( + stored().await?.is_none(), + "an omitted path clears the handler" + ); + + Ok(()) +} diff --git a/backend/tests/workspace_export.rs b/backend/tests/workspace_export.rs index 5894ca8394..792d41b487 100644 --- a/backend/tests/workspace_export.rs +++ b/backend/tests/workspace_export.rs @@ -288,6 +288,48 @@ async fn test_tarball_export_gates_values_on_item_scopes(db: Pool<Postgres>) -> Ok(()) } +/// The tarball drops variables by `expires_at`, never `value_valid_until`, and the exported +/// entry carries the date, or a pull/push round-trip clears it. +#[sqlx::test(fixtures("base"))] +async fn test_tarball_export_excludes_only_gc_variables(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}", server.addr.port()); + + sqlx::query( + r#"INSERT INTO variable (workspace_id, path, value, is_secret, description, expires_at, value_valid_until) + VALUES ('test-workspace', 'u/test-user/expiring', 'v', false, '', NULL, '2030-01-15T08:00:00Z'), + ('test-workspace', 'u/test-user/ephemeral', 'v', false, '', now() + interval '7 days', NULL)"#, + ) + .execute(&db) + .await?; + + let resp = reqwest::Client::new() + .get(format!( + "{base_url}/api/w/test-workspace/workspaces/tarball" + )) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(resp.status().as_u16(), 200); + let body = String::from_utf8_lossy(&resp.bytes().await?).into_owned(); + + assert!( + body.contains("u/test-user/expiring.variable.json"), + "a variable with an expiry must still reach git sync" + ); + assert!( + body.contains("2030-01-15T08:00:00Z"), + "the exported entry must carry the expiry back" + ); + assert!( + !body.contains("u/test-user/ephemeral.variable.json"), + "a variable awaiting garbage collection must stay out of the export" + ); + + Ok(()) +} + /// `settings.json` carries the admin-managed integration config that `get_settings` /// is admin-only for (the webhook URL, ai_config, git_sync, handler extra_args), so /// `include_settings` takes the same admin check as `get_settings` rather than diff --git a/backend/windmill-api-groups/src/groups.rs b/backend/windmill-api-groups/src/groups.rs index 860e486a75..0d3b5e360d 100644 --- a/backend/windmill-api-groups/src/groups.rs +++ b/backend/windmill-api-groups/src/groups.rs @@ -218,12 +218,13 @@ pub async fn require_is_owner( } async fn _check_nb_of_groups(db: &DB) -> Result<()> { - let nb_groups = sqlx::query_scalar!("SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers'",) + // Groups that back workspace settings do not count toward the limit. + let nb_groups = sqlx::query_scalar!("SELECT COUNT(*) FROM group_ WHERE name != 'all' AND name != 'error_handler' AND name != 'slack' AND name != 'wm_deployers' AND name != 'variable_expiration_handler'",) .fetch_one(db) .await?; if nb_groups.unwrap_or(0) >= 3 { return Err(Error::BadRequest( - "You have reached the maximum number of groups (3 outside of native groups 'all', 'slack', 'error_handler' and 'wm_deployers') without an enterprise license" + "You have reached the maximum number of groups (3 outside of native groups 'all', 'slack', 'error_handler', 'wm_deployers' and 'variable_expiration_handler') without an enterprise license" .to_string(), )); } diff --git a/backend/windmill-api-integration-tests/tests/variables.rs b/backend/windmill-api-integration-tests/tests/variables.rs index 7332383936..adb9f29c36 100644 --- a/backend/windmill-api-integration-tests/tests/variables.rs +++ b/backend/windmill-api-integration-tests/tests/variables.rs @@ -339,6 +339,74 @@ async fn test_variables_are_cached(db: Pool<Postgres>) -> anyhow::Result<()> { Ok(()) } +/// A draft-only row is built field by field, so a forgotten field is dropped silently. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_draft_only_row_carries_value_valid_until(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/drafts/update/variable/u/test-user/draft_var" + ))) + .json(&json!({ + "value": { + "path": "u/test-user/draft_var", + "variable": { "value": "x", "is_secret": true, "description": "" }, + "wsSpecific": false, + "value_valid_until": "2027-03-15T08:00:00Z" + } + })) + .send() + .await?; + + let resp = authed(client().get(format!( + "http://localhost:{port}/api/w/test-workspace/variables/list?include_draft_only=true" + ))) + .send() + .await?; + assert_eq!(resp.status(), 200); + let rows = resp.json::<Vec<serde_json::Value>>().await?; + + let row = rows + .iter() + .find(|v| v["path"] == "u/test-user/draft_var") + .expect("draft-only row is listed"); + assert_eq!(row["draft_only"], true); + assert_eq!(row["value_valid_until"], "2027-03-15T08:00:00Z"); + + Ok(()) +} + +/// An expiry on an OAuth-linked variable is refused with a readable error, not a raw +/// constraint violation. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_oauth_variable_refuses_value_expiry(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::query( + "WITH a AS (INSERT INTO account (workspace_id, expires_at, refresh_token, client) + VALUES ('test-workspace', now() + interval '1 hour', 'r', 'github') RETURNING id) + INSERT INTO variable (workspace_id, path, value, is_secret, description, account, is_oauth) + SELECT 'test-workspace', 'u/test-user/oauth_var', 't', false, '', id, true FROM a", + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/variables/update/u/test-user/oauth_var" + ))) + .json(&json!({ "value_valid_until": "2027-03-15T08:00:00Z" })) + .send() + .await?; + assert_eq!(resp.status(), 400); + assert!(resp.text().await?.contains("OAuth")); + + Ok(()) +} + /// Reading a variable linked to an OAuth account refreshes through it and returns the fresh token, /// so the variable endpoints must not let a caller choose the link. #[sqlx::test(migrations = "../migrations", fixtures("base"))] diff --git a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs index bef3b5dd78..830a29e8c2 100644 --- a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs +++ b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs @@ -2770,3 +2770,83 @@ async fn test_compare_secret_variables_by_value(db: Pool<Postgres>) -> anyhow::R Ok(()) } + +/// `compare_two_variables` hand-lists its columns, so a forgotten one hides that difference +/// from the fork diff, and it can never be promoted. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_compare_variables_detects_value_valid_until(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base_url = format!("http://localhost:{port}/api"); + let admin = windmill_api_client::create_client( + &format!("http://localhost:{port}"), + "SECRET_TOKEN".to_string(), + ); + + sqlx::query!( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, value_valid_until) + VALUES ('test-workspace', 'u/admin/expiring', 'v', false, 'same', '2027-01-01T00:00:00Z')" + ) + .execute(&db) + .await?; + + let resp = admin + .client() + .post(&format!( + "{base_url}/w/test-workspace/workspaces/create_fork" + )) + .json(&json!({ "id": "wm-fork-expiry", "name": "Expiry Fork" })) + .send() + .await?; + assert!( + resp.status().is_success(), + "fork creation failed: {}", + resp.status() + ); + + // Before the UPDATE below overwrites it: the fork must inherit the date from the source. + let inherited: Option<String> = sqlx::query_scalar( + "SELECT to_char(value_valid_until, 'YYYY-MM-DD') FROM variable + WHERE workspace_id = 'wm-fork-expiry' AND path = 'u/admin/expiring'", + ) + .fetch_one(&db) + .await?; + assert_eq!(inherited.as_deref(), Some("2027-01-01")); + + // Only the expiry differs. + sqlx::query!( + "UPDATE variable SET value_valid_until = '2029-12-31T00:00:00Z' + WHERE workspace_id = 'wm-fork-expiry' AND path = 'u/admin/expiring'" + ) + .execute(&db) + .await?; + + // Forces the endpoint to re-evaluate the pair rather than trust a cached verdict. + sqlx::query!( + "INSERT INTO workspace_diff + (source_workspace_id, fork_workspace_id, path, kind, ahead, behind, has_changes) + VALUES ('test-workspace', 'wm-fork-expiry', 'u/admin/expiring', 'variable', 0, 1, NULL)" + ) + .execute(&db) + .await?; + + let comparison = admin + .client() + .get(&format!( + "{base_url}/w/test-workspace/workspaces/compare/wm-fork-expiry" + )) + .send() + .await? + .json::<serde_json::Value>() + .await?; + + assert_eq!( + comparison["summary"]["variables_changed"].as_u64(), + Some(1), + "an expiry-only change must show as deployable: {comparison}" + ); + + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 4184af9779..0534f3e7ee 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -127,6 +127,10 @@ pub fn workspaced_service() -> Router { .route("/billable_seats", get(get_billable_seats)) .route("/edit_error_handler", post(edit_error_handler)) .route("/edit_success_handler", post(edit_success_handler)) + .route( + "/edit_variable_expiration_handler", + post(edit_variable_expiration_handler), + ) .route( "/edit_large_file_storage_config", post(edit_large_file_storage_config), @@ -342,6 +346,8 @@ pub struct WorkspaceSettings { #[serde(skip_serializing_if = "Option::is_none")] pub success_handler: Option<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] + pub variable_expiration_handler: Option<serde_json::Value>, + #[serde(skip_serializing_if = "Option::is_none")] pub public_app_execution_limit_per_minute: Option<i32>, pub error_handler_fallback_to_instance_alerts: bool, /// Whether this workspace admits guest sessions (`ExecutionMode::Guest`). An app's @@ -1203,6 +1209,7 @@ async fn get_settings( auto_invite, error_handler, success_handler, + variable_expiration_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, @@ -6253,6 +6260,157 @@ async fn edit_error_handler( Ok(format!("Edit error_handler for workspace {}", &w_id)) } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EditVariableExpirationHandler { + pub path: Option<String>, + pub extra_args: Option<serde_json::Value>, + #[serde(default)] + pub muted_on_user_path: bool, + pub notify_before_secs: Option<u32>, + pub remind_every_secs: Option<u32>, +} + +async fn edit_variable_expiration_handler( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Path(w_id): Path<String>, + Json(es): Json<EditVariableExpirationHandler>, +) -> Result<String> { + require_admin(authed.is_admin, &authed.username)?; + + let mut tx = db.begin().await?; + + // Created with no access: an admin grants it write access to each variable it rotates. + sqlx::query_as!( + Group, + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING", + w_id, + "variable_expiration_handler", + "The group the variable expiration handler acts on behalf of", + serde_json::json!({username_to_permissioned_as(&authed.username): true}) + ) + .execute(&mut *tx) + .await?; + + if let Some(path) = &es.path { + if es + .extra_args + .as_ref() + .is_some_and(|extra_args| !extra_args.is_object()) + { + return Err(Error::BadRequest( + "Field `extra_args` expected to be JSON object".to_string(), + )); + } + + // Any hub script is left unchecked, so saving never needs the hub. + let exists = if let Some(p) = path.strip_prefix("script/") { + p.starts_with("hub/") + || sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND path = $2 AND archived = false AND deleted = false)", + w_id, + p + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false) + } else if let Some(p) = path.strip_prefix("flow/") { + sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM flow WHERE workspace_id = $1 AND path = $2 AND archived = false)", + w_id, + p + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false) + } else { + return Err(Error::BadRequest(format!( + "Field `path` must start with script/ or flow/ (got {path})" + ))); + }; + if !exists { + return Err(Error::BadRequest(format!( + "Variable expiration handler '{path}' not found. The handler must be an existing, non-archived script or flow." + ))); + } + + // Persisted even when false, like `error_handler`'s. + let mut variable_expiration_handler = serde_json::json!({ + "path": path, + "muted_on_user_path": es.muted_on_user_path, + }); + if let Some(extra_args) = &es.extra_args { + variable_expiration_handler["extra_args"] = extra_args.clone(); + } + if let Some(notify_before_secs) = es.notify_before_secs { + variable_expiration_handler["notify_before_secs"] = notify_before_secs.into(); + } + if let Some(remind_every_secs) = es.remind_every_secs { + variable_expiration_handler["remind_every_secs"] = remind_every_secs.into(); + } + + // A recorded failure is the sweep's: it ends at the handler's next start. + sqlx::query!( + "UPDATE workspace_settings SET variable_expiration_handler = $1 WHERE workspace_id = $2", + variable_expiration_handler, + &w_id + ) + .execute(&mut *tx) + .await?; + } else { + sqlx::query!( + "UPDATE workspace_settings SET variable_expiration_handler = NULL WHERE workspace_id = $1", + &w_id + ) + .execute(&mut *tx) + .await?; + } + + audit_log( + &mut *tx, + &authed, + "workspaces.edit_variable_expiration_handler", + ActionKind::Update, + &w_id, + Some(&authed.email), + Some([("variable_expiration_handler", &format!("{:?}", es.path)[..])].into()), + ) + .await?; + tx.commit().await?; + + handle_deployment_metadata( + &authed.email, + &authed.username, + &db, + &w_id, + windmill_git_sync::DeployedObject::Settings { + setting_type: "variable_expiration_handler".to_string(), + }, + Some("Variable expiration handler configuration updated".to_string()), + false, + None, + ) + .await?; + + windmill_common::feature_usage::log_feature_usage( + "variable_expiration", + "handler_configured", + // By slug, not hub id, so a bumped hub version still counts as the built-in. + match es.path.as_deref() { + None => "cleared", + Some(p) if p.ends_with("/variable-expiration-handler-slack") => "slack", + Some(p) if p.ends_with("/variable-expiration-handler-teams") => "teams", + Some(_) => "custom", + }, + ); + + Ok(format!( + "Edit variable_expiration_handler for workspace {}", + &w_id + )) +} + async fn edit_success_handler( authed: ApiAuthed, Extension(db): Extension<DB>, @@ -7925,9 +8083,10 @@ async fn clone_variables( source_workspace_id: &str, target_workspace_id: &str, ) -> Result<()> { + // Dispatch markers are not copied, so the fork re-arms its own handler. sqlx::query!( - "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at) - SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at + "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until) + SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until FROM variable WHERE workspace_id = $1", source_workspace_id, @@ -14503,7 +14662,7 @@ async fn compare_two_variables( // Get variable from each workspace let source_variable = sqlx::query!( - "SELECT value::text AS \"value!\", is_secret, description + "SELECT value::text AS \"value!\", is_secret, description, value_valid_until FROM variable WHERE workspace_id = $1 AND path = $2", source_workspace_id, @@ -14513,7 +14672,7 @@ async fn compare_two_variables( .await?; let target_variable = sqlx::query!( - "SELECT value::text AS \"value!\", is_secret, description + "SELECT value::text AS \"value!\", is_secret, description, value_valid_until FROM variable WHERE workspace_id = $1 AND path = $2", fork_workspace_id, @@ -14526,7 +14685,10 @@ async fn compare_two_variables( // Check metadata differences if let (Some(source), Some(target)) = (&source_variable, &target_variable) { - if source.is_secret != target.is_secret || source.description != target.description { + if source.is_secret != target.is_secret + || source.description != target.description + || source.value_valid_until != target.value_valid_until + { has_changes = true; } else if source.value != target.value || (source.is_secret && is_external_stored_value(&source.value)) @@ -15355,6 +15517,7 @@ pub enum SettingsEdit { InstanceGroups, ErrorHandler, SuccessHandler, + VariableExpirationHandler, LargeFileStorage, GitSync, DefaultScripts, @@ -15407,6 +15570,9 @@ pub async fn apply_settings_edit( InstanceGroups => edit_instance_groups(a, d, p, settings_edit_body(edit, body)?).await?, ErrorHandler => edit_error_handler(a, d, p, settings_edit_body(edit, body)?).await?, SuccessHandler => edit_success_handler(a, d, p, settings_edit_body(edit, body)?).await?, + VariableExpirationHandler => { + edit_variable_expiration_handler(a, d, p, settings_edit_body(edit, body)?).await? + } LargeFileStorage => { edit_large_file_storage_config(a, d, p, settings_edit_body(edit, body)?).await? } diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index 64aa5c6a08..aea887624d 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -135,7 +135,7 @@ pub(crate) async fn change_workspace_id( // Duplicate workspace settings (keep copy in old workspace for reference) info!("Duplicating workspace_settings table"); sqlx::query!( - "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at FROM workspace_settings WHERE workspace_id = $2", + "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_access_enabled, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", &rw.new_id, &old_id ) diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 36b170b22d..c5f3a902eb 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -4366,6 +4366,8 @@ paths: $ref: "#/components/schemas/ErrorHandlerConfig" success_handler: $ref: "#/components/schemas/SuccessHandlerConfig" + variable_expiration_handler: + $ref: "#/components/schemas/VariableExpirationHandlerConfig" large_file_storage: $ref: "#/components/schemas/LargeFileStorage" ducklake: @@ -5432,6 +5434,29 @@ paths: schema: type: string + /w/{workspace}/workspaces/edit_variable_expiration_handler: + post: + summary: edit variable expiration handler + operationId: editVariableExpirationHandler + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + description: WorkspaceVariableExpirationHandler + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/EditVariableExpirationHandler" + responses: + "200": + description: status + content: + text/plain: + schema: + type: string + /w/{workspace}/workspaces/edit_success_handler: post: summary: edit success handler @@ -29832,6 +29857,45 @@ components: type: boolean default: false + EditVariableExpirationHandler: + type: object + description: > + Request body for editing the workspace variable expiration handler. Omit + `path` (or send null) to unset the handler. + properties: + path: + type: string + nullable: true + description: Path to the variable expiration handler script or flow + extra_args: + $ref: "#/components/schemas/ScriptArgs" + muted_on_user_path: + type: boolean + description: Do not run the handler for variables on a personal (u/) path + notify_before_secs: + type: integer + minimum: 0 + description: How long before a variable's value expires the handler runs. 1 day when omitted. + remind_every_secs: + type: integer + minimum: 0 + description: Run the handler again at this interval until the value expires. No reminders when omitted or 0. + + VariableExpirationHandlerConfig: + type: object + description: Workspace variable expiration handler configuration + properties: + path: + type: string + extra_args: + $ref: "#/components/schemas/ScriptArgs" + muted_on_user_path: + type: boolean + notify_before_secs: + type: integer + remind_every_secs: + type: integer + EditSuccessHandler: description: Request body for editing the workspace success handler. Accepts both new grouped format and legacy flat format for backward compatibility. oneOf: @@ -32613,6 +32677,10 @@ components: expires_at: type: string format: date-time + value_valid_until: + type: string + nullable: true + format: date-time labels: type: array items: @@ -32689,7 +32757,18 @@ components: description: Whether the variable is an OAuth variable expires_at: type: string - description: The expiration date of the variable + description: > + When to garbage-collect the variable. Used for ephemeral secrets; + the variable is deleted once this is reached. Not the value's expiry + — see value_valid_until. + format: date-time + value_valid_until: + type: string + description: > + When the value stored in this variable stops working. Triggers the + workspace's variable expiration handler ahead of it, by the handler's + `notify_before_secs` (1 day by default); never causes the variable + to be deleted. format: date-time labels: type: array @@ -32718,6 +32797,14 @@ components: description: type: string description: The new description of the variable + value_valid_until: + type: string + nullable: true + description: > + When the value stored in this variable stops working. Omit to leave + it unchanged; send null to clear it. Changing it re-arms the + workspace's variable expiration handler. + format: date-time labels: type: array items: @@ -32825,6 +32912,7 @@ components: - "workspaces.edit_webhook" - "workspaces.edit_copilot_config" - "workspaces.edit_error_handler" + - "workspaces.edit_variable_expiration_handler" - "workspaces.create" - "workspaces.update" - "workspaces.archive" diff --git a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs index 8ff3e9f5c2..9add0792ee 100644 --- a/backend/windmill-api/src/mcp/auto_generated_endpoints.rs +++ b/backend/windmill-api/src/mcp/auto_generated_endpoints.rs @@ -184,7 +184,12 @@ pub fn all_tools() -> Vec<EndpointTool> { }, "expires_at": { "type": "string", - "description": "The expiration date of the variable", + "description": "When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry — see value_valid_until.\n", + "format": "date-time" + }, + "value_valid_until": { + "type": "string", + "description": "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it, by the handler's `notify_before_secs` (1 day by default); never causes the variable to be deleted.\n", "format": "date-time" }, "labels": { @@ -272,6 +277,12 @@ pub fn all_tools() -> Vec<EndpointTool> { "type": "string", "description": "The new description of the variable" }, + "value_valid_until": { + "type": "string", + "nullable": true, + "description": "When the value stored in this variable stops working. Omit to leave it unchanged; send null to clear it. Changing it re-arms the workspace's variable expiration handler.\n", + "format": "date-time" + }, "labels": { "type": "array", "items": { diff --git a/backend/windmill-api/src/mcp/session/deploy.rs b/backend/windmill-api/src/mcp/session/deploy.rs index e508a16174..ba65488c75 100644 --- a/backend/windmill-api/src/mcp/session/deploy.rs +++ b/backend/windmill-api/src/mcp/session/deploy.rs @@ -268,11 +268,16 @@ async fn deploy_variable( || draft.get("is_oauth") == Some(&Value::Bool(true)) || non_null(draft.get("account")).is_some(); let keep_stored = protected && stages_no_value; - let body = if keep_stored { + let mut body = if keep_stored { without(draft, &["value"]) } else { draft.clone() }; + // The draft holds the full variable, so an absent expiry was cleared, while the update + // endpoint reads an absent one as unchanged. + if let Some(body) = body.as_object_mut() { + body.entry("value_valid_until").or_insert(Value::Null); + } ctx.post( &ctx.ws(&format!("variables/update/{}", path_enc(path))), body, diff --git a/backend/windmill-api/src/mcp/session/gen/instructions.json b/backend/windmill-api/src/mcp/session/gen/instructions.json index b5e6609ef4..9cdb920c99 100644 --- a/backend/windmill-api/src/mcp/session/gen/instructions.json +++ b/backend/windmill-api/src/mcp/session/gen/instructions.json @@ -225,7 +225,7 @@ "script.bunnative": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (bunnative)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# TypeScript (Bun Native)\n\nNative TypeScript execution. Native scripts are Bun scripts that run on the native worker — a lightweight V8 isolate that exposes `fetch` and the JavaScript standard library — and can be heavily parallelized. Every script MUST start with `//native` on its first line so Windmill routes it to the native worker; without it the exact same script runs on the regular Bun worker. You may import npm packages and other Windmill scripts (e.g. `./helper.ts`) — imports are resolved and bundled just like a regular Bun script — as long as everything (your code and its dependencies) relies only on `fetch` and the standard library. Libraries that need Node/Bun runtime APIs (filesystem, `node:*` modules, child processes, native addons) will not work on the native worker; use the regular `bun` language for those.\n\n## Structure\n\nExport a single **async** function called `main`:\n\n```typescript\n//native\nexport async function main(param1: string, param2: number) {\n // Your code here\n return { result: param1, count: param2 };\n}\n```\n\nDo not call the main function.\n\n## Resource Types\n\nOn Windmill, credentials and configuration are stored in resources and passed as parameters to main.\n\nUse the `RT` namespace for resource types:\n\n```typescript\n//native\nexport async function main(stripe: RT.Stripe) {\n // stripe contains API key and config from the resource\n}\n```\n\nOnly use resource types if you need them to satisfy the instructions. Always use the RT namespace.\n\n## Imports\n\n**The constraint is the runtime, not the import list.** You may import npm packages and relative Windmill scripts; they are resolved and bundled exactly like a regular Bun script. But the native worker only provides `fetch` and the JavaScript standard library, so any imported code must work using only those. Anything requiring Node/Bun built-ins (`node:fs`, `child_process`, the `Bun` API, native modules) belongs in a regular `bun` script instead. Use the globally available `fetch` for HTTP:\n\n```typescript\n//native\nexport async function main(url: string) {\n const response = await fetch(url);\n return await response.json();\n}\n```\n\n## Pure computation: `//no_network`\n\nA native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. Without `//native` it means something else: the script must run in an nsjail sandbox (`//sandbox`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments:\n\n```typescript\n//native\n//no_network\nexport async function main(items: { price: number; qty: number }[]) {\n return items.reduce((sum, i) => sum + i.price * i.qty, 0);\n}\n```\n\n## Windmill Client\n\n`windmill-client` works on the native worker (its calls go over `fetch`), so use it as the **preferred way to talk to Windmill** — reading resources/variables/states, running scripts and flows, and the S3 helpers below (`loadS3File`, `loadS3FileStream`, `writeS3File`, `S3Object`). It handles auth, the workspace, and the base URL for you. Reserve raw `fetch` for calling *external* HTTP APIs that aren't Windmill.\n\nThe full `windmill-client` API reference (every exported function and its signature) is included below — consult it for the exact method instead of hand-rolling a `fetch` against the Windmill API.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```typescript\n//native\ntype Event = {\n kind:\n | \"webhook\"\n | \"http\"\n | \"websocket\"\n | \"kafka\"\n | \"email\"\n | \"nats\"\n | \"postgres\"\n | \"sqs\"\n | \"mqtt\"\n | \"amqp\"\n | \"gcp\"\n | \"azure\";\n body: any;\n headers: Record<string, string>;\n query: Record<string, string>;\n};\n\nexport async function preprocessor(event: Event) {\n return {\n param1: event.body.field1,\n param2: event.query.id,\n };\n}\n```\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations. The `wmill.S3Object` type covers both the `s3://storage/key` URI form (`s3:///key` for the workspace default storage) and the `{ s3, storage? }` record form — always use it instead of redefining your own.\n\n### Receiving an S3Object as a script parameter\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\nexport async function main(file: wmill.S3Object) {\n const content = await wmill.loadS3File(file);\n // ...\n}\n```\n\n### S3 operations\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\n// Load file content from S3\nconst content: Uint8Array = await wmill.loadS3File(s3object);\n\n// Load file as stream\nconst blob: Blob = await wmill.loadS3FileStream(s3object);\n\n// Write file to S3\nconst result: wmill.S3Object = await wmill.writeS3File(\n s3object, // Target path (or undefined to auto-generate)\n fileContent, // string or Blob\n s3ResourcePath // Optional: specific S3 resource to use\n);\n```\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise<string>\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable<string>): Promise<void>\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise<any>\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise<any>\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise<any>\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise<string>\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string>\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise<any>\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise<void>\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise<void>\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise<void>\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise<number | null>\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise<boolean>\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise<void>\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise<any>\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise<any>\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise<string>\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise<void>\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise<string>\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise<DenoS3LightClientSettings>\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Uint8Array | undefined>\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Blob | undefined>\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise<S3Object>\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise<void>\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object[]>\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object>\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string[]>\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string>\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise<string>\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise<void>} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise<void>\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise<void>} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise<void>\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise<void>\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow<T>(fn: (...args: any[]) => Promise<T>): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel<T, R>(items: T[], fn: (item: T) => PromiseLike<R> | R, options?: { concurrency?: number },): Promise<R[]>\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise<void>\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement<any>\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit<DucklakeMaterializeOptions, \"uniqueKey\">,): SqlStatement<any>\n", "script.dbt": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (dbt)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n", "flow": "# Global draft flow instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` when the user gave a bare name; only use `f/<folder>/<name>` when the folder is known to exist. Never invent a folder.\n- `write_flow` mirrors flow mode's `set_flow_json`: pass `path`, optional `summary`, optional `description`, required `modules`, and optional `schema`, `preprocessor_module`, `failure_module`, `groups`, and `notes`. `summary` and `description` are top-level flow metadata (not part of the compact value `patch_flow_json` edits); the flow-structure arguments are JSON strings, matching the tool schema descriptions. When overwriting an existing flow, top-level flow settings (see below) are preserved from the current flow — use `patch_flow_json` to change them.\n- `read_workspace_item` returns a compact flow `value` object with `modules`, `schema`, `preprocessor_module`, `failure_module`, `groups`, `notes`, and any top-level flow settings that are set.\n- Top-level flow settings appear as top-level keys of the compact flow value and can be added, edited, or removed with `patch_flow_json`: same_worker, preserve_step_tags, concurrent_limit, concurrency_key, concurrency_time_window_s, debounce_delay_s, debounce_key, debounce_args_to_accumulate, max_total_debouncing_time, max_total_debounces_amount, skip_expr, cache_ttl, cache_ignore_s3_path, delete_after_secs, flow_env, priority, early_return, chat_input_enabled. For example, `chat_input_enabled: true` marks a flow as chat-style (flow-as-chat); keep it intact when restructuring such a flow.\n- `modules` contains normal sequential modules. Use top-level `preprocessor_module` and `failure_module` for special modules; do not put `preprocessor` or `failure` in `modules`.\n- Every module needs a stable unique `id` and a useful `summary` when the schema supports it.\n- Prefer path/script/flow modules when composing existing workspace logic. Use rawscript modules only when new inline code is needed.\n- When writing rawscript module code, call `get_instructions` with `subject: \"script\"` and the rawscript language first.\n\n## Groups and notes\n\n- Add `groups` to any non-trivial flow without being asked; \"Organizing Flows: Groups and Notes\" in the reference below gives the fields and the rules the editor enforces. Pass `null` to `write_flow` to clear them, and the same for `notes`.\n- With `patch_flow_json`, edit `groups` and `notes` the same way as any other field — they appear as top-level keys in the compact flow value.\n\n## Compact view: how rawscript bodies surface in tool I/O\n\n- `read_workspace_item` and `patch_flow_json` operate on a **compact view** of the flow: every rawscript module's `value.content` is replaced with the placeholder `\"inline_script.<moduleId>\"` so inline script bodies don't bloat tool I/O. Schema, groups, notes, preprocessor_module and failure_module are all shown in this view.\n- Inline rawscript content is **not** part of the JSON `patch_flow_json` sees. Edits to inline bodies happen via dedicated tools:\n - `read_flow_module_code(path, module_id)` — returns the raw inline script content for one module.\n - `set_flow_module_code(path, module_id, code)` — overwrites that module's inline script content; saves to the draft.\n- Use `patch_flow_json` for *structural* edits: module ids, paths, input_transforms, branch arrangement, summaries, preprocessor/failure swaps, schema/groups/notes. Use `set_flow_module_code` for changes inside a specific rawscript body.\n- When **adding a new rawscript module** with `patch_flow_json`, set its `content` to the placeholder `\"inline_script.<moduleId>\"` (matching the compact view) — never real code — then **immediately fill the body** with `set_flow_module_code(path, module_id, code)`. The module is saved with an empty body until you do; the tool result lists the module ids still awaiting code. A placeholder that names anything other than the module's own id or an existing rawscript module is rejected.\n- `write_flow` is for full overwrites / create-from-scratch. Its `modules`, `preprocessor_module`, and `failure_module` arguments are **non-compact** flow modules: inline each rawscript body directly in `content` by default. But if a body is long or quote/backslash-heavy enough that escaping it into the JSON string is error-prone — or if a `write_flow` call comes back with a JSON parse error — create that module with **empty content** (`\"content\": \"\"`) and fill it with `set_flow_module_code(path, module_id, code)`, whose `code` is a plain argument with no nested escaping. `write_flow` reports which modules still have empty bodies so you know what to fill.\n - When overwriting an **existing** flow, set `\"content\": \"inline_script.<moduleId>\"` on any rawscript module whose code you are not changing — the placeholder resolves to that module's current body, so you never re-send (or re-read) unchanged code. Placeholders that match no existing rawscript module and are not the module's own id are rejected.\n\n\n# Windmill flow authoring reference\n\n# Windmill Flow Building Guide\n\n## OpenFlow Schema\n\nThe OpenFlow schema (openflow.openapi.yaml) is the source of truth for flow structure. Refer to OPENFLOW_SCHEMA for the complete type definitions.\n\n## Reserved Module IDs\n\n- `failure` - Reserved for failure handler module\n- `preprocessor` - Reserved for preprocessor module\n- `Input` - Reserved for flow input reference\n\n## Hard Structural Rules\n\nThese are strict Windmill schema rules. Follow them exactly.\n\n- `value.modules` is only for normal sequential steps\n- `value.preprocessor_module` and `value.failure_module` are special top-level fields inside `value`, not entries in `value.modules`\n- If a flow needs a preprocessor, create `value.preprocessor_module` with `id: preprocessor`\n- If a flow needs a failure handler, create `value.failure_module` with `id: failure`\n- Do NOT create regular modules inside `value.modules` named `preprocessor` or `failure`\n- `preprocessor_module` and `failure_module` only support `script` or `rawscript`\n- `preprocessor_module` runs before normal modules and cannot reference `results.*`\n- `failure_module` can use the `error` object with `error.message`, `error.step_id`, `error.name`, and `error.stack`\n- A flow whose `failure_module` runs still ends as failed, unless the handler returns an object with `recover: true`: the flow then ends as a success. This also holds when the failing step is inside a loop, a branch or a subflow. `recover` never changes which steps run; whether a loop or branch carries on past a failure is still decided by its own settings (`skip_failures`, `continue_on_error`)\n\nCorrect shape:\n\n```yaml\nvalue:\n preprocessor_module:\n id: preprocessor\n value:\n type: rawscript\n ...\n failure_module:\n id: failure\n value:\n type: rawscript\n ...\n modules:\n - id: process_event\n value:\n type: rawscript\n ...\n```\n\nIncorrect shape:\n\n```yaml\nvalue:\n modules:\n - id: preprocessor\n ...\n - id: process_event\n ...\n - id: failure\n ...\n```\n\n## Module ID Rules\n\n- Must be unique across the entire flow\n- Use underscores, not spaces (e.g., `fetch_data` not `fetch data`)\n- Use descriptive names that reflect the step's purpose\n\n## AI Agent Modules\n\nAn `aiagent` module runs an LLM that can call tools. Each entry of `value.tools` is a module-shaped\nobject with an extra `value.tool_type`: `flowmodule` for a script/flow tool, `mcp` for an MCP server\ntool, `websearch` for web search.\n\n```json\n{\n \"id\": \"support_agent\",\n \"summary\": \"AI agent for customer support\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"openai\", \"resource\": \"$res:f/ai_providers/openai\", \"model\": \"gpt-4o\" }\n },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.query\" },\n \"system_prompt\": { \"type\": \"static\", \"value\": \"You are a helpful assistant.\" }\n },\n \"tools\": [\n {\n \"id\": \"search_docs\",\n \"summary\": \"search_documentation\",\n \"description\": \"Search the product documentation. Use it whenever the user asks how a feature works.\",\n \"value\": {\n \"tool_type\": \"flowmodule\",\n \"type\": \"rawscript\",\n \"language\": \"bun\",\n \"content\": \"export async function main(query: string) { return ['doc1', 'doc2']; }\",\n \"input_transforms\": { \"query\": { \"type\": \"static\", \"value\": \"\" } }\n }\n }\n ]\n }\n}\n```\n\n- `provider` is an object, not a bare resource string: `{ \"kind\": <provider kind>,\n \"resource\": \"$res:<path>\", \"model\": <model id> }`. Required unless the module links to a saved\n agent through `value.agent`. Static is right for a flow run from a form; a chat flow wires its\n fields to flow inputs instead — see below\n\n### Chat-Mode Flows\n\nA flow with `value.chat_input_enabled: true` is run from a chat instead of a form: the composer\nsends one message per turn and renders the conversation. It needs a required `user_message` string\ninput, read by the agent. Any other flow input the composer does not edit itself is asked for\nunder Configure inputs.\n\n**A static `provider` gives a chat that cannot change its model.** Feed it from flow inputs\ninstead, either way round: one input carrying the whole object (`\"expr\": \"flow_input.model_config\"`)\nmakes every field editable, or wire it field by field to fix some and expose others. A field the\nchat can write becomes a control in the composer — a provider picker, a model list, a thinking\ncontrol — and a field left static is fixed, with no control drawn for it. `kind` is the one\nexception: the composer writes it only together with `resource`, since a provider is picked as a\npair, so a `kind` input wired on its own stays askable under Configure inputs and nothing the run\nneeds becomes unreachable.\n\n```json\n{\n \"id\": \"chat_agent\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"javascript\",\n \"expr\": \"({ kind: 'anthropic', resource: '$res:f/ai/claude', model: flow_input.model, reasoning_effort: flow_input.thinking })\"\n },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.user_message\" },\n \"user_attachments\": { \"type\": \"javascript\", \"expr\": \"flow_input.files\" },\n \"memory\": { \"type\": \"static\", \"value\": { \"kind\": \"compaction\" } },\n \"streaming\": { \"type\": \"static\", \"value\": true },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" }\n },\n \"tools\": []\n }\n}\n```\n\n- Wiring field by field means one object literal whose values are literals or bare `flow_input.x`\n references. A spread, a call or a computed key leaves the composer unable to tell which input\n feeds which field, so it offers no control at all — a bare `flow_input.x` for the whole object\n is read instead as that one input carrying every field\n- A step linked to a saved agent (`agent` set) has no `provider` of its own. It exposes the same\n two controls through its `model` and `reasoning_effort` inputs, which replace what the agent\n saved: `\"model\": { \"type\": \"javascript\", \"expr\": \"flow_input.model\" }`. An empty model keeps the\n saved one, an empty effort sends none, and the provider resource always stays the agent's\n- `memory` is what lets the agent see earlier turns; without it every message starts from nothing\n- `streaming` on makes the answer and its thinking appear token by token instead of all at once\n- `user_attachments` points at a flow input typed as an array of s3 objects\n (`{ \"type\": \"array\", \"items\": { \"type\": \"object\", \"resourceType\": \"s3object\" } }`), so files\n sent with a message reach the agent\n- Running one needs a `memory_id` **query parameter** — not a flow argument — naming the\n conversation the turn belongs to: a fresh UUID starts one, reusing a UUID continues it. The chat\n supplies it itself; a run driven any other way has to pass it or the server refuses the job\n\n### Tool Naming Rules\n\nThese rules cover `flowmodule` tools, the ones the agent calls by name. A `websearch` tool's\n`summary` is a plain label (`Web Search`), and an `mcp` tool exposes the MCP server's own tool\nnames, so neither is name-checked at all — leave those summaries as they are.\n\n- A flowmodule tool's `summary` is the **name the agent calls it by**, not a human label. Put the\n human-readable explanation in `description`\n- `summary` must match `^[a-zA-Z0-9_]+$`: letters, numbers and underscores only. No spaces, dashes,\n dots or accents — `search_documentation`, never `Search documentation`\n- Always set `summary`. It must be unique among that agent's tools, and must not be one of the\n reserved ids (`do`, `bg`, `ctx`, `state`, `if`, `else`, `for`, `delete`, `while`, `new`, `in`,\n `failure`, `preprocessor`, `as`, `Input`, `Result`, `Trigger`)\n- A tool name outside that character set fails any run that offers the tool to the agent, with `Invalid tool name`.\n The flow write tools refuse such a name.\n- Tool `id` follows the same rules as any module ID — unique across the flow, underscores not spaces\n- `description` is optional free text telling the agent when and how to call the tool. Set it\n whenever the name alone does not make that obvious; it overrides the description derived from the\n underlying script\n\n## AI Decision Modules\n\nAn `aidecision` module asks a decision model (TypeSafe's Jev, Cloudflare's Clef or OpenAI's Decisions API) typed questions about a `state` and\nanswers each with calibrated probabilities instead of text. Prefer it over an `aiagent` when the step\nis a judgment (classify, route, score or a yes/no check) that needs no tools and no free text: it\nis faster, cheaper, and its answers have a fixed shape.\n\n```json\n{\n \"id\": \"triage\",\n \"summary\": \"Classify the ticket\",\n \"value\": {\n \"type\": \"aidecision\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"typesafe\", \"resource\": \"$res:f/ai/typesafe\", \"model\": \"jev-latest\" }\n },\n \"state\": { \"type\": \"javascript\", \"expr\": \"flow_input.message\" },\n \"questions\": {\n \"type\": \"static\",\n \"value\": {\n \"intent\": {\n \"type\": \"choice\",\n \"instructions\": \"What does the customer want?\",\n \"criteria\": { \"refund\": \"Money back\", \"bug\": \"Something is broken\", \"other\": \"Anything else\" }\n },\n \"urgency\": {\n \"type\": \"score\",\n \"instructions\": \"How urgent is the ticket?\",\n \"criteria\": [\"Can wait\", \"This week\", \"Today\", \"Right now\"]\n },\n \"angry\": { \"type\": \"noul\", \"instructions\": \"Is the customer angry?\" }\n }\n }\n }\n }\n}\n```\n\n- `provider.kind` is `typesafe` (`model` `jev-latest` unless a version is pinned), `cloudflare`\n (`model` `clef`, or `clef-flash` for faster answers) or `openai` (`model` `gpt-6-luna`, never a\n chat model); the resource is of that same type\n- `state` is the content to evaluate: usually a text, such as the message to classify. To combine\n several values, pass an object with descriptive keys holding only what the questions need\n (`({ message: flow_input.message, plan: results.get_account.plan })`); an array of strings also works\n- `questions` maps each question name to `{ type, instructions, criteria }`:\n - `choice`: `criteria` maps each option to its description (up to 255 options). The answer has\n `choice`, `probabilities` and `confidence`\n - `score`: `criteria` is an ordered array of 2 to 10 level descriptions. The answer has `score`,\n `legend`, `probabilities` and `confidence`\n - `noul`: yes/no, `criteria` optionally `{ \"true\": ..., \"false\": ... }` descriptions. The answer has\n `noul`, the probability of yes from 0 to 1\n- The result is `{ output, model, usage }` with `output` keyed by question name, so a later step\n reads `results.triage.output.intent.choice`, `results.triage.output.urgency.score` or\n `results.triage.output.angry.noul > 0.7`\n- On `openai` the same `questions` are translated for its Decisions API and the answers read the\n same way (`choice`, `score`, `noul`), except that `probabilities` is a list of\n `{ value, probability }` (plus `label` on a score) and a score has no `legend`. A question OpenAI\n refuses to answer fails the step. A `state` that is\n an array of user messages (`[{ role: \"user\", content: [{ type: \"input_text\", text }, { type: \"input_image\", image_url: \"data:image/png;base64,...\" }] }]`)\n is sent as is, which is how an image is evaluated; any other object or array is sent as JSON text\n\n### Branching on the Answers\n\nTo route on the answers, put a `branchone` right after the decision, one branch per option, with\neach `expr` reading the decision by id:\n\n```json\n{\n \"id\": \"route\",\n \"value\": {\n \"type\": \"branchone\",\n \"branches\": [\n { \"summary\": \"refund\", \"expr\": \"results.triage.output.intent.choice === 'refund'\", \"modules\": [...] },\n { \"summary\": \"bug\", \"expr\": \"results.triage.output.intent.choice === 'bug'\", \"modules\": [...] }\n ],\n \"default\": [...]\n }\n}\n```\n\nFor a yes/no question, one branch with `\"expr\": \"results.triage.output.angry.noul >= 0.5\"` (tune the\nthreshold as needed) and the `default` as the \"no\" path.\n\n### As an Agent Tool\n\nAn `aidecision` can be a `flowmodule` tool of an `aiagent` (`\"tool_type\": \"flowmodule\", \"type\":\n\"aidecision\"`): set `state` to `{ \"type\": \"ai\" }` so the calling model supplies it, and only `output`\ngoes back to the model. The Tool Naming Rules apply to its `summary`. Only a flow's own agent step\ncan call one, not an agent used as a tool.\n\n## Common Mistakes to Avoid\n\n- Missing `input_transforms` - Rawscript parameters won't receive values without them\n- Referencing future steps - `results.step_id` only works for steps that execute before the current one\n- Duplicate module IDs - Each module ID must be unique in the flow\n- AI agent flowmodule tool names with spaces - `summary` is the tool name and only accepts letters, numbers and underscores\n\n## Data Flow Between Steps\n\n- `flow_input.property` - Access flow input parameters\n- `results.step_id` - Access output from a previous step only when that step result is in scope\n- `results.step_id.property` - Access specific property from a previous step output only when that step result is in scope\n- `flow_input.iter.value` - Current iteration value inside a `forloopflow`; in a `whileloopflow` it is just the iteration index (a plain number, same as `flow_input.iter.index`)\n- `flow_input.iter.index` - Current loop index when inside a loop (`forloopflow` or `whileloopflow`)\n- After a suspend step (approval), the next step's javascript expressions also get:\n - `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: \"SuspendedDisapproved\" | \"SuspendedTimedOut\", message } }` instead\n - `resumes` - every resume payload, in arrival order\n - `approvers` - a plain array of strings, one per resume: for a resume through the `resume`/`cancel` URL from `getResumeUrls(approver)`, the `approver` passed there if any; otherwise (including the `approvalPage` link) the resuming user's username, else `\"anonymous\"`, e.g. `approvers[0]`. It is NOT the `{ resume_id, approver }` objects stored in the flow status, so `approvers[0].approver` is always undefined\n\n## Loop Structure Rules\n\n- A `forloopflow` runs its `modules` once per element of `iterator`, a javascript expression returning an array (e.g. `results.get_items`); `parallel: true` runs the iterations concurrently, and `skip_failures: true` carries on past a failed iteration\n- For `whileloopflow`, break the loop with a module-level `stop_after_if`: on the loop module itself, or on an inner step (required when that step carries state via its own `results` — see below)\n- `stop_after_if` is always a sibling of `id` and `value` on a flow module — never a direct key of the loop's `value` object\n- `stop_after_all_iters_if` is for checks after the whole loop finishes, not the normal per-iteration break condition\n- `stop_after_if` is evaluated after each iteration: on the loop module, `result` is that iteration's result (what its last step returned); on an inner step, it is that step's result\n- `flow_input.iter.value` in a `whileloopflow` is just the iteration index (same number as `flow_input.iter.index`) — it never carries state, so `flow_input.iter.value.<field>` is always undefined and a loop whose stop condition depends on it never terminates\n- To carry state across iterations, a step reads its own previous-iteration result via `results.<its_own_id>` with a first-iteration fallback (e.g. `results.b ?? flow_input.start`) — but then the loop's `stop_after_if` MUST sit on that inner step, not on the loop module: a body that is exactly one plain step with the stop condition on the loop module runs on a fast path where `results.<step_id>` is null on every iteration and the loop never terminates (bodies with 2+ steps, or whose single step has its own `stop_after_if`, retry or similar, resolve `results` across iterations regardless of stop placement)\n- For state that is just a counter, derive it from the index instead (e.g. `flow_input.iter.index + 1`) — that works in every configuration, including with `stop_after_if` on the loop module\n- If the user asks for a final scalar/object after a loop, add a normal step after the loop that extracts the final value from the loop result instead of returning the whole loop result array\n\nCorrect `whileloopflow` shape:\n\n```yaml\n- id: loop_until_done\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n value:\n type: rawscript\n input_transforms:\n count:\n type: javascript\n expr: flow_input.iter.index + 1\n- id: return_final_state\n value:\n type: rawscript\n input_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done[results.loop_until_done.length - 1]\n```\n\nCorrect `whileloopflow` shape carrying state via `results` (stop condition on the inner step):\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: rawscript\n input_transforms:\n state:\n type: javascript\n expr: results.advance_state ?? flow_input.initial_state\n```\n\nIncorrect `whileloopflow` patterns:\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n stop_after_if:\n expr: result.done === true\n```\n\n```yaml\ninput_transforms:\n state:\n type: javascript\n # iter.value is a number (the iteration index); there is no previous-iteration state\n expr: flow_input.iter.value.count\n```\n\n```yaml\ninput_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done\n```\n\n## Approval / Suspend Structure\n\nAn approval step is a normal **script** step (`type: rawscript` or `type: script`) that is turned into an approval by adding a module-level `suspend`. Its script calls `wmill.getResumeUrls(approver)` to generate the secret resume/cancel URLs and returns them so they can be sent to the approver(s) (Slack, email, etc.) or approved from the run page.\n\n- `suspend` belongs on the flow module object itself, as a sibling of `id` and `value`\n- Never put `suspend` inside `value`\n- Do NOT use `type: identity` for an approval step. An identity step suspends but never produces the resume URLs, so approvers have no link to act on — it is not a functional approval.\n\nCorrect shape:\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n resume_form:\n schema:\n type: object\n properties:\n comment:\n type: string\n required: [comment]\n value:\n type: rawscript\n language: bun\n input_transforms:\n approver:\n type: static\n value: ''\n content: |\n import * as wmill from \"windmill-client\"\n\n export async function main(approver?: string) {\n const urls = await wmill.getResumeUrls(approver)\n // send urls.resume / urls.cancel to the approver(s), e.g. via Slack or email\n return urls\n }\n```\n\nIncorrect shape (suspend misplaced inside `value`):\n\n```yaml\n- id: request_approval\n value:\n type: rawscript\n suspend:\n required_events: 1\n```\n\nIncorrect shape (identity has no resume URLs — not a real approval):\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n value:\n type: identity\n```\n\n## Branch Result Scope Rules\n\n- A `branchone` runs the first of its `branches` whose `expr` is true, in order, and its `default` modules when none is; a `branchall` runs every branch (concurrently with `parallel: true`)\n- Inside a branch, you may reference earlier outer steps and earlier steps in the same branch\n- Outside a `branchone`, do NOT reference ids of steps that only exist inside its branches or default branch. Use `results.<branchone_module_id>` instead\n- Outside a `branchall`, do NOT reference ids of steps inside its branches. Use `results.<branchall_module_id>` instead\n- If downstream steps need a stable shape after a branch, make each branch return the same fields\n- When needed, add a normalization step immediately after the branch and consume `results.<branch_module_id>` there\n\nCorrect after `branchone`:\n\n```yaml\n- id: route_order\n value:\n type: branchone\n ...\n- id: send_confirmation\n value:\n input_transforms:\n routed:\n type: javascript\n expr: results.route_order\n```\n\nIncorrect after `branchone`:\n\n```yaml\nexpr: results.create_shipment\nexpr: results.create_backorder\n```\n\nCorrect after `branchall`:\n\n```yaml\n- id: enrich_parallel\n value:\n type: branchall\n parallel: true\n ...\n- id: combine_data\n value:\n input_transforms:\n enrichments:\n type: javascript\n expr: results.enrich_parallel\n```\n\n## Input Transforms\n\nEvery rawscript module needs `input_transforms` to map function parameters to values:\n\nStatic transform (fixed value):\n{\"param_name\": {\"type\": \"static\", \"value\": \"fixed_string\"}}\n\nJavaScript transform (dynamic expression):\n{\"param_name\": {\"type\": \"javascript\", \"expr\": \"results.previous_step.data\"}}\n\n## Resource References\n\n- For flow inputs: Use type `\"object\"` with format `\"resource-{type}\"` (e.g., `\"resource-postgresql\"`)\n- For step inputs: Use static value `\"$res:path/to/resource\"`\n\n## Reusing Existing Scripts and Flows\n\nUnless the user asked for new code, look for a workspace script or flow that already does a step's job before writing it, and reuse it by path instead of copying its logic into a rawscript:\n\n- a workspace script: `type: script` with `path` (e.g. `f/folder/send_email`)\n- a workspace flow, run as a subflow: `type: flow` with `path`\n- a Hub script: `type: script` with a `hub/<version>/<app>/<name>` path\n\nThe step's `input_transforms` must cover the reused item's inputs, so read its input schema first.\n\n## Additional Prompt for AI\n\nA flow's input schema may carry a top-level `prompt_for_ai` string, as a script's can: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that flow, and keep it when you rewrite the schema.\n\n## Organizing Flows: Groups and Notes\n\nGroups and notes shape how a flow reads in the editor; neither changes what it does.\n\n**Segment every non-trivial flow into groups without waiting to be asked.** Whenever a flow has more than a couple of steps, or consecutive steps form a stage (\"fetch\", \"transform\", \"notify\"), put them in a group, and aim for every meaningful step to belong to one. Use notes sparingly, for flow-wide information that belongs to no span of steps: the flow's purpose, key assumptions, warnings, TODOs. One note is usually enough; never label a run of steps with a note, which is what a group is for.\n\n`value.groups` lists the groups, each spanning the steps from `start_id` to `end_id`:\n\n- `start_id`, `end_id` (required): ids of the group's first and last step; the same id for both makes a one-step group\n- `summary`: the group's title\n- `note`: markdown shown under the title\n- `color`: one of `yellow`, `blue`, `green`, `purple`, `pink`, `orange`, `red`, `cyan`, `lime`, `gray`, never a hex code or CSS color; leave it out and the editor picks one\n- `autocollapse`: `true` shows the group collapsed by default\n\nThe editor refuses to draw a flow whose groups break any of these rules:\n\n- `start_id` and `end_id` are steps of the same list: both top-level, or both in the same loop body or branch. A group can hold a loop or branch step whole, but cannot start outside one and end inside it\n- `start_id` does not come after `end_id` in that list\n- groups nest (one entirely inside another) but never partly overlap, and no two groups share both `start_id` and `end_id`\n- groups hold ordinary steps only: never `preprocessor`, `failure`, `Input`, `Result`, `Trigger`, or an AI agent's tools\n\n`value.notes` lists sticky notes, each with a unique `id`, markdown `text`, a `color` from the same list, and `type: free`. The `group` note type is deprecated; use `value.groups` instead.\nLeave a note's `position` and `size` out and they are filled in for you.\n\n## Final Structural Self-Check\n\nBefore finalizing a flow, verify:\n\n- any preprocessor is in `value.preprocessor_module`\n- any failure handler is in `value.failure_module`\n- any approval step has module-level `suspend`\n- no downstream step references inner branch step ids from outside the branch\n- every AI agent flowmodule tool has a unique `summary` made only of letters, numbers and underscores\n- every group starts and ends on steps of the same list, start before end, nesting without partial overlap\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations.\n\nTo accept an S3 object as flow input:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\n \"type\": \"object\",\n \"format\": \"resource-s3_object\",\n \"description\": \"File to process\"\n }\n }\n}\n```\n\n## Using Resources in Flows\n\nOn Windmill, credentials and configuration are stored in resources. Resource types define the format of the resource.\n\n### As Flow Input\n\nIn the flow schema, set the property type to `\"object\"` with format `\"resource-{type}\"`:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"database\": {\n \"type\": \"object\",\n \"format\": \"resource-postgresql\",\n \"description\": \"Database connection\"\n }\n }\n}\n```\n\n### When No Resource Type Fits\n\nA connection still comes in as one resource input, not as separate string inputs (a URL, a token) or a variable read inside a step: type the input `resource-c_<name>` with a custom resource type holding the service's connection fields, its secret in a variable the resource references. The `c_` prefix of custom types keeps one apart from a hub type synced later under the same name.\n\n- If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services.\n- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it.\n- A plain variable is fine when the user asks for it.\n\n### As Step Input (Static Reference)\n\nReference a specific resource using `$res:` prefix:\n\n```json\n{\n \"database\": {\n \"type\": \"static\",\n \"value\": \"$res:f/folder/my_database\"\n }\n}\n```\n\n\n## OpenFlow Schema\n\n{\"OpenFlow\":{\"type\":\"object\",\"description\":\"Top-level flow definition containing metadata, configuration, and the flow structure\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of what this flow does\"},\"description\":{\"type\":\"string\",\"description\":\"Detailed documentation for this flow\"},\"value\":{\"$ref\":\"#/components/schemas/FlowValue\"},\"schema\":{\"type\":\"object\",\"description\":\"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')\"},\"on_behalf_of_email\":{\"type\":\"string\",\"description\":\"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names.\"},\"on_behalf_of\":{\"type\":\"string\",\"description\":\"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead.\"}},\"required\":[\"summary\",\"value\"]},\"FlowValue\":{\"type\":\"object\",\"description\":\"The flow structure containing modules and optional preprocessor/failure handlers\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"failure_module\":{\"description\":\"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types\",\"$ref\":\"#/components/schemas/FlowModule\"},\"preprocessor_module\":{\"description\":\"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results\",\"$ref\":\"#/components/schemas/FlowModule\"},\"same_worker\":{\"type\":\"boolean\",\"description\":\"If true, all steps run on the same worker for better performance\"},\"preserve_step_tags\":{\"type\":\"boolean\",\"description\":\"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag.\"},\"concurrent_limit\":{\"type\":\"number\",\"description\":\"Maximum number of concurrent executions of this flow\"},\"concurrency_key\":{\"type\":\"string\",\"description\":\"Expression to group concurrent executions (e.g., by user ID)\"},\"concurrency_time_window_s\":{\"type\":\"number\",\"description\":\"Time window in seconds for concurrent_limit\"},\"debounce_delay_s\":{\"type\":\"integer\",\"description\":\"Delay in seconds to debounce flow executions\"},\"debounce_key\":{\"type\":\"string\",\"description\":\"Expression to group debounced executions\"},\"debounce_args_to_accumulate\":{\"type\":\"array\",\"description\":\"Arguments to accumulate across debounced executions\",\"items\":{\"type\":\"string\"}},\"max_total_debouncing_time\":{\"type\":\"integer\",\"description\":\"Maximum total time in seconds that a job can be debounced\"},\"max_total_debounces_amount\":{\"type\":\"integer\",\"description\":\"Maximum number of times a job can be debounced\"},\"skip_expr\":{\"type\":\"string\",\"description\":\"JavaScript expression to conditionally skip the entire flow\"},\"cache_ttl\":{\"type\":\"number\",\"description\":\"Cache duration in seconds for flow results\"},\"cache_ignore_s3_path\":{\"type\":\"boolean\"},\"delete_after_secs\":{\"type\":\"integer\",\"description\":\"If set, delete the flow job's args, result and logs after this many seconds following job completion\"},\"flow_env\":{\"type\":\"object\",\"description\":\"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).\",\"additionalProperties\":{}},\"priority\":{\"type\":\"number\",\"description\":\"Execution priority (higher numbers run first)\"},\"early_return\":{\"type\":\"string\",\"description\":\"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead.\"},\"chat_input_enabled\":{\"type\":\"boolean\",\"description\":\"Whether this flow accepts chat-style input\"},\"notes\":{\"type\":\"array\",\"description\":\"Sticky notes attached to the flow\",\"items\":{\"$ref\":\"#/components/schemas/FlowNote\"}},\"groups\":{\"type\":\"array\",\"description\":\"Semantic groups of modules for organizational purposes\",\"items\":{\"$ref\":\"#/components/schemas/FlowGroup\"}}},\"required\":[\"modules\"]},\"Retry\":{\"type\":\"object\",\"description\":\"Retry configuration for failed module executions\",\"properties\":{\"constant\":{\"type\":\"object\",\"description\":\"Retry with constant delay between attempts\",\"properties\":{\"attempts\":{\"type\":\"integer\",\"description\":\"Number of retry attempts\"},\"seconds\":{\"type\":\"integer\",\"description\":\"Seconds to wait between retries\"}}},\"exponential\":{\"type\":\"object\",\"description\":\"Retry with exponential backoff: the n-th retry waits multiplier \\u00d7 seconds^n\",\"properties\":{\"attempts\":{\"type\":\"integer\",\"description\":\"Number of retry attempts\"},\"multiplier\":{\"type\":\"integer\",\"description\":\"Multiplier for exponential backoff\"},\"seconds\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Base of the exponential (seconds); the n-th retry waits multiplier \\u00d7 seconds^n, where n counts constant retries too\"},\"random_factor\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"description\":\"Random jitter percentage (0-100) to avoid thundering herd\"}}},\"retry_if\":{\"$ref\":\"#/components/schemas/RetryIf\"}}},\"FlowNote\":{\"type\":\"object\",\"description\":\"A sticky note attached to a flow for documentation and annotation\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for the note\"},\"text\":{\"type\":\"string\",\"description\":\"Content of the note\"},\"position\":{\"type\":\"object\",\"description\":\"Position of the note in the flow editor\",\"properties\":{\"x\":{\"type\":\"number\",\"description\":\"X coordinate\"},\"y\":{\"type\":\"number\",\"description\":\"Y coordinate\"}},\"required\":[\"x\",\"y\"]},\"size\":{\"type\":\"object\",\"description\":\"Size of the note in the flow editor\",\"properties\":{\"width\":{\"type\":\"number\",\"description\":\"Width in pixels\"},\"height\":{\"type\":\"number\",\"description\":\"Height in pixels\"}},\"required\":[\"width\",\"height\"]},\"color\":{\"type\":\"string\",\"description\":\"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled.\"},\"type\":{\"type\":\"string\",\"enum\":[\"free\",\"group\"],\"description\":\"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead.\"},\"locked\":{\"type\":\"boolean\",\"default\":false,\"description\":\"Whether the note is locked and cannot be edited or moved\"},\"contained_node_ids\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"For group notes, the IDs of nodes contained within this group\"}},\"required\":[\"id\",\"text\",\"color\",\"type\"]},\"FlowGroup\":{\"type\":\"object\",\"description\":\"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Display name for this group\"},\"note\":{\"type\":\"string\",\"description\":\"Markdown note shown below the group header\"},\"autocollapse\":{\"type\":\"boolean\",\"default\":false,\"description\":\"If true, this group is collapsed by default in the flow editor. UI hint only.\"},\"start_id\":{\"type\":\"string\",\"description\":\"ID of the first flow module in this group (topological entry point)\"},\"end_id\":{\"type\":\"string\",\"description\":\"ID of the last flow module in this group (topological exit point)\"},\"color\":{\"type\":\"string\",\"description\":\"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one.\"}},\"required\":[\"start_id\",\"end_id\"]},\"RetryIf\":{\"type\":\"object\",\"description\":\"Conditional retry based on error or result\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables\"}},\"required\":[\"expr\"]},\"StopAfterIf\":{\"type\":\"object\",\"description\":\"Early termination condition for a module\",\"properties\":{\"skip_if_stopped\":{\"type\":\"boolean\",\"description\":\"If true, following steps are skipped when this condition triggers\"},\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop\"},\"error_message\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.\"},\"error_include_result\":{\"type\":\"boolean\",\"description\":\"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.\"}},\"required\":[\"expr\"]},\"FlowModule\":{\"type\":\"object\",\"description\":\"A single step in a flow. Can be a script, subflow, loop, or branch\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)\"},\"value\":{\"$ref\":\"#/components/schemas/FlowModuleValue\"},\"stop_after_if\":{\"description\":\"Early termination condition evaluated after this step completes\",\"$ref\":\"#/components/schemas/StopAfterIf\"},\"stop_after_all_iters_if\":{\"description\":\"For loops only - early termination condition evaluated after all iterations complete\",\"$ref\":\"#/components/schemas/StopAfterIf\"},\"skip_if\":{\"type\":\"object\",\"description\":\"Conditionally skip this step based on previous results or flow inputs\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'\"}},\"required\":[\"expr\"]},\"sleep\":{\"description\":\"Delay before executing this step (in seconds or as expression)\",\"$ref\":\"#/components/schemas/InputTransform\"},\"cache_ttl\":{\"type\":\"number\",\"description\":\"Cache duration in seconds for this step's results\"},\"cache_ignore_s3_path\":{\"type\":\"boolean\"},\"timeout\":{\"description\":\"Maximum execution time in seconds (static value or expression)\",\"$ref\":\"#/components/schemas/InputTransform\"},\"delete_after_secs\":{\"type\":\"integer\",\"description\":\"If set, delete the step's args, result and logs after this many seconds following job completion\"},\"summary\":{\"type\":\"string\",\"description\":\"Short description of what this step does\"},\"mock\":{\"type\":\"object\",\"description\":\"Mock configuration for testing without executing the actual step\",\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"If true, return mock value instead of executing\"},\"return_value\":{\"description\":\"Value to return when mocked\"}}},\"suspend\":{\"type\":\"object\",\"description\":\"Configuration for approval/resume steps that wait for user input\",\"properties\":{\"required_events\":{\"type\":\"integer\",\"description\":\"Number of approvals required before continuing\"},\"timeout\":{\"type\":\"integer\",\"description\":\"Timeout in seconds before auto-continuing or canceling\"},\"resume_form\":{\"type\":\"object\",\"description\":\"Form schema for collecting input when resuming\",\"properties\":{\"schema\":{\"type\":\"object\",\"description\":\"JSON Schema for the resume form\"}}},\"user_auth_required\":{\"type\":\"boolean\",\"description\":\"If true, only authenticated users can approve\"},\"user_groups_required\":{\"description\":\"Expression or list of groups that can approve\",\"$ref\":\"#/components/schemas/InputTransform\"},\"self_approval_disabled\":{\"type\":\"boolean\",\"description\":\"If true, the user who started the flow cannot approve\"},\"hide_cancel\":{\"type\":\"boolean\",\"description\":\"If true, hide the cancel button on the approval form\"},\"continue_on_disapprove_timeout\":{\"type\":\"boolean\",\"description\":\"If true, continue flow on timeout instead of canceling\"},\"skin\":{\"type\":\"string\",\"enum\":[\"detailed\",\"minimal\"],\"description\":\"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions\"}}},\"priority\":{\"type\":\"number\",\"description\":\"Execution priority for this step (higher numbers run first)\"},\"continue_on_error\":{\"type\":\"boolean\",\"description\":\"If true, flow continues even if this step fails\"},\"job_token_scopes\":{\"type\":\"array\",\"nullable\":true,\"items\":{\"type\":\"string\"},\"description\":\"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).\"},\"retry\":{\"description\":\"Retry configuration if this step fails\",\"$ref\":\"#/components/schemas/Retry\"},\"debouncing\":{\"description\":\"Debounce configuration for this step (EE only)\",\"type\":\"object\",\"properties\":{\"debounce_delay_s\":{\"type\":\"integer\",\"description\":\"Delay in seconds to debounce this step's executions across flow runs\"},\"debounce_key\":{\"type\":\"string\",\"description\":\"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>\"},\"debounce_args_to_accumulate\":{\"type\":\"array\",\"description\":\"Array-type arguments to accumulate across debounced executions\",\"items\":{\"type\":\"string\"}},\"max_total_debouncing_time\":{\"type\":\"integer\",\"description\":\"Maximum total time in seconds before forced execution\"},\"max_total_debounces_amount\":{\"type\":\"integer\",\"description\":\"Maximum number of debounces before forced execution\"}}}},\"required\":[\"value\",\"id\"]},\"InputTransform\":{\"description\":\"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"StaticTransform\":{\"type\":\"object\",\"description\":\"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'\",\"properties\":{\"value\":{\"description\":\"The static value. For resources, use format '$res:path/to/resource'\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\"]},\"JavascriptTransform\":{\"type\":\"object\",\"description\":\"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')\",\"properties\":{\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)\"},\"type\":{\"type\":\"string\",\"enum\":[\"javascript\"]}},\"required\":[\"expr\",\"type\"]},\"AiTransform\":{\"type\":\"object\",\"description\":\"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"ai\"]}},\"required\":[\"type\"]},\"AIProviderKind\":{\"type\":\"string\",\"description\":\"Supported AI provider types\",\"enum\":[\"openai\",\"azure_openai\",\"azure_foundry\",\"anthropic\",\"mistral\",\"deepseek\",\"googleai\",\"groq\",\"openrouter\",\"togetherai\",\"customai\",\"aws_bedrock\",\"typesafe\",\"cloudflare\"]},\"ProviderConfig\":{\"type\":\"object\",\"description\":\"Complete AI provider configuration with resource reference and model selection\",\"properties\":{\"kind\":{\"$ref\":\"#/components/schemas/AIProviderKind\"},\"resource\":{\"type\":\"string\",\"description\":\"Resource reference in format '$res:{resource_path}' pointing to provider credentials\"},\"model\":{\"type\":\"string\",\"description\":\"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')\"},\"reasoning_effort\":{\"type\":\"string\",\"description\":\"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.\"}},\"required\":[\"kind\",\"resource\",\"model\"]},\"StaticProviderTransform\":{\"type\":\"object\",\"description\":\"Static provider configuration passed directly to the AI agent\",\"properties\":{\"value\":{\"$ref\":\"#/components/schemas/ProviderConfig\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\",\"value\"]},\"ProviderTransform\":{\"description\":\"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticProviderTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticProviderTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"MemoryOff\":{\"type\":\"object\",\"description\":\"No conversation memory/context\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"off\"]}},\"required\":[\"kind\"]},\"MemoryWindow\":{\"type\":\"object\",\"description\":\"Keeps the most recent messages of the memory named by the run's memory id (or the step's\\n`memory_id`). Without a memory id the agent runs without memory.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"window\"]},\"context_length\":{\"type\":\"integer\",\"description\":\"Number of most recent messages to load and store. 0 turns memory off.\"}},\"required\":[\"kind\",\"context_length\"]},\"MemoryAuto\":{\"type\":\"object\",\"deprecated\":true,\"description\":\"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"auto\"]},\"context_length\":{\"type\":\"integer\",\"description\":\"Maximum number of messages to retain in context\"},\"memory_id\":{\"type\":\"string\",\"description\":\"Identifier for persistent memory across agent invocations\"}},\"required\":[\"kind\"]},\"MemoryCompaction\":{\"type\":\"object\",\"description\":\"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\\nits older part with a summary as the conversation approaches the model's context window.\\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\\n\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"compaction\"]},\"context_window\":{\"type\":\"integer\",\"description\":\"Overrides the context window looked up from the model, in tokens. Only a model\\nWindmill does not know needs one; those fall back to 128000.\\n\"}},\"required\":[\"kind\"]},\"MemoryMessage\":{\"type\":\"object\",\"description\":\"A single message in conversation history\",\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"user\",\"assistant\",\"system\"]},\"content\":{\"type\":\"string\"}},\"required\":[\"role\",\"content\"]},\"MemoryManual\":{\"type\":\"object\",\"deprecated\":true,\"description\":\"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.\",\"properties\":{\"kind\":{\"type\":\"string\",\"enum\":[\"manual\"]},\"messages\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/MemoryMessage\"}}},\"required\":[\"kind\",\"messages\"]},\"MemoryConfig\":{\"description\":\"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.\",\"oneOf\":[{\"$ref\":\"#/components/schemas/MemoryOff\"},{\"$ref\":\"#/components/schemas/MemoryWindow\"},{\"$ref\":\"#/components/schemas/MemoryCompaction\"},{\"$ref\":\"#/components/schemas/MemoryAuto\"},{\"$ref\":\"#/components/schemas/MemoryManual\"}],\"discriminator\":{\"propertyName\":\"kind\",\"mapping\":{\"off\":\"#/components/schemas/MemoryOff\",\"window\":\"#/components/schemas/MemoryWindow\",\"compaction\":\"#/components/schemas/MemoryCompaction\",\"auto\":\"#/components/schemas/MemoryAuto\",\"manual\":\"#/components/schemas/MemoryManual\"}}},\"StaticMemoryTransform\":{\"type\":\"object\",\"description\":\"Static memory configuration passed directly to the AI agent\",\"properties\":{\"value\":{\"$ref\":\"#/components/schemas/MemoryConfig\"},\"type\":{\"type\":\"string\",\"enum\":[\"static\"]}},\"required\":[\"type\",\"value\"]},\"MemoryTransform\":{\"description\":\"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined\",\"oneOf\":[{\"$ref\":\"#/components/schemas/StaticMemoryTransform\"},{\"$ref\":\"#/components/schemas/JavascriptTransform\"},{\"$ref\":\"#/components/schemas/AiTransform\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"static\":\"#/components/schemas/StaticMemoryTransform\",\"javascript\":\"#/components/schemas/JavascriptTransform\",\"ai\":\"#/components/schemas/AiTransform\"}}},\"FlowModuleValue\":{\"description\":\"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type\",\"oneOf\":[{\"$ref\":\"#/components/schemas/RawScript\"},{\"$ref\":\"#/components/schemas/PathScript\"},{\"$ref\":\"#/components/schemas/PathFlow\"},{\"$ref\":\"#/components/schemas/ForloopFlow\"},{\"$ref\":\"#/components/schemas/WhileloopFlow\"},{\"$ref\":\"#/components/schemas/BranchOne\"},{\"$ref\":\"#/components/schemas/BranchAll\"},{\"$ref\":\"#/components/schemas/Identity\"},{\"$ref\":\"#/components/schemas/AiAgent\"},{\"$ref\":\"#/components/schemas/AiDecision\"}],\"discriminator\":{\"propertyName\":\"type\",\"mapping\":{\"rawscript\":\"#/components/schemas/RawScript\",\"script\":\"#/components/schemas/PathScript\",\"flow\":\"#/components/schemas/PathFlow\",\"forloopflow\":\"#/components/schemas/ForloopFlow\",\"whileloopflow\":\"#/components/schemas/WhileloopFlow\",\"branchone\":\"#/components/schemas/BranchOne\",\"branchall\":\"#/components/schemas/BranchAll\",\"identity\":\"#/components/schemas/Identity\",\"aiagent\":\"#/components/schemas/AiAgent\",\"aidecision\":\"#/components/schemas/AiDecision\"}}},\"RawScript\":{\"type\":\"object\",\"description\":\"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"content\":{\"type\":\"string\",\"description\":\"The script source code. Should export a 'main' function\"},\"language\":{\"type\":\"string\",\"description\":\"Programming language for this script\",\"enum\":[\"deno\",\"bun\",\"bunnative\",\"python3\",\"go\",\"bash\",\"powershell\",\"postgresql\",\"mysql\",\"bigquery\",\"snowflake\",\"mssql\",\"oracledb\",\"graphql\",\"nativets\",\"php\",\"rust\",\"ansible\",\"csharp\",\"nu\",\"java\",\"ruby\",\"rlang\",\"duckdb\"]},\"path\":{\"type\":\"string\",\"description\":\"Optional path for saving this script\"},\"lock\":{\"type\":\"string\",\"description\":\"Lock file content for dependencies\"},\"type\":{\"type\":\"string\",\"enum\":[\"rawscript\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing\"},\"concurrent_limit\":{\"type\":\"number\",\"description\":\"Maximum concurrent executions of this script\"},\"concurrency_time_window_s\":{\"type\":\"number\",\"description\":\"Time window for concurrent_limit\"},\"custom_concurrency_key\":{\"type\":\"string\",\"description\":\"Custom key for grouping concurrent executions\"},\"is_trigger\":{\"type\":\"boolean\",\"description\":\"If true, this script is a trigger that can start the flow\"},\"assets\":{\"type\":\"array\",\"description\":\"External resources this script accesses (S3 objects, resources, etc.)\",\"items\":{\"type\":\"object\",\"required\":[\"path\",\"kind\"],\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Path to the asset\"},\"kind\":{\"type\":\"string\",\"description\":\"Type of asset\",\"enum\":[\"s3object\",\"resource\",\"ducklake\",\"datatable\",\"volume\",\"dbt\"]},\"access_type\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Access level for this asset\",\"enum\":[\"r\",\"w\",\"rw\"]},\"alt_access_type\":{\"type\":\"string\",\"nullable\":true,\"description\":\"Alternative access level\",\"enum\":[\"r\",\"w\",\"rw\"]}}}}},\"required\":[\"type\",\"content\",\"language\",\"input_transforms\"]},\"PathScript\":{\"type\":\"object\",\"description\":\"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"path\":{\"type\":\"string\",\"description\":\"Path to the script in the workspace (e.g., 'f/scripts/send_email')\"},\"hash\":{\"type\":\"string\",\"description\":\"Optional specific version hash of the script to use\"},\"type\":{\"type\":\"string\",\"enum\":[\"script\"]},\"tag_override\":{\"type\":\"string\",\"description\":\"Override the script's default worker group tag\"},\"is_trigger\":{\"type\":\"boolean\",\"description\":\"If true, this script is a trigger that can start the flow\"}},\"required\":[\"type\",\"path\",\"input_transforms\"]},\"PathFlow\":{\"type\":\"object\",\"description\":\"Reference to an existing flow by path. Use this to call another flow as a subflow\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}},\"path\":{\"type\":\"string\",\"description\":\"Path to the flow in the workspace (e.g., 'f/flows/process_user')\"},\"type\":{\"type\":\"string\",\"enum\":[\"flow\"]}},\"required\":[\"type\",\"path\",\"input_transforms\"]},\"ForloopFlow\":{\"type\":\"object\",\"description\":\"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"iterator\":{\"description\":\"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'\",\"$ref\":\"#/components/schemas/InputTransform\"},\"skip_failures\":{\"type\":\"boolean\",\"description\":\"If true, iteration failures don't stop the loop. Failed iterations return null\"},\"type\":{\"type\":\"string\",\"enum\":[\"forloopflow\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency\"},\"parallelism\":{\"description\":\"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression\",\"$ref\":\"#/components/schemas/InputTransform\"},\"squash\":{\"type\":\"boolean\"}},\"required\":[\"modules\",\"iterator\",\"skip_failures\",\"type\"]},\"WhileloopFlow\":{\"type\":\"object\",\"description\":\"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result\",\"properties\":{\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute in each iteration\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"skip_failures\":{\"type\":\"boolean\",\"description\":\"If true, iteration failures don't stop the loop. Failed iterations return null\"},\"type\":{\"type\":\"string\",\"enum\":[\"whileloopflow\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, iterations run concurrently (use with caution in while loops)\"},\"parallelism\":{\"description\":\"Maximum number of concurrent iterations when parallel=true\",\"$ref\":\"#/components/schemas/InputTransform\"},\"squash\":{\"type\":\"boolean\"}},\"required\":[\"modules\",\"skip_failures\",\"type\"]},\"BranchOne\":{\"type\":\"object\",\"description\":\"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes\",\"properties\":{\"branches\":{\"type\":\"array\",\"description\":\"Array of branches to evaluate in order. The first branch with expr evaluating to true executes\",\"items\":{\"type\":\"object\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of this branch condition\"},\"expr\":{\"type\":\"string\",\"description\":\"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins\"},\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute if this branch's expr is true\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}}},\"required\":[\"modules\",\"expr\"]}},\"default\":{\"type\":\"array\",\"description\":\"Steps to execute if no branch expressions match\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}},\"type\":{\"type\":\"string\",\"enum\":[\"branchone\"]}},\"required\":[\"branches\",\"default\",\"type\"]},\"BranchAll\":{\"type\":\"object\",\"description\":\"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently\",\"properties\":{\"branches\":{\"type\":\"array\",\"description\":\"Array of branches that all execute (either in parallel or sequentially)\",\"items\":{\"type\":\"object\",\"properties\":{\"summary\":{\"type\":\"string\",\"description\":\"Short description of this branch's purpose\"},\"skip_failure\":{\"type\":\"boolean\",\"description\":\"If true, failure in this branch doesn't fail the entire flow\"},\"modules\":{\"type\":\"array\",\"description\":\"Steps to execute in this branch\",\"items\":{\"$ref\":\"#/components/schemas/FlowModule\"}}},\"required\":[\"modules\"]}},\"type\":{\"type\":\"string\",\"enum\":[\"branchall\"]},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, all branches execute concurrently. If false, they execute sequentially\"}},\"required\":[\"branches\",\"type\"]},\"AgentTool\":{\"type\":\"object\",\"description\":\"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')\"},\"summary\":{\"type\":\"string\",\"description\":\"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'.\"},\"description\":{\"type\":\"string\",\"description\":\"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script.\"},\"job_token_scopes\":{\"type\":\"array\",\"nullable\":true,\"items\":{\"type\":\"string\"},\"description\":\"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it.\"},\"value\":{\"$ref\":\"#/components/schemas/ToolValue\"}},\"required\":[\"id\",\"value\"]},\"ToolValue\":{\"description\":\"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference\",\"oneOf\":[{\"$ref\":\"#/components/schemas/FlowModuleTool\"},{\"$ref\":\"#/components/schemas/McpToolValue\"},{\"$ref\":\"#/components/schemas/WebsearchToolValue\"}],\"discriminator\":{\"propertyName\":\"tool_type\",\"mapping\":{\"flowmodule\":\"#/components/schemas/FlowModuleTool\",\"mcp\":\"#/components/schemas/McpToolValue\",\"websearch\":\"#/components/schemas/WebsearchToolValue\"}}},\"FlowModuleTool\":{\"description\":\"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module\",\"allOf\":[{\"type\":\"object\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"flowmodule\"]}},\"required\":[\"tool_type\"]},{\"$ref\":\"#/components/schemas/FlowModuleValue\"}]},\"WebsearchToolValue\":{\"type\":\"object\",\"description\":\"A tool implemented as a websearch tool. The AI can call this like any other websearch tool\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"websearch\"]}},\"required\":[\"tool_type\"]},\"McpToolValue\":{\"type\":\"object\",\"description\":\"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"mcp\"]},\"resource_path\":{\"type\":\"string\",\"description\":\"Path to the MCP resource/server configuration\"},\"include_tools\":{\"type\":\"array\",\"description\":\"Whitelist of specific tools to include from this MCP server\",\"items\":{\"type\":\"string\"}},\"exclude_tools\":{\"type\":\"array\",\"description\":\"Blacklist of tools to exclude from this MCP server\",\"items\":{\"type\":\"string\"}}},\"required\":[\"tool_type\",\"resource_path\"]},\"AiAgent\":{\"type\":\"object\",\"description\":\"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Input parameters for the AI agent mapped to their values\",\"properties\":{\"provider\":{\"$ref\":\"#/components/schemas/ProviderTransform\"},\"output_type\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n\"},\"user_message\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"The user's prompt/message to the AI agent. Supports variable interpolation with\\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\\nthe prompt; image output always needs it.\\n\"},\"system_prompt\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"System instructions that guide the AI's behavior, persona, and response style. Optional.\"},\"streaming\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n\"},\"memory\":{\"$ref\":\"#/components/schemas/MemoryTransform\"},\"memory_id\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Names the memory this step reads and writes, overriding the memory id the run\\nwas started with (the chat conversation, an app chat session or the `memory_id` run\\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\\nkey. When it evaluates to an empty value the agent runs without memory. Read only\\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\\nolder `auto` or `manual` memory reads neither history input.\\n\"},\"previous_messages\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\\nand the user message. Read only while `memory` is off or absent: managed memory\\nignores it, and an older `auto` or `manual` memory reads neither history input.\\n\"},\"output_schema\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n\"},\"user_attachments\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n\"},\"enabled_tools\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Array of strings naming which of the tools configured in `tools` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n\"},\"max_completion_tokens\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n\"},\"temperature\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n\"},\"max_iterations\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n\"},\"model\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Only on a step linked to a saved agent (see `agent`): replaces the model\\nsaved on the agent for this step's runs, on the agent's own provider resource. An\\nempty value keeps the saved model. Set it to an expression such as\\n`flow_input.model` to choose the model per run.\\n\"},\"reasoning_effort\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning\\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\\ndefault. Leave the input out to keep the saved effort, which holds only while the\\nstep runs the saved model. A step that is not linked sets both inside `provider`.\\n\"}}},\"tools\":{\"type\":\"array\",\"description\":\"Array of tools the agent can use. The agent decides which tools to call based on the task\",\"items\":{\"$ref\":\"#/components/schemas/AgentTool\"}},\"type\":{\"type\":\"string\",\"enum\":[\"aiagent\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)\"},\"omit_output_from_conversation\":{\"type\":\"boolean\",\"default\":false,\"description\":\"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.\"},\"agent\":{\"type\":\"string\",\"description\":\"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\\nand, optionally, the `model` and `reasoning_effort` overrides of what the agent saved.\\n\"},\"tool_inputs\":{\"type\":\"object\",\"description\":\"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n\",\"additionalProperties\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/InputTransform\"}}},\"parallel\":{\"type\":\"boolean\",\"description\":\"If true, the agent can execute multiple tool calls in parallel\"}},\"required\":[\"type\",\"input_transforms\"]},\"AiDecision\":{\"type\":\"object\",\"description\":\"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\\nstate with calibrated probabilities, instead of generating text.\\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\\nsupplies the state.\\n\",\"properties\":{\"input_transforms\":{\"type\":\"object\",\"description\":\"Input parameters for the decision mapped to their values\",\"properties\":{\"provider\":{\"$ref\":\"#/components/schemas/ProviderTransform\"},\"state\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"What the questions are asked about: a string, an object or an array of strings.\\nAn object with descriptive keys holding only what the questions need works best.\\nExample: { message: flow_input.message, plan: results.a.plan }\\n\"},\"questions\":{\"allOf\":[{\"$ref\":\"#/components/schemas/InputTransform\"}],\"description\":\"Object mapping each question name to { type, instructions, criteria }, where type is:\\n- 'choice': criteria maps each option to its description (up to 255); the answer\\n has choice, probabilities and confidence\\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\\n has score, legend, probabilities and confidence\\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\\n noul, the probability of yes (0 to 1)\\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\\n\"}},\"required\":[\"provider\",\"state\",\"questions\"]},\"type\":{\"type\":\"string\",\"enum\":[\"aidecision\"]},\"tag\":{\"type\":\"string\",\"description\":\"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)\"}},\"required\":[\"type\",\"input_transforms\"]},\"Identity\":{\"type\":\"object\",\"description\":\"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"identity\"]},\"flow\":{\"type\":\"boolean\",\"description\":\"If true, marks this as a flow identity (special handling)\"}},\"required\":[\"type\"]},\"FlowStatus\":{\"type\":\"object\",\"properties\":{\"step\":{\"type\":\"integer\"},\"modules\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/FlowStatusModule\"}},\"user_states\":{\"additionalProperties\":true},\"preprocessor_module\":{\"allOf\":[{\"$ref\":\"#/components/schemas/FlowStatusModule\"}]},\"failure_module\":{\"allOf\":[{\"$ref\":\"#/components/schemas/FlowStatusModule\"},{\"type\":\"object\",\"properties\":{\"parent_module\":{\"type\":\"string\"}}}]},\"retry\":{\"type\":\"object\",\"properties\":{\"fail_count\":{\"type\":\"integer\"},\"failed_jobs\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}}}}},\"required\":[\"step\",\"modules\",\"failure_module\"]},\"FlowStatusModule\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"WaitingForPriorSteps\",\"WaitingForEvents\",\"WaitingForExecutor\",\"InProgress\",\"Success\",\"Failure\"]},\"id\":{\"type\":\"string\"},\"job\":{\"type\":\"string\",\"format\":\"uuid\"},\"count\":{\"type\":\"integer\"},\"progress\":{\"type\":\"integer\"},\"iterator\":{\"type\":\"object\",\"properties\":{\"index\":{\"type\":\"integer\"},\"itered\":{\"type\":\"array\",\"items\":{}},\"itered_len\":{\"type\":\"integer\"},\"args\":{}}},\"flow_jobs\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"flow_jobs_success\":{\"type\":\"array\",\"items\":{\"type\":\"boolean\"}},\"flow_jobs_duration\":{\"type\":\"object\",\"properties\":{\"started_at\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"duration_ms\":{\"type\":\"array\",\"items\":{\"type\":\"integer\"}}}},\"branch_chosen\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"branch\",\"default\"]},\"branch\":{\"type\":\"integer\"}},\"required\":[\"type\"]},\"branchall\":{\"type\":\"object\",\"properties\":{\"branch\":{\"type\":\"integer\"},\"len\":{\"type\":\"integer\"}},\"required\":[\"branch\",\"len\"]},\"approvers\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"resume_id\":{\"type\":\"integer\"},\"approver\":{\"type\":\"string\"}},\"required\":[\"resume_id\",\"approver\"]}},\"failed_retries\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}},\"skipped\":{\"type\":\"boolean\"},\"agent_actions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"oneOf\":[{\"type\":\"object\",\"properties\":{\"job_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"function_name\":{\"type\":\"string\"},\"type\":{\"type\":\"string\",\"enum\":[\"tool_call\"]},\"module_id\":{\"type\":\"string\"}},\"required\":[\"job_id\",\"function_name\",\"type\",\"module_id\"]},{\"type\":\"object\",\"properties\":{\"call_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"function_name\":{\"type\":\"string\"},\"resource_path\":{\"type\":\"string\"},\"type\":{\"type\":\"string\",\"enum\":[\"mcp_tool_call\"]},\"arguments\":{\"type\":\"object\"}},\"required\":[\"call_id\",\"function_name\",\"resource_path\",\"type\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"web_search\"]}},\"required\":[\"type\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"message\"]}},\"required\":[\"content\",\"type\"]}]}},\"agent_actions_success\":{\"type\":\"array\",\"items\":{\"type\":\"boolean\"}}},\"required\":[\"type\"]}}", - "resource": "# Global draft resource & variable instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- A resource draft is a workspace item: `{ type: 'resource', path, summary?, value, isDraft }`. `value` is a CreateResource body: `{ path, value, description?, resource_type, labels? }` where the inner `value` is the resource type's data shape.\n- Reading a variable returns `{ type: 'variable', path, summary?, isSecret, isDraft }` — never its value, secret or not. `isSecret` tells you whether the value is encrypted.\n- `write_variable` takes `{ path, value?, is_secret?, description?, is_oauth?, expires_at?, labels? }`. Creating a variable needs `value` and `is_secret`; editing one needs only the fields you are changing. Omitting `value` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any `value` you did not get from the user destroys it.\n- For secret fields in a resource value, create the variable with `write_variable` and `is_secret: true`, and deploy it before the resource (see \"Secrets\" in the reference below).\n- Reference formats inside resource values: `$var:g/all/name` (global), `$var:u/user/name` (user), `$var:f/folder/name` (folder). Reference another resource with `$res:path/to/resource`. The same strings are also how a resource or variable is passed as a run argument (see the run-argument rule in the resource reference below); what they are never valid as is a variable's own value.\n- Use `search_resource_types` to discover valid `resource_type` names and their JSON Schemas. Match the resource value to that schema.\n- For OAuth resources, the `is_oauth: true` flag is managed by Windmill's OAuth flow; global mode generally creates manual resources, not OAuth ones.\n\n# Windmill resource & variable reference\n\n# Windmill Resources\n\nResources store credentials and configuration for external services.\n\n## Resource Structure\n\n```json\n{\n \"value\": {\n \"host\": \"db.example.com\",\n \"port\": 5432,\n \"user\": \"admin\",\n \"password\": \"$var:g/all/db_password\",\n \"dbname\": \"production\"\n },\n \"description\": \"Production PostgreSQL database\",\n \"resource_type\": \"postgresql\"\n}\n```\n\n## Required Fields\n\n- `value` - Object containing the resource configuration\n- `resource_type` - Name of the resource type (e.g., \"postgresql\", \"slack\")\n\n## Agents\n\nAn agent, as the Agents page lists it, is a resource of type `ai_agent`. Its value holds the\nagent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by\nlinking its path.\n\n## Variable References\n\nReference variables in resource values:\n\n```json\n{\n \"value\": {\n \"api_key\": \"$var:g/all/api_key\",\n \"secret\": \"$var:u/admin/secret\"\n }\n}\n```\n\n**Reference formats:**\n- `$var:g/all/name` - Global variable\n- `$var:u/username/name` - User variable\n- `$var:f/folder/name` - Folder variable\n\n## Secrets\n\nNever put a secret (password, API key, token) inline in a resource value. Store it in a secret variable and reference that variable as `$var:<path>`.\n\n- `$var:<path>` is a reference, not a value: it resolves to the variable's value at run time. Never invent a value for a variable.\n- A resource that references a variable needs the variable to exist first, so create or deploy the variable before the resource.\n\n## Resource References\n\nReference other resources:\n\n```json\n{\n \"value\": {\n \"database\": \"$res:f/databases/postgres\"\n }\n}\n```\n\n## Passing a Resource or Variable as a Run Argument\n\nA script or flow argument typed as a resource (schema `format: resource-<type>`) is passed as\nthe **bare string** `$res:<path>` — the whole argument value. Same for a variable, with\n`$var:<path>`. This applies everywhere job arguments are supplied: `wmill script run/preview`,\n`wmill flow run/preview`, the `runScriptByPath` / `runFlowByPath` API, a schedule's `args`, a\ntrigger's configured static args.\n\n```json\n{\n \"db\": \"$res:f/databases/postgres_prod\",\n \"api_token\": \"$var:g/all/api_token\"\n}\n```\n\nThe reference is resolved when the job runs, under the job's run-as identity — the caller for an\nordinary run, but the configured principal for a schedule, a trigger, or a runnable set to run on\nbehalf of someone else. The run fails if that identity cannot read the referenced resource or\nvariable.\n\n**Never wrap it in an object.** The resolver only rewrites a JSON value that *is* a string\nstarting with `$res:` / `$var:`; keys are never inspected. These are all wrong and are passed\nthrough to the script unchanged:\n\n```json\n{ \"db\": { \"$res\": \"f/databases/postgres_prod\" } }\n{ \"db\": { \"resource\": \"f/databases/postgres_prod\" } }\n{ \"db\": \"f/databases/postgres_prod\" }\n```\n\nThe string may sit anywhere a string can — a top-level argument, a nested object field\n(`{ \"gh_auth\": { \"token\": \"$var:g/all/gh_token\" } }`), or an array element (array elements are\nwalked only while nested at most two levels deep, and only for arrays of at most 1000 items).\nThe prefix must be on the string itself.\n\n## Common Resource Types\n\n### PostgreSQL\n```json\n{\n \"resource_type\": \"postgresql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"user\": \"postgres\",\n \"password\": \"$var:g/all/pg_password\",\n \"dbname\": \"windmill\",\n \"sslmode\": \"prefer\"\n }\n}\n```\n\n### MySQL\n```json\n{\n \"resource_type\": \"mysql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"$var:g/all/mysql_password\",\n \"database\": \"myapp\"\n }\n}\n```\n\n### Slack\n```json\n{\n \"resource_type\": \"slack\",\n \"value\": {\n \"token\": \"$var:g/all/slack_token\"\n }\n}\n```\n\n### AWS S3\n```json\n{\n \"resource_type\": \"s3\",\n \"value\": {\n \"bucket\": \"my-bucket\",\n \"region\": \"us-east-1\",\n \"accessKeyId\": \"$var:g/all/aws_access_key\",\n \"secretAccessKey\": \"$var:g/all/aws_secret_key\"\n }\n}\n```\n\n### HTTP/API\n```json\n{\n \"resource_type\": \"http\",\n \"value\": {\n \"baseUrl\": \"https://api.example.com\",\n \"headers\": {\n \"Authorization\": \"Bearer $var:g/all/api_token\"\n }\n }\n}\n```\n\n### Kafka\n```json\n{\n \"resource_type\": \"kafka\",\n \"value\": {\n \"brokers\": \"broker1:9092,broker2:9092\",\n \"sasl_mechanism\": \"PLAIN\",\n \"security_protocol\": \"SASL_SSL\",\n \"username\": \"$var:g/all/kafka_user\",\n \"password\": \"$var:g/all/kafka_password\"\n }\n}\n```\n\n### NATS\n```json\n{\n \"resource_type\": \"nats\",\n \"value\": {\n \"servers\": [\"nats://localhost:4222\"],\n \"user\": \"$var:g/all/nats_user\",\n \"password\": \"$var:g/all/nats_password\"\n }\n}\n```\n\n### MQTT\n```json\n{\n \"resource_type\": \"mqtt\",\n \"value\": {\n \"host\": \"mqtt.example.com\",\n \"port\": 8883,\n \"username\": \"$var:g/all/mqtt_user\",\n \"password\": \"$var:g/all/mqtt_password\",\n \"tls\": true\n }\n}\n```\n\n## When No Resource Type Fits\n\nThe Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service:\n\n- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both.\n- Otherwise, or when the user prefers it to syncing, propose a custom resource type named `c_<name>` holding the service's connection fields (base URL, account or region identifiers, credentials), as in \"Custom Resource Types\" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields.\n- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references.\n\n## Custom Resource Types\n\nA custom type's name starts with `c_`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: `format: resource-c_custom_api`, `RT.CCustomApi` in TypeScript, a `c_custom_api` TypedDict in Python.\n\nCreate custom resource types with JSON Schema:\n\n```json\n{\n \"name\": \"c_custom_api\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"base_url\": {\"type\": \"string\", \"format\": \"uri\"},\n \"api_key\": {\"type\": \"string\"},\n \"timeout\": {\"type\": \"integer\", \"default\": 30}\n },\n \"required\": [\"base_url\", \"api_key\"]\n },\n \"description\": \"Custom API connection\"\n}\n```\n\nSave as: `c_custom_api.resource-type.json`\n\n## OAuth Resources\n\nOAuth resources are managed through the Windmill UI and marked:\n\n```json\n{\n \"is_oauth\": true,\n \"account\": 123\n}\n```\n\nOAuth tokens are automatically refreshed by Windmill.\n\n## Using Resources in Scripts\n\n### TypeScript (Bun/Deno)\n```typescript\nexport async function main(db: RT.Postgresql) {\n // db contains the resource values\n const { host, port, user, password, dbname } = db;\n}\n```\n\n### Python\n```python\nclass postgresql(TypedDict):\n host: str\n port: int\n user: str\n password: str\n dbname: str\n\ndef main(db: postgresql):\n # db contains the resource values\n pass\n```\n\n", + "resource": "# Global draft resource & variable instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- A resource draft is a workspace item: `{ type: 'resource', path, summary?, value, isDraft }`. `value` is a CreateResource body: `{ path, value, description?, resource_type, labels? }` where the inner `value` is the resource type's data shape.\n- Reading a variable returns `{ type: 'variable', path, summary?, isSecret, isDraft }` — never its value, secret or not. `isSecret` tells you whether the value is encrypted.\n- `write_variable` takes `{ path, value?, is_secret?, description?, is_oauth?, expires_at?, value_valid_until?, labels? }`. Creating a variable needs `value` and `is_secret`; editing one needs only the fields you are changing. Omitting `value` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any `value` you did not get from the user destroys it.\n- For secret fields in a resource value, create the variable with `write_variable` and `is_secret: true`, and deploy it before the resource (see \"Secrets\" in the reference below).\n- Reference formats inside resource values: `$var:g/all/name` (global), `$var:u/user/name` (user), `$var:f/folder/name` (folder). Reference another resource with `$res:path/to/resource`. The same strings are also how a resource or variable is passed as a run argument (see the run-argument rule in the resource reference below); what they are never valid as is a variable's own value.\n- Use `search_resource_types` to discover valid `resource_type` names and their JSON Schemas. Match the resource value to that schema.\n- For OAuth resources, the `is_oauth: true` flag is managed by Windmill's OAuth flow; global mode generally creates manual resources, not OAuth ones.\n\n# Windmill resource & variable reference\n\n# Windmill Resources\n\nResources store credentials and configuration for external services.\n\n## Resource Structure\n\n```json\n{\n \"value\": {\n \"host\": \"db.example.com\",\n \"port\": 5432,\n \"user\": \"admin\",\n \"password\": \"$var:g/all/db_password\",\n \"dbname\": \"production\"\n },\n \"description\": \"Production PostgreSQL database\",\n \"resource_type\": \"postgresql\"\n}\n```\n\n## Required Fields\n\n- `value` - Object containing the resource configuration\n- `resource_type` - Name of the resource type (e.g., \"postgresql\", \"slack\")\n\n## Agents\n\nAn agent, as the Agents page lists it, is a resource of type `ai_agent`. Its value holds the\nagent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by\nlinking its path.\n\n## Variable References\n\nReference variables in resource values:\n\n```json\n{\n \"value\": {\n \"api_key\": \"$var:g/all/api_key\",\n \"secret\": \"$var:u/admin/secret\"\n }\n}\n```\n\n**Reference formats:**\n- `$var:g/all/name` - Global variable\n- `$var:u/username/name` - User variable\n- `$var:f/folder/name` - Folder variable\n\n## Secrets\n\nNever put a secret (password, API key, token) inline in a resource value. Store it in a secret variable and reference that variable as `$var:<path>`.\n\n- `$var:<path>` is a reference, not a value: it resolves to the variable's value at run time. Never invent a value for a variable.\n- A resource that references a variable needs the variable to exist first, so create or deploy the variable before the resource.\n\n## Resource References\n\nReference other resources:\n\n```json\n{\n \"value\": {\n \"database\": \"$res:f/databases/postgres\"\n }\n}\n```\n\n## Passing a Resource or Variable as a Run Argument\n\nA script or flow argument typed as a resource (schema `format: resource-<type>`) is passed as\nthe **bare string** `$res:<path>` — the whole argument value. Same for a variable, with\n`$var:<path>`. This applies everywhere job arguments are supplied: `wmill script run/preview`,\n`wmill flow run/preview`, the `runScriptByPath` / `runFlowByPath` API, a schedule's `args`, a\ntrigger's configured static args.\n\n```json\n{\n \"db\": \"$res:f/databases/postgres_prod\",\n \"api_token\": \"$var:g/all/api_token\"\n}\n```\n\nThe reference is resolved when the job runs, under the job's run-as identity — the caller for an\nordinary run, but the configured principal for a schedule, a trigger, or a runnable set to run on\nbehalf of someone else. The run fails if that identity cannot read the referenced resource or\nvariable.\n\n**Never wrap it in an object.** The resolver only rewrites a JSON value that *is* a string\nstarting with `$res:` / `$var:`; keys are never inspected. These are all wrong and are passed\nthrough to the script unchanged:\n\n```json\n{ \"db\": { \"$res\": \"f/databases/postgres_prod\" } }\n{ \"db\": { \"resource\": \"f/databases/postgres_prod\" } }\n{ \"db\": \"f/databases/postgres_prod\" }\n```\n\nThe string may sit anywhere a string can — a top-level argument, a nested object field\n(`{ \"gh_auth\": { \"token\": \"$var:g/all/gh_token\" } }`), or an array element (array elements are\nwalked only while nested at most two levels deep, and only for arrays of at most 1000 items).\nThe prefix must be on the string itself.\n\n## Common Resource Types\n\n### PostgreSQL\n```json\n{\n \"resource_type\": \"postgresql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"user\": \"postgres\",\n \"password\": \"$var:g/all/pg_password\",\n \"dbname\": \"windmill\",\n \"sslmode\": \"prefer\"\n }\n}\n```\n\n### MySQL\n```json\n{\n \"resource_type\": \"mysql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"$var:g/all/mysql_password\",\n \"database\": \"myapp\"\n }\n}\n```\n\n### Slack\n```json\n{\n \"resource_type\": \"slack\",\n \"value\": {\n \"token\": \"$var:g/all/slack_token\"\n }\n}\n```\n\n### AWS S3\n```json\n{\n \"resource_type\": \"s3\",\n \"value\": {\n \"bucket\": \"my-bucket\",\n \"region\": \"us-east-1\",\n \"accessKeyId\": \"$var:g/all/aws_access_key\",\n \"secretAccessKey\": \"$var:g/all/aws_secret_key\"\n }\n}\n```\n\n### HTTP/API\n```json\n{\n \"resource_type\": \"http\",\n \"value\": {\n \"baseUrl\": \"https://api.example.com\",\n \"headers\": {\n \"Authorization\": \"Bearer $var:g/all/api_token\"\n }\n }\n}\n```\n\n### Kafka\n```json\n{\n \"resource_type\": \"kafka\",\n \"value\": {\n \"brokers\": \"broker1:9092,broker2:9092\",\n \"sasl_mechanism\": \"PLAIN\",\n \"security_protocol\": \"SASL_SSL\",\n \"username\": \"$var:g/all/kafka_user\",\n \"password\": \"$var:g/all/kafka_password\"\n }\n}\n```\n\n### NATS\n```json\n{\n \"resource_type\": \"nats\",\n \"value\": {\n \"servers\": [\"nats://localhost:4222\"],\n \"user\": \"$var:g/all/nats_user\",\n \"password\": \"$var:g/all/nats_password\"\n }\n}\n```\n\n### MQTT\n```json\n{\n \"resource_type\": \"mqtt\",\n \"value\": {\n \"host\": \"mqtt.example.com\",\n \"port\": 8883,\n \"username\": \"$var:g/all/mqtt_user\",\n \"password\": \"$var:g/all/mqtt_password\",\n \"tls\": true\n }\n}\n```\n\n## When No Resource Type Fits\n\nThe Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service:\n\n- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both.\n- Otherwise, or when the user prefers it to syncing, propose a custom resource type named `c_<name>` holding the service's connection fields (base URL, account or region identifiers, credentials), as in \"Custom Resource Types\" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields.\n- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references.\n\n## Custom Resource Types\n\nA custom type's name starts with `c_`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: `format: resource-c_custom_api`, `RT.CCustomApi` in TypeScript, a `c_custom_api` TypedDict in Python.\n\nCreate custom resource types with JSON Schema:\n\n```json\n{\n \"name\": \"c_custom_api\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"base_url\": {\"type\": \"string\", \"format\": \"uri\"},\n \"api_key\": {\"type\": \"string\"},\n \"timeout\": {\"type\": \"integer\", \"default\": 30}\n },\n \"required\": [\"base_url\", \"api_key\"]\n },\n \"description\": \"Custom API connection\"\n}\n```\n\nSave as: `c_custom_api.resource-type.json`\n\n## OAuth Resources\n\nOAuth resources are managed through the Windmill UI and marked:\n\n```json\n{\n \"is_oauth\": true,\n \"account\": 123\n}\n```\n\nOAuth tokens are automatically refreshed by Windmill.\n\n## Using Resources in Scripts\n\n### TypeScript (Bun/Deno)\n```typescript\nexport async function main(db: RT.Postgresql) {\n // db contains the resource values\n const { host, port, user, password, dbname } = db;\n}\n```\n\n### Python\n```python\nclass postgresql(TypedDict):\n host: str\n port: int\n user: str\n password: str\n dbname: str\n\ndef main(db: postgresql):\n # db contains the resource values\n pass\n```\n\n", "app": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u/<current-user>/<name>` for bare names; only use `f/<folder>/<name>` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend/<key>/main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the TypeScript SDK. For a `python3` runnable, call `get_instructions` again with `subject: \"app\"` and `language: \"python3\"`.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id=\"root\">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**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.\n\n**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.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise<string>\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable<string>): Promise<void>\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise<any>\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise<any>\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise<any>\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise<string>\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string>\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise<any>\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise<void>\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise<void>\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise<void>\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise<number | null>\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise<boolean>\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise<void>\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise<any>\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise<any>\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise<string>\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise<void>\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise<string>\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise<DenoS3LightClientSettings>\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Uint8Array | undefined>\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Blob | undefined>\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise<S3Object>\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise<void>\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object[]>\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object>\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string[]>\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string>\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise<string>\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise<void>} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise<void>\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise<void>} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise<void>\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise<void>\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow<T>(fn: (...args: any[]) => Promise<T>): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel<T, R>(items: T[], fn: (item: T) => PromiseLike<R> | R, options?: { concurrency?: number },): Promise<R[]>\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise<void>\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement<any>\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit<DucklakeMaterializeOptions, \"uniqueKey\">,): SqlStatement<any>\n", "app.python3": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u/<current-user>/<name>` for bare names; only use `f/<folder>/<name>` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) and, for an app that stores data, its `data` setup. \"Starting a new app\" below decides the framework and when the data setup is asked. Ask the user each of its questions, suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool. `init_app` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend/<key>/main.{ts|py}` from the file tools, but you create or update them via `write_app_runnable` / `delete_app_runnable` (which take the runnable shape directly: `{ name, type, inlineScript?, path?, staticInputs? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- When a path runnable points at a draft (see \"Draft code vs deployed code\" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page.\n- The authoring reference below carries the Python SDK, for `python3` inline runnables. For a `bun` runnable, call `get_instructions` again with `subject: \"app\"` and no language.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- Use `read_workspace_item` with `type: 'app'` for a metadata summary (file paths and runnable list, no contents). Use `read_app_file` to read an individual file; large files are truncated to a head slice, so pass `offset`/`limit` to page through the rest rather than re-reading the whole file.\n- To find where a symbol or string lives across the app, call `search_app` (greps every frontend file and inline runnable, returns matching `file:line` rows) instead of reading files one by one — then `read_app_file` only the ranges you need. The loop is list (`read_workspace_item`) → locate (`search_app`) → inspect (`read_app_file` with `offset`/`limit`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id=\"root\">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`.\n\n**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.\n\n**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.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message` and `memory_id`, the conversation id, which the chat fills in: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })` without `memory_id`, it is a single run with no conversation, for a one-off question. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead of `memory_id`, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id.\n\n#### The `wmill` client is already authenticated\n\nAn inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `memory_id` when the agent keeps managed memory or `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them.\n\nInside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable.\n4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables.\n5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`.\n6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see \"Reading data as the viewer\"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# Python SDK (wmill)\n\nImport: import wmill\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe functions below are the surface to prefer. For an endpoint none of them covers,\nwmill.Windmill().get(endpoint) and .post(endpoint) issue an authenticated request against this\ninstance. What does not exist is a function name you guessed at: if it is not listed below, do\nnot call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`os.environ.get(\"WM_END_USER_EMAIL\") or os.environ.get(\"WM_EMAIL\")`. WM_END_USER_EMAIL is the app\nviewer when the run was triggered from an app and empty otherwise (both variables are always\ndefined), WM_EMAIL is the user the job is permissioned as. WM_USERNAME is the matching username.\n\ndef worker_has_internal_server() -> bool\n\ndef get_mocked_api() -> Optional[dict]\n\n# Get the HTTP client instance.\n# \n# Returns:\n# Configured httpx.Client for API requests\ndef get_client() -> httpx.Client\n\n# Make an HTTP GET request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Make an HTTP POST request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.post\n# \n# Returns:\n# HTTP response object\ndef post(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Create a new authentication token.\n# \n# Args:\n# duration: Token validity duration (default: 1 day)\n# \n# Returns:\n# New authentication token string\ndef create_token(duration = dt.timedelta(days=1)) -> str\n\n# Create a script job by path and return its job id.\n# \n# ``retry`` re-runs the job when it fails, with the policy a schedule takes,\n# e.g. ``{\"constant\": {\"attempts\": 3, \"seconds\": 10}}``. The returned id is\n# the first attempt's; each retry is a job of its own, recorded as a child of it.\ndef run_script_by_path_async(path: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a script job by hash and return its job id. See ``run_script_by_path_async`` for ``retry``.\ndef run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a flow job and return its job id.\ndef run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str\n\n# Run script by path synchronously and return its result.\ndef run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run script by hash synchronously and return its result.\ndef run_script_by_hash(hash_: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run a script on the current worker without creating a job.\n# \n# On agent workers (no internal server), falls back to running a normal\n# preview job and waiting for the result.\ndef run_inline_script_preview(content: str, language: str, args: dict = None) -> Any\n\n# Wait for a job to complete and return its result.\n# \n# Args:\n# job_id: ID of the job to wait for\n# timeout: Maximum time to wait (seconds or timedelta)\n# verbose: Enable verbose logging\n# cleanup: Register cleanup handler to cancel job on exit\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result when completed\n# \n# Raises:\n# TimeoutError: If timeout is reached\n# Exception: If job fails\ndef wait_job(job_id, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False)\n\n# Cancel a specific job by ID.\n# \n# Args:\n# job_id: UUID of the job to cancel\n# reason: Optional reason for cancellation\n# \n# Returns:\n# Response message from the cancel endpoint\ndef cancel_job(job_id: str, reason: str = None) -> str\n\n# Cancel currently running executions of the same script.\ndef cancel_running() -> dict\n\n# Get job details by ID.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job details dictionary\ndef get_job(job_id: str) -> dict\n\n# Get the root job ID for a flow hierarchy.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Root job ID\ndef get_root_job_id(job_id: str | None = None) -> dict\n\n# Get an OIDC JWT token for authentication to external services.\n# \n# Args:\n# audience: Token audience (e.g., \"vault\", \"aws\")\n# expires_in: Optional expiration time in seconds\n# \n# Returns:\n# JWT token string\ndef get_id_token(audience: str, expires_in: int | None = None) -> str\n\n# Get the status of a job.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job status: \"RUNNING\", \"WAITING\", or \"COMPLETED\"\ndef get_job_status(job_id: str) -> JobStatus\n\n# Get the result of a completed job.\n# \n# Args:\n# job_id: UUID of the completed job\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result\ndef get_result(job_id: str, assert_result_is_not_none: bool = True) -> Any\n\n# Get a variable value by path.\n# \n# Args:\n# path: Variable path in Windmill\n# \n# Returns:\n# Variable value as string\ndef get_variable(path: str) -> str\n\n# Set a variable value by path, creating it if it doesn't exist.\n# \n# Args:\n# path: Variable path in Windmill\n# value: Variable value to set\n# is_secret: Whether the variable should be secret (default: False)\ndef set_variable(path: str, value: str, is_secret: bool = False) -> None\n\n# Get a resource value by path.\n# \n# Args:\n# path: Resource path in Windmill\n# none_if_undefined: Return None instead of raising if not found\n# interpolated: if variables and resources are fully unrolled\n# \n# Returns:\n# Resource value dictionary or None\ndef get_resource(path: str, none_if_undefined: bool = False, interpolated: bool = True) -> dict | None\n\n# Set a resource value by path, creating it if it doesn't exist.\n# \n# Args:\n# value: Resource value to set\n# path: Resource path in Windmill\n# resource_type: Resource type for creation\ndef set_resource(value: Any, path: str, resource_type: str)\n\n# List resources from Windmill workspace.\n# \n# Args:\n# resource_type: Optional resource type to filter by (e.g., \"postgresql\", \"mysql\", \"s3\")\n# page: Optional page number for pagination\n# per_page: Optional number of results per page\n# \n# Returns:\n# List of resource dictionaries\ndef list_resources(resource_type: str = None, page: int = None, per_page: int = None) -> list[dict]\n\n# Set the workflow state.\n# \n# Args:\n# value: State value to set\n# path: Optional state resource path override.\ndef set_state(value: Any, path: str | None = None) -> None\n\n# Get the workflow state.\n# \n# Args:\n# path: Optional state resource path override.\n# \n# Returns:\n# State value or None if not set\ndef get_state(path: str | None = None) -> Any\n\n# Set job progress percentage (0-99).\n# \n# Args:\n# value: Progress percentage\n# job_id: Job ID (defaults to current WM_JOB_ID)\ndef set_progress(value: int, job_id: Optional[str] = None)\n\n# Get job progress percentage.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Progress value (0-100) or None if not set\ndef get_progress(job_id: Optional[str] = None) -> Any\n\n# Whether the worker running the job has received its shutdown signal.\n# \n# A draining worker waits for its current job to finish before exiting. A long-running\n# script can poll this and return early so the worker can be replaced.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# True if the worker running the job is draining\ndef worker_is_draining(job_id: Optional[str] = None) -> bool\n\n# Set the user state of a flow at a given key\ndef set_flow_user_state(key: str, value: Any) -> None\n\n# Get the user state of a flow at a given key\ndef get_flow_user_state(key: str) -> Any\n\n# Get the Windmill server version.\n# \n# Returns:\n# Version string\ndef version()\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy\n# serves object reads, writes, deletes, listing and multipart uploads of that bucket only;\n# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials,\n# which passing the resource path returns.\ndef get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Load a file from the workspace s3 bucket and returns its content as bytes.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# my_obj_content = client.load_s3_file(s3_obj)\n# file_content = my_obj_content.decode(\"utf-8\")\n# '''\ndef load_s3_file(s3object: S3Object | str, s3_resource_path: str | None) -> bytes\n\n# Load a file from the workspace s3 bucket and returns the bytes stream.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# with wmill.load_s3_file_reader(s3object, s3_resource_path) as file_reader:\n# print(file_reader.read())\n# '''\ndef load_s3_file_reader(s3object: S3Object | str, s3_resource_path: str | None) -> BufferedReader\n\n# Write a file to the workspace S3 bucket\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# \n# # for an in memory bytes array:\n# file_content = b'Hello Windmill!'\n# client.write_s3_file(s3_obj, file_content)\n# \n# # for a file:\n# with open(\"my_file.txt\", \"rb\") as my_file:\n# client.write_s3_file(s3_obj, my_file)\n# '''\ndef write_s3_file(s3object: S3Object | str | None, file_content: BufferedReader | bytes, s3_resource_path: str | None, content_type: str | None = None, content_disposition: str | None = None) -> S3Object\n\n# Permanently delete a file from the workspace S3 bucket.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# client.delete_s3_object(s3_obj)\n# '''\ndef delete_s3_object(s3object: S3Object | str, s3_resource_path: str | None = None) -> None\n\n# Sign S3 objects for use by anonymous users in public apps.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed S3 objects\ndef sign_s3_objects(s3_objects: list[S3Object | str], expiry_secs: int | None = None) -> list[S3Object]\n\n# Sign a single S3 object for use by anonymous users in public apps.\n# \n# Args:\n# s3_object: S3 object to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed S3 object\ndef sign_s3_object(s3_object: S3Object | str, expiry_secs: int | None = None) -> S3Object\n\n# Generate presigned public URLs for an array of S3 objects.\n# If an S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# base_url: Optional base URL for the presigned URLs (defaults to WM_BASE_URL)\n# expiry_secs: How long the signatures stay valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed public URLs\n# \n# Example:\n# >>> s3_objs = [S3Object(s3=\"/path/to/file1.txt\"), S3Object(s3=\"/path/to/file2.txt\")]\n# >>> urls = client.get_presigned_s3_public_urls(s3_objs)\ndef get_presigned_s3_public_urls(s3_objects: list[S3Object | str], base_url: str | None = None, expiry_secs: int | None = None) -> list[str]\n\n# Generate a presigned public URL for an S3 object.\n# If the S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_object: S3 object to sign\n# base_url: Optional base URL for the presigned URL (defaults to WM_BASE_URL)\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed public URL\n# \n# Example:\n# >>> s3_obj = S3Object(s3=\"/path/to/file.txt\")\n# >>> url = client.get_presigned_s3_public_url(s3_obj)\ndef get_presigned_s3_public_url(s3_object: S3Object | str, base_url: str | None = None, expiry_secs: int | None = None) -> str\n\n# Get the current user information.\n# \n# Returns:\n# User details dictionary\ndef whoami() -> dict\n\n# Get the current user information (alias for whoami).\n# \n# Returns:\n# User details dictionary\ndef user() -> dict\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef state_path() -> str\n\n# Get the workflow state.\n# \n# Returns:\n# State value or None if not set\ndef state() -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state_pickle(value: Any, path: str = 'state.pickle') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state_pickle(path: str = 'state.pickle') -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state(value: Any, path: str = 'state.json') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state(path: str = 'state.json') -> None\n\n# Get URLs needed for resuming a flow after suspension.\n# \n# Args:\n# approver: Optional approver name\n# flow_level: If True, generate resume URLs for the parent flow instead of the\n# specific step. This allows pre-approvals that can be consumed by any later\n# suspend step in the same flow.\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_resume_urls(approver: str = None, flow_level: bool = None) -> dict\n\n# Get the resume URLs bound to one ``wait_for_approval`` step of this workflow.\n# \n# Args:\n# step_key: Checkpoint key of the approval step, as passed to\n# ``wait_for_approval(key=...)``\n# approver: Optional approver name\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_approval_urls(step_key: str = 'approval', approver: str = None) -> dict\n\n# Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n# \n# **[Enterprise Edition Only]** To include form fields in the Slack approval request, use the \"Advanced -> Suspend -> Form\" functionality.\n# Learn more at: https://www.windmill.dev/docs/flows/flow_approval#form\n# \n# :param slack_resource_path: The path to the Slack resource in Windmill.\n# :type slack_resource_path: str\n# :param channel_id: The Slack channel ID where the approval request will be sent.\n# :type channel_id: str\n# :param message: Optional custom message to include in the Slack approval request.\n# :type message: str, optional\n# :param approver: Optional user ID or name of the approver for the request.\n# :type approver: str, optional\n# :param default_args_json: Optional dictionary defining or overriding the default arguments for form fields.\n# :type default_args_json: dict, optional\n# :param dynamic_enums_json: Optional dictionary overriding the enum default values of enum form fields.\n# :type dynamic_enums_json: dict, optional\n# \n# :raises Exception: If the function is not called within a flow or flow preview.\n# :raises Exception: If the required flow job or flow step environment variables are not set.\n# \n# :return: None\n# \n# **Usage Example:**\n# >>> client.request_interactive_slack_approval(\n# ... slack_resource_path=\"/u/alex/my_slack_resource\",\n# ... channel_id=\"admins-slack-channel\",\n# ... message=\"Please approve this request\",\n# ... approver=\"approver123\",\n# ... default_args_json={\"key1\": \"value1\", \"key2\": 42},\n# ... dynamic_enums_json={\"foo\": [\"choice1\", \"choice2\"], \"bar\": [\"optionA\", \"optionB\"]},\n# ... )\n# \n# **Notes:**\n# - This function must be executed within a Windmill flow or flow preview.\n# - The function checks for required environment variables (`WM_FLOW_JOB_ID`, `WM_FLOW_STEP_ID`) to ensure it is run in the appropriate context.\ndef request_interactive_slack_approval(slack_resource_path: str, channel_id: str, message: str = None, approver: str = None, default_args_json: dict = None, dynamic_enums_json: dict = None) -> None\n\n# Send a message to a Microsoft Teams conversation with conversation_id, where success is used to style the message\ndef send_teams_message(conversation_id: str, text: str, success: bool = True, card_block: dict = None)\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# Only meaningful on a data table under roles, and only for a role you are a\n# tenant of.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None)\n\n# Get a DuckLake client for DuckDB queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# \n# Returns:\n# DucklakeClient instance\ndef ducklake(name: str = 'main')\n\ndef init_global_client(f)\n\ndef deprecate(in_favor_of: str)\n\n# Get the current workspace ID.\n# \n# Returns:\n# Workspace ID string\ndef get_workspace() -> str\n\ndef get_version() -> str\n\n# Create a script job and return its job ID.\n# \n# Args:\n# hash_or_path: Script hash or path (determined by presence of '/')\n# args: Script arguments\n# scheduled_in_secs: Delay before execution in seconds\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Job ID string\ndef run_script_async(hash_or_path: str, args: Dict[str, Any] = None, scheduled_in_secs: int = None, tag: str = None) -> str\n\n# Run a script synchronously by hash and return its result.\n# \n# Args:\n# hash: Script hash\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_sync(hash: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Run a script synchronously by path and return its result.\n# \n# Args:\n# path: Script path\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_by_path_sync(path: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB\ndef duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars\ndef polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3\ndef boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef get_state_path() -> str\n\n# Parse resource syntax from string.\ndef parse_resource_syntax(s: str) -> Optional[str]\n\n# Parse S3 object from a `s3://<storage>/<key>` URI string (`s3:///<key>`\n# for the default storage) or S3Object format. Any other string raises\n# rather than falling back to an auto-generated key: an auto key is\n# requested by omitting the object, and a fallback would silently misplace\n# the upload on any typo.\ndef parse_s3_object(s3_object: S3Object | str) -> S3Object\n\n# Parse variable syntax from string.\ndef parse_variable_syntax(s: str) -> Optional[str]\n\n# Append a text to the result stream.\n# \n# Args:\n# text: text to append to the result stream\ndef append_to_result_stream(text: str) -> None\n\n# Stream to the result stream.\n# \n# Args:\n# stream: stream to stream to the result stream\ndef stream_result(stream) -> None\n\n# Execute a SQL query against the DataTable.\n# \n# Args:\n# sql: SQL query string with $1, $2, etc. placeholders\n# *args: Positional arguments to bind to query placeholders\n# \n# Returns:\n# SqlQuery instance for fetching results\ndef query(sql: str, *args) -> SqlQuery\n\n# Idempotently materialize the rows of `select_sql` into ducklake\n# `table` for one `partition` (or the whole table when `partition` is\n# None). Client-side equivalent of the `// materialize` engine: with\n# `unique_key` it upserts within the slice (delete-by-key + insert);\n# without it, it replaces (whole table → CREATE OR REPLACE; partition →\n# delete the partition + insert). Re-running the same slice is safe — the\n# backfill / failure-recovery contract.\n# \n# The partition value is bound as a DuckDB arg (never string-interpolated)\n# so it cannot inject SQL. `select_sql` is trusted (your own query).\ndef upsert_partition(table: str, select_sql: str, partition: str = None, unique_key: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# INSERT-only materialization (no dedup / no replace) for an immutable\n# event-log table — for one `partition`, or the whole table when\n# `partition` is None. NOTE: unlike `upsert_partition`, re-running the same\n# slice duplicates rows — use only for append-only sources.\ndef append_partition(table: str, select_sql: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Read a materialized ducklake table, optionally a single partition.\ndef read(table: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Execute query and fetch results.\n# \n# Args:\n# result_collection: Optional result collection mode\n# \n# Returns:\n# Query results\ndef fetch(result_collection: str | None = None)\n\n# Execute query and fetch first row of results.\n# \n# Returns:\n# First row of query results\ndef fetch_one()\n\n# Execute query and fetch first row of results. Return result as a scalar value.\n# \n# Returns:\n# First row of query result as a scalar value\ndef fetch_one_scalar()\n\n# Execute query and don't return any results.\n# \ndef execute()\n\n# DuckDB executor requires explicit argument types at declaration\n# These types exist in both DuckDB and Postgres\n# Check that the types exist if you plan to extend this function for other SQL engines.\ndef infer_sql_type(value) -> str\n\ndef parse_sql_client_name(name: str) -> tuple[str, Optional[str]]\n\n# Decorator that marks a function as a workflow task.\n# \n# Works in both WAC v1 (sync, HTTP-based dispatch) and WAC v2\n# (async, checkpoint/replay) modes:\n# \n# - **v2 (inside @workflow)**: dispatches as a checkpoint step.\n# - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API.\n# - **Standalone, or called from inside another v2 task**: executes the\n# function body directly. A task runs as a single job, so the tasks it\n# calls run in that same job, without their own options.\n# \n# A task runs as its own job, so its result is always encoded as JSON and\n# decoded back before the caller sees it: a ``datetime`` comes back as a\n# string, a tuple as a list.\n# \n# ``retry`` re-dispatches the task after a failure, inside ``@workflow`` only.\n# Every attempt is a step of its own (``call_api``, ``call_api#2``, ...) and\n# the wait between two of them is a durable sleep, so a retrying task holds no\n# worker while it backs off. Keys: ``attempts`` (retries after the first\n# failure, a whole number from 0 to 100), ``delay`` (seconds before the first\n# retry, sub-second delays dropped), ``multiplier`` (applied to the delay\n# after each attempt, 1 keeps it constant), ``max_delay`` (ceiling in\n# seconds). ``attempts`` is required, and an out-of-range or unknown key is\n# rejected where the policy is written.\n# \n# A workflow sleeps once per round, so tasks backing off in the same fan-out\n# wait one after another rather than together: the delay before a fan-out\n# retries is the sum of every backoff pending in it, not the longest one, and\n# it grows with both the width of the fan-out and ``attempts``. Retries with\n# no ``delay`` all go out in a single round.\n# \n# ``cache_ttl`` serves a previous result of the task for that many seconds\n# instead of running it again. A task is keyed on its step key (its name and\n# call order) and the workflow's input, not on the arguments it is called\n# with, so cache one only when whether it runs, and what it receives, follow\n# from the workflow's input alone. A ``task_script`` target is keyed on the\n# arguments it is called with. It has no effect on a ``task_flow`` target,\n# which keeps its flow's own cache policy.\n# \n# Usage::\n# \n# @task\n# async def extract_data(url: str): ...\n# \n# @task(path=\"f/external_script\", timeout=600, tag=\"gpu\")\n# async def run_external(x: int): ...\n# \n# @task(retry={\"attempts\": 3, \"delay\": 30, \"multiplier\": 2})\n# async def call_api(payload: dict): ...\ndef task(_func = None, *, path: Optional[str] = None, tag: Optional[str] = None, timeout: Optional[int] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill script.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# extract = task_script(\"f/data/extract\", timeout=600)\n# \n# @workflow\n# async def main():\n# data = await extract(url=\"https://...\")\ndef task_script(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill flow.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# pipeline = task_flow(\"f/etl/pipeline\", priority=10)\n# \n# @workflow\n# async def main():\n# result = await pipeline(input=data)\ndef task_flow(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Decorator marking an async function as a workflow-as-code entry point.\n# \n# The function must be **deterministic**: given the same inputs it must call\n# tasks in the same order on every replay. Branching on task results is fine\n# (results are replayed from checkpoint), but branching on external state\n# (current time, random values, external API calls) must use ``step()`` to\n# checkpoint the value so replays see the same result.\ndef workflow(func)\n\n# Execute ``fn`` inline and checkpoint the result.\n# \n# On replay the cached value is returned without re-executing ``fn``.\n# Use for lightweight deterministic operations (timestamps, random IDs,\n# config reads) that should not incur the overhead of a child job.\n# \n# ``fn``'s result is encoded as JSON and decoded back before it is returned,\n# so the round that runs the body sees the same types every replay sees:\n# a ``datetime`` comes back as a string, a tuple as a list.\n# \n# Called from inside a task body, ``fn`` runs in place and nothing is\n# checkpointed: a task is a single job and is never replayed.\nasync def step(name: str, fn)\n\n# Server-side sleep — suspend the workflow for the given duration without holding a worker.\n# \n# Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``.\n# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``.\nasync def sleep(seconds: int)\n\n# Suspend the workflow and wait for an external approval.\n# \n# Pass ``key`` to name the step, then ``get_approval_urls(key)`` yields the URLs\n# that resume exactly this approval — route them through your own channel.\n# Without a key the steps are named ``approval``, ``approval_2``, ...\n# \n# Returns a dict with ``value`` (form data), ``approver``, and ``approved``.\n# \n# Args:\n# timeout: Approval timeout in seconds (default 1800).\n# form: Optional form schema for the approval page.\n# self_approval: Whether the user who triggered the flow can approve it (default True).\n# key: Optional checkpoint key naming this approval step.\n# skin: ``\"minimal\"`` shows approvers only the request (form and approve/reject)\n# instead of the detailed page with the workflow's details.\n# description: Shown to approvers above the form: a string, or a rich value such as\n# ``{\"markdown\": \"...\"}``.\n# \n# Example::\n# \n# urls = await step(\"urls\", lambda: get_approval_urls(\"manager\"))\n# await step(\"notify\", lambda: send_email(urls[\"resume\"], urls[\"cancel\"]))\n# result = await wait_for_approval(key=\"manager\", timeout=3600)\nasync def wait_for_approval(timeout: int = 1800, form: dict | None = None, self_approval: bool = True, key: str | None = None, skin: Literal['detailed', 'minimal'] | None = None, description: str | dict | None = None) -> dict\n\n# Process items in parallel with optional concurrency control.\n# \n# Each item is processed by calling ``fn(item)``, which should be a @task.\n# Items are dispatched in batches of ``concurrency`` (default: all at once).\n# \n# Example::\n# \n# @task\n# async def process(item: str):\n# ...\n# \n# results = await parallel(items, process, concurrency=5)\nasync def parallel(items, fn, *, concurrency: Optional[int] = None)\n\n# Commit Kafka offsets for a trigger with auto_commit disabled.\n# \n# Args:\n# trigger_path: Path to the Kafka trigger (from event['wm_trigger']['trigger_path'])\n# topic: Kafka topic name (from event['topic'])\n# partition: Partition number (from event['partition'])\n# offset: Message offset to commit (from event['offset'])\ndef commit_kafka_offsets(trigger_path: str, topic: str, partition: int, offset: int) -> None\n\n", "datatable": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement<T> = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record<string, any>;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch<ResultCollectionT extends ResultCollection = \"last_statement_all_rows\">(\n params?: FetchParams<ResultCollectionT | ResultCollection> // The union is for auto-completion\n ): Promise<SqlResult<T, ResultCollectionT>>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<SqlResult<T, \"last_statement_first_row\">>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise<SqlResult<T, \"last_statement_first_row_scalar\">>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<void>;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n <T = any>(strings: TemplateStringsArray, ...values: any[]): SqlStatement<T>;\n query<T = any>(sql: string, ...params: any[]): SqlStatement<T>;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n", diff --git a/backend/windmill-api/src/mcp/session/gen/tools.json b/backend/windmill-api/src/mcp/session/gen/tools.json index 1cc1f19e97..da1d9cb32a 100644 --- a/backend/windmill-api/src/mcp/session/gen/tools.json +++ b/backend/windmill-api/src/mcp/session/gen/tools.json @@ -1680,11 +1680,24 @@ "type": "boolean" }, "expires_at": { - "description": "The expiration date of the variable", + "description": "When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry — see value_valid_until.\n", "type": "string", "format": "date-time", "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" }, + "value_valid_until": { + "description": "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it (1 day by default, set on the handler); never causes the variable to be deleted. Omit it to keep the current expiry, or pass null to clear one — for instance once the value has been rotated.", + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + { + "type": "null" + } + ] + }, "labels": { "type": "array", "items": { diff --git a/backend/windmill-api/src/mcp/session/items.rs b/backend/windmill-api/src/mcp/session/items.rs index 4f221180d7..c075586a40 100644 --- a/backend/windmill-api/src/mcp/session/items.rs +++ b/backend/windmill-api/src/mcp/session/items.rs @@ -363,7 +363,7 @@ fn variable_to_draft_state(variable: &Value) -> Value { "wsSpecific".into(), field("ws_specific").unwrap_or(json!(false)), ); - for key in ["account", "is_oauth", "expires_at"] { + for key in ["account", "is_oauth", "expires_at", "value_valid_until"] { put(&mut state, key, field(key)); } Value::Object(state) @@ -429,6 +429,13 @@ fn variable_draft(args: &Value, base: Option<Value>) -> Result<Value, String> { for (key, value) in extras { put(&mut draft, key, value); } + // Deploying a draft reads an absent expiry as cleared. The draft starts from the base, so a + // `null` has to remove its date rather than skip it. + if args.get("value_valid_until").is_some_and(Value::is_null) { + draft.remove("value_valid_until"); + } else { + put(&mut draft, "value_valid_until", arg("value_valid_until")); + } Ok(Value::Object(draft)) } @@ -703,6 +710,18 @@ mod tests { variable_draft(&json!({"path": "p", "is_secret": true}), Some(plain_empty)).is_err() ); + let dated = variable_to_draft_state(&json!({ + "path": "p", "value": "v", "is_secret": false, "value_valid_until": "2027-01-15T00:00:00Z", + })); + let edit = |args: Value| variable_draft(&args, Some(dated.clone())).unwrap(); + assert_eq!( + edit(json!({"path": "p", "description": "new"}))["value_valid_until"], + "2027-01-15T00:00:00Z" + ); + assert!(edit(json!({"path": "p", "value_valid_until": null})) + .get("value_valid_until") + .is_none()); + let oauth = variable_to_draft_state(&json!({ "path": "p", "value": "live-token", "is_secret": true, "account": 3, "description": null, "expires_at": null, diff --git a/backend/windmill-api/src/mcp/session/workspace.rs b/backend/windmill-api/src/mcp/session/workspace.rs index 3e3cf45459..43ab2c33ec 100644 --- a/backend/windmill-api/src/mcp/session/workspace.rs +++ b/backend/windmill-api/src/mcp/session/workspace.rs @@ -499,6 +499,7 @@ pub(super) fn draft_item(kind: &str, path: &str, draft: &Value) -> Option<Value> put(&mut value, "account", field("account")); put(&mut value, "is_oauth", field("is_oauth")); put(&mut value, "expires_at", field("expires_at")); + put(&mut value, "value_valid_until", field("value_valid_until")); put(&mut value, "labels", field("labels")); put(&mut value, "ws_specific", field("wsSpecific")); item.insert("value".into(), Value::Object(value)); @@ -1972,4 +1973,11 @@ mod tests { ); assert!(draft_item("app", "u/a/s", &draft).is_none()); } + + #[test] + fn draft_item_carries_the_variable_expiry() { + let draft = json!({ "path": "u/a/v", "variable": { "value": "", "is_secret": true, "description": "" }, "value_valid_until": "2027-01-15T00:00:00Z" }); + let item = draft_item("variable", "u/a/v", &draft).unwrap(); + assert_eq!(item["value"]["value_valid_until"], "2027-01-15T00:00:00Z"); + } } diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index 67243b361e..d222188319 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -60,6 +60,7 @@ struct SettingsRow { webhook: Option<String>, error_handler: Option<Value>, success_handler: Option<Value>, + variable_expiration_handler: Option<Value>, ai_config: Option<Value>, large_file_storage: Option<Value>, git_sync: Option<Value>, @@ -298,7 +299,8 @@ pub async fn load_settings_document( ) -> Result<Map<String, Value>> { let row = sqlx::query_as::<_, SettingsRow>( r#"SELECT - auto_invite, webhook, error_handler, success_handler, ai_config, large_file_storage, + auto_invite, webhook, error_handler, success_handler, variable_expiration_handler, + ai_config, large_file_storage, git_sync, default_app, default_scripts, workspace.name AS name, mute_critical_alerts, color, operator_settings, datatable, slack_team_id, slack_name, slack_command_script, slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, deploy_ui, @@ -350,11 +352,16 @@ pub async fn load_settings_document( // In the order `wmill sync pull` has always written settings.yaml. A key that predates the // document and is not marked `always` is written only when set, as it always was; a key // added since is always written, so a pulled file states it and from then on manages it. - let entries: [(&str, Option<Value>, bool); 31] = [ + let entries: [(&str, Option<Value>, bool); 32] = [ ("auto_invite", row.auto_invite, false), ("webhook", row.webhook.map(Value::String), false), ("error_handler", row.error_handler, true), ("success_handler", row.success_handler, true), + ( + "variable_expiration_handler", + row.variable_expiration_handler, + true, + ), ("ai_config", row.ai_config, false), ("large_file_storage", row.large_file_storage, false), ("git_sync", git_sync, false), @@ -680,6 +687,7 @@ const KNOWN_KEYS: &[&str] = &[ "webhook", "error_handler", "success_handler", + "variable_expiration_handler", "ai_config", "large_file_storage", "git_sync", @@ -1059,7 +1067,12 @@ fn plan_document( if !unknown.is_empty() { warnings.push(format!("Ignored unknown settings: {}", unknown.join(", "))); } - for key in ["auto_invite", "error_handler", "success_handler"] { + for key in [ + "auto_invite", + "error_handler", + "success_handler", + "variable_expiration_handler", + ] { if desired .get(key) .is_some_and(|v| !v.is_null() && !v.is_object()) @@ -1122,6 +1135,24 @@ fn plan_document( Value::is_boolean, "a boolean", ), + ( + "variable_expiration_handler", + "muted_on_user_path", + Value::is_boolean, + "a boolean", + ), + ( + "variable_expiration_handler", + "notify_before_secs", + |v: &Value| v.as_u64().is_some_and(|n| n <= u32::MAX as u64), + "a non-negative number of seconds", + ), + ( + "variable_expiration_handler", + "remind_every_secs", + |v: &Value| v.as_u64().is_some_and(|n| n <= u32::MAX as u64), + "a non-negative number of seconds", + ), ] { let v = desired.get(parent).and_then(|p| p.get(key)); typed(&format!("{parent}.{key}"), v, ok, ty)?; @@ -1135,14 +1166,19 @@ fn plan_document( let v = normalize_protection_rules(v, &mut warnings)?; desired.insert("protection_rules".to_string(), v); } - // The endpoint stores an omitted mute flag as `false`. - if let Some(handler) = desired - .get_mut("error_handler") - .and_then(Value::as_object_mut) - { - for key in ["muted_on_cancel", "muted_on_user_path"] { - if is_null(handler.get(key)) { - handler.insert(key.to_string(), Value::Bool(false)); + // The endpoints store an omitted mute flag as `false`. + for (handler, keys) in [ + ( + "error_handler", + &["muted_on_cancel", "muted_on_user_path"][..], + ), + ("variable_expiration_handler", &["muted_on_user_path"][..]), + ] { + if let Some(handler) = desired.get_mut(handler).and_then(Value::as_object_mut) { + for key in keys { + if is_null(handler.get(*key)) { + handler.insert(key.to_string(), Value::Bool(false)); + } } } } @@ -1289,6 +1325,23 @@ fn plan_document( |v| json!({ "path": v.get("path"), "extra_args": v.get("extra_args") }), ); + // Managed only when stated, like every key added after the document. + let variable_expiration_handler = p.managed("variable_expiration_handler"); + p.simple( + "variable_expiration_handler", + variable_expiration_handler, + Target::Edit(SettingsEdit::VariableExpirationHandler), + |v| { + json!({ + "path": v.get("path"), + "extra_args": v.get("extra_args"), + "muted_on_user_path": v.get("muted_on_user_path").and_then(Value::as_bool).unwrap_or(false), + "notify_before_secs": v.get("notify_before_secs"), + "remind_every_secs": v.get("remind_every_secs"), + }) + }, + ); + let lfs = p.legacy("large_file_storage"); p.simple( "large_file_storage", @@ -2010,6 +2063,29 @@ mod tests { assert!(p.changes.is_empty(), "{:?}", keys(&p)); } + #[test] + fn variable_expiration_handler_is_managed_only_when_stated() { + let mc = WorkspaceCrypt::new("k"); + let names = DatatableNames::default(); + let mut cur = current(); + cur.insert( + "variable_expiration_handler".into(), + json!({ "path": "script/f/x", "muted_on_user_path": false }), + ); + let omitted = doc(json!({ "webhook": "https://b" })); + let p = plan_document(cur.clone(), omitted, true, &mc, &names).unwrap(); + assert!(!keys(&p).contains(&"variable_expiration_handler")); + + let same = doc(json!({ "variable_expiration_handler": { "path": "script/f/x" } })); + let p = plan_document(cur.clone(), same, false, &mc, &names).unwrap(); + assert!(p.changes.is_empty(), "{:?}", keys(&p)); + + let cleared = doc(json!({ "variable_expiration_handler": null })); + let p = plan_document(cur, cleared, false, &mc, &names).unwrap(); + assert_eq!(keys(&p), ["variable_expiration_handler"]); + assert_eq!(p.writes[0].body["path"], Value::Null); + } + #[cfg(all(feature = "private", feature = "enterprise"))] #[test] fn datatable_roles_are_named_in_the_document_and_written_by_id() { diff --git a/backend/windmill-api/src/workspaces_export.rs b/backend/windmill-api/src/workspaces_export.rs index 705c409621..46b7a7a8dd 100644 --- a/backend/windmill-api/src/workspaces_export.rs +++ b/backend/windmill-api/src/workspaces_export.rs @@ -972,9 +972,9 @@ pub(crate) async fn tarball_workspace( // would never match the variable it created and every sync would report it changed. let variables = sqlx::query_as::<_, ExportableListableVariable>(if !skip_secrets.unwrap_or(false) { - "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" + "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, value_valid_until, labels FROM variable WHERE workspace_id = $1 AND expires_at IS NULL" } else { - "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" + "SELECT workspace_id, path, value::text AS value, is_secret, description, extra_perms, NULL::int AS account, is_oauth, expires_at, value_valid_until, labels FROM variable WHERE workspace_id = $1 AND is_secret = false AND expires_at IS NULL" }) .bind(&w_id) .fetch_all(&mut *tx) diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 1fdfe72de7..4e1524580e 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -175,7 +175,13 @@ pub const DEFAULT_AI_SHARED_ARTIFACT_RETENTION_SECS: i64 = 60 * 60 * 24 * 30; pub const WM_DEPLOYERS_GROUP: &str = "wm_deployers"; /// Groups Windmill creates lazily (`ON CONFLICT DO NOTHING`) and grants permissions to before /// they exist; a member who created one first would inherit those grants. -pub const RESERVED_GROUP_NAMES: &[&str] = &["error_handler", "success_handler", "slack", "teams"]; +pub const RESERVED_GROUP_NAMES: &[&str] = &[ + "error_handler", + "success_handler", + "variable_expiration_handler", + "slack", + "teams", +]; /// A century. Every consumer has to survive `now - retention`, and the ceilings are much lower /// than an `i64`: `DateTime` subtraction panics past year 262143, and the `(<n> s)::interval` diff --git a/backend/windmill-common/src/utils.rs b/backend/windmill-common/src/utils.rs index c034edc203..074469893d 100644 --- a/backend/windmill-common/src/utils.rs +++ b/backend/windmill-common/src/utils.rs @@ -286,6 +286,13 @@ pub fn sanitize_db_error(e: sqlx::Error) -> Error { Some("23514") if db_err.constraint() == Some("variable_value_length") => { Error::BadRequest("A field exceeds its maximum length".to_string()) } + Some("23514") if db_err.constraint() == Some("variable_oauth_no_value_expiry") => { + Error::BadRequest( + "A variable linked to an OAuth account cannot have a value expiry: Windmill \ + refreshes its token" + .to_string(), + ) + } // check_violation — `proper_id` / `proper_name` and friends Some("23514") => Error::BadRequest( "Invalid path or name: it does not match the required format".to_string(), diff --git a/backend/windmill-common/src/variables.rs b/backend/windmill-common/src/variables.rs index bc015ef022..f3ee17769b 100644 --- a/backend/windmill-common/src/variables.rs +++ b/backend/windmill-common/src/variables.rs @@ -260,6 +260,7 @@ pub struct ListableVariable { pub refresh_error: Option<String>, pub is_linked: Option<bool>, pub expires_at: Option<chrono::DateTime<Utc>>, + pub value_valid_until: Option<chrono::DateTime<Utc>>, #[serde(skip_serializing_if = "Option::is_none")] pub labels: Option<Vec<String>>, /// Labels inherited from the parent folder, computed at read time. @@ -302,6 +303,8 @@ pub struct ExportableListableVariable { #[serde(skip_serializing_if = "Option::is_none")] pub expires_at: Option<chrono::DateTime<Utc>>, #[serde(skip_serializing_if = "Option::is_none")] + pub value_valid_until: Option<chrono::DateTime<Utc>>, + #[serde(skip_serializing_if = "Option::is_none")] pub labels: Option<Vec<String>>, } @@ -317,7 +320,11 @@ pub struct CreateVariable { pub description: String, pub account: Option<i32>, pub is_oauth: Option<bool>, + /// When the row itself is garbage-collected. pub expires_at: Option<chrono::DateTime<Utc>>, + /// When the value stops working. Drives the workspace's variable expiration handler; + /// never deletes the row. + pub value_valid_until: Option<chrono::DateTime<Utc>>, #[serde(default)] pub labels: Option<Vec<String>>, #[serde(default)] diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index c51f057f16..b886a8844d 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -170,12 +170,15 @@ const ERROR_HANDLER_USERNAME: &str = "error_handler"; pub const SCHEDULE_ERROR_HANDLER_USERNAME: &str = "schedule_error_handler"; const GLOBAL_ERROR_HANDLER_USERNAME: &str = "global"; const SUCCESS_HANDLER_USERNAME: &str = "success_handler"; +const VARIABLE_EXPIRATION_HANDLER_USERNAME: &str = "variable_expiration_handler"; pub const ERROR_HANDLER_USER_GROUP: &str = "g/error_handler"; pub const ERROR_HANDLER_USER_EMAIL: &str = "error_handler@windmill.dev"; pub const SCHEDULE_ERROR_HANDLER_USER_EMAIL: &str = "schedule_error_handler@windmill.dev"; pub const SUCCESS_HANDLER_USER_GROUP: &str = "g/success_handler"; pub const SUCCESS_HANDLER_USER_EMAIL: &str = "success_handler@windmill.dev"; +pub const VARIABLE_EXPIRATION_HANDLER_USER_GROUP: &str = "g/variable_expiration_handler"; +pub const VARIABLE_EXPIRATION_HANDLER_USER_EMAIL: &str = "variable_expiration_handler@windmill.dev"; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CanceledBy { @@ -3599,6 +3602,100 @@ pub async fn push_error_handler<'a, 'c, T: Serialize + Send + Sync>( return Ok(uuid); } +/// Handler arguments, so the field names are wire format. Never add the value: job args and +/// results are stored in cleartext and shown in Runs. +#[derive(Serialize)] +pub struct ExpiringVariable { + pub workspace_id: String, + pub variable_path: String, + pub description: String, + pub value_valid_until: DateTime<Utc>, + pub is_secret: bool, +} + +/// Takes and returns the caller's transaction so the claim and the push commit together. +pub(crate) async fn push_variable_expiration_handler<'c>( + db: &Pool<Postgres>, + tx: Transaction<'c, Postgres>, + w_id: &str, + (payload, tag, on_behalf_of): ( + JobPayload, + Option<String>, + Option<windmill_common::jobs::OnBehalfOf>, + ), + expiring: &ExpiringVariable, + extra_args: Option<Json<Box<RawValue>>>, +) -> windmill_common::error::Result<(Uuid, Transaction<'c, Postgres>)> { + // Serialized whole so a new `ExpiringVariable` field reaches handlers. Any writer of the + // variable controls these, so only they are neutralized: the admin's `extra_args` keep their + // `$res:` references, which is how the handler gets its token. + let mut extra = omit_untrusted_interpolation( + serde_json::from_value(serde_json::to_value(expiring)?)?, + "The following resource has been omitted for security reasons: ", + ); + + if let Some(args_v) = extra_args { + if let Ok(args_m) = serde_json::from_str::<HashMap<String, Box<RawValue>>>(args_v.get()) { + extra.extend(args_m); + } else { + return Err(error::Error::ExecutionErr( + "args of scripts needs to be dict".to_string(), + )); + } + } + + let (email, permissioned_as) = if let Some(on_behalf_of) = on_behalf_of.as_ref() { + ( + on_behalf_of.email.as_str(), + on_behalf_of.permissioned_as.clone(), + ) + } else { + ( + VARIABLE_EXPIRATION_HANDLER_USER_EMAIL, + VARIABLE_EXPIRATION_HANDLER_USER_GROUP.to_string(), + ) + }; + + let empty: HashMap<String, Box<RawValue>> = HashMap::new(); + let args = PushArgs { extra: Some(extra), args: &empty }; + push( + db, + PushIsolationLevel::Transaction(tx), + w_id, + payload, + args, + VARIABLE_EXPIRATION_HANDLER_USERNAME, + email, + permissioned_as, + Some(&format!( + "variable.expiration.{}", + expiring.variable_path.replace('/', ".") + )), + None, + None, + None, + None, + None, + None, + None, + false, + false, + None, + true, + tag, + None, + None, + None, + None, + false, + None, + None, + None, + None, + ) + .await +} + pub async fn push_success_handler<'a, 'c, T: Serialize + Send + Sync>( db: &Pool<Postgres>, job_id: Uuid, @@ -6357,6 +6454,7 @@ async fn push_inner<'c, 'd>( if !team_plan_status.premium && email != ERROR_HANDLER_USER_EMAIL && email != SCHEDULE_ERROR_HANDLER_USER_EMAIL + && email != VARIABLE_EXPIRATION_HANDLER_USER_EMAIL && email != recovery_email && email != "worker@windmill.dev" && email != SUPERADMIN_SECRET_EMAIL @@ -8886,7 +8984,8 @@ mod preset_handler_path_tests { let hub_paths: std::collections::HashMap<String, String> = serde_json::from_str(include_str!("../../../frontend/src/lib/hubPaths.json")).unwrap(); for (name, path) in hub_paths { - if path.contains("-handler-") { + // Variable expiration handlers run as their own group whatever their path. + if path.contains("-handler-") && !path.contains("variable-expiration") { assert!( is_preset_handler_path(&path), "{name}: {path} is not pinned" diff --git a/backend/windmill-queue/src/lib.rs b/backend/windmill-queue/src/lib.rs index ff93ea2665..5358960635 100644 --- a/backend/windmill-queue/src/lib.rs +++ b/backend/windmill-queue/src/lib.rs @@ -34,6 +34,7 @@ pub mod jobs; pub mod jobs_ee; pub mod jobs_oss; pub mod schedule; +pub mod variable_expiration; pub use jobs::*; pub mod flow_status; pub mod tags; diff --git a/backend/windmill-queue/src/variable_expiration.rs b/backend/windmill-queue/src/variable_expiration.rs new file mode 100644 index 0000000000..74c0eaf393 --- /dev/null +++ b/backend/windmill-queue/src/variable_expiration.rs @@ -0,0 +1,309 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2022 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! Dispatches the workspace variable expiration handler for variables coming due. + +use std::collections::{HashMap, HashSet}; + +use serde_json::value::RawValue; +use sqlx::types::Json; +use windmill_common::jobs::get_payload_tag_from_prefixed_path; +use windmill_common::utils::{report_critical_error, report_recovered_critical_error}; +use windmill_common::DB; + +use crate::jobs::{push_variable_expiration_handler, ExpiringVariable}; + +/// Lead time when the handler setting has no `notify_before_secs`. +const VARIABLE_EXPIRATION_DEFAULT_NOTIFY_BEFORE_SECS: i64 = 24 * 3600; + +/// Subtracted from `remind_every_secs` so a reminder whose interval is a multiple of the +/// sweep's period is not skipped by tick jitter. +const VARIABLE_EXPIRATION_REMINDER_SLACK_SECS: i64 = 30; + +/// Advisory lock id ensuring only one server replica sweeps at a time. Must not reuse one of +/// the other monitor pass locks (737_483_920..=737_483_925): both sides try-lock and skip. +const VARIABLE_EXPIRATION_LOCK_ID: i64 = 737_483_926; + +/// System caller only: dispatches across every workspace. A handler job that fails is not +/// re-dispatched before its next reminder, as re-running it would repeat its side effects +/// against the third party it rotates; retrying is the handler's job. +pub async fn dispatch_expiring_variables(db: &DB) { + // Transaction-scoped, not session-scoped: a session lock would go back to the pool still + // held if this future were dropped mid-pass, wedging the sweep on every replica. + let mut lock_tx = match db.begin().await { + Ok(tx) => tx, + Err(e) => { + tracing::error!("variable expiration: failed to begin lock tx: {e:#}"); + return; + } + }; + let locked: bool = match sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)") + .bind(VARIABLE_EXPIRATION_LOCK_ID) + .fetch_one(&mut *lock_tx) + .await + { + Ok(v) => v, + Err(e) => { + tracing::error!("variable expiration: advisory lock failed: {e:#}"); + return; + } + }; + if !locked { + return; + } + + dispatch_expiring_variables_inner(db).await; + + if let Err(e) = lock_tx.rollback().await { + tracing::error!("variable expiration: releasing lock failed: {e:#}"); + } +} + +async fn dispatch_expiring_variables_inner(db: &DB) { + resolve_removed_handlers(db).await; + + // No lower bound on `value_valid_until`, so a downed instance catches up. No cap either: + // everything due is tried every pass, so no workspace or kind of notice can be crowded out. + let due = sqlx::query!( + r#"SELECT v.workspace_id, v.path, v.description, v.value_valid_until AS "value_valid_until!", + v.is_secret, v.expiration_dispatched_for, v.expiration_notified_at, + ws.variable_expiration_handler->>'path' AS "handler_path!", + (ws.variable_expiration_handler->'extra_args')::text::json + AS "extra_args: Json<Box<RawValue>>" + FROM variable v + JOIN workspace_settings ws ON ws.workspace_id = v.workspace_id + JOIN workspace w ON w.id = v.workspace_id + WHERE NOT w.deleted + AND v.value_valid_until IS NOT NULL + AND (v.value_valid_until IS DISTINCT FROM v.expiration_dispatched_for + OR (v.value_valid_until > now() + AND v.expiration_notified_at <= now() - make_interval(secs => + NULLIF((ws.variable_expiration_handler->>'remind_every_secs')::bigint, 0) - $2))) + AND v.value_valid_until <= now() + make_interval(secs => + COALESCE((ws.variable_expiration_handler->>'notify_before_secs')::bigint, $1)) + AND ws.variable_expiration_handler->>'path' IS NOT NULL + AND (NOT COALESCE((ws.variable_expiration_handler->>'muted_on_user_path')::boolean, false) + OR v.path NOT LIKE 'u/%')"#, + VARIABLE_EXPIRATION_DEFAULT_NOTIFY_BEFORE_SECS, + VARIABLE_EXPIRATION_REMINDER_SLACK_SECS, + ) + .fetch_all(db) + .await; + + let due = match due { + Ok(due) => due, + Err(e) => { + tracing::error!("Error listing expiring variables: {e:#}"); + return; + } + }; + + let mut dispatched = 0usize; + // A handler fails alike for every variable of its workspace: try it once per pass. + let mut failed_this_pass: HashSet<String> = HashSet::new(); + // Hub handlers are shared by every workspace using them, so a hub outage is fetched once + // per pass rather than once per workspace. + let mut failed_hub_handlers: HashMap<String, String> = HashMap::new(); + + for row in due { + if failed_this_pass.contains(&row.workspace_id) { + continue; + } + // Resolved before the claim's transaction opens, so a pass never holds one connection + // while waiting on another. + let handler = match failed_hub_handlers.get(&row.handler_path) { + Some(error) => Err(error.clone()), + None => get_payload_tag_from_prefixed_path(&row.handler_path, db, &row.workspace_id) + .await + .map_err(|e| { + let error = format!("{e:#}"); + if row.handler_path.starts_with("script/hub/") + || row.handler_path.starts_with("flow/hub/") + { + failed_hub_handlers.insert(row.handler_path.clone(), error.clone()); + } + error + }), + }; + let handler = match handler { + Ok(handler) => handler, + Err(error) => { + failed_this_pass.insert(row.workspace_id.clone()); + record_failure(db, &row.workspace_id, &row.handler_path, &error).await; + continue; + } + }; + + // Claim and push in one transaction. The claim matches the row as it was read, so it + // loses both to a concurrent re-arm and to whichever replica got there first. + let mut tx = match db.begin().await { + Ok(tx) => tx, + Err(e) => { + tracing::error!("Error opening tx for expiring variable {}: {e:#}", row.path); + continue; + } + }; + + let claimed = sqlx::query_scalar!( + "UPDATE variable SET expiration_dispatched_for = $3, expiration_notified_at = now() + WHERE workspace_id = $1 AND path = $2 AND value_valid_until = $3 + AND expiration_dispatched_for IS NOT DISTINCT FROM $4 + AND expiration_notified_at IS NOT DISTINCT FROM $5 + RETURNING 1", + row.workspace_id, + row.path, + row.value_valid_until, + row.expiration_dispatched_for, + row.expiration_notified_at, + ) + .fetch_optional(&mut *tx) + .await; + + match claimed { + Ok(Some(_)) => {} + Ok(None) => continue, + Err(e) => { + tracing::error!("Error claiming expiring variable {}: {e:#}", row.path); + continue; + } + } + + let expiring = ExpiringVariable { + workspace_id: row.workspace_id.clone(), + variable_path: row.path.clone(), + description: row.description, + value_valid_until: row.value_valid_until, + is_secret: row.is_secret, + }; + + let pushed = push_variable_expiration_handler( + db, + tx, + &row.workspace_id, + handler, + &expiring, + row.extra_args, + ) + .await; + + let tx = match pushed { + Ok((_job_id, tx)) => tx, + Err(e) => { + // Dropping the tx un-claims the variable, so the next pass retries it. + failed_this_pass.insert(row.workspace_id.clone()); + record_failure(db, &row.workspace_id, &row.handler_path, &format!("{e:#}")).await; + continue; + } + }; + + if let Err(e) = tx.commit().await { + tracing::error!("Error committing dispatch for {}: {e:#}", row.path); + continue; + } + windmill_common::feature_usage::log_feature_usage( + "variable_expiration", + "dispatched", + if row.is_secret { "secret" } else { "plain" }, + ); + dispatched += 1; + recover(db, &row.workspace_id, &row.handler_path).await; + } + + if dispatched > 0 { + tracing::info!("Dispatched {dispatched} variable expiration handler job(s)"); + } +} + +/// Alerts once per failure, not per pass: the alert is resolved when the handler next starts. +async fn record_failure(db: &DB, w_id: &str, handler_path: &str, error: &str) { + let newly_failing = sqlx::query_scalar!( + "UPDATE workspace_settings SET variable_expiration_failed_at = now() + WHERE workspace_id = $1 AND variable_expiration_failed_at IS NULL + RETURNING 1", + w_id, + ) + .fetch_optional(db) + .await; + match newly_failing { + Ok(Some(_)) => { + report_critical_error( + format!( + "The variable expiration handler {handler_path} of workspace {w_id} failed to \ + start, so variables in this workspace are not being notified. It is retried \ + on every check, and this alert is resolved once it starts: {error}" + ), + db.clone(), + Some(w_id), + Some(&alert_resource(w_id)), + ) + .await + } + Ok(None) => {} + Err(e) => { + tracing::error!("Error recording variable expiration handler failure of {w_id}: {e:#}") + } + } +} + +/// Tags a failing handler's critical alerts, so they can be resolved together. +fn alert_resource(w_id: &str) -> String { + format!("variable_expiration_handler:{w_id}") +} + +/// A removed handler has nothing left to retry, so its failure would never be resolved. +async fn resolve_removed_handlers(db: &DB) { + let removed = sqlx::query_scalar!( + "UPDATE workspace_settings SET variable_expiration_failed_at = NULL + WHERE variable_expiration_failed_at IS NOT NULL AND variable_expiration_handler IS NULL + RETURNING workspace_id", + ) + .fetch_all(db) + .await; + match removed { + Ok(removed) => { + for w_id in removed { + report_recovered_critical_error( + format!("The variable expiration handler of workspace {w_id} was removed"), + db.clone(), + Some(&w_id), + Some(&alert_resource(&w_id)), + ) + .await; + } + } + Err(e) => tracing::error!("Error resolving removed variable expiration handlers: {e:#}"), + } +} + +async fn recover(db: &DB, w_id: &str, handler_path: &str) { + let cleared = sqlx::query_scalar!( + "UPDATE workspace_settings SET variable_expiration_failed_at = NULL + WHERE workspace_id = $1 AND variable_expiration_failed_at IS NOT NULL + RETURNING 1", + w_id, + ) + .fetch_optional(db) + .await; + match cleared { + Ok(Some(_)) => { + report_recovered_critical_error( + format!( + "The variable expiration handler {handler_path} of workspace {w_id} started again" + ), + db.clone(), + Some(w_id), + Some(&alert_resource(w_id)), + ) + .await + } + Ok(None) => {} + Err(e) => { + tracing::error!("Error clearing variable expiration handler failure of {w_id}: {e:#}") + } + } +} diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index 76e21908cd..7d85fa59ce 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -149,6 +149,7 @@ async fn list_variables( "resource.path IS NOT NULL as is_linked", "account.refresh_token != '' as is_refreshed", "variable.expires_at", + "variable.value_valid_until", "variable.labels", "folder_labels(variable.workspace_id, variable.path) as inherited_labels", "ws_specific.path IS NOT NULL as ws_specific", @@ -245,7 +246,7 @@ async fn list_variables( for row in draft_only_rows { let v: serde_json::Value = serde_json::from_str(row.value.0.get()).unwrap_or(serde_json::Value::Null); - // VariableEditor's `VariableState`: { path, variable: { value, is_secret, description }, labels?, wsSpecific } + // VariableEditor's `VariableState`: { path, variable: { value, is_secret, description }, labels?, wsSpecific, value_valid_until? } let path = v .get("path") .and_then(|s| s.as_str()) @@ -284,6 +285,11 @@ async fn list_variables( }) }); let ws_specific = v.get("wsSpecific").and_then(|x| x.as_bool()); + let value_valid_until = v + .get("value_valid_until") + .and_then(|x| x.as_str()) + .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) + .map(|dt| dt.with_timezone(&chrono::Utc)); rows.push(ListableVariable { workspace_id: w_id.clone(), @@ -299,6 +305,7 @@ async fn list_variables( refresh_error: None, is_linked: None, expires_at: None, + value_valid_until, labels, // No deployed row to inherit folder labels from. inherited_labels: None, @@ -339,7 +346,7 @@ async fn get_variable( let variable_o = sqlx::query_as::<_, ListableVariable>( "SELECT variable.workspace_id, variable.path, variable.value::text AS value, variable.is_secret, variable.description, variable.extra_perms, variable.account, variable.is_oauth, - variable.expires_at, variable.labels, + variable.expires_at, variable.value_valid_until, variable.labels, folder_labels(variable.workspace_id, variable.path) as inherited_labels, variable.edited_at, variable.edited_by, (now() > account.expires_at) as is_expired, account.refresh_error, @@ -712,8 +719,8 @@ pub async fn create_variable_with_account( sqlx::query!( "INSERT INTO variable - (workspace_id, path, value, is_secret, description, account, is_oauth, expires_at, labels, edited_by) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", + (workspace_id, path, value, is_secret, description, account, is_oauth, expires_at, value_valid_until, labels, edited_by) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", &w_id, variable.path, value, @@ -722,6 +729,7 @@ pub async fn create_variable_with_account( account_id, variable.is_oauth.unwrap_or(false), variable.expires_at, + variable.value_valid_until, variable.labels.as_deref() as Option<&[String]>, &authed.username ) @@ -1122,6 +1130,13 @@ struct EditVariable { description: Option<String>, labels: Option<Vec<String>>, ws_specific: Option<bool>, + /// Absent leaves the stored expiry alone and `null` clears it, so a partial update + /// never clears it by omission. + #[serde( + default, + deserialize_with = "windmill_common::more_serde::double_option" + )] + value_valid_until: Option<Option<chrono::DateTime<chrono::Utc>>>, } #[derive(Deserialize)] @@ -1216,6 +1231,16 @@ async fn update_variable( has_sql_updates = true; } + if let Some(nvalue_valid_until) = ns.value_valid_until { + // Nothing to reset: the sweep compares the date with `expiration_dispatched_for`, so + // moving it re-arms the handler and rewriting the same date does not. + match nvalue_valid_until { + Some(ts) => sqlb.set("value_valid_until", "?".bind(&ts.to_rfc3339())), + None => sqlb.set("value_valid_until", "NULL"), + }; + has_sql_updates = true; + } + if let Some(nbool) = ns.is_secret { let old_secret = sqlx::query_scalar!( "SELECT is_secret from variable WHERE path = $1 AND workspace_id = $2", diff --git a/cli/src/commands/variable/variable.ts b/cli/src/commands/variable/variable.ts index 88ad108a1a..c79630d1de 100644 --- a/cli/src/commands/variable/variable.ts +++ b/cli/src/commands/variable/variable.ts @@ -98,6 +98,7 @@ export interface VariableFile { description: string; account?: number; is_oauth?: boolean; + value_valid_until?: string; extra_perms?: Record<string, boolean>; } @@ -162,7 +163,14 @@ export async function pushVariable( const { extra_perms: localPerms, ...localVariableBody } = localVariable; if (variable) { - if (isSuperset(localVariableBody, variable)) { + // An expiry removed from the file is sent as `null` (absent keeps the stored date), and + // `isSuperset` cannot see a removed key, so the clear is detected here. + const clearsValueValidUntil = + localVariableBody.value_valid_until === undefined && + variable.value_valid_until !== undefined && + variable.value_valid_until !== null; + + if (!clearsValueValidUntil && isSuperset(localVariableBody, variable)) { log.debug(`Variable ${remotePath} is up-to-date`); } else { log.debug(`Variable ${remotePath} is not up-to-date, updating`); @@ -188,6 +196,7 @@ export async function pushVariable( ...localVariableBody, is_secret: nextIsSecret, ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}), + ...(clearsValueValidUntil ? { value_valid_until: null } : {}), }, }); } diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index 502d0037bb..94875d2659 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -34,12 +34,21 @@ export interface SuccessHandlerConfig { extra_args?: any; } +export interface VariableExpirationHandlerConfig { + path?: string; + extra_args?: any; + muted_on_user_path?: boolean; + notify_before_secs?: number; + remind_every_secs?: number; +} + export interface SimplifiedSettings { // Grouped format (current). Explicit `null` on error_handler / success_handler // signals "clear the remote value"; `undefined` means "not managed by git". auto_invite?: AutoInviteConfig; error_handler?: ErrorHandlerConfig | null; success_handler?: SuccessHandlerConfig | null; + variable_expiration_handler?: VariableExpirationHandlerConfig | null; // Other fields webhook?: string; @@ -85,6 +94,7 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ "guest_jwt_jwks_url", "error_handler_fallback_to_instance_alerts", "add_admins_and_developers_to_forks", + "variable_expiration_handler", ] as const; // Legacy settings interface for reading old settings.yaml files diff --git a/cli/test/deploy_variable_expiry_unit.test.ts b/cli/test/deploy_variable_expiry_unit.test.ts new file mode 100644 index 0000000000..5569883121 --- /dev/null +++ b/cli/test/deploy_variable_expiry_unit.test.ts @@ -0,0 +1,60 @@ +import { expect, test } from "bun:test"; +import { deployItem } from "../windmill-utils-internal/src/deploy.ts"; + +// Workspace deploy builds the variable body field by field, so a forgotten field is +// dropped silently on promotion, and a source with no expiry must send `null`. +function recordingProvider( + captured: [string, any][], + exists: boolean, + value_valid_until: string | null, +) { + return { + existsVariable: async () => exists, + getVariable: async () => ({ + path: "f/x/v", + value: "secret", + is_secret: true, + description: "d", + value_valid_until, + }), + createVariable: async (p: any) => + void captured.push(["createVariable", p.requestBody]), + updateVariable: async (p: any) => + void captured.push(["updateVariable", p.requestBody]), + } as any; +} + +test("deployItem: carries value_valid_until, and clears it explicitly", async () => { + const captured: [string, any][] = []; + + // Written once per branch: create and update. + for (const exists of [false, true]) { + await deployItem( + recordingProvider(captured, exists, "2027-03-15T08:00:00Z"), + "variable" as any, + "f/x/v", + "src", + "dst", + ); + await deployItem( + recordingProvider(captured, exists, null), + "variable" as any, + "f/x/v", + "src", + "dst", + ); + } + + expect(captured.map(([fn]) => fn)).toEqual([ + "createVariable", + "createVariable", + "updateVariable", + "updateVariable", + ]); + expect(captured.map(([, body]) => body.value_valid_until)).toEqual([ + "2027-03-15T08:00:00Z", + null, + "2027-03-15T08:00:00Z", + null, + ]); +}); diff --git a/cli/test/variable_resource_push.test.ts b/cli/test/variable_resource_push.test.ts index b77ed48b50..67be8bf3b7 100644 --- a/cli/test/variable_resource_push.test.ts +++ b/cli/test/variable_resource_push.test.ts @@ -133,6 +133,70 @@ describe("variable", () => { }); }); + test("push clears value_valid_until when the key is dropped from the file", async () => { + await withTestBackend(async (backend, tempDir) => { + await setupWorkspaceProfile(backend); + + const uniqueId = Date.now(); + const path = `f/test/expiry_var_${uniqueId}`; + + const createResp = await backend.apiRequest!( + `/api/w/${backend.workspace}/variables/create`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + path, + value: "original_value", + is_secret: false, + description: "Expiring", + value_valid_until: "2027-03-15T08:00:00Z", + }), + } + ); + expect(createResp.status).toBeLessThan(300); + await createResp.text(); + const created = await backend.apiRequest!( + `/api/w/${backend.workspace}/variables/get/${path}` + ); + expect((await created.json()).value_valid_until).toBe("2027-03-15T08:00:00Z"); + + await writeFile( + join(tempDir, "wmill.yaml"), + `defaultTs: bun\nincludes:\n - "**"\nexcludes: []\n`, + "utf-8" + ); + await mkdir(join(tempDir, "f", "test"), { recursive: true }); + // No value_valid_until: the CLI must send an explicit null to clear it. + await writeFile( + join(tempDir, `${path}.variable.yaml`), + `value: "original_value"\nis_secret: false\ndescription: "Expiring"\n`, + "utf-8" + ); + + const pushResult = await backend.runCLICommand( + ["sync", "push", "--yes", "--includes", `${path}**`], + tempDir + ); + expect(pushResult.code).toEqual(0); + + const apiResp = await backend.apiRequest!( + `/api/w/${backend.workspace}/variables/get/${path}` + ); + expect(apiResp.status).toEqual(200); + const varData = await apiResp.json(); + expect(varData.value_valid_until ?? null).toBeNull(); + + // A clear that did not land leaves the diff pending, so push success is not proof. + const secondPush = await backend.runCLICommand( + ["sync", "push", "--yes", "--includes", `${path}**`], + tempDir + ); + expect(secondPush.code).toEqual(0); + expect(secondPush.stdout).toContain("0 changes to apply"); + }); + }); + test("add creates secret by default and preserves fields on update", async () => { await withTestBackend(async (backend, tempDir) => { await setupWorkspaceProfile(backend); diff --git a/cli/windmill-utils-internal/package-lock.json b/cli/windmill-utils-internal/package-lock.json index b9508332f0..3babfd3631 100644 --- a/cli/windmill-utils-internal/package-lock.json +++ b/cli/windmill-utils-internal/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-utils-internal", - "version": "1.8.3", + "version": "1.8.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-utils-internal", - "version": "1.8.3", + "version": "1.8.4", "license": "Apache 2.0", "devDependencies": { "@types/node": "^24.2.0", diff --git a/cli/windmill-utils-internal/package.json b/cli/windmill-utils-internal/package.json index cf4138e6fc..4b3c96903d 100644 --- a/cli/windmill-utils-internal/package.json +++ b/cli/windmill-utils-internal/package.json @@ -1,6 +1,6 @@ { "name": "windmill-utils-internal", - "version": "1.8.3", + "version": "1.8.4", "description": "Internal utility functions for Windmill", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index b2c11253af..3478fa8b0b 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -617,6 +617,8 @@ export async function deployItem( is_secret: variable.is_secret, description: variable.description ?? "", labels: variable.labels, + // `null` clears; absent would keep the target's stored date. + value_valid_until: variable.value_valid_until ?? null, }, alreadyEncrypted: false, }); @@ -629,6 +631,7 @@ export async function deployItem( is_secret: variable.is_secret, description: variable.description ?? "", labels: variable.labels, + value_valid_until: variable.value_valid_until ?? null, }, }); } @@ -930,6 +933,7 @@ export async function getItemValue( value: variable.value, is_secret: variable.is_secret, description: variable.description, + value_valid_until: variable.value_valid_until ?? undefined, }; } else if (kind === "resource") { const resource = await provider.getResource({ workspace, path }); diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index 8e658eda3f..0862453020 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,10 +4,12 @@ anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick" without any identifying data leaving the instance. -It currently carries 62 registered actions across twenty-one features (`ai_session`, `ai_chat`, +It currently carries 78 registered actions across twenty-nine features (`ai_session`, `ai_chat`, `ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`, -`flow_run`, `flow_step`, `home`, `run_form`, `debugger`, `trigger`, `command_script`, -`hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`). Nearly all of the +`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `debugger`, `trigger`, `command_script`, +`hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`, `job_token_scopes`, +`worker_draining`, `worker_group`, `worker_resource_stats`, `dev_workspace_isolation`, +`slack_agent`, `variable_expiration`). Nearly all of the product is uninstrumented, so new user-facing work is the opportunity to change that. ## When to instrument diff --git a/frontend/package-lock.json b/frontend/package-lock.json index e1fa01dbaa..6034f153d4 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -110,7 +110,7 @@ "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", - "windmill-utils-internal": "1.8.3", + "windmill-utils-internal": "1.8.4", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", @@ -14719,9 +14719,9 @@ "integrity": "sha512-uHNL8F72/Tf96xF3hOHnPDjkEyqXw7fNjcPJiUhth9sTQkcwUIoJMOdwm8/cs+j9kKVRJ4tgNYMHEBLylazp6g==" }, "node_modules/windmill-utils-internal": { - "version": "1.8.3", - "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.3.tgz", - "integrity": "sha512-Lp8fVM/uHUvO6q01rIODIR46hTQ9D9R9BEiKoZHQqw9NJoy1OxhcsvX4usBbkXff/GbHlkWiQfZXCOn0ozJeKQ==", + "version": "1.8.4", + "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.4.tgz", + "integrity": "sha512-s27Di5z/vonhMLd52P4i3iILQyty6ZIXYc89CCdkKZzseE6WiX/VMwdTF4nvNCjV3xN0WhAtXR+/PBhzarU2GQ==", "license": "Apache 2.0" }, "node_modules/word-wrap": { diff --git a/frontend/package.json b/frontend/package.json index d417cee0a4..b193c05bcb 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -177,7 +177,7 @@ "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", - "windmill-utils-internal": "1.8.3", + "windmill-utils-internal": "1.8.4", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 1c718287fc..096bc290c4 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -290,7 +290,8 @@ path, value: v.value ?? '', is_secret: v.is_secret ?? false, - description: v.description ?? '' + description: v.description ?? '', + value_valid_until: v.value_valid_until ?? undefined } }) } diff --git a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte index 6d95ad0c82..bddf68fc0d 100644 --- a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte +++ b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte @@ -16,6 +16,15 @@ 'trigger_path' ] + /** Arguments the variable expiration sweep always sends. */ + const variableExpirationHandlerArgs = [ + 'workspace_id', + 'variable_path', + 'description', + 'value_valid_until', + 'is_secret' + ] + export const slackErrorHandlerHubPathEnding = '/workspace-or-schedule-error-handler-slack' </script> @@ -78,6 +87,7 @@ /** Offer the instance critical alert channels as a destination. Workspace-level * error handling only: schedules and triggers have no such setting. */ showInstanceAlerts?: boolean + customRequiresEE?: boolean } let { @@ -90,9 +100,15 @@ customTabTooltip, noMargin = false, workspace = undefined, - showInstanceAlerts = false + showInstanceAlerts = false, + customRequiresEE = true }: Props = $props() + let isVariableExpiration = $derived(errorOrRecovery === 'variableExpiration') + let handlerArgs = $derived( + isVariableExpiration ? variableExpirationHandlerArgs : errorHandlerArgs + ) + let effectiveWorkspace = $derived(workspace ?? $operatingWorkspace) // Carry the workspace onto the "create from template" route, so the handler script is // created where this handler is saved. `customScriptTemplate` already has a query string. @@ -156,7 +172,11 @@ let submitted_job = await testJobFunction({ workspace: effectiveWorkspace!, requestBody: { - hub_script_path: draft[platform].path, + // Ours are not test-runnable presets; the error handler's checks the same + // token and channel. + hub_script_path: isVariableExpiration + ? builtinHubPath('error', platform) + : draft[platform].path, channel: channel, test_msg: `This is a notification to test the connection between ${platform} and Windmill workspace '${effectiveWorkspace!}'` } @@ -250,7 +270,7 @@ $effect(() => { const { path, kind } = draft.custom path && - loadHandlerScriptArgs(path, kind, errorHandlerArgs).then( + loadHandlerScriptArgs(path, kind, handlerArgs).then( (schema) => (customHandlerSchema = schema) ) }) @@ -258,7 +278,7 @@ $effect(() => { const path = draft.slack.path path && - loadHandlerScriptArgs(path, 'script', [...errorHandlerArgs, 'slack']).then( + loadHandlerScriptArgs(path, 'script', [...handlerArgs, 'slack']).then( (schema) => (slackHandlerSchema = schema) ) }) @@ -269,7 +289,9 @@ {#snippet children({ item })} <ToggleButton label="Slack" value="slack" {item} disabled={!isEditable} /> <ToggleButton label="Teams" value="teams" {item} disabled={!isEditable} /> - <ToggleButton label="Email" value="email" {item} disabled={!isEditable} /> + {#if !isVariableExpiration} + <ToggleButton label="Email" value="email" {item} disabled={!isEditable} /> + {/if} <ToggleButton label="Custom" value="custom" @@ -294,7 +316,7 @@ <div class="flex flex-col gap-1"> <div class="flex flex-row"> <ScriptPicker - disabled={!isEditable || !$enterpriseLicense} + disabled={!isEditable || (customRequiresEE && !$enterpriseLicense)} kinds={['script', 'failure']} allowFlow={true} bind:scriptPath={draft.custom.path} @@ -343,7 +365,7 @@ /> {/await} {#if customHandlerSchema && customHandlerSchema.properties && Object.keys(customHandlerSchema.properties).length === 0} - <div class="text-xs text-secondary">This error handler takes no extra arguments</div> + <div class="text-xs text-secondary">This handler takes no extra arguments</div> {/if} </div> {/if} @@ -381,6 +403,7 @@ }} bind:args={draft.slack.args} shouldHideNoInputs + compact className="text-xs" /> {/await} diff --git a/frontend/src/lib/components/VariableEditor.svelte b/frontend/src/lib/components/VariableEditor.svelte index d2af0187bc..a308237f5a 100644 --- a/frontend/src/lib/components/VariableEditor.svelte +++ b/frontend/src/lib/components/VariableEditor.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { VariableService, WorkspaceService } from '$lib/gen' + import { VariableService, WorkspaceService, type ListableVariable } from '$lib/gen' import { createEventDispatcher, onDestroy, untrack } from 'svelte' import { Button } from './common' import Drawer from './common/drawer/Drawer.svelte' @@ -29,17 +29,37 @@ import { useDraftConflictSession } from '$lib/draftConflictSession.svelte' import { isEncryptedDraftValue } from '$lib/encryptedDraft' import { setLocalDraftHint } from '$lib/localDraftHints.svelte' + import { logFeatureUsage } from '$lib/utils/featureUsage' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() const dispatch = createEventDispatcher() + // Subset of VariableDraftState (copilot/chat/global/workspaceItems.ts) — the same + // localStorage rows back both, so a field this shape omits is dropped on save. type VariableState = { path: string variable: { value: string; is_secret: boolean; description: string } labels: string[] | undefined wsSpecific: boolean + value_valid_until?: string + } + + // The deployed baseline every dirty check and save diff runs against: a field it + // leaves out reads as unchanged, so its edits are never sent. + function deployedVariableState(v: ListableVariable): VariableState { + return { + path: v.path, + variable: { + value: v.value ?? '', + is_secret: v.is_secret, + description: v.description ?? '' + }, + labels: v.labels ?? undefined, + wsSpecific: v.ws_specific ?? false, + value_valid_until: v.value_valid_until ?? undefined + } } // The "current" workspace this editor defaults New/Edit actions to. Session @@ -79,6 +99,7 @@ let initialStates: Record<string, VariableState> = $state({}) let existedInitially: Record<string, boolean> = $state({}) let extraPerms: Record<string, Record<string, boolean>> = $state({}) + let oauthLinked: Record<string, boolean> = $state({}) let selected: string | undefined = $state(undefined) let pathError = $state('') const acting = useActingUser(() => selected) @@ -224,16 +245,7 @@ decryptSecret: false, getDraft: true }) - const deployedState: VariableState = { - path: v.path, - variable: { - value: v.value ?? '', - is_secret: v.is_secret, - description: v.description ?? '' - }, - labels: v.labels ?? undefined, - wsSpecific: v.ws_specific ?? false - } + const deployedState = deployedVariableState(v) // Everything below writes shared editor state, so first make sure it is still this // variable's: the drawer stays closable while the read is out, and another variable // opened meanwhile would otherwise get this one's baseline — and with it this one's @@ -257,6 +269,7 @@ // displayed would leave those deciding on the version the user just replaced. existedInitially[ws] = !(v as any).no_deployed extraPerms[ws] = v.extra_perms ?? {} + oauthLinked[ws] = v.account != null UserDraftDbSyncer.recordRemoteSync(query, (v as any).draft_saved_at) UserDraft.seed( 'variable', @@ -332,16 +345,7 @@ const savedDraftState = (v as any).draft as VariableState | undefined // Deployed baseline as the dirty-check reference, so the banner // compares draft-vs-deployed and fires immediately when a draft exists. - const deployedState: VariableState = { - path: v.path, - variable: { - value: v.value ?? '', - is_secret: v.is_secret, - description: v.description ?? '' - }, - labels: v.labels ?? undefined, - wsSpecific: v.ws_specific ?? false - } + const deployedState = deployedVariableState(v) // A refused save leaves this tab's own version parked. `.draft` is the version // that refused it, so opening on that would quietly drop the edit the alert is // about and leave "Keep mine" offering to keep the other one. @@ -363,6 +367,7 @@ // CREATE, not update (update 404s). existedInitially[ws] = !(v as any).no_deployed extraPerms[ws] = v.extra_perms ?? {} + oauthLinked[ws] = v.account != null }) }) }) @@ -376,6 +381,7 @@ initialStates = {} existedInitially = {} extraPerms = {} + oauthLinked = {} pathError = '' acting.forgetFailures() } @@ -435,6 +441,11 @@ async function save(): Promise<void> { const dirty = dirtyWorkspaces const savedPath = (curWs ? states[curWs]?.draft?.path : undefined) ?? editPath ?? '' + // Before the loop rewrites the baselines; once per save, not per workspace. + const expiryChanged = dirty.filter( + (ws) => initialStates[ws]?.value_valid_until !== states[ws].draft?.value_valid_until + ) + const expiryNowSet = expiryChanged.some((ws) => !!states[ws].draft?.value_valid_until) try { for (const ws of dirty) { const s = states[ws].draft! @@ -452,6 +463,11 @@ ini.variable.description != s.variable.description ? s.variable.description : undefined, + // Tri-state: absent leaves the stored date alone, `null` clears it. + value_valid_until: + ini.value_valid_until != s.value_valid_until + ? (s.value_valid_until ?? null) + : undefined, labels: s.labels, ws_specific: s.wsSpecific } @@ -464,6 +480,7 @@ value: s.variable.value, is_secret: s.variable.is_secret, description: s.variable.description, + value_valid_until: s.value_valid_until, labels: s.labels, ws_specific: s.wsSpecific } @@ -480,6 +497,11 @@ // it shows up immediately instead of after the 60s TTL. invalidateWorkspacePaths(ws) } + if (expiryChanged.length > 0) { + logFeatureUsage('variable_expiration', 'expiry_edited', { + key: expiryNowSet ? 'set' : 'cleared' + }) + } sendUserToast(edit ? `Updated variable in ${dirty.length} workspace(s)` : `Created variable`) dispatch('create') onSaved?.(savedPath) @@ -567,6 +589,7 @@ bind:variable={current.variable} bind:labels={current.labels} bind:wsSpecific={current.wsSpecific} + bind:valueValidUntil={current.value_valid_until} {initialPath} deployTo={deployTo.current} can_write={can_write === true} @@ -578,6 +601,7 @@ !!initialStates[selected]?.variable.is_secret} workspace={selected} actingUser={acting.in(selected) ?? null} + oauthLinked={!!selected && !!oauthLinked[selected]} /> {/key} {/if} diff --git a/frontend/src/lib/components/VariableForm.svelte b/frontend/src/lib/components/VariableForm.svelte index e3542b9b36..8bebd55953 100644 --- a/frontend/src/lib/components/VariableForm.svelte +++ b/frontend/src/lib/components/VariableForm.svelte @@ -3,7 +3,7 @@ import LabelsInput from './LabelsInput.svelte' import Toggle from './Toggle.svelte' import Alert from './common/alert/Alert.svelte' - import { Button } from './common' + import { Button, Section } from './common' import Tooltip from './Tooltip.svelte' import Label from './Label.svelte' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' @@ -15,6 +15,7 @@ import { isOwner } from '$lib/utils' import { isEncryptedDraftValue } from '$lib/encryptedDraft' import EncryptedDraftField from './EncryptedDraftField.svelte' + import DateTimeInput from './DateTimeInput.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -32,6 +33,7 @@ variable: Variable labels: string[] | undefined wsSpecific: boolean + valueValidUntil: string | undefined deployTo: string | undefined can_write: boolean edit: boolean @@ -47,6 +49,8 @@ * refuses, rather than answering with the navigation user's rights in another * workspace. */ actingUser: UserExt | null + /** Linked to an OAuth account, whose token Windmill refreshes on its own. */ + oauthLinked?: boolean } let { @@ -56,6 +60,7 @@ variable = $bindable(), labels = $bindable(), wsSpecific = $bindable(), + valueValidUntil = $bindable(), deployTo, can_write, edit, @@ -63,7 +68,8 @@ onSecretChange, deployedSecret = false, workspace = undefined, - actingUser + actingUser, + oauthLinked = false }: Props = $props() let ws = $derived(workspace ?? $operatingWorkspace) @@ -74,6 +80,15 @@ ) ) + // Enabling seeds a date: an empty DateTimeInput still shows 12:00, which reads as set. + const DEFAULT_EXPIRY_DAYS = 90 + + function defaultValueExpiry(): string { + const d = new Date() + d.setDate(d.getDate() + DEFAULT_EXPIRY_DAYS) + return d.toISOString() + } + // Loading the deployed secret overwrites the draft row this form shares with the AI // chat, so every path that would trigger it has to be blocked while that row stages a // value — otherwise the staged one is replaced and the next deploy carries the old one. @@ -243,3 +258,44 @@ stretch the hit area over the whole row and the alert. The toggle carries its na <textarea rows="4" use:autosize bind:value={variable.description} placeholder="Used for X" ></textarea> </label> + +{#if !oauthLinked} + <Section label="Advanced" small collapsable initiallyCollapsed={!valueValidUntil}> + <Label + label="Value expiration" + tooltip="When the value stored here stops working, such as the expiry date of an API key. Ahead of it (1 day by default), Windmill runs the workspace's variable expiration handler if one is set, so the value can be rotated. The variable itself is never deleted." + > + <Toggle + size="sm" + checked={Boolean(valueValidUntil)} + disabled={!can_write} + on:change={() => (valueValidUntil = valueValidUntil ? undefined : defaultValueExpiry())} + options={{ right: 'Set a date on which this value expires' }} + /> + {#if valueValidUntil} + <span class="text-xs font-semibold text-emphasis leading-none mt-2">Expires on</span> + <!-- Unbound: DateTimeInput writes `null` when emptied, which reads as an edit, + so empty states become `undefined`. Not `clearable`: the toggle means "no expiry". --> + <DateTimeInput + value={valueValidUntil} + useDropdown + disabled={!can_write} + on:change={(e) => (valueValidUntil = e.detail ?? undefined)} + /> + <span class="text-2xs font-normal text-hint"> + {#if new Date(valueValidUntil).getTime() <= Date.now()} + This date has passed. Set a new one once the value is rotated. + {:else} + Runs the workspace's <a + href="/workspace_settings?tab=variable_expiration&workspace={ws}" + >variable expiration handler</a + > + ahead of this date, if the workspace has one{path.startsWith('u/') + ? ' and does not skip u/ paths' + : ''}. + {/if} + </span> + {/if} + </Label> + </Section> +{/if} diff --git a/frontend/src/lib/components/common/seconds/SecondsInput.svelte b/frontend/src/lib/components/common/seconds/SecondsInput.svelte index 9ca42379d4..ad4c0abee7 100644 --- a/frontend/src/lib/components/common/seconds/SecondsInput.svelte +++ b/frontend/src/lib/components/common/seconds/SecondsInput.svelte @@ -23,6 +23,10 @@ size?: ButtonType.UnifiedSize clearable?: boolean defaultValue?: number | undefined + /** For a value consumed at a coarser granularity, where seconds would have no effect. */ + hideSeconds?: boolean + /** Hides the "= N seconds" caption below the input. */ + hideTotal?: boolean onfocus?: (e: FocusEvent) => void } @@ -33,6 +37,8 @@ size = 'md', clearable = false, defaultValue = undefined, + hideSeconds = false, + hideTotal = false, onfocus }: Props = $props() @@ -193,30 +199,32 @@ ><span class="invisible">mins</span><span>{min && min > 1 ? 'mins' : 'min'}</span></span > </div> - <div class="flex items-baseline"> - <input - type="number" - class={segmentClass} - value={hasValue ? sec || 0 : ''} - placeholder="_ _" - min="0" - max="59" - {disabled} - oninput={(e) => handleInput(e, (v) => (sec = v), 59)} - onkeydown={(e) => - handleKeydown( - e, - () => sec, - (v) => (sec = v), - 59 - )} - onfocus={handleFocus} - onblur={handleBlur} - /> - <span class="text-secondary text-2xs inline-grid [&>*]:col-start-1 [&>*]:row-start-1" - ><span class="invisible">secs</span><span>{sec && sec > 1 ? 'secs' : 'sec'}</span></span - > - </div> + {#if !hideSeconds} + <div class="flex items-baseline"> + <input + type="number" + class={segmentClass} + value={hasValue ? sec || 0 : ''} + placeholder="_ _" + min="0" + max="59" + {disabled} + oninput={(e) => handleInput(e, (v) => (sec = v), 59)} + onkeydown={(e) => + handleKeydown( + e, + () => sec, + (v) => (sec = v), + 59 + )} + onfocus={handleFocus} + onblur={handleBlur} + /> + <span class="text-secondary text-2xs inline-grid [&>*]:col-start-1 [&>*]:row-start-1" + ><span class="invisible">secs</span><span>{sec && sec > 1 ? 'secs' : 'sec'}</span></span + > + </div> + {/if} </div> {#if clearable && !disabled && seconds != null && seconds !== defaultValue} <CloseButton @@ -229,11 +237,13 @@ /> {/if} </div> - {#if seconds != null} - <span class="text-2xs text-hint"> - = {seconds.toLocaleString()} second{seconds === 1 ? '' : 's'} - </span> - {:else} - <span class="text-2xs text-hint"> no time set </span> + {#if !hideTotal} + {#if seconds != null} + <span class="text-2xs text-hint"> + = {seconds.toLocaleString()} second{seconds === 1 ? '' : 's'} + </span> + {:else} + <span class="text-2xs text-hint"> no time set </span> + {/if} {/if} </div> diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index 61bdea9dc9..17cd4c8960 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -1370,6 +1370,40 @@ describe('global AI tools', () => { expect(localStorageSnapshot()).not.toContain('new-secret-token') }) + // The draft has no null, so a cleared expiry must deploy as an explicit one. + it('clears a variable value expiry through to the deploy body', async () => { + vi.mocked(VariableService.existsVariable).mockResolvedValueOnce(true) // write probe + vi.mocked(VariableService.existsVariable).mockResolvedValueOnce(true) // deploy probe + vi.mocked(VariableService.getVariable).mockResolvedValueOnce({ + path: 'f/secrets/api_key', + value: 'tok', + is_secret: false, + description: 'd', + value_valid_until: '2027-03-15T08:30:00Z' + } as any) + + await callGlobalTool('write_variable', { + path: 'f/secrets/api_key', + value_valid_until: null + }) + + expect( + getBackendDraft<any>('variable', 'f/secrets/api_key', { workspace: WORKSPACE }) + ?.value_valid_until + ).toBeUndefined() + + await callGlobalTool('deploy_workspace_item', { + type: 'variable', + path: 'f/secrets/api_key' + }) + + expect(VariableService.updateVariable).toHaveBeenCalledWith( + expect.objectContaining({ + requestBody: expect.objectContaining({ value_valid_until: null }) + }) + ) + }) + // '' means "no value staged", so there is nothing to create the secret with. it('does not create a secret variable draft that stages no value', async () => { seedBackendDraft( diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 81f1169386..c93c83eae4 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -747,6 +747,15 @@ const writeVariableSchema = variableRequestSchema.extend({ .string() .optional() .describe('The description of the variable. Omit it to keep the current description.'), + // Nullable, unlike the generated schema, so a cleared expiry differs from an omitted one. + value_valid_until: z + .string() + .datetime({ offset: true }) + .nullable() + .optional() + .describe( + "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it (1 day by default, set on the handler); never causes the variable to be deleted. Omit it to keep the current expiry, or pass null to clear one — for instance once the value has been rotated." + ), override: draftOverrideField }) @@ -2879,7 +2888,7 @@ function getResourceInstructions(): string { - Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata. - A resource draft is a workspace item: \`{ type: 'resource', path, summary?, value, isDraft }\`. \`value\` is a CreateResource body: \`{ path, value, description?, resource_type, labels? }\` where the inner \`value\` is the resource type's data shape. - Reading a variable returns \`{ type: 'variable', path, summary?, isSecret, isDraft }\` — never its value, secret or not. \`isSecret\` tells you whether the value is encrypted. -- \`write_variable\` takes \`{ path, value?, is_secret?, description?, is_oauth?, expires_at?, labels? }\`. Creating a variable needs \`value\` and \`is_secret\`; editing one needs only the fields you are changing. Omitting \`value\` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any \`value\` you did not get from the user destroys it. +- \`write_variable\` takes \`{ path, value?, is_secret?, description?, is_oauth?, expires_at?, value_valid_until?, labels? }\`. Creating a variable needs \`value\` and \`is_secret\`; editing one needs only the fields you are changing. Omitting \`value\` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any \`value\` you did not get from the user destroys it. - For secret fields in a resource value, create the variable with \`write_variable\` and \`is_secret: true\`, and deploy it before the resource (see "Secrets" in the reference below). - Reference formats inside resource values: \`$var:g/all/name\` (global), \`$var:u/user/name\` (user), \`$var:f/folder/name\` (folder). Reference another resource with \`$res:path/to/resource\`. The same strings are also how a resource or variable is passed as a run argument (see the run-argument rule in the resource reference below); what they are never valid as is a variable's own value. - Use \`search_resource_types\` to discover valid \`resource_type\` names and their JSON Schemas. Match the resource value to that schema. @@ -5781,7 +5790,8 @@ function variableToDraftState(variable: ListableVariable): VariableDraftState { // reviews. Undefined drops out of the JSON instead. account: variable.account ?? undefined, is_oauth: variable.is_oauth ?? undefined, - expires_at: variable.expires_at ?? undefined + expires_at: variable.expires_at ?? undefined, + value_valid_until: variable.value_valid_until ?? undefined } } @@ -5851,7 +5861,11 @@ function createVariableToDraftState( wsSpecific: args.ws_specific ?? base?.wsSpecific ?? false, account: args.account ?? base?.account, is_oauth: args.is_oauth ?? base?.is_oauth, - expires_at: args.expires_at ?? base?.expires_at + expires_at: args.expires_at ?? base?.expires_at, + // `null` clears and omitted keeps the base's. The draft stores a cleared expiry as + // `undefined`, since a stored draft goes through a JSON round-trip. + value_valid_until: + args.value_valid_until === null ? undefined : (args.value_valid_until ?? base?.value_valid_until) } } @@ -5870,10 +5884,16 @@ function buildVariableCreateRequestBody(draftValue: CreateVariable): CreateVaria // endpoint, and a draft stores '' when it stages no new value — so omitting `value` in // that case is what leaves the stored one untouched. A staged value is sent as-is: the // endpoint decrypts an `$encrypted:` marker and encrypts plaintext. -function buildVariableUpdateRequestBody( - draftValue: CreateVariable -): Omit<CreateVariable, 'value'> & { value?: string } { - const { value, ...rest } = structuredClone(draftValue) +function buildVariableUpdateRequestBody(draftValue: CreateVariable): Omit< + CreateVariable, + 'value' | 'value_valid_until' +> & { + value?: string + value_valid_until?: string | null +} { + const { value, value_valid_until, ...others } = structuredClone(draftValue) + // The draft holds the full state, so an absent expiry was cleared: send `null`. + const rest = { ...others, value_valid_until: value_valid_until ?? null } // A value the draft is never allowed to carry — a secret's, and an OAuth-managed one // dropped by `variableToDraftState` — reaches here as '' whenever this edit staged // none, so sending it would blank the stored value or wipe a rotating token. diff --git a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts index 7c8253684d..56fa40655d 100644 --- a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.test.ts @@ -573,6 +573,20 @@ describe('fork mode', () => { expect(entry?.valueMasked).toBe(true) }) + it('sees an expiry-only variable change', async () => { + mockComparison([comparisonDiff({ kind: 'variable', path: 'f/a/plain' })]) + vi.mocked(VariableService.getVariable).mockImplementation(async ({ workspace }: any) => ({ + path: 'f/a/plain', + is_secret: false, + value: 'same', + description: 'same', + value_valid_until: workspace === FORK ? '2027-09-09T10:00:00Z' : '2027-03-01T10:00:00Z' + })) as any + const entry = await readForkDiffEntryOne(FORK, PARENT, ['variable'], 'f/a/plain') + expect(entry?.status).toBe('modified') + expect(entry?.patch).toContain('2027-09-09') + }) + it('sees flow schema-only changes the shared projection drops', async () => { mockComparison([comparisonDiff({ kind: 'flow', path: 'f/a/fl' })]) vi.mocked(FlowService.getFlowByPath).mockImplementation(async ({ workspace }: any) => ({ diff --git a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts index 472a9e6e61..9b8d04d370 100644 --- a/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts +++ b/frontend/src/lib/components/copilot/chat/global/diffSnapshot.ts @@ -904,6 +904,7 @@ async function fetchForkSideValue( value: { description: variable.description, is_secret: variable.is_secret, + value_valid_until: variable.value_valid_until, value: VARIABLE_VALUE_PLACEHOLDER }, valueMasked: true diff --git a/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts b/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts index c53aa1b7d1..6368a27e24 100644 --- a/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts +++ b/frontend/src/lib/components/copilot/chat/global/userDraftAdapter.ts @@ -239,6 +239,7 @@ function variableDraftToWorkspaceItem(path: string, draft: VariableDraftState): account: draft.account, is_oauth: draft.is_oauth, expires_at: draft.expires_at, + value_valid_until: draft.value_valid_until, labels: draft.labels, ws_specific: draft.wsSpecific }, diff --git a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts index d08fe4fd58..949a016b65 100644 --- a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts +++ b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts @@ -108,6 +108,7 @@ export type VariableDraftState = { account?: number is_oauth?: boolean expires_at?: string + value_valid_until?: string } export type WorkspaceItem = { diff --git a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts index e4817e190c..c4acf87ffb 100644 --- a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts +++ b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts @@ -490,7 +490,8 @@ export const variableRequestSchema = z.object({ "description": z.string().describe("The description of the variable"), "account": z.number().int().describe("Ignored. A variable is linked to an OAuth account only when `createAccount` creates both.").optional(), "is_oauth": z.boolean().describe("Whether the variable is an OAuth variable").optional(), - "expires_at": z.string().datetime({ offset: true }).describe("The expiration date of the variable").optional(), + "expires_at": z.string().datetime({ offset: true }).describe("When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry \u2014 see value_valid_until.\n").optional(), + "value_valid_until": z.string().datetime({ offset: true }).describe("When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it, by the handler's `notify_before_secs` (1 day by default); never causes the variable to be deleted.\n").optional(), "labels": z.array(z.string()).optional(), "ws_specific": z.boolean().optional() }) diff --git a/frontend/src/lib/components/handlerDraft.svelte.ts b/frontend/src/lib/components/handlerDraft.svelte.ts index a1422e42ed..ac73fc1d6a 100644 --- a/frontend/src/lib/components/handlerDraft.svelte.ts +++ b/frontend/src/lib/components/handlerDraft.svelte.ts @@ -2,7 +2,7 @@ import type { ErrorHandler } from '$lib/gen' import { WORKSPACE_SLACK_BOT_TOKEN_PATH } from '$lib/consts' import hubPaths from '$lib/hubPaths.json' -export type HandlerMode = 'error' | 'recovery' | 'success' +export type HandlerMode = 'error' | 'recovery' | 'success' | 'variableExpiration' type BuiltinDestination = 'slack' | 'teams' | 'email' export type HandlerSlot = { path?: string; args: Record<string, any> } @@ -32,6 +32,10 @@ const BUILTIN_SUFFIXES: Record<HandlerMode, Record<'slack' | 'teams', string>> = success: { slack: '/schedule-success-handler-slack', teams: '/schedule-success-handler-teams' + }, + variableExpiration: { + slack: '/variable-expiration-handler-slack', + teams: '/variable-expiration-handler-teams' } } diff --git a/frontend/src/lib/components/variables/VariablesList.svelte b/frontend/src/lib/components/variables/VariablesList.svelte index 6b40eda798..c01eb5dbd4 100644 --- a/frontend/src/lib/components/variables/VariablesList.svelte +++ b/frontend/src/lib/components/variables/VariablesList.svelte @@ -50,6 +50,7 @@ Shield, Trash, Building, + CalendarClock, DollarSign, EyeOff, Circle, @@ -441,7 +442,7 @@ </tr> </Head> <tbody class="divide-y"> - {#each filteredItems as { path, value, is_secret, description, extra_perms, canWrite, account, is_refreshed, is_expired, refresh_error, is_linked, labels, inherited_labels, ws_specific, draft_only, is_draft }} + {#each filteredItems as { path, value, is_secret, description, extra_perms, canWrite, account, is_refreshed, is_expired, refresh_error, is_linked, labels, inherited_labels, ws_specific, draft_only, is_draft, value_valid_until }} {@const hasDraft = getLocalDraftHint($operatingWorkspace, 'variable', path) ?? is_draft} <Row> @@ -522,6 +523,21 @@ {/snippet} </Popover> {/if} + {#if value_valid_until} + {@const expired = new Date(value_valid_until).getTime() <= Date.now()} + <Popover notClickable> + <CalendarClock + size={16} + class={expired ? 'text-red-600' : 'text-secondary'} + /> + {#snippet text()} + <div> + The value {expired ? 'expired' : 'expires'} on + {new Date(value_valid_until).toLocaleString()}. + </div> + {/snippet} + </Popover> + {/if} {#if account} <Popover notClickable> <RefreshCw size={16} /> diff --git a/frontend/src/lib/hub.ts b/frontend/src/lib/hub.ts index 9f81614258..41e0c41f66 100644 --- a/frontend/src/lib/hub.ts +++ b/frontend/src/lib/hub.ts @@ -86,6 +86,8 @@ type HubPaths = { teamsErrorHandler: string teamsRecoveryHandler: string teamsSuccessHandler: string + slackVariableExpirationHandler: string + teamsVariableExpirationHandler: string emailErrorHandler: string cloneRepoToS3forGitRepoViewer: string appReport: string diff --git a/frontend/src/lib/hubPaths.json b/frontend/src/lib/hubPaths.json index 74c2d6f9f4..41f7f50c33 100644 --- a/frontend/src/lib/hubPaths.json +++ b/frontend/src/lib/hubPaths.json @@ -8,6 +8,8 @@ "teamsErrorHandler": "hub/19742/workspace-or-schedule-error-handler-teams", "teamsRecoveryHandler": "hub/11593/schedule-recovery-handler-teams", "teamsSuccessHandler": "hub/11596/schedule-success-handler-teams", + "slackVariableExpirationHandler": "hub/30049/variable-expiration-handler-slack", + "teamsVariableExpirationHandler": "hub/30048/variable-expiration-handler-teams", "slackReport": "hub/28792/slack", "discordReport": "hub/9085/discord", "smtpReport": "hub/28242/smtp", diff --git a/frontend/src/lib/mcpEndpointTools.ts b/frontend/src/lib/mcpEndpointTools.ts index e53beeb53b..a81110805c 100644 --- a/frontend/src/lib/mcpEndpointTools.ts +++ b/frontend/src/lib/mcpEndpointTools.ts @@ -193,7 +193,12 @@ export const mcpEndpointTools: EndpointTool[] = [ }, "expires_at": { "type": "string", - "description": "The expiration date of the variable", + "description": "When to garbage-collect the variable. Used for ephemeral secrets; the variable is deleted once this is reached. Not the value's expiry \u2014 see value_valid_until.\n", + "format": "date-time" + }, + "value_valid_until": { + "type": "string", + "description": "When the value stored in this variable stops working. Triggers the workspace's variable expiration handler ahead of it, by the handler's `notify_before_secs` (1 day by default); never causes the variable to be deleted.\n", "format": "date-time" }, "labels": { @@ -281,6 +286,12 @@ export const mcpEndpointTools: EndpointTool[] = [ "type": "string", "description": "The new description of the variable" }, + "value_valid_until": { + "type": "string", + "nullable": true, + "description": "When the value stored in this variable stops working. Omit to leave it unchanged; send null to clear it. Changing it re-arms the workspace's variable expiration handler.\n", + "format": "date-time" + }, "labels": { "type": "array", "items": { diff --git a/frontend/src/lib/utils_draft_deploy.test.ts b/frontend/src/lib/utils_draft_deploy.test.ts index c141af3a3b..71ee7b560b 100644 --- a/frontend/src/lib/utils_draft_deploy.test.ts +++ b/frontend/src/lib/utils_draft_deploy.test.ts @@ -6,7 +6,7 @@ vi.mock('$lib/gen', () => ({ FlowService: { getFlowByPath: vi.fn(), createFlow: vi.fn(), updateFlow: vi.fn() }, DraftService: { deleteDraft: vi.fn() }, AppService: {}, - VariableService: {}, + VariableService: { getVariable: vi.fn(), createVariable: vi.fn(), updateVariable: vi.fn() }, ResourceService: { getResource: vi.fn(), updateResource: vi.fn(), createResource: vi.fn() }, ScheduleService: {}, HttpTriggerService: {}, @@ -32,7 +32,7 @@ vi.mock('$lib/components/raw_apps/utils', () => ({ canonicalRawAppDiffValue: vi. vi.mock('$lib/appDiffSides', () => ({ classicAppDraftParts: vi.fn() })) vi.mock('$lib/utils_deployable', () => ({ TRIGGER_RUNTIME_IGNORE: [] })) -import { ScriptService, FlowService, ResourceService } from '$lib/gen' +import { ScriptService, FlowService, VariableService, ResourceService } from '$lib/gen' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' // draftBaseIsStale compares a draft's base pointer against the deployed head @@ -143,6 +143,62 @@ describe('deployDraft preserves on_behalf_of', () => { }) }) +// The deploy bodies are built field by field, so a forgotten field is dropped silently. +describe('deployDraft variable value_valid_until', () => { + beforeEach(() => vi.clearAllMocks()) + + const DATE = '2027-03-15T08:30:00.000Z' + + function mockVariable(deployedExpiry: string | undefined, draftExpiry: string | undefined) { + vi.mocked(VariableService.getVariable).mockResolvedValueOnce({ + path: 'u/admin/key', + value: 'v', + is_secret: false, + description: '', + value_valid_until: deployedExpiry, + draft: { + path: 'u/admin/key', + variable: { value: 'v', is_secret: false, description: '' }, + value_valid_until: draftExpiry + } + } as any) + } + + const updateBody = () => + vi.mocked(VariableService.updateVariable).mock.calls[0][0].requestBody as any + + it('sends a date the draft set on a variable that had none', async () => { + mockVariable(undefined, DATE) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBe(DATE) + }) + + it('sends null when the draft cleared the deployed date', async () => { + mockVariable(DATE, undefined) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBeNull() + }) + + it('omits it when the draft leaves the deployed date alone', async () => { + mockVariable(DATE, DATE) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBeUndefined() + }) + + it('omits it when the draft spells the deployed moment differently', async () => { + mockVariable('2027-03-15T08:30:00Z', DATE) + await deployDraft('variable', 'u/admin/key', 'ws') + expect(updateBody().value_valid_until).toBeUndefined() + }) + + it('carries the date onto a draft-only variable', async () => { + mockVariable(undefined, DATE) + await deployDraft('variable', 'u/admin/key', 'ws', { draftOnly: true }) + const body = vi.mocked(VariableService.createVariable).mock.calls[0][0].requestBody as any + expect(body.value_valid_until).toBe(DATE) + }) +}) + // The backend skips the dependency job when `lock` is set, so a draft that inherited the // deployed lock would deploy new content against the old lockfile. describe('deployDraft: script lock', () => { diff --git a/frontend/src/lib/utils_draft_deploy.ts b/frontend/src/lib/utils_draft_deploy.ts index 96b83239b7..716eaca9d7 100644 --- a/frontend/src/lib/utils_draft_deploy.ts +++ b/frontend/src/lib/utils_draft_deploy.ts @@ -219,14 +219,15 @@ function stripScheduleTriggerRuntime(row: any): Record<string, unknown> { function canonicalizeDraftDiffValue(kind: DraftKind, raw: any, isDraft: boolean): unknown { if (!raw || typeof raw !== 'object') return raw ?? {} if (kind === 'variable') { - // draft: { variable: { value, is_secret, description }, labels, wsSpecific } - // deployed row: { value, is_secret, description, labels, ws_specific } + // draft: { variable: { value, is_secret, description }, value_valid_until, labels, wsSpecific } + // deployed row: { value, is_secret, description, value_valid_until, labels, ws_specific } const v = isDraft ? (raw.variable ?? {}) : raw const is_secret = !!v.is_secret return { value: is_secret ? '<secret>' : (v.value ?? ''), is_secret, description: v.description ?? '', + value_valid_until: raw.value_valid_until ?? undefined, labels: raw.labels ?? undefined, ws_specific: (isDraft ? raw.wsSpecific : raw.ws_specific) ?? undefined } @@ -446,6 +447,10 @@ async function deployDraftTriggers( await deployTriggers(triggers, workspace, isAdmin, writable<string[]>([]), path, isNew) } +function timeOf(date: string | null | undefined): number | undefined { + return date ? new Date(date).getTime() : undefined +} + /** * Promote a draft to deployed by replaying the editor's create/update call with * the stored draft value. The matching draft row is deleted server-side by the @@ -594,7 +599,7 @@ export async function deployDraft( } else if (kind === 'variable') { const { deployed, draft: d } = splitOverlay(await OVERLAY_GETTERS.variable!(workspace, path)) // VariableEditor's `VariableState` draft shape: - // { path, variable: { value, is_secret, description }, labels?, wsSpecific } + // { path, variable: { value, is_secret, description }, value_valid_until?, labels?, wsSpecific } if (draftOnly) { await VariableService.createVariable({ workspace, @@ -603,6 +608,7 @@ export async function deployDraft( value: d.variable?.value ?? '', is_secret: !!d.variable?.is_secret, description: d.variable?.description ?? '', + value_valid_until: d.value_valid_until, labels: d.labels, ws_specific: d.wsSpecific } @@ -617,12 +623,17 @@ export async function deployDraft( value: d.variable?.value === '' ? undefined : d.variable?.value, is_secret: d.variable?.is_secret, description: d.variable?.description, + // `null` clears, absent keeps. Diffed against the deployed row by moment, since + // an absent date in the draft means "no expiry", not "unchanged". + value_valid_until: + timeOf(deployed.value_valid_until) !== timeOf(d.value_valid_until) + ? (d.value_valid_until ?? null) + : undefined, labels: d.labels, ws_specific: d.wsSpecific } }) } - void deployed } else if (kind === 'resource') { const overlay = await OVERLAY_GETTERS.resource!(workspace, path) // Adopt the row this promote is based on as the baseline for the delete below. Without one diff --git a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte index 4cda55f662..5ba85cdbe0 100644 --- a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte @@ -3,7 +3,7 @@ import { page } from '$app/stores' import { isCloudHosted } from '$lib/cloud' import CenteredPage from '$lib/components/CenteredPage.svelte' - import { Alert, Button, Section, Skeleton, Tab, Tabs } from '$lib/components/common' + import { Alert, Button, SecondsInput, Section, Skeleton, Tab, Tabs } from '$lib/components/common' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' @@ -60,6 +60,7 @@ import PremiumInfo from '$lib/components/settings/PremiumInfo.svelte' import Toggle from '$lib/components/Toggle.svelte' + import Popover from '$lib/components/Popover.svelte' import SlackChannelAgents from '$lib/components/workspaceSettings/SlackChannelAgents.svelte' import ChangeWorkspaceName from '$lib/components/settings/ChangeWorkspaceName.svelte' @@ -222,6 +223,21 @@ let errorHandlerMutedOnCancel: boolean | undefined = $state(undefined) let errorHandlerMutedOnUserPath: boolean | undefined = $state(undefined) let successHandlerScriptPath: string | undefined = $state(undefined) + const noVariableExpirationHandler = handlerDraftFromStored('variableExpiration', undefined) + let variableExpirationDraft: HandlerDraft = $state(cloneHandlerDraft(noVariableExpirationHandler)) + let variableExpirationMutedOnUserPath: boolean = $state(false) + // The sweep's default when the stored handler has no `notify_before_secs`. + const defaultNotifyBeforeSecs = 24 * 3600 + let variableExpirationNotifyBeforeSecs: number = $state(defaultNotifyBeforeSecs) + let variableExpirationRemindEverySecs: number | undefined = $state(undefined) + // The sweep runs every 5 minutes, so shorter intervals count as 5 minutes. + let variableExpirationRuns = $derived( + variableExpirationRemindEverySecs + ? Math.ceil( + variableExpirationNotifyBeforeSecs / Math.max(variableExpirationRemindEverySecs, 300) + ) + : 1 + ) let criticalAlertUIMuted: boolean | undefined = $state(undefined) let initialCriticalAlertUIMuted: boolean | undefined = $state(undefined) let publicAppRateLimitPerMinute: number | undefined = $state(undefined) @@ -291,6 +307,14 @@ // Track initial success handler for unsaved changes detection let initialSuccessHandlerScriptPath: string | undefined = $state(undefined) + // Track initial variable expiration handler for unsaved changes detection + let initialVariableExpirationDraft: HandlerDraft = $state( + cloneHandlerDraft(noVariableExpirationHandler) + ) + let initialVariableExpirationMutedOnUserPath: boolean = $state(false) + let initialVariableExpirationNotifyBeforeSecs: number = $state(defaultNotifyBeforeSecs) + let initialVariableExpirationRemindEverySecs: number | undefined = $state(undefined) + let s3ResourceSettings: S3ResourceSettings = $state({ resourceType: 's3', resourcePath: undefined, @@ -348,6 +372,43 @@ ) }) + // The mute flag is stored inside the handler setting, which saving with no handler + // clears, so the toggle is gated on having one. + let variableExpirationHasHandler = $derived(!!handlerDraftToStored(variableExpirationDraft).path) + + // The stored handler is nested because `hasUnsavedChanges` drops a top-level `path`. + function variableExpirationSettingsValue( + draft: HandlerDraft, + mutedOnUserPath: boolean, + notifyBeforeSecs: number, + remindEverySecs: number | undefined + ) { + return { + handler: handlerDraftToStored(draft), + mutedOnUserPath, + notifyBeforeSecs, + remindEverySecs: remindEverySecs || undefined + } + } + + let hasVariableExpirationChanges = $derived.by(() => { + if (tab !== 'variable_expiration') return false + return hasUnsavedChanges( + variableExpirationSettingsValue( + initialVariableExpirationDraft, + initialVariableExpirationMutedOnUserPath, + initialVariableExpirationNotifyBeforeSecs, + initialVariableExpirationRemindEverySecs + ), + variableExpirationSettingsValue( + variableExpirationDraft, + variableExpirationMutedOnUserPath, + variableExpirationNotifyBeforeSecs, + variableExpirationRemindEverySecs + ) + ) + }) + // Derived state for checking unsaved changes in critical alert mute setting let hasCriticalAlertMuteChanges = $derived.by(() => { if (tab !== 'critical_alerts') return false @@ -491,6 +552,7 @@ | 'dev_workspace' | 'error_handler' | 'success_handler' + | 'variable_expiration' | 'critical_alerts' | 'ai' | 'windmill_data_tables' @@ -809,6 +871,20 @@ | { path?: string; extra_args?: any } | undefined successHandlerScriptPath = (successHandler?.path ?? '').split('/').slice(1).join('/') + const variableExpirationHandler = settings.variable_expiration_handler + const [variableExpirationKind, ...variableExpirationPath] = ( + variableExpirationHandler?.path ?? '' + ).split('/') + variableExpirationDraft = handlerDraftFromStored( + 'variableExpiration', + variableExpirationPath.join('/'), + variableExpirationKind === 'flow' ? 'flow' : 'script', + variableExpirationHandler?.extra_args + ) + variableExpirationMutedOnUserPath = variableExpirationHandler?.muted_on_user_path ?? false + variableExpirationNotifyBeforeSecs = + variableExpirationHandler?.notify_before_secs ?? defaultNotifyBeforeSecs + variableExpirationRemindEverySecs = variableExpirationHandler?.remind_every_secs || undefined workspaceDefaultAppPath = settings.default_app initialWorkspaceDefaultAppPath = settings.default_app @@ -860,6 +936,12 @@ // Store initial success handler state for unsaved changes detection initialSuccessHandlerScriptPath = successHandlerScriptPath + // Store initial variable expiration handler state for unsaved changes detection + initialVariableExpirationDraft = cloneHandlerDraft(variableExpirationDraft) + initialVariableExpirationMutedOnUserPath = variableExpirationMutedOnUserPath + initialVariableExpirationNotifyBeforeSecs = variableExpirationNotifyBeforeSecs + initialVariableExpirationRemindEverySecs = variableExpirationRemindEverySecs + loadedSettings = true } @@ -1066,6 +1148,46 @@ initialErrorHandlerMutedOnUserPath = errorHandlerMutedOnUserPath } + async function editVariableExpirationHandler() { + const handler = handlerDraftToStored(variableExpirationDraft) + await WorkspaceService.editVariableExpirationHandler({ + workspace: $workspaceStore!, + requestBody: { + path: handler.path ? `${handler.kind}/${handler.path}` : undefined, + extra_args: handler.args, + muted_on_user_path: variableExpirationMutedOnUserPath, + notify_before_secs: variableExpirationNotifyBeforeSecs, + remind_every_secs: variableExpirationRemindEverySecs || undefined + } + }) + sendUserToast( + handler.path + ? `Variable expiration handler set to ${handler.path}` + : handlerDraftToStored(initialVariableExpirationDraft).path + ? 'Variable expiration handler removed' + : 'Variable expiration settings saved' + ) + + // Rebuilt from what was stored, so Discard also drops the other tabs' unsaved edits. + initialVariableExpirationDraft = handlerDraftFromStored( + 'variableExpiration', + handler.path, + handler.kind, + handler.args, + { emptySelected: variableExpirationDraft.selected } + ) + initialVariableExpirationMutedOnUserPath = variableExpirationMutedOnUserPath + initialVariableExpirationNotifyBeforeSecs = variableExpirationNotifyBeforeSecs + initialVariableExpirationRemindEverySecs = variableExpirationRemindEverySecs + } + + function discardVariableExpirationChanges() { + variableExpirationDraft = cloneHandlerDraft(initialVariableExpirationDraft) + variableExpirationMutedOnUserPath = initialVariableExpirationMutedOnUserPath + variableExpirationNotifyBeforeSecs = initialVariableExpirationNotifyBeforeSecs + variableExpirationRemindEverySecs = initialVariableExpirationRemindEverySecs + } + async function editSuccessHandler() { if (successHandlerScriptPath) { await WorkspaceService.editSuccessHandler({ @@ -1330,6 +1452,21 @@ } } } + case 'variable_expiration': + return { + savedValue: variableExpirationSettingsValue( + initialVariableExpirationDraft, + initialVariableExpirationMutedOnUserPath, + initialVariableExpirationNotifyBeforeSecs, + initialVariableExpirationRemindEverySecs + ), + modifiedValue: variableExpirationSettingsValue( + variableExpirationDraft, + variableExpirationMutedOnUserPath, + variableExpirationNotifyBeforeSecs, + variableExpirationRemindEverySecs + ) + } case 'critical_alerts': return { savedValue: { criticalAlertUIMuted: initialCriticalAlertUIMuted }, @@ -1374,6 +1511,9 @@ discardErrorHandlerSettingsChanges() successHandlerScriptPath = initialSuccessHandlerScriptPath break + case 'variable_expiration': + discardVariableExpirationChanges() + break case 'critical_alerts': criticalAlertUIMuted = initialCriticalAlertUIMuted break @@ -1481,6 +1621,13 @@ aiDescription: 'Error and success handler workspace settings', isEE: true }, + { + id: 'variable_expiration', + label: 'Variable expiration', + aiId: 'workspace-settings-variable-expiration', + aiDescription: + 'Runnable executed when a variable value is about to expire, so the value can be rotated' + }, { id: 'critical_alerts', label: 'Critical alerts', @@ -2293,6 +2440,125 @@ export async function main( disabled={!$enterpriseLicense} /> </Section> + {:else if tab == 'variable_expiration'} + <SettingsPageHeader + title="Variable expiration handler" + description="Run a script or flow ahead of the date the value of a workspace variable expires, so it can be rotated before it stops working." + link="https://www.windmill.dev/docs/core_concepts/variables_and_secrets" + /> + + {#if !$enterpriseLicense && variableExpirationDraft.selected !== 'custom'} + <Alert type="warning" title="Slack and Teams handlers are an EE feature"> + Connecting a workspace to Slack or Teams is a Windmill EE feature. + </Alert> + {/if} + + <Section label="Handler"> + <div class="flex flex-col gap-6"> + <ErrorOrRecoveryHandler + noMargin + isEditable={true} + errorOrRecovery="variableExpiration" + customRequiresEE={false} + toggleText="Notify when a variable is about to expire" + bind:draft={variableExpirationDraft} + customScriptTemplate="/scripts/add?hub=hub%2F30050%2Fwindmill%2Fworkspace_variable_expiration_handler_template" + /> + + <SettingCard + label="Notify before expiry" + description="How long before a variable's value expires the handler runs" + class="gap-2" + > + <SecondsInput + bind:seconds={variableExpirationNotifyBeforeSecs} + disabled={!variableExpirationHasHandler} + hideSeconds + hideTotal + /> + <div class="flex flex-col gap-1 mt-4"> + <span class="text-xs font-semibold text-emphasis">Remind every</span> + <span class="text-xs text-secondary"> + Run the handler again at this interval until the value expires. Expiries are + checked every 5 minutes, so shorter intervals act as 5 minutes. Leave empty + or at 0 for a single notice. + </span> + <SecondsInput + bind:seconds={variableExpirationRemindEverySecs} + disabled={!variableExpirationHasHandler} + clearable + hideSeconds + hideTotal + /> + {#if variableExpirationRemindEverySecs && variableExpirationRemindEverySecs >= variableExpirationNotifyBeforeSecs} + <span class="text-xs text-yellow-600 dark:text-yellow-400"> + No reminder will be sent: the interval must be shorter than Notify before + expiry. + </span> + {:else if variableExpirationRuns >= 24} + <span class="text-xs text-yellow-600 dark:text-yellow-400"> + This runs the handler up to {variableExpirationRuns} times before the value + expires. + </span> + {/if} + </div> + </SettingCard> + + <SettingCard class="gap-2"> + <!-- `w-fit`: the trigger is a flex item of the card, so it would otherwise + stretch the full width and anchor the popup away from the toggle. --> + <Popover + notClickable + disablePopup={variableExpirationHasHandler} + placement="bottom-start" + class="w-fit" + > + <Toggle + bind:checked={variableExpirationMutedOnUserPath} + disabled={!variableExpirationHasHandler} + options={{ + right: 'Do not run the handler for variables in u/ paths' + }} + /> + {#snippet text()} + Select a handler first + {/snippet} + </Popover> + </SettingCard> + + <Alert type="info" title="Runs as g/variable_expiration_handler"> + {#if variableExpirationDraft.selected === 'custom'} + The handler is executed by the automatically created group + g/variable_expiration_handler. Rotating a variable means writing to it, so + grant that group write access to the variables it is meant to rotate. It + starts with none. A script that carries an on-behalf-of identity is the + exception: it runs as that user, with their permissions rather than the + group's. + {:else} + The handler is executed by the automatically created group + g/variable_expiration_handler. It only posts a message, so it needs no access + to your variables: it is given the path and the expiry date, never the value. + {#if variableExpirationDraft.selected === 'slack'} + Access to the Slack bot token is granted for you. + {/if} + {/if} + </Alert> + <span class="text-xs text-secondary"> + If the handler fails to start, a critical alert is raised once and the handler + is tried again at every check. The alert is resolved as soon as it starts. + </span> + </div> + + <SettingsFooter + class="mt-6" + inline + hasUnsavedChanges={hasVariableExpirationChanges} + onSave={editVariableExpirationHandler} + onDiscard={discardVariableExpirationChanges} + saveLabel="Save variable expiration handler" + disabled={!$enterpriseLicense && variableExpirationDraft.selected !== 'custom'} + /> + </Section> {:else if tab == 'critical_alerts'} <SettingsPageHeader title="Workspace critical alerts" diff --git a/rust-client/src/client.rs b/rust-client/src/client.rs index ea3d92bf28..6e03372865 100644 --- a/rust-client/src/client.rs +++ b/rust-client/src/client.rs @@ -247,6 +247,7 @@ impl Windmill { account: None, is_oauth: None, expires_at: None, + value_valid_until: None, labels: None, ws_specific: None, }, @@ -263,6 +264,7 @@ impl Windmill { value: Some(value), is_secret: None, description: None, + value_valid_until: None, labels: None, ws_specific: None, }, From b2243cb2ea02aa45691e38567ac9c3834f9b3460 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Fri, 23 Oct 2026 09:15:22 -0700 Subject: [PATCH 073/101] chore(main): release 1.848.0 (#11971) --- .release-please-manifest.json | 2 +- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ version.txt | 2 +- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ef65812b73..e9ac4479c8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.847.0" + ".": "1.848.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 12e61b56bc..f817035464 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## [1.848.0](https://github.com/windmill-labs/windmill/compare/v1.847.0...v1.848.0) (2026-10-23) + + +### Features + +* add a use/plan/build mode picker and read-only prod sessions ([#11940](https://github.com/windmill-labs/windmill/issues/11940)) ([d6c2b2c](https://github.com/windmill-labs/windmill/commit/d6c2b2c68344bb95939701c418116b2e7d4715a3)) +* composer pills that teach Windmill from the workspace ([#11889](https://github.com/windmill-labs/windmill/issues/11889)) ([ebeea51](https://github.com/windmill-labs/windmill/commit/ebeea514926f60295f3f11f516f4ccda3448f829)) +* fill docusign, salesforce and quickbooks fields on connect ([#11960](https://github.com/windmill-labs/windmill/issues/11960)) ([11f2a4c](https://github.com/windmill-labs/windmill/commit/11f2a4c7ffac980036f839759ae93da6ff3f22e4)) +* group home row menus and open them at their final height ([#11949](https://github.com/windmill-labs/windmill/issues/11949)) ([91bf9b6](https://github.com/windmill-labs/windmill/commit/91bf9b67a74afb419659719949484f1cfd5338c0)) +* let flow builder operators build AI agents ([#11898](https://github.com/windmill-labs/windmill/issues/11898)) ([e5dedd1](https://github.com/windmill-labs/windmill/commit/e5dedd147e1db0c4f36796ba292188bcdb0efc5a)) +* manage and create folders from the home tree view ([#11943](https://github.com/windmill-labs/windmill/issues/11943)) ([da443d2](https://github.com/windmill-labs/windmill/commit/da443d2fb263ecaf90320809b1bb2fc8a4f65b20)) +* run a workspace handler when a variable's value expires ([#10837](https://github.com/windmill-labs/windmill/issues/10837)) ([7a29abc](https://github.com/windmill-labs/windmill/commit/7a29abc7eec491c35217445c1c08486ff030a22c)) + + +### Bug Fixes + +* change an app's access mode under the deploy row lock ([#11965](https://github.com/windmill-labs/windmill/issues/11965)) ([725b15f](https://github.com/windmill-labs/windmill/commit/725b15f546cf20c2e5908acffb105d73fe907558)) +* fork a raw app into the raw app builder, in its session when there ([#11978](https://github.com/windmill-labs/windmill/issues/11978)) ([3d6a2bc](https://github.com/windmill-labs/windmill/commit/3d6a2bcef2e284d64690db04db32a2326a4b0670)) +* home's acting-on follows the workspace home switches to ([#11946](https://github.com/windmill-labs/windmill/issues/11946)) ([18c6936](https://github.com/windmill-labs/windmill/commit/18c69360c9a8e9a9fe4c7c1d9e825a2b7be403a9)) +* keep a staged flow path across reloads and follow moves in session tabs ([#11967](https://github.com/windmill-labs/windmill/issues/11967)) ([6b56656](https://github.com/windmill-labs/windmill/commit/6b56656bd650f2db5fbd74e23b55b926c6f69dd7)) +* keep the log indexer starting when a stored day chunk is broken ([#11979](https://github.com/windmill-labs/windmill/issues/11979)) ([79fe8ab](https://github.com/windmill-labs/windmill/commit/79fe8ab03f6f052bf7fe763b6f8a0a23fe922611)) +* list usr columns explicitly in whoami's user lookup ([#11970](https://github.com/windmill-labs/windmill/issues/11970)) ([fb193d7](https://github.com/windmill-labs/windmill/commit/fb193d7a816ae97fa8fc60608270296e159dfd3c)) +* make the autoscaling Test scaling button run the integration ([#11972](https://github.com/windmill-labs/windmill/issues/11972)) ([72c6b10](https://github.com/windmill-labs/windmill/commit/72c6b10821cfa35ff3deb3a3ecc729ed75a9dbc6)) +* return variable.value as text so widening it changes no result type ([#11976](https://github.com/windmill-labs/windmill/issues/11976)) ([f6f3a0a](https://github.com/windmill-labs/windmill/commit/f6f3a0a1f24cd9ea0d78207d6848147ebd73bea0)) +* run unstamped git auto-pulls as a superadmin when no admin ([#11973](https://github.com/windmill-labs/windmill/issues/11973)) ([c89a827](https://github.com/windmill-labs/windmill/commit/c89a82750ed0a461d8d4f1502f019bc0da4ed58c)) +* send app editor inspector picks to a new AI session as a chip ([#11966](https://github.com/windmill-labs/windmill/issues/11966)) ([28d2556](https://github.com/windmill-labs/windmill/commit/28d2556c941f66cad353eca3809f43e8d8cf3c05)) +* share settings.yaml's git sync block between a fork and its parent ([#11974](https://github.com/windmill-labs/windmill/issues/11974)) ([fe38a1d](https://github.com/windmill-labs/windmill/commit/fe38a1d3763a11f8b0bc4b07d61824d3a7b51850)) + ## [1.847.0](https://github.com/windmill-labs/windmill/compare/v1.846.1...v1.847.0) (2026-10-22) diff --git a/version.txt b/version.txt index 44bc59b37f..d6dfecff17 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.847.0 +1.848.0 From 511e10563ececdd8645e7a808f56e3cb6173d922 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Fri, 23 Oct 2026 09:18:52 -0700 Subject: [PATCH 074/101] chore: apply 1.848.0 version bump (#11980) The change-versions job on the release PR failed to push after the branch was deleted on merge, so v1.848.0 shipped with only version.txt bumped. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- backend/Cargo.lock | 200 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 ++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 19 files changed, 145 insertions(+), 145 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 97626ab116..1bc57db04a 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -1992,18 +1992,18 @@ dependencies = [ [[package]] name = "bon" -version = "3.10.2" +version = "3.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "214f5df094ce551a10a30ffb9c70243d61f121a3d985a6495933e181dee6a7d2" +checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6" dependencies = [ "bon-macros", ] [[package]] name = "bon-macros" -version = "3.10.2" +version = "3.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2706da6c749998cc555d04184909608956a69ad3f8ab1a076fbc867b4a3c3ce5" +checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6" dependencies = [ "darling 0.24.1", "ident_case", @@ -2366,9 +2366,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", "jobserver", @@ -2964,9 +2964,9 @@ dependencies = [ [[package]] name = "crypto-bigint" -version = "0.7.5" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0" dependencies = [ "cpubits", "ctutils", @@ -3055,9 +3055,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0" dependencies = [ "cmov", "subtle", @@ -5131,7 +5131,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" dependencies = [ "base16ct 1.0.0", - "crypto-bigint 0.7.5", + "crypto-bigint 0.7.6", "crypto-common 0.2.2", "ff 0.14.0", "group 0.14.0", @@ -6745,7 +6745,7 @@ dependencies = [ "tokio", "tokio-rustls 0.26.6", "tower-service", - "webpki-roots 1.0.10", + "webpki-roots 1.0.11", ] [[package]] @@ -10889,7 +10889,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.10", + "webpki-roots 1.0.11", ] [[package]] @@ -15052,9 +15052,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.28.0" +version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -15369,9 +15369,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" dependencies = [ "rustls-pki-types", ] @@ -15382,14 +15382,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.10", + "webpki-roots 1.0.11", ] [[package]] name = "webpki-roots" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" dependencies = [ "rustls-pki-types", ] @@ -15487,7 +15487,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-nats", @@ -15577,7 +15577,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.847.0" +version = "1.848.0" dependencies = [ "async-stream", "async-trait", @@ -15612,7 +15612,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15625,7 +15625,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "argon2", @@ -15768,7 +15768,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15792,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15809,7 +15809,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "axum", @@ -15835,7 +15835,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.847.0" +version = "1.848.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15845,7 +15845,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15862,7 +15862,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "base64 0.22.1", @@ -15884,7 +15884,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "axum", @@ -15907,7 +15907,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15923,7 +15923,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15945,7 +15945,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15967,7 +15967,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -15981,7 +15981,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-nats", @@ -16017,7 +16017,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "axum", @@ -16043,7 +16043,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -16071,7 +16071,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "axum", @@ -16093,7 +16093,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -16113,7 +16113,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "axum", @@ -16155,7 +16155,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "axum", @@ -16185,7 +16185,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.847.0" +version = "1.848.0" dependencies = [ "lazy_static", "serde", @@ -16197,7 +16197,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.847.0" +version = "1.848.0" dependencies = [ "argon2", "axum", @@ -16221,7 +16221,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -16236,7 +16236,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.847.0" +version = "1.848.0" dependencies = [ "axum", "chrono", @@ -16275,7 +16275,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.847.0" +version = "1.848.0" dependencies = [ "chrono", "lazy_static", @@ -16290,7 +16290,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "axum", @@ -16309,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.847.0" +version = "1.848.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16415,7 +16415,7 @@ dependencies = [ "url", "urlencoding", "uuid", - "webpki-roots 1.0.10", + "webpki-roots 1.0.11", "windmill-macros", "windmill-parser", "windmill-parser-py", @@ -16427,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.847.0" +version = "1.848.0" dependencies = [ "chrono", "futures", @@ -16447,7 +16447,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.847.0" +version = "1.848.0" dependencies = [ "regex", "serde", @@ -16464,7 +16464,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16491,7 +16491,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "futures", @@ -16508,7 +16508,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.847.0" +version = "1.848.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16524,7 +16524,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -16546,7 +16546,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -16577,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "arc-swap", @@ -16602,7 +16602,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-stream", @@ -16638,7 +16638,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "futures", @@ -16657,7 +16657,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.847.0" +version = "1.848.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16666,7 +16666,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -16678,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde_json", @@ -16690,7 +16690,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "gosyn", @@ -16702,7 +16702,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -16714,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde_json", @@ -16726,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "nu-parser", @@ -16737,7 +16737,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16748,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16760,7 +16760,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16771,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-recursion", @@ -16794,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde_json", @@ -16806,7 +16806,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -16820,7 +16820,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16837,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -16850,7 +16850,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde", @@ -16862,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -16880,7 +16880,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16896,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16913,7 +16913,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -16927,7 +16927,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-recursion", @@ -16966,7 +16966,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "const_format", @@ -17004,7 +17004,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.847.0" +version = "1.848.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17015,7 +17015,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-recursion", @@ -17050,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17074,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17107,7 +17107,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17134,7 +17134,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17167,7 +17167,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17187,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17221,7 +17221,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17258,7 +17258,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17281,7 +17281,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17305,7 +17305,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-nats", @@ -17329,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17364,7 +17364,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17392,7 +17392,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-trait", @@ -17417,7 +17417,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17436,7 +17436,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-once-cell", @@ -17554,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.847.0" +version = "1.848.0" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d2d4678718..ddd4133213 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.847.0" +version = "1.848.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.847.0" +version = "1.848.0" authors = ["Ruben Fiszel <ruben@windmill.dev>"] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index a73343f8b9..9b2d7397e8 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.847.0" +version = "1.848.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.847.0" +version = "1.848.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.847.0" +version = "1.848.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.847.0" +version = "1.848.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 6955752a98..0133fa778d 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.847.0" +version = "1.848.0" edition = "2021" authors = ["Ruben Fiszel <ruben@windmill.dev>"] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index c5f3a902eb..f4a5bf53b0 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.847.0 + version: 1.848.0 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 6be8a4523e..c64103bc46 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.847.0"; +export const VERSION = "v1.848.0"; export async function login(email: string, password: string): Promise<string> { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 56e888035e..cea12f7cee 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.847.0", + "version": "1.848.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.847.0", + "version": "1.848.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 74fb87fc20..73957de9de 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.847.0", + "version": "1.848.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index e02c5a2217..2b4cacdd8a 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.847.0"; +export const VERSION = "1.848.0"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 6034f153d4..f5aafb851e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.847.0", + "version": "1.848.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.847.0", + "version": "1.848.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index b193c05bcb..39f644f810 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.847.0", + "version": "1.848.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index cab32152b8..98fd22cc68 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.847.0" +wmill = ">=1.848.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 489888ee60..37450c254f 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.847.0 + version: 1.848.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 713e75f667..d3e380a9c9 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.847.0' + ModuleVersion = '1.848.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 2ef9c5923b..8a4e49f849 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.847.0" +version = "1.848.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 2a1a7b3c15..1804d98aa7 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.847.0", + "version": "1.848.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 5f7b4f3fef..aafe90749a 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.847.0", + "version": "1.848.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index fe642da3da..5242f951fc 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.847.0", + "version": "1.848.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.847.0", + "version": "1.848.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index 43d8faa83f..d3a74ba131 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.847.0", + "version": "1.848.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 001313aa242c6de053a9deb0c6cdb64580ce1cee Mon Sep 17 00:00:00 2001 From: hugocasa <hugo@casademont.ch> Date: Fri, 23 Oct 2026 18:20:04 +0200 Subject: [PATCH 075/101] fix: use linkedin openid connect default scopes (#11953) * oauth: linkedin OIDC default scopes + scope_options, quickbooks asks isSandBox Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: leave quickbooks connect fields to #11960 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- backend/oauth_connect.json | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/backend/oauth_connect.json b/backend/oauth_connect.json index ecb4f95166..48957fee2f 100644 --- a/backend/oauth_connect.json +++ b/backend/oauth_connect.json @@ -337,7 +337,20 @@ "auth_url": "https://www.linkedin.com/oauth/v2/authorization", "token_url": "https://www.linkedin.com/oauth/v2/accessToken", "grant_types": ["authorization_code", "client_credentials"], - "scopes": ["w_member_social", "r_liteprofile", "r_emailaddress"], + "scopes": ["openid", "profile", "email", "w_member_social"], + "scope_options": [ + "openid", + "profile", + "email", + "w_member_social", + "r_member_social", + "w_organization_social", + "r_organization_social", + "r_organization_admin", + "rw_organization_admin", + "r_ads", + "r_basicprofile" + ], "req_body_auth": true }, "quickbooks": { From 19204f57572aafbb755120f34eb3b2ef45f34fd2 Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:35:12 -0400 Subject: [PATCH 076/101] ci: let a PR opt out of automatic AI review (#11984) A PR whose body contains `[skip-ai-review]` no longer triggers the automatic Codex, Pi and Claude reviews on open/ready/synchronize, and is left out of the weekly merged-PR summary. Explicit requests (workflow_call from the review commands) still run. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/codex-pr-review.yml | 4 +++- .github/workflows/pi-pr-review.yml | 4 +++- .github/workflows/pr-ready-review.yml | 4 +++- .github/workflows/weekly-pr-summary.yml | 3 ++- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/codex-pr-review.yml b/.github/workflows/codex-pr-review.yml index 2d70ad7f7a..e1628729d8 100644 --- a/.github/workflows/codex-pr-review.yml +++ b/.github/workflows/codex-pr-review.yml @@ -42,12 +42,14 @@ jobs: # skips auto-review for every private member. # Dependabot-triggered runs get a separate secret scope, so this job has no API # key and cannot review. workflow_call stays open for an explicit request. + # `[skip-ai-review]` in the PR body opts out of the automatic run only. if: | github.event_name == 'workflow_call' || ( github.event.pull_request.draft == false && github.event.pull_request.head.repo.fork == false && - github.event.pull_request.user.login != 'dependabot[bot]' + github.event.pull_request.user.login != 'dependabot[bot]' && + !contains(github.event.pull_request.body, '[skip-ai-review]') ) permissions: contents: read diff --git a/.github/workflows/pi-pr-review.yml b/.github/workflows/pi-pr-review.yml index a18dc28ff2..4b57db7b78 100644 --- a/.github/workflows/pi-pr-review.yml +++ b/.github/workflows/pi-pr-review.yml @@ -40,12 +40,14 @@ jobs: # skips auto-review for every private member. # Dependabot-triggered runs get a separate secret scope, so this job has no API # key and cannot review. workflow_call stays open for an explicit request. + # `[skip-ai-review]` in the PR body opts out of the automatic run only. if: | github.event_name == 'workflow_call' || ( github.event.pull_request.draft == false && github.event.pull_request.head.repo.fork == false && - github.event.pull_request.user.login != 'dependabot[bot]' + github.event.pull_request.user.login != 'dependabot[bot]' && + !contains(github.event.pull_request.body, '[skip-ai-review]') ) permissions: contents: read diff --git a/.github/workflows/pr-ready-review.yml b/.github/workflows/pr-ready-review.yml index 90714cba53..4b88273cad 100644 --- a/.github/workflows/pr-ready-review.yml +++ b/.github/workflows/pr-ready-review.yml @@ -39,12 +39,14 @@ jobs: # skips auto-review for every private member. # Dependabot-triggered runs get a separate secret scope, so this job has no API # key and cannot review. workflow_call stays open for an explicit request. + # `[skip-ai-review]` in the PR body opts out of the automatic run only. if: | github.event_name == 'workflow_call' || ( (github.event.pull_request.draft == false || github.event.pull_request.ready_for_review == true) && github.event.pull_request.head.repo.fork == false && - github.event.pull_request.user.login != 'dependabot[bot]' + github.event.pull_request.user.login != 'dependabot[bot]' && + !contains(github.event.pull_request.body, '[skip-ai-review]') ) permissions: contents: read diff --git a/.github/workflows/weekly-pr-summary.yml b/.github/workflows/weekly-pr-summary.yml index 9d1f0631fb..14551e9943 100644 --- a/.github/workflows/weekly-pr-summary.yml +++ b/.github/workflows/weekly-pr-summary.yml @@ -39,9 +39,10 @@ jobs: - This gives you the exact 7-day window (store these in variables for use in commands) 2. **Fetch ONLY Merged PRs from Past Week**: - - Command: `gh pr list --repo ${{ github.repository }} --state merged --search "merged:>=$CUTOFF_DATE" --limit 100 --json number,title,author,mergedAt,url` + - Command: `gh pr list --repo ${{ github.repository }} --state merged --search "merged:>=$CUTOFF_DATE" --limit 100 --json number,title,author,mergedAt,url,body --jq '[.[] | select((.body // "") | contains("[skip-ai-review]") | not) | del(.body)]'` - This returns ONLY PRs that were merged in the last 7 days - The --search flag filters by merge date using GitHub's search syntax + - The --jq filter drops PRs whose body contains `[skip-ai-review]`; never fetch or mention those PRs - **FILTER OUT** any PRs with titles starting with "chore: release" or "chore(release)" 3. **Categorize PRs**: Group PRs into three categories by analyzing titles and labels: From 70d3c637ef9a9e6832714130b17f839c157e3081 Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:45:11 -0400 Subject: [PATCH 077/101] chore(rust): run host-side cargo commands from a dedicated working directory (#11985) Run `cargo sweep` and `cargo generate-lockfile` from a worker-owned scratch directory instead of the job directory, pointing at the crate with `--manifest-path`. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- backend/windmill-worker/src/rust_executor.rs | 382 ++++++++++++++++--- 1 file changed, 320 insertions(+), 62 deletions(-) diff --git a/backend/windmill-worker/src/rust_executor.rs b/backend/windmill-worker/src/rust_executor.rs index fabea34499..bba1be8ad4 100644 --- a/backend/windmill-worker/src/rust_executor.rs +++ b/backend/windmill-worker/src/rust_executor.rs @@ -87,6 +87,8 @@ lazy_static::lazy_static! { static ref CARGO_PATH: String = find_cargo_path(); static ref SWEEP_MAXSIZE: String = std::env::var("CARGO_SWEEP_MAXSIZE").unwrap_or("25GB".to_owned()); static ref NO_SHARED_BUILD_DIR: bool = std::env::var("RUST_NO_SHARED_BUILD_DIR").ok().map(|flag| flag == "true").unwrap_or(false); + /// Parent of the worker-owned working directories of host-side cargo invocations, see [`HostCargoCwd`]. + static ref HOST_CARGO_CWD_DIR: String = format!("{}/host_cargo_cwd", *RUST_CACHE_DIR); } #[cfg(windows)] @@ -242,13 +244,10 @@ pub fn __WINDMILL_RUN__(_args: __WINDMILL_ARGS__) -> Result<String, Box<dyn std: Ok(()) } -async fn write_cargo_config( - job_dir: &str, - job_id: &Uuid, - w_id: &str, - conn: &Connection, -) -> anyhow::Result<()> { - if let Some(cargo_registries) = read_ee_registry_with_workspace_override( +/// The instance/workspace cargo registry configuration, if any is set, as the body of a +/// `.cargo/config.toml`. +async fn cargo_registries_config(job_id: &Uuid, w_id: &str, conn: &Connection) -> Option<String> { + read_ee_registry_with_workspace_override( CARGO_REGISTRIES.read().await.clone(), "cargo_registries", "cargo registries", @@ -257,16 +256,150 @@ async fn write_cargo_config( conn, ) .await - { - if !cargo_registries.trim().is_empty() { - let cargo_dir = format!("{job_dir}/.cargo"); - create_dir_all(&cargo_dir).await?; - write_file(&cargo_dir, "config.toml", &cargo_registries)?; - } + .filter(|cargo_registries| !cargo_registries.trim().is_empty()) +} + +/// Write `{dir}/.cargo/config.toml`. cargo only reads it when `dir` is the working +/// directory of the invocation (or an ancestor of it), never because `dir` holds the +/// manifest the invocation was pointed at. +async fn write_cargo_registries_config(dir: &str, registries: &str) -> anyhow::Result<()> { + let cargo_dir = format!("{dir}/.cargo"); + create_dir_all(&cargo_dir).await?; + write_file(&cargo_dir, "config.toml", registries)?; + Ok(()) +} + +async fn write_cargo_config( + job_dir: &str, + job_id: &Uuid, + w_id: &str, + conn: &Connection, +) -> anyhow::Result<()> { + if let Some(cargo_registries) = cargo_registries_config(job_id, w_id, conn).await { + write_cargo_registries_config(job_dir, &cargo_registries).await?; } Ok(()) } +/// Stub manifest for a [`HostCargoCwd`]. Nothing is ever built from it; `cargo sweep` +/// only needs *a* manifest in its working directory to ask `cargo metadata` where the +/// target directory is, and `[workspace]` keeps cargo from walking further up. +const HOST_CARGO_CWD_MANIFEST: &str = r#"# Worker-owned stub crate. Host-side cargo invocations run from here so that their +# configuration discovery never reaches a job directory. Nothing is built from it. +[workspace] + +[package] +name = "windmill_host_cargo_cwd" +version = "0.0.0" + +[lib] +path = "src/lib.rs" +"#; + +/// Working directory for cargo invocations that run outside the build jail. cargo reads +/// `.cargo/config.toml` from its working directory and that directory's ancestors (not +/// from the manifest's directory), so this is a worker-owned directory under the rust +/// cache dir, outside any job directory and outside the build dirs. +struct HostCargoCwd { + path: String, +} + +impl HostCargoCwd { + /// `registries` is the worker's own cargo registry configuration (never the job's), to + /// be made visible to the invocation as this directory's `.cargo/config.toml`. + async fn new(kind: &str, registries: Option<&str>) -> anyhow::Result<Self> { + let path = format!("{}/{kind}-{}", *HOST_CARGO_CWD_DIR, Uuid::new_v4()); + create_dir_all(format!("{path}/src")).await.map_err(|e| { + anyhow::anyhow!("Could not create host cargo working dir {path}.\ne: {e}") + })?; + let cwd = HostCargoCwd { path }; + write_file(&cwd.path, "Cargo.toml", HOST_CARGO_CWD_MANIFEST)?; + write_file(&format!("{}/src", cwd.path), "lib.rs", "")?; + if let Some(registries) = registries { + write_cargo_registries_config(&cwd.path, registries).await?; + } + Ok(cwd) + } + + fn path(&self) -> &str { + &self.path + } +} + +impl Drop for HostCargoCwd { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// `cargo generate-lockfile` for the crate in `job_dir`, run from `cwd`. +/// +/// `cwd` is a [`HostCargoCwd`] and not `job_dir`, so the crate is named with +/// `--manifest-path`; cargo writes `Cargo.lock` next to that manifest, i.e. still at +/// `{job_dir}/Cargo.lock`. +fn build_generate_lockfile_command(cwd: &str, job_dir: &str) -> Command { + let mut gen_lockfile_cmd = Command::new(CARGO_PATH.as_str()); + gen_lockfile_cmd + .current_dir(cwd) + .env_clear() + .env("PATH", PATH_ENV.as_str()) + .env("HOME", HOME_ENV.as_str()) + .env("CARGO_HOME", CARGO_HOME.as_str()) + .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) + .envs(PROXY_ENVS.clone()) + .args([ + "generate-lockfile", + "--manifest-path", + &format!("{job_dir}/Cargo.toml"), + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + gen_lockfile_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); + gen_lockfile_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); + gen_lockfile_cmd.env( + "TMP", + std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), + ); + } + gen_lockfile_cmd +} + +/// `cargo sweep` over the shared build dir's target dir, run from `cwd`. +/// +/// `cwd` is a [`HostCargoCwd`] and not `job_dir`. `cargo sweep` resolves the target +/// directory to prune by running `cargo metadata` for the manifest in its working +/// directory, and `CARGO_TARGET_DIR` overrides what that resolves to — which is how this +/// invocation has always reached `{build_dir}/target`, the stub manifest in `cwd` standing +/// in for the job's crate. +fn build_cargo_sweep_command(cwd: &str, build_dir: &str) -> Command { + let mut sweep_cmd = Command::new(CARGO_PATH.as_str()); + let sweep_path = format!("{}/bin:{}", CARGO_HOME.as_str(), PATH_ENV.as_str()); + sweep_cmd + .current_dir(cwd) + .env_clear() + .env("PATH", &sweep_path) + .env("CARGO_HOME", CARGO_HOME.as_str()) + .env("HOME", HOME_ENV.as_str()) + .env("CARGO_TARGET_DIR", &format!("{build_dir}/target")) + .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) + .args(["sweep", "--maxsize", SWEEP_MAXSIZE.as_str()]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + #[cfg(windows)] + { + sweep_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); + sweep_cmd.env( + "TMP", + std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), + ); + sweep_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); + } + sweep_cmd +} + pub async fn generate_cargo_lockfile( job_id: &Uuid, code: &str, @@ -282,29 +415,14 @@ pub async fn generate_cargo_lockfile( check_executor_binary_exists("cargo", CARGO_PATH.as_str(), "rust")?; gen_cargo_crate(code, job_dir)?; - write_cargo_config(job_dir, job_id, w_id, conn).await?; - - let mut gen_lockfile_cmd = Command::new(CARGO_PATH.as_str()); - gen_lockfile_cmd - .current_dir(job_dir) - .env_clear() - .env("PATH", PATH_ENV.as_str()) - .env("HOME", HOME_ENV.as_str()) - .env("CARGO_HOME", CARGO_HOME.as_str()) - .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) - .envs(PROXY_ENVS.clone()) - .args(vec!["generate-lockfile"]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - #[cfg(windows)] - { - gen_lockfile_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); - gen_lockfile_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); - gen_lockfile_cmd.env( - "TMP", - std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), - ); + let registries = cargo_registries_config(job_id, w_id, conn).await; + if let Some(registries) = registries.as_deref() { + write_cargo_registries_config(job_dir, registries).await?; } + + // Run outside `job_dir`; the registry configuration is carried over explicitly. + let cwd = HostCargoCwd::new("lockfile", registries.as_deref()).await?; + let gen_lockfile_cmd = build_generate_lockfile_command(cwd.path(), job_dir); let gen_lockfile_process = start_child_process(gen_lockfile_cmd, CARGO_PATH.as_str(), false).await?; handle_child( @@ -334,7 +452,6 @@ pub async fn generate_cargo_lockfile( async fn get_build_dir( job: &MiniPulledJob, - job_dir: &str, conn: &Connection, worker_name: &str, is_preview: bool, @@ -387,38 +504,29 @@ async fn get_build_dir( if run_sweep { // Also run sweep to make sure target isn't using too much disk - let mut sweep_cmd = Command::new(CARGO_PATH.as_str()); - let sweep_path = format!("{}/bin:{}", CARGO_HOME.as_str(), PATH_ENV.as_str()); - sweep_cmd - .current_dir(job_dir) - .env_clear() - .env("PATH", &sweep_path) - .env("CARGO_HOME", CARGO_HOME.as_str()) - .env("HOME", HOME_ENV.as_str()) - .env("CARGO_TARGET_DIR", &(bd.clone() + "/target")) - .env("RUSTUP_HOME", RUSTUP_HOME.as_str()) - .args(["sweep", "--maxsize", SWEEP_MAXSIZE.as_str()]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - - #[cfg(windows)] - { - sweep_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); - sweep_cmd.env( - "TMP", - std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()), - ); - sweep_cmd.env("USERPROFILE", crate::USERPROFILE_ENV.as_str()); - } - - let (job_id, conn, w_id, wk_name) = ( + let (job_id, conn, w_id, wk_name, build_dir) = ( job.id.clone(), conn.clone(), job.workspace_id.clone(), worker_name.to_owned(), + bd.clone(), ); tokio::spawn(async move { + // Run from a dedicated directory rather than the job directory. `cwd` is held + // for the whole sweep; dropping it removes the directory. + let cwd = match HostCargoCwd::new("sweep", None).await { + Ok(cwd) => cwd, + Err(e) => { + tracing::warn!( + workspace_id = %w_id, + job_id = %job_id, + "Failed to prepare working directory for `cargo sweep`. Rust cache may grow over time, cargo sweep is meant to clean up unused cache.\ne: {e}\n" + ); + return; + } + }; + let sweep_cmd = build_cargo_sweep_command(cwd.path(), &build_dir); if let Err(e) = match start_child_process(sweep_cmd, CARGO_PATH.as_str(), false).await { Ok(sweep_process) => { handle_child( @@ -467,7 +575,7 @@ pub async fn build_rust_crate( ensure_rust_runtime_dirs(); let bin_path = format!("{}/{hash}", *RUST_CACHE_DIR); - let build_dir = get_build_dir(job, job_dir, conn, worker_name, is_preview).await?; + let build_dir = get_build_dir(job, conn, worker_name, is_preview).await?; let child = if is_sandboxing_enabled() { let _ = write_file( @@ -851,3 +959,153 @@ pub async fn handle_rust_job( .await?; read_result(job_dir, None).await } + +#[cfg(test)] +mod host_cargo_cwd_tests { + use super::*; + use std::ffi::OsStr; + use std::path::Path; + + /// A plausible job directory: `{TMP}/windmill/{worker}/{job_id}`. + const JOB_DIR: &str = "/tmp/windmill/wk-default-xyz-AbCdE/01a12c99-6620-74b9-a4ca-189c60de272c"; + + fn args(cmd: &Command) -> Vec<String> { + cmd.as_std() + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect() + } + + fn env(cmd: &Command, key: &str) -> Option<String> { + cmd.as_std() + .get_envs() + .find(|(k, _)| *k == OsStr::new(key)) + .map(|(_, v)| v.unwrap_or(OsStr::new("")).to_string_lossy().into_owned()) + } + + /// The working directory is neither inside the job directory nor an ancestor of it. + fn assert_cwd_is_isolated_from_job_dir(cmd: &Command, job_dir: &str) { + let cwd = cmd + .as_std() + .get_current_dir() + .expect("host-side cargo must set an explicit working directory"); + let job_dir = Path::new(job_dir); + assert!( + cwd.ancestors().all(|a| a != job_dir), + "cwd {cwd:?} is inside the job dir {job_dir:?}" + ); + assert!( + job_dir.ancestors().all(|a| a != cwd), + "cwd {cwd:?} is an ancestor of the job dir {job_dir:?}" + ); + assert!( + cwd.starts_with(Path::new(HOST_CARGO_CWD_DIR.as_str())), + "cwd {cwd:?} is not one of the worker-owned dirs under {}", + *HOST_CARGO_CWD_DIR + ); + } + + #[test] + fn generate_lockfile_runs_outside_the_job_dir_and_names_the_manifest() { + let cwd = format!("{}/lockfile-deadbeef", *HOST_CARGO_CWD_DIR); + let cmd = build_generate_lockfile_command(&cwd, JOB_DIR); + + assert_eq!(cmd.as_std().get_current_dir(), Some(Path::new(&cwd))); + assert_cwd_is_isolated_from_job_dir(&cmd, JOB_DIR); + // Cargo writes Cargo.lock next to the manifest it is given, which is where + // `generate_cargo_lockfile` reads it back from. + assert_eq!( + args(&cmd), + vec![ + "generate-lockfile".to_string(), + "--manifest-path".to_string(), + format!("{JOB_DIR}/Cargo.toml"), + ] + ); + } + + #[test] + fn cargo_sweep_runs_outside_the_job_dir_and_still_targets_the_build_dir() { + let cwd = format!("{}/sweep-deadbeef", *HOST_CARGO_CWD_DIR); + let build_dir = format!("{}/build/acme@u.dev.script@dev", *RUST_CACHE_DIR); + let cmd = build_cargo_sweep_command(&cwd, &build_dir); + + assert_eq!(cmd.as_std().get_current_dir(), Some(Path::new(&cwd))); + assert_cwd_is_isolated_from_job_dir(&cmd, JOB_DIR); + assert_eq!( + args(&cmd), + vec![ + "sweep".to_string(), + "--maxsize".to_string(), + SWEEP_MAXSIZE.to_string(), + ] + ); + // `cargo sweep` prunes the target dir that `cargo metadata` reports, and + // CARGO_TARGET_DIR is what decides that -- not the cwd's manifest. + assert_eq!( + env(&cmd, "CARGO_TARGET_DIR").as_deref(), + Some(format!("{build_dir}/target").as_str()) + ); + } + + #[tokio::test] + async fn host_cargo_cwd_is_a_worker_owned_stub_crate_removed_on_drop() { + let registries = "[registries.acme]\nindex = \"sparse+https://acme.test/index/\"\n"; + let path = { + let cwd = HostCargoCwd::new("unittest", Some(registries)) + .await + .expect("could not create host cargo cwd"); + let path = cwd.path().to_string(); + + assert!( + path.starts_with(&format!("{}/unittest-", *HOST_CARGO_CWD_DIR)), + "unexpected host cargo cwd {path}" + ); + assert!( + !path.starts_with(&format!("{}/build/", *RUST_CACHE_DIR)), + "host cargo cwd {path} is under the build dirs" + ); + + // `cargo sweep` needs a manifest in its cwd to ask `cargo metadata` for the + // target dir; `[workspace]` keeps cargo from walking further up. + let manifest = std::fs::read_to_string(format!("{path}/Cargo.toml")) + .expect("stub Cargo.toml missing"); + assert!( + manifest.contains("[workspace]"), + "stub manifest is not its own workspace root: {manifest}" + ); + assert!( + manifest.contains("path = \"src/lib.rs\""), + "stub manifest does not point at its stub target: {manifest}" + ); + assert_eq!( + std::fs::read_to_string(format!("{path}/src/lib.rs")).expect("stub lib.rs missing"), + "" + ); + // The worker's own registry configuration has to follow the invocation out + // of the job dir, since cargo only reads it from the cwd and CARGO_HOME. + assert_eq!( + std::fs::read_to_string(format!("{path}/.cargo/config.toml")) + .expect("registry config missing"), + registries + ); + path + }; + + assert!( + !Path::new(&path).exists(), + "host cargo cwd {path} outlived its guard" + ); + } + + #[tokio::test] + async fn host_cargo_cwd_has_no_config_when_no_registries_are_set() { + let cwd = HostCargoCwd::new("unittest", None) + .await + .expect("could not create host cargo cwd"); + assert!( + !Path::new(&format!("{}/.cargo", cwd.path())).exists(), + "host cargo cwd has a .cargo dir although no registries are configured" + ); + } +} From 65c078d2a070efdcf2555480a21947edf13ed096 Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:03:14 -0400 Subject: [PATCH 078/101] chore(nsjail): align dependency install profiles with the run profiles (#11986) Set `keep_caps: false` in the python, ruby and R dependency install/lock profiles, matching the run profiles, and build the uv argument list in `download_deps.py.sh` directly instead of through a command string. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../nsjail/download.py.config.proto | 3 +- .../nsjail/download.ruby.config.proto | 3 +- .../nsjail/download_deps.py.sh | 34 ++++---- .../nsjail/install.r.config.proto | 3 +- .../nsjail/lock.py.config.proto | 3 +- .../nsjail/lock.ruby.config.proto | 3 +- backend/windmill-worker/src/nsjail_compat.rs | 86 +++++++++++++++++++ 7 files changed, 114 insertions(+), 21 deletions(-) diff --git a/backend/windmill-worker/nsjail/download.py.config.proto b/backend/windmill-worker/nsjail/download.py.config.proto index 18957bb4a5..a68d96eb92 100644 --- a/backend/windmill-worker/nsjail/download.py.config.proto +++ b/backend/windmill-worker/nsjail/download.py.config.proto @@ -30,7 +30,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/download.ruby.config.proto b/backend/windmill-worker/nsjail/download.ruby.config.proto index 31eefae766..3a3a6f3b74 100644 --- a/backend/windmill-worker/nsjail/download.ruby.config.proto +++ b/backend/windmill-worker/nsjail/download.ruby.config.proto @@ -23,7 +23,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/download_deps.py.sh b/backend/windmill-worker/nsjail/download_deps.py.sh index 6b4cd8cfd8..8f0ebd1cd0 100755 --- a/backend/windmill-worker/nsjail/download_deps.py.sh +++ b/backend/windmill-worker/nsjail/download_deps.py.sh @@ -20,20 +20,22 @@ then echo "\$TRUSTED_HOST is set to $TRUSTED_HOST" fi -CMD="/usr/local/bin/uv pip install -\"$REQ\" ---target \"$TARGET\" ---no-cache ---no-config ---no-color ---no-deps ---link-mode=copy -$PY_PATH -$INDEX_URL_ARG $EXTRA_INDEX_URL_ARG $TRUSTED_HOST_ARG ---system ---reinstall ---compile-bytecode -" +# Build the argv directly so each value reaches uv as a single argument, quoting +# intact (e.g. PEP 508 markers). The unquoted expansions are worker configuration +# and split into separate arguments on purpose. +set -- /usr/local/bin/uv pip install \ + "$REQ" \ + --target "$TARGET" \ + --no-cache \ + --no-config \ + --no-color \ + --no-deps \ + --link-mode=copy \ + $PY_PATH \ + $INDEX_URL_ARG $EXTRA_INDEX_URL_ARG $TRUSTED_HOST_ARG \ + --system \ + --reinstall \ + --compile-bytecode -echo $CMD -eval $CMD +echo "$@" +exec "$@" diff --git a/backend/windmill-worker/nsjail/install.r.config.proto b/backend/windmill-worker/nsjail/install.r.config.proto index dff9acde15..e844b2e720 100644 --- a/backend/windmill-worker/nsjail/install.r.config.proto +++ b/backend/windmill-worker/nsjail/install.r.config.proto @@ -16,7 +16,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/lock.py.config.proto b/backend/windmill-worker/nsjail/lock.py.config.proto index 14119c4089..60c5573f40 100644 --- a/backend/windmill-worker/nsjail/lock.py.config.proto +++ b/backend/windmill-worker/nsjail/lock.py.config.proto @@ -23,7 +23,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/nsjail/lock.ruby.config.proto b/backend/windmill-worker/nsjail/lock.ruby.config.proto index 6f82f3b748..bcca74e77e 100644 --- a/backend/windmill-worker/nsjail/lock.ruby.config.proto +++ b/backend/windmill-worker/nsjail/lock.ruby.config.proto @@ -19,7 +19,8 @@ clone_newnet: false clone_newuser: {CLONE_NEWUSER} skip_setsid: true -keep_caps: true +# No capability needed: writes go to the rw-mounted dirs as the jail's own uid, like the run.* profiles. +keep_caps: false keep_env: true mount_proc: true diff --git a/backend/windmill-worker/src/nsjail_compat.rs b/backend/windmill-worker/src/nsjail_compat.rs index 3069dcee52..e3b1f7656f 100644 --- a/backend/windmill-worker/src/nsjail_compat.rs +++ b/backend/windmill-worker/src/nsjail_compat.rs @@ -46,4 +46,90 @@ mod tests { assert_eq!(twice.matches("gvisor_compat").count(), 1); assert!(twice.ends_with("\nclone_newcgroup: false\ngvisor_compat: true\n")); } + + /// Every nsjail profile drops its capabilities. + #[test] + fn every_nsjail_config_drops_capabilities() { + let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/nsjail"); + let mut checked = 0; + for entry in std::fs::read_dir(dir).expect("nsjail config dir") { + let path = entry.expect("dir entry").path(); + if path.extension().and_then(|e| e.to_str()) != Some("proto") { + continue; + } + let content = std::fs::read_to_string(&path).expect("read config"); + let settings = content + .lines() + .map(str::trim) + .filter(|l| l.starts_with("keep_caps")) + .collect::<Vec<_>>(); + assert_eq!( + settings, + vec!["keep_caps: false"], + "{} must set keep_caps: false exactly once", + path.display() + ); + checked += 1; + } + assert!( + checked >= 20, + "only {checked} nsjail configs found in {dir}, expected all of them" + ); + } + + /// `REQ` and `TARGET` reach uv as single, unaltered argv words. + #[cfg(unix)] + #[test] + fn download_deps_passes_the_requirement_as_a_literal_argv_word() { + use std::os::unix::fs::PermissionsExt; + + let dir = std::env::temp_dir().join(format!("wm_download_deps_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + + // Stand-in for uv that prints each argument it receives on its own line. + let uv = dir.join("uv_argv_dump"); + std::fs::write( + &uv, + "#!/bin/sh\nfor a in \"$@\"; do printf '<%s>\\n' \"$a\"; done\n", + ) + .expect("write stub"); + std::fs::set_permissions(&uv, std::fs::Permissions::from_mode(0o755)).expect("chmod stub"); + + let script = dir.join("download_deps.sh"); + std::fs::write( + &script, + include_str!("../nsjail/download_deps.py.sh") + .replace("/usr/local/bin/uv", uv.to_str().unwrap()), + ) + .expect("write script"); + + let marker = dir.join("marker"); + let req = format!("x==$(touch {})", marker.display()); + let target = dir.join("target dir with spaces"); + let out = std::process::Command::new("/bin/sh") + .arg(&script) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("REQ", &req) + .env("TARGET", &target) + .output() + .expect("run download_deps.sh"); + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + + assert!( + !marker.exists(), + "REQ was not passed through verbatim; stdout was:\n{stdout}" + ); + assert!( + stdout.contains(&format!("<{req}>\n")), + "the requirement must be one literal argv word; stdout was:\n{stdout}" + ); + assert!( + stdout.contains(&format!("<--target>\n<{}>\n", target.display())), + "--target must be followed by the target dir as one argv word; stdout was:\n{stdout}" + ); + + std::fs::remove_dir_all(&dir).expect("cleanup scratch dir"); + } } From f1c361e3d10eab48ca04be7d7496d509e663d05c Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:15:15 -0400 Subject: [PATCH 079/101] chore(worker): identify init and periodic scripts by how they are queued (#11987) Recognise the worker's own init and periodic scripts through a single helper shared by the bash and PowerShell executors, based on the workspace, identity and tag they are queued with. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- backend/windmill-queue/src/jobs.rs | 131 ++++++++++++++++++- backend/windmill-worker/src/bash_executor.rs | 15 +-- backend/windmill-worker/src/pwsh_executor.rs | 16 +-- 3 files changed, 137 insertions(+), 25 deletions(-) diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index b886a8844d..b8d2458b90 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -483,6 +483,9 @@ pub const PERIODIC_SCRIPT_TAG: &str = "periodic_bash_script"; pub const INIT_SCRIPT_TAG: &str = "init_script"; pub const INIT_SCRIPT_PATH_PREFIX: &str = "init_script_"; pub const PERIODIC_SCRIPT_PATH_PREFIX: &str = "periodic_script_"; +/// The email the worker's own init/periodic scripts are pushed under by [`push_init_job`] +/// and [`push_periodic_bash_job`]. +pub const WORKER_SCRIPT_EMAIL: &str = "worker@windmill.dev"; pub async fn push_init_job<'c>( db: &Pool<Postgres>, @@ -511,7 +514,7 @@ pub async fn push_init_job<'c>( }), PushArgs::from(&ehm), worker_name, - "worker@windmill.dev", + WORKER_SCRIPT_EMAIL, SUPERADMIN_SECRET_EMAIL.to_string(), Some("worker_init_job"), None, @@ -572,7 +575,7 @@ pub async fn push_periodic_bash_job<'c>( }), PushArgs::from(&ehm), worker_name, - "worker@windmill.dev", + WORKER_SCRIPT_EMAIL, SUPERADMIN_SECRET_EMAIL.to_string(), Some("worker_periodic_script_job"), None, @@ -3855,6 +3858,25 @@ pub struct MiniPulledJob { } impl MiniPulledJob { + /// Whether this is an init or periodic script a worker queued for itself + /// ([`push_init_job`], [`push_periodic_bash_job`]). These run outside any sandbox, so every + /// executor that skips isolation uses this check. + pub fn is_worker_own_script(&self) -> bool { + let own_script = |own_tag: &str, path_prefix: &str| { + self.tag == own_tag + && self + .runnable_path + .as_ref() + .is_some_and(|p| p.starts_with(path_prefix)) + }; + self.workspace_id == "admins" + && self.permissioned_as == SUPERADMIN_SECRET_EMAIL + && self.permissioned_as_email == WORKER_SCRIPT_EMAIL + && self.parent_job.is_none() + && (own_script(INIT_SCRIPT_TAG, INIT_SCRIPT_PATH_PREFIX) + || own_script(PERIODIC_SCRIPT_TAG, PERIODIC_SCRIPT_PATH_PREFIX)) + } + pub fn new_inline( workspace_id: String, args: Option<HashMap<String, Box<RawValue>>>, @@ -8959,6 +8981,111 @@ mod git_sync_concurrency_key_tests { } } +#[cfg(test)] +mod worker_own_script_tests { + use super::*; + + const WK: &str = "wk-default-host-a1b2c"; + + /// Built exactly as [`push_init_job`] and [`push_periodic_bash_job`] queue them. + fn own_script(path: &str, tag: &str) -> MiniPulledJob { + MiniPulledJob::new_inline( + "admins".to_string(), + None, + WK.to_string(), + SUPERADMIN_SECRET_EMAIL.to_string(), + WORKER_SCRIPT_EMAIL.to_string(), + Some(path.to_string()), + JobKind::Preview, + None, + tag.to_string(), + Some(ScriptLang::Bash), + ) + } + + /// The init and periodic scripts the worker queues for itself are recognised. + #[test] + fn what_the_worker_queues_for_itself_is_recognized() { + assert!( + own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}{WK}"), INIT_SCRIPT_TAG) + .is_worker_own_script() + ); + assert!(own_script( + &format!("{PERIODIC_SCRIPT_PATH_PREFIX}{WK}_1700000000"), + PERIODIC_SCRIPT_TAG + ) + .is_worker_own_script()); + } + + /// Only the exact shape the worker queues is recognised. + #[test] + fn other_job_shapes_are_not_recognized() { + let init = || own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}x"), INIT_SCRIPT_TAG); + let periodic = || { + own_script( + &format!("{PERIODIC_SCRIPT_PATH_PREFIX}x"), + PERIODIC_SCRIPT_TAG, + ) + }; + for (what, job) in [ + ( + "other workspace", + MiniPulledJob { workspace_id: "ws-a".to_string(), ..init() }, + ), + ( + "other permissioned_as", + MiniPulledJob { permissioned_as: "u/deva".to_string(), ..init() }, + ), + ( + "other email", + MiniPulledJob { permissioned_as_email: "deva@example.com".to_string(), ..init() }, + ), + ( + "flow step", + MiniPulledJob { parent_job: Some(Uuid::from_u128(1)), ..init() }, + ), + ( + "flow step", + MiniPulledJob { parent_job: Some(Uuid::from_u128(1)), ..periodic() }, + ), + ( + "user tag", + own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}x"), "bash"), + ), + ( + "crossed tag", + own_script(&format!("{INIT_SCRIPT_PATH_PREFIX}x"), PERIODIC_SCRIPT_TAG), + ), + ( + "crossed tag", + own_script(&format!("{PERIODIC_SCRIPT_PATH_PREFIX}x"), INIT_SCRIPT_TAG), + ), + ("ordinary path", own_script("u/admin/s", INIT_SCRIPT_TAG)), + ( + "ordinary path", + own_script("u/admin/s", PERIODIC_SCRIPT_TAG), + ), + ] { + assert!( + !job.is_worker_own_script(), + "{what}: {:?}/{:?}/{} must not be recognised as a worker script", + job.workspace_id, + job.runnable_path, + job.tag + ); + } + } + + /// A job without a path is not a worker script. + #[test] + fn a_job_without_a_path_is_not_an_own_script() { + assert!( + !MiniPulledJob { runnable_path: None, ..own_script("x", INIT_SCRIPT_TAG) } + .is_worker_own_script() + ); + } +} + #[cfg(test)] mod preset_handler_path_tests { use super::is_preset_handler_path; diff --git a/backend/windmill-worker/src/bash_executor.rs b/backend/windmill-worker/src/bash_executor.rs index 7ec2f4fd33..217d1927f8 100644 --- a/backend/windmill-worker/src/bash_executor.rs +++ b/backend/windmill-worker/src/bash_executor.rs @@ -21,9 +21,7 @@ use windmill_common::{ #[cfg(feature = "dind")] use windmill_common::error::to_anyhow; -use windmill_queue::{ - append_logs, CanceledBy, MiniPulledJob, INIT_SCRIPT_PATH_PREFIX, PERIODIC_SCRIPT_PATH_PREFIX, -}; +use windmill_queue::{append_logs, CanceledBy, MiniPulledJob}; lazy_static::lazy_static! { pub static ref BIN_BASH: String = std::env::var("BASH_PATH").unwrap_or_else(|_| { @@ -148,14 +146,9 @@ pub async fn handle_bash_job( )); } - // Init/periodic scripts need full system access without isolation - let is_regular_job = job - .runnable_path - .as_ref() - .map(|x| { - !x.starts_with(INIT_SCRIPT_PATH_PREFIX) && !x.starts_with(PERIODIC_SCRIPT_PATH_PREFIX) - }) - .unwrap_or(true); + // Init/periodic scripts need full system access without isolation; see + // `MiniPulledJob::is_worker_own_script`. + let is_regular_job = !job.is_worker_own_script(); // Use nsjail if globally enabled OR if script has #sandbox annotation let nsjail = (is_sandboxing_enabled() || annotation.sandbox) && is_regular_job; diff --git a/backend/windmill-worker/src/pwsh_executor.rs b/backend/windmill-worker/src/pwsh_executor.rs index f1baf9d5aa..4572a868a8 100644 --- a/backend/windmill-worker/src/pwsh_executor.rs +++ b/backend/windmill-worker/src/pwsh_executor.rs @@ -9,9 +9,7 @@ use windmill_common::error::Error; use windmill_common::scripts::ScriptLang; use windmill_common::worker::{to_raw_value, write_file, Connection}; use windmill_common::workspace_dependencies::clean_lock_from_annotations; -use windmill_queue::{ - append_logs, CanceledBy, MiniPulledJob, INIT_SCRIPT_PATH_PREFIX, PERIODIC_SCRIPT_PATH_PREFIX, -}; +use windmill_queue::{append_logs, CanceledBy, MiniPulledJob}; #[cfg(windows)] use crate::SYSTEM_ROOT; @@ -690,15 +688,9 @@ $env:PSModulePath = \"{};$PSModulePathBackup\"", let _ = write_file(job_dir, "result.out", "")?; let _ = write_file(job_dir, "result2.out", "")?; - // Check if this is a regular job (not init or periodic script) - // Init/periodic scripts need full system access without isolation - let is_regular_job = job - .runnable_path - .as_ref() - .map(|x| { - !x.starts_with(INIT_SCRIPT_PATH_PREFIX) && !x.starts_with(PERIODIC_SCRIPT_PATH_PREFIX) - }) - .unwrap_or(true); + // Init/periodic scripts need full system access without isolation; see + // `MiniPulledJob::is_worker_own_script`. + let is_regular_job = !job.is_worker_own_script(); let nsjail = is_sandboxing_enabled() && is_regular_job; let child = if nsjail { From 8af484292f73a477d4ffe22a63a7be8cc258bcb4 Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:35:50 -0400 Subject: [PATCH 080/101] Merge commit from fork The database name of a Postgres resource was the bare positional argument of pg_dump and the value of psql's --dbname. Both forms are interpreted: as a positional argument a name opening with `-` is read as an option of pg_dump (`--file=`, `--restrict-key=`), and in both forms a name holding `=` is expanded as a libpq connection string that overrides the host, port and user Windmill passed before it. libpq reads PGDATABASE as a plain name, neither parsed nor expanded, so the name now goes there. The change is in the shared helpers, so it covers every caller: import_pg_database, export_pg_schema, datatable_clone::make_copy, generate_initial_datatable_migration and pg_import_dump. pg_dump's invocation is extracted into pg_dump_command() beside the existing psql_command() so the argument vector can be asserted on directly. Beside that: - resolve_pg_source_checked_with_kind() now refuses a name opening with `-` for every source and target it resolves, where validate_dbname() only ever reached a target. The check is deliberately narrower than validate_dbname(): a source is any database a user already has, and `2024_archive`, `my.db` or a non-ASCII name are all names Postgres accepts and resources carry today. - export_pg_schema and import_pg_database now require the `code` capability, the one the data table migration endpoints next door already ask for. Both make the API server run pg_dump/psql as children of its own process against a database the request names, so the role that may not run code should not reach them; they stay open to every author, who can run pg_dump in a job anyway. The frontend offers both only from the database manager. Co-authored-by: Claude Opus 5 <noreply@anthropic.com> --- .../tests/operator_manage_rights.rs | 59 +++++++ .../windmill-api-workspaces/src/workspaces.rs | 163 ++++++++++++++++-- backend/windmill-common/src/lib.rs | 64 +++++++ 3 files changed, 273 insertions(+), 13 deletions(-) diff --git a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs index cfbeae7a69..dbc5f36e01 100644 --- a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs +++ b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs @@ -406,3 +406,62 @@ async fn test_operators_draft_resources_and_variables(db: Pool<Postgres>) -> any Ok(()) } + +/// The two endpoints that make the API server run `pg_dump`/`psql` against a database a request +/// names are closed to a role that cannot run code. +/// +/// Both polarities on each route: a 403 alone would equally be a route that does not exist or one +/// refusing the source for some other reason, and the admin's 400 shows the gate is about the role +/// rather than the request. The source is deliberately unresolvable, so the gate is the only thing +/// that can answer 403 and no database is ever reached. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_dumping_a_database_needs_the_code_right(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + windmill_common::roles::invalidate_all_roles_cache(); + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + + let cases = [ + ( + "workspaces/export_pg_schema", + json!({"source": "u/operator/not-a-source"}), + "export a database schema", + ), + ( + "workspaces/import_pg_database", + json!({"source": "u/operator/not-a-source", "target": "u/operator/not-a-source", + "fork_behavior": "schema_only"}), + "import a database", + ), + ]; + + for (route, body, action) in cases { + let resp = operator_client() + .post(format!("{api}/{route}")) + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert_eq!(status, 403, "{route}: {text}"); + assert!( + text.contains(&format!("Your role cannot {action} in this workspace")), + "{route} refused for another reason: {text}" + ); + + let resp = reqwest::Client::new() + .post(format!("{api}/{route}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert_eq!(status, 400, "{route}: {text}"); + assert!(text.contains("Invalid source format"), "{route}: {text}"); + } + + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 0534f3e7ee..9a6efec148 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -3366,6 +3366,10 @@ pub(crate) async fn resolve_pg_source_checked_with_kind( let pg: PgDatabase = serde_json::from_value(db_resource) .map_err(|e| Error::internal_err(format!("Failed to parse database credentials: {}", e)))?; + // Checked here rather than at each caller: every source and target of a dump, restore or copy + // comes through this function, and `validate_dbname` only ever reaches a target. The check is + // deliberately the narrow one — see `validate_dbname_not_option_like`. + windmill_common::validate_dbname_not_option_like(&pg.dbname)?; Ok((pg, managed_kind)) } @@ -3455,21 +3459,20 @@ pub(crate) struct PgDumpOptions<'a> { pub(crate) no_acl: bool, } -/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. -/// Returns a DumpFile handle; the file is deleted when the handle is dropped. -pub(crate) async fn pg_dump_database( +/// A pg_dump invocation against `pg_db` writing to `dump_path`, carrying the connection settings +/// the CLI reads from the environment. The returned file, when there is one, holds the root +/// certificate the command points at and must outlive it. +fn pg_dump_command( pg_db: &PgDatabase, opts: PgDumpOptions<'_>, -) -> Result<DumpFile> { - let dump_file = DumpFile::new()?; - + dump_path: &std::path::Path, +) -> Result<(tokio::process::Command, Option<DumpFile>)> { let host = &pg_db.host; let port = pg_db.port.unwrap_or(5432).to_string(); let user = pg_db.login_name(); - let dbname = &pg_db.dbname; let mut cmd = tokio::process::Command::new("pg_dump"); - cmd.arg("--format=plain").arg("--file").arg(&dump_file.path); + cmd.arg("--format=plain").arg("--file").arg(dump_path); if opts.schema_only { cmd.arg("--schema-only"); } @@ -3487,13 +3490,31 @@ pub(crate) async fn pg_dump_database( .arg("--port") .arg(&port) .arg("--username") - .arg(user) - .arg(dbname); + .arg(user); + + // The name comes from a resource, so it never goes on the command line: as the positional + // argument a name starting with `-` is read as an option of pg_dump (`--file`, + // `--restrict-key`), and as `--dbname` a name holding `=` is expanded as a libpq connection + // string overriding the host, port and user set above. libpq takes the environment variable + // as a plain database name, neither parsed as an option nor expanded. + cmd.env("PGDATABASE", &pg_db.dbname); if let Some(ref password) = pg_db.password { cmd.env("PGPASSWORD", password); } - let _root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; + let root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; + Ok((cmd, root_cert)) +} + +/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. +/// Returns a DumpFile handle; the file is deleted when the handle is dropped. +pub(crate) async fn pg_dump_database( + pg_db: &PgDatabase, + opts: PgDumpOptions<'_>, +) -> Result<DumpFile> { + let dump_file = DumpFile::new()?; + + let (mut cmd, _root_cert) = pg_dump_command(pg_db, opts, &dump_file.path)?; let output = cmd .output() @@ -3619,12 +3640,14 @@ fn psql_command(pg_db: &PgDatabase) -> Result<(tokio::process::Command, Option<D .arg(pg_db.port.unwrap_or(5432).to_string()) .arg("--username") .arg(pg_db.login_name()) - .arg("--dbname") - .arg(&pg_db.dbname) .arg("--no-psqlrc") .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); + // Not `--dbname`, which expands a name holding `=` as a libpq connection string overriding + // the host, port and user set above. See `pg_dump_command`. + cmd.env("PGDATABASE", &pg_db.dbname); + if let Some(ref password) = pg_db.password { cmd.env("PGPASSWORD", password); } @@ -3715,6 +3738,97 @@ mod pg_tls_env_tests { } } +/// The database name of a resource reaches `pg_dump` and `psql` through `PGDATABASE`, never in +/// their argument vector, so neither an option (`--file=`, `--restrict-key=`) nor a libpq +/// connection string (`host=... port=...`) in that field is parsed as one. +#[cfg(test)] +mod pg_dbname_env_tests { + use super::{pg_dump_command, pg_dump_database, psql_command, DumpFile, PgDumpOptions}; + use windmill_common::PgDatabase; + + /// Nothing listens on that port. + fn pg_db(dbname: &str) -> PgDatabase { + PgDatabase { + host: "127.0.0.1".to_string(), + user: None, + password: None, + port: Some(1), + sslmode: None, + dbname: dbname.to_string(), + root_certificate_pem: None, + accept_invalid_certs: None, + use_iam_auth: None, + region: None, + options: None, + } + } + + fn pgdatabase_of(cmd: &std::process::Command) -> Option<std::ffi::OsString> { + cmd.get_envs() + .find(|(k, _)| *k == "PGDATABASE") + .and_then(|(_, v)| v.map(|v| v.to_os_string())) + } + + #[test] + fn pg_dump_takes_the_dbname_from_the_environment() { + let dump_file = DumpFile::new().unwrap(); + let name = "--file=/tmp/written_by_the_caller"; + let (cmd, _root_cert) = + pg_dump_command(&pg_db(name), PgDumpOptions::default(), &dump_file.path).unwrap(); + let cmd = cmd.as_std(); + assert!( + cmd.get_args().all(|arg| arg != name), + "the dbname is still in pg_dump's argument vector" + ); + assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); + // The only `--file` pg_dump is given is still Windmill's own. + assert_eq!( + cmd.get_args() + .filter(|arg| arg.to_string_lossy().starts_with("--file")) + .count(), + 1 + ); + } + + #[test] + fn psql_takes_the_dbname_from_the_environment() { + let name = "host=elsewhere"; + let (cmd, _root_cert) = psql_command(&pg_db(name)).unwrap(); + let cmd = cmd.as_std(); + assert!( + cmd.get_args().all(|arg| arg != name), + "the dbname is still in psql's argument vector" + ); + assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); + } + + /// The same, observed on the real binary: an option-shaped name must reach the connection + /// attempt rather than pg_dump's option parser. Skipped where pg_dump is not installed — + /// which is why the assertion also requires that pg_dump ran at all (our `pg_dump failed:` + /// prefix) instead of only that the option message is absent. + #[tokio::test] + async fn pg_dump_does_not_read_an_option_shaped_dbname_as_an_option() { + if std::process::Command::new("pg_dump") + .arg("--version") + .output() + .is_err() + { + eprintln!("skipped: pg_dump is not installed"); + return; + } + let Err(err) = pg_dump_database(&pg_db("--no-such-option"), PgDumpOptions::default()).await + else { + panic!("pg_dump reached a server on 127.0.0.1:1"); + }; + let err = err.to_string(); + assert!( + err.contains("pg_dump failed:"), + "pg_dump did not run: {err}" + ); + assert!(!err.contains("unrecognized option"), "{err}"); + } +} + /// GUC names the server backing `pg_db` knows about. /// /// Asked through psql rather than a tokio-postgres connection so the lookup reaches @@ -4061,6 +4175,25 @@ fn ensure_copied_without_roles(governing: &GoverningDatatable) -> Result<()> { Ok(()) } +/// Gate for the endpoints that make the API server run `pg_dump`/`psql` against a database a +/// request names. +/// +/// Those two processes are children of the API server, outside any job sandbox and holding its +/// environment, and the dump they exchange is a `psql` script assembled from strings the source +/// server returns — so reaching them is close enough to running code on the server that the role +/// which may not run code at all must not reach them either. `code` is the capability the data +/// table migration endpoints next door already ask for (`datatable_migrations::ensure_not_operator`), +/// and not admin: the database manager offers an export and an import of a user's own Postgres +/// resource to every author, who can run the same `pg_dump` in a job anyway. +async fn ensure_can_dump_databases( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + action: &str, +) -> Result<()> { + windmill_common::workspaces::check_role_can_code(db, w_id, authed, action).await +} + /// Import (pg_dump/pg_import) from source to target async fn import_pg_database( authed: ApiAuthed, @@ -4069,6 +4202,8 @@ async fn import_pg_database( Path(w_id): Path<String>, Json(req): Json<ImportPgDatabaseRequest>, ) -> Result<String> { + ensure_can_dump_databases(&db, &w_id, &authed, "import a database").await?; + if req.fork_behavior == DataTableForkBehavior::KeepOriginal { return Ok("No action needed for KeepOriginal behavior".to_string()); } @@ -4185,6 +4320,8 @@ async fn export_pg_schema( Path(w_id): Path<String>, Json(req): Json<ExportPgSchemaRequest>, ) -> Result<String> { + ensure_can_dump_databases(&db, &w_id, &authed, "export a database schema").await?; + let pg = resolve_pg_source_checked(&db, &user_db, &authed, &w_id, &req.source).await?; let dump_file = pg_dump_database( &pg, diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 4e1524580e..2d60008373 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -843,6 +843,50 @@ mod validate_dbname_tests { } } +#[cfg(test)] +mod validate_dbname_not_option_like_tests { + use super::validate_dbname_not_option_like; + + /// A source is any database a user already has, so everything `validate_dbname` refuses but + /// Postgres accepts has to keep working. + #[test] + fn accepts_every_name_that_is_not_an_option() { + for name in [ + "mydb", + "My-Db_1", + "2024_archive", + "my.db", + "db with spaces", + "Grüße", + "host=elsewhere port=5433", + "", + "a-dash-inside--it", + ] { + assert!( + validate_dbname_not_option_like(name).is_ok(), + "refused the legitimate name {name:?}" + ); + } + } + + #[test] + fn rejects_a_name_that_an_argument_vector_would_read_as_an_option() { + for name in [ + "--file=/tmp/x", + "--restrict-key=k", + "-f", + "-", + " --file=/tmp/x", + "\t-f", + ] { + let err = validate_dbname_not_option_like(name) + .expect_err(&format!("accepted the option-like name {name:?}")) + .to_string(); + assert!(err.contains("cannot start with '-'"), "{err}"); + } + } +} + #[cfg(test)] mod pg_tls_tests { use super::PgDatabase; @@ -1595,6 +1639,26 @@ pub fn validate_dbname(dbname: &str) -> error::Result<()> { Ok(()) } +/// The one restriction on the name of a database Windmill only *reads from*: it may not look like +/// a command-line option. +/// +/// [`validate_dbname`] is the rule for a name Windmill creates or interpolates into SQL, and is +/// far too narrow here: a source is any Postgres resource a user already has, and an existing +/// database may legitimately be named `2024_archive`, `my.db`, `Grüße` or anything else Postgres +/// accepts as a quoted identifier. Refusing those would break working resources. A name opening +/// with `-` is the one shape that is never a database and always a mistake or an attempt to smuggle +/// an option into a `pg_dump`/`psql` argument vector, so it is refused wherever a source is +/// resolved — the commands themselves pass the name through `PGDATABASE` and never on the command +/// line, and this keeps a future caller that forgets from re-opening that door. +pub fn validate_dbname_not_option_like(dbname: &str) -> error::Result<()> { + if dbname.trim_start().starts_with('-') { + return Err(error::Error::BadRequest( + "Database name cannot start with '-'".to_string(), + )); + } + Ok(()) +} + /// Lock the instance databases among `names` until `tx` ends, in a stable order. Taken by every /// settings save naming an instance database, and by [`drop_unused_instance_database`]: a save /// cannot start using a database between that drop's check that nothing does and the drop. From 812ff6ea5e1144e38d4ba00a48de7d35bd6178bd Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:49:17 -0400 Subject: [PATCH 081/101] Merge commit from fork Co-authored-by: Claude Opus 5 <noreply@anthropic.com> --- backend/ee-repo-ref.txt | 2 +- backend/windmill-api-flows/src/flows.rs | 42 ++++- .../tests/operator_manage_rights.rs | 59 ------- backend/windmill-api-jobs/src/query.rs | 37 +++- backend/windmill-api-schedule/src/lib.rs | 7 +- backend/windmill-api-scripts/src/scripts.rs | 4 +- .../windmill-api-workspaces/src/workspaces.rs | 163 ++---------------- backend/windmill-api/src/apps.rs | 4 +- backend/windmill-api/src/mcp/utils.rs | 4 +- backend/windmill-api/src/raw_apps.rs | 4 +- backend/windmill-common/src/lib.rs | 64 ------- backend/windmill-store/src/resources.rs | 7 +- backend/windmill-store/src/variables.rs | 7 +- 13 files changed, 105 insertions(+), 299 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index d961a68842..1986b0b23f 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -b6e23d229966cf0019c0a1926a254fda658d8def +5dfdf811c862c689e42f03f485e02f9f1e7bc7ca diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index 4c0ecaf4c4..5d4268a93c 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -134,6 +134,17 @@ async fn list_search_flows( Ok(Json(rows)) } +/// `WHERE` condition matching one label, directly on the flow or inherited from its folder. +/// +/// The template has two `?`, so both are filled in a single `binds` pass. Chaining `bind` +/// would not work: `bind` replaces the first `?` of the string *as it is at that moment*, +/// so the second call would find the `?` that the first call inserted as part of the bound +/// value and substitute there, leaving the value partly outside its quotes. +fn label_condition(label: &str) -> String { + "(o.labels @> ARRAY[?] OR folder_labels(o.workspace_id, o.path) @> ARRAY[?])" + .binds(&[&label.trim()]) +} + async fn list_flows( authed: ApiAuthed, Extension(user_db): Extension<UserDB>, @@ -217,11 +228,7 @@ async fn list_flows( } if let Some(label) = &lq.label { for l in label.split(',') { - sqlb.and_where( - "(o.labels @> ARRAY[?] OR folder_labels(o.workspace_id, o.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), - ); + sqlb.and_where(label_condition(l)); } } @@ -2284,6 +2291,31 @@ mod tests { const SECOND: Duration = Duration::from_secs(1); + #[test] + fn label_condition_fills_both_placeholders_in_one_pass() { + // Ordinary label: unchanged behaviour, the value appears quoted in both positions. + assert_eq!( + super::label_condition(" finance "), + "(o.labels @> ARRAY['finance'] OR folder_labels(o.workspace_id, o.path) @> ARRAY['finance'])" + ); + + // A `?` in the label must stay inside the quoted literal in both positions and must + // not leave a placeholder behind. With chained `bind`s this produced + // `ARRAY['a'a?b'b'] ... ARRAY[?]`, i.e. label text outside the quotes. + let cond = super::label_condition("a?b"); + assert_eq!( + cond, + "(o.labels @> ARRAY['a?b'] OR folder_labels(o.workspace_id, o.path) @> ARRAY['a?b'])" + ); + assert!(!cond.contains("ARRAY[?]")); + + // Single quotes keep being escaped by doubling. + assert_eq!( + super::label_condition("a'?b"), + "(o.labels @> ARRAY['a''?b'] OR folder_labels(o.workspace_id, o.path) @> ARRAY['a''?b'])" + ); + } + #[test] fn flowmodule_serde() { let fv = FlowValue { diff --git a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs index dbc5f36e01..cfbeae7a69 100644 --- a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs +++ b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs @@ -406,62 +406,3 @@ async fn test_operators_draft_resources_and_variables(db: Pool<Postgres>) -> any Ok(()) } - -/// The two endpoints that make the API server run `pg_dump`/`psql` against a database a request -/// names are closed to a role that cannot run code. -/// -/// Both polarities on each route: a 403 alone would equally be a route that does not exist or one -/// refusing the source for some other reason, and the admin's 400 shows the gate is about the role -/// rather than the request. The source is deliberately unresolvable, so the gate is the only thing -/// that can answer 403 and no database is ever reached. -#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] -#[serial] -async fn test_dumping_a_database_needs_the_code_right(db: Pool<Postgres>) -> anyhow::Result<()> { - initialize_tracing().await; - windmill_common::roles::invalidate_all_roles_cache(); - let server = ApiServer::start(db.clone()).await?; - let port = server.addr.port(); - let api = format!("http://localhost:{port}/api/w/{WS}"); - - let cases = [ - ( - "workspaces/export_pg_schema", - json!({"source": "u/operator/not-a-source"}), - "export a database schema", - ), - ( - "workspaces/import_pg_database", - json!({"source": "u/operator/not-a-source", "target": "u/operator/not-a-source", - "fork_behavior": "schema_only"}), - "import a database", - ), - ]; - - for (route, body, action) in cases { - let resp = operator_client() - .post(format!("{api}/{route}")) - .json(&body) - .send() - .await?; - let status = resp.status(); - let text = resp.text().await?; - assert_eq!(status, 403, "{route}: {text}"); - assert!( - text.contains(&format!("Your role cannot {action} in this workspace")), - "{route} refused for another reason: {text}" - ); - - let resp = reqwest::Client::new() - .post(format!("{api}/{route}")) - .header("Authorization", "Bearer SECRET_TOKEN") - .json(&body) - .send() - .await?; - let status = resp.status(); - let text = resp.text().await?; - assert_eq!(status, 400, "{route}: {text}"); - assert!(text.contains("Invalid source format"), "{route}: {text}"); - } - - Ok(()) -} diff --git a/backend/windmill-api-jobs/src/query.rs b/backend/windmill-api-jobs/src/query.rs index 96d8ca3698..ebfc0c3725 100644 --- a/backend/windmill-api-jobs/src/query.rs +++ b/backend/windmill-api-jobs/src/query.rs @@ -268,9 +268,10 @@ pub fn filter_list_queue_query( if let Some(bf) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(bf)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(runnable_path ILIKE ? OR v2_job.tag ILIKE ? OR trigger ILIKE ? OR trigger_kind::text ILIKE ?)" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } @@ -490,7 +491,7 @@ pub fn filter_list_completed_query( } if let Some(dt) = &lq.created_or_started_after { let ts = dt.to_rfc3339(); - sqlb.and_where("(created_at >= ? OR started_at >= ?)".bind(&ts).bind(&ts)); + sqlb.and_where("(created_at >= ? OR started_at >= ?)".binds(&[&ts])); } if let Some(dt) = &lq.created_before { @@ -591,10 +592,11 @@ pub fn filter_list_completed_query( if let Some(bf) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(bf)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(runnable_path ILIKE ? OR v2_job.tag ILIKE ? OR trigger ILIKE ? OR trigger_kind::text ILIKE ? \ OR EXISTS (SELECT 1 FROM unnest(v2_job.labels) lbl WHERE lbl ILIKE ?))" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } @@ -945,6 +947,20 @@ mod tests { assert!(sql.contains("'schedule'")); } + #[test] + fn test_queue_broad_filter_with_question_mark() { + let lq = ListQueueQuery { broad_filter: Some("a?b".to_string()), ..empty_queue_query() }; + let sqlb = filter_list_queue_query( + SqlBuilder::select_from("v2_job_queue").clone(), + &lq, + "ws", + false, + ); + let sql = build_sql(sqlb); + assert_eq!(sql.matches("ILIKE '%a?b%'").count(), 4); + assert!(!sql.contains("ILIKE ?")); + } + // --- Completed query tests --- #[test] @@ -1124,4 +1140,19 @@ mod tests { let sql = build_sql(sqlb); assert!(sql.contains("result @>")); } + + #[test] + fn test_completed_broad_filter_with_question_mark() { + let lq = + ListCompletedQuery { broad_filter: Some("a?b".to_string()), ..empty_completed_query() }; + let sqlb = filter_list_completed_query( + SqlBuilder::select_from("v2_job_completed").clone(), + &lq, + "ws", + false, + ); + let sql = build_sql(sqlb); + assert_eq!(sql.matches("ILIKE '%a?b%'").count(), 5); + assert!(!sql.contains("ILIKE ?")); + } } diff --git a/backend/windmill-api-schedule/src/lib.rs b/backend/windmill-api-schedule/src/lib.rs index 787742d18d..e2fa7da8fe 100644 --- a/backend/windmill-api-schedule/src/lib.rs +++ b/backend/windmill-api-schedule/src/lib.rs @@ -894,17 +894,18 @@ async fn list_schedule( } if let Some(broad_filter) = &lsq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(broad_filter)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(path ILIKE ? OR script_path ILIKE ? OR description ILIKE ? OR summary ILIKE ? OR schedule ILIKE ?)" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } if let Some(label) = &lsq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(labels @> ARRAY[?] OR folder_labels(workspace_id, path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index e6dcfe8155..4e8516b8ed 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -309,10 +309,10 @@ async fn list_scripts( } if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(o.labels @> ARRAY[?] OR folder_labels(o.workspace_id, o.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 9a6efec148..0534f3e7ee 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -3366,10 +3366,6 @@ pub(crate) async fn resolve_pg_source_checked_with_kind( let pg: PgDatabase = serde_json::from_value(db_resource) .map_err(|e| Error::internal_err(format!("Failed to parse database credentials: {}", e)))?; - // Checked here rather than at each caller: every source and target of a dump, restore or copy - // comes through this function, and `validate_dbname` only ever reaches a target. The check is - // deliberately the narrow one — see `validate_dbname_not_option_like`. - windmill_common::validate_dbname_not_option_like(&pg.dbname)?; Ok((pg, managed_kind)) } @@ -3459,20 +3455,21 @@ pub(crate) struct PgDumpOptions<'a> { pub(crate) no_acl: bool, } -/// A pg_dump invocation against `pg_db` writing to `dump_path`, carrying the connection settings -/// the CLI reads from the environment. The returned file, when there is one, holds the root -/// certificate the command points at and must outlive it. -fn pg_dump_command( +/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. +/// Returns a DumpFile handle; the file is deleted when the handle is dropped. +pub(crate) async fn pg_dump_database( pg_db: &PgDatabase, opts: PgDumpOptions<'_>, - dump_path: &std::path::Path, -) -> Result<(tokio::process::Command, Option<DumpFile>)> { +) -> Result<DumpFile> { + let dump_file = DumpFile::new()?; + let host = &pg_db.host; let port = pg_db.port.unwrap_or(5432).to_string(); let user = pg_db.login_name(); + let dbname = &pg_db.dbname; let mut cmd = tokio::process::Command::new("pg_dump"); - cmd.arg("--format=plain").arg("--file").arg(dump_path); + cmd.arg("--format=plain").arg("--file").arg(&dump_file.path); if opts.schema_only { cmd.arg("--schema-only"); } @@ -3490,31 +3487,13 @@ fn pg_dump_command( .arg("--port") .arg(&port) .arg("--username") - .arg(user); - - // The name comes from a resource, so it never goes on the command line: as the positional - // argument a name starting with `-` is read as an option of pg_dump (`--file`, - // `--restrict-key`), and as `--dbname` a name holding `=` is expanded as a libpq connection - // string overriding the host, port and user set above. libpq takes the environment variable - // as a plain database name, neither parsed as an option nor expanded. - cmd.env("PGDATABASE", &pg_db.dbname); + .arg(user) + .arg(dbname); if let Some(ref password) = pg_db.password { cmd.env("PGPASSWORD", password); } - let root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; - Ok((cmd, root_cert)) -} - -/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. -/// Returns a DumpFile handle; the file is deleted when the handle is dropped. -pub(crate) async fn pg_dump_database( - pg_db: &PgDatabase, - opts: PgDumpOptions<'_>, -) -> Result<DumpFile> { - let dump_file = DumpFile::new()?; - - let (mut cmd, _root_cert) = pg_dump_command(pg_db, opts, &dump_file.path)?; + let _root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; let output = cmd .output() @@ -3640,14 +3619,12 @@ fn psql_command(pg_db: &PgDatabase) -> Result<(tokio::process::Command, Option<D .arg(pg_db.port.unwrap_or(5432).to_string()) .arg("--username") .arg(pg_db.login_name()) + .arg("--dbname") + .arg(&pg_db.dbname) .arg("--no-psqlrc") .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); - // Not `--dbname`, which expands a name holding `=` as a libpq connection string overriding - // the host, port and user set above. See `pg_dump_command`. - cmd.env("PGDATABASE", &pg_db.dbname); - if let Some(ref password) = pg_db.password { cmd.env("PGPASSWORD", password); } @@ -3738,97 +3715,6 @@ mod pg_tls_env_tests { } } -/// The database name of a resource reaches `pg_dump` and `psql` through `PGDATABASE`, never in -/// their argument vector, so neither an option (`--file=`, `--restrict-key=`) nor a libpq -/// connection string (`host=... port=...`) in that field is parsed as one. -#[cfg(test)] -mod pg_dbname_env_tests { - use super::{pg_dump_command, pg_dump_database, psql_command, DumpFile, PgDumpOptions}; - use windmill_common::PgDatabase; - - /// Nothing listens on that port. - fn pg_db(dbname: &str) -> PgDatabase { - PgDatabase { - host: "127.0.0.1".to_string(), - user: None, - password: None, - port: Some(1), - sslmode: None, - dbname: dbname.to_string(), - root_certificate_pem: None, - accept_invalid_certs: None, - use_iam_auth: None, - region: None, - options: None, - } - } - - fn pgdatabase_of(cmd: &std::process::Command) -> Option<std::ffi::OsString> { - cmd.get_envs() - .find(|(k, _)| *k == "PGDATABASE") - .and_then(|(_, v)| v.map(|v| v.to_os_string())) - } - - #[test] - fn pg_dump_takes_the_dbname_from_the_environment() { - let dump_file = DumpFile::new().unwrap(); - let name = "--file=/tmp/written_by_the_caller"; - let (cmd, _root_cert) = - pg_dump_command(&pg_db(name), PgDumpOptions::default(), &dump_file.path).unwrap(); - let cmd = cmd.as_std(); - assert!( - cmd.get_args().all(|arg| arg != name), - "the dbname is still in pg_dump's argument vector" - ); - assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); - // The only `--file` pg_dump is given is still Windmill's own. - assert_eq!( - cmd.get_args() - .filter(|arg| arg.to_string_lossy().starts_with("--file")) - .count(), - 1 - ); - } - - #[test] - fn psql_takes_the_dbname_from_the_environment() { - let name = "host=elsewhere"; - let (cmd, _root_cert) = psql_command(&pg_db(name)).unwrap(); - let cmd = cmd.as_std(); - assert!( - cmd.get_args().all(|arg| arg != name), - "the dbname is still in psql's argument vector" - ); - assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); - } - - /// The same, observed on the real binary: an option-shaped name must reach the connection - /// attempt rather than pg_dump's option parser. Skipped where pg_dump is not installed — - /// which is why the assertion also requires that pg_dump ran at all (our `pg_dump failed:` - /// prefix) instead of only that the option message is absent. - #[tokio::test] - async fn pg_dump_does_not_read_an_option_shaped_dbname_as_an_option() { - if std::process::Command::new("pg_dump") - .arg("--version") - .output() - .is_err() - { - eprintln!("skipped: pg_dump is not installed"); - return; - } - let Err(err) = pg_dump_database(&pg_db("--no-such-option"), PgDumpOptions::default()).await - else { - panic!("pg_dump reached a server on 127.0.0.1:1"); - }; - let err = err.to_string(); - assert!( - err.contains("pg_dump failed:"), - "pg_dump did not run: {err}" - ); - assert!(!err.contains("unrecognized option"), "{err}"); - } -} - /// GUC names the server backing `pg_db` knows about. /// /// Asked through psql rather than a tokio-postgres connection so the lookup reaches @@ -4175,25 +4061,6 @@ fn ensure_copied_without_roles(governing: &GoverningDatatable) -> Result<()> { Ok(()) } -/// Gate for the endpoints that make the API server run `pg_dump`/`psql` against a database a -/// request names. -/// -/// Those two processes are children of the API server, outside any job sandbox and holding its -/// environment, and the dump they exchange is a `psql` script assembled from strings the source -/// server returns — so reaching them is close enough to running code on the server that the role -/// which may not run code at all must not reach them either. `code` is the capability the data -/// table migration endpoints next door already ask for (`datatable_migrations::ensure_not_operator`), -/// and not admin: the database manager offers an export and an import of a user's own Postgres -/// resource to every author, who can run the same `pg_dump` in a job anyway. -async fn ensure_can_dump_databases( - db: &DB, - w_id: &str, - authed: &ApiAuthed, - action: &str, -) -> Result<()> { - windmill_common::workspaces::check_role_can_code(db, w_id, authed, action).await -} - /// Import (pg_dump/pg_import) from source to target async fn import_pg_database( authed: ApiAuthed, @@ -4202,8 +4069,6 @@ async fn import_pg_database( Path(w_id): Path<String>, Json(req): Json<ImportPgDatabaseRequest>, ) -> Result<String> { - ensure_can_dump_databases(&db, &w_id, &authed, "import a database").await?; - if req.fork_behavior == DataTableForkBehavior::KeepOriginal { return Ok("No action needed for KeepOriginal behavior".to_string()); } @@ -4320,8 +4185,6 @@ async fn export_pg_schema( Path(w_id): Path<String>, Json(req): Json<ExportPgSchemaRequest>, ) -> Result<String> { - ensure_can_dump_databases(&db, &w_id, &authed, "export a database schema").await?; - let pg = resolve_pg_source_checked(&db, &user_db, &authed, &w_id, &req.source).await?; let dump_file = pg_dump_database( &pg, diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 773e407372..575306fe95 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -740,10 +740,10 @@ async fn list_apps( if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(app.labels @> ARRAY[?] OR folder_labels(app.workspace_id, app.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index dcf84e1851..6e125eefc6 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -183,8 +183,8 @@ fn items_query( let mut sqlb = SqlBuilder::select_from(&format!("{} as o", item_type)); if scope_type == "favorites" { sqlb.join("favorite") - .on("favorite.favorite_kind = ? AND favorite.workspace_id = o.workspace_id AND favorite.path = o.path AND favorite.usr = ?".bind(&item_type) - .bind(&authed.username)); + .on("favorite.favorite_kind = ? AND favorite.workspace_id = o.workspace_id AND favorite.path = o.path AND favorite.usr = ?" + .binds(&[&item_type, &authed.username])); } sqlb.and_where("o.workspace_id = ?".bind(&workspace_id)) .and_where("o.archived = false"); diff --git a/backend/windmill-api/src/raw_apps.rs b/backend/windmill-api/src/raw_apps.rs index 35e4f693a4..ad53872ca0 100644 --- a/backend/windmill-api/src/raw_apps.rs +++ b/backend/windmill-api/src/raw_apps.rs @@ -98,10 +98,10 @@ async fn list_apps( if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(app.labels @> ARRAY[?] OR folder_labels(app.workspace_id, app.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 2d60008373..4e1524580e 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -843,50 +843,6 @@ mod validate_dbname_tests { } } -#[cfg(test)] -mod validate_dbname_not_option_like_tests { - use super::validate_dbname_not_option_like; - - /// A source is any database a user already has, so everything `validate_dbname` refuses but - /// Postgres accepts has to keep working. - #[test] - fn accepts_every_name_that_is_not_an_option() { - for name in [ - "mydb", - "My-Db_1", - "2024_archive", - "my.db", - "db with spaces", - "Grüße", - "host=elsewhere port=5433", - "", - "a-dash-inside--it", - ] { - assert!( - validate_dbname_not_option_like(name).is_ok(), - "refused the legitimate name {name:?}" - ); - } - } - - #[test] - fn rejects_a_name_that_an_argument_vector_would_read_as_an_option() { - for name in [ - "--file=/tmp/x", - "--restrict-key=k", - "-f", - "-", - " --file=/tmp/x", - "\t-f", - ] { - let err = validate_dbname_not_option_like(name) - .expect_err(&format!("accepted the option-like name {name:?}")) - .to_string(); - assert!(err.contains("cannot start with '-'"), "{err}"); - } - } -} - #[cfg(test)] mod pg_tls_tests { use super::PgDatabase; @@ -1639,26 +1595,6 @@ pub fn validate_dbname(dbname: &str) -> error::Result<()> { Ok(()) } -/// The one restriction on the name of a database Windmill only *reads from*: it may not look like -/// a command-line option. -/// -/// [`validate_dbname`] is the rule for a name Windmill creates or interpolates into SQL, and is -/// far too narrow here: a source is any Postgres resource a user already has, and an existing -/// database may legitimately be named `2024_archive`, `my.db`, `Grüße` or anything else Postgres -/// accepts as a quoted identifier. Refusing those would break working resources. A name opening -/// with `-` is the one shape that is never a database and always a mistake or an attempt to smuggle -/// an option into a `pg_dump`/`psql` argument vector, so it is refused wherever a source is -/// resolved — the commands themselves pass the name through `PGDATABASE` and never on the command -/// line, and this keeps a future caller that forgets from re-opening that door. -pub fn validate_dbname_not_option_like(dbname: &str) -> error::Result<()> { - if dbname.trim_start().starts_with('-') { - return Err(error::Error::BadRequest( - "Database name cannot start with '-'".to_string(), - )); - } - Ok(()) -} - /// Lock the instance databases among `names` until `tx` ends, in a stable order. Taken by every /// settings save naming an instance database, and by [`drop_unused_instance_database`]: a save /// cannot start using a database between that drop's check that nothing does and the drop. diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index 9af92361f6..541369f327 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -439,9 +439,10 @@ async fn list_resources( if let Some(broad_filter) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(broad_filter)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(resource.path ILIKE ? OR resource.description ILIKE ? OR resource_type ILIKE ? OR resource.value::text ILIKE ?)" - .bind(&pat).bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } @@ -455,10 +456,10 @@ async fn list_resources( if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(resource.labels @> ARRAY[?] OR folder_labels(resource.workspace_id, resource.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index 7d85fa59ce..e9aa3ab60d 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -200,18 +200,19 @@ async fn list_variables( if let Some(broad_filter) = &lq.broad_filter { let pat = format!("%{}%", escape_ilike_pattern(broad_filter)); + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(variable.path ILIKE ? OR variable.description ILIKE ? OR (is_secret = FALSE AND variable.value ILIKE ?))" - .bind(&pat).bind(&pat).bind(&pat) + .binds(&[&pat]), ); } if let Some(label) = &lq.label { for l in label.split(',') { + // `binds` fills every `?` in one pass; chained `bind`s would re-scan a `?` in the bound value sqlb.and_where( "(variable.labels @> ARRAY[?] OR folder_labels(variable.workspace_id, variable.path) @> ARRAY[?])" - .bind(&l.trim()) - .bind(&l.trim()), + .binds(&[&l.trim()]), ); } } From 45d3c951bb8827c67daaaf75ed52f3c3e1215911 Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:56:08 -0400 Subject: [PATCH 082/101] fix: restore workspace pg_dump changes reverted by 812ff6ea5e (#11988) 812ff6ea5e was squashed from a branch based before 8af48429 and reverted its changes to these three files. Restore them as they were in 8af48429. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../tests/operator_manage_rights.rs | 59 +++++++ .../windmill-api-workspaces/src/workspaces.rs | 163 ++++++++++++++++-- backend/windmill-common/src/lib.rs | 64 +++++++ 3 files changed, 273 insertions(+), 13 deletions(-) diff --git a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs index cfbeae7a69..dbc5f36e01 100644 --- a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs +++ b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs @@ -406,3 +406,62 @@ async fn test_operators_draft_resources_and_variables(db: Pool<Postgres>) -> any Ok(()) } + +/// The two endpoints that make the API server run `pg_dump`/`psql` against a database a request +/// names are closed to a role that cannot run code. +/// +/// Both polarities on each route: a 403 alone would equally be a route that does not exist or one +/// refusing the source for some other reason, and the admin's 400 shows the gate is about the role +/// rather than the request. The source is deliberately unresolvable, so the gate is the only thing +/// that can answer 403 and no database is ever reached. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_dumping_a_database_needs_the_code_right(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + windmill_common::roles::invalidate_all_roles_cache(); + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + + let cases = [ + ( + "workspaces/export_pg_schema", + json!({"source": "u/operator/not-a-source"}), + "export a database schema", + ), + ( + "workspaces/import_pg_database", + json!({"source": "u/operator/not-a-source", "target": "u/operator/not-a-source", + "fork_behavior": "schema_only"}), + "import a database", + ), + ]; + + for (route, body, action) in cases { + let resp = operator_client() + .post(format!("{api}/{route}")) + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert_eq!(status, 403, "{route}: {text}"); + assert!( + text.contains(&format!("Your role cannot {action} in this workspace")), + "{route} refused for another reason: {text}" + ); + + let resp = reqwest::Client::new() + .post(format!("{api}/{route}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert_eq!(status, 400, "{route}: {text}"); + assert!(text.contains("Invalid source format"), "{route}: {text}"); + } + + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 0534f3e7ee..9a6efec148 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -3366,6 +3366,10 @@ pub(crate) async fn resolve_pg_source_checked_with_kind( let pg: PgDatabase = serde_json::from_value(db_resource) .map_err(|e| Error::internal_err(format!("Failed to parse database credentials: {}", e)))?; + // Checked here rather than at each caller: every source and target of a dump, restore or copy + // comes through this function, and `validate_dbname` only ever reaches a target. The check is + // deliberately the narrow one — see `validate_dbname_not_option_like`. + windmill_common::validate_dbname_not_option_like(&pg.dbname)?; Ok((pg, managed_kind)) } @@ -3455,21 +3459,20 @@ pub(crate) struct PgDumpOptions<'a> { pub(crate) no_acl: bool, } -/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. -/// Returns a DumpFile handle; the file is deleted when the handle is dropped. -pub(crate) async fn pg_dump_database( +/// A pg_dump invocation against `pg_db` writing to `dump_path`, carrying the connection settings +/// the CLI reads from the environment. The returned file, when there is one, holds the root +/// certificate the command points at and must outlive it. +fn pg_dump_command( pg_db: &PgDatabase, opts: PgDumpOptions<'_>, -) -> Result<DumpFile> { - let dump_file = DumpFile::new()?; - + dump_path: &std::path::Path, +) -> Result<(tokio::process::Command, Option<DumpFile>)> { let host = &pg_db.host; let port = pg_db.port.unwrap_or(5432).to_string(); let user = pg_db.login_name(); - let dbname = &pg_db.dbname; let mut cmd = tokio::process::Command::new("pg_dump"); - cmd.arg("--format=plain").arg("--file").arg(&dump_file.path); + cmd.arg("--format=plain").arg("--file").arg(dump_path); if opts.schema_only { cmd.arg("--schema-only"); } @@ -3487,13 +3490,31 @@ pub(crate) async fn pg_dump_database( .arg("--port") .arg(&port) .arg("--username") - .arg(user) - .arg(dbname); + .arg(user); + + // The name comes from a resource, so it never goes on the command line: as the positional + // argument a name starting with `-` is read as an option of pg_dump (`--file`, + // `--restrict-key`), and as `--dbname` a name holding `=` is expanded as a libpq connection + // string overriding the host, port and user set above. libpq takes the environment variable + // as a plain database name, neither parsed as an option nor expanded. + cmd.env("PGDATABASE", &pg_db.dbname); if let Some(ref password) = pg_db.password { cmd.env("PGPASSWORD", password); } - let _root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; + let root_cert = apply_pg_tls_env(&mut cmd, pg_db)?; + Ok((cmd, root_cert)) +} + +/// Run pg_dump against a PgDatabase, writing output to a temp file on disk. +/// Returns a DumpFile handle; the file is deleted when the handle is dropped. +pub(crate) async fn pg_dump_database( + pg_db: &PgDatabase, + opts: PgDumpOptions<'_>, +) -> Result<DumpFile> { + let dump_file = DumpFile::new()?; + + let (mut cmd, _root_cert) = pg_dump_command(pg_db, opts, &dump_file.path)?; let output = cmd .output() @@ -3619,12 +3640,14 @@ fn psql_command(pg_db: &PgDatabase) -> Result<(tokio::process::Command, Option<D .arg(pg_db.port.unwrap_or(5432).to_string()) .arg("--username") .arg(pg_db.login_name()) - .arg("--dbname") - .arg(&pg_db.dbname) .arg("--no-psqlrc") .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); + // Not `--dbname`, which expands a name holding `=` as a libpq connection string overriding + // the host, port and user set above. See `pg_dump_command`. + cmd.env("PGDATABASE", &pg_db.dbname); + if let Some(ref password) = pg_db.password { cmd.env("PGPASSWORD", password); } @@ -3715,6 +3738,97 @@ mod pg_tls_env_tests { } } +/// The database name of a resource reaches `pg_dump` and `psql` through `PGDATABASE`, never in +/// their argument vector, so neither an option (`--file=`, `--restrict-key=`) nor a libpq +/// connection string (`host=... port=...`) in that field is parsed as one. +#[cfg(test)] +mod pg_dbname_env_tests { + use super::{pg_dump_command, pg_dump_database, psql_command, DumpFile, PgDumpOptions}; + use windmill_common::PgDatabase; + + /// Nothing listens on that port. + fn pg_db(dbname: &str) -> PgDatabase { + PgDatabase { + host: "127.0.0.1".to_string(), + user: None, + password: None, + port: Some(1), + sslmode: None, + dbname: dbname.to_string(), + root_certificate_pem: None, + accept_invalid_certs: None, + use_iam_auth: None, + region: None, + options: None, + } + } + + fn pgdatabase_of(cmd: &std::process::Command) -> Option<std::ffi::OsString> { + cmd.get_envs() + .find(|(k, _)| *k == "PGDATABASE") + .and_then(|(_, v)| v.map(|v| v.to_os_string())) + } + + #[test] + fn pg_dump_takes_the_dbname_from_the_environment() { + let dump_file = DumpFile::new().unwrap(); + let name = "--file=/tmp/written_by_the_caller"; + let (cmd, _root_cert) = + pg_dump_command(&pg_db(name), PgDumpOptions::default(), &dump_file.path).unwrap(); + let cmd = cmd.as_std(); + assert!( + cmd.get_args().all(|arg| arg != name), + "the dbname is still in pg_dump's argument vector" + ); + assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); + // The only `--file` pg_dump is given is still Windmill's own. + assert_eq!( + cmd.get_args() + .filter(|arg| arg.to_string_lossy().starts_with("--file")) + .count(), + 1 + ); + } + + #[test] + fn psql_takes_the_dbname_from_the_environment() { + let name = "host=elsewhere"; + let (cmd, _root_cert) = psql_command(&pg_db(name)).unwrap(); + let cmd = cmd.as_std(); + assert!( + cmd.get_args().all(|arg| arg != name), + "the dbname is still in psql's argument vector" + ); + assert_eq!(pgdatabase_of(cmd).as_deref(), Some(name.as_ref())); + } + + /// The same, observed on the real binary: an option-shaped name must reach the connection + /// attempt rather than pg_dump's option parser. Skipped where pg_dump is not installed — + /// which is why the assertion also requires that pg_dump ran at all (our `pg_dump failed:` + /// prefix) instead of only that the option message is absent. + #[tokio::test] + async fn pg_dump_does_not_read_an_option_shaped_dbname_as_an_option() { + if std::process::Command::new("pg_dump") + .arg("--version") + .output() + .is_err() + { + eprintln!("skipped: pg_dump is not installed"); + return; + } + let Err(err) = pg_dump_database(&pg_db("--no-such-option"), PgDumpOptions::default()).await + else { + panic!("pg_dump reached a server on 127.0.0.1:1"); + }; + let err = err.to_string(); + assert!( + err.contains("pg_dump failed:"), + "pg_dump did not run: {err}" + ); + assert!(!err.contains("unrecognized option"), "{err}"); + } +} + /// GUC names the server backing `pg_db` knows about. /// /// Asked through psql rather than a tokio-postgres connection so the lookup reaches @@ -4061,6 +4175,25 @@ fn ensure_copied_without_roles(governing: &GoverningDatatable) -> Result<()> { Ok(()) } +/// Gate for the endpoints that make the API server run `pg_dump`/`psql` against a database a +/// request names. +/// +/// Those two processes are children of the API server, outside any job sandbox and holding its +/// environment, and the dump they exchange is a `psql` script assembled from strings the source +/// server returns — so reaching them is close enough to running code on the server that the role +/// which may not run code at all must not reach them either. `code` is the capability the data +/// table migration endpoints next door already ask for (`datatable_migrations::ensure_not_operator`), +/// and not admin: the database manager offers an export and an import of a user's own Postgres +/// resource to every author, who can run the same `pg_dump` in a job anyway. +async fn ensure_can_dump_databases( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + action: &str, +) -> Result<()> { + windmill_common::workspaces::check_role_can_code(db, w_id, authed, action).await +} + /// Import (pg_dump/pg_import) from source to target async fn import_pg_database( authed: ApiAuthed, @@ -4069,6 +4202,8 @@ async fn import_pg_database( Path(w_id): Path<String>, Json(req): Json<ImportPgDatabaseRequest>, ) -> Result<String> { + ensure_can_dump_databases(&db, &w_id, &authed, "import a database").await?; + if req.fork_behavior == DataTableForkBehavior::KeepOriginal { return Ok("No action needed for KeepOriginal behavior".to_string()); } @@ -4185,6 +4320,8 @@ async fn export_pg_schema( Path(w_id): Path<String>, Json(req): Json<ExportPgSchemaRequest>, ) -> Result<String> { + ensure_can_dump_databases(&db, &w_id, &authed, "export a database schema").await?; + let pg = resolve_pg_source_checked(&db, &user_db, &authed, &w_id, &req.source).await?; let dump_file = pg_dump_database( &pg, diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 4e1524580e..2d60008373 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -843,6 +843,50 @@ mod validate_dbname_tests { } } +#[cfg(test)] +mod validate_dbname_not_option_like_tests { + use super::validate_dbname_not_option_like; + + /// A source is any database a user already has, so everything `validate_dbname` refuses but + /// Postgres accepts has to keep working. + #[test] + fn accepts_every_name_that_is_not_an_option() { + for name in [ + "mydb", + "My-Db_1", + "2024_archive", + "my.db", + "db with spaces", + "Grüße", + "host=elsewhere port=5433", + "", + "a-dash-inside--it", + ] { + assert!( + validate_dbname_not_option_like(name).is_ok(), + "refused the legitimate name {name:?}" + ); + } + } + + #[test] + fn rejects_a_name_that_an_argument_vector_would_read_as_an_option() { + for name in [ + "--file=/tmp/x", + "--restrict-key=k", + "-f", + "-", + " --file=/tmp/x", + "\t-f", + ] { + let err = validate_dbname_not_option_like(name) + .expect_err(&format!("accepted the option-like name {name:?}")) + .to_string(); + assert!(err.contains("cannot start with '-'"), "{err}"); + } + } +} + #[cfg(test)] mod pg_tls_tests { use super::PgDatabase; @@ -1595,6 +1639,26 @@ pub fn validate_dbname(dbname: &str) -> error::Result<()> { Ok(()) } +/// The one restriction on the name of a database Windmill only *reads from*: it may not look like +/// a command-line option. +/// +/// [`validate_dbname`] is the rule for a name Windmill creates or interpolates into SQL, and is +/// far too narrow here: a source is any Postgres resource a user already has, and an existing +/// database may legitimately be named `2024_archive`, `my.db`, `Grüße` or anything else Postgres +/// accepts as a quoted identifier. Refusing those would break working resources. A name opening +/// with `-` is the one shape that is never a database and always a mistake or an attempt to smuggle +/// an option into a `pg_dump`/`psql` argument vector, so it is refused wherever a source is +/// resolved — the commands themselves pass the name through `PGDATABASE` and never on the command +/// line, and this keeps a future caller that forgets from re-opening that door. +pub fn validate_dbname_not_option_like(dbname: &str) -> error::Result<()> { + if dbname.trim_start().starts_with('-') { + return Err(error::Error::BadRequest( + "Database name cannot start with '-'".to_string(), + )); + } + Ok(()) +} + /// Lock the instance databases among `names` until `tx` ends, in a stable order. Taken by every /// settings save naming an instance database, and by [`drop_unused_instance_database`]: a save /// cannot start using a database between that drop's check that nothing does and the drop. From 82d10766046d62459a6503df16e0df9f1dc8f30e Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:41:05 -0400 Subject: [PATCH 083/101] chore: normalize NUL escapes in job args before name-based checks (#11989) --- backend/tests/app_run_mode_lock_strip.rs | 7 +- backend/tests/caller_modules_strip.rs | 10 +- backend/tests/reserved_control_args.rs | 436 ++++++++++++++++++ backend/windmill-api/src/apps.rs | 28 +- backend/windmill-api/src/jobs.rs | 18 +- backend/windmill-common/src/jobs.rs | 158 ++++++- backend/windmill-queue/src/jobs.rs | 45 +- .../windmill-trigger/src/trigger_helpers.rs | 14 +- backend/windmill-types/src/jobs.rs | 20 + 9 files changed, 711 insertions(+), 25 deletions(-) create mode 100644 backend/tests/reserved_control_args.rs diff --git a/backend/tests/app_run_mode_lock_strip.rs b/backend/tests/app_run_mode_lock_strip.rs index 7a1bba75f6..77265f2bcd 100644 --- a/backend/tests/app_run_mode_lock_strip.rs +++ b/backend/tests/app_run_mode_lock_strip.rs @@ -110,10 +110,13 @@ async fn test_run_mode_strips_caller_lock_and_modules(db: Pool<Postgres>) -> any .json(&json!({ // The args map is the other injection channel: an inline run is a // `JobKind::Preview` job, so the worker/executors read `_MODULES` and - // `_TEMP_SCRIPT_REFS` back out of the job args. Both must be stripped. + // `_TEMP_SCRIPT_REFS` back out of the job args. Both must be stripped — + // including the NUL spellings, which `push` stores under the plain name. "args": { "_MODULES": { "m.py": { "content": "print('evil')\n", "language": "python3" } }, - "_TEMP_SCRIPT_REFS": { "../evil": "deadbeef" } + "_MODULES\u{0}": { "m.py": { "content": "print('evil')\n", "language": "python3" } }, + "_TEMP_SCRIPT_REFS": { "../evil": "deadbeef" }, + "_TEMP_SCRIPT_REFS\u{0}": { "../evil": "deadbeef" } }, "component": "comp", "raw_code": inline_raw_code(Some(CALLER_HASH), true) diff --git a/backend/tests/caller_modules_strip.rs b/backend/tests/caller_modules_strip.rs index a65ca22d1b..bf4a096ee1 100644 --- a/backend/tests/caller_modules_strip.rs +++ b/backend/tests/caller_modules_strip.rs @@ -20,10 +20,16 @@ fn modules(v: &str) -> serde_json::Value { /// Pushes `payload` with a caller `_MODULES` both in `args` and in `extra` (where webhook /// query and headers land), and returns the stored `_MODULES`. +/// +/// Every spelling `push` stores as `_MODULES` is sent, not just the exact name: it writes +/// the args with their `\u0000` escapes removed, keys included, so `_MODULES\0` lands in +/// the job as `_MODULES` unless the removal compares the name that will be stored. async fn stored_modules(db: &Pool<Postgres>, payload: JobPayload) -> Option<serde_json::Value> { let caller: Box<RawValue> = serde_json::value::to_raw_value(&modules("caller")).unwrap(); - let args = HashMap::from([("_MODULES".to_string(), caller.clone())]); - let extra = HashMap::from([("_MODULES".to_string(), caller)]); + let spellings = + || ["_MODULES", "_MODULES\0", "_MOD\0ULES"].map(|k| (k.to_string(), caller.clone())); + let args = HashMap::from(spellings()); + let extra = HashMap::from(spellings()); let (id, tx) = windmill_queue::push( db, PushIsolationLevel::IsolatedRoot(db.clone()), diff --git a/backend/tests/reserved_control_args.rs b/backend/tests/reserved_control_args.rs new file mode 100644 index 0000000000..a733546e51 --- /dev/null +++ b/backend/tests/reserved_control_args.rs @@ -0,0 +1,436 @@ +//! `_ENTRYPOINT_OVERRIDE`, `_MODULES` and `_TEMP_SCRIPT_REFS` steer *how* a runnable runs: +//! which function the worker calls instead of `main`, what module files land in the job +//! directory, where its workspace imports resolve from. They are legitimate for a caller +//! running its own code under its own identity, and must not be settable by a third party +//! whose payload runs under somebody else's: an HTTP route body or native trigger message +//! (the job runs as the trigger's owner) and a public app viewer's inputs (as the +//! publisher). +//! +//! `push` stores the args with their `\u0000` escapes removed, keys included, so every +//! check also has to hold for a NUL-spelled key: `_ENTRYPOINT_OVERRIDE\0` is read back as +//! `_ENTRYPOINT_OVERRIDE`. The same rename is what lets a viewer's `tenant\0` land as +//! `tenant` over an app policy's pinned `tenant`. + +use std::collections::HashMap; + +use serde_json::{json, value::RawValue, Value}; +use sqlx::{Pool, Postgres}; +use windmill_common::{ + jobs::JobPayload, + runnable_settings::{ConcurrencySettings, DebouncingSettings}, + scripts::{ScriptHash, ScriptLang}, + triggers::TriggerMetadata, +}; +use windmill_queue::{PushArgs, PushArgsOwned, PushIsolationLevel}; +use windmill_test_utils::*; + +const SCRIPT_PATH: &str = "f/system/hello"; +const SCRIPT_HASH: i64 = 123412; +/// Two top-level functions, as in the report: `main` authenticates, `apply` acts. +const SCRIPT_CONTENT: &str = "export async function main(data: string) { return data }\n\ + export async function apply(action: string) { return action }\n"; + +fn client() -> reqwest::Client { + reqwest::Client::new() +} + +fn authed(b: reqwest::RequestBuilder, token: &str) -> reqwest::RequestBuilder { + b.header("Authorization", format!("Bearer {}", token)) +} + +fn raw(v: Value) -> Box<RawValue> { + serde_json::value::to_raw_value(&v).unwrap() +} + +fn modules() -> Value { + json!({ "bunfig.toml": { "content": "preload = [\"./x.ts\"]", "language": "bun" } }) +} + +/// Deploy `SCRIPT_PATH` (a non-null `lock` is what makes a script count as deployed). +async fn deploy_script(db: &Pool<Postgres>) -> anyhow::Result<()> { + sqlx::query( + r#"INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, + schema, summary, description, lock) + VALUES ('test-workspace', $1, $2, $3, 'bun', 'script', 'test-user', '{}', '', '', + E'{}\n//bun.lock\n<empty>')"#, + ) + .bind(SCRIPT_HASH) + .bind(SCRIPT_PATH) + .bind(SCRIPT_CONTENT) + .execute(db) + .await?; + Ok(()) +} + +async fn job_args_and_entrypoint( + db: &Pool<Postgres>, + id: uuid::Uuid, +) -> anyhow::Result<(Value, Option<String>)> { + Ok( + sqlx::query_as("SELECT args, script_entrypoint_override FROM v2_job WHERE id = $1") + .bind(id) + .fetch_one(db) + .await?, + ) +} + +fn trigger_authed() -> windmill_api_auth::ApiAuthed { + windmill_api_auth::ApiAuthed { + email: "test@windmill.dev".to_string(), + username: "test-user".to_string(), + is_admin: true, + is_operator: false, + groups: vec![], + folders: vec![], + scopes: None, + username_override: None, + username_override_is_token_label: false, + is_session_token: false, + token_prefix: None, + read_only: false, + job_id: None, + credential_expiry: None, + } +} + +/// `trigger_runnable_inner` is the one funnel every trigger reaches `push` through, so it +/// stands in here for the HTTP route whose body keys become the job's top-level args. The +/// sender is anonymous on a `none`/`custom_script` route; the job runs as the route owner. +#[sqlx::test(fixtures("base"))] +async fn trigger_args_lose_every_reserved_control_key(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + deploy_script(&db).await?; + + let args = PushArgsOwned { + args: HashMap::from([ + // Picks `apply` instead of `main`, skipping whatever `main` authenticates. + ("_ENTRYPOINT_OVERRIDE".to_string(), raw(json!("apply"))), + ("_ENTRYPOINT_OVERRIDE\u{0}".to_string(), raw(json!("apply"))), + ("_ENTRY\u{0}POINT_OVERRIDE".to_string(), raw(json!("apply"))), + ("_MODULES\u{0}".to_string(), raw(modules())), + ( + "_TEMP_SCRIPT_REFS\u{0}".to_string(), + raw(json!({ "f/system/dep": "deadbeef" })), + ), + // An ordinary input must still get through, NUL-renamed or not. + ("data".to_string(), raw(json!("payload"))), + ("action\u{0}".to_string(), raw(json!("refund"))), + ]), + extra: None, + }; + + let (id, _, _, _, _) = windmill_trigger::trigger_helpers::trigger_runnable_inner( + &db, + None, + None, + trigger_authed(), + "test-workspace", + SCRIPT_PATH, + false, + args, + None, + None, + None, + "u/test-user/route".to_string(), + None, + TriggerMetadata::new( + Some("u/test-user/route".to_string()), + windmill_common::jobs::JobTriggerKind::Http, + ), + None, + ) + .await?; + + let (args, entrypoint) = job_args_and_entrypoint(&db, id).await?; + assert_eq!( + args, + json!({ "data": "payload", "action": "refund" }), + "a trigger payload may carry the runnable's inputs and nothing that steers how it runs" + ); + assert_eq!( + entrypoint, None, + "a trigger payload must not pick the function the worker calls instead of `main`" + ); + Ok(()) +} + +/// The counterpart: `_ENTRYPOINT_OVERRIDE` stays for a caller that runs the script under +/// its own identity with `jobs:run` — the script editor's preprocessor test, dynamic-select +/// helpers, the CLI and workflow-as-code all send it this way (GHSA-wxjq-w5pj-jqhx bounds +/// what it may contain, not who may set it). Stripping it in `push` would break them. +#[sqlx::test(fixtures("base"))] +async fn an_authenticated_push_keeps_the_entrypoint_override( + db: Pool<Postgres>, +) -> anyhow::Result<()> { + deploy_script(&db).await?; + + // Both spellings: `push` normalizes the names to what it stores, so the NUL-spelled one + // selects the function exactly like the plain one instead of being silently different. + for key in ["_ENTRYPOINT_OVERRIDE", "_ENTRYPOINT_OVERRIDE\u{0}"] { + let args = HashMap::from([ + (key.to_string(), raw(json!("apply"))), + ("action".to_string(), raw(json!("refund"))), + ]); + let (id, tx) = windmill_queue::push( + &db, + PushIsolationLevel::IsolatedRoot(db.clone()), + "test-workspace", + JobPayload::ScriptHash { + hash: ScriptHash(SCRIPT_HASH), + path: SCRIPT_PATH.to_string(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + language: ScriptLang::Bun, + priority: None, + apply_preprocessor: false, + concurrency_settings: ConcurrencySettings::default(), + debouncing_settings: DebouncingSettings::default(), + labels: None, + job_token_scopes: None, + }, + PushArgs { args: &args, extra: None }, + "test-user", + "test@windmill.dev", + "u/test-user".to_string(), + None, + None, + None, + None, + None, + None, + None, + None, + false, + false, + None, + true, + None, + None, + None, + None, + None, + false, + None, + None, + None, + None, + ) + .await?; + tx.commit().await?; + let (args, entrypoint) = job_args_and_entrypoint(&db, id).await?; + assert_eq!( + entrypoint.as_deref(), + Some("apply"), + "an authenticated caller running a script as itself may still pick the entrypoint \ + (sent as {key:?})" + ); + assert_eq!( + args, + json!({ "_ENTRYPOINT_OVERRIDE": "apply", "action": "refund" }), + "the stored name is the normalized one (sent as {key:?})" + ); + } + Ok(()) +} + +/// Create a public (anonymous) app whose single component is the deployed script, with the +/// given policy inputs, and return its path. +async fn create_public_app( + ws: &str, + path: &str, + static_inputs: Value, + one_of_inputs: Value, +) -> anyhow::Result<()> { + let resp = authed(client().post(format!("{ws}/apps/create")), "SECRET_TOKEN") + .json(&json!({ + "path": path, + "summary": "", + "value": {}, + "policy": { + "execution_mode": "anonymous", + "triggerables_v2": { + format!("comp:script/{SCRIPT_PATH}"): { + "static_inputs": static_inputs, + "one_of_inputs": one_of_inputs, + } + } + } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create app: {}", resp.text().await?); + Ok(()) +} + +/// A viewer of a public app runs the publisher's pinned script as the publisher: it may +/// fill in the inputs the policy leaves free and nothing else. +#[sqlx::test(fixtures("base"))] +async fn public_app_viewer_cannot_steer_the_pinned_runnable( + db: Pool<Postgres>, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + deploy_script(&db).await?; + + let app_path = "u/test-user/reserved_args"; + create_public_app( + &ws, + app_path, + json!({ "tenant": "acme" }), + json!({ "greeting": ["Hello,", "Bonjour,"] }), + ) + .await?; + + // No `Authorization` header at all: the anonymous visitor of a public app. + let run = |args: &'static str| { + client() + .post(format!("{ws}/apps_u/execute_component/{app_path}")) + .header("content-type", "application/json") + .body(format!( + r#"{{"component": "comp", "path": "script/{SCRIPT_PATH}", "args": {args}}}"# + )) + .send() + }; + + // A name spelled with a NUL is the same name once stored, so the policy's pinned value + // must still win and the one-of list must still be enforced. + let resp = run(r#"{"tenant\u0000": "globex", "greeting": "Hello,"}"#).await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 200, "run must be accepted: {body}"); + let (args, _) = job_args_and_entrypoint(&db, uuid::Uuid::parse_str(body.trim())?).await?; + assert_eq!( + args["tenant"], + json!("acme"), + "a NUL-renamed arg must not override an input the policy pins: {args}" + ); + + let resp = run(r#"{"greeting\u0000": "anything"}"#).await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!( + status, 400, + "a NUL-renamed arg must still be held to the policy's one_of list: {body}" + ); + assert!( + body.contains("must be one of"), + "expected the one_of rejection, got: {body}" + ); + + // The control keys, in both spellings, in one request. + let resp = run( + r#"{"_ENTRYPOINT_OVERRIDE": "apply", "_ENTRYPOINT_OVERRIDE\u0000": "apply", + "_MODULES": {"bunfig.toml": {"content": "x", "language": "bun"}}, + "_MODULES\u0000": {"bunfig.toml": {"content": "x", "language": "bun"}}, + "_TEMP_SCRIPT_REFS": {"f/system/dep": "deadbeef"}, + "_TEMP_SCRIPT_REFS\u0000": {"f/system/dep": "deadbeef"}, + "greeting": "Hello,"}"#, + ) + .await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 200, "run must be accepted: {body}"); + let (args, entrypoint) = + job_args_and_entrypoint(&db, uuid::Uuid::parse_str(body.trim())?).await?; + assert_eq!( + entrypoint, None, + "a viewer must not pick the function the worker calls instead of `main`" + ); + assert_eq!( + args, + json!({ "tenant": "acme", "greeting": "Hello," }), + "only the policy's pinned input and the viewer's allowed one may reach the job: {args}" + ); + Ok(()) +} + +/// A deployed flow's dynamic-select code has no deployed runnable, so it is queued as a +/// `JobKind::Preview` job — the one kind on which the bun and python executors honor +/// `_TEMP_SCRIPT_REFS` and resolve the code's workspace imports from the temporary script +/// store, which any workspace member can write. The caller of this route only fills in that +/// code's inputs (it may be an operator, who is refused `jobs/run/preview` outright), so the +/// key must not reach the job, in either spelling. +#[sqlx::test(fixtures("base"))] +async fn flow_dynamic_select_strips_caller_control_args(db: Pool<Postgres>) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + + // Someone else's flow: `test-user-2` below can run it, not edit it. + let flow_path = "u/test-user/dynselect_control_args"; + let resp = authed(client().post(format!("{ws}/flows/create")), "SECRET_TOKEN") + .json(&json!({ + "path": flow_path, + "summary": "", + "description": "", + "value": { "modules": [] }, + "schema": { + "type": "object", + "properties": { "region": { "type": "object", "format": "dynselect-region" } }, + "x-windmill-dyn-select-lang": "bun", + "x-windmill-dyn-select-code": + "import { regions } from \"/f/system/regions\"\n\ + export async function region() { return regions() }\n" + } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create flow: {}", resp.text().await?); + + // Read-only for the caller below: running the dyn-select code is all it may do. + sqlx::query( + "UPDATE flow SET extra_perms = '{\"u/test-user-2\": false}' + WHERE path = $1 AND workspace_id = 'test-workspace'", + ) + .bind(flow_path) + .execute(&db) + .await?; + + let refs = json!({ "f/system/regions": "deadbeef" }); + let modules = json!({ "regions.ts": { "content": "export const v = 1", "language": "bun" } }); + let resp = authed( + client().post(format!("{ws}/jobs/run/dynamic_select")), + "SECRET_TOKEN_2", + ) + .json(&json!({ + "entrypoint_function": "region", + "runnable_ref": { "source": "deployed", "path": flow_path, "runnable_kind": "flow" }, + "args": { + "_TEMP_SCRIPT_REFS": refs, + "_TEMP_SCRIPT_REFS\u{0}": refs, + "_MODULES": modules, + "_MODULES\u{0}": modules, + "filterText": "eu" + } + })) + .send() + .await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 201, "dynamic select must be accepted: {body}"); + + let id = uuid::Uuid::parse_str(body.trim())?; + let kind: String = sqlx::query_scalar("SELECT kind::text FROM v2_job WHERE id = $1") + .bind(id) + .fetch_one(&db) + .await?; + assert_eq!( + kind, "preview", + "the premise of this test: a deployed flow's dyn-select code runs as a preview job" + ); + let (args, _) = job_args_and_entrypoint(&db, id).await?; + assert_eq!( + args, + json!({ "_ENTRYPOINT_OVERRIDE": "region", "filterText": "eu" }), + "only the caller's inputs and the server-set entrypoint may reach the job" + ); + Ok(()) +} diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 575306fe95..cdc66496c0 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -66,8 +66,8 @@ use windmill_common::{ db::{DbWithOptAuthed, UserDB}, error::{to_anyhow, Error, JsonResult, Result}, jobs::{ - get_payload_tag_from_prefixed_path, resolve_delete_after_secs, schedule_job_deletion, - JobPayload, JobTriggerKind, RawCode, + get_payload_tag_from_prefixed_path, normalize_nul_in_args, resolve_delete_after_secs, + sanitize_untrusted_args, schedule_job_deletion, JobPayload, JobTriggerKind, RawCode, }, scripts::ScriptLang, triggers::TriggerMetadata, @@ -4963,11 +4963,15 @@ async fn execute_component( let resolved_delete_secs = resolve_delete_after_secs(None, policy_triggerables.delete_after_secs); - // `_TEMP_SCRIPT_REFS` is a server-injected control key (into `extra`) that the - // worker reads back for a `Preview` job, which an inline run is. A caller - // supplying it in `args` would redirect relative-import resolution, unpinned, as - // the app identity. Drop it; the legitimate value rides in `extra`. - payload.args.remove("_TEMP_SCRIPT_REFS"); + // The caller here is a viewer of the app, down to an anonymous visitor of a public one, + // and the job runs as the app's identity on code the policy pins. So the viewer fills in + // the runnable's inputs and nothing else: not the function called instead of `main` + // (which would reach helpers the app never exposes, as the publisher), not the module + // files written into the job directory, and not `_TEMP_SCRIPT_REFS`, which would + // redirect relative-import resolution, unpinned, as the app identity. The legitimate + // `_TEMP_SCRIPT_REFS` is server-injected into `extra` further below, which this leaves + // alone — as it does the policy's own `static_inputs`, which the publisher writes. + sanitize_untrusted_args(&mut payload.args); // An agent runnable takes the message and its files, plus optionally the conversation they // belong to, which names the agent's memory rather than an input of its run. Without it the @@ -6640,6 +6644,16 @@ async fn build_args( let mut job_id: Option<Uuid> = None; let mut safe_args = HashMap::<String, Box<RawValue>>::new(); + // Every check below matches an argument by name against the policy the publisher wrote, + // and `push` stores the args with their `\u0000` escapes removed, names included. So + // compare the names that will actually be stored: otherwise a viewer's `tenant\0` is + // never recognized as the `tenant` the policy pins in `static_inputs` (and is stored as + // `tenant`, winning over the pinned value), and `greeting\0` is never recognized as the + // `greeting` restricted by `one_of_inputs`, so neither list is enforced. Values are + // normalized along with the names, so the checks that look at a value see what the job + // will receive. + normalize_nul_in_args(&mut args); + // Before anything reads `args`: a context input the runnable declares is never taken // from the request, or a viewer could name someone else as themselves. for (k, prop) in ctx_inputs.into_iter().flatten() { diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index c5dd374c7a..bf3d7ea24c 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -36,7 +36,7 @@ use windmill_common::error::JsonResult; use windmill_common::flow_status::{JobResult, RestartedFrom}; use windmill_common::jobs::{ format_completed_job_result, format_result, is_safe_log_file_path, is_valid_entrypoint_name, - DynamicInput, ENTRYPOINT_OVERRIDE, + sanitize_untrusted_args, DynamicInput, ENTRYPOINT_OVERRIDE, }; #[cfg(feature = "run_inline")] use windmill_common::jobs::{ @@ -10488,7 +10488,7 @@ async fn run_dynamic_select( Extension(user_db): Extension<UserDB>, Path(w_id): Path<String>, Query(run_query): Query<RunJobQuery>, - Json(request): Json<DynamicSelectRequest>, + Json(mut request): Json<DynamicSelectRequest>, ) -> error::Result<Response> { #[cfg(feature = "enterprise")] check_license_key_valid().await?; @@ -10510,6 +10510,20 @@ async fn run_dynamic_select( ))); } + // The dyn-select code is the runnable's, not necessarily the caller's: a deployed flow + // has no deployed runnable for it, so it runs as a `JobKind::Preview` job, and the + // executors honor `_TEMP_SCRIPT_REFS` on every preview — it resolves the code's + // workspace imports from the temporary script store, which any workspace member can + // write. A caller of this route (an operator, for a deployed flow) only fills in that + // code's inputs; the function to call is taken from `entrypoint_function`, validated + // above and inserted server-side below, never from the args. So the reserved control + // keys are dropped here, in the spellings `push` would store them under. Nothing + // server-side puts them in `args`: the request has no `temp_script_refs` field, and the + // run form does not send them. + if let Some(args) = request.args.as_mut() { + sanitize_untrusted_args(args); + } + // Deployed scripts keep their normal deployed-run path (a `script` job, resolved below by // push_script_job_by_path_into_queue). Deployed flows and inline snippets have no deployed // runnable, so they run their dyn-select code as a `preview`; the flow carries its path and diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index d7190ff45f..5ca70d3b58 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -16,12 +16,77 @@ use crate::{ flows::get_full_hub_flow_by_path, get_latest_deployed_hash_for_path, get_latest_flow_version_info_for_path, scripts::{get_full_hub_script_by_path, ScriptHash, ScriptLang}, - utils::{StripPath, HTTP_CLIENT}, + utils::{strip_json_nul, StripPath, HTTP_CLIENT}, worker::{custom_tag_matches, to_raw_value, CUSTOM_TAGS_PER_WORKSPACE, WINDMILL_DIR}, workspaces::workspace_with_fork_ancestors, FlowVersionInfo, ScriptHashInfo, Tag, }; +/// Whether `args` already reads the way `push` will store it, i.e. holds no NUL escape in a +/// name or a value. Cheap (one SIMD substring scan per value) so the normalization below can +/// be a no-op on the overwhelmingly common clean case. +pub fn args_contain_nul(args: &HashMap<String, Box<RawValue>>) -> bool { + args.iter().any(|(k, v)| { + k.contains('\0') || memchr::memmem::find(v.get().as_bytes(), b"\\u0000").is_some() + }) +} + +/// Rewrite `args` the way `push` stores it: `push` runs [`strip_json_nul`] over the +/// serialized args just before the INSERT, which removes `\u0000` escapes from **names as +/// well as values** (jsonb rejects them with 22P05). Any decision taken on a name before +/// that — `push`'s own removal of a caller [`MODULES_ARG`], an app policy's `static_inputs` +/// and `one_of_inputs`, the `PushArgs` serializer's "`extra` wins this name" rule — would +/// otherwise compare a name nobody knows against the name that actually lands in the job: +/// an arg sent as `_MODULES\0` is stored as `_MODULES`, and a viewer's `tenant\0` is stored +/// as `tenant`, after the publisher's pinned value, which jsonb then discards as the earlier +/// of two equal keys. +/// +/// Normalizing first makes every such check see the stored name. Values are normalized too, +/// so a check on a value sees what the job will receive. +/// +/// Two names that collide once normalized keep a single value, deterministically: the +/// spelling without NULs wins, then the lexicographically smallest original name — never the +/// one that `HashMap` iteration happened to serialize last. +pub fn normalize_nul_in_args(args: &mut HashMap<String, Box<RawValue>>) { + if !args_contain_nul(args) { + return; + } + let mut entries = args.drain().collect::<Vec<_>>(); + entries.sort_by(|(a, _), (b, _)| { + a.contains('\0') + .cmp(&b.contains('\0')) + .then_with(|| a.cmp(b)) + }); + for (key, value) in entries { + let key = if key.contains('\0') { + key.replace('\0', "") + } else { + key + }; + let stripped = match strip_json_nul(value.get()) { + std::borrow::Cow::Owned(stripped) => RawValue::from_string(stripped).ok(), + std::borrow::Cow::Borrowed(_) => None, + }; + args.entry(key).or_insert(stripped.unwrap_or(value)); + } +} + +/// Drop every [`RESERVED_CONTROL_ARGS`] key from args that a third party supplied for a job +/// running under somebody else's identity (an HTTP route body or native trigger message run +/// as the trigger's owner, a public app viewer's inputs run as the app's publisher). Those +/// keys pick the function the worker calls instead of `main`, the module files written into +/// the job directory, and where workspace imports resolve from: the third party must not +/// choose any of them, while a caller running its own code under its own identity still may. +/// +/// Normalizes first, so a key spelled `_ENTRYPOINT_OVERRIDE\0` — which `push` stores as +/// `_ENTRYPOINT_OVERRIDE` — cannot slip past the comparison. +pub fn sanitize_untrusted_args(args: &mut HashMap<String, Box<RawValue>>) { + normalize_nul_in_args(args); + for key in RESERVED_CONTROL_ARGS { + args.remove(key); + } +} + pub fn get_has_preprocessor_from_content_and_lang( content: &str, language: &ScriptLang, @@ -633,6 +698,97 @@ pub async fn delete_jobs(conn: &mut sqlx::PgConnection, ids: &[uuid::Uuid]) -> e Ok(()) } +#[cfg(test)] +mod reserved_args_tests { + use super::{normalize_nul_in_args, sanitize_untrusted_args}; + use serde_json::value::RawValue; + use std::collections::HashMap; + + fn raw(json: &str) -> Box<RawValue> { + RawValue::from_string(json.to_string()).unwrap() + } + + fn args(entries: &[(&str, &str)]) -> HashMap<String, Box<RawValue>> { + entries + .iter() + .map(|(k, v)| (k.to_string(), raw(v))) + .collect() + } + + fn as_json(args: &HashMap<String, Box<RawValue>>) -> serde_json::Value { + serde_json::to_value(args).unwrap() + } + + /// A clean map must come out byte for byte the same: this runs on every push. + #[test] + fn normalization_leaves_clean_args_alone() { + let mut map = args(&[ + ("tenant", r#""acme""#), + // A legitimately escaped backslash followed by the literal text `u0000` + // (minified JS regexes contain these) is not a NUL and must survive. + ("src", r#""[^\\u0000]+""#), + ]); + let before = as_json(&map); + normalize_nul_in_args(&mut map); + assert_eq!(as_json(&map), before); + } + + /// `push` stores the args with their NUL escapes removed, names included, so a name + /// that only differs by NULs is the same name and must be compared as such. + #[test] + fn normalization_renames_nul_spelled_names_and_cleans_values() { + let mut map = args(&[ + ("_MODULES\u{0}", r#"{"m.py": "evil"}"#), + ("_MOD\u{0}ULES", r#"{"m.py": "evil"}"#), + ("greeting\u{0}", r#""anything""#), + ("note", r#""a\u0000b""#), + ]); + normalize_nul_in_args(&mut map); + let mut names = map.keys().cloned().collect::<Vec<_>>(); + names.sort(); + assert_eq!(names, vec!["_MODULES", "greeting", "note"]); + assert_eq!(map["note"].get(), r#""ab""#); + } + + /// Which of two names that collide once normalized survives may not depend on + /// `HashMap` iteration order: the spelling the publisher/server used wins. + #[test] + fn normalization_keeps_the_nul_free_spelling_on_collision() { + for _ in 0..16 { + let mut map = args(&[ + ("tenant", r#""acme""#), + ("tenant\u{0}", r#""globex""#), + ("\u{0}tenant", r#""initech""#), + ]); + normalize_nul_in_args(&mut map); + assert_eq!(map.len(), 1); + assert_eq!(map["tenant"].get(), r#""acme""#); + } + } + + /// Every reserved control key goes, in every spelling, and nothing else does. + #[test] + fn untrusted_args_lose_every_reserved_control_key() { + let mut map = args(&[ + ("_ENTRYPOINT_OVERRIDE", r#""apply""#), + ("_ENTRYPOINT_OVERRIDE\u{0}", r#""apply""#), + ("_ENTRY\u{0}POINT_OVERRIDE", r#""apply""#), + ("_MODULES", r#"{"m.py": "evil"}"#), + ("_MODULES\u{0}", r#"{"m.py": "evil"}"#), + ("_TEMP_SCRIPT_REFS", r#"{"f/a/b": "deadbeef"}"#), + ("_TEMP_SCRIPT_REFS\u{0}", r#"{"f/a/b": "deadbeef"}"#), + // Neighbours that must not be caught by a prefix/contains match. + ("_TEMP_SCRIPT_REFS_", r#"1"#), + ("entrypoint", r#""main""#), + ("action", r#""refund""#), + ]); + sanitize_untrusted_args(&mut map); + let mut names = map.keys().cloned().collect::<Vec<_>>(); + names.sort(); + assert_eq!(names, vec!["_TEMP_SCRIPT_REFS_", "action", "entrypoint"]); + } +} + #[cfg(test)] mod tests { use super::is_safe_log_file_path; diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index b8d2458b90..b78da75edf 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -42,8 +42,8 @@ use windmill_common::auth::JobPerms; #[cfg(feature = "benchmark")] use windmill_common::bench::BenchmarkIter; use windmill_common::jobs::{ - script_path_to_payload, JobTriggerKind, TriggerKindLabel, EMAIL_ERROR_HANDLER_USER_EMAIL, - MODULES_ARG, + args_contain_nul, normalize_nul_in_args, sanitize_untrusted_args, script_path_to_payload, + JobTriggerKind, TriggerKindLabel, EMAIL_ERROR_HANDLER_USER_EMAIL, MODULES_ARG, }; use windmill_common::min_version::{ MIN_VERSION_SUPPORTS_DEBOUNCING, MIN_VERSION_SUPPORTS_DEBOUNCING_V2, @@ -6153,6 +6153,18 @@ impl PushArgsOwned { pub fn empty() -> Self { PushArgsOwned { extra: None, args: HashMap::new() } } + + /// Mark these args as coming from an untrusted third party: see + /// [`windmill_common::jobs::sanitize_untrusted_args`]. Applied to both maps, because a + /// name in `extra` wins over the same name in `args` when the job is serialized, and no + /// source that builds args from a third party's payload sets a reserved control key of + /// its own. + pub fn sanitize_untrusted(&mut self) { + sanitize_untrusted_args(&mut self.args); + if let Some(extra) = self.extra.as_mut() { + sanitize_untrusted_args(extra); + } + } } pub fn empty_result() -> Box<RawValue> { @@ -6398,21 +6410,34 @@ async fn push_inner<'c, 'd>( suspended_mode: Option<bool>, scope_ceiling: Option<&[String]>, ) -> Result<(Uuid, Transaction<'c, Postgres>), Error> { - // The worker builds a preview's `_MODULES` arg into the job as its module code. Every - // caller-reachable value lands in `args` or `extra` (webhook query and headers go to - // `extra`, WAC children copy their parent's args), so it is dropped from both and only - // the `JobPayload::Code` arm below sets it, from the server-side `RawCode::modules`. - let args_without_modules; + // Normalize the names and values to what the INSERT below will actually store before + // anything here goes by a name: `strip_json_nul` runs over the serialized args just + // before that INSERT and removes `\u0000` escapes from keys as well as values, so a + // name compared as sent is not the name that lands in the job. Without this, `_MODULES` + // is dropped below while `_MODULES\0` is stored as `_MODULES` and built into a preview's + // job directory as module code; likewise the serializer's "`extra` wins this name" rule + // (which is how an app policy's `static_inputs` override a viewer's args) compares the + // name as sent, so `tenant\0` is written after the pinned `tenant` and jsonb keeps the + // viewer's, as the later of two equal keys. The final strip stays, harmless once this + // has run. + let normalized_args; let mut args = { let mut extra = args.extra; if let Some(extra) = extra.as_mut() { + normalize_nul_in_args(extra); + // The worker builds a preview's `_MODULES` arg into the job as its module code. + // Every caller-reachable value lands in `args` or `extra` (webhook query and + // headers go to `extra`, WAC children copy their parent's args), so it is + // dropped from both and only the `JobPayload::Code` arm below sets it, from the + // server-side `RawCode::modules`. extra.remove(MODULES_ARG); } - let args = if args.args.contains_key(MODULES_ARG) { + let args = if args_contain_nul(args.args) || args.args.contains_key(MODULES_ARG) { let mut stripped = args.args.clone(); + normalize_nul_in_args(&mut stripped); stripped.remove(MODULES_ARG); - args_without_modules = stripped; - &args_without_modules + normalized_args = stripped; + &normalized_args } else { args.args }; diff --git a/backend/windmill-trigger/src/trigger_helpers.rs b/backend/windmill-trigger/src/trigger_helpers.rs index ae805d195e..4056ae85e6 100644 --- a/backend/windmill-trigger/src/trigger_helpers.rs +++ b/backend/windmill-trigger/src/trigger_helpers.rs @@ -512,7 +512,7 @@ pub async fn trigger_runnable_inner<'c>( workspace_id: &str, runnable_path: &str, is_flow: bool, - args: PushArgsOwned, + mut args: PushArgsOwned, retry: Option<&sqlx::types::Json<Retry>>, error_handler_path: Option<&str>, error_handler_args: Option<&sqlx::types::Json<HashMap<String, serde_json::Value>>>, @@ -527,6 +527,18 @@ pub async fn trigger_runnable_inner<'c>( bool, Option<sqlx::Transaction<'c, sqlx::Postgres>>, )> { + // A trigger's args are built from a third party's payload — for an HTTP route without + // preprocessor the request body's keys *are* the job's top-level args — and the job runs + // as the trigger's owner, not as whoever sent that payload. So the sender may not steer + // how the runnable runs: pick the function called instead of `main` (and skip whatever + // `main` authenticates, e.g. the signature check of a `custom_script` route), plant + // module files in the job directory, or redirect where its workspace imports resolve. + // Every trigger kind funnels through here on its way to `push`, and none of them sets + // one of those keys itself, so this is the single place to do it rather than each args + // builder. It does not restrict what the runnable is *given*: ordinary inputs pass + // through untouched. + args.sanitize_untrusted(); + let error_handler_args = error_handler_args.map(|args| { let args = args .0 diff --git a/backend/windmill-types/src/jobs.rs b/backend/windmill-types/src/jobs.rs index 9768373b91..17e5235c5f 100644 --- a/backend/windmill-types/src/jobs.rs +++ b/backend/windmill-types/src/jobs.rs @@ -724,6 +724,26 @@ pub const ENTRYPOINT_OVERRIDE: &str = "_ENTRYPOINT_OVERRIDE"; /// `RawCode::modules`: a caller-supplied one is dropped there. pub const MODULES_ARG: &str = "_MODULES"; +/// Job-arg key mapping a runnable's workspace imports to contents of the temporary script +/// store (`scripts/raw_temp/store`, writable by any workspace member). The preview routes +/// set it server-side from their `temp_script_refs` field; the bun and python executors +/// honor it on every `JobKind::Preview` job. +pub const TEMP_SCRIPT_REFS_ARG: &str = "_TEMP_SCRIPT_REFS"; + +/// Job-arg keys that steer *how* a runnable runs rather than what it is given: which +/// function the worker calls instead of `main` ([`ENTRYPOINT_OVERRIDE`]), what module files +/// are written into the job directory ([`MODULES_ARG`]) and where its workspace imports +/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]). +/// +/// Each is legitimate for a caller that runs code it authored under its own identity (the +/// script editor's preprocessor test, dynamic-select helpers, the CLI, workflow-as-code), so +/// they are not dropped for every job. None of them may come from a third party whose +/// payload runs under somebody else's identity — an HTTP route body, a native trigger +/// message, a public app viewer's inputs — which is what `sanitize_untrusted_args` in +/// `windmill_common::jobs` drops. +pub const RESERVED_CONTROL_ARGS: [&str; 3] = + [ENTRYPOINT_OVERRIDE, MODULES_ARG, TEMP_SCRIPT_REFS_ARG]; + /// Reserved job-arg key holding the inbound W3C `traceparent` captured from the /// request that enqueued the job (run endpoints). It rides the `args` jsonb like /// [`ENTRYPOINT_OVERRIDE`]; normal scripts never see it because args are bound by From 2e577bb6f6bff796c777756018f6916c6a55a2c2 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Fri, 23 Oct 2026 16:52:58 -0700 Subject: [PATCH 084/101] chore(main): release 1.848.1 (#11981) * chore(main): release 1.848.1 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 + backend/Cargo.lock | 170 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 ++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 140 insertions(+), 132 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e9ac4479c8..9fc05fadd8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.848.0" + ".": "1.848.1" } diff --git a/CHANGELOG.md b/CHANGELOG.md index f817035464..b25e249639 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## [1.848.1](https://github.com/windmill-labs/windmill/compare/v1.848.0...v1.848.1) (2026-10-23) + + +### Bug Fixes + +* restore workspace pg_dump changes reverted by 812ff6ea5e ([#11988](https://github.com/windmill-labs/windmill/issues/11988)) ([45d3c95](https://github.com/windmill-labs/windmill/commit/45d3c951bb8827c67daaaf75ed52f3c3e1215911)) +* use linkedin openid connect default scopes ([#11953](https://github.com/windmill-labs/windmill/issues/11953)) ([001313a](https://github.com/windmill-labs/windmill/commit/001313aa242c6de053a9deb0c6cdb64580ce1cee)) + ## [1.848.0](https://github.com/windmill-labs/windmill/compare/v1.847.0...v1.848.0) (2026-10-23) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 1bc57db04a..930fcc2bf2 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2695,9 +2695,9 @@ checksum = "3618cccc083bb987a415d85c02ca6c9994ea5b44731ec28b9ecf09658655fba9" [[package]] name = "const_format" -version = "0.2.36" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +checksum = "a3decb4d6965448659923544a634a0571ba44cede4e11ef15a5a317126840454" dependencies = [ "const_format_proc_macros", "konst", @@ -2705,9 +2705,9 @@ dependencies = [ [[package]] name = "const_format_proc_macros" -version = "0.2.34" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +checksum = "941b570269a642506f08cb5b688c04bfa6cfd41a26f8bcdc49db8fd00c0ab659" dependencies = [ "proc-macro2", "quote", @@ -12423,9 +12423,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" dependencies = [ "serde", ] @@ -15487,7 +15487,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-nats", @@ -15577,7 +15577,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.848.0" +version = "1.848.1" dependencies = [ "async-stream", "async-trait", @@ -15612,7 +15612,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15625,7 +15625,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "argon2", @@ -15768,7 +15768,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15792,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15809,7 +15809,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "axum", @@ -15835,7 +15835,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.848.0" +version = "1.848.1" dependencies = [ "reqwest 0.12.28", "serde", @@ -15845,7 +15845,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15862,7 +15862,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "base64 0.22.1", @@ -15884,7 +15884,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "axum", @@ -15907,7 +15907,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15923,7 +15923,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15945,7 +15945,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15967,7 +15967,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -15981,7 +15981,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-nats", @@ -16017,7 +16017,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "axum", @@ -16043,7 +16043,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -16071,7 +16071,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "axum", @@ -16093,7 +16093,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -16113,7 +16113,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "axum", @@ -16155,7 +16155,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "axum", @@ -16185,7 +16185,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.848.0" +version = "1.848.1" dependencies = [ "lazy_static", "serde", @@ -16197,7 +16197,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.848.0" +version = "1.848.1" dependencies = [ "argon2", "axum", @@ -16221,7 +16221,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -16236,7 +16236,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.848.0" +version = "1.848.1" dependencies = [ "axum", "chrono", @@ -16275,7 +16275,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.848.0" +version = "1.848.1" dependencies = [ "chrono", "lazy_static", @@ -16290,7 +16290,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "axum", @@ -16309,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.848.0" +version = "1.848.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -16427,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.848.0" +version = "1.848.1" dependencies = [ "chrono", "futures", @@ -16447,7 +16447,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.848.0" +version = "1.848.1" dependencies = [ "regex", "serde", @@ -16464,7 +16464,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16491,7 +16491,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "futures", @@ -16508,7 +16508,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.0" +version = "1.848.1" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16524,7 +16524,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -16546,7 +16546,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -16577,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "arc-swap", @@ -16602,7 +16602,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-stream", @@ -16638,7 +16638,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "futures", @@ -16657,7 +16657,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.0" +version = "1.848.1" dependencies = [ "convert_case 0.6.0", "serde", @@ -16666,7 +16666,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -16678,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde_json", @@ -16690,7 +16690,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "gosyn", @@ -16702,7 +16702,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -16714,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde_json", @@ -16726,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "nu-parser", @@ -16737,7 +16737,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16748,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16760,7 +16760,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -16771,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-recursion", @@ -16794,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde_json", @@ -16806,7 +16806,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -16820,7 +16820,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16837,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -16850,7 +16850,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde", @@ -16862,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -16880,7 +16880,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16896,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -16913,7 +16913,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -16927,7 +16927,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-recursion", @@ -16966,7 +16966,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "const_format", @@ -17004,7 +17004,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.848.0" +version = "1.848.1" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17015,7 +17015,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-recursion", @@ -17050,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17074,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17107,7 +17107,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17134,7 +17134,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17167,7 +17167,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17187,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17221,7 +17221,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17258,7 +17258,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17281,7 +17281,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17305,7 +17305,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-nats", @@ -17329,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17364,7 +17364,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17392,7 +17392,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-trait", @@ -17417,7 +17417,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17436,7 +17436,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-once-cell", @@ -17554,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.848.0" +version = "1.848.1" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index ddd4133213..1e3d0a1eff 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.848.0" +version = "1.848.1" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.848.0" +version = "1.848.1" authors = ["Ruben Fiszel <ruben@windmill.dev>"] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 9b2d7397e8..476fd721fd 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.848.0" +version = "1.848.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.0" +version = "1.848.1" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.0" +version = "1.848.1" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.0" +version = "1.848.1" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 0133fa778d..b331b17cc2 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.848.0" +version = "1.848.1" edition = "2021" authors = ["Ruben Fiszel <ruben@windmill.dev>"] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index f4a5bf53b0..c590eb2801 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.848.0 + version: 1.848.1 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index c64103bc46..d67b8d48ea 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.848.0"; +export const VERSION = "v1.848.1"; export async function login(email: string, password: string): Promise<string> { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index cea12f7cee..8a79683ebd 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.848.0", + "version": "1.848.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.848.0", + "version": "1.848.1", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 73957de9de..0ee41e80bf 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.848.0", + "version": "1.848.1", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 2b4cacdd8a..99f8332c1d 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.848.0"; +export const VERSION = "1.848.1"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f5aafb851e..791f95ad5e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.848.0", + "version": "1.848.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.848.0", + "version": "1.848.1", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 39f644f810..e34f4beb79 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.848.0", + "version": "1.848.1", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index 98fd22cc68..fc2a6f943f 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.848.0" +wmill = ">=1.848.1" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 37450c254f..ec5b94df9b 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.848.0 + version: 1.848.1 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index d3e380a9c9..a9c7b689ca 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.848.0' + ModuleVersion = '1.848.1' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 8a4e49f849..48c0324142 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.848.0" +version = "1.848.1" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 1804d98aa7..25c18a389f 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.848.0", + "version": "1.848.1", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index aafe90749a..d31463e3ad 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.848.0", + "version": "1.848.1", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index d6dfecff17..bb87eddefd 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.848.0 +1.848.1 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 5242f951fc..3ded38af47 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.848.0", + "version": "1.848.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.848.0", + "version": "1.848.1", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index d3a74ba131..fa9e73b05a 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.848.0", + "version": "1.848.1", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From ccf889269b8897be707cde639b2531d522c286c9 Mon Sep 17 00:00:00 2001 From: Alexander Petric <alpetric@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:45:03 -0400 Subject: [PATCH 085/101] fix: tighten file handling in deno/bun, stricter codebase tarball,executor isolation (#11990) * chore: tighten file handling in deno/bun, stricter codebase tarball, executor isolation * fix(worker): gate now-unused extract_tar behind its enterprise+parquet caller Removing the codebase-bundle caller of global_cache::extract_tar left its only remaining caller, pull_from_tar, gated on enterprise+parquet, so under other feature sets the function (and its tokio::time::Instant import) became dead code and failed CI's -D warnings build. Gate the definition and the import with the same cfg as the caller so they appear and disappear together. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> --- backend/windmill-common/src/lib.rs | 19 ++++- backend/windmill-worker/src/bun_executor.rs | 82 +++++++++++++++++++- backend/windmill-worker/src/deno_executor.rs | 61 +++++++++++++++ backend/windmill-worker/src/global_cache.rs | 7 ++ 4 files changed, 165 insertions(+), 4 deletions(-) diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 2d60008373..fac05d1fea 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -1013,6 +1013,13 @@ ta9ELulniZau8zUAtwqwecxodzl+KO8NYj0a9PGgAM64dMqkRtRA8P4UP350Nag3\n\ assert!(pg(None, None).to_uri().contains("sslmode=prefer")); } + #[test] + fn to_uri_sslmode_cannot_add_parameters() { + let uri = pg(Some("disable&hostaddr=127.0.0.2"), None).to_uri(); + assert!(uri.ends_with("?sslmode=disable%26hostaddr%3D127.0.0.2")); + assert!(uri.parse::<tokio_postgres::Config>().is_err()); + } + #[test] fn options_survive_to_uri() { let mut db = pg(Some("require"), None); @@ -1152,7 +1159,9 @@ impl PgDatabase { let sslmode = match self.sslmode.as_deref() { Some("allow") => "prefer".to_string(), Some("require") | Some("verify-ca") | Some("verify-full") => "require".to_string(), - Some(s) => s.to_string(), + // Encoded like the other fields: a raw '&' would append parameters (`hostaddr`, `host`, + // `port`) that send the connection somewhere else than the host this struct names. + Some(s) => urlencoding::encode(s).into_owned(), None => "prefer".to_string(), }; // Encode host/dbname too: an unencoded '@', '/', '?' or '&' would otherwise @@ -1207,6 +1216,14 @@ impl PgDatabase { let on_local_cluster = local.host == self.host && local.port.unwrap_or(5432) == self.port.unwrap_or(5432); if let Some(db) = main_db.filter(|_| on_local_cluster) { + // Only a connection Windmill built carries the stored password (and the + // role's has drifted from it). Anything else is a resource whose author + // named this role and host: retrying it would log them in with a + // credential they were never given, and rotate it on their say-so. + let stored_pwd = crate::utils::get_custom_pg_instance_password(db).await?; + if self.password.as_deref() != Some(stored_pwd.as_str()) { + return Err(e); + } tracing::warn!( "custom_instance_user password auth failed, refreshing and retrying..." ); diff --git a/backend/windmill-worker/src/bun_executor.rs b/backend/windmill-worker/src/bun_executor.rs index 0094328927..e64a725b7c 100644 --- a/backend/windmill-worker/src/bun_executor.rs +++ b/backend/windmill-worker/src/bun_executor.rs @@ -1961,6 +1961,32 @@ async fn pull_codebase(w_id: &str, id: &str, job_dir: &str) -> Result<PulledCode Ok(PulledCodebase { is_esm }) } +/// Unpack a codebase tar into the job dir, refusing anything but regular files and +/// directories. +/// +/// The archive comes from the caller (`preview_bundle`, `create_snapshot`) and lands next to +/// the files the worker writes and nsjail bind-mounts by name (`args.json`, `result.json`, +/// `node_modules`, ...). A symlink or hard link entry with one of those names would redirect +/// the write, or the mount, to an arbitrary host path: `tar::Archive::unpack` keeps entry +/// names inside the destination but creates links with whatever target they carry. The +/// archives the CLI and the frontend build contain regular files only. +fn extract_codebase_tar(tar: &[u8], job_dir: &str) -> Result<()> { + let mut ar = tar::Archive::new(tar); + for entry in ar.entries()? { + let mut entry = entry?; + let kind = entry.header().entry_type(); + if !(kind.is_file() || kind.is_dir()) { + return Err(error::Error::ExecutionErr(format!( + "codebase archive entry {} is a {:?}, only regular files and directories are allowed", + entry.path()?.display(), + kind + ))); + } + entry.unpack_in(job_dir)?; + } + Ok(()) +} + fn extract_saved_codebase( job_dir: &str, bun_cache_path: &String, @@ -1968,10 +1994,8 @@ fn extract_saved_codebase( dst: &str, copy: bool, ) -> Result<()> { - use crate::global_cache::extract_tar; - Ok(if is_tar { - extract_tar(fs::read(bun_cache_path)?.into(), job_dir)?; + extract_codebase_tar(&fs::read(bun_cache_path)?, job_dir)?; } else { if copy { std::fs::copy(bun_cache_path, dst)?; @@ -5517,4 +5541,56 @@ export function main(x: number) { return x; }"#; assert_eq!(key_for(None).await, key_for(Some(&HashMap::new())).await); assert_ne!(key_for(None).await, attacker); } + + /// Build a codebase tar in memory; `link` adds a symlink entry named after a file the + /// worker writes and nsjail bind-mounts. + fn codebase_tar(link: Option<(&str, &str)>) -> Vec<u8> { + let mut builder = tar::Builder::new(Vec::new()); + let main = b"export async function main() {}\n"; + let mut header = tar::Header::new_gnu(); + header.set_size(main.len() as u64); + header.set_mode(0o644); + header.set_path("main.js").unwrap(); + header.set_cksum(); + builder.append(&header, &main[..]).unwrap(); + if let Some((name, target)) = link { + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_mode(0o777); + header.set_entry_type(tar::EntryType::Symlink); + header.set_path(name).unwrap(); + header.set_link_name(target).unwrap(); + header.set_cksum(); + builder.append(&header, &[][..]).unwrap(); + } + builder.into_inner().unwrap() + } + + #[test] + fn extract_codebase_tar_unpacks_regular_files() { + let dir = tempfile::tempdir().unwrap(); + let job_dir = dir.path().to_str().unwrap(); + + extract_codebase_tar(&codebase_tar(None), job_dir).unwrap(); + + assert_eq!( + std::fs::read_to_string(dir.path().join("main.js")).unwrap(), + "export async function main() {}\n" + ); + } + + #[test] + fn extract_codebase_tar_refuses_links() { + let dir = tempfile::tempdir().unwrap(); + let job_dir = dir.path().to_str().unwrap(); + + let err = extract_codebase_tar(&codebase_tar(Some(("args.json", "/etc/passwd"))), job_dir) + .unwrap_err(); + + assert!(err.to_string().contains("args.json"), "{err}"); + assert!( + std::fs::symlink_metadata(dir.path().join("args.json")).is_err(), + "the link must not be created" + ); + } } diff --git a/backend/windmill-worker/src/deno_executor.rs b/backend/windmill-worker/src/deno_executor.rs index 881923f299..de2098392e 100644 --- a/backend/windmill-worker/src/deno_executor.rs +++ b/backend/windmill-worker/src/deno_executor.rs @@ -244,6 +244,40 @@ pub async fn generate_deno_lock( } } +/// SECURITY: a sandboxed deno job is not nsjail-wrapped; its confinement is +/// `--allow-read=./` / `--allow-write=./`, which Deno checks against the path +/// as written and then hands to the kernel, which follows symlinks. `./shared` +/// is the worker's own link to the flow's shared directory, and every other +/// step of a `same_worker` flow gets that directory bind-mounted read-write +/// inside its jail. A link planted there (`ln -s / /tmp/shared/root` from a +/// bash step) would let the following deno step read and write the whole +/// worker host through `./shared/root/...`. Links pointing inside the +/// directory are not safe either: Deno collapses `..` textually before the +/// check while the kernel applies it to the resolved target. So nothing but +/// regular files and directories may be in there when the job starts. +/// `DirEntry::file_type` reports a link's own type without following it. +async fn refuse_links_in_shared_dir(job_dir: &str) -> error::Result<()> { + let shared = format!("{job_dir}/shared"); + let mut dirs = vec![std::path::PathBuf::from(&shared)]; + while let Some(dir) = dirs.pop() { + let mut entries = tokio::fs::read_dir(&dir).await?; + while let Some(entry) = entries.next_entry().await? { + let file_type = entry.file_type().await?; + if file_type.is_dir() { + dirs.push(entry.path()); + } else if !file_type.is_file() { + let path = entry.path(); + return Err(error::Error::ExecutionErr(format!( + "the flow's shared directory contains ./{}, which is not a regular file \ + or directory: a sandboxed deno step cannot run with it", + path.strip_prefix(job_dir).unwrap_or(&path).display() + ))); + } + } + } + Ok(()) +} + #[tracing::instrument(level = "trace", skip_all)] pub async fn handle_deno_job( requirements_o: Option<&String>, @@ -265,6 +299,10 @@ pub async fn handle_deno_job( ensure_deno_installed()?; let annotations = TypeScriptAnnotations::parse(inner_content); + if job.same_worker && (is_sandboxing_enabled() || annotations.sandbox) { + refuse_links_in_shared_dir(job_dir).await?; + } + // let mut start = Instant::now(); let mut logs1 = "\n\n--- DENO CODE EXECUTION ---\n".to_string(); if annotations.sandbox { @@ -453,6 +491,12 @@ try {{ conn, ) .await; + // The only deno.json deno may honour is the one the worker writes here. Script modules + // are written verbatim into the job dir, so without an explicit choice deno would + // discover a `deno.json(c)` the job shipped as a module, and a config is applied by + // the runtime itself, outside the --allow-* permissions: its `lock` key alone makes + // deno write a file wherever it points, past --allow-write. + let mut deno_config_path: Option<String> = None; if let Some(ref npmrc_content) = npmrc { if !npmrc_content.trim().is_empty() { write_file(job_dir, ".npmrc", npmrc_content)?; @@ -461,8 +505,16 @@ try {{ // routinely serve just-published versions, so the guard would break them. // Older Deno ignores the unknown field, so this is safe across versions. write_file(job_dir, "deno.json", r#"{"minimumDependencyAge":"0"}"#)?; + deno_config_path = Some(format!("{job_dir}/deno.json")); } } + // An admin may pass a config of their own through DENO_FLAGS; deno refuses it next + // to --no-config or a second --config, so it then stands on its own. + let config_in_deno_flags = DENO_FLAGS.as_ref().is_some_and(|flags| { + flags + .iter() + .any(|f| f == "-c" || f == "--config" || f.starts_with("--config=")) + }); //do not cache local dependencies let child = { @@ -472,6 +524,15 @@ try {{ let mut args = Vec::with_capacity(12); args.push("run"); args.push("--no-check"); + if !config_in_deno_flags { + match deno_config_path.as_deref() { + Some(config) => { + args.push("--config"); + args.push(config); + } + None => args.push("--no-config"), + } + } args.push("--import-map"); args.push(&import_map_path); args.push(&reload); diff --git a/backend/windmill-worker/src/global_cache.rs b/backend/windmill-worker/src/global_cache.rs index 1c3bbf870f..622f021fcb 100644 --- a/backend/windmill-worker/src/global_cache.rs +++ b/backend/windmill-worker/src/global_cache.rs @@ -1,3 +1,6 @@ +// Only the enterprise object-store tar helpers use this; `load_cache` below qualifies +// `std::time::Instant` directly, so the import is dead in other builds. +#[cfg(all(feature = "enterprise", feature = "parquet"))] use tokio::time::Instant; use windmill_common::error; @@ -199,6 +202,10 @@ pub async fn pull_from_tar( Ok(()) } +// Only `pull_from_tar` (the enterprise object-store cache path) still unpacks a tar +// through this helper; the codebase-bundle path uses `extract_codebase_tar` instead. +// Gate it with the caller's cfg so it is not dead code in other builds. +#[cfg(all(feature = "enterprise", feature = "parquet"))] pub fn extract_tar(tar: bytes::Bytes, folder: &str) -> error::Result<()> { use bytes::Buf; From 34a01cc61ae7b81df0f6a5e9d9ce545292733f85 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Fri, 23 Oct 2026 17:48:07 -0700 Subject: [PATCH 086/101] chore(main): release 1.848.2 (#11993) * chore(main): release 1.848.2 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 + backend/Cargo.lock | 158 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 +++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 133 insertions(+), 126 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9fc05fadd8..7e451cc599 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.848.1" + ".": "1.848.2" } diff --git a/CHANGELOG.md b/CHANGELOG.md index b25e249639..29eaca64bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.848.2](https://github.com/windmill-labs/windmill/compare/v1.848.1...v1.848.2) (2026-10-24) + + +### Bug Fixes + +* tighten file handling in deno/bun, stricter codebase tarball,executor isolation ([#11990](https://github.com/windmill-labs/windmill/issues/11990)) ([ccf8892](https://github.com/windmill-labs/windmill/commit/ccf889269b8897be707cde639b2531d522c286c9)) + ## [1.848.1](https://github.com/windmill-labs/windmill/compare/v1.848.0...v1.848.1) (2026-10-23) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 930fcc2bf2..5bcc74a555 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -15487,7 +15487,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-nats", @@ -15577,7 +15577,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.848.1" +version = "1.848.2" dependencies = [ "async-stream", "async-trait", @@ -15612,7 +15612,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15625,7 +15625,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "argon2", @@ -15768,7 +15768,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15792,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15809,7 +15809,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "axum", @@ -15835,7 +15835,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.848.1" +version = "1.848.2" dependencies = [ "reqwest 0.12.28", "serde", @@ -15845,7 +15845,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15862,7 +15862,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "base64 0.22.1", @@ -15884,7 +15884,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "axum", @@ -15907,7 +15907,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15923,7 +15923,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15945,7 +15945,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15967,7 +15967,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -15981,7 +15981,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-nats", @@ -16017,7 +16017,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "axum", @@ -16043,7 +16043,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -16071,7 +16071,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "axum", @@ -16093,7 +16093,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -16113,7 +16113,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "axum", @@ -16155,7 +16155,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "axum", @@ -16185,7 +16185,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.848.1" +version = "1.848.2" dependencies = [ "lazy_static", "serde", @@ -16197,7 +16197,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.848.1" +version = "1.848.2" dependencies = [ "argon2", "axum", @@ -16221,7 +16221,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -16236,7 +16236,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.848.1" +version = "1.848.2" dependencies = [ "axum", "chrono", @@ -16275,7 +16275,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.848.1" +version = "1.848.2" dependencies = [ "chrono", "lazy_static", @@ -16290,7 +16290,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "axum", @@ -16309,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.848.1" +version = "1.848.2" dependencies = [ "aes-gcm", "aho-corasick", @@ -16427,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.848.1" +version = "1.848.2" dependencies = [ "chrono", "futures", @@ -16447,7 +16447,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.848.1" +version = "1.848.2" dependencies = [ "regex", "serde", @@ -16464,7 +16464,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16491,7 +16491,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "futures", @@ -16508,7 +16508,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.1" +version = "1.848.2" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16524,7 +16524,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -16546,7 +16546,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -16577,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "arc-swap", @@ -16602,7 +16602,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-stream", @@ -16638,7 +16638,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "futures", @@ -16657,7 +16657,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.1" +version = "1.848.2" dependencies = [ "convert_case 0.6.0", "serde", @@ -16666,7 +16666,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -16678,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde_json", @@ -16690,7 +16690,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "gosyn", @@ -16702,7 +16702,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -16714,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde_json", @@ -16726,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "nu-parser", @@ -16737,7 +16737,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16748,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16760,7 +16760,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "ruff_python_ast", @@ -16771,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-recursion", @@ -16794,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde_json", @@ -16806,7 +16806,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -16820,7 +16820,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16837,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -16850,7 +16850,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde", @@ -16862,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -16880,7 +16880,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16896,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "ruff_python_ast", @@ -16913,7 +16913,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -16927,7 +16927,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-recursion", @@ -16966,7 +16966,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "const_format", @@ -17004,7 +17004,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.848.1" +version = "1.848.2" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17015,7 +17015,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-recursion", @@ -17050,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17074,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17107,7 +17107,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17134,7 +17134,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17167,7 +17167,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17187,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17221,7 +17221,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17258,7 +17258,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17281,7 +17281,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17305,7 +17305,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-nats", @@ -17329,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17364,7 +17364,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17392,7 +17392,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-trait", @@ -17417,7 +17417,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17436,7 +17436,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-once-cell", @@ -17554,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.848.1" +version = "1.848.2" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 1e3d0a1eff..36ab62452e 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.848.1" +version = "1.848.2" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.848.1" +version = "1.848.2" authors = ["Ruben Fiszel <ruben@windmill.dev>"] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 476fd721fd..1cede10209 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.848.1" +version = "1.848.2" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.1" +version = "1.848.2" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.1" +version = "1.848.2" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.1" +version = "1.848.2" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index b331b17cc2..669e3b2b52 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.848.1" +version = "1.848.2" edition = "2021" authors = ["Ruben Fiszel <ruben@windmill.dev>"] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index c590eb2801..81aa881d97 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.848.1 + version: 1.848.2 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index d67b8d48ea..527b975ec7 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.848.1"; +export const VERSION = "v1.848.2"; export async function login(email: string, password: string): Promise<string> { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 8a79683ebd..9f47ba2f71 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.848.1", + "version": "1.848.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.848.1", + "version": "1.848.2", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 0ee41e80bf..f1e990ac0e 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.848.1", + "version": "1.848.2", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 99f8332c1d..d30591d7c2 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.848.1"; +export const VERSION = "1.848.2"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 791f95ad5e..5749c367bb 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.848.1", + "version": "1.848.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.848.1", + "version": "1.848.2", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index e34f4beb79..9ee19f9482 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.848.1", + "version": "1.848.2", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index fc2a6f943f..5c04732bc5 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.848.1" +wmill = ">=1.848.2" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index ec5b94df9b..04b252a92d 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.848.1 + version: 1.848.2 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index a9c7b689ca..69ea522091 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.848.1' + ModuleVersion = '1.848.2' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 48c0324142..f8b532328c 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.848.1" +version = "1.848.2" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 25c18a389f..064d1df2a1 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.848.1", + "version": "1.848.2", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index d31463e3ad..6658778155 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.848.1", + "version": "1.848.2", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index bb87eddefd..a3305f95fb 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.848.1 +1.848.2 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 3ded38af47..74bf912baf 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.848.1", + "version": "1.848.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.848.1", + "version": "1.848.2", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index fa9e73b05a..4ea543ff74 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.848.1", + "version": "1.848.2", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 0e79e934b6342150ee31de08a19400de482b1969 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sat, 24 Oct 2026 19:19:38 -0700 Subject: [PATCH 087/101] fix: pin node to 24.22.1 in the worker image for CVE-2026-111497 (#11995) * chore: update node to 26 in the docker image and CI Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: pin node to 24.22.1 in the worker image for CVE-2026-111497 The unpinned NodeSource install was served from the build cache, so images built after the security release still shipped 24.22.0. Reverts the node 26 bump. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- Dockerfile | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index ad3a79a2b6..93862fe0b9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -144,6 +144,9 @@ ARG KUBECTL_VERSION=1.37.1 ARG HELM_VERSION=3.21.4 # NOTE: If changing, also change go version in workspace dependencies template at WorkspaceDependenciesEditor.svelte ARG GO_VERSION=1.27.1 +# Pinned to the patch: an unpinned install is cached by the image build and stops picking up +# security releases. +ARG NODE_VERSION=24.22.1 ARG APP=/usr/src/app ARG WITH_POWERSHELL=true ARG WITH_KUBECTL=true @@ -252,8 +255,8 @@ RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_r RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $NEW_INSTANCE_PY --compile-bytecode -RUN curl -sL https://deb.nodesource.com/setup_24.x | bash - -RUN apt-get -y update && apt-get install -y --no-install-recommends curl procps nodejs awscli && apt-get clean \ +RUN curl -sL https://deb.nodesource.com/setup_${NODE_VERSION%%.*}.x | bash - +RUN apt-get -y update && apt-get install -y --no-install-recommends curl procps nodejs=${NODE_VERSION}-1nodesource1 awscli && apt-get clean \ && rm -rf /var/lib/apt/lists/* # The npm bundled with nodejs is replaced by a pinned one: it is what `//npm` scripts install with From 1ce00e0263469c2bb2799ff4631e42c77e91d7ec Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sat, 24 Oct 2026 19:28:55 -0700 Subject: [PATCH 088/101] chore(main): release 1.848.3 (#11996) * chore(main): release 1.848.3 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 + backend/Cargo.lock | 172 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 ++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 140 insertions(+), 133 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7e451cc599..6fabba7832 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.848.2" + ".": "1.848.3" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 29eaca64bb..67af90452a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.848.3](https://github.com/windmill-labs/windmill/compare/v1.848.2...v1.848.3) (2026-10-25) + + +### Bug Fixes + +* pin node to 24.22.1 in the worker image for CVE-2026-111497 ([#11995](https://github.com/windmill-labs/windmill/issues/11995)) ([0e79e93](https://github.com/windmill-labs/windmill/commit/0e79e934b6342150ee31de08a19400de482b1969)) + ## [1.848.2](https://github.com/windmill-labs/windmill/compare/v1.848.1...v1.848.2) (2026-10-24) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5bcc74a555..b913ba0193 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2964,9 +2964,9 @@ dependencies = [ [[package]] name = "crypto-bigint" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0" +checksum = "d726facc8b27e604391b232b970cdc19b5468c69f08b466b9734c759216c7415" dependencies = [ "cpubits", "ctutils", @@ -5070,7 +5070,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b805154de2e68f59874ec217ca36790dcffe500cd872c60fe509d28d0814a74d" dependencies = [ "ed448", - "elliptic-curve 0.14.1", + "elliptic-curve 0.14.2", "hash2curve", "rand_core 0.10.1", "serdect 0.4.3", @@ -5126,12 +5126,12 @@ dependencies = [ [[package]] name = "elliptic-curve" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" +checksum = "0ad4496221fcfc21015fd8c0e26fcfab00504832dc0604f52acdd7bad2a8dc81" dependencies = [ "base16ct 1.0.0", - "crypto-bigint 0.7.6", + "crypto-bigint 0.7.8", "crypto-common 0.2.2", "ff 0.14.0", "group 0.14.0", @@ -6241,7 +6241,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1eaf40612d7d854743e7189228a6d528f0f6e8502cf6a0cb831d28a218b7f3f6" dependencies = [ "digest 0.11.3", - "elliptic-curve 0.14.1", + "elliptic-curve 0.14.2", ] [[package]] @@ -15487,7 +15487,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-nats", @@ -15577,7 +15577,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.848.2" +version = "1.848.3" dependencies = [ "async-stream", "async-trait", @@ -15612,7 +15612,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15625,7 +15625,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "argon2", @@ -15768,7 +15768,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15792,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15809,7 +15809,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "axum", @@ -15835,7 +15835,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.848.2" +version = "1.848.3" dependencies = [ "reqwest 0.12.28", "serde", @@ -15845,7 +15845,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15862,7 +15862,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "base64 0.22.1", @@ -15884,7 +15884,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "axum", @@ -15907,7 +15907,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15923,7 +15923,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15945,7 +15945,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15967,7 +15967,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -15981,7 +15981,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-nats", @@ -16017,7 +16017,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "axum", @@ -16043,7 +16043,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -16071,7 +16071,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "axum", @@ -16093,7 +16093,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -16113,7 +16113,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "axum", @@ -16155,7 +16155,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "axum", @@ -16185,7 +16185,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.848.2" +version = "1.848.3" dependencies = [ "lazy_static", "serde", @@ -16197,7 +16197,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.848.2" +version = "1.848.3" dependencies = [ "argon2", "axum", @@ -16221,7 +16221,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -16236,7 +16236,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.848.2" +version = "1.848.3" dependencies = [ "axum", "chrono", @@ -16275,7 +16275,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.848.2" +version = "1.848.3" dependencies = [ "chrono", "lazy_static", @@ -16290,7 +16290,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "axum", @@ -16309,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.848.2" +version = "1.848.3" dependencies = [ "aes-gcm", "aho-corasick", @@ -16427,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.848.2" +version = "1.848.3" dependencies = [ "chrono", "futures", @@ -16447,7 +16447,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.848.2" +version = "1.848.3" dependencies = [ "regex", "serde", @@ -16464,7 +16464,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16491,7 +16491,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "futures", @@ -16508,7 +16508,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.2" +version = "1.848.3" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16524,7 +16524,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -16546,7 +16546,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -16577,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "arc-swap", @@ -16602,7 +16602,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-stream", @@ -16638,7 +16638,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "futures", @@ -16657,7 +16657,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.2" +version = "1.848.3" dependencies = [ "convert_case 0.6.0", "serde", @@ -16666,7 +16666,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -16678,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde_json", @@ -16690,7 +16690,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "gosyn", @@ -16702,7 +16702,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -16714,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde_json", @@ -16726,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "nu-parser", @@ -16737,7 +16737,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16748,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16760,7 +16760,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "ruff_python_ast", @@ -16771,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-recursion", @@ -16794,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde_json", @@ -16806,7 +16806,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -16820,7 +16820,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16837,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -16850,7 +16850,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde", @@ -16862,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -16880,7 +16880,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16896,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "ruff_python_ast", @@ -16913,7 +16913,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -16927,7 +16927,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-recursion", @@ -16966,7 +16966,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "const_format", @@ -17004,7 +17004,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.848.2" +version = "1.848.3" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17015,7 +17015,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-recursion", @@ -17050,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17074,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17107,7 +17107,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17134,7 +17134,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17167,7 +17167,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17187,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17221,7 +17221,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17258,7 +17258,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17281,7 +17281,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17305,7 +17305,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-nats", @@ -17329,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17364,7 +17364,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17392,7 +17392,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-trait", @@ -17417,7 +17417,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17436,7 +17436,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-once-cell", @@ -17554,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.848.2" +version = "1.848.3" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 36ab62452e..aa8758573b 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.848.2" +version = "1.848.3" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.848.2" +version = "1.848.3" authors = ["Ruben Fiszel <ruben@windmill.dev>"] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 1cede10209..c55eb2fb2c 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.848.2" +version = "1.848.3" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.2" +version = "1.848.3" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.2" +version = "1.848.3" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.2" +version = "1.848.3" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 669e3b2b52..f87bd41aca 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.848.2" +version = "1.848.3" edition = "2021" authors = ["Ruben Fiszel <ruben@windmill.dev>"] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 81aa881d97..74a22ff905 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.848.2 + version: 1.848.3 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 527b975ec7..f519ba0f9e 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.848.2"; +export const VERSION = "v1.848.3"; export async function login(email: string, password: string): Promise<string> { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 9f47ba2f71..3181efaa9d 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.848.2", + "version": "1.848.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.848.2", + "version": "1.848.3", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index f1e990ac0e..84a5acf811 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.848.2", + "version": "1.848.3", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index d30591d7c2..195a8d06d7 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.848.2"; +export const VERSION = "1.848.3"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 5749c367bb..4a6e9d3d23 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.848.2", + "version": "1.848.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.848.2", + "version": "1.848.3", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 9ee19f9482..ce3bdf92a7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.848.2", + "version": "1.848.3", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index 5c04732bc5..7eb45d3a49 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.848.2" +wmill = ">=1.848.3" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 04b252a92d..7b9aebc10c 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.848.2 + version: 1.848.3 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 69ea522091..e19b49fd21 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.848.2' + ModuleVersion = '1.848.3' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index f8b532328c..9c5dd16e04 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.848.2" +version = "1.848.3" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 064d1df2a1..ba2516029a 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.848.2", + "version": "1.848.3", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 6658778155..05d6deb80a 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.848.2", + "version": "1.848.3", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index a3305f95fb..6ef6b432c3 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.848.2 +1.848.3 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 74bf912baf..93f505572e 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.848.2", + "version": "1.848.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.848.2", + "version": "1.848.3", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index 4ea543ff74..623e656869 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.848.2", + "version": "1.848.3", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 6c8fd6cfe2057f2822230bdf9ad2058f537df996 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sun, 25 Oct 2026 08:37:29 -0700 Subject: [PATCH 089/101] feat: per-user Anthropic Workload Identity Federation for Windmill AI (#11998) * feat: authenticate Windmill AI to Anthropic with per-user Workload Identity Federation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: reject WIF-only Anthropic resources in agent steps, scale token refresh margin Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: move Anthropic WIF to a separate anthropic_federated resource type Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: point agent steps at an anthropic resource instead of a federated one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: report a federated resource missing a field instead of reading it as standard Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: count Anthropic federated token exchanges in feature_usage Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to 747336910e5c7498544613ad7863cea59f4db6a1 This commit updates the EE repository reference after PR #923 was merged in windmill-ee-private. Previous ee-repo-ref: 3ea70adff288448f7318ff20b41225fd726ca8d1 New ee-repo-ref: 747336910e5c7498544613ad7863cea59f4db6a1 Automated by sync-ee-ref workflow. * feat: authenticate AI agent steps with anthropic_federated resources (#11999) * feat: authenticate AI agent steps with anthropic_federated resources Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep get_id_token's signature for its EE callers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to 747336910e5c7498544613ad7863cea59f4db6a1 This commit updates the EE repository reference after PR #923 was merged in windmill-ee-private. Previous ee-repo-ref: 3ea70adff288448f7318ff20b41225fd726ca8d1 New ee-repo-ref: 747336910e5c7498544613ad7863cea59f4db6a1 Automated by sync-ee-ref workflow. * feat: switch between anthropic and anthropic_federated when adding a resource Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep registryCcCapable's doc comment on it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> --- backend/ee-repo-ref.txt | 2 +- backend/windmill-ai/src/ai_providers.rs | 4 +- backend/windmill-ai/src/credentials.rs | 15 ++ .../windmill-ai/src/providers/anthropic.rs | 165 +++++++++++++++++ .../windmill-ai/src/providers/google_ai.rs | 1 + backend/windmill-ai/src/providers/mod.rs | 1 + backend/windmill-ai/src/proxy.rs | 1 + backend/windmill-ai/src/types.rs | 87 ++++++++- backend/windmill-api/src/ai.rs | 174 +++++++++++++++++- backend/windmill-common/src/client.rs | 23 ++- backend/windmill-common/src/oidc_oss.rs | 1 + backend/windmill-worker/src/ai/compaction.rs | 22 ++- backend/windmill-worker/src/ai_executor.rs | 25 ++- .../lib/components/AIProviderPicker.svelte | 14 +- .../src/lib/components/AppConnectInner.svelte | 19 ++ .../src/lib/components/ResourcePicker.svelte | 10 +- .../components/copilot/aiResourceProvider.ts | 11 ++ .../workspaceSettings/AISettings.svelte | 3 + 18 files changed, 556 insertions(+), 22 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 1986b0b23f..a0a07e91e0 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -5dfdf811c862c689e42f03f485e02f9f1e7bc7ca +747336910e5c7498544613ad7863cea59f4db6a1 diff --git a/backend/windmill-ai/src/ai_providers.rs b/backend/windmill-ai/src/ai_providers.rs index 311c8d3eb7..489a965ef1 100644 --- a/backend/windmill-ai/src/ai_providers.rs +++ b/backend/windmill-ai/src/ai_providers.rs @@ -213,7 +213,9 @@ impl AIProvider { AIProvider::Groq => Ok("https://api.groq.com/openai/v1".to_string()), AIProvider::OpenRouter => Ok("https://openrouter.ai/api/v1".to_string()), AIProvider::TogetherAI => Ok("https://api.together.xyz/v1".to_string()), - AIProvider::Anthropic => Ok("https://api.anthropic.com/v1".to_string()), + AIProvider::Anthropic => { + Ok(crate::providers::anthropic::ANTHROPIC_API_BASE_URL.to_string()) + } AIProvider::Mistral => Ok("https://api.mistral.ai/v1".to_string()), AIProvider::TypeSafe => Ok(TYPESAFE_BASE_URL.to_string()), AIProvider::Cloudflare => Err(Error::BadRequest( diff --git a/backend/windmill-ai/src/credentials.rs b/backend/windmill-ai/src/credentials.rs index 5a779938ed..f5489c5c30 100644 --- a/backend/windmill-ai/src/credentials.rs +++ b/backend/windmill-ai/src/credentials.rs @@ -32,6 +32,21 @@ pub struct ProviderCredentials { /// A role trust policy that conditions on `sub` has to admit both, or only /// one of the copilot and the AI agent step will be able to assume the role. pub oidc_role_arn: Option<String>, + /// Anthropic Workload Identity Federation settings, from an `anthropic_federated` + /// resource. The API proxy exchanges an OIDC token minted for the requesting + /// user for a short-lived access token, which then goes out as `access_token`. + pub anthropic_federation: Option<AnthropicFederation>, pub platform: AIPlatform, pub custom_headers: HashMap<String, String>, } + +/// The identifiers a Claude Console federation rule needs in a token exchange. +/// None of them is a secret: what authorises the exchange is the OIDC token. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct AnthropicFederation { + pub federation_rule_id: String, + pub organization_id: String, + pub service_account_id: String, + /// Required by Anthropic only when the rule is enabled in several workspaces. + pub workspace_id: Option<String>, +} diff --git a/backend/windmill-ai/src/providers/anthropic.rs b/backend/windmill-ai/src/providers/anthropic.rs index 7acd2db939..2a3417bc62 100644 --- a/backend/windmill-ai/src/providers/anthropic.rs +++ b/backend/windmill-ai/src/providers/anthropic.rs @@ -2,6 +2,7 @@ use super::{anthropic_model_rejects_sampling_params, REASONING_OFF_SENTINEL}; use crate::{ ai_google::parse_data_url, ai_providers::{AIPlatform, AIProvider, DISABLE_ANTHROPIC_PROMPT_CACHING}, + credentials::AnthropicFederation, image_handler::prepare_messages_for_api, proxy::{ add_user_to_body, common_outbound_headers, credential_header, ProxyBuildArgs, ProxyRequest, @@ -837,6 +838,169 @@ impl QueryBuilder for AnthropicQueryBuilder { } } +pub const ANTHROPIC_API_BASE_URL: &str = "https://api.anthropic.com/v1"; + +/// Audience of the OIDC token Windmill presents in an Anthropic token exchange, +/// which a federation rule can pin with its `audience` matcher. +pub const ANTHROPIC_OIDC_AUDIENCE: &str = "https://api.anthropic.com"; + +/// Lifetime of that OIDC token. A federation issuer refuses a token that lives +/// longer than its maximum (one hour by default), and Anthropic caps the access +/// token at twice the assertion's remaining life, so 30 minutes still lets a rule +/// mint its default one-hour token. +pub const ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS: i64 = 1800; + +/// Exchange again this long before the access token expires, so a long streamed +/// response that starts on a reused token cannot outlive it. Capped at half the +/// token's lifetime: a rule may mint tokens for as little as a minute, and a +/// margin longer than that would exchange again on every request. +const FEDERATED_TOKEN_REFRESH_MARGIN: std::time::Duration = std::time::Duration::from_secs(300); + +/// A short-lived Anthropic access token minted by a federated token exchange. +#[derive(Clone, Debug)] +pub struct FederatedAccessToken { + pub access_token: String, + refresh_at: std::time::SystemTime, +} + +impl FederatedAccessToken { + fn new(access_token: String, lifetime: std::time::Duration) -> Self { + // Anthropic mints tokens for at most a day; the clamp keeps an out-of-range + // `expires_in` from overflowing the clock arithmetic. + let lifetime = lifetime.min(std::time::Duration::from_secs(86400)); + let margin = FEDERATED_TOKEN_REFRESH_MARGIN.min(lifetime / 2); + Self { access_token, refresh_at: std::time::SystemTime::now() + lifetime - margin } + } + + pub fn is_fresh(&self) -> bool { + std::time::SystemTime::now() < self.refresh_at + } +} + +#[derive(Serialize)] +struct FederatedTokenRequest<'a> { + grant_type: &'static str, + assertion: &'a str, + federation_rule_id: &'a str, + organization_id: &'a str, + service_account_id: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + workspace_id: Option<&'a str>, +} + +#[derive(Deserialize)] +struct FederatedTokenResponse { + access_token: String, + expires_in: u64, +} + +/// Exchange an OIDC token for an Anthropic access token at `POST /v1/oauth/token` +/// (RFC 7523 `jwt-bearer` grant). `client` must already be pinned to the +/// validated address of `base_url`. +pub async fn exchange_federated_token( + client: &reqwest::Client, + base_url: &str, + federation: &AnthropicFederation, + assertion: &str, +) -> Result<FederatedAccessToken, Error> { + let exchanged = request_federated_token(client, base_url, federation, assertion).await; + windmill_common::feature_usage::log_feature_usage( + "anthropic_federation", + "token_exchange", + if exchanged.is_ok() { "ok" } else { "failed" }, + ); + exchanged +} + +async fn request_federated_token( + client: &reqwest::Client, + base_url: &str, + federation: &AnthropicFederation, + assertion: &str, +) -> Result<FederatedAccessToken, Error> { + let url = AIProvider::build_anthropic_api_url(base_url, "oauth/token"); + let response = client + .post(url) + .header("anthropic-version", ANTHROPIC_VERSION_STANDARD) + .json(&FederatedTokenRequest { + grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", + assertion, + federation_rule_id: &federation.federation_rule_id, + organization_id: &federation.organization_id, + service_account_id: &federation.service_account_id, + workspace_id: federation.workspace_id.as_deref(), + }) + .send() + .await + .map_err(|e| Error::internal_err(format!("Anthropic token exchange failed: {e}")))?; + + let status = response.status(); + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + // Anthropic answers every denied assertion with the same opaque 401; the + // reason is only recorded in the Console's authentication history. + let hint = if status == reqwest::StatusCode::UNAUTHORIZED { + " The reason the exchange was denied is in the authentication history of the Claude Console's Workload identity page." + } else { + "" + }; + return Err(Error::BadRequest(format!( + "Anthropic token exchange failed with status {status}: {body}.{hint}" + ))); + } + + let token = response + .json::<FederatedTokenResponse>() + .await + .map_err(|e| { + Error::internal_err(format!( + "Failed to parse the Anthropic token exchange response: {e}" + )) + })?; + Ok(FederatedAccessToken::new( + token.access_token, + std::time::Duration::from_secs(token.expires_in), + )) +} + +/// The access token of a federated resource for a job, reusing `cached` while it +/// is still fresh, so the agent loop exchanges once per job rather than per turn. +/// Returns `None` for a resource that does not federate. +pub async fn refresh_federated_access_token<'a>( + credentials: &crate::credentials::ProviderCredentials, + cached: &'a mut Option<FederatedAccessToken>, + client: &AuthedClient, +) -> Result<Option<&'a str>, Error> { + let Some(federation) = credentials.anthropic_federation.as_ref() else { + return Ok(None); + }; + if !cached.as_ref().is_some_and(FederatedAccessToken::is_fresh) { + // A worker holds no OIDC signing key, so it asks the API to mint the token for this job. + let assertion = client + .get_id_token_expiring_in( + ANTHROPIC_OIDC_AUDIENCE, + Some(ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS), + ) + .await + .map_err(|e| Error::ExecutionErr(format!("Failed to get an OIDC token: {e}")))?; + let http_client = crate::utils::pinned_ai_client_for(&credentials.base_url).await?; + *cached = Some( + exchange_federated_token(&http_client, &credentials.base_url, federation, &assertion) + .await?, + ); + } + Ok(cached.as_ref().map(|token| token.access_token.as_str())) +} + +/// Headers authenticating a request with a federated access token, which Anthropic +/// takes as a bearer token in place of `x-api-key`. +pub fn federated_auth_headers(access_token: &str) -> Vec<(&'static str, String)> { + vec![ + ("Authorization", format!("Bearer {access_token}")), + ("anthropic-version", ANTHROPIC_VERSION_STANDARD.to_string()), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -859,6 +1023,7 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform, custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/providers/google_ai.rs b/backend/windmill-ai/src/providers/google_ai.rs index bbf45e5e57..06a404e5a4 100644 --- a/backend/windmill-ai/src/providers/google_ai.rs +++ b/backend/windmill-ai/src/providers/google_ai.rs @@ -805,6 +805,7 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform, custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/providers/mod.rs b/backend/windmill-ai/src/providers/mod.rs index 82dceaa02f..ffddd33d3a 100644 --- a/backend/windmill-ai/src/providers/mod.rs +++ b/backend/windmill-ai/src/providers/mod.rs @@ -370,6 +370,7 @@ mod parity_tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: kase.platform.clone(), custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/proxy.rs b/backend/windmill-ai/src/proxy.rs index ca6ee1b59b..66285437e4 100644 --- a/backend/windmill-ai/src/proxy.rs +++ b/backend/windmill-ai/src/proxy.rs @@ -285,6 +285,7 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/types.rs b/backend/windmill-ai/src/types.rs index 59733e352c..3950576aed 100644 --- a/backend/windmill-ai/src/types.rs +++ b/backend/windmill-ai/src/types.rs @@ -19,7 +19,7 @@ pub struct McpToolSource { use crate::{ ai_google::sanitize_schema_for_google, ai_providers::{empty_string_as_none, AIProvider}, - credentials::ProviderCredentials, + credentials::{AnthropicFederation, ProviderCredentials}, }; use windmill_common::{db::DB, error::Error, flow_status::AgentAction, flows::FlowModule}; use windmill_parser::Typ; @@ -270,6 +270,16 @@ pub struct ProviderResource { /// credentials exchange this crate does not perform. #[serde(default, deserialize_with = "empty_string_as_none")] pub token_url: Option<String>, + /// Set only by `anthropic_federated` resources, which authenticate through + /// Workload Identity Federation with an OIDC token minted for the job. + #[serde(default, deserialize_with = "empty_string_as_none")] + pub federation_rule_id: Option<String>, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub organization_id: Option<String>, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub service_account_id: Option<String>, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub workspace_id: Option<String>, /// The API token of a `cloudflare` resource, which names it `token` rather than `api_key`. #[serde(default, deserialize_with = "empty_string_as_none")] pub token: Option<String>, @@ -323,8 +333,13 @@ impl ProviderWithResource { /// Callers must only pass resources that were already authorized for the /// current job/workspace; this helper does not perform access checks. pub async fn to_provider_credentials(&self, db: &DB) -> Result<ProviderCredentials, Error> { + let anthropic_federation = self.anthropic_federation()?; let base_url = if self.kind == AIProvider::AWSBedrock { String::new() + } else if anthropic_federation.is_some() { + // The exchanged token is the job's identity, so it only ever goes to + // Anthropic: a resource cannot point it at another host. + crate::providers::anthropic::ANTHROPIC_API_BASE_URL.to_string() } else { self.get_base_url(db).await? }; @@ -348,11 +363,40 @@ impl ProviderWithResource { aws_secret_access_key: self.resource.aws_secret_access_key.clone(), aws_session_token: self.resource.aws_session_token.clone(), oidc_role_arn: self.resource.oidc_role_arn.clone(), + anthropic_federation, platform: self.resource.platform.clone(), custom_headers: self.resource.headers.clone(), }) } + /// The federation settings of an `anthropic_federated` resource, which only + /// `federation_rule_id` identifies; the other required fields are checked here. + fn anthropic_federation(&self) -> Result<Option<AnthropicFederation>, Error> { + let resource = &self.resource; + let Some(federation_rule_id) = resource.federation_rule_id.clone() else { + return Ok(None); + }; + if self.kind != AIProvider::Anthropic { + return Err(Error::ExecutionErr(format!( + "An anthropic_federated resource can only be used with the Anthropic provider, not {:?}", + self.kind + ))); + } + let required = |value: &Option<String>, name: &str| { + value.clone().ok_or_else(|| { + Error::ExecutionErr(format!( + "The anthropic_federated resource needs {name} to be set" + )) + }) + }; + Ok(Some(AnthropicFederation { + federation_rule_id, + organization_id: required(&resource.organization_id, "organization_id")?, + service_account_id: required(&resource.service_account_id, "service_account_id")?, + workspace_id: resource.workspace_id.clone(), + })) + } + #[cfg(feature = "bedrock")] pub fn get_region(&self) -> Option<&str> { self.resource.region.as_deref() @@ -983,6 +1027,47 @@ pub struct S3ObjectWithType { mod tests { use super::*; + #[test] + fn a_federated_resource_resolves_its_federation_and_names_a_missing_field() { + let provider = |kind: &str, resource: &str| -> ProviderWithResource { + serde_json::from_str(&format!( + r#"{{"kind":"{kind}","model":"m","resource":{resource}}}"# + )) + .unwrap() + }; + let federated = r#"{"federation_rule_id":"fdrl_x","organization_id":"org","service_account_id":"svac_x","workspace_id":""}"#; + + assert_eq!( + provider("anthropic", federated) + .anthropic_federation() + .unwrap(), + Some(AnthropicFederation { + federation_rule_id: "fdrl_x".to_string(), + organization_id: "org".to_string(), + service_account_id: "svac_x".to_string(), + workspace_id: None, + }) + ); + let incomplete = provider( + "anthropic", + r#"{"federation_rule_id":"fdrl_x","organization_id":"org"}"#, + ); + assert!(incomplete + .anthropic_federation() + .unwrap_err() + .to_string() + .contains("service_account_id")); + assert!(provider("openai", federated) + .anthropic_federation() + .is_err()); + assert_eq!( + provider("anthropic", r#"{"api_key":"k","organization_id":"org"}"#) + .anthropic_federation() + .unwrap(), + None + ); + } + /// The schema is part of the prompt prefix the provider caches on, so its keys must /// serialize in the same order on every request. #[test] diff --git a/backend/windmill-api/src/ai.rs b/backend/windmill-api/src/ai.rs index 8de5e16c11..213a41b4eb 100644 --- a/backend/windmill-api/src/ai.rs +++ b/backend/windmill-api/src/ai.rs @@ -24,7 +24,10 @@ use windmill_ai::ai_providers::{ empty_string_as_none, AIPlatform, AIProvider, ProviderConfig, ProviderModel, }; use windmill_ai::ai_types::{validate_token_limit, CONTEXT_WINDOWS, MAX_MODEL_RATE, OUTPUT_LIMITS}; -use windmill_ai::credentials::ProviderCredentials; +use windmill_ai::credentials::{AnthropicFederation, ProviderCredentials}; +use windmill_ai::providers::anthropic::{ + exchange_federated_token, FederatedAccessToken, ANTHROPIC_API_BASE_URL, +}; #[cfg(feature = "bedrock")] use windmill_ai::providers::bedrock::{ handle_bedrock_proxy, BedrockProxyResponse, BedrockProxyResponseBody, @@ -119,6 +122,10 @@ lazy_static::lazy_static! { pub static ref AI_REQUEST_CACHE: Cache<(String, AIProvider), ExpiringProviderCredentials> = Cache::new(500); + /// Anthropic access tokens from a federated exchange, keyed by (workspace, + /// federation settings, user email). Like BEDROCK_ASSUMED_ROLE_CACHE, an entry + /// is never handed to another user than the one the OIDC token named. + static ref ANTHROPIC_FEDERATED_TOKEN_CACHE: Cache<(String, AnthropicFederation, String), FederatedAccessToken> = Cache::new(500); } #[cfg(feature = "bedrock")] @@ -132,6 +139,8 @@ lazy_static::lazy_static! { pub(crate) fn invalidate_ai_request_cache_for_workspace(workspace_id: &str) { AI_REQUEST_CACHE.retain(|(cached_workspace_id, _), _| cached_workspace_id != workspace_id); + ANTHROPIC_FEDERATED_TOKEN_CACHE + .retain(|(cached_workspace_id, _, _), _| cached_workspace_id != workspace_id); // Dropped alongside the credentials that named the role, so that changing a // workspace's AI settings does not leave a session assumed under the old ones // in play until STS expires it. @@ -247,10 +256,33 @@ struct OAuthTokens { access_token: String, } +/// An `anthropic_federated` resource: the Claude Console federation rule, +/// organization, service account and (for a rule enabled in several workspaces) +/// workspace to exchange the requesting user's OIDC token against. +/// +/// It has no base URL on purpose. The exchanged token is the identity of whoever +/// uses the resource, not of whoever wrote it, so a configurable host would let +/// the resource's author collect other users' tokens. +/// +/// Only `federation_rule_id` decides that a value is one: the other fields are +/// optional here and checked afterwards, so a resource missing one is reported +/// rather than read as a standard resource with no key. +#[derive(Deserialize, Debug)] +struct AIAnthropicFederatedResource { + federation_rule_id: String, + #[serde(default)] + organization_id: String, + #[serde(default)] + service_account_id: String, + #[serde(default, deserialize_with = "empty_string_as_none")] + workspace_id: Option<String>, +} + #[derive(Deserialize, Debug)] #[serde(untagged)] enum AIResource { OAuth(AIOAuthResource), + AnthropicFederated(AIAnthropicFederatedResource), Standard(AIStandardResource), } @@ -345,10 +377,50 @@ async fn resolve_provider_credentials( aws_secret_access_key, aws_session_token, oidc_role_arn, + anthropic_federation: None, platform: resource.platform, custom_headers: resource.headers, }) } + AIResource::AnthropicFederated(resource) => { + if *provider != AIProvider::Anthropic { + return Err(Error::BadRequest(format!( + "An anthropic_federated resource can only be used for the Anthropic provider, not {provider:?}" + ))); + } + let required = [ + ("federation_rule_id", &resource.federation_rule_id), + ("organization_id", &resource.organization_id), + ("service_account_id", &resource.service_account_id), + ]; + if let Some((field, _)) = required.iter().find(|(_, value)| value.is_empty()) { + return Err(Error::BadRequest(format!( + "The anthropic_federated resource needs {field} to be set" + ))); + } + + Ok(ProviderCredentials { + provider: provider.clone(), + base_url: ANTHROPIC_API_BASE_URL.to_string(), + api_key: None, + access_token: None, + organization_id: None, + user: None, + region: None, + aws_access_key_id: None, + aws_secret_access_key: None, + aws_session_token: None, + oidc_role_arn: None, + anthropic_federation: Some(AnthropicFederation { + federation_rule_id: resource.federation_rule_id, + organization_id: resource.organization_id, + service_account_id: resource.service_account_id, + workspace_id: resource.workspace_id, + }), + platform: AIPlatform::Standard, + custom_headers: HashMap::new(), + }) + } AIResource::OAuth(resource) => { let user = if let Some(user) = resource.user.clone() { Some(resolve_var(user, db, w_id, user_db.as_ref(), authed).await?) @@ -370,6 +442,7 @@ async fn resolve_provider_credentials( aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), }) @@ -522,6 +595,73 @@ async fn assume_bedrock_role( } } +/// Exchange an OIDC token minted for the requesting user for an Anthropic access +/// token, in place, when the resource is set up for Workload Identity Federation. +/// +/// Runs after the workspace credential cache for the same reason the Bedrock +/// exchange does: the token's `sub` names the user, and is what a federation rule +/// matches and the Claude Console's authentication history records. +async fn resolve_anthropic_federated_credentials( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + credentials: &mut ProviderCredentials, +) -> Result<()> { + let Some(federation) = credentials.anthropic_federation.as_ref() else { + return Ok(()); + }; + + let cache_key = (w_id.to_string(), federation.clone(), authed.email.clone()); + let token = match ANTHROPIC_FEDERATED_TOKEN_CACHE + .get(&cache_key) + .filter(FederatedAccessToken::is_fresh) + { + Some(cached) => cached, + None => { + let assertion = mint_anthropic_oidc_token(db, w_id, authed).await?; + let client = pinned_ai_client_for(&credentials.base_url).await?; + let token = + exchange_federated_token(&client, &credentials.base_url, federation, &assertion) + .await?; + ANTHROPIC_FEDERATED_TOKEN_CACHE.insert(cache_key, token.clone()); + token + } + }; + + credentials.access_token = Some(token.access_token); + Ok(()) +} + +async fn mint_anthropic_oidc_token(db: &DB, w_id: &str, authed: &ApiAuthed) -> Result<String> { + #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] + { + use windmill_ai::providers::anthropic::{ + ANTHROPIC_OIDC_AUDIENCE, ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS, + }; + use windmill_common::oidc_oss::{generate_id_token, OidcCaller, WorkspaceClaim}; + + let id_token = generate_id_token( + OidcCaller::Anthropic, + Some(db), + WorkspaceClaim { workspace: w_id.to_string() }, + ANTHROPIC_OIDC_AUDIENCE, + format!("{}::{}", authed.email, w_id), + Some(authed.email.clone()), + Some(ANTHROPIC_OIDC_TOKEN_LIFETIME_SECS), + ) + .await?; + Ok(id_token.to_string()) + } + #[cfg(not(all(feature = "enterprise", feature = "openidconnect", feature = "private")))] + { + let _ = (db, w_id, authed); + Err(Error::BadRequest( + "Anthropic Workload Identity Federation through Windmill's OIDC provider requires an enterprise license" + .to_string(), + )) + } +} + #[derive(Clone, Debug)] pub struct ExpiringProviderCredentials { credentials: ProviderCredentials, @@ -1129,6 +1269,7 @@ async fn global_proxy( aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), }; @@ -1435,6 +1576,7 @@ async fn proxy( #[cfg(feature = "bedrock")] resolve_bedrock_oidc_credentials(&db, &w_id, &authed, &mut credentials).await?; + resolve_anthropic_federated_credentials(&db, &w_id, &authed, &mut credentials).await?; // Free tier: pin the model and clamp max_tokens server-side before forwarding, // since the request body is otherwise client-controlled. @@ -1643,11 +1785,41 @@ mod tests { aws_secret_access_key: None, aws_session_token: None, oidc_role_arn: None, + anthropic_federation: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), } } + #[test] + fn only_a_federation_rule_makes_a_resource_anthropic_federated() { + let federated = serde_json::json!({ + "federation_rule_id": "fdrl_x", + "organization_id": "00000000-0000-0000-0000-000000000000", + "service_account_id": "svac_x", + "workspace_id": "" + }); + assert!(matches!( + serde_json::from_value::<AIResource>(federated), + Ok(AIResource::AnthropicFederated( + AIAnthropicFederatedResource { workspace_id: None, .. } + )) + )); + + let incomplete = serde_json::json!({"federation_rule_id": "fdrl_x"}); + assert!(matches!( + serde_json::from_value::<AIResource>(incomplete), + Ok(AIResource::AnthropicFederated(_)) + )); + + // `organization_id` is also the OpenAI organization of a standard resource. + let standard = serde_json::json!({"api_key": "k", "organization_id": "org-x"}); + assert!(matches!( + serde_json::from_value::<AIResource>(standard), + Ok(AIResource::Standard(_)) + )); + } + #[test] fn ai_standard_resource_ignores_legacy_enable_1m_context_keys() { // Resources created before the field was removed still carry the legacy key diff --git a/backend/windmill-common/src/client.rs b/backend/windmill-common/src/client.rs index 8edcdc64fe..54eb486da7 100644 --- a/backend/windmill-common/src/client.rs +++ b/backend/windmill-common/src/client.rs @@ -71,15 +71,32 @@ impl AuthedClient { } pub async fn get_id_token(&self, audience: &str) -> anyhow::Result<String> { + self.get_id_token_expiring_in(audience, None).await + } + + /// `expires_in` caps the token's lifetime below the instance default, for + /// audiences that refuse long-lived assertions. + pub async fn get_id_token_expiring_in( + &self, + audience: &str, + expires_in: Option<i64>, + ) -> anyhow::Result<String> { + // An audience can be a URL, whose slashes would otherwise split the path segment. let url = format!( "{}/api/w/{}/oidc/token/{}", - self.base_internal_url, self.workspace, audience + self.base_internal_url, + self.workspace, + urlencoding::encode(audience) ); - let response = self + let mut request = self .force_client .as_ref() .unwrap_or(&HTTP_CLIENT) - .post(&url) + .post(&url); + if let Some(expires_in) = expires_in { + request = request.query(&[("expires_in", expires_in)]); + } + let response = request .header( reqwest::header::AUTHORIZATION, reqwest::header::HeaderValue::from_str(&format!("Bearer {}", self.token))?, diff --git a/backend/windmill-common/src/oidc_oss.rs b/backend/windmill-common/src/oidc_oss.rs index 2945f8b87a..60ef4da687 100644 --- a/backend/windmill-common/src/oidc_oss.rs +++ b/backend/windmill-common/src/oidc_oss.rs @@ -98,6 +98,7 @@ pub enum OidcCaller { Vault, Sqs, Bedrock, + Anthropic, } #[cfg(not(feature = "private"))] diff --git a/backend/windmill-worker/src/ai/compaction.rs b/backend/windmill-worker/src/ai/compaction.rs index b933348a2e..82a79985e8 100644 --- a/backend/windmill-worker/src/ai/compaction.rs +++ b/backend/windmill-worker/src/ai/compaction.rs @@ -610,12 +610,24 @@ async fn summarize_prefix( request .query_builder .get_endpoint(base_url, request.model, &OutputType::Text); - let auth_headers = retain_effective_credentials( + // Summaries are rare enough that exchanging afresh costs less than threading + // the agent loop's cached token through. + let mut federated_token = None; + let auth_headers = match windmill_ai::providers::anthropic::refresh_federated_access_token( request.credentials, - request - .query_builder - .get_auth_headers(api_key, base_url, &OutputType::Text), - ); + &mut federated_token, + request.client, + ) + .await? + { + Some(token) => windmill_ai::providers::anthropic::federated_auth_headers(token), + None => retain_effective_credentials( + request.credentials, + request + .query_builder + .get_auth_headers(api_key, base_url, &OutputType::Text), + ), + }; // As in the agent loop, `endpoint` derives from the user-controlled provider // base_url, so DNS is pinned to the SSRF-validated address. diff --git a/backend/windmill-worker/src/ai_executor.rs b/backend/windmill-worker/src/ai_executor.rs index bf5c3e4f9f..6c37f67f2e 100644 --- a/backend/windmill-worker/src/ai_executor.rs +++ b/backend/windmill-worker/src/ai_executor.rs @@ -1666,6 +1666,9 @@ pub async fn run_agent( // re-assumed only near expiry, rather than on every model turn. #[cfg(feature = "bedrock")] let mut bedrock_assumed_role: Option<windmill_ai::ai_bedrock::AssumedRoleCredentials> = None; + let mut anthropic_federated_token: Option< + windmill_ai::providers::anthropic::FederatedAccessToken, + > = None; // Main agent loop for i in 0..max_iterations { @@ -1804,6 +1807,15 @@ pub async fn run_agent( ))); } + let federated_token = + windmill_ai::providers::anthropic::refresh_federated_access_token( + &credentials, + &mut anthropic_federated_token, + client, + ) + .await? + .map(str::to_string); + let timeout = resolve_job_timeout(conn, &job.workspace_id, job.id, job.timeout) .await .0; @@ -1855,10 +1867,15 @@ pub async fn run_agent( }; let endpoint = query_builder.get_endpoint(base_url, args.provider.get_model(), output_type); - let auth_headers = retain_effective_credentials( - &credentials, - query_builder.get_auth_headers(api_key, base_url, output_type), - ); + let auth_headers = match federated_token.as_deref() { + Some(token) => { + windmill_ai::providers::anthropic::federated_auth_headers(token) + } + None => retain_effective_credentials( + &credentials, + query_builder.get_auth_headers(api_key, base_url, output_type), + ), + }; let resp = build_http_request(&endpoint, &auth_headers, request_body) .send() diff --git a/frontend/src/lib/components/AIProviderPicker.svelte b/frontend/src/lib/components/AIProviderPicker.svelte index 67afad9be6..0d23ab55a3 100644 --- a/frontend/src/lib/components/AIProviderPicker.svelte +++ b/frontend/src/lib/components/AIProviderPicker.svelte @@ -9,6 +9,7 @@ } from './copilot/lib' import type { AIProvider, ProviderConfig } from '$lib/gen' import ResourcePicker from './ResourcePicker.svelte' + import { aiResourceProvider } from './copilot/aiResourceProvider' import Toggle from './Toggle.svelte' import { saveConfig, removeConfig, isSameAsStoredConfig } from './aiProviderStorage' import AIReasoningEffortPicker from './AIReasoningEffortPicker.svelte' @@ -57,7 +58,11 @@ const offeredProviders = Object.keys( untrack(() => decision) ? DECISION_AI_PROVIDERS : AI_PROVIDERS ) - const providerResourceTypes = offeredProviders.join(',') + // Federated Anthropic resources authenticate the anthropic provider without a key of their own. + const providerResourceTypes = [ + ...offeredProviders, + ...(offeredProviders.includes('anthropic') ? ['anthropic_federated'] : []) + ].join(',') if (!_uncheckedValue) { _uncheckedValue = { @@ -143,13 +148,14 @@ function onResourcePicked(_path: string | undefined, type: string | undefined) { // An empty type is the placeholder the picker keeps for a saved path it could not find. It // says nothing about the provider, so the kind stands. - if (!value || !type || !offeredProviders.includes(type)) { + const provider = aiResourceProvider(type) + if (!value || !provider || !offeredProviders.includes(provider)) { return } - if (value.kind === type) { + if (value.kind === provider) { return } - value.kind = type as AIProvider + value.kind = provider // Models are per provider, and a reasoning token is per model. value.model = '' value.reasoning_effort = undefined diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index 81dd5225fb..069965b4e7 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -54,6 +54,7 @@ import SchemaForm from './SchemaForm.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import type { NativeConnect } from './triggers/native/utils' + import { AI_RESOURCE_TYPE_ALTERNATIVES } from './copilot/aiResourceProvider' const operatingWorkspace = useOperatingWorkspace() @@ -258,6 +259,16 @@ return registryEntryFor(connectClient, resourceType) } + let resourceTypeAlternative = $derived(AI_RESOURCE_TYPE_ALTERNATIVES[resourceType]) + + function switchToResourceType(rt: string) { + connectClient = rt + resourceType = rt + linkedSecrets = [] + args = {} + getResourceTypeInfo() + } + /** The static registry declares this provider supports client credentials */ function registryCcCapable(): boolean { return registryCcCapableFor(connectClient, resourceType) @@ -1477,6 +1488,14 @@ Acquire the token automatically via client credentials instead </button> {/if} + {#if resourceTypeAlternative} + <button + onclick={() => switchToResourceType(resourceTypeAlternative.resourceType)} + class="text-xs font-normal text-accent w-fit -mt-4" + > + {resourceTypeAlternative.label} + </button> + {/if} <!-- The form is a section of its own, not just the next field: it needs more of a break from the description than the uniform gap gives. --> <div class="mt-2"> diff --git a/frontend/src/lib/components/ResourcePicker.svelte b/frontend/src/lib/components/ResourcePicker.svelte index b396bd6dee..d766e5a51f 100644 --- a/frontend/src/lib/components/ResourcePicker.svelte +++ b/frontend/src/lib/components/ResourcePicker.svelte @@ -20,6 +20,9 @@ value?: string | undefined valueType?: string | undefined resourceType?: string | undefined + /** Further resource types whose resources are offered alongside `resourceType`'s. New + * resources are still created as `resourceType`. */ + additionalResourceTypes?: string[] disabled?: boolean disablePortal?: boolean showSchemaExplorer?: boolean @@ -46,6 +49,7 @@ value = $bindable(undefined), valueType = $bindable(undefined), resourceType = undefined, + additionalResourceTypes = [], disabled = false, disablePortal = false, showSchemaExplorer = false, @@ -114,8 +118,10 @@ async function loadResources(resourceType: string | undefined) { loading = true try { - const resourceTypesToQuery = - resourceType === 'snowflake' ? ['snowflake', 'snowflake_oauth'] : [resourceType] + const resourceTypesToQuery = [ + ...(resourceType === 'snowflake' ? ['snowflake', 'snowflake_oauth'] : [resourceType]), + ...additionalResourceTypes + ] const resources = await Promise.all( resourceTypesToQuery.map((rt) => diff --git a/frontend/src/lib/components/copilot/aiResourceProvider.ts b/frontend/src/lib/components/copilot/aiResourceProvider.ts index 91ae926dfc..cd80bb21c0 100644 --- a/frontend/src/lib/components/copilot/aiResourceProvider.ts +++ b/frontend/src/lib/components/copilot/aiResourceProvider.ts @@ -1,9 +1,20 @@ import type { AIProvider } from '$lib/gen' import { AI_PROVIDERS } from './lib' +/** A resource type that authenticates the same provider another way, offered as a switch when + * creating a resource of the first, since a picker scoped to a provider only creates its main type. */ +export const AI_RESOURCE_TYPE_ALTERNATIVES: Record<string, { resourceType: string; label: string }> = { + anthropic: { + resourceType: 'anthropic_federated', + label: 'Authenticate with Workload Identity Federation instead of an API key' + }, + anthropic_federated: { resourceType: 'anthropic', label: 'Use an API key instead' } +} + /** The AI provider a resource of this type holds credentials for, if any. */ export function aiResourceProvider(resourceType: string | undefined): AIProvider | undefined { if (resourceType === 'openai_client_credentials_oauth') return 'openai' + if (resourceType === 'anthropic_federated') return 'anthropic' return resourceType && Object.hasOwn(AI_PROVIDERS, resourceType) ? (resourceType as AIProvider) : undefined diff --git a/frontend/src/lib/components/workspaceSettings/AISettings.svelte b/frontend/src/lib/components/workspaceSettings/AISettings.svelte index 05159e3057..79d7be2214 100644 --- a/frontend/src/lib/components/workspaceSettings/AISettings.svelte +++ b/frontend/src/lib/components/workspaceSettings/AISettings.svelte @@ -520,6 +520,9 @@ resourceType={provider === 'openai' && usingOpenaiClientCredentialsOauth ? 'openai_client_credentials_oauth' : provider} + additionalResourceTypes={provider === 'anthropic' + ? ['anthropic_federated'] + : []} initialValue={aiProviders[provider].resource_path} bind:value={ () => aiProviders[provider].resource_path || undefined, From 878d690a5bfd438cd10f228ca7e9a4cacbd82893 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sun, 25 Oct 2026 08:53:44 -0700 Subject: [PATCH 090/101] chore: remove nsjail enterprise feature startup warning (#12003) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- backend/windmill-worker/src/worker.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index aa742bfdf5..a4749f3ee5 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -2890,14 +2890,6 @@ pub async fn run_worker( killpill_tx: KillpillSender, base_internal_url: &str, ) { - #[cfg(not(feature = "enterprise"))] - if is_sandboxing_enabled() { - tracing::warn!( - worker = %worker_name, hostname = %hostname, - "NSJAIL to sandbox process in untrusted environments is an enterprise feature but allowed to be used for testing purposes" - ); - } - // Force UNSHARE_PATH and NSJAIL_AVAILABLE initialization now for clear startup logging let _ = &*UNSHARE_PATH; let _ = &*NSJAIL_AVAILABLE; From a72484b2aaeccbd5a2d19e71ee75d21494ea74f4 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sun, 25 Oct 2026 08:57:47 -0700 Subject: [PATCH 091/101] chore(main): release 1.849.0 (#12002) * chore(main): release 1.849.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 + backend/Cargo.lock | 166 +++++++++--------- backend/Cargo.toml | 4 +- .../parsers/windmill-parser-wasm/Cargo.lock | 48 ++--- .../parsers/windmill-parser-wasm/Cargo.toml | 2 +- backend/windmill-api/openapi.yaml | 2 +- benchmarks/lib.ts | 2 +- chat-sdk/package-lock.json | 4 +- chat-sdk/package.json | 2 +- cli/src/core/constants.ts | 2 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- lsp/Pipfile | 2 +- openflow.openapi.yaml | 2 +- .../WindmillClient/WindmillClient.psd1 | 2 +- python-client/wmill/pyproject.toml | 2 +- typescript-client/jsr.json | 2 +- typescript-client/package.json | 2 +- version.txt | 2 +- windmill-yaml-validator/package-lock.json | 4 +- windmill-yaml-validator/package.json | 2 +- 22 files changed, 137 insertions(+), 130 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6fabba7832..9edb1a8e87 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.848.3" + ".": "1.849.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 67af90452a..d0fccb9912 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.849.0](https://github.com/windmill-labs/windmill/compare/v1.848.3...v1.849.0) (2026-10-25) + + +### Features + +* per-user Anthropic Workload Identity Federation for Windmill AI ([#11998](https://github.com/windmill-labs/windmill/issues/11998)) ([6c8fd6c](https://github.com/windmill-labs/windmill/commit/6c8fd6cfe2057f2822230bdf9ad2058f537df996)) + ## [1.848.3](https://github.com/windmill-labs/windmill/compare/v1.848.2...v1.848.3) (2026-10-25) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index b913ba0193..3ae4630fe5 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -5218,9 +5218,9 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "erased-serde" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" dependencies = [ "serde", "serde_core", @@ -12408,9 +12408,9 @@ checksum = "1b6709c7b6754dca1311b3c73e79fcce40dd414c782c66d88e8823030093b02b" [[package]] name = "sketches-ddsketch" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513c3f5f732bfd6fbb187619c2dfe9d2f25f1a2976f01d575f0fd329d565df56" +checksum = "e53e2f8d4e9c692f23a90208fad6a64862f413e286d533f1f649f160e2d5caee" dependencies = [ "serde", ] @@ -15487,7 +15487,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-nats", @@ -15577,7 +15577,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.848.3" +version = "1.849.0" dependencies = [ "async-stream", "async-trait", @@ -15612,7 +15612,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15625,7 +15625,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "argon2", @@ -15768,7 +15768,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15792,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15809,7 +15809,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -15835,7 +15835,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.848.3" +version = "1.849.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15845,7 +15845,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15862,7 +15862,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "base64 0.22.1", @@ -15884,7 +15884,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -15907,7 +15907,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15923,7 +15923,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15945,7 +15945,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15967,7 +15967,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -15981,7 +15981,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-nats", @@ -16017,7 +16017,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16043,7 +16043,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16071,7 +16071,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16093,7 +16093,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16113,7 +16113,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16155,7 +16155,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16185,7 +16185,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.848.3" +version = "1.849.0" dependencies = [ "lazy_static", "serde", @@ -16197,7 +16197,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.848.3" +version = "1.849.0" dependencies = [ "argon2", "axum", @@ -16221,7 +16221,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16236,7 +16236,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.848.3" +version = "1.849.0" dependencies = [ "axum", "chrono", @@ -16275,7 +16275,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.848.3" +version = "1.849.0" dependencies = [ "chrono", "lazy_static", @@ -16290,7 +16290,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "axum", @@ -16309,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.848.3" +version = "1.849.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16427,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.848.3" +version = "1.849.0" dependencies = [ "chrono", "futures", @@ -16447,7 +16447,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.848.3" +version = "1.849.0" dependencies = [ "regex", "serde", @@ -16464,7 +16464,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16491,7 +16491,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "futures", @@ -16508,7 +16508,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.3" +version = "1.849.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16524,7 +16524,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -16546,7 +16546,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -16577,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "arc-swap", @@ -16602,7 +16602,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-stream", @@ -16638,7 +16638,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "futures", @@ -16657,7 +16657,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.3" +version = "1.849.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16666,7 +16666,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16678,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -16690,7 +16690,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "gosyn", @@ -16702,7 +16702,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16714,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -16726,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "nu-parser", @@ -16737,7 +16737,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16748,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16760,7 +16760,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16771,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -16794,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -16806,7 +16806,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16820,7 +16820,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16837,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16850,7 +16850,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde", @@ -16862,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16880,7 +16880,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16896,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16913,7 +16913,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -16927,7 +16927,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -16966,7 +16966,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "const_format", @@ -17004,7 +17004,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.848.3" +version = "1.849.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17015,7 +17015,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -17050,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17074,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17107,7 +17107,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17134,7 +17134,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17167,7 +17167,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17187,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17221,7 +17221,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17258,7 +17258,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17281,7 +17281,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17305,7 +17305,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-nats", @@ -17329,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17364,7 +17364,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17392,7 +17392,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-trait", @@ -17417,7 +17417,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17436,7 +17436,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-once-cell", @@ -17554,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.848.3" +version = "1.849.0" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index aa8758573b..b42cac10f0 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.848.3" +version = "1.849.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.848.3" +version = "1.849.0" authors = ["Ruben Fiszel <ruben@windmill.dev>"] edition = "2021" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index c55eb2fb2c..ba2d483531 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.848.3" +version = "1.849.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.848.3" +version = "1.849.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.848.3" +version = "1.849.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.848.3" +version = "1.849.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index f87bd41aca..0d0697c3fd 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.848.3" +version = "1.849.0" edition = "2021" authors = ["Ruben Fiszel <ruben@windmill.dev>"] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 74a22ff905..9e26d400cd 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.848.3 + version: 1.849.0 title: Windmill API contact: diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index f519ba0f9e..41d2fe87c0 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.848.3"; +export const VERSION = "v1.849.0"; export async function login(email: string, password: string): Promise<string> { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 3181efaa9d..61ed2382a8 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.848.3", + "version": "1.849.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.848.3", + "version": "1.849.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 84a5acf811..992d52b207 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.848.3", + "version": "1.849.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 195a8d06d7..bf083042d9 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.848.3"; +export const VERSION = "1.849.0"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 4a6e9d3d23..206f8bb476 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.848.3", + "version": "1.849.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.848.3", + "version": "1.849.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index ce3bdf92a7..86b73762fa 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.848.3", + "version": "1.849.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/lsp/Pipfile b/lsp/Pipfile index 7eb45d3a49..db712975b4 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.848.3" +wmill = ">=1.849.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 7b9aebc10c..91a2d4b79e 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.848.3 + version: 1.849.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index e19b49fd21..786d50f9fa 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.848.3' + ModuleVersion = '1.849.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 9c5dd16e04..b365d607b8 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.848.3" +version = "1.849.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index ba2516029a..7606c7fd06 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.848.3", + "version": "1.849.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 05d6deb80a..70dec2bd09 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.848.3", + "version": "1.849.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index 6ef6b432c3..d8b82c7f85 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.848.3 +1.849.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 93f505572e..211d9f0455 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.848.3", + "version": "1.849.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.848.3", + "version": "1.849.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index 623e656869..abfe2607d0 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.848.3", + "version": "1.849.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts", From 53197e96d7a2e5871960de1c2c941fbf468f5590 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sun, 25 Oct 2026 21:11:50 +0100 Subject: [PATCH 092/101] docs(readme): code-first workflows, apps and AI agents, with review guardrails for AI-built code (#12006) * docs(readme): lead with code-first workflows, apps and AI agents, and the review guardrails for AI-built code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(readme): name Lovable among the alternatives Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(readme): name n8n among the alternatives Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 597a9142b2..754ec2aab2 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@ </p> <p align=center> -Open-source developer platform for internal code: APIs, background jobs, workflows and UIs. Self-hostable alternative to Retool, Pipedream, Superblocks and a simplified Temporal with autogenerated UIs and custom UIs to trigger workflows and scripts as internal apps. +Open-source, self-hostable code-first platform for workflows, apps and AI agents, running on the fastest self-hostable orchestrator. Engineers write code in 20+ languages and sync it with Git. Business teams build on the same platform with AI, while review, promotion between environments and isolated workers keep engineers in control of what ships. Self-hostable alternative to Lovable, Retool, n8n and a simplified Temporal. <p align=center> -Scripts are turned into sharable UIs automatically, and can be composed together into flows or used into richer apps built with low-code. Supported languages: Python, TypeScript, Go, Bash, SQL, GraphQL, PowerShell, Rust, and more. +Scripts are turned into sharable UIs, APIs and cron jobs automatically, and can be composed together into flows, data pipelines, AI agents or full-code React and Svelte apps. Supported languages: Python, TypeScript, Go, Bash, SQL, GraphQL, PowerShell, Rust, and more. </p> <p align="center"> @@ -34,7 +34,7 @@ Scripts are turned into sharable UIs automatically, and can be composed together <a href="https://app.windmill.dev">Try it</a> - <a href="https://www.windmill.dev/">Website</a> - <a href="https://www.windmill.dev/docs/intro/">Docs</a> - <a href="https://discord.gg/V7PM2YHsPB">Discord</a> - <a href="https://hub.windmill.dev">Hub</a> - <a href="./CONTRIBUTING.md">Contributing</a> </p> -# Windmill - Developer platform for APIs, background jobs, workflows and UIs +# Windmill - Code-first platform for workflows, apps and AI agents Windmill is fully open-sourced (AGPLv3) and Windmill Labs offers dedicated instances and commercial support and licenses. @@ -42,7 +42,8 @@ Windmill is fully open-sourced (AGPLv3) and Windmill Labs offers dedicated insta https://github.com/user-attachments/assets/d80de1d9-64de-4d89-aacd-6df23fa81fc4 -- [Windmill - Developer platform for APIs, background jobs, workflows and UIs](#windmill---developer-platform-for-apis-background-jobs-workflows-and-uis) +- [Windmill - Code-first platform for workflows, apps and AI agents](#windmill---code-first-platform-for-workflows-apps-and-ai-agents) + - [Build with AI, ship with review](#build-with-ai-ship-with-review) - [Main Concepts](#main-concepts) - [Show me some actual script code](#show-me-some-actual-script-code) - [Local Development](#local-development) @@ -66,6 +67,18 @@ https://github.com/user-attachments/assets/d80de1d9-64de-4d89-aacd-6df23fa81fc4 - [Contributors](#contributors) - [Copyright](#copyright) +## Build with AI, ship with review + +Business teams and engineers build on the same Windmill instance. What the AI builds is an ordinary script, flow or app, and goes through the same review as code written by engineers: + +- [AI sessions](https://www.windmill.dev/docs/core_concepts/ai_sessions) build scripts, flows and apps with AI in a workspace fork, with a live preview and a diff to review before deploying. +- [Workspace roles](https://www.windmill.dev/docs/core_concepts/roles_and_permissions#workspace-roles) decide what each team can author, and [folders](https://www.windmill.dev/docs/core_concepts/groups_and_folders) scope the resources, skills and MCP servers its AI can reach. +- [Protection rulesets](https://www.windmill.dev/docs/core_concepts/protection_rulesets) block direct deployment, so changes reach production only after an engineer reviews and deploys them. +- [Dev workspaces](https://www.windmill.dev/docs/advanced/dev_workspaces) keep their own credentials, and promote to prod through Compare & Deploy or a Git pull request. +- [Worker groups](https://www.windmill.dev/docs/core_concepts/worker_groups) run AI-built code on its own workers, or on a [separate instance](https://www.windmill.dev/docs/core_concepts/staging_prod#deploy-to-a-workspace-on-another-instance). + +See [let business teams build with AI safely](https://www.windmill.dev/docs/advanced/ai_guardrails) for the full setup. Engineers keep writing code locally with the [CLI](https://www.windmill.dev/docs/advanced/cli), the [VS Code extension](https://www.windmill.dev/docs/cli_local_dev/vscode-extension) and their coding agent, synced with [Git](https://www.windmill.dev/docs/advanced/git_sync). + ## Main Concepts 1. Define a minimal and generic script in Python, TypeScript, Go or Bash that solves a specific task. The code can be defined in the provided Web IDE or synchronized with your own GitHub repo (e.g. through VS Code extension): [provided Web IDE](https://www.windmill.dev/docs/code_editor) or [synchronized with your own GitHub repo](https://www.windmill.dev/docs/advanced/cli/sync) (e.g. through [VS Code](https://www.windmill.dev/docs/cli_local_dev/vscode-extension) extension): From b9b1bbd9615fcfca47560e94804fd711311938a3 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sun, 25 Oct 2026 21:15:34 +0100 Subject: [PATCH 093/101] docs(readme): drop the local dev setup and contributors sections (#12007) * docs(readme): drop the local dev setup section, point to README_DEV.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(readme): drop the contributors section Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 54 +----------------------------------------------------- 1 file changed, 1 insertion(+), 53 deletions(-) diff --git a/README.md b/README.md index 754ec2aab2..03a6f56a44 100644 --- a/README.md +++ b/README.md @@ -60,11 +60,7 @@ https://github.com/user-attachments/assets/d80de1d9-64de-4d89-aacd-6df23fa81fc4 - [License](#license) - [Integrations](#integrations) - [Environment Variables](#environment-variables) - - [Run a local dev setup](#run-a-local-dev-setup) - - [Frontend only](#frontend-only) - - [Backend + Frontend](#backend--frontend) - [Contributing](#contributing) - - [Contributors](#contributors) - [Copyright](#copyright) ## Build with AI, ship with review @@ -301,61 +297,13 @@ On self-hosted instances, you might want to import all the approved resource typ | RUN_UPDATE_CA_CERTIFICATE_PATH | /usr/sbin/update-ca-certificates | Path to the CA certificate update command/script to run when RUN_UPDATE_CA_CERTIFICATE_AT_START is true | All | | GOOGLE_APPLICATION_CREDENTIALS | None | (ee only) Credentials file for GCP Pub/Sub triggers that authenticate as the instance rather than through a `gcloud` resource (workspace admins only). Application default credentials also resolve the gcloud well-known file and the GCE metadata server. Workload Identity Federation files work with the `file`, `url` and `aws` credential sources; the `executable` source is not supported. | Server | -## Run a local dev setup - -We recommend using [Nix](./frontend/README_DEV.md#nix). See [./frontend/README_DEV.md](./frontend/README_DEV.md) for all options. - -### Frontend only - -Uses the backend of <https://app.windmill.dev> with local frontend (hot-reload): - -```bash -cd frontend -npm install -npm run generate-backend-client # or generate-backend-client-mac on Mac -npm run dev -``` - -Windmill available at `http://localhost/` - -### Backend + Frontend - -See the [./frontend/README_DEV.md](./frontend/README_DEV.md) file for all -running options. - -1. Start a local Postgres database using for instance the `start-dev-db.sh` script which will make a database available at `postgres://postgres:changeme@localhost:5432/windmill` - Then run the migrations using the following command: - ``` - cargo install sqlx-cli - env DATABASE_URL=<YOUR_DATABASE_URL> sqlx migrate run - ``` - This will also avoid compile time issue with sqlx's `query!` macro. -2. (optional, linux only) Install [nsjail](https://github.com/google/nsjail) and have it accessible in - your PATH -3. Install bun and python3 (+ any languages you want to use), have the bins at `/usr/bin/bun` and - `/usr/local/bin/python3` or set the corresponding environment variables. -4. (optional) Install the [lld linker](https://lld.llvm.org/) -5. Go to `frontend/`: - 1. `npm install`, `npm run generate-backend-client` then `REMOTE=http://localhost:8000 npm run dev` - 2. You might need to set some extra heap space for the node runtime - `export NODE_OPTIONS="--max-old-space-size=4096"` - 3. Create an empty `frontend/build` folder using `mkdir frontend/build` -6. Go to `backend/`: - 1. `env DATABASE_URL=<YOUR_DATABASE_URL> RUST_LOG=info cargo run` - 2. You can specify any feature flag you want to enable, for example `cargo run --features python` to enable the python executor. -7. Windmill should be available at `http://localhost:3000` - ## Contributing At this time, we are not seeking outside contribution. Bug reports and feature requests remain very welcome, and small, trivially-verified PRs that fix a problem are still accepted. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full policy. -## Contributors - -<a href="https://github.com/windmill-labs/windmill/graphs/contributors"> - <img src="https://contrib.rocks/image?repo=windmill-labs/windmill" /> -</a> +To run Windmill from source, see [frontend/README_DEV.md](./frontend/README_DEV.md). ## Copyright From 98299b919ebfe61abf29d5de69ab72a5242c4821 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel <ruben@windmill.dev> Date: Sun, 25 Oct 2026 21:20:31 +0100 Subject: [PATCH 094/101] docs(readme): replace the architecture diagram with an accurate one, with light and dark variants (#12008) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 9 +- imgs/architecture-dark.svg | 94 +++++ imgs/architecture-light.svg | 94 +++++ imgs/architecture.svg | 4 - imgs/diagram.svg | 780 ------------------------------------ 5 files changed, 193 insertions(+), 788 deletions(-) create mode 100644 imgs/architecture-dark.svg create mode 100644 imgs/architecture-light.svg delete mode 100644 imgs/architecture.svg delete mode 100644 imgs/diagram.svg diff --git a/README.md b/README.md index 03a6f56a44..c55e823abd 100644 --- a/README.md +++ b/README.md @@ -194,11 +194,12 @@ back to the database is ~50ms. A typical lightweight deno job will take around ## Architecture -<p align="center"> +Stateless API servers and workers share a PostgreSQL database that holds the job queue and all workspace state (remote agent workers go through the API servers instead). Workers pull jobs by tag, so each worker group can run in its own network, for example dev workers that only reach dev systems and prod workers that only run reviewed code. -<img src="./imgs/diagram.svg"> - -</p> +<picture> + <source media="(prefers-color-scheme: dark)" srcset="./imgs/architecture-dark.svg"> + <img alt="Windmill architecture: business teams and engineers build through stateless API servers into workspaces, where changes move from dev and forks to prod after review. PostgreSQL holds the job queue and state. Worker groups for dev and prod, native workers and remote agent workers pull jobs by tag and reach your databases, APIs and AI model providers." src="./imgs/architecture-light.svg"> +</picture> ## How to self-host diff --git a/imgs/architecture-dark.svg b/imgs/architecture-dark.svg new file mode 100644 index 0000000000..d69d89bfa0 --- /dev/null +++ b/imgs/architecture-dark.svg @@ -0,0 +1,94 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="700" viewBox="0 0 1200 700" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif"> +<title>Windmill architecture + + + +BUILD AND TRIGGER + +Business teams +Build with AI in AI sessions, +in the Windmill UI, in a fork +or a dev workspace + +Engineers +Code in 20+ languages, +CLI, VS Code, coding agents, +Git sync and CI + +Triggers and callers +HTTP routes and webhooks +Schedules +Kafka, NATS, SQS, MQTT +Postgres CDC, email, WebSocket +Apps and auto-generated UIs +Your services, via the REST API +MCP clients + +WINDMILL CONTROL PLANE + +API servers and web UI +Stateless, scale horizontally: +editor, AI sessions, apps, REST API + +Workspaces + +dev / forks +AI-built and new +changes land here + +prod +Locked: deploys +only after review + + +Review and promotion +Protection rulesets, Compare & Deploy, +Git pull requests, CI tests, audit logs + +PostgreSQL +Job queue, workspaces, scripts, flows, +apps, resources, encrypted secrets, +run history and audit logs + +Object storage (optional) +S3, Azure Blob or GCS: large logs, +dependency cache, pipeline data + +EXECUTION ON YOUR INFRA + +Worker group: dev +Runs jobs from dev and forks, +in a network that only reaches +dev systems + +Worker group: prod +Runs reviewed code only, +next to production systems + +Native workers +SQL, REST and GraphQL jobs + +Agent workers +Remote, connect over HTTP, +no direct database access + +Your systems +Databases and warehouses +Internal APIs and SaaS +AI model providers you +configure, local models included + + + + + + +pull jobs from the queue, by tag + +HTTP + + + + + + \ No newline at end of file diff --git a/imgs/architecture-light.svg b/imgs/architecture-light.svg new file mode 100644 index 0000000000..fb7a74df58 --- /dev/null +++ b/imgs/architecture-light.svg @@ -0,0 +1,94 @@ + +Windmill architecture + + + +BUILD AND TRIGGER + +Business teams +Build with AI in AI sessions, +in the Windmill UI, in a fork +or a dev workspace + +Engineers +Code in 20+ languages, +CLI, VS Code, coding agents, +Git sync and CI + +Triggers and callers +HTTP routes and webhooks +Schedules +Kafka, NATS, SQS, MQTT +Postgres CDC, email, WebSocket +Apps and auto-generated UIs +Your services, via the REST API +MCP clients + +WINDMILL CONTROL PLANE + +API servers and web UI +Stateless, scale horizontally: +editor, AI sessions, apps, REST API + +Workspaces + +dev / forks +AI-built and new +changes land here + +prod +Locked: deploys +only after review + + +Review and promotion +Protection rulesets, Compare & Deploy, +Git pull requests, CI tests, audit logs + +PostgreSQL +Job queue, workspaces, scripts, flows, +apps, resources, encrypted secrets, +run history and audit logs + +Object storage (optional) +S3, Azure Blob or GCS: large logs, +dependency cache, pipeline data + +EXECUTION ON YOUR INFRA + +Worker group: dev +Runs jobs from dev and forks, +in a network that only reaches +dev systems + +Worker group: prod +Runs reviewed code only, +next to production systems + +Native workers +SQL, REST and GraphQL jobs + +Agent workers +Remote, connect over HTTP, +no direct database access + +Your systems +Databases and warehouses +Internal APIs and SaaS +AI model providers you +configure, local models included + + + + + + +pull jobs from the queue, by tag + +HTTP + + + + + + \ No newline at end of file diff --git a/imgs/architecture.svg b/imgs/architecture.svg deleted file mode 100644 index 570f4ebc54..0000000000 --- a/imgs/architecture.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - -
    worker
    (Rust)
    worker...
    worker
    (Rust)
    worker...
    worker
    (Rust)
    worker...
    frontend
    (SPA svelte)
    frontend...
    DB (Postgres)
    DB (Postgr...
    Database shardable by workspace_id
    Database shardable by...
    server
    server
    HTTPS
    HTTPS
    server
    server
    API server
    (stateless Rust)
    API server...
    HTTPS
    HTTPS
    Cloud / on-prem
    Cloud / on-prem
    Co-located with API servers or remote
    Co-located with API servers or remote
    Browser
    Browser


    nsjail

    nsjail
    Python/TS
    script exec
    Python/TS...
    your DB
    your DB
    your API
    your API
    Internet
    Internet
    Horizontally scalable
    Horizontally scalable
    Horizontally scalable
    Horizontally scalable
    If workers co-located with your internal DB/Services
    If workers co-l...
    Text is not SVG - cannot display
    \ No newline at end of file diff --git a/imgs/diagram.svg b/imgs/diagram.svg deleted file mode 100644 index a7f50abfd3..0000000000 --- a/imgs/diagram.svg +++ /dev/null @@ -1,780 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 83ea0ef06849b16d2eb92b5775338a9dfd9ae403 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sun, 25 Oct 2026 21:33:25 +0100 Subject: [PATCH 095/101] docs(readme): modernize code examples, in-browser AI building, trim env vars and license (#12009) * docs(readme): modernize the code examples, cover in-browser AI building, trim the env var table Co-Authored-By: Claude Opus 5.5 * docs(license): move the re-expose and internal-use terms from the README into LICENSE, summarize them in the README Co-Authored-By: Claude Opus 5.5 * docs(readme): use a data table in the script example, add a data section (data tables, DuckDB, DuckLake, pipelines) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- LICENSE | 13 ++++ README.md | 173 ++++++++++++++++++++++++++++-------------------------- 2 files changed, 104 insertions(+), 82 deletions(-) diff --git a/LICENSE b/LICENSE index aea6c58c6f..7e682e7dd1 100644 --- a/LICENSE +++ b/LICENSE @@ -30,5 +30,18 @@ quotas set in the software and a right to distribute the community edition as is but not to sell, resell, serve as a managed service, modify or wrap under any form without an explicit agreement. +To re-expose directly any Windmill parts to your users (see +https://www.windmill.dev/docs/misc/white_labelling) as a feature of your +product, with the exception of iframed public Windmill "apps", or to build a +feature on top of "Windmill Community Edition" that you sell commercially or +embed in a distributable product or binary, you must get a commercial license. +Contact us at sales@windmill.dev if you have any questions. To do the same from +the binary compiled from the source code in this repository without the +"enterprise" feature flag, you must comply with the AGPLv3 license terms and +conditions or get a commercial license from Windmill Labs, Inc. + +To use Windmill "Community Edition" as is internally in your organization, or to +use its APIs as is, you do NOT need a commercial license. + All third party components incorporated into the Windmill Software are licensed under the original license provided by the owner of the applicable component. diff --git a/README.md b/README.md index c55e823abd..df877e2c0f 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,9 @@ https://github.com/user-attachments/assets/d80de1d9-64de-4d89-aacd-6df23fa81fc4 - [Windmill - Code-first platform for workflows, apps and AI agents](#windmill---code-first-platform-for-workflows-apps-and-ai-agents) - [Build with AI, ship with review](#build-with-ai-ship-with-review) - [Main Concepts](#main-concepts) - - [Show me some actual script code](#show-me-some-actual-script-code) - - [Local Development](#local-development) + - [What the code looks like](#what-the-code-looks-like) + - [Data: data tables, DuckDB and DuckLake](#data-data-tables-duckdb-and-ducklake) + - [Develop locally or in the browser](#develop-locally-or-in-the-browser) - [Stack](#stack) - [Fastest Self-Hostable Workflow Engine](#fastest-self-hostable-workflow-engine) - [Security](#security) @@ -99,54 +100,93 @@ Scripts and flows can be triggered by [schedules](https://www.windmill.dev/docs/ Build your entire infra on top of Windmill! -## Show me some actual script code +## What the code looks like + +A script is a plain function. Its typed arguments become a generated form, an HTTP endpoint and a CLI command: ```typescript -//import any dependency from npm import * as wmill from "windmill-client"; -import * as cowsay from "cowsay@1.5.0"; - -// fill the type, or use the +Resource type to get a type-safe reference to a resource -type Postgresql = { - host: string; - port: number; - user: string; - dbname: string; - sslmode: string; - password: string; -}; +import dayjs from "dayjs"; // any npm package, resolved and pinned automatically export async function main( - a: number, - b: "my" | "enum", - c: Postgresql, - d = "inferred type string from default arg", - e = { nested: "object" } - //f: wmill.Base64 + customerId: string, + plan: "starter" | "pro", // a union of strings becomes a dropdown + trialDays = 14 // defaults infer the type ) { - const email = process.env["WM_EMAIL"]; - // variables are permissioned and by path - let variable = await wmill.getVariable("f/company-folder/my_secret"); - const lastTimeRun = await wmill.getState(); - // logs are printed and always inspectable - console.log(cowsay.say({ text: "hello " + email + " " + lastTimeRun })); - await wmill.setState(Date.now()); + const trialEnd = dayjs().add(trialDays, "day").toISOString(); - // return is serialized as JSON - return { foo: d, variable }; + // a data table: the workspace's Postgres, queried without a connection string + const sql = wmill.datatable(); + await sql`INSERT INTO trials (customer_id, plan, trial_end) VALUES (${customerId}, ${plan}, ${trialEnd})`.fetch(); + + // secrets are permissioned by path + const slackToken = await wmill.getVariable("f/sales/slack_token"); + await fetch("https://slack.com/api/chat.postMessage", { + method: "POST", + headers: { Authorization: `Bearer ${slackToken}`, "Content-Type": "application/json" }, + body: JSON.stringify({ channel: "#sales", text: `New ${plan} trial: ${customerId}` }), + }); + + console.log(`Trial started for ${customerId}`); // logs stream live in the UI + return { customerId, plan, trialEnd }; // returned as JSON } ``` -## Local Development +Workflows are code too. Each task runs as its own job with its own logs, and waiting for an approval releases the worker: -Windmill supports multiple ways to develop locally and sync with your instance: +```typescript +import { task, waitForApproval, workflow } from "windmill-client"; + +async function plan(env: string) { + return { env, changes: 3 }; +} + +async function apply(plan: { env: string; changes: number }) { + return `applied ${plan.changes} changes to ${plan.env}`; +} + +export const main = workflow(async (env: string) => { + const changes = await task(plan)(env); + const approval = await waitForApproval({ timeout: 3600 }); + if (!approval.approved) { + return `rejected by ${approval.approver}`; + } + return await task(apply)(changes); +}); +``` + +Flows can also be built in the visual [flow editor](https://www.windmill.dev/docs/flows/flow_editor) or as YAML, with scripts like the first one as steps. See [workflows as code](https://www.windmill.dev/docs/core_concepts/workflows_as_code). + +## Data: data tables, DuckDB and DuckLake + +- [Data tables](https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables) give each workspace managed Postgres tables, queried with type-checked SQL from TypeScript, Python and DuckDB scripts without exposing a connection string. +- [DuckDB](https://www.windmill.dev/docs/integrations/duckdb) scripts query S3 and Azure Blob files (CSV, Parquet, JSON), data tables, Postgres, MySQL and BigQuery in SQL, on your workers. +- [DuckLake](https://www.windmill.dev/docs/core_concepts/persistent_storage/ducklake) stores large datasets as lakehouse tables in your workspace object storage, queried in plain SQL. +- [Pipelines](https://www.windmill.dev/docs/core_concepts/pipelines) (alpha) wire scripts by the data they read and write instead of a hand-drawn DAG. This script runs whenever `events` is materialized, and materializes its own table: + +```sql +-- pipeline +-- on ducklake://main/events +-- materialize ducklake://main/events_by_kind +ATTACH 'ducklake://main' AS dl; +SELECT kind, count(*) AS n +FROM dl.events +GROUP BY kind; +``` + +Existing [dbt projects](https://www.windmill.dev/docs/getting_started/scripts_quickstart/dbt) run unmodified as scripts. See the [pipelines quickstart](https://www.windmill.dev/docs/getting_started/pipeline_quickstart). + +## Develop locally or in the browser + +Engineers work from their editor and coding agent, business teams build with AI in the browser, and both land in the same workspace: | Tool | Description | |------|-------------| -| **[CLI](https://www.windmill.dev/docs/advanced/cli)** | Sync scripts from local files or GitHub, run scripts/flows from the command line | -| **[VS Code Extension](https://www.windmill.dev/docs/cli_local_dev/vscode-extension)** | Edit and test scripts & flows directly from VS Code / Cursor with full IDE support | -| **[Git Sync](https://www.windmill.dev/docs/advanced/git_sync)** | Two-way sync between Windmill and your Git repository | -| **[Claude Code](https://www.windmill.dev/docs/core_concepts/ai_generation)** | AI-assisted development with Claude for scripts, flows, and apps | +| **[CLI](https://www.windmill.dev/docs/advanced/cli)** | Sync a workspace with local files and Git, run scripts and flows from the command line. `wmill init` generates `AGENTS.md` and [skill files](https://www.windmill.dev/docs/misc/guides/local_dev_with_ai) for Claude Code, Cursor and other AI tools | +| **[VS Code extension](https://www.windmill.dev/docs/cli_local_dev/vscode-extension)** | Edit and test scripts and flows from VS Code or Cursor with full IDE support | +| **[Git sync](https://www.windmill.dev/docs/advanced/git_sync)** | Two-way sync between a workspace and your Git repository | +| **[MCP server](https://www.windmill.dev/docs/core_concepts/mcp)** | Let coding agents and AI clients run scripts, manage resources and monitor jobs in a workspace | +| **[AI sessions](https://www.windmill.dev/docs/core_concepts/ai_sessions)** | The same agent loop in the browser, with nothing to install: plan mode, skills and MCP servers, a live preview, and a diff to review before deploying, in a fork of the workspace | https://github.com/user-attachments/assets/c541c326-e9ae-4602-a09a-1989aaded1e9 @@ -240,15 +280,11 @@ Configure OAuth and SSO (Google Workspace, Microsoft/Azure, Okta) directly from ### License -The Community Edition is free to use internally. For commercial redistribution or managed services, contact . See [LICENSE](./LICENSE) and [Pricing](https://www.windmill.dev/pricing) for details. +- Using the Community Edition as is, internally or through its APIs, is free and needs no commercial license, within the limits and quotas set in the software. +- Selling, reselling or serving the Community Edition as a managed service, modifying or wrapping it, or re-exposing it to your users as a feature of your product (iframed public apps excepted) requires a commercial license: contact . +- The binary built from this repository without the `enterprise` feature flag is open source under [AGPLv3](./LICENSE-AGPL): the same uses are then allowed under the AGPLv3 terms, or with a commercial license. The API clients and the OpenAPI spec are [Apache 2.0](./LICENSE-APACHE). -The "Community Edition" of Windmill available in the docker images hosted under ghcr.io/windmill-labs/windmill and the github binary releases contains the files under the AGPLv3 and Apache 2 sources but also includes proprietary and non-public code and features which are not open source and under the following terms: Windmill Labs, Inc. grants a right to use all the features of the "Community Edition" for free without restrictions other than the limits and quotas set in the software and a right to distribute the community edition as is but not to sell, resell, serve Windmill as a managed service, modify or wrap under any form without an explicit agreement. - -The binary compilable from source code in this repository without the "enterprise" feature flag is open-source under the [LICENSE-AGPLv3](https://github.com/windmill-labs/windmill/blob/main/LICENSE-AGPL) License terms and conditions. - -To [re-expose directly any Windmill parts to your users](https://www.windmill.dev/docs/misc/white_labelling) as a feature of your product, with the exception of iframed public Windmill "apps", or to build a feature on top of "Windmill Community Edition" that you sell commercially or embed in a distributable product or binary, you must get a commercial license. Contact us at if you have any questions. To do the same from the binary compiled from the source code in this repository without the "enterprise" feature flag, you must comply with the AGPLv3 license terms and conditions or get a commercial license from Windmill Labs, Inc. - -To use Windmill "Community Edition" as is internally in your organization, or to use its APIs as is, you do NOT need a commercial license. +See [LICENSE](./LICENSE) for the full terms and [Pricing](https://www.windmill.dev/pricing) for plans. ### Integrations @@ -259,44 +295,17 @@ On self-hosted instances, you might want to import all the approved resource typ ## Environment Variables -| Environment Variable name | Default | Description | Api Server/Worker/All | -| ----------------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| DATABASE_URL | | The Postgres database url. | All | -| WORKER_GROUP | default | The worker group the worker belongs to and get its configuration pulled from | Worker | -| MODE | standalone | The mode if the binary. Possible values: standalone, worker, server, agent | All | -| METRICS_ADDR | None | (ee only) The socket addr at which to expose Prometheus metrics at the /metrics path. Set to "true" to expose it on port 8001 | All | -| JSON_FMT | false | Output the logs in json format instead of logfmt | All | -| BASE_URL | http://localhost:8000 | The base url that is exposed publicly to access your instance. Is overriden by the instance settings if any. | Server | -| ZOMBIE_JOB_TIMEOUT | 30 | The timeout after which a job is considered to be zombie if the worker did not send pings about processing the job (every server check for zombie jobs every 30s) | Server | -| RESTART_ZOMBIE_JOBS | true | If true then a zombie job is restarted (in-place with the same uuid and some logs), if false the zombie job is failed | Server | -| NATIVE_MODE | false | Enable native mode: sets NUM_WORKERS=8, rejects non-native jobs (nativets, postgresql, mysql, etc.) | Worker | -| SLEEP_QUEUE | 50 | The number of ms to sleep in between the last check for new jobs in the DB. It is multiplied by NUM_WORKERS such that in average, for one worker instance, there is one pull every SLEEP_QUEUE ms. | Worker | -| KEEP_JOB_DIR | false | Keep the job directory after the job is done. Useful for debugging. | Worker | -| EXIT_AFTER_N_JOBS | None | Exit the worker process after it has executed that many jobs, so that a supervisor restarts it and no process runs more than that many, bar the steps of a same-worker flow it has started, which it always finishes (set it to 1 for a process per job; jobs handed to a dedicated worker, and the worker's own init and periodic scripts, do not count). Not counting the init and periodic scripts means they run again on every restart: an init script's runtime is added to the latency of every batch of that many jobs, and a periodic script fires once per process start whatever its interval says. The worker's shell in the workers page also starts backed off rather than after the two minutes it otherwise takes, since a process due to be recycled cannot count on living that long: the first command of a session can wait up to 15s, later ones are immediate. For deployments that isolate executions by process lifetime rather than with nsjail; note that a container restart resets the process, not the container filesystem, so caches and `/tmp` survive it. The worker name is then derived from the hostname instead of being random, so the restarted worker keeps its row in the workers list (an agent worker keeps the row but restarts its job count). Use one worker per process: workers of one process share its environment, so the first to reach the limit shuts the others down too. | Worker | -| WORKER_SUFFIX | None | Pins the last part of the worker name, which is otherwise random, so that a restarted worker keeps its row in the workers list. Only needed when several worker processes of the same worker group run on one host, since the name is derived from the hostname: give each of them a distinct value, as two processes sharing one must never happen. At most 64 letters, digits and underscores; anything else is refused at startup. | Worker | -| LICENSE_KEY (EE only) | None | License key checked at startup for the Enterprise Edition of Windmill | Worker | -| SLACK_SIGNING_SECRET | None | The signing secret of your Slack app. See [Slack documentation](https://api.slack.com/authentication/verifying-requests-from-slack) | Server | -| COOKIE_DOMAIN | None | The domain of the cookie. If not set, the cookie will be set by the browser based on the full origin | Server | -| DENO_PATH | /usr/bin/deno | The path to the deno binary. | Worker | -| PYTHON_PATH | | The path to the python binary if wanting to not have it managed by uv. | Worker | -| GO_PATH | /usr/bin/go | The path to the go binary. | Worker | -| GOPRIVATE | | The GOPRIVATE env variable to use private go modules | Worker | -| GOPROXY | | The GOPROXY env variable to use | Worker | -| NETRC | | The netrc content to use a private go registry | Worker | -| PY_CONCURRENT_DOWNLOADS | 20 | Sets the maximum number of in-flight concurrent python downloads that windmill will perform at any given time. | Worker | -| PATH | None | The path environment variable, usually inherited | Worker | -| HOME | None | The home directory to use for Go and Bash , usually inherited | Worker | -| DATABASE_CONNECTIONS | 50 (Server)/3 (Worker) | The max number of connections in the database connection pool | All | -| SUPERADMIN_SECRET | None | A token that would let the caller act as a virtual superadmin superadmin@windmill.dev | Server | -| TIMEOUT_WAIT_RESULT | 20 | The number of seconds to wait before timeout on the 'run_wait_result' endpoint | Worker | -| QUEUE_LIMIT_WAIT_RESULT | None | The number of max jobs in the queue before rejecting immediately the request in 'run_wait_result' endpoint. Takes precedence on the query arg. If none is specified, there are no limit. | Worker | -| DENO_AUTH_TOKENS | None | Custom DENO_AUTH_TOKENS to pass to worker to allow the use of private modules | Worker | -| DISABLE_RESPONSE_LOGS | false | Disable response logs | Server | -| CREATE_WORKSPACE_REQUIRE_SUPERADMIN | true | If true, only superadmins can create new workspaces | Server | -| MIN_FREE_DISK_SPACE_MB | 15000 | Minimum amount of free space on worker. Sends critical alert if worker has less free space. | Worker | -| RUN_UPDATE_CA_CERTIFICATE_AT_START | false | If true, runs CA certificate update command at startup before other initialization | All | -| RUN_UPDATE_CA_CERTIFICATE_PATH | /usr/sbin/update-ca-certificates | Path to the CA certificate update command/script to run when RUN_UPDATE_CA_CERTIFICATE_AT_START is true | All | -| GOOGLE_APPLICATION_CREDENTIALS | None | (ee only) Credentials file for GCP Pub/Sub triggers that authenticate as the instance rather than through a `gcloud` resource (workspace admins only). Application default credentials also resolve the gcloud well-known file and the GCE metadata server. Workload Identity Federation files work with the `file`, `url` and `aws` credential sources; the `executable` source is not supported. | Server | +The variables most deployments set: + +| Environment Variable name | Default | Description | Api Server/Worker/All | +| ------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------- | +| DATABASE_URL | | The Postgres database url. | All | +| MODE | standalone | The mode of the binary: standalone, server, worker, agent (EE), indexer (EE image, full-text search), mcp | All | +| WORKER_GROUP | default | The worker group the worker belongs to and gets its configuration pulled from | Worker | +| BASE_URL | http://localhost:8000 | The base url that is exposed publicly to access your instance. Is overriden by the instance settings if any. | Server | +| LICENSE_KEY (EE only) | None | License key checked at startup for the Enterprise Edition of Windmill | Worker | + +All other variables (database pool, queue, runtimes, private registries, certificates, zombie jobs and more) are documented in the [environment variables reference](https://www.windmill.dev/docs/core_concepts/environment_variables). ## Contributing From 35be14ea27e70025b46d33fb072ad3767211eb17 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Mon, 26 Oct 2026 13:44:01 +0100 Subject: [PATCH 096/101] fix: stop starred items showing a starred removal in the editor diff (#12017) * fix: stop starred items showing a starred removal in the editor diff Co-Authored-By: Claude Opus 5.5 (1M context) * fix: ignore starred in every value diff Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- frontend/src/lib/components/FlowBuilder.svelte | 3 +-- frontend/src/lib/components/ScriptBuilder.svelte | 3 +-- .../src/lib/components/apps/editor/AppEditorHeader.svelte | 3 +-- .../src/lib/components/raw_apps/RawAppEditorHeader.svelte | 3 +-- frontend/src/lib/utils.test.ts | 3 ++- frontend/src/lib/utils.ts | 6 ++++-- 6 files changed, 10 insertions(+), 11 deletions(-) diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index 86fa1d5864..a3d70a157c 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -514,8 +514,7 @@ // the draft's `draft_path` so the topbar shows the pending name, which after // someone renames the item still names the old location. Comparing against // that fetches the row left behind there instead of the live one. - path: userDraftPath || initialPath, - withStarredInfo: true + path: userDraftPath || initialPath }) // A superseded opening must not write these: the current one would then render // and offer Take latest against the older head. diff --git a/frontend/src/lib/components/ScriptBuilder.svelte b/frontend/src/lib/components/ScriptBuilder.svelte index 3ee365be89..7c6db7b242 100644 --- a/frontend/src/lib/components/ScriptBuilder.svelte +++ b/frontend/src/lib/components/ScriptBuilder.svelte @@ -693,8 +693,7 @@ // the user has typed, so after someone renames the item it still names // the old location and this would compare against the archived row left // there. Resolving by the row is what lets the diff show the rename. - path: userDraftPath || initialPath, - withStarredInfo: true + path: userDraftPath || initialPath }) // A superseded opening must not write these: the current one would then render diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte index f6f89b864f..b6e0134eff 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte @@ -380,8 +380,7 @@ async function syncWithDeployed(opening?: number) { const deployedApp = await AppService.getAppByPath({ workspace: $workspaceStore!, - path: $appPath!, - withStarredInfo: true + path: $appPath! }) // A superseded opening must not write these: the current one would then render diff --git a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte index fbc391ac78..a03d5512ca 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte @@ -479,8 +479,7 @@ async function syncWithDeployed(opening?: number) { const deployedApp = await AppService.getAppByPath({ workspace: opWorkspace!, - path: appPath!, - withStarredInfo: true + path: appPath! }) // A superseded opening must not write these: the current one would then render diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts index 07216d341f..65cef7085c 100644 --- a/frontend/src/lib/utils.test.ts +++ b/frontend/src/lib/utils.test.ts @@ -367,7 +367,8 @@ describe('cleanValueProperties', () => { 'edited_by', 'workspace_id', 'parent_hashes', - 'lock_error_logs' + 'lock_error_logs', + 'starred' ] it('strips every server-managed bookkeeping key', () => { diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index cbc6b84503..f3dfb01746 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -1422,7 +1422,8 @@ function replaceFalseWithUndefinedRec(obj: any) { // `hash` is the deployed version's identity, `assets` is re-derived from the // script content by the editor, and `inherited_labels` is computed at read time // from the parent folder — none is editable content, so all three are noise in a -// fork/workspace or version diff. +// fork/workspace or version diff. `starred` is the viewer's own favorite flag, and a +// starred item's `starred: true` survives `replaceFalseWithUndefined`. // // `lock` and `extra_perms` are deliberately NOT in this set: both are legitimate, // user-meaningful fields in some diff contexts (lockfile changes in version-to-version @@ -1447,7 +1448,8 @@ const CLEANED_VALUE_KEYS = new Set([ 'edited_by', 'workspace_id', 'parent_hashes', - 'lock_error_logs' + 'lock_error_logs', + 'starred' ]) export function cleanValueProperties(obj: Value) { From 6e4094009901f0702dc8b102390466d120361156 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Mon, 26 Oct 2026 13:45:03 +0100 Subject: [PATCH 097/101] feat: add a home setting to hide empty folders (#12011) * feat: add a home setting to hide empty folders Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep empty folders listed in a workspace holding nothing else Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep a folder created from home listed while empty folders are hidden Co-Authored-By: Claude Opus 5.5 (1M context) * fix: say which kinds keep a folder listed when hiding empty folders Co-Authored-By: Claude Opus 5.5 (1M context) * fix: hide the empty-folders toggle where it has no effect, honour it beside pipelines Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep empty folders listed when the item count request fails Co-Authored-By: Claude Opus 5.5 (1M context) * fix: keep the tree when only non-empty folders remain past the loaded window Co-Authored-By: Claude Opus 5.5 (1M context) * refactor: hide empty folders inside the tree only, keep main's empty-state choice Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- .../src/lib/components/home/ItemsList.svelte | 66 +++++++++++++------ .../lib/components/home/TreeViewRoot.svelte | 10 ++- 2 files changed, 55 insertions(+), 21 deletions(-) diff --git a/frontend/src/lib/components/home/ItemsList.svelte b/frontend/src/lib/components/home/ItemsList.svelte index 9832215405..36099ac1b9 100644 --- a/frontend/src/lib/components/home/ItemsList.svelte +++ b/frontend/src/lib/components/home/ItemsList.svelte @@ -820,6 +820,41 @@ storeLocalSetting(FLAT_LIST_SETTING_NAME, v ? 'true' : undefined) } + // Unfiltered, the tree lists every folder, empty ones too, so a workspace holding only + // folders is not empty: its first folder is created from here and managed from its row. + // A role without the Folders page gets no folder menu, so empty rows would be noise. + let keepEmptyFolders = $derived(itemKind === 'all' && $roleCapabilities.visibility.folders) + // Only drops rows inside the tree. Whether the tree shows at all, rather than the "no items" + // or empty-workspace state, must not depend on it: either state can take down the settings + // menu, or replace owners whose items sit past the loaded window. + const HIDE_EMPTY_FOLDERS_SETTING_NAME = 'homeHideEmptyFolders' + let hideEmptyFolders = $state(getLocalSetting(HIDE_EMPTY_FOLDERS_SETTING_NAME) == 'true') + function setHideEmptyFolders(v: boolean) { + hideEmptyFolders = v + storeLocalSetting(HIDE_EMPTY_FOLDERS_SETTING_NAME, v ? 'true' : undefined) + } + // A folder created here starts empty; hiding it would read as a failed create. It stays + // listed until the page reloads. + let createdFolders = $state<{ workspace: string; name: string }[]>([]) + let keptFolders = $derived( + createdFolders.filter((f) => f.workspace === $workspaceStore).map((f) => f.name) + ) + + // Reload from the server whenever an input the endpoint resolves changes: order, + // archived/library scope, kind, the selected owner/folder, or entering/leaving + // search (see the reload effect below). Only the label filter and fuzzy ranking + // stay client-side over the loaded pages, so they don't reload here. + let searching = $derived(filter !== '') + // Lazy owner tree is active only in the tree when browsing all (no owner selected, no + // search, no label filter): every folder AND user shows as a top-level node and paginates + // on expand, its items coming from the separate `treeOwnerItems` store. In the flat list, + // or with a selected owner / active search / label filter, the lazy store is unused + // (reloadItems must not touch it), so this is false and the view reads the global loaded + // window instead. + let treeLazyMode = $derived( + !flatList && !searching && ownerFilter == undefined && labelFilter == undefined + ) + let listSettingsItems: MenuItem[] = $derived([ { displayName: 'Flat list', @@ -827,6 +862,15 @@ toggle: flatList, action: () => setFlatList(!flatList) }, + { + displayName: 'Hide empty folders', + description: + 'Folders with no scripts, flows, apps, agents or data pipelines. They may still hold resources, variables or schedules.', + toggle: hideEmptyFolders, + // Only the unfiltered tree lists folders it holds no rows of. + hide: !treeLazyMode || archived || !keepEmptyFolders, + action: () => setHideEmptyFolders(!hideEmptyFolders) + }, { displayName: 'Show library scripts', description: 'Scripts without a main function', @@ -1037,24 +1081,6 @@ }) ) }) - // Reload from the server whenever an input the endpoint resolves changes: order, - // archived/library scope, kind, the selected owner/folder, or entering/leaving - // search (see the reload effect below). Only the label filter and fuzzy ranking - // stay client-side over the loaded pages, so they don't reload here. - let searching = $derived(filter !== '') - // Lazy owner tree is active only in the tree when browsing all (no owner selected, no - // search, no label filter): every folder AND user shows as a top-level node and paginates - // on expand, its items coming from the separate `treeOwnerItems` store. In the flat list, - // or with a selected owner / active search / label filter, the lazy store is unused - // (reloadItems must not touch it), so this is false and the view reads the global loaded - // window instead. - let treeLazyMode = $derived( - !flatList && !searching && ownerFilter == undefined && labelFilter == undefined - ) - // Unfiltered, the tree lists every folder, empty ones too, so a workspace holding only - // folders is not empty: its first folder is created from here and managed from its row. - // A role without the Folders page gets no folder menu, so empty rows would be noise. - let keepEmptyFolders = $derived(itemKind === 'all' && $roleCapabilities.visibility.folders) let treeShowsFolders = $derived( treeLazyMode && !archived && keepEmptyFolders && (folderNamesRes.current?.length ?? 0) > 0 ) @@ -1895,6 +1921,7 @@ // the server only resends on the next whoami. The creator is the folder's owner. $userStore?.folders.push(name) $userStore?.folders_owners.push(name) + if ($workspaceStore) createdFolders.push({ workspace: $workspaceStore, name }) await folderNamesRes.refetch() } await reloadItemsAndCounts() @@ -2209,7 +2236,8 @@ onManageFolder={$roleCapabilities.visibility.folders ? (name) => folderEditorDrawer?.initEdit(name) : undefined} - {keepEmptyFolders} + keepEmptyFolders={keepEmptyFolders && !hideEmptyFolders} + {keptFolders} /> {/key} {/if} diff --git a/frontend/src/lib/components/home/TreeViewRoot.svelte b/frontend/src/lib/components/home/TreeViewRoot.svelte index d5023176b5..935157d152 100644 --- a/frontend/src/lib/components/home/TreeViewRoot.svelte +++ b/frontend/src/lib/components/home/TreeViewRoot.svelte @@ -58,6 +58,8 @@ // Inject folders `ownerCounts` calls empty, as "0 items". Off under a kind filter, // where those counts are per kind and every folder lacking that kind would show. keepEmptyFolders?: boolean + // Folders injected even when empty and `keepEmptyFolders` is off. + keptFolders?: string[] } let { @@ -83,7 +85,8 @@ leaf, openMemory, onManageFolder, - keepEmptyFolders = false + keepEmptyFolders = false, + keptFolders }: Props = $props() const unruled = inUnruledList() @@ -110,6 +113,8 @@ allUsers ownerCounts selfUsername + keepEmptyFolders + keptFolders untrack(() => { // While searching, `items` is already relevance-ranked and the sort // selector is disabled, so keep that order: a no-op leaf comparator @@ -136,7 +141,7 @@ ) // Once counts are in, a user space holding nothing the user can see is dropped // rather than injected — the member list is mostly noise in the tree otherwise. - // Empty folders are dropped too unless `keepEmptyFolders`. Pipeline folders are + // Empty folders are dropped too unless `keepEmptyFolders` or `keptFolders`. Pipeline folders are // exempt: their entry is the pipeline, whose scripts the count folds out. const isEmptyOwner = (prefix: string) => ownerCounts != undefined && !ownerCounts[prefix] const missingFolders: { folderName: string; items: [] }[] = [] @@ -145,6 +150,7 @@ if ( !keepEmptyFolders && !pipelineFolders?.has(folderName) && + !keptFolders?.includes(folderName) && isEmptyOwner(`f/${folderName}`) ) continue From 2b4dfccb36493365de4e358f4f8c0fb7d7009c4a Mon Sep 17 00:00:00 2001 From: hugocasa Date: Mon, 26 Oct 2026 13:45:31 +0100 Subject: [PATCH 098/101] fix: add job_id, step_id and flow_path to native ts step errors (#12012) * fix: add job_id, step_id and flow_path to every executor's step error Co-Authored-By: Claude Opus 5.5 * fix: take the step error's flow_path from the pulled job, not a query Co-Authored-By: Claude Opus 5.5 * fix: add step context to native ts errors in the executor instead of process_result Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- backend/windmill-worker/src/bun_executor.rs | 12 +++++----- backend/windmill-worker/src/js_eval.rs | 25 +++++++++++++++++++++ backend/windmill-worker/src/worker.rs | 3 ++- 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/backend/windmill-worker/src/bun_executor.rs b/backend/windmill-worker/src/bun_executor.rs index e64a725b7c..f2d683bcbf 100644 --- a/backend/windmill-worker/src/bun_executor.rs +++ b/backend/windmill-worker/src/bun_executor.rs @@ -3170,7 +3170,8 @@ try {{ None, has_stream, ) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; let preprocessed: HashMap> = serde_json::from_str(pre_result.get()).map_err(|e| { @@ -3202,7 +3203,8 @@ try {{ stream_notifier, has_stream, ) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; tracing::info!( "Executed native code (with preprocessor) in {}ms", started_at.elapsed().as_millis() @@ -3230,7 +3232,8 @@ try {{ stream_notifier, has_stream, ) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; tracing::info!( "Executed native code in {}ms", started_at.elapsed().as_millis() @@ -4190,8 +4193,7 @@ pub async fn handle_wac_v2_output( let resume_id: u32 = windmill_common::wac::approval_resume_id(&key); // Read before the tx: it holds the queue row lock, and a pool checkout under it // waits on the connections every other suspending parent is holding. - let wkey = - windmill_common::variables::get_workspace_key(&job.workspace_id, db).await?; + let wkey = windmill_common::variables::get_workspace_key(&job.workspace_id, db).await?; let approval_token = windmill_common::variables::approval_token_from_key(&wkey, job.id)?; diff --git a/backend/windmill-worker/src/js_eval.rs b/backend/windmill-worker/src/js_eval.rs index bc8b33a5f2..2e78f0aae8 100644 --- a/backend/windmill-worker/src/js_eval.rs +++ b/backend/windmill-worker/src/js_eval.rs @@ -107,6 +107,31 @@ pub async fn eval_timeout( } } +/// Adds `step_id`, `job_id` and `flow_path` to a native script's thrown error, as the +/// subprocess wrappers do from the same env vars. +pub fn with_step_context( + e: windmill_common::error::Error, + reserved_variables: &HashMap, +) -> windmill_common::error::Error { + use windmill_common::error::Error; + let Error::ExecutionRawError(raw) = &e else { + return e; + }; + let Ok(serde_json::Value::Object(mut err)) = serde_json::from_str(raw.get()) else { + return e; + }; + for (key, var) in [ + ("step_id", "WM_FLOW_STEP_ID"), + ("job_id", "WM_JOB_ID"), + ("flow_path", "WM_FLOW_PATH"), + ] { + if let Some(v) = reserved_variables.get(var).filter(|v| !v.is_empty()) { + err.insert(key.to_string(), serde_json::Value::String(v.clone())); + } + } + Error::ExecutionRawError(windmill_common::worker::to_raw_value(&err)) +} + #[cfg(feature = "deno_core")] pub fn transpile_ts(expr: String) -> anyhow::Result { windmill_runtime_nativets::transpile_ts(expr) diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index a4749f3ee5..beeac41a5c 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -6695,7 +6695,8 @@ pub async fn run_language_executor( occupancy_metrics, has_stream, )) - .await?; + .await + .map_err(|e| crate::js_eval::with_step_context(e, &reserved_variables))?; return Ok(result); } From 6939454edb55a8df39b4fc5460f77333554f48a5 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Mon, 26 Oct 2026 16:27:44 +0100 Subject: [PATCH 099/101] feat: name the previewed item in an empty AI session's composer (#12021) * feat: name the previewed item in an empty session's composer instead of greeting * feat: name the item's kind in the empty session's composer placeholder * fix: name the previewed item as its tab does, so view tabs get the summary --- .../components/sessions/SessionWrapper.svelte | 61 +++++++++++++++---- .../(root)/(logged)/sessions/+page.svelte | 11 +++- 2 files changed, 56 insertions(+), 16 deletions(-) diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index e51445deeb..fc128584ba 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -79,17 +79,23 @@ import { goto } from '$lib/navigation' import { splitterPointerCapture } from '$lib/utils/splitterPointerCapture' import { StarterPrompts } from '$lib/components/copilot/chat/starter/starterPrompts.svelte' + import { resolvePreviewTab } from './previewRouter' + import { whereIs } from './sessionPreviewTabs.svelte' + import type { SessionPreviewTab } from './sessionState.svelte' let { sessionId, headerInPage = false, - covered = false + covered = false, + previewTabName }: { sessionId: string /** True for the session the page is showing: its header rides the page header bar. */ headerInPage?: boolean /** True while the page holds this wrapper inert under an overlay, where nothing takes focus. */ covered?: boolean + /** The name the preview's tab strip shows for a tab, without its side marker. */ + previewTabName: (tab: SessionPreviewTab) => string } = $props() // Parent keys by sessionId; this wrapper only mounts when the session exists. @@ -117,8 +123,25 @@ // Whether the first message goes out in Use. Not `permissions.readOnly`: before that send a // staged fork's session reads the workspace it forks, while the message builds in the fork. const heldInUse = $derived(!!workModeLock.current || runtime?.manager.workMode === AIWorkMode.USE) + // The item an unsent session opened on ("Open in AI session", or a tab opened before the + // first send): the chat reads the displayed tab with each message, so the empty chat asks + // about that item instead of greeting. What is on screen only: a collapsed panel hides it. + // Named as its tab is, so a deployed item in View mode gets its summary from the listing. + const previewedItem = $derived.by(() => { + if (!opensSession) return undefined + const tab = runtime?.previewTabs.displayedTab + if (!tab) return undefined + const slot = resolvePreviewTab(whereIs(tab)) + if (slot.kind !== 'editor' && slot.kind !== 'viewer') return undefined + const kind = slot.kind === 'editor' ? slot.editorKind : slot.viewerKind + return { + kind: kind === 'raw_app' ? 'app' : kind, + name: previewTabName(tab) + } + }) + const greets = $derived(opensSession && !previewedItem) const starterPrompts = new StarterPrompts( - () => (opensSession ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined), + () => (greets ? (actingWorkspaceId ?? $workspaceStore ?? undefined) : undefined), () => !heldInUse ) @@ -402,6 +425,13 @@ // utilities on one element resolve by stylesheet order, not attribute order. const bannerClass = 'flex flex-row items-center justify-between gap-2 py-2 px-3 text-xs border rounded-md' + + const previewedItemPlaceholder = $derived( + previewedItem && + (heldInUse + ? `Ask about the ${previewedItem.kind} ${previewedItem.name}, or run it…` + : `Ask about the ${previewedItem.kind} ${previewedItem.name}, or describe a change…`) + ) {#if !session || !runtime} @@ -409,7 +439,12 @@ {:else} - {#snippet sessionEmptyHint()}{/snippet} + {#snippet sessionEmptyHint()} + {#if previewedItem} + +
    + {/if} + {/snippet} {#snippet inputPreface()} {#if showRecoveryNotice} @@ -583,14 +618,14 @@ onDraftChange={(text) => setSessionDraftPrompt(sessionId, text)} initialAttachments={armedAtInit ? undefined : getSessionDraftAttachments(sessionId)} onAttachmentsChange={(a) => setSessionDraftAttachments(sessionId, a)} - placeholder={composerPlaceholder} + placeholder={previewedItemPlaceholder ?? composerPlaceholder} forceDisabled={isUnavailable || !!session.archived} forceDisabledMessage={isUnavailable ? 'This session is linked to a workspace that no longer exists. Move it or discard it from the banner above to keep working.' : session.archived ? 'This session is archived. Unarchive it from the banner above to keep working.' : ''} - starter={opensSession + starter={greets ? { where: 'session', suggestions: starterPrompts.suggestions } : undefined} viewTransitionNames={headerInPage && (opensSession || arrivingFromHomeSend())} @@ -604,37 +639,37 @@ its transcript area, its column, and its footer row's height; for a session that has never sent, the greeting above the centred composer. -->
    () => runtime.manager.setComposerHasDraft(PLACEHOLDER_DRAFT_KEY, false)} > - {#if opensSession} + {#if greets}
    - {:else if runtime.manager.displayMessages.length > 0} + {:else if previewedItem || runtime.manager.displayMessages.length > 0}
    {/if}
    {@render inputPreface()} draftText, setPlaceholderText} - toolbar={opensSession ? placeholderToolbar : undefined} - placeholder={opensSession + toolbar={greets ? placeholderToolbar : undefined} + placeholder={greets ? heldInUse ? USE_STARTER_PLACEHOLDER : STARTER_PLACEHOLDER : runtime.manager.displayMessages.length > 0 ? 'Ask followup' - : composerPlaceholder} + : (previewedItemPlaceholder ?? composerPlaceholder)} disabled={isUnavailable || !!session.archived} autofocus={sessionState.currentSessionId === sessionId && !covered} onSelectionChange={(selection) => (handoff = selection ?? null)} onCompositionChange={(composing) => (placeholderComposing = composing)} /> - {#if !opensSession} + {#if !greets}
    {:else if !isUnavailable && !session.archived && starterPrompts.suggestions.length > 0}
    @@ -646,7 +681,7 @@
    {/if}
    - {#if opensSession} + {#if greets}
    {/if}
    diff --git a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte index ee1b95c765..19e7b60462 100644 --- a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte @@ -852,13 +852,16 @@ // cell reactively, so the editor mirrors the name onto the tab model). Before // that, the workspace listing names it. Falls back to the plain location label // for summary-less items and non-item pages. - function tabLabelFor(tab: SessionPreviewTab, workspace: string): string { + function tabNameFor(tab: SessionPreviewTab, workspace: string): string { const listed = listedItemFor(tab, workspace) - const name = + return ( tab.friendlyLabel ?? (listed && itemDisplayName(listed.path, listed.draftPath, listed.summary)) ?? previewLocationLabel(tab.loc) - return name + sideSuffix(tab.url) + ) + } + function tabLabelFor(tab: SessionPreviewTab, workspace: string): string { + return tabNameFor(tab, workspace) + sideSuffix(tab.url) } // Hover title for a tab. A summary label is free text the strip truncates, and @@ -1118,6 +1121,8 @@ sessionId={s.id} headerInPage={s.id === activeSession?.id} covered={aiHiddenVerdict !== false} + previewTabName={(tab) => + tabNameFor(tab, getEffectiveWorkspaceId(s) ?? $workspaceStore ?? '')} />
    {/each} From cd4e55de7d1760ceaeafe0306b1d1555385f34fb Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Mon, 26 Oct 2026 18:06:25 +0100 Subject: [PATCH 100/101] force a fresh apt-get upgrade in docker images via APT_REFRESH (#12026) Co-authored-by: Claude Opus 5.5 --- Dockerfile | 8 ++++++-- docker/DockerfileSlim | 5 ++++- docker/DockerfileSlimEe | 5 ++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 93862fe0b9..7d53a5a58a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -169,8 +169,12 @@ ENV UV_TOOL_DIR=/usr/local/uv ENV PATH /usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH - -RUN apt-get update \ +# The build cache keeps the apt layer while the base image digest and this line are unchanged, so +# Debian security updates are not picked up by later builds. Bump to force a fresh apt-get upgrade; +# bump it in docker/DockerfileSlim and docker/DockerfileSlimEe too. +ARG APT_REFRESH=1 +RUN echo "apt refresh ${APT_REFRESH}" \ + && apt-get update \ && apt-get upgrade -y \ && apt-get install -y --no-install-recommends netbase tzdata ca-certificates wget curl jq unzip build-essential unixodbc xmlsec1 tini gnupg libargon2-1 \ && if echo "$features" | grep -q "ee"; then apt-get install -y --no-install-recommends libsasl2-modules-gssapi-mit krb5-user; fi \ diff --git a/docker/DockerfileSlim b/docker/DockerfileSlim index 0a1e5a0c42..daeb64b637 100644 --- a/docker/DockerfileSlim +++ b/docker/DockerfileSlim @@ -44,7 +44,10 @@ ENV UV_TOOL_DIR=/usr/local/uv ENV PATH=/usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH # Install system dependencies -RUN apt-get update \ +# Bump to force a fresh apt-get upgrade past the build cache; keep in step with ../Dockerfile. +ARG APT_REFRESH=1 +RUN echo "apt refresh ${APT_REFRESH}" \ + && apt-get update \ && apt-get upgrade -y \ && apt-get install -y --no-install-recommends ca-certificates wget curl git jq unzip unixodbc xmlsec1 gnupg lsb-release libgnutls30t64 libgcrypt20 \ && apt-get clean \ diff --git a/docker/DockerfileSlimEe b/docker/DockerfileSlimEe index 46d0d2d98f..3edff33038 100644 --- a/docker/DockerfileSlimEe +++ b/docker/DockerfileSlimEe @@ -44,7 +44,10 @@ ENV UV_TOOL_DIR=/usr/local/uv ENV PATH=/usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH # Install system dependencies -RUN apt-get update \ +# Bump to force a fresh apt-get upgrade past the build cache; keep in step with ../Dockerfile. +ARG APT_REFRESH=1 +RUN echo "apt refresh ${APT_REFRESH}" \ + && apt-get update \ && apt-get upgrade -y \ && apt-get install -y --no-install-recommends ca-certificates wget curl git jq unzip unixodbc xmlsec1 gnupg lsb-release libgnutls30t64 libgcrypt20 \ && apt-get clean \ From ee4150a69cca745ce3a909cefa5b9c1627a5f992 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Mon, 26 Oct 2026 18:25:47 +0100 Subject: [PATCH 101/101] fix: serve new MCP OAuth sign-ins the session toolset on the tools server URLs (#12024) * fix: serve new MCP OAuth sign-ins the session toolset on /api/mcp/gateway Co-Authored-By: Claude Opus 5.5 * fix: keep the mcp:session marker across every token scope edit Co-Authored-By: Claude Opus 5.5 * fix: serve marked MCP sign-ins the session toolset on the per-workspace URL too Co-Authored-By: Claude Opus 5.5 * fix: let a restricted caller re-save a token's mcp:session marker Co-Authored-By: Claude Opus 5.5 * fix: preselect build and run when an MCP client requests every scope Co-Authored-By: Claude Opus 5.5 * fix: advertise only granting MCP scopes in protected resource metadata Co-Authored-By: Claude Opus 5.5 * fix: apply the blanket-request default on the consent page only Co-Authored-By: Claude Opus 5.5 * fix: treat only an mcp:all request with both narrowings as blanket Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 2 +- backend/windmill-api-auth/src/lib.rs | 9 ++- backend/windmill-api/src/mcp/core.rs | 72 ++++++++++++++++--- backend/windmill-api/src/mcp/oauth_server.rs | 37 ++++++---- backend/windmill-mcp/src/common/mod.rs | 2 +- backend/windmill-mcp/src/common/scope.rs | 9 +++ .../lib/components/mcp/McpAccessPicker.svelte | 8 ++- .../settings/EditTokenScopesModal.svelte | 9 ++- .../components/settings/TokensTable.svelte | 9 ++- .../oauth/mcp_authorize/+page@(root).svelte | 9 ++- 10 files changed, 133 insertions(+), 33 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 835c8a4edb..ef87f1c4dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,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 `` / `` 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/mcp/session/`), 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. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/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 twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/mcp/session/`), 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). What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/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 twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). - **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. diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 82a40377a0..6a09710b5e 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -591,7 +591,9 @@ pub fn ensure_scopes_within_caller( for requested in requested_restrictions { if requested.starts_with("mcp:") { - if !caller_mcp.contains(requested.as_str()) { + // `mcp:session` (windmill_mcp's SESSION_SCOPE) grants nothing: it only picks + // the toolset an `mcp:all` token gets, and `mcp:all` is matched here itself. + if requested != "mcp:session" && !caller_mcp.contains(requested.as_str()) { return Err(Error::PermissionDenied(format!( "A scope-restricted token cannot grant MCP scope '{requested}' unless the \ caller holds the same scope verbatim" @@ -1964,6 +1966,11 @@ mod tests { opt_scopes(Some(vec!["mcp:scripts:*"])).as_deref() ) .is_err()); + assert!(ensure_scopes_within_caller( + &mcp_all, + opt_scopes(Some(vec!["mcp:all", "mcp:session"])).as_deref() + ) + .is_ok()); } #[test] diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index d31234b585..52a6a32014 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -35,6 +35,7 @@ use std::sync::Arc; use std::time::Duration; use tokio_util::sync::CancellationToken; +use windmill_mcp::common::SESSION_SCOPE; use windmill_mcp::server::{ LocalSessionManager, McpToken, MultiWorkspaceMcp, NoEndpointTools, Runner, SessionRunner, StreamableHttpServerConfig, StreamableHttpService, @@ -503,6 +504,17 @@ fn scoped_to_selection(scopes: &[String]) -> bool { mcp.clone().next().is_some() && !mcp.any(|scope| scope == "mcp:all") } +/// Whether the tools server's URLs (`/api/mcp/gateway`, `/api/mcp/w/{workspace}/mcp`) serve +/// a token the session's toolset: an `mcp:all` grant marked `mcp:session`, or narrowed by +/// `mcp:read_only` / `mcp:read_run`, which the consent page describes as session access. +/// Every other token there keeps the tools server it was issued for. +fn serves_session_toolset(scopes: &[String]) -> bool { + scopes.iter().any(|scope| scope == "mcp:all") + && scopes + .iter() + .any(|scope| [SESSION_SCOPE, "mcp:read_only", "mcp:read_run"].contains(&scope.as_str())) +} + /// The path of a workspace-less MCP URL, when it is not the tools server's /// `/api/mcp/gateway`: each URL is its own OAuth protected resource. #[derive(Clone, Copy)] @@ -519,6 +531,16 @@ pub async fn extract_and_store_workspace_id( next.run(request).await } +/// RFC 9728 challenge pointing at the endpoint's protected resource metadata. `scope` is what +/// a client requests: without it, Claude requests every scope the metadata lists, read-only +/// included, and the consent page would then default to read-only access. +fn www_authenticate_value(base_url: &str, endpoint: &str) -> String { + format!( + "Bearer resource_metadata=\"{base_url}/.well-known/oauth-protected-resource{endpoint}\", \ + scope=\"mcp:all\"" + ) +} + /// Middleware that adds WWW-Authenticate header to 401 responses /// This helps MCP clients discover the OAuth authorization server (RFC 9728) pub async fn add_www_authenticate_header( @@ -545,11 +567,8 @@ pub async fn add_www_authenticate_header( if response.status() == StatusCode::UNAUTHORIZED { let base_url = BASE_URL.load(); - // RFC 9728: The resource parameter contains the protected resource URL. - // Clients derive the metadata URL by inserting /.well-known/oauth-protected-resource - // after the host, e.g., http://host/.well-known/oauth-protected-resource/api/mcp/w/test/mcp - let resource_url = format!("{}/api/mcp/w/{}/mcp", base_url, workspace_id); - let www_authenticate = format!("Bearer resource=\"{}\"", resource_url); + let www_authenticate = + www_authenticate_value(&base_url, &format!("/api/mcp/w/{}/mcp", workspace_id)); // Reconstruct response with the new header let (mut parts, body) = response.into_parts(); @@ -678,8 +697,7 @@ pub async fn add_www_authenticate_header_gateway( if response.status() == StatusCode::UNAUTHORIZED { let base_url = BASE_URL.load(); - let resource_url = format!("{}{}", base_url, endpoint); - let www_authenticate = format!("Bearer resource=\"{}\"", resource_url); + let www_authenticate = www_authenticate_value(&base_url, endpoint); let (mut parts, body) = response.into_parts(); parts.headers.insert( @@ -735,7 +753,30 @@ pub async fn setup_mcp_server( let service = StreamableHttpService::new(move || Ok(runner.clone()), session_manager, service_config); - let router = Router::new().route_service("/", service.clone()); + let router = Router::new().route( + "/", + axum::routing::any({ + let (service, session_service) = (service.clone(), session_service.clone()); + move |request: Request| { + let (service, session_service) = (service.clone(), session_service.clone()); + async move { + use tower::ServiceExt; + let session = request.extensions().get::().is_some_and(|a| { + serves_session_toolset(a.scopes.as_deref().unwrap_or_default()) + }); + let response = if session { + session_service.oneshot(request).await + } else { + service.oneshot(request).await + }; + match response { + Ok(response) => response.into_response(), + Err(never) => match never {}, + } + } + } + }), + ); // `/api/mcp` serves both servers: a token scoped to a selection of scripts, flows and // endpoints gets the tools server, any other the session's toolset. At `/mcp` itself, // beside the `/mcp/...` routes, so it is merged rather than nested. @@ -810,7 +851,7 @@ pub fn toolset_service() -> Router { #[cfg(test)] mod tests { - use super::scoped_to_selection; + use super::{scoped_to_selection, serves_session_toolset}; #[test] fn only_a_token_without_mcp_all_is_a_selection() { @@ -829,4 +870,17 @@ mod tests { assert!(!selection(&[])); assert!(!selection(&["variables:read"])); } + + #[test] + fn tools_server_urls_keep_unmarked_tokens() { + let session = |scopes: &[&str]| { + serves_session_toolset(&scopes.iter().map(|s| s.to_string()).collect::>()) + }; + assert!(session(&["mcp:all", "mcp:session"])); + assert!(session(&["mcp:all", "mcp:read_only"])); + assert!(session(&["mcp:all", "mcp:read_run", "mcp:workspaces:a,b"])); + assert!(!session(&["mcp:all"])); + assert!(!session(&["mcp:favorites", "mcp:session"])); + assert!(!session(&["mcp:all:f/x/*", "mcp:read_only"])); + } } diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index de07647305..677875da96 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -19,7 +19,7 @@ use windmill_common::{ use crate::db::ApiAuthed; use windmill_api_auth::forbid_elevated_job_token; -use windmill_mcp::parse_mcp_scopes; +use windmill_mcp::{common::SESSION_SCOPE, parse_mcp_scopes}; /// Token expiration for MCP OAuth tokens (1 week in seconds) const MCP_OAUTH_TOKEN_EXPIRATION_SECS: u64 = 7 * 24 * 60 * 60; @@ -225,17 +225,25 @@ struct RefreshTokenRow { revoked: bool, } -fn supported_scopes() -> Vec { - vec![ - "mcp:all".to_string(), - "mcp:favorites".to_string(), - "mcp:scripts:*".to_string(), - "mcp:flows:*".to_string(), - "mcp:endpoints:*".to_string(), - "mcp:read_only".to_string(), - "mcp:read_run".to_string(), - "mcp:runnables_as_tools".to_string(), +/// The scopes that grant access. A protected resource advertises only these: MCP clients +/// that request every listed scope must not pick up a narrowing, which would make the +/// consent page start from a narrower access than they meant to ask for. +fn granting_scopes() -> Vec { + [ + "mcp:all", + "mcp:favorites", + "mcp:scripts:*", + "mcp:flows:*", + "mcp:endpoints:*", ] + .map(String::from) + .to_vec() +} + +fn supported_scopes() -> Vec { + let mut scopes = granting_scopes(); + scopes.extend(["mcp:read_only", "mcp:read_run", "mcp:runnables_as_tools"].map(String::from)); + scopes } /// GET /.well-known/oauth-authorization-server/api/w/:workspace_id/mcp/oauth/server @@ -263,7 +271,7 @@ fn build_protected_resource_metadata( ProtectedResourceMetadata { resource: format!("{}{}", base_url, resource_path), authorization_servers: vec![format!("{}{}", base_url, oauth_prefix)], - scopes_supported: Some(supported_scopes()), + scopes_supported: Some(granting_scopes()), bearer_methods_supported: Some(vec!["header".to_string()]), } } @@ -873,11 +881,14 @@ async fn oauth_approve_inner( let code = format!("mcp-code-{}", rd_string(32)); - let scopes: Vec = form + let mut scopes: Vec = form .scope .split_whitespace() .map(|s| s.to_string()) .collect(); + if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) { + scopes.push(SESSION_SCOPE.to_string()); + } // The approver's own token bounds what it may grant: a scope-restricted MCP // token must not approve a broader one (e.g. mcp:scripts:f/x -> mcp:all). An diff --git a/backend/windmill-mcp/src/common/mod.rs b/backend/windmill-mcp/src/common/mod.rs index 2632a28962..6707943482 100644 --- a/backend/windmill-mcp/src/common/mod.rs +++ b/backend/windmill-mcp/src/common/mod.rs @@ -9,7 +9,7 @@ pub mod transform; pub mod types; pub use schema::convert_schema_to_schema_type; -pub use scope::{is_resource_allowed, parse_mcp_scopes, McpScopeConfig}; +pub use scope::{is_resource_allowed, parse_mcp_scopes, McpScopeConfig, SESSION_SCOPE}; pub use transform::{ apply_key_transformation, extract_hub_version_id_from_hashed, extract_path_prefix_from_hashed, parse_tool_prefix, reverse_transform, reverse_transform_key, transform_hub_path, diff --git a/backend/windmill-mcp/src/common/scope.rs b/backend/windmill-mcp/src/common/scope.rs index 42327215ae..642c02a2bc 100644 --- a/backend/windmill-mcp/src/common/scope.rs +++ b/backend/windmill-mcp/src/common/scope.rs @@ -161,6 +161,11 @@ fn pattern_covers(caller: &str, requested: &str) -> bool { /// URL, which an older selection, carrying none of the newer scopes, still does. pub const RUNNABLES_AS_TOOLS_SCOPE: &str = "mcp:runnables_as_tools"; +/// Added server-side to an `mcp:all` OAuth grant so the tools server's URLs serve it the AI +/// session's toolset. Grants nothing: an un-narrowed `mcp:all` token without it predates the +/// session toolset there, and must keep the tools server's endpoint tools. +pub const SESSION_SCOPE: &str = "mcp:session"; + /// Parse MCP scopes from token scope strings pub fn parse_mcp_scopes(scopes: &[String]) -> Result { let mut config = McpScopeConfig::default(); @@ -233,6 +238,10 @@ pub fn parse_mcp_scopes(scopes: &[String]) -> Result { continue; } + if scope == SESSION_SCOPE { + continue; + } + if let Some(ids) = scope.strip_prefix("mcp:workspaces:") { config .workspaces diff --git a/frontend/src/lib/components/mcp/McpAccessPicker.svelte b/frontend/src/lib/components/mcp/McpAccessPicker.svelte index c80ab00ed2..6466bb8761 100644 --- a/frontend/src/lib/components/mcp/McpAccessPicker.svelte +++ b/frontend/src/lib/components/mcp/McpAccessPicker.svelte @@ -4,6 +4,10 @@ /** Marks a selection, so the per-workspace URLs add no API endpoint tools to it. */ export const RUNNABLES_AS_TOOLS = 'mcp:runnables_as_tools' + /** Added by the server to an `mcp:all` sign-in so the tools server's URLs serve it the AI + * session's tools. Grants nothing, so it is never shown. */ + export const MCP_SESSION = 'mcp:session' + const ACCESS_SCOPES: Record, string[]> = { read: ['mcp:all', 'mcp:read_only'], read_run: ['mcp:all', 'mcp:read_run'], @@ -13,7 +17,7 @@ /** The access a token's MCP scopes give: `mcp:all` and how it is narrowed, or else a * selection of scripts, flows and endpoints. */ export function mcpAccessOf(scopes: string[]): McpAccess { - scopes = scopes.filter((s) => s !== RUNNABLES_AS_TOOLS) + scopes = scopes.filter((s) => s !== RUNNABLES_AS_TOOLS && s !== MCP_SESSION) if (!scopes.includes('mcp:all')) return scopes.length > 0 ? 'selected' : 'full' if (scopes.includes('mcp:read_only')) return 'read' if (scopes.includes('mcp:read_run')) return 'read_run' @@ -50,7 +54,7 @@ access = initialAccess const initialSelection = initialAccess === 'selected' - ? initialScopes.filter((s) => s !== RUNNABLES_AS_TOOLS).join(' ') + ? initialScopes.filter((s) => s !== RUNNABLES_AS_TOOLS && s !== MCP_SESSION).join(' ') : undefined let selection = $state(initialSelection ?? 'mcp:favorites') diff --git a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte index 7125093749..46ad5b4720 100644 --- a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte +++ b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte @@ -6,7 +6,7 @@ import Modal from '../common/modal/Modal.svelte' import TextInput from '../text_input/TextInput.svelte' import ScopesPicker from './ScopesPicker.svelte' - import McpAccessPicker, { mcpAccessOf } from '../mcp/McpAccessPicker.svelte' + import McpAccessPicker, { MCP_SESSION, mcpAccessOf } from '../mcp/McpAccessPicker.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -50,10 +50,13 @@ // user has used the picker; until then the token keeps exactly the scopes it had. let mcpTouched = $state(false) // Carried over as is, the picker knowing nothing of them: dropping the workspace list - // would widen the token to every workspace. + // would widen the token to every workspace, dropping `mcp:session` would move a sign-in + // back to the endpoint tools once it is given `mcp:all` again. const isWorkspaceList = (s: string) => s.startsWith('mcp:workspaces:') const keptAside = (s: string) => - isWorkspaceList(s) || (mcpAccessOf(mcpScopes) !== 'selected' && s.startsWith('mcp:hub:')) + isWorkspaceList(s) || + s === MCP_SESSION || + (mcpAccessOf(mcpScopes) !== 'selected' && s.startsWith('mcp:hub:')) const scopesToSave = $derived( isMcp ? mcpTouched diff --git a/frontend/src/lib/components/settings/TokensTable.svelte b/frontend/src/lib/components/settings/TokensTable.svelte index a13c06312b..3cd83e7d89 100644 --- a/frontend/src/lib/components/settings/TokensTable.svelte +++ b/frontend/src/lib/components/settings/TokensTable.svelte @@ -10,6 +10,7 @@ import Badge from '../common/badge/Badge.svelte' import Alert from '../common/alert/Alert.svelte' import { Pen, Trash } from 'lucide-svelte' + import { MCP_SESSION } from '../mcp/McpAccessPicker.svelte' // --- Props --- interface Props { @@ -114,6 +115,10 @@ listTokens() } + function shownScopes(scopes: string[] | null | undefined): string { + return (scopes ?? []).filter((s) => s !== MCP_SESSION).join(', ') + } + function handleEditClick( tokenPrefix: string, tokenLabel: string | undefined, @@ -199,13 +204,13 @@
    {#if read_only} Read-only {/if} - {scopes?.join(', ') ?? ''} + {shownScopes(scopes)}
    diff --git a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte index a917de4d4a..3daaeba05c 100644 --- a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte +++ b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte @@ -20,9 +20,16 @@ let clientName = page.url.searchParams.get('client_name') || 'Unknown Client' let redirectUri = page.url.searchParams.get('redirect_uri') || '' // What the client asked for seeds the access picker; what is approved is the picker's. - const requestedScopes = (page.url.searchParams.get('scope') || 'mcp:all') + const askedScopes = (page.url.searchParams.get('scope') || 'mcp:all') .split(' ') .filter((s) => s.startsWith('mcp:')) + // Both narrowings at once is a client requesting every scope it was offered, not a choice. + const requestedScopes = + askedScopes.includes('mcp:all') && + askedScopes.includes('mcp:read_only') && + askedScopes.includes('mcp:read_run') + ? askedScopes.filter((s) => s !== 'mcp:read_only' && s !== 'mcp:read_run') + : askedScopes let scopes = $state([]) let access = $state() let oauthState = page.url.searchParams.get('state') || ''