Files
windmill/frontend/src/lib/components/RunForm.svelte
T
Ruben FiszelandClaude Opus 4.6 0317d5891c feat: add powershell common parameters support (#8683)
* feat: add powershell common parameters support (-Verbose, -Debug, -ErrorAction, -WhatIf)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add powershell common params to script editor test panel

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: detect CmdletBinding from code instead of schema in script editor

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: ignore commented-out CmdletBinding in powershell detection

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: use preference variables for -Verbose/-Debug instead of CLI args

Verbose/Debug output goes to PowerShell stream 4/5 which isn't captured
by the 2>&1 redirect. Setting $VerbosePreference/$DebugPreference in the
wrapper scope propagates to child scripts and output flows through the
host to stderr, which Windmill captures as logs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: use *>&1 to capture all powershell streams including verbose/debug

The previous 2>&1 only captured error stream. Verbose (stream 4) and
debug (stream 5) output was silently lost. Using *>&1 redirects all
streams to success stream so they flow through Tee-Object into logs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: use targeted stream redirects (4>&1 5>&1 2>&1) instead of *>&1

*>&1 breaks $PSCmdlet.ShouldProcess() by redirecting internal streams.
Only redirect verbose (4), debug (5), and error (2) to success stream.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: revert to 2>&1 redirect — stream 4/5 redirects break powershell

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: use 4>&1 5>&1 for verbose/debug capture, remove WhatIf support

Stream 4/5 redirects capture verbose/debug in the pipeline. WhatIf is
removed because $PSCmdlet.ShouldProcess() doesn't work when scripts
are invoked through Windmill's wrapper.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: redirect verbose/debug to files to keep result pipeline clean

Verbose (4) and debug (5) streams are redirected to separate log files
during script execution, then output via Write-Host after the script
completes. This keeps them out of the Tee-Object pipeline (used for
result extraction) while still showing them in the job logs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: output verbose/debug to stderr via Console.Error for log capture

Write-Host goes to stdout which gets mixed with result output and
truncated by OSS log threshold. Using [Console]::Error.WriteLine()
writes to stderr which Windmill captures separately as logs, with
VERBOSE:/DEBUG: prefixes for clarity.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: redirect script output to file only, send verbose/debug to stdout

The OSS log storage has a 9KB threshold. Previously, Tee-Object sent
the full JSON result to both stdout (logs) and the pipe file, eating
the log budget. Now script output goes only to the pipe file (> $pipe),
and only verbose/debug messages go to stdout for the log viewer.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: preserve original Tee-Object behavior, append verbose/debug after

Keep the original wrapper behavior (Tee-Object to stdout + pipe file).
Only add 4>verbose.log 5>debug.log to capture those streams, and
output them at the end of logs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: inject preference vars into main.ps1 instead of CLI args

Passing -Verbose/-Debug as CLI args causes PowerShell module loading
to emit verbose noise. Instead, inject $VerbosePreference/$DebugPreference
inside main.ps1's try block so they only affect user code. Stream 4/5
are still redirected to files in the wrapper for log output.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: restore common param toggles from previous job args on Run Again

Extract _wm_ps_* keys from loaded args and initialize the toggle
states in PowerShellCommonParams. Also strip them from main args
so they don't appear as unknown schema form inputs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: show active common param badges when section is collapsed

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: inject ErrorAction as preference variable instead of CLI arg

-ErrorAction as a CLI arg only affects the caller, not the script's
internal error handling. Setting $ErrorActionPreference inside main.ps1
correctly overrides the default 'Stop' behavior for the user's code.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: ensure full backward compatibility with existing powershell scripts

- Only filter common param names when [CmdletBinding()] is present
  (without it, $Verbose etc. are regular user-defined parameters)
- Only add 4>verbose.log 5>debug.log and log output lines when common
  params are actually enabled — original wrapper is unchanged otherwise

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: lighter styling for common params section

Replaced heavy Section component with a subtle inline chevron toggle
labeled "Common parameters". Smaller text, secondary color, indented
options. Badges still show when collapsed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: rename section to CmdletBinding parameters

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add ..Default::default() to windmill-parser-r (new parser from main)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: missing comma in graphql parser test + merge main

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add missing commas before ..Default::default() in parser tests

Merge from main brought test constructors with formatting issues
from the original automated script (missing comma between last field
and ..Default::default()).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: restore comment markers in nu parser test that script broke

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review — ignore commented CmdletBinding, clear stale params

1. Parser: strip comment lines before detecting [CmdletBinding()] to
   avoid false positives from commented-out attributes
2. RunForm: always assign psCommonParams (not just when non-empty) so
   stale settings from a previous run don't leak into later runs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 13:03:22 +00:00

409 lines
11 KiB
Svelte

<script lang="ts">
import {
computeSharableHash as computeSharableHash,
defaultIfEmptyString,
emptyString,
truncateHash,
sendUserToast
} from '$lib/utils'
import type { Schema } from '$lib/common'
import { Badge, Button } from './common'
import SchemaForm from './SchemaForm.svelte'
import SharedBadge from './SharedBadge.svelte'
import TimeAgo from './TimeAgo.svelte'
import Popover from './meltComponents/Popover.svelte'
import { Calendar, Check, CornerDownLeft } from 'lucide-svelte'
import RunFormAdvancedPopup from './RunFormAdvancedPopup.svelte'
import { page } from '$app/state'
import { replaceState } from '$app/navigation'
import JsonInputs from '$lib/components/JsonInputs.svelte'
import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte'
import InputSelectedBadge from './schema/InputSelectedBadge.svelte'
import { untrack } from 'svelte'
import { processSecretArgs } from './secretArgUtils'
import PowerShellCommonParams from './PowerShellCommonParams.svelte'
let reloadArgs = $state(0)
let jsonEditor: JsonInputs | undefined = $state(undefined)
let schemaHeight = $state(0)
let showInputSelectedBadge = $state(false)
let savedPreviousArgs: Record<string, any> | undefined = $state(undefined)
let psCommonParams: Record<string, any> = $state({})
function extractPsCommonParams(allArgs: Record<string, any>): {
scriptArgs: Record<string, any>
commonParams: Record<string, any>
} {
const scriptArgs: Record<string, any> = {}
const commonParams: Record<string, any> = {}
for (const [k, v] of Object.entries(allArgs)) {
if (k.startsWith('_wm_ps_')) {
commonParams[k] = v
} else {
scriptArgs[k] = v
}
}
return { scriptArgs, commonParams }
}
export async function setArgs(nargs: Record<string, any>) {
const { scriptArgs, commonParams } = extractPsCommonParams(nargs)
args = scriptArgs
psCommonParams = commonParams
reloadArgs++
}
export async function run(overrideScheduledForStr?: string | undefined | null) {
let processedArgs: Record<string, any>
try {
processedArgs = await processSecretArgs(
enforceDisabledDefaults(args ?? {}, true),
runnable?.schema
)
} catch (e) {
sendUserToast('Failed to process sensitive args: ' + e, true)
return
}
if (showPsCommonParams) {
for (const [k, v] of Object.entries(psCommonParams)) {
if (v !== undefined && v !== false && v !== '') {
processedArgs[k] = v
}
}
}
runAction(
overrideScheduledForStr === null ? undefined : (overrideScheduledForStr ?? scheduledForStr),
processedArgs,
invisible_to_owner,
overrideTag
)
}
interface Props {
runnable:
| {
summary?: string
schema?: Schema | any
description?: string
path?: string
is_template?: boolean
hash?: string
kind?: string
language?: string
can_write?: boolean
created_at?: string
created_by?: string
extra_perms?: Record<string, boolean>
}
| undefined
runAction: (
scheduledForStr: string | undefined,
args: Record<string, any>,
invisible_to_owner: boolean | undefined,
overrideTag: string | undefined
) => void
buttonText?: string
schedulable?: boolean
detailed?: boolean
autofocus?: boolean
loading?: boolean
noVariablePicker?: boolean
viewKeybinding?: boolean
scheduledForStr: string | undefined
invisible_to_owner: boolean | undefined
overrideTag: string | undefined
args?: Record<string, any>
jsonView?: boolean
isValid?: boolean
}
let {
runnable,
runAction,
buttonText = 'Run',
schedulable = true,
detailed = true,
autofocus = false,
loading = false,
noVariablePicker = false,
viewKeybinding = false,
scheduledForStr = $bindable(),
invisible_to_owner = $bindable(),
overrideTag = $bindable(),
args = $bindable(),
jsonView = false,
isValid = $bindable(true)
}: Props = $props()
let showPsCommonParams = $derived(
runnable?.language === 'powershell' && runnable?.schema?.['x-windmill-ps-cmd-binding'] === true
)
$effect.pre(() => {
if (args == undefined) {
args = {}
}
// Extract _wm_ps_* keys from args on initial load (e.g. "Run again" via URL hash)
if (args && Object.keys(args).some((k) => k.startsWith('_wm_ps_'))) {
const { scriptArgs, commonParams } = extractPsCommonParams(args)
args = scriptArgs
psCommonParams = commonParams
}
})
let debounced: number | undefined = undefined
function onArgsChange(args: any) {
try {
debounced && clearTimeout(debounced)
debounced = setTimeout(() => {
const nurl = new URL(window.location.href)
nurl.hash = computeSharableHash(args)
try {
replaceState(nurl.toString(), page.state)
} catch (e) {
console.error(e)
}
}, 200)
} catch (e) {
console.error('Impossible to set hash in args', e)
}
}
function enforceDisabledDefaults(
args: Record<string, any>,
notify: boolean = false
): Record<string, any> {
const schema = runnable?.schema
if (!schema?.properties) return args
const result = { ...args }
const resetKeys: string[] = []
for (const [key, prop] of Object.entries(schema.properties) as [string, any][]) {
if (prop?.disabled && 'default' in prop) {
if (notify && result[key] !== prop.default) {
resetKeys.push(key)
}
result[key] = prop.default
}
}
if (resetKeys.length > 0) {
sendUserToast(
`Disabled field${resetKeys.length > 1 ? 's' : ''} ${resetKeys.map((k) => `'${k}'`).join(', ')} reset to default value${resetKeys.length > 1 ? 's' : ''}`
)
}
return result
}
export function setCode(code: string) {
jsonEditor?.setCode(code)
}
$effect(() => {
Object.keys(args ?? {}).forEach((key) => {
args?.[key]
})
untrack(() => onArgsChange(args))
})
</script>
<!-- Standalone triggerable registration for the run form -->
<div
style="display: none"
use:triggerableByAI={{
id: `run-form-${runnable?.path ?? ''}`,
description: `Form to fill the inputs to run ${runnable?.summary && runnable?.summary.length > 0 ? runnable?.summary : runnable?.path}.
## Script description: ${runnable?.description ?? ''}.
## Schema used: ${JSON.stringify(runnable?.schema)}.
## Current args: ${JSON.stringify(args)}}`,
callback: (value) => {
savedPreviousArgs = args
setArgs(JSON.parse(value ?? '{}'))
showInputSelectedBadge = true
},
showAnimation: false
}}
></div>
{#snippet acceptButton()}
<Button
startIcon={{
icon: Check
}}
size="xs2"
btnClasses="border border-gray-200 dark:border-gray-600 !bg-surface text-primary"
on:click={() => {
showInputSelectedBadge = false
savedPreviousArgs = undefined
}}
>
Accept
</Button>
{/snippet}
{#if showInputSelectedBadge}
<InputSelectedBadge
inputSelected="ai"
labelColor="text-violet-800 dark:text-primary"
className="dark:!bg-violet-800 !bg-violet-200 !border-violet-200 dark:!border-violet-800"
{acceptButton}
onReject={() => {
setArgs(savedPreviousArgs ?? {})
savedPreviousArgs = undefined
showInputSelectedBadge = false
}}
/>
{/if}
<div class="max-w-3xl">
{#if detailed}
{#if runnable}
<div class="flex flex-row flex-wrap justify-between gap-4">
<div>
<div class="flex flex-col mb-2">
<h1 class="break-words py-2 mr-2">
{defaultIfEmptyString(runnable.summary, runnable.path ?? '')}
</h1>
{#if !emptyString(runnable.summary)}
<h2 class="font-bold pb-4">{runnable.path}</h2>
{/if}
<div class="flex items-center gap-2">
<span class="text-sm text-primary">
{#if runnable}
Edited <TimeAgo agoOnlyIfRecent date={runnable.created_at || ''} /> by {runnable.created_by ||
'unknown'}
{/if}
</span>
<Badge color="dark-gray">
{truncateHash(runnable?.hash ?? '')}
</Badge>
{#if runnable?.is_template}
<Badge color="blue">Template</Badge>
{/if}
{#if runnable && runnable.kind !== 'runnable'}
<Badge color="blue">
{runnable?.kind}
</Badge>
{/if}
<SharedBadge
canWrite={runnable.can_write ?? true}
extraPerms={runnable?.extra_perms ?? {}}
/>
</div>
</div>
</div>
</div>
{:else}
<h1
use:triggerableByAI={{
id: 'run-form-loading',
description: 'Run form is loading, should scan the page until this is gone'
}}>Loading...</h1
>
{/if}
{/if}
{#if runnable?.schema}
{#if jsonView}
<div
class="py-2"
style="height: {!schemaHeight || schemaHeight < 600 ? 600 : schemaHeight}px"
data-schema-picker
>
<JsonInputs
bind:this={jsonEditor}
on:select={(e) => {
if (e.detail) {
args = enforceDisabledDefaults(e.detail)
}
}}
updateOnBlur={false}
placeholder={`Write args as JSON.<br/><br/>Example:<br/><br/>{<br/>&nbsp;&nbsp;"foo": "12"<br/>}`}
/>
</div>
{:else if !runnable.schema.properties || Object.keys(runnable.schema.properties).length === 0}
<div class="text-sm italic">{`This ${runnable.kind ?? 'runnable'} takes no arguments`}</div>
{:else}
{#key reloadArgs}
<div bind:clientHeight={schemaHeight}>
<SchemaForm
helperScript={{
source: 'deployed',
path: runnable.path!,
runnable_kind: runnable.hash ? 'script' : 'flow'
}}
prettifyHeader
{noVariablePicker}
{autofocus}
schema={runnable.schema}
bind:isValid
bind:args
/>
</div>
{/key}
{/if}
{:else}
<div class="text-xs text-primary">No arguments</div>
{/if}
{#if showPsCommonParams}
<div class="mt-4">
<PowerShellCommonParams bind:args={psCommonParams} />
</div>
{/if}
{#if schedulable}
<div class="flex gap-2 items-start flex-wrap justify-between mt-2 md:mt-6">
<div class="flex-row-reverse flex-wrap flex w-full gap-4">
<Button
id="run-form-run-button"
{loading}
variant="accent"
unifiedSize="md"
btnClasses="!inline-flex"
disabled={!isValid && !jsonView}
on:click={() => run()}
shortCut={{ Icon: CornerDownLeft, hide: !viewKeybinding }}
>
{scheduledForStr ? 'Schedule to run later' : buttonText}
</Button>
<div>
<Popover placement="bottom" closeButton usePointerDownOutside>
{#snippet trigger()}
<Button nonCaptureEvent startIcon={{ icon: Calendar }} unifiedSize="md" color="light">
Advanced
</Button>
{/snippet}
{#snippet content()}
<RunFormAdvancedPopup
bind:scheduledForStr
bind:invisible_to_owner
bind:overrideTag
{runnable}
/>
{/snippet}
</Popover>
</div>
</div>
{#if overrideTag}
<div class="flex-row-reverse flex w-full text-primary text-sm">
tag override: {overrideTag}
</div>
{/if}
{#if invisible_to_owner}
<div class="flex-row-reverse flex w-full text-primary text-sm">
Job will be invisible to owner
</div>
{/if}
</div>
{:else}
<Button
btnClasses="!px-6 !py-1 w-full"
variant="accent"
disabled={!isValid && !jsonView}
on:click={() => run(null)}
shortCut={{ Icon: CornerDownLeft, hide: !viewKeybinding }}
>
{buttonText}
</Button>
{/if}
</div>