From 6378f94a65eacbd05765bb9ed83bed0e5a2a9921 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 14 Nov 2026 00:45:43 +0900 Subject: [PATCH] refac --- backend/open_webui/models/automations.py | 8 + backend/open_webui/models/chats.py | 1 + backend/open_webui/routers/automations.py | 30 +- backend/open_webui/routers/folders.py | 25 +- backend/open_webui/routers/templates.py | 7 + backend/open_webui/utils/agents/discovery.py | 2 +- backend/open_webui/utils/automations.py | 5 +- backend/open_webui/utils/terminals.py | 33 +- src/lib/apis/automations/index.ts | 25 + src/lib/components/AutomationModal.svelte | 12 +- .../automations/AutomationEditor.svelte | 28 +- .../automations/TerminalDropdown.svelte | 2 +- src/lib/components/chat/Chat.svelte | 9 +- src/lib/components/chat/FileNav.svelte | 2 +- src/lib/components/chat/MessageInput.svelte | 4 +- .../chat/MessageInput/TerminalMenu.svelte | 15 +- src/lib/components/chat/Placeholder.svelte | 7 +- .../chat/Placeholder/ChatList.svelte | 9 + .../chat/Placeholder/FolderAutomations.svelte | 119 ++++ .../chat/Placeholder/FolderBoard.svelte | 8 + .../chat/Placeholder/FolderPlaceholder.svelte | 587 ++++++++++-------- src/lib/components/chat/Tabs.svelte | 3 +- .../components/chat/UserTerminalsModal.svelte | 1 + src/lib/utils/folders.ts | 2 + 24 files changed, 657 insertions(+), 287 deletions(-) create mode 100644 src/lib/components/chat/Placeholder/FolderAutomations.svelte diff --git a/backend/open_webui/models/automations.py b/backend/open_webui/models/automations.py index 7f5707d78a..973eea2fa4 100644 --- a/backend/open_webui/models/automations.py +++ b/backend/open_webui/models/automations.py @@ -160,6 +160,14 @@ class AutomationTable: row = await db.get(Automation, id) return AutomationModel.model_validate(row) if row else None + async def get_by_folder(self, folder_id: str, db: Optional[AsyncSession] = None) -> list[AutomationModel]: + """Every automation that lives in a folder, whoever created it.""" + async with get_async_db_context(db) as db: + result = await db.execute( + select(Automation).filter_by(folder_id=folder_id).order_by(Automation.created_at.asc()) + ) + return [AutomationModel.model_validate(r) for r in result.scalars().all()] + async def get_active_by_user(self, user_id: str, db: Optional[AsyncSession] = None) -> list[AutomationModel]: """Get active automations for a user (for calendar RRULE expansion).""" async with get_async_db_context(db) as db: diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index bc4ba72a78..5bd373b116 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -2882,6 +2882,7 @@ class ChatTable: } # Tags are the owner's own records; status is folder workflow, so folder editors may set it. chat['can_edit_tags'] = chat['user_id'] == user_id + chat['automation_id'] = meta.get('automation_id') chat['can_edit_status'] = folder_write_access or chat['user_id'] == user_id # Only explain matches the title doesn't already show. chat['search_snippet'] = ( diff --git a/backend/open_webui/routers/automations.py b/backend/open_webui/routers/automations.py index f1800519fe..bc44410303 100644 --- a/backend/open_webui/routers/automations.py +++ b/backend/open_webui/routers/automations.py @@ -19,6 +19,7 @@ from open_webui.models.access_grants import AccessGrants, has_public_write_acces from open_webui.models.channels import Channels from open_webui.models.config import Config from open_webui.models.folders import Folders +from open_webui.utils.access_control.folders import has_folder_write_access from open_webui.utils.access_control import has_permission 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 @@ -96,16 +97,33 @@ async def check_automation_limits(request, user, rrule_str: str, db, is_create: async def check_automation_folder_access(folder_id: Optional[str], user, db: AsyncSession): + """An automation can live in any folder its creator can write to.""" if folder_id is None: return - folder = await Folders.get_folder_by_id_and_user_id(folder_id, user.id, db=db) - if not folder: + folder = await Folders.get_folder_by_id(folder_id, db=db) + if not folder or not (user.role == 'admin' or await has_folder_write_access(user.id, folder_id, db=db)): raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND, ) +async def check_automation_manage_access(automation, user, db: AsyncSession): + """Pausing, running and run history: the creator, or anyone who can write to its folder.""" + if automation and automation.user_id == user.id: + return + if ( + automation + and automation.folder_id + and (user.role == 'admin' or await has_folder_write_access(user.id, automation.folder_id, db=db)) + ): + return + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=ERROR_MESSAGES.NOT_FOUND, + ) + + async def check_automation_channel_access(form_data: AutomationForm, user, db: AsyncSession): target = form_data.data.target if not target or target.type != 'channel': @@ -324,7 +342,7 @@ async def toggle_automation_by_id( ): await check_automations_permission(request, user) automation = await Automations.get_by_id(id, db=db) - check_automation_access(automation, user) + 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) await publish_event( @@ -350,7 +368,7 @@ async def run_automation_by_id( ): await check_automations_permission(request, user) automation = await Automations.get_by_id(id, db=db) - check_automation_access(automation, user) + await check_automation_manage_access(automation, user, db) automation = await Automations.update_last_run_at(automation.id, db=db) asyncio.create_task(execute_automation(request.app, automation)) await publish_event( @@ -403,7 +421,7 @@ async def get_automation_runs( ): await check_automations_permission(request, user) automation = await Automations.get_by_id(id, db=db) - check_automation_access(automation, user) + await check_automation_manage_access(automation, user, db) return await AutomationRuns.get_by_automation(id, skip=skip, limit=limit, db=db) @@ -419,7 +437,7 @@ async def get_automation_run( await check_automations_permission(request, user) automation = await Automations.get_by_id(id, db=db) - check_automation_access(automation, user) + await check_automation_manage_access(automation, user, db) run = await db.get(AutomationRun, run_id) if not run or run.automation_id != id: raise HTTPException(404, 'Run not found') diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py index 0801423682..7a2e8d309d 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 Automations +from open_webui.models.automations import AutomationResponse, AutomationRuns, Automations from open_webui.models.chat_messages import ChatMessages from open_webui.models.chats import Chats from open_webui.models.config import Config @@ -743,6 +743,29 @@ async def check_folder_read_access(request: Request, id: str, user, db: AsyncSes return folder +@router.get('/{id}/automations') +async def get_folder_automations( + request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + """The folder's automations, whoever made them. Only creators edit; folder editors may pause and run.""" + folder = await check_folder_read_access(request, id, user, db) + automations = await Automations.get_by_folder(id, db=db) + if not automations: + return [] + latest = await AutomationRuns.get_latest_batch([item.id for item in automations], db=db) + creators = {u.id: u.name for u in await Users.get_users_by_user_ids(list({a.user_id for a in automations}), db=db)} + has_write = user.role == 'admin' or folder.user_id == user.id or await _has_folder_access(user.id, folder, 'write', db) + return [ + { + **AutomationResponse(**item.model_dump(), 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, + } + for item in automations + ] + + @router.get('/{id}/users') async def get_folder_users(request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): await check_folder_read_access(request, id, user, db) diff --git a/backend/open_webui/routers/templates.py b/backend/open_webui/routers/templates.py index a0fccd9fd0..ee6ecd4e11 100644 --- a/backend/open_webui/routers/templates.py +++ b/backend/open_webui/routers/templates.py @@ -35,6 +35,7 @@ class ShareForm(BaseModel): class InstanceForm(BaseModel): user_id: str | None = Field(default=None, min_length=1) chat_id: str | None = None + folder_id: str | None = None model_id: str | None = None @@ -169,6 +170,7 @@ async def current_instance( @router.get('/{terminal_id}/instances') async def list_instances(terminal_id: str, user=Depends(get_verified_user)): from open_webui.models.chats import Chats + from open_webui.models.folders import Folders from open_webui.models.models import Models from open_webui.models.users import Users @@ -182,6 +184,11 @@ async def list_instances(terminal_id: str, user=Depends(get_verified_user)): owner = await Users.get_user_by_id(chat.user_id) if chat else None row['label'] = chat.title if chat else None row['user_name'] = owner.name if owner else None + elif kind == 'folder': + folder = await Folders.get_folder_by_id(value) + owner = await Users.get_user_by_id(folder.user_id) if folder else None + row['label'] = folder.name if folder else None + row['user_name'] = owner.name if owner else None elif kind == 'user': owner = await Users.get_user_by_id(value) row['label'] = owner.name if owner else None diff --git a/backend/open_webui/utils/agents/discovery.py b/backend/open_webui/utils/agents/discovery.py index 5332cfdfe5..bc039c94f4 100644 --- a/backend/open_webui/utils/agents/discovery.py +++ b/backend/open_webui/utils/agents/discovery.py @@ -14,7 +14,7 @@ def model_controls(model): 'Reasoning effort', 'supportedReasoningEfforts', 'reasoningEffort', - 'reasoningEffort', + 'label', 'defaultReasoningEffort', ), ('service_tier', 'Service tier', 'serviceTiers', 'id', 'name', 'defaultServiceTier'), diff --git a/backend/open_webui/utils/automations.py b/backend/open_webui/utils/automations.py index e920b2c0f6..b47c50a5a2 100644 --- a/backend/open_webui/utils/automations.py +++ b/backend/open_webui/utils/automations.py @@ -33,6 +33,7 @@ from open_webui.models.automations import AutomationModel, AutomationRuns, Autom from open_webui.models.chats import ChatForm, Chats from open_webui.models.config import Config from open_webui.models.folders import Folders +from open_webui.utils.access_control.folders import has_folder_write_access from open_webui.models.messages import MessageForm from open_webui.models.users import Users from open_webui.utils.auth import create_token @@ -393,8 +394,9 @@ async def execute_automation(app, automation: AutomationModel) -> None: await _execute_channel_automation(app, automation, user, prompt, model_id, token) return + # Runs land in the automation's folder while its creator can still write there. folder_id = automation.folder_id - if folder_id and not await Folders.get_folder_by_id_and_user_id(folder_id, automation.user_id): + if folder_id and not await has_folder_write_access(automation.user_id, folder_id): await Automations.clear_folder_ids(automation.user_id, [folder_id]) folder_id = None @@ -441,6 +443,7 @@ async def execute_automation(app, automation: AutomationModel) -> None: 'meta': {'automation_id': automation.id}, }, ), + internal_meta={'automation_id': automation.id}, ) if not chat: diff --git a/backend/open_webui/utils/terminals.py b/backend/open_webui/utils/terminals.py index 79130da6cd..c21e30e22a 100644 --- a/backend/open_webui/utils/terminals.py +++ b/backend/open_webui/utils/terminals.py @@ -192,7 +192,10 @@ async def list_template_connections(user, connections): class MissingTerminalContext(HTTPException): def __init__(self, scope): - detail = 'This terminal requires a saved chat' if scope == 'chat' else f'This terminal requires a {scope}' + detail = { + 'chat': 'This terminal requires a saved chat', + 'folder': 'This terminal requires a chat in a folder', + }.get(scope, f'This terminal requires a {scope}') super().__init__(409, detail) @@ -200,17 +203,21 @@ def get_terminal_context(template, user_id, metadata=None): """Validate a template's scope and return context for its environment.""" metadata = metadata or {} scope = (template.get('data') or {}).get('scope') - if scope not in (None, 'user', 'chat', 'model'): + if scope not in (None, 'user', 'chat', 'folder', 'model'): raise HTTPException(422, 'Invalid template scope') chat_id = metadata.get('chat_id') + folder_id = metadata.get('folder_id') model_id = metadata.get('model_id') or metadata.get('model') if scope == 'chat' and not is_saved_chat_id(chat_id): raise MissingTerminalContext(scope) + if scope == 'folder' and not folder_id: + raise MissingTerminalContext(scope) if scope == 'model' and not model_id: raise MissingTerminalContext(scope) return { 'user_id': user_id, 'chat_id': chat_id if is_saved_chat_id(chat_id) else None, + 'folder_id': folder_id if scope == 'folder' else None, 'model_id': model_id if scope == 'model' else None, } @@ -253,6 +260,8 @@ def terminal_headers(connection): } if context.get('chat_id'): headers['X-Terminal-Chat-Id'] = context['chat_id'] + if context.get('folder_id'): + headers['X-Terminal-Folder-Id'] = context['folder_id'] if context.get('model_id'): headers['X-Terminal-Model-Id'] = context['model_id'] return headers @@ -323,11 +332,25 @@ async def find_terminal_connection(user, terminal_id, metadata=None, request=Non if stored and stored != terminal_id: raise HTTPException(409, 'Chat terminal selection changed; refresh the chat') + folder = None + if scope == 'folder': + # The folder comes from the saved chat, never from the request. + metadata['folder_id'] = None + if chat and chat.folder_id: + from open_webui.models.folders import Folders + from open_webui.utils.access_control.folders import has_folder_access + + folder = await Folders.get_folder_by_id(chat.folder_id) + if folder is None or not await has_folder_access(user.id, folder, 'write', None): + raise HTTPException(403, 'Folder access denied') + metadata['folder_id'] = folder.id + principal = instance_user - if not shared_session and scope == 'chat' and chat: - owner = user if chat.user_id == user.id else await Users.get_user_by_id(chat.user_id) + if not shared_session and scope in ('chat', 'folder') and chat: + owner_id = folder.user_id if folder else chat.user_id + owner = user if owner_id == user.id else await Users.get_user_by_id(owner_id) if owner is None: - raise HTTPException(403, 'Chat owner is unavailable') + raise HTTPException(403, f"{'Folder' if folder else 'Chat'} owner is unavailable") if ( owner.id != instance_user.id and not await has_connection_access(owner, connection) diff --git a/src/lib/apis/automations/index.ts b/src/lib/apis/automations/index.ts index 6f51c5aaaf..a3fde62242 100644 --- a/src/lib/apis/automations/index.ts +++ b/src/lib/apis/automations/index.ts @@ -327,3 +327,28 @@ export const getAutomationRuns = async ( return res; }; + +/** An automation listed in a folder, with what the viewer may do with it. */ +export type FolderAutomation = AutomationResponse & { + user_name: string; + can_edit: boolean; + can_manage: boolean; +}; + +export const getFolderAutomations = async ( + token: string, + folderId: string +): Promise => { + const res = await fetch( + `${WEBUI_API_BASE_URL}/folders/${encodeURIComponent(folderId)}/automations`, + { + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + } + } + ); + if (!res.ok) throw (await res.json().catch(() => ({})))?.detail ?? res.statusText; + return res.json(); +}; diff --git a/src/lib/components/AutomationModal.svelte b/src/lib/components/AutomationModal.svelte index bf415c2092..9e824fcf81 100644 --- a/src/lib/components/AutomationModal.svelte +++ b/src/lib/components/AutomationModal.svelte @@ -29,6 +29,8 @@ export let show = false; export let automation: AutomationResponse | null = null; export let cloneFrom: AutomationResponse | null = null; + /** Folder a new automation starts in. */ + export let folderId: string | null = null; let name = ''; let prompt = ''; @@ -201,7 +203,7 @@ name = ''; prompt = ''; model_id = ''; - folder_id = ''; + folder_id = folderId ?? ''; target_type = 'chat'; channel_id = ''; is_active = true; @@ -214,12 +216,12 @@ } - +
-
+