From f59a3aff858aa788bc916be4e6c2fac71c092a52 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 22 Nov 2026 02:10:33 +0400 Subject: [PATCH] refac --- backend/open_webui/config.py | 2 + backend/open_webui/main.py | 2 + backend/open_webui/models/automations.py | 46 ++++- backend/open_webui/routers/auths.py | 2 + backend/open_webui/routers/automations.py | 182 ++++++++++++++---- backend/open_webui/routers/folders.py | 10 +- backend/open_webui/tools/builtin.py | 41 ++-- backend/open_webui/utils/automations.py | 16 +- backend/open_webui/utils/prompt_variables.py | 136 +++++++++++++ src/lib/apis/automations/index.ts | 58 +++++- src/lib/components/AutomationModal.svelte | 41 +++- .../components/admin/Settings/General.svelte | 13 ++ .../automations/AutomationEditor.svelte | 82 +++++++- .../components/automations/Automations.svelte | 39 +++- .../automations/ScheduleDropdown.svelte | 13 +- .../automations/WebhookDropdown.svelte | 109 +++++++++++ .../chat/Placeholder/FolderAutomations.svelte | 4 +- src/lib/i18n/locales/ar-BH/translation.json | 7 + src/lib/i18n/locales/ar/translation.json | 7 + src/lib/i18n/locales/az-AZ/translation.json | 7 + src/lib/i18n/locales/bg-BG/translation.json | 7 + src/lib/i18n/locales/bn-BD/translation.json | 7 + src/lib/i18n/locales/bo-TB/translation.json | 7 + src/lib/i18n/locales/bs-BA/translation.json | 7 + src/lib/i18n/locales/ca-ES/translation.json | 7 + src/lib/i18n/locales/ceb-PH/translation.json | 7 + src/lib/i18n/locales/cs-CZ/translation.json | 7 + src/lib/i18n/locales/da-DK/translation.json | 7 + src/lib/i18n/locales/de-DE/translation.json | 7 + src/lib/i18n/locales/dg-DG/translation.json | 7 + src/lib/i18n/locales/el-GR/translation.json | 7 + src/lib/i18n/locales/en-GB/translation.json | 7 + src/lib/i18n/locales/en-US/translation.json | 7 + src/lib/i18n/locales/es-ES/translation.json | 7 + src/lib/i18n/locales/et-EE/translation.json | 7 + src/lib/i18n/locales/eu-ES/translation.json | 7 + src/lib/i18n/locales/fa-IR/translation.json | 7 + src/lib/i18n/locales/fi-FI/translation.json | 7 + src/lib/i18n/locales/fil-PH/translation.json | 7 + src/lib/i18n/locales/fo-FO/translation.json | 7 + src/lib/i18n/locales/fr-CA/translation.json | 7 + src/lib/i18n/locales/fr-FR/translation.json | 7 + src/lib/i18n/locales/gl-ES/translation.json | 7 + src/lib/i18n/locales/he-IL/translation.json | 7 + src/lib/i18n/locales/hi-IN/translation.json | 7 + src/lib/i18n/locales/hr-HR/translation.json | 7 + src/lib/i18n/locales/hu-HU/translation.json | 7 + src/lib/i18n/locales/id-ID/translation.json | 7 + src/lib/i18n/locales/ie-GA/translation.json | 7 + src/lib/i18n/locales/it-IT/translation.json | 7 + src/lib/i18n/locales/ja-JP/translation.json | 7 + src/lib/i18n/locales/ka-GE/translation.json | 7 + src/lib/i18n/locales/kab-DZ/translation.json | 7 + src/lib/i18n/locales/ko-KR/translation.json | 7 + src/lib/i18n/locales/lt-LT/translation.json | 7 + src/lib/i18n/locales/lv-LV/translation.json | 7 + src/lib/i18n/locales/ms-MY/translation.json | 7 + src/lib/i18n/locales/nb-NO/translation.json | 7 + src/lib/i18n/locales/nl-NL/translation.json | 7 + src/lib/i18n/locales/pa-IN/translation.json | 7 + src/lib/i18n/locales/pl-PL/translation.json | 7 + src/lib/i18n/locales/pt-BR/translation.json | 7 + src/lib/i18n/locales/pt-PT/translation.json | 7 + src/lib/i18n/locales/ro-RO/translation.json | 7 + src/lib/i18n/locales/ru-RU/translation.json | 7 + src/lib/i18n/locales/sk-SK/translation.json | 7 + src/lib/i18n/locales/sl-SI/translation.json | 7 + src/lib/i18n/locales/sr-RS/translation.json | 7 + src/lib/i18n/locales/sv-SE/translation.json | 7 + src/lib/i18n/locales/ta-IN/translation.json | 7 + src/lib/i18n/locales/th-TH/translation.json | 7 + src/lib/i18n/locales/tk-TM/translation.json | 7 + src/lib/i18n/locales/tr-TR/translation.json | 7 + src/lib/i18n/locales/ug-CN/translation.json | 7 + src/lib/i18n/locales/uk-UA/translation.json | 7 + src/lib/i18n/locales/ur-PK/translation.json | 7 + .../i18n/locales/uz-Cyrl-UZ/translation.json | 7 + .../i18n/locales/uz-Latn-UZ/translation.json | 7 + src/lib/i18n/locales/vi-VN/translation.json | 7 + src/lib/i18n/locales/zh-CN/translation.json | 7 + src/lib/i18n/locales/zh-TW/translation.json | 7 + src/lib/stores/index.ts | 1 + src/lib/utils/schedule.ts | 8 + 83 files changed, 1177 insertions(+), 76 deletions(-) create mode 100644 backend/open_webui/utils/prompt_variables.py create mode 100644 src/lib/components/automations/WebhookDropdown.svelte diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index 274696b562..473fdc6d75 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -2104,6 +2104,7 @@ CHANNEL_MODEL_RESPONSE_MODE = os.getenv('CHANNEL_MODEL_RESPONSE_MODE', 'thread') ENABLE_CALENDAR = os.getenv('ENABLE_CALENDAR', 'True').lower() == 'true' ENABLE_AUTOMATIONS = os.getenv('ENABLE_AUTOMATIONS', 'True').lower() == 'true' +ENABLE_AUTOMATION_WEBHOOKS = os.getenv('ENABLE_AUTOMATION_WEBHOOKS', 'True').lower() == 'true' ENABLE_SUBAGENTS = os.getenv('ENABLE_SUBAGENTS', 'False').lower() == 'true' SUBAGENTS_BACKGROUND_ENABLED = os.getenv('SUBAGENTS_BACKGROUND_ENABLED', 'False').lower() == 'true' @@ -3291,6 +3292,7 @@ DEFAULT_CONFIG = { 'channels.model_response_mode': CHANNEL_MODEL_RESPONSE_MODE, 'calendar.enable': ENABLE_CALENDAR, 'automations.enable': ENABLE_AUTOMATIONS, + 'automations.webhooks.enable': ENABLE_AUTOMATION_WEBHOOKS, 'subagents.enable': ENABLE_SUBAGENTS, 'subagents.background_enabled': SUBAGENTS_BACKGROUND_ENABLED, 'subagents.max_concurrent': SUBAGENTS_MAX_CONCURRENT, diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index e1e6f094b8..bf53bdacc9 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -2391,6 +2391,7 @@ async def get_app_config(request: Request): 'apps.enable', 'calendar.enable', 'automations.enable', + 'automations.webhooks.enable', 'notes.enable', 'comments.enable', 'notifications.enable', @@ -2501,6 +2502,7 @@ async def get_app_config(request: Request): 'enable_apps': config.get('apps.enable'), 'enable_calendar': config.get('calendar.enable'), 'enable_automations': config.get('automations.enable'), + 'enable_automation_webhooks': config.get('automations.webhooks.enable'), 'enable_notes': config.get('notes.enable'), 'enable_comments': config.get('comments.enable'), 'enable_notifications': config.get('notifications.enable'), diff --git a/backend/open_webui/models/automations.py b/backend/open_webui/models/automations.py index f4af151aa4..b51f6c37d7 100644 --- a/backend/open_webui/models/automations.py +++ b/backend/open_webui/models/automations.py @@ -1,4 +1,5 @@ import logging +import secrets import time from typing import Literal, Optional from uuid import uuid4 @@ -92,12 +93,38 @@ def keep_target_refs(target: Optional[dict], previous: Optional[dict]) -> Option return target +class AutomationWebhook(BaseModel): + token: Optional[str] = None # server-owned + allow_get: bool = False + + +def has_webhook(data: Optional[dict]) -> bool: + return bool((data or {}).get('webhook')) + + +def hide_webhook_token(data: dict) -> dict: + if not (data.get('webhook') or {}).get('token'): + return data + return {**data, 'webhook': {**data['webhook'], 'token': None}} + + +def new_webhook_token() -> str: + return secrets.token_urlsafe(32) + + +def keep_webhook_token(webhook: Optional[dict], previous: Optional[dict]) -> Optional[dict]: + if not webhook: + return None + return {**webhook, 'token': (previous or {}).get('token') or new_webhook_token()} + + class AutomationData(BaseModel): prompt: str model_id: str - rrule: str + rrule: str = '' # empty: no schedule terminal: Optional[AutomationTerminalConfig] = None target: Optional[AutomationTarget] = None + webhook: Optional[AutomationWebhook] = None class AutomationModel(BaseModel): @@ -159,12 +186,14 @@ class AutomationTable: ) -> AutomationModel: async with get_async_db_context(db) as db: now = int(time.time_ns()) + data = form.data.model_dump() + data['webhook'] = keep_webhook_token(data.get('webhook'), None) row = Automation( id=str(uuid4()), user_id=user_id, folder_id=form.folder_id, name=form.name, - data=form.data.model_dump(), + data=data, meta=form.meta, is_active=form.is_active, next_run_at=next_run_at, @@ -265,6 +294,7 @@ class AutomationTable: row.folder_id = form.folder_id data = form.data.model_dump() data['target'] = keep_target_refs(data.get('target'), (row.data or {}).get('target')) + data['webhook'] = keep_webhook_token(data.get('webhook'), (row.data or {}).get('webhook')) row.data = data row.meta = form.meta if form.is_active is not None: @@ -285,6 +315,18 @@ class AutomationTable: row.data = data await db.commit() + async def regenerate_webhook_token(self, id: str, db: Optional[AsyncSession] = None) -> Optional[AutomationModel]: + async with get_async_db_context(db) as db: + row = await db.get(Automation, id, with_for_update=True) + if not row or not has_webhook(row.data): + return None + data = dict(row.data or {}) + data['webhook'] = {**data['webhook'], 'token': new_webhook_token()} + row.data = data + row.updated_at = int(time.time_ns()) + await db.commit() + return AutomationModel.model_validate(row) + async def update_last_run_at(self, id: str, db: Optional[AsyncSession] = None) -> Optional[AutomationModel]: async with get_async_db_context(db) as db: row = await db.get(Automation, id) diff --git a/backend/open_webui/routers/auths.py b/backend/open_webui/routers/auths.py index a35ea0d88c..bfc3f6b1aa 100644 --- a/backend/open_webui/routers/auths.py +++ b/backend/open_webui/routers/auths.py @@ -131,6 +131,7 @@ ADMIN_CONFIG_KEYS = { 'AUTOMATION_MAX_COUNT': 'automations.max_count', 'AUTOMATION_MIN_INTERVAL': 'automations.min_interval', 'ENABLE_AUTOMATIONS': 'automations.enable', + 'ENABLE_AUTOMATION_WEBHOOKS': 'automations.webhooks.enable', 'ENABLE_CHANNELS': 'channels.enable', 'ENABLE_COMMENTS': 'comments.enable', 'ENABLE_NOTIFICATIONS': 'notifications.enable', @@ -1184,6 +1185,7 @@ class AdminConfig(MfaConfigForm): AUTOMATION_MAX_COUNT: int | str | None = None AUTOMATION_MIN_INTERVAL: int | str | None = None ENABLE_AUTOMATIONS: bool + ENABLE_AUTOMATION_WEBHOOKS: bool = True ENABLE_CHANNELS: bool ENABLE_COMMENTS: bool = False ENABLE_NOTIFICATIONS: bool = True diff --git a/backend/open_webui/routers/automations.py b/backend/open_webui/routers/automations.py index 1459545318..4fe8224cf4 100644 --- a/backend/open_webui/routers/automations.py +++ b/backend/open_webui/routers/automations.py @@ -1,8 +1,11 @@ import asyncio +import hmac +import json import logging -from typing import Literal, Optional +from typing import Any, Literal, Optional from fastapi import APIRouter, Depends, HTTPException, Request, status +from fastapi.responses import JSONResponse from open_webui.constants import ERROR_MESSAGES from open_webui.events import EVENTS, publish_event from open_webui.internal.db import get_async_session @@ -14,7 +17,9 @@ from open_webui.models.automations import ( AutomationRunModel, AutomationRuns, Automations, + hide_webhook_token, ) +from open_webui.models.users import Users from open_webui.models.access_grants import AccessGrants, has_public_write_access_grant from open_webui.models.channels import Channels from open_webui.models.config import Config @@ -25,12 +30,15 @@ from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.agents.discovery import get_models as get_agent_models from open_webui.utils.automations import ( execute_automation, - next_n_runs_ns, - next_run_ns, rrule_interval_seconds, + schedule_next_run, + schedule_next_runs, validate_rrule, validate_automation_terminal, ) +from open_webui.utils.prompt_variables import PromptVariableError, fill_variables +from open_webui.utils.rate_limit import RateLimiter +from pydantic import BaseModel from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) @@ -38,6 +46,8 @@ log = logging.getLogger(__name__) router = APIRouter() PAGE_ITEM_COUNT = 30 +HOOK_MAX_BODY = 64 * 1024 +hook_limiter = RateLimiter(30, 60) # Helpers @@ -59,6 +69,27 @@ async def check_automations_permission(request, user): ) +async def can_use_automation_webhooks(user) -> bool: + config = await Config.get_many('automations.enable', 'automations.webhooks.enable', 'user.permissions') + if not config.get('automations.enable') or not config.get('automations.webhooks.enable'): + return False + return user.role == 'admin' or await has_permission(user.id, 'features.automations', config.get('user.permissions')) + + +async def check_automation_triggers(form_data: AutomationForm, user, db, is_create: bool = False): + data = form_data.data + if data.webhook and not await can_use_automation_webhooks(user): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.UNAUTHORIZED) + if not data.rrule and not data.webhook: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Add a schedule or a webhook') + if data.rrule: + try: + await validate_rrule(data.rrule, tz=user.timezone) + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + await check_automation_limits(None, user, data.rrule or None, db, is_create=is_create) + + def check_automation_access(automation, user): if not automation or user.id != automation.user_id: raise HTTPException( @@ -67,7 +98,7 @@ def check_automation_access(automation, user): ) -async def check_automation_limits(request, user, rrule_str: str, db, is_create: bool = False): +async def check_automation_limits(request, user, rrule_str: Optional[str], db, is_create: bool = False): """Enforce global automation limits. Admins bypass all checks.""" if user.role == 'admin': return @@ -84,7 +115,7 @@ async def check_automation_limits(request, user, rrule_str: str, db, is_create: ) # Min interval (create + update) - min_interval = await Config.get('automations.min_interval') + min_interval = await Config.get('automations.min_interval') if rrule_str else None if min_interval: min_interval = int(min_interval) if min_interval > 0: @@ -162,13 +193,16 @@ async def check_automation_channel_access(form_data: AutomationForm, user, db: A ) -async def enrich_automation(automation: AutomationModel, db: AsyncSession, tz: str = None) -> AutomationResponse: +async def enrich_automation( + automation: AutomationModel, db: AsyncSession, tz: str = None, viewer=None +) -> AutomationResponse: """Full enrichment for single-item views (includes next_runs computation).""" last_run = await AutomationRuns.get_latest(automation.id, db=db) + data = automation.data if viewer is None or viewer.id == automation.user_id else hide_webhook_token(automation.data) return AutomationResponse( - **automation.model_dump(), + **{**automation.model_dump(), 'data': data}, last_run=last_run, - next_runs=await next_n_runs_ns(automation.data['rrule'], tz=tz), + next_runs=await schedule_next_runs(automation.data, tz=tz), ) @@ -254,18 +288,11 @@ async def create_new_automation( if form_data.data.target: form_data.data.target.chat_id = None form_data.data.target.thread_id = None - try: - await validate_rrule(form_data.data.rrule, tz=user.timezone) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) - - await check_automation_limits(request, user, form_data.data.rrule, db, is_create=True) + await check_automation_triggers(form_data, user, db, is_create=True) tz = user.timezone - automation = await Automations.insert(user.id, form_data, await next_run_ns(form_data.data.rrule, tz=tz), db=db) + next_run_at = await schedule_next_run(form_data.data.model_dump(), tz=tz) + automation = await Automations.insert(user.id, form_data, next_run_at, db=db) response = await enrich_automation(automation, db, tz=tz) await publish_event( request, @@ -310,19 +337,11 @@ async def update_automation_by_id( await check_automation_folder_access(form_data.folder_id, user, db) await check_automation_channel_access(form_data, user, db) await validate_automation_terminal(request, user, form_data.data.model_dump(), id) - - try: - await validate_rrule(form_data.data.rrule, tz=user.timezone) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) - - await check_automation_limits(request, user, form_data.data.rrule, db, is_create=False) + await check_automation_triggers(form_data, user, db) tz = user.timezone - updated = await Automations.update_by_id(id, form_data, await next_run_ns(form_data.data.rrule, tz=tz), db=db) + next_run_at = await schedule_next_run(form_data.data.model_dump(), tz=tz) + updated = await Automations.update_by_id(id, form_data, next_run_at, db=db) response = await enrich_automation(updated, db, tz=tz) await publish_event( request, @@ -347,8 +366,8 @@ async def toggle_automation_by_id( await check_automations_permission(request, user) automation = await Automations.get_by_id(id, db=db) await check_automation_manage_access(automation, user, db) - toggled = await Automations.toggle(id, await next_run_ns(automation.data['rrule'], tz=user.timezone), db=db) - response = await enrich_automation(toggled, db, tz=user.timezone) + toggled = await Automations.toggle(id, await schedule_next_run(automation.data, tz=user.timezone), db=db) + response = await enrich_automation(toggled, db, tz=user.timezone, viewer=user) await publish_event( request, EVENTS.AUTOMATION_ENABLED if toggled.is_active else EVENTS.AUTOMATION_DISABLED, @@ -363,18 +382,32 @@ async def toggle_automation_by_id( # Run Automation By Id +class AutomationRunForm(BaseModel): + variables: Optional[dict[str, Any]] = None + + +def check_variables(automation: AutomationModel, variables: Optional[dict]): + try: + fill_variables(automation.data['prompt'], variables) + except PromptVariableError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + + @router.post('/{id}/run') async def run_automation_by_id( request: Request, id: str, + form_data: Optional[AutomationRunForm] = None, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) automation = await Automations.get_by_id(id, db=db) await check_automation_manage_access(automation, user, db) + variables = form_data.variables if form_data else None + check_variables(automation, variables) automation = await Automations.update_last_run_at(automation.id, db=db) - asyncio.create_task(execute_automation(request.app, automation)) + asyncio.create_task(execute_automation(request.app, automation, variables)) await publish_event( request, EVENTS.AUTOMATION_RUN_STARTED, @@ -382,7 +415,90 @@ async def run_automation_by_id( subject_id=automation.id, data={'name': automation.name}, ) - return await enrich_automation(automation, db, tz=user.timezone) + return await enrich_automation(automation, db, tz=user.timezone, viewer=user) + + +# Webhook Trigger + + +@router.post('/{id}/token/regenerate', response_model=AutomationResponse) +async def regenerate_automation_token( + request: Request, + id: str, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + await check_automations_permission(request, user) + automation = await Automations.get_by_id(id, db=db) + check_automation_access(automation, user) + if not await can_use_automation_webhooks(user): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.UNAUTHORIZED) + updated = await Automations.regenerate_webhook_token(id, db=db) + if not updated: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()) + return await enrich_automation(updated, db, tz=user.timezone) + + +async def read_hook_variables(request: Request) -> dict: + variables: dict = dict(request.query_params) + if request.method != 'POST': + return variables + if int(request.headers.get('content-length') or 0) > HOOK_MAX_BODY: + raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE) + body = await request.body() + if len(body) > HOOK_MAX_BODY: + raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE) + if not body.strip(): + return variables + try: + payload = json.loads(body) + except ValueError: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Body must be JSON') + if not isinstance(payload, dict): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Body must be a JSON object') + # {"variables": {...}} wins; any other payload (GitHub, Gitea) is read as-is. + wrapped = payload.get('variables') + return {**variables, **payload, **(wrapped if isinstance(wrapped, dict) else {})} + + +@router.api_route('/hooks/{id}/{token}', methods=['GET', 'POST']) +async def trigger_automation_webhook(request: Request, id: str, token: str): + """Public: the token in the URL is the credential.""" + automation = await Automations.get_by_id(id) + webhook = (automation.data.get('webhook') or {}) if automation else {} + config = await Config.get_many('automations.enable', 'automations.webhooks.enable') + if ( + not automation + or not webhook.get('token') + or not hmac.compare_digest(webhook['token'], token) + or not config.get('automations.enable') + or not config.get('automations.webhooks.enable') + ): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + if request.method == 'GET' and not webhook.get('allow_get'): + raise HTTPException(status_code=status.HTTP_405_METHOD_NOT_ALLOWED) + + owner = await Users.get_user_by_id(automation.user_id) + if not owner or not await can_use_automation_webhooks(owner): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + if not automation.is_active: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail='Automation is paused') + if await hook_limiter.is_limited(getattr(request.app.state, 'redis', None), f'automation-hook:{id}'): + raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS) + + variables = await read_hook_variables(request) + check_variables(automation, variables) + automation = await Automations.update_last_run_at(automation.id) + asyncio.create_task(execute_automation(request.app, automation, variables)) + await publish_event( + request, + EVENTS.AUTOMATION_RUN_STARTED, + actor=owner, + subject_id=automation.id, + source='automation_webhook', + data={'name': automation.name}, + ) + return JSONResponse({'status': 'accepted'}, status_code=202, headers={'Cache-Control': 'no-store'}) # Delete Automation By Id diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py index 605b81a31f..e8e9a770cb 100644 --- a/backend/open_webui/routers/folders.py +++ b/backend/open_webui/routers/folders.py @@ -13,7 +13,7 @@ from open_webui.constants import ERROR_MESSAGES from open_webui.events import EVENTS, publish_event from open_webui.internal.db import get_async_session from open_webui.models.access_grants import AccessGrants -from open_webui.models.automations import AutomationResponse, AutomationRuns, Automations +from open_webui.models.automations import AutomationResponse, AutomationRuns, Automations, hide_webhook_token from open_webui.models.chat_messages import ChatMessages from open_webui.models.chats import FOLDER_PRIORITIES, NO_FOLDER_PRIORITY, Chats from open_webui.models.config import Config @@ -762,7 +762,13 @@ async def get_folder_automations( ) return [ { - **AutomationResponse(**item.model_dump(), last_run=latest.get(item.id)).model_dump(), + **AutomationResponse( + **{ + **item.model_dump(), + 'data': item.data if item.user_id == user.id else hide_webhook_token(item.data), + }, + last_run=latest.get(item.id), + ).model_dump(), 'user_name': creators.get(item.user_id) or 'Unknown', 'can_edit': item.user_id == user.id, 'can_manage': item.user_id == user.id or has_write, diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py index 7fd1cb2081..3053931310 100644 --- a/backend/open_webui/tools/builtin.py +++ b/backend/open_webui/tools/builtin.py @@ -4552,10 +4552,18 @@ async def update_automation( return JSONCodec.dumps({'error': 'User context not available'}) try: - from open_webui.models.automations import AutomationData, AutomationForm, Automations, AutomationTarget + from open_webui.models.automations import ( + AutomationData, + AutomationForm, + Automations, + AutomationTarget, + AutomationTerminalConfig, + AutomationWebhook, + has_webhook, + ) from open_webui.models.users import Users from open_webui.routers.automations import check_automation_limits - from open_webui.utils.automations import next_n_runs_ns, next_run_ns, validate_rrule + from open_webui.utils.automations import schedule_next_run, schedule_next_runs, validate_rrule user_id = __user__.get('id') user = await Users.get_user_by_id(user_id) @@ -4583,15 +4591,18 @@ async def update_automation( except ValueError as e: return JSONCodec.dumps({'error': str(e)}) + if not new_rrule and not has_webhook(automation.data): + return JSONCodec.dumps({'error': 'An automation without a webhook needs a schedule'}) + # Validate RRULE if changed - if rrule is not None: + if rrule: try: await validate_rrule(new_rrule, tz=user.timezone) except ValueError as e: return JSONCodec.dumps({'error': f'Invalid schedule: {e}'}) try: - await check_automation_limits(__request__, user, new_rrule, None) + await check_automation_limits(__request__, user, new_rrule or None, None) except HTTPException as e: return JSONCodec.dumps({'error': e.detail}) @@ -4604,11 +4615,17 @@ async def update_automation( model_id=new_model_id, rrule=new_rrule, target=AutomationTarget(**automation.data['target']) if automation.data.get('target') else None, + terminal=AutomationTerminalConfig(**automation.data['terminal']) + if automation.data.get('terminal') + else None, + webhook=AutomationWebhook(**automation.data['webhook']) if automation.data.get('webhook') else None, ), is_active=automation.is_active, ) - updated = await Automations.update_by_id(automation_id, form, await next_run_ns(new_rrule, tz=tz)) + updated = await Automations.update_by_id( + automation_id, form, await schedule_next_run(form.data.model_dump(), tz=tz) + ) return JSONCodec.dumps( { @@ -4619,7 +4636,7 @@ async def update_automation( 'model_id': new_model_id, 'target': updated.data.get('target'), 'is_active': updated.is_active, - 'next_runs': await next_n_runs_ns(new_rrule, tz=tz), + 'next_runs': await schedule_next_runs(updated.data, tz=tz), }, ensure_ascii=False, ) @@ -4650,9 +4667,9 @@ async def list_automations( return JSONCodec.dumps({'error': 'User context not available'}) try: - from open_webui.models.automations import Automations + from open_webui.models.automations import Automations, has_webhook from open_webui.models.users import Users - from open_webui.utils.automations import next_n_runs_ns + from open_webui.utils.automations import schedule_next_runs user_id = __user__.get('id') user = await Users.get_user_by_id(user_id) @@ -4685,9 +4702,10 @@ async def list_automations( 'model_id': item.data.get('model_id', ''), 'target': item.data.get('target'), 'rrule': rrule, + 'webhook': has_webhook(item.data), 'is_active': item.is_active, 'last_run_at': item.last_run_at, - 'next_runs': await next_n_runs_ns(rrule, tz=user.timezone if user else None), + 'next_runs': await schedule_next_runs(item.data, tz=user.timezone if user else None), } ) @@ -4720,7 +4738,7 @@ async def toggle_automation( try: from open_webui.models.automations import Automations from open_webui.models.users import Users - from open_webui.utils.automations import next_run_ns + from open_webui.utils.automations import schedule_next_run user_id = __user__.get('id') user = await Users.get_user_by_id(user_id) @@ -4731,10 +4749,9 @@ async def toggle_automation( if automation.user_id != user_id: return JSONCodec.dumps({'error': 'Access denied'}) - rrule = automation.data.get('rrule', '') toggled = await Automations.toggle( automation_id, - await next_run_ns(rrule, tz=user.timezone if user else None), + await schedule_next_run(automation.data, tz=user.timezone if user else None), ) return JSONCodec.dumps( diff --git a/backend/open_webui/utils/automations.py b/backend/open_webui/utils/automations.py index 2d4cdee56f..05583f894e 100644 --- a/backend/open_webui/utils/automations.py +++ b/backend/open_webui/utils/automations.py @@ -47,6 +47,7 @@ from open_webui.utils.recurrence import ( rrule_interval_seconds, validate_rrule, ) +from open_webui.utils.prompt_variables import fill_variables from open_webui.utils.task import prompt_template from open_webui.utils.agents.discovery import get_models as get_agent_models from open_webui.utils.machines import initialize_terminal_directory, resolve_terminal_connection @@ -59,6 +60,17 @@ TIMER_POLL_INTERVAL = int(os.getenv('TIMER_POLL_INTERVAL', '1')) CALENDAR_ALERT_LOOKAHEAD_MINUTES = int(os.getenv('CALENDAR_ALERT_LOOKAHEAD_MINUTES', '10')) +# Schedule + + +async def schedule_next_run(data: dict, tz: str = None) -> Optional[int]: + return await next_run_ns(data['rrule'], tz=tz) if data.get('rrule') else None + + +async def schedule_next_runs(data: dict, tz: str = None) -> list[int]: + return await next_n_runs_ns(data['rrule'], tz=tz) if data.get('rrule') else [] + + # Worker Loop @@ -368,7 +380,7 @@ async def _execute_channel_automation( ) -async def execute_automation(app, automation: AutomationModel) -> None: +async def execute_automation(app, automation: AutomationModel, variables: Optional[dict] = None) -> None: """Execute an automation through the full chat completion pipeline. Creates a real chat or channel message, then calls chat_completion exactly like the frontend: @@ -394,7 +406,7 @@ async def execute_automation(app, automation: AutomationModel) -> None: await _record_run(request, automation.id, 'error', error=error, actor=user) return - prompt = await prompt_template(automation.data['prompt'], user) + prompt = fill_variables(await prompt_template(automation.data['prompt'], user), variables, strict=False) model_id = automation.data['model_id'] try: expires_delta = parse_duration(str(await Config.get('automations.auth_token_expires_in', '1h'))) diff --git a/backend/open_webui/utils/prompt_variables.py b/backend/open_webui/utils/prompt_variables.py new file mode 100644 index 0000000000..d8165a3f72 --- /dev/null +++ b/backend/open_webui/utils/prompt_variables.py @@ -0,0 +1,136 @@ +"""Prompt input variables, `{{name}}` / `{{name | type:prop=value}}`. Mirrors extractInputVariables in src/lib/utils.""" + +import json +import re +from typing import Any, Optional + +VARIABLE_PATTERN = re.compile(r'{{\s*([^|}\s]+)\s*(?:\|\s*([^}]+?)\s*)?}}') + +NUMBER_TYPES = {'number', 'range'} + + +class PromptVariableError(ValueError): + pass + + +def _split_properties(value: str, delimiter: str) -> list[str]: + parts, current, depth, in_string, escape = [], '', 0, False, False + for char in value: + if escape: + current += char + escape = False + continue + if char == '\\': + current += char + escape = True + continue + if char == '"': + in_string = not in_string + current += char + continue + if not in_string: + if char in '{[': + depth += 1 + elif char in '}]': + depth -= 1 + if char == delimiter and depth == 0: + parts.append(current) + current = '' + continue + current += char + if current: + parts.append(current) + return parts + + +def _parse_value(value: str) -> Any: + if value.startswith('"') and value.endswith('"'): + return value[1:-1] + try: + return json.loads(value) + except ValueError: + return value + + +def parse_definition(definition: Optional[str]) -> dict[str, Any]: + if not definition: + return {'type': 'text'} + first, *props = _split_properties(definition, ':') + first = first.strip() + result: dict[str, Any] = {'type': first[5:] if first.startswith('type=') else first} + for prop in props: + prop = prop.strip() + if not prop: + continue + name, *rest = _split_properties(prop, '=') + name = name.strip() + if not name: + continue + result[name] = _parse_value('='.join(rest).strip()) if rest else True + return result + + +def extract_variables(template: str) -> dict[str, dict[str, Any]]: + variables: dict[str, dict[str, Any]] = {} + for match in VARIABLE_PATTERN.finditer(template): + name, definition = match.group(1), match.group(2) + if definition or name not in variables: + variables[name] = parse_definition(definition) + return variables + + +def _lookup(values: dict[str, Any], name: str) -> Any: + if name in values: + return values[name] + current: Any = values + for part in name.split('.'): + if isinstance(current, dict) and part in current: + current = current[part] + elif isinstance(current, list) and part.isdigit() and int(part) < len(current): + current = current[int(part)] + else: + return None + return current + + +def _to_text(value: Any) -> str: + if isinstance(value, bool): + return 'true' if value else 'false' + if isinstance(value, (dict, list)): + return json.dumps(value, ensure_ascii=False) + return str(value) + + +def _check(name: str, definition: dict[str, Any], value: Any) -> None: + kind = definition.get('type') + if kind in NUMBER_TYPES and not isinstance(value, bool): + try: + float(value) + except (TypeError, ValueError): + raise PromptVariableError(f'Variable "{name}" must be a number') + options = definition.get('options') + if kind == 'select' and isinstance(options, list) and options and _to_text(value) not in map(_to_text, options): + raise PromptVariableError(f'Variable "{name}" must be one of: {", ".join(map(_to_text, options))}') + + +def fill_variables(template: str, values: Optional[dict[str, Any]] = None, *, strict: bool = True) -> str: + """Unmatched variables without a default stay as written.""" + values = values or {} + variables = extract_variables(template) + resolved: dict[str, str] = {} + missing = [] + for name, definition in variables.items(): + value = _lookup(values, name) + if value is None: + value = definition.get('default') + if value is None: + if definition.get('required'): + missing.append(name) + continue + if strict: + _check(name, definition, value) + resolved[name] = _to_text(value) + if strict and missing: + raise PromptVariableError(f'Missing required variable(s): {", ".join(missing)}') + # Single pass: values are never re-expanded. + return VARIABLE_PATTERN.sub(lambda m: resolved.get(m.group(1), m.group(0)), template) diff --git a/src/lib/apis/automations/index.ts b/src/lib/apis/automations/index.ts index 85adbb4fbc..011e0ba053 100644 --- a/src/lib/apis/automations/index.ts +++ b/src/lib/apis/automations/index.ts @@ -1,5 +1,6 @@ import type { AgentModel } from '$lib/stores'; import { WEBUI_API_BASE_URL } from '$lib/constants'; +import { extractInputVariables } from '$lib/utils'; export type AutomationTerminalConfig = { server_id: string; @@ -27,14 +28,36 @@ export const startsNew = (target?: AutomationTarget | null) => export const repliesInThread = (target?: AutomationTarget | null) => target?.reply_in_thread !== false; +export type AutomationWebhook = { + /** Set by the server. */ + token?: string | null; + allow_get?: boolean; +}; + export type AutomationData = { prompt: string; model_id: string; + /** Empty: no schedule. */ rrule: string; terminal?: AutomationTerminalConfig; target?: AutomationTarget | null; + webhook?: AutomationWebhook | null; }; +// Filled by the server, not the Run form. +const BUILTIN_VARIABLE = /^(CURRENT_[A-Z_]+|USER_[A-Z_]+|CLIPBOARD)$/; + +/** The prompt's input variables a manual run asks for. */ +export const getRunVariables = (prompt: string): Record => + Object.fromEntries( + Object.entries(extractInputVariables(prompt)).filter(([name]) => !BUILTIN_VARIABLE.test(name)) + ); + +export const getAutomationHookUrl = (automation: { id: string; data: AutomationData }) => + automation.data.webhook?.token + ? `${window.location.origin}${WEBUI_API_BASE_URL}/automations/hooks/${automation.id}/${automation.data.webhook.token}` + : ''; + export type AutomationForm = { name: string; folder_id?: string | null; @@ -252,10 +275,43 @@ export const toggleAutomationById = async (token: string, id: string) => { return res; }; -export const runAutomationById = async (token: string, id: string) => { +export const runAutomationById = async ( + token: string, + id: string, + variables?: Record +) => { let error = null; const res = await fetch(`${WEBUI_API_BASE_URL}/automations/${id}/run`, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + }, + ...(variables ? { body: JSON.stringify({ variables }) } : {}) + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + error = err.detail; + console.error(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const regenerateAutomationToken = async (token: string, id: string) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/automations/${id}/token/regenerate`, { method: 'POST', headers: { Accept: 'application/json', diff --git a/src/lib/components/AutomationModal.svelte b/src/lib/components/AutomationModal.svelte index 7c5872e5e1..290ec6a087 100644 --- a/src/lib/components/AutomationModal.svelte +++ b/src/lib/components/AutomationModal.svelte @@ -9,11 +9,12 @@ import ScheduleDropdown from '$lib/components/automations/ScheduleDropdown.svelte'; import ModelDropdown from '$lib/components/automations/ModelDropdown.svelte'; import TerminalDropdown from '$lib/components/automations/TerminalDropdown.svelte'; + import WebhookDropdown from '$lib/components/automations/WebhookDropdown.svelte'; import { getTerminalServers, type TerminalServer } 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, folders, type AgentModel } from '$lib/stores'; + import { baseModels, channels, config, folders, type AgentModel } from '$lib/stores'; import { createAutomation, @@ -51,6 +52,8 @@ let start_new = true; let reply_in_thread = true; let is_active = true; + let webhookEnabled = false; + let webhookAllowGet = false; let loading = false; let foldersLoaded = false; @@ -106,6 +109,7 @@ // Schedule dropdown ref let scheduleDropdown: ScheduleDropdown; + $: allowWebhook = !!$config?.features?.enable_automation_webhooks; const submitHandler = async () => { if (!name.trim() || !prompt.trim() || !model_id.trim()) { @@ -116,6 +120,10 @@ toast.error($i18n.t('Channel is required')); return; } + if (!scheduleDropdown.buildRrule() && !webhookEnabled) { + toast.error($i18n.t('Add a schedule or a webhook')); + return; + } if (scheduleDropdown?.frequency === 'ONCE') { const scheduled = new Date(`${scheduleDropdown.onceDate}T${scheduleDropdown.onceTime}`); if (scheduled <= new Date()) { @@ -132,6 +140,7 @@ prompt: prompt.trim(), model_id: model_id.trim(), rrule: scheduleDropdown.buildRrule(), + webhook: webhookEnabled ? { allow_get: webhookAllowGet } : null, terminal: terminalServerId ? { server_id: terminalServerId, cwd: terminalCwd.trim() || undefined } : undefined, @@ -188,9 +197,9 @@ start_new = startsNew(automation.data.target); reply_in_thread = repliesInThread(automation.data.target); is_active = automation.is_active; - if (scheduleDropdown) { - scheduleDropdown.parseRrule(automation.data.rrule); - } + webhookEnabled = !!automation.data.webhook; + webhookAllowGet = !!automation.data.webhook?.allow_get; + scheduleDropdown?.parseRrule(automation.data.rrule); } else if (cloneFrom) { name = cloneFrom.name; prompt = cloneFrom.data.prompt; @@ -207,9 +216,9 @@ start_new = startsNew(cloneFrom.data.target); reply_in_thread = repliesInThread(cloneFrom.data.target); is_active = true; - if (scheduleDropdown) { - scheduleDropdown.parseRrule(cloneFrom.data.rrule); - } + webhookEnabled = !!cloneFrom.data.webhook; + webhookAllowGet = !!cloneFrom.data.webhook?.allow_get; + scheduleDropdown?.parseRrule(cloneFrom.data.rrule); } else { name = ''; prompt = ''; @@ -220,6 +229,8 @@ start_new = true; reply_in_thread = true; is_active = true; + webhookEnabled = false; + webhookAllowGet = false; } initialized = true; }; @@ -268,7 +279,21 @@ class="flex flex-col sm:flex-row sm:items-center sm:justify-between px-4 pb-3.5 pt-1 gap-2" >
- + + + {#if allowWebhook || webhookEnabled} + + {/if} + {#if adminConfig.ENABLE_AUTOMATIONS} + + + + {/if} = {}; + const runNowHandler = async () => { if (loading) return; - loading = true; - const res = await runAutomationById(localStorage.token, automation.id).catch((err) => { + runVariables = getRunVariables(automation.data.prompt); + if (Object.keys(runVariables).length > 0) { + showVariablesModal = true; + return; + } + await run(); + }; + + const regenerateHookUrlHandler = async () => { + const res = await regenerateAutomationToken(localStorage.token, automation.id).catch((err) => { toast.error(`${err}`); return null; }); + if (res) { + automation = res; + toast.success($i18n.t('New URL created. The old one no longer works.')); + } + }; + + const run = async (variables?: Record) => { + loading = true; + const res = await runAutomationById(localStorage.token, automation.id, variables).catch( + (err) => { + toast.error(`${err}`); + return null; + } + ); if (res) { automation = res; toast.success($i18n.t('Automation triggered')); @@ -445,6 +490,13 @@
+ run(values)} +/> + + {#if allowWebhook || automation.data.webhook} +
+ {$i18n.t('Webhook')} +
+ +
+
+ {/if} +
{$i18n.t('Model')}
@@ -620,7 +692,7 @@
-
+
= {}; + let showVariablesModal = false; + const runNowHandler = async (automation: AutomationResponse) => { - const res = await runAutomationById(localStorage.token, automation.id).catch((err) => { - toast.error(`${err}`); - return null; - }); + runVariables = getRunVariables(automation.data.prompt); + if (Object.keys(runVariables).length > 0) { + runTarget = automation; + showVariablesModal = true; + return; + } + await run(automation); + }; + + const run = async (automation: AutomationResponse, variables?: Record) => { + const res = await runAutomationById(localStorage.token, automation.id, variables).catch( + (err) => { + toast.error(`${err}`); + return null; + } + ); if (res) { toast.success($i18n.t('Automation triggered')); } @@ -391,6 +409,13 @@ }} /> + runTarget && run(runTarget, values)} +/> +
- {formatSchedule(automation.data.rrule, $i18n)} · {formatDestination(automation)} + {formatTrigger(automation.data, $i18n)} · {formatDestination(automation)}
diff --git a/src/lib/components/automations/ScheduleDropdown.svelte b/src/lib/components/automations/ScheduleDropdown.svelte index 11e3d6e376..b448b3e8f8 100644 --- a/src/lib/components/automations/ScheduleDropdown.svelte +++ b/src/lib/components/automations/ScheduleDropdown.svelte @@ -16,6 +16,8 @@ export let onceDate = ''; export let onceTime = '09:00'; export let customRrule = ''; + /** Offer "None", for automations that run only on a webhook. */ + export let allowNone = false; export let side: 'top' | 'bottom' = 'top'; export let align: 'start' | 'end' = 'start'; @@ -28,6 +30,7 @@ let showDropdown = false; $: FREQUENCIES = [ + ...(allowNone || frequency === 'NONE' ? [{ key: 'NONE', label: $i18n.t('None') }] : []), { key: 'ONCE', label: $i18n.t('Once') }, { key: 'HOURLY', label: $i18n.t('Hourly') }, { key: 'DAILY', label: $i18n.t('Daily') }, @@ -49,7 +52,7 @@ let lastVisualFrequency = 'DAILY'; let prevFrequency = 'DAILY'; - $: if (frequency !== 'CUSTOM') { + $: if (frequency !== 'CUSTOM' && frequency !== 'NONE') { lastVisualFrequency = frequency; } @@ -87,6 +90,7 @@ }; export const buildRrule = (): string => { + if (frequency === 'NONE') return ''; if (frequency === 'CUSTOM') return customRrule; if (frequency === 'ONCE') { const dt = onceDate.replace(/-/g, '') + 'T' + onceTime.replace(/:/g, '') + '00'; @@ -108,6 +112,11 @@ }; export const parseRrule = (s: string) => { + if (!s.trim()) { + frequency = 'NONE'; + prevFrequency = 'NONE'; + return; + } const match = s.match(/DTSTART[^:]*:(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/i); // Detect ONCE (COUNT=1 with DTSTART) if (/COUNT=1(?!\d)/.test(s)) { @@ -225,7 +234,7 @@ on:input={onChange} />
- {:else if frequency !== 'HOURLY'} + {:else if frequency !== 'HOURLY' && frequency !== 'NONE'}
{#if frequency === 'ONCE'}
diff --git a/src/lib/components/automations/WebhookDropdown.svelte b/src/lib/components/automations/WebhookDropdown.svelte new file mode 100644 index 0000000000..cbc14840d3 --- /dev/null +++ b/src/lib/components/automations/WebhookDropdown.svelte @@ -0,0 +1,109 @@ + + + + + +
+
+ {$i18n.t('Webhook')} + +
+ + {#if enabled} +
+ {$i18n.t('Allow GET')} + +
+ +
+ {#if url} + +
+ + {#if onRegenerate} + + {/if} +
+ {:else} +
+ {$i18n.t('The URL appears once saved.')} +
+ {/if} +
+ {/if} +
+
diff --git a/src/lib/components/chat/Placeholder/FolderAutomations.svelte b/src/lib/components/chat/Placeholder/FolderAutomations.svelte index 6fef6f964a..cb1b900b31 100644 --- a/src/lib/components/chat/Placeholder/FolderAutomations.svelte +++ b/src/lib/components/chat/Placeholder/FolderAutomations.svelte @@ -6,7 +6,7 @@ import { socket } from '$lib/stores'; import { toggleAutomationById, type FolderAutomation } from '$lib/apis/automations'; import { formatShortDate } from '$lib/utils'; - import { formatSchedule } from '$lib/utils/schedule'; + import { formatTrigger } from '$lib/utils/schedule'; import AutomationModal from '$lib/components/AutomationModal.svelte'; import Switch from '$lib/components/common/Switch.svelte'; import Spinner from '$lib/components/common/Spinner.svelte'; @@ -98,7 +98,7 @@ >{automation.name} {formatTrigger(automation.data, $i18n)} + [data.rrule ? formatSchedule(data.rrule, i18n) : '', data.webhook ? i18n.t('Webhook') : ''] + .filter(Boolean) + .join(' + ') || i18n.t('None'); + export const formatSchedule = (rrule: string, i18n: I18n): string => { const match = rrule.match(/DTSTART[^:]*:(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/i); if (/COUNT=1(?!\d)/.test(rrule)) {