Files
open-webui/src/lib/components/automations/AutomationEditor.svelte
T
2026-11-14 00:45:43 +09:00

409 lines
12 KiB
Svelte

<script lang="ts">
import { getPageContext } from '$lib/utils/page';
const { goto, url: pageUrl } = getPageContext();
import { formatSchedule } from '$lib/utils/schedule';
import { onMount, onDestroy, getContext, tick } from 'svelte';
import { toast } from 'svelte-sonner';
import { WEBUI_API_BASE_URL } from '$lib/constants';
import dayjs from 'dayjs';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import type i18nType from '$lib/i18n';
import { WEBUI_NAME, channels, folders } from '$lib/stores';
import { getFolders } from '$lib/apis/folders';
import { getChannels } from '$lib/apis/channels';
import {
getAutomationById,
toggleAutomationById,
runAutomationById,
deleteAutomationById,
getAutomationRuns,
type AutomationResponse,
type AutomationRunModel
} from '$lib/apis/automations';
import AutomationModal from '$lib/components/AutomationModal.svelte';
import AutomationItemHeaderActions from '$lib/components/automations/AutomationItemHeaderActions.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
import ArrowRight from '$lib/components/icons/ArrowRight.svelte';
import Check from '$lib/components/icons/Check.svelte';
import XMark from '$lib/components/icons/XMark.svelte';
dayjs.extend(localizedFormat);
const i18n: typeof i18nType = getContext('i18n');
const automationsLayout: any = getContext('automationsLayout');
export let automation: AutomationResponse;
let is_active = automation.is_active;
let loading = false;
let showDeleteConfirm = false;
let showEditModal = false;
let runs: AutomationRunModel[] = [];
let linkedRun: AutomationRunModel | null = null;
$: visibleRuns =
linkedRun && !runs.some((run) => run.id === linkedRun?.id)
? [...runs, linkedRun].sort((a, b) => b.created_at - a.created_at)
: runs;
let linkedRunId = '';
let alive = true;
onDestroy(() => {
alive = false;
});
$: if (($pageUrl.searchParams.get('run') ?? '') !== linkedRunId) {
linkedRunId = $pageUrl.searchParams.get('run') ?? '';
void revealRun(linkedRunId);
}
async function revealRun(id: string) {
linkedRun = null;
if (!id) return;
try {
const response = await fetch(
`${WEBUI_API_BASE_URL}/automations/${encodeURIComponent(automation.id)}/runs/${encodeURIComponent(id)}`,
{ headers: { Authorization: `Bearer ${localStorage.token}` } }
);
if (!response.ok) throw new Error($i18n.t('Run not found'));
const run = await response.json();
if (!alive || linkedRunId !== id) return;
linkedRun = run;
await tick();
document.getElementById('inbox-automation-run')?.scrollIntoView({ block: 'center' });
} catch (error) {
if (alive && linkedRunId === id) toast.error(String(error));
}
}
let runsLoading = false;
let hasMoreRuns = true;
let runsPage = 0;
let foldersLoaded = false;
let channelsLoaded = false;
const ensureFolders = async () => {
if (foldersLoaded || ($folders ?? []).length > 0) return;
const res = await getFolders(localStorage.token).catch(() => null);
if (res) folders.set(res);
foldersLoaded = true;
};
const ensureChannels = async () => {
if (channelsLoaded || ($channels ?? []).length > 0) return;
const res = await getChannels(localStorage.token).catch(() => null);
if (res) channels.set(res);
channelsLoaded = true;
};
const getFolderName = (folderId: string | null): string =>
folderId
? (($folders ?? []).find((folder) => folder.id === folderId)?.name ?? $i18n.t('None'))
: $i18n.t('None');
const getDestinationName = (): string => {
const target = automation.data.target;
if (target?.type === 'channel') {
const channel = ($channels ?? []).find((channel) => channel.id === target.channel_id);
return channel?.name ? `#${channel.name}` : $i18n.t('Channel');
}
return automation.folder_id
? `${$i18n.t('Folder')}: ${getFolderName(automation.folder_id)}`
: $i18n.t('New chat');
};
const formatTime = (ts: number | null): string => {
if (!ts) return '-';
return new Date(ts / 1_000_000).toLocaleString($i18n.language, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
const formatNextRun = (ts: number | null): string => {
if (!ts) return $i18n.t('Not scheduled');
const d = dayjs(ts / 1_000_000).locale($i18n.language);
if (d.isSame(dayjs().locale($i18n.language), 'day'))
return `${$i18n.t('Today at')} ${d.format('LT')}`;
return d.format('L LT');
};
const toggleHandler = async () => {
const previousState = automation.is_active;
const res = await toggleAutomationById(localStorage.token, automation.id).catch((err) => {
toast.error(`${err}`);
return null;
});
if (res) {
is_active = res.is_active;
automation = res;
} else {
is_active = previousState;
}
};
const runNowHandler = async () => {
if (loading) return;
loading = true;
const res = await runAutomationById(localStorage.token, automation.id).catch((err) => {
toast.error(`${err}`);
return null;
});
if (res) {
automation = res;
toast.success($i18n.t('Automation triggered'));
setTimeout(() => loadRuns(false), 2000);
}
loading = false;
};
const editSavedHandler = async () => {
const updated = await getAutomationById(localStorage.token, automation.id).catch((err) => {
toast.error(`${err}`);
return null;
});
if (updated) {
automation = updated;
is_active = updated.is_active;
await loadRuns();
}
};
const deleteHandler = async () => {
const res = await deleteAutomationById(localStorage.token, automation.id).catch((err) => {
toast.error(`${err}`);
return null;
});
if (res) {
toast.success($i18n.t(`Deleted {{name}}`, { name: automation.name }));
goto('/automations');
}
};
const loadRuns = async (loadMore = false) => {
if (runsLoading || (!hasMoreRuns && loadMore)) return;
runsLoading = true;
if (!loadMore) {
runsPage = 0;
hasMoreRuns = true;
}
try {
const fetchedRuns =
(await getAutomationRuns(localStorage.token, automation.id, runsPage * 50, 50)) ?? [];
if (loadMore) {
runs = [...runs, ...fetchedRuns];
} else {
runs = fetchedRuns;
}
if (fetchedRuns.length < 50) {
hasMoreRuns = false;
}
runsPage++;
} catch {
if (!loadMore) runs = [];
}
runsLoading = false;
};
const onScroll = (e: Event) => {
const target = e.target as HTMLElement;
if (target.scrollTop + target.clientHeight >= target.scrollHeight - 50) {
if (!runsLoading && hasMoreRuns) {
loadRuns(true);
}
}
};
onMount(async () => {
is_active = automation.is_active;
await ensureFolders();
await ensureChannels();
await loadRuns();
});
$: if (automation) {
automationsLayout?.setHeader({
itemName: automation.name,
actions: AutomationItemHeaderActions,
actionProps: {
isActive: is_active,
loading,
toggleHandler,
runNowHandler,
editHandler: () => (showEditModal = true),
deleteHandler: () => (showDeleteConfirm = true)
}
});
}
import PageTitle from '$lib/components/common/PageTitle.svelte';
</script>
<!-- LICENSE covers this Open WebUI browser-title identifier.
Do not alter, remove, obscure, or replace it except as LICENSE permits:
https://docs.openwebui.com/license. -->
<PageTitle title={(automation.name || $i18n.t('Automation')) + ' / ' + $WEBUI_NAME} />
<DeleteConfirmDialog
bind:show={showDeleteConfirm}
title={$i18n.t('Delete automation?')}
on:confirm={deleteHandler}
>
<div class="text-sm text-gray-500 truncate">
{$i18n.t('This will delete')} <span class="">{automation.name}</span>.
</div>
</DeleteConfirmDialog>
<AutomationModal bind:show={showEditModal} {automation} on:save={editSavedHandler} />
<div class="h-full overflow-y-auto scrollbar-hidden">
<div class="pb-1 px-1">
<div class="flex h-7 items-center px-3">
<span class="w-24 shrink-0 text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Status')}
</span>
<span class="min-w-0 text-xs text-gray-700 dark:text-gray-300">
{is_active ? $i18n.t('Active') : $i18n.t('Paused')}
</span>
</div>
<div class="flex h-7 items-center px-3">
<span class="w-24 shrink-0 text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Schedule')}
</span>
<span class="min-w-0 truncate text-xs text-gray-700 dark:text-gray-300">
{formatSchedule(automation.data.rrule, $i18n)}
</span>
</div>
<div class="flex h-7 items-center px-3">
<span class="w-24 shrink-0 text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Destination')}
</span>
<span class="min-w-0 truncate text-xs text-gray-700 dark:text-gray-300">
{getDestinationName()}
</span>
</div>
<div class="flex h-7 items-center px-3">
<span class="w-24 shrink-0 text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Model')}
</span>
<span class="min-w-0 truncate text-xs text-gray-700 dark:text-gray-300">
{automation.data.model_id}
</span>
</div>
<div class="flex h-7 items-center px-3">
<span class="w-24 shrink-0 text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Next run')}
</span>
<span class="min-w-0 truncate text-xs text-gray-700 dark:text-gray-300">
{formatNextRun(automation.next_runs?.[0] ?? automation.next_run_at)}
</span>
</div>
<div class="flex h-7 items-center px-3">
<span class="w-24 shrink-0 text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Last run')}
</span>
<span class="min-w-0 truncate text-xs text-gray-700 dark:text-gray-300">
{automation.last_run_at ? formatNextRun(automation.last_run_at) : $i18n.t('Never')}
</span>
</div>
</div>
<hr class="my-1.5 border-gray-50/60 dark:border-gray-850/25" />
<div class="px-4 py-2">
<div class="mb-2 text-[0.6875rem] text-gray-400 dark:text-gray-500">{$i18n.t('Prompt')}</div>
<div
class="whitespace-pre-wrap font-mono text-xs leading-relaxed text-gray-700 dark:text-gray-300"
>
{automation.data.prompt}
</div>
</div>
<hr class="my-1.5 border-gray-50/60 dark:border-gray-850/25" />
<div class="px-4 py-2">
<div class="mb-1 text-[0.6875rem] text-gray-400 dark:text-gray-500">{$i18n.t('Runs')}</div>
<div class="overflow-y-auto scrollbar-hidden" on:scroll={onScroll}>
{#if runsLoading && visibleRuns.length === 0}
<div class="flex justify-center py-8">
<Spinner className="size-4" />
</div>
{:else if visibleRuns.length === 0}
<div class="py-2 text-[0.6875rem] text-gray-400 dark:text-gray-600">
{$i18n.t('No runs yet')}
</div>
{:else}
<div>
{#each visibleRuns as run}
<div
id={run.id === linkedRun?.id ? 'inbox-automation-run' : undefined}
class="flex h-7 items-center gap-2 text-xs"
>
<span
class="flex shrink-0 text-gray-400"
title={run.status === 'success' ? $i18n.t('Succeeded') : $i18n.t('Failed')}
aria-label={run.status === 'success' ? $i18n.t('Succeeded') : $i18n.t('Failed')}
>
{#if run.status === 'success'}<Check className="size-3" />{:else}<XMark
className="size-3"
/>{/if}
</span>
<span class="text-gray-500 dark:text-gray-400">{formatTime(run.created_at)}</span>
{#if run.chat_id}
<button
class="group flex items-center gap-1 text-[0.6875rem] text-gray-400"
on:click={() => {
if (run.chat_id?.startsWith('channel:')) {
goto(`/channels/${run.chat_id.replace('channel:', '')}`);
} else {
goto(`/c/${run.chat_id}`);
}
}}
type="button"
>
<span class="group-hover:underline">
{run.chat_id?.startsWith('channel:')
? $i18n.t('View channel')
: $i18n.t('View chat')}
</span>
<ArrowRight className="size-2.5" strokeWidth="2" />
</button>
{/if}
{#if run.error}
<span
class="truncate text-[0.6875rem] text-gray-400 dark:text-gray-500"
title={run.error}
>
{run.error}
</span>
{/if}
</div>
{/each}
{#if runsLoading && runs.length > 0}
<div class="flex justify-center py-4">
<Spinner className="size-4" />
</div>
{/if}
</div>
{/if}
</div>
</div>
</div>