Files
open-webui/src/lib/components/AutomationModal.svelte
T
2026-12-03 00:03:39 +04:00

484 lines
16 KiB
Svelte

<script lang="ts">
import { createEventDispatcher, getContext, tick, onDestroy } from 'svelte';
import { toast } from 'svelte-sonner';
import dayjs from 'dayjs';
import Modal from '$lib/components/common/Modal.svelte';
import XMark from '$lib/components/icons/XMark.svelte';
import Check from '$lib/components/icons/Check.svelte';
import Calendar from '$lib/components/icons/Calendar.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import CodeEditor from '$lib/components/common/CodeEditor.svelte';
import Dropdown from '$lib/components/common/Dropdown.svelte';
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
import Switch from '$lib/components/common/Switch.svelte';
import Textarea from '$lib/components/common/Textarea.svelte';
import CodeBracket from '$lib/components/icons/CodeBracket.svelte';
import Sparkles from '$lib/components/icons/Sparkles.svelte';
import Folder from '$lib/components/icons/Folder.svelte';
import Icon from '$lib/components/chat/FileNav/Icon.svelte';
import Triggers, { type TriggerCard } from '$lib/components/automations/Triggers.svelte';
import ModelDropdown from '$lib/components/automations/ModelDropdown.svelte';
import MachineDropdown from '$lib/components/automations/MachineDropdown.svelte';
import { getMachines, type MachineServer } from '$lib/apis/machines';
import DestinationDropdown from '$lib/components/automations/DestinationDropdown.svelte';
import { getFolders } from '$lib/apis/folders';
import { getChannels } from '$lib/apis/channels';
import { baseModels, channels, config, folders, type AgentModel } from '$lib/stores';
import {
createAutomation,
getAutomationModels,
startsNew,
repliesInThread,
type AutomationForm,
type AutomationResponse
} from '$lib/apis/automations';
const i18n = getContext('i18n');
const dispatch = createEventDispatcher();
export let show = false;
export let cloneFrom: AutomationResponse | null = null;
/** Folder a new automation starts in. */
export let folderId: string | null = null;
let name = '';
let prompt = '';
let code = '';
let action_type: 'prompt' | 'code' = 'prompt';
let showActionTypeMenu = false;
const actionTypes: ('prompt' | 'code')[] = ['prompt', 'code'];
let model_id = '';
let machineServerId = '';
let machineCwd = '';
let machines: MachineServer[] = [];
let agentModels: AgentModel[] = [];
let modelsLoading = false;
let initialized = false;
let modelRequest = 0;
let modelTimer: ReturnType<typeof setTimeout>;
let folder_id = '';
let target_type: 'chat' | 'channel' = 'chat';
let channel_id = '';
let start_new = true;
let reply_in_thread = true;
let is_active = true;
let scheduleRows: TriggerCard[] = [];
// The copied rules as the schedule fields rebuild them, so an untouched schedule keeps its start date.
let savedRrules: string[] = [];
let webhookEnabled = false;
let webhookAllowGet = false;
// A local date and time, as the datetime input holds it; empty means it never expires.
let expiresAt = '';
let savedExpiresAt = '';
let loading = false;
let foldersLoaded = false;
let channelsLoaded = false;
const loadAgentModels = (visible: boolean, machineId: string, cwd: string, target: string) => {
const request = ++modelRequest;
clearTimeout(modelTimer);
agentModels = [];
modelsLoading = visible && !!machineId && target === 'chat';
if (!visible) return;
if (!modelsLoading) {
if (model_id.startsWith('agent:')) model_id = '';
return;
}
modelTimer = setTimeout(async () => {
try {
const available = await getAutomationModels(localStorage.token, machineId, cwd.trim());
if (request !== modelRequest) return;
agentModels = available;
if (model_id.startsWith('agent:') && !available.some((model) => model.id === model_id)) {
model_id = '';
}
} catch (error: any) {
if (request === modelRequest) toast.error(error?.detail ?? String(error));
} finally {
if (request === modelRequest) modelsLoading = false;
}
}, 250);
};
$: loadAgentModels(show && initialized, machineServerId, machineCwd, target_type);
onDestroy(() => {
clearTimeout(modelTimer);
modelRequest++;
});
$: allowWebhook = !!$config?.features?.enable_automation_webhooks;
const submitHandler = async () => {
if (!name.trim() || !(action_type === 'code' ? code : prompt).trim() || !model_id.trim()) {
toast.error($i18n.t('Name, prompt, and model are required'));
return;
}
if (target_type === 'channel' && !channel_id) {
toast.error($i18n.t('Channel is required'));
return;
}
const rrules = scheduleRows.map((row) => row.fields?.buildRrule() ?? '');
if (scheduleRows.some((row, i) => row.frequency === 'CUSTOM' && !rrules[i].trim())) {
toast.error($i18n.t('Invalid value') + ': ' + $i18n.t('Custom schedule'));
return;
}
const storedRrules = (cloneFrom?.data.triggers ?? []).flatMap((trigger) =>
trigger.type === 'schedule' ? [trigger.rrule] : []
);
loading = true;
try {
const form: AutomationForm = {
name: name.trim(),
folder_id: target_type === 'channel' ? null : folder_id || null,
data: {
triggers: [
// An untouched schedule keeps its stored start date.
...rrules.filter(Boolean).map((rrule) => ({
type: 'schedule' as const,
rrule: storedRrules[savedRrules.indexOf(rrule)] ?? rrule
})),
...(webhookEnabled ? [{ type: 'webhook' as const, allow_get: webhookAllowGet }] : [])
],
action: {
// The server works out a code action's tools from the code.
...(action_type === 'code'
? { type: 'code' as const, code, tools: [] }
: { type: 'prompt' as const, prompt: prompt.trim() }),
model_id: model_id.trim(),
machine: machineServerId
? { server_id: machineServerId, cwd: machineCwd.trim() || undefined }
: undefined,
target:
target_type === 'channel'
? { type: 'channel', channel_id, new_thread: start_new, reply_in_thread }
: { type: 'chat', new_chat: start_new }
}
},
is_active,
expires_at: expiresAt
? expiresAt === savedExpiresAt
? cloneFrom?.expires_at
: dayjs(expiresAt).valueOf() * 1_000_000
: null
};
const created = await createAutomation(localStorage.token, form);
toast.success($i18n.t('Automation created'));
show = false;
dispatch('save', { id: created?.id });
} catch (e: any) {
toast.error(e?.detail ?? `${e}` ?? 'Failed to save');
} finally {
loading = false;
}
};
const init = async () => {
initialized = false;
await tick();
machines = await getMachines(localStorage.token);
if (!foldersLoaded && ($folders ?? []).length === 0) {
const res = await getFolders(localStorage.token).catch(() => null);
if (res) folders.set(res);
foldersLoaded = true;
}
if (!channelsLoaded && ($channels ?? []).length === 0) {
const res = await getChannels(localStorage.token).catch(() => null);
if (res) channels.set(res);
channelsLoaded = true;
}
machineServerId = cloneFrom?.data.action.machine?.server_id ?? '';
machineCwd = cloneFrom?.data.action.machine?.cwd ?? '';
if (cloneFrom) {
name = cloneFrom.name;
prompt = cloneFrom.data.action.type === 'prompt' ? cloneFrom.data.action.prompt : '';
code = cloneFrom.data.action.type === 'code' ? cloneFrom.data.action.code : '';
action_type = cloneFrom.data.action.type;
model_id = cloneFrom.data.action.model_id;
folder_id = ($folders ?? []).some((folder) => folder.id === cloneFrom.folder_id)
? (cloneFrom.folder_id ?? '')
: '';
target_type = cloneFrom.data.action.target?.type === 'channel' ? 'channel' : 'chat';
channel_id = ($channels ?? []).some(
(channel) => channel.id === cloneFrom.data.action.target?.channel_id
)
? (cloneFrom.data.action.target?.channel_id ?? '')
: '';
start_new = startsNew(cloneFrom.data.action.target);
reply_in_thread = repliesInThread(cloneFrom.data.action.target);
webhookEnabled = cloneFrom.data.triggers.some((trigger) => trigger.type === 'webhook');
webhookAllowGet = cloneFrom.data.triggers.some(
(trigger) => trigger.type === 'webhook' && !!trigger.allow_get
);
savedExpiresAt = cloneFrom.expires_at
? dayjs(cloneFrom.expires_at / 1_000_000).format('YYYY-MM-DDTHH:mm')
: '';
} else {
name = '';
prompt = '';
code = '';
action_type = 'prompt';
model_id = '';
folder_id = folderId ?? '';
target_type = 'chat';
channel_id = '';
start_new = true;
reply_in_thread = true;
webhookEnabled = false;
webhookAllowGet = false;
savedExpiresAt = '';
}
expiresAt = savedExpiresAt;
is_active = true;
// A new automation starts with one schedule at its defaults.
const rrules = cloneFrom
? cloneFrom.data.triggers.flatMap((trigger) =>
trigger.type === 'schedule' ? [trigger.rrule] : []
)
: [''];
scheduleRows = rrules.map(() => ({}));
await tick();
scheduleRows.forEach((row, i) => rrules[i] && row.fields?.parseRrule(rrules[i]));
savedRrules = cloneFrom
? rrules.map((rrule, i) => scheduleRows[i].fields?.buildRrule?.() ?? rrule)
: [];
initialized = true;
};
$: if (show) {
init();
}
const rowClass =
'flex h-7 items-center gap-2 rounded-lg px-2 transition-colors hover:bg-base-50 dark:hover:bg-base-850/50';
const labelClass =
'flex w-[5.375rem] shrink-0 items-center gap-1.5 text-xs text-base-500 dark:text-base-400';
const valueClass = 'text-xs text-base-700 dark:text-base-300';
</script>
<Modal ariaLabel={name || $i18n.t('Automation')} size="lg" bind:show>
<div class="px-4 pt-3 pb-3.5">
<div class="flex h-7 items-center gap-1">
<input
class="w-full min-w-0 text-sm font-normal bg-transparent outline-hidden"
bind:value={name}
aria-label={$i18n.t('Name')}
placeholder={$i18n.t('Automation name')}
/>
<button
class="flex size-6 shrink-0 items-center justify-center text-base-400 transition-colors hover:text-base-700 dark:text-base-600 dark:hover:text-base-300"
aria-label={$i18n.t('Close')}
type="button"
on:click={() => (show = false)}
>
<XMark className="size-4" />
</button>
</div>
<div class="py-1">
<div class="mt-2 mb-1 text-[0.6875rem] text-base-400 dark:text-base-500">
{$i18n.t('Triggers')}
</div>
<div class="-mx-2">
<Triggers
bind:scheduleRows
bind:webhookEnabled
bind:webhookAllowGet
{allowWebhook}
fallbackStart={cloneFrom
? dayjs(cloneFrom.created_at / 1_000_000).format('YYYY-MM-DD')
: ''}
/>
<div class={rowClass}>
<span class={labelClass}
><Calendar className="size-3 shrink-0" />{$i18n.t('Expires')}</span
>
<div class="flex min-w-0 flex-1 items-center gap-1">
<input
type="datetime-local"
class="min-w-0 flex-1 bg-transparent text-xs text-base-700 outline-hidden dark:text-base-300 dark:[color-scheme:dark]"
aria-label={$i18n.t('Expires')}
bind:value={expiresAt}
/>
{#if expiresAt}
<button
type="button"
class="flex size-4 shrink-0 items-center justify-center rounded-full text-base-400 hover:text-base-700 dark:hover:text-base-200"
aria-label={$i18n.t('Clear')}
on:click={() => (expiresAt = '')}
>
<XMark className="size-3" strokeWidth="2" />
</button>
{/if}
</div>
</div>
</div>
<div class="mt-6 mb-1 text-[0.6875rem] text-base-400 dark:text-base-500">
{$i18n.t('Action')}
</div>
<div class="-mx-2">
<div class={rowClass}>
<span class={labelClass}
><CodeBracket className="size-3 shrink-0" />{$i18n.t('Action')}</span
>
<div class="flex min-w-0 flex-1 items-center gap-2">
<Dropdown bind:show={showActionTypeMenu} align="start" sideOffset={4}>
<button
type="button"
aria-label={$i18n.t('Action')}
class="flex w-fit min-w-0 items-center text-left text-xs font-normal leading-6 text-base-700 dark:text-base-300"
>
{action_type === 'code' ? $i18n.t('Code') : $i18n.t('Prompt')}
</button>
<div slot="content">
<DropdownMenu className="min-w-[9.375rem]">
{#each actionTypes as value (value)}
<button
type="button"
class="flex h-7 w-full select-none items-center gap-2 rounded-lg px-2 text-xs transition hover:bg-base-50/40 dark:hover:bg-base-0/4"
on:click={() => {
action_type = value;
showActionTypeMenu = false;
}}
>
<span class="flex-1 text-left"
>{value === 'code' ? $i18n.t('Code') : $i18n.t('Prompt')}</span
>
{#if action_type === value}
<Check className="size-3 text-base-500 dark:text-base-400" />
{/if}
</button>
{/each}
</DropdownMenu>
</div>
</Dropdown>
</div>
</div>
</div>
<div class="mt-3 text-[0.6875rem] text-base-400 dark:text-base-500">
{action_type === 'code' ? $i18n.t('Code') : $i18n.t('Prompt')}
</div>
{#if action_type === 'code'}
<div class="relative mt-1">
<CodeEditor
value={code}
lang="python"
ariaLabel={$i18n.t('Code')}
className="text-xs"
onChange={(value) => {
code = value;
}}
/>
</div>
{:else}
<Textarea
className="mt-1 w-full resize-none overflow-hidden bg-transparent text-xs font-normal leading-relaxed text-base-700 outline-hidden placeholder:text-base-400 dark:text-base-300 dark:placeholder:text-base-500"
bind:value={prompt}
rows={1}
ariaLabel={$i18n.t('Instructions')}
placeholder={$i18n.t('Enter prompt here.')}
/>
{/if}
<div class="mt-6 mb-1 text-[0.6875rem] text-base-400 dark:text-base-500">
{$i18n.t('Properties')}
</div>
<div class="-mx-2">
<div class={rowClass}>
<span class={labelClass}>
<svg class="size-3 shrink-0" viewBox="0 0 16 16" fill="none" aria-hidden="true"
><circle cx="8" cy="8" r="5.75" stroke="currentColor" stroke-width="1.5" /><path
d="M8 2.25a5.75 5.75 0 0 1 0 11.5z"
fill="currentColor"
/></svg
>{$i18n.t('Status')}
</span>
<span class="min-w-0 truncate {valueClass}"
>{is_active ? $i18n.t('Active') : $i18n.t('Paused')}</span
>
<Switch
bind:state={is_active}
ariaLabel={is_active ? $i18n.t('Active') : $i18n.t('Paused')}
/>
</div>
<div class={rowClass}>
<span class={labelClass}><Sparkles className="size-3 shrink-0" />{$i18n.t('Model')}</span>
<div class="min-w-0 flex-1">
<ModelDropdown
bind:model_id
items={[...$baseModels, ...agentModels]}
disabled={modelsLoading}
plain
side="bottom"
align="start"
/>
</div>
</div>
<div class={rowClass}>
<span class={labelClass}
><Folder className="size-3 shrink-0" />{$i18n.t('Destination')}</span
>
<div class="min-w-0 flex-1">
<DestinationDropdown
bind:target_type
bind:channel_id
bind:folder_id
bind:start_new
bind:reply_in_thread
folders={$folders}
channels={$channels}
plain
side="bottom"
align="start"
/>
</div>
</div>
<div class={rowClass}>
<span class={labelClass}
><Icon name="terminal" size={12} class="shrink-0" />{$i18n.t('Machine')}</span
>
<div class="min-w-0 flex-1">
<MachineDropdown
{machines}
bind:machineServerId
bind:machineCwd
plain
side="bottom"
align="start"
/>
</div>
</div>
</div>
</div>
<div class="mt-4 flex items-center justify-end gap-2">
<button
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2.5 text-xs font-normal text-base-600 transition hover:bg-base-100 hover:text-base-900 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-850 dark:hover:text-base-0"
type="button"
on:click={() => (show = false)}
>
{$i18n.t('Cancel')}
</button>
<button
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-base-900 px-2.5 text-xs font-normal text-base-0 transition hover:bg-base-1000 disabled:opacity-60 dark:bg-base-100 dark:text-base-900 dark:hover:bg-base-0 disabled:cursor-not-allowed"
on:click={submitHandler}
type="button"
disabled={loading || modelsLoading || !initialized}
>
{$i18n.t('Create')}
{#if loading}
<span class="shrink-0"><Spinner className="size-3" /></span>
{/if}
</button>
</div>
</div>
</Modal>