From 4116a5bffee31f42a0cb5b9686d2a9c8903776a0 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 4 Dec 2026 07:30:14 +0400 Subject: [PATCH] refac --- backend/open_webui/main.py | 72 +++--- backend/open_webui/models/chats.py | 4 +- backend/open_webui/routers/channels.py | 4 +- backend/open_webui/routers/chats.py | 26 +- backend/open_webui/routers/folders.py | 8 +- backend/open_webui/routers/scim.py | 4 +- backend/open_webui/routers/users.py | 4 +- backend/open_webui/{tasks.py => runs.py} | 229 +++++++++--------- backend/open_webui/socket/main.py | 22 +- backend/open_webui/socket/utils.py | 4 +- backend/open_webui/utils/agents/output.py | 2 +- backend/open_webui/utils/apps.py | 4 +- backend/open_webui/utils/middleware.py | 2 +- backend/open_webui/utils/subagents.py | 18 +- backend/open_webui/utils/timers.py | 4 +- .../chat/Settings/About/NightSky.svelte | 30 +++ 16 files changed, 234 insertions(+), 203 deletions(-) rename backend/open_webui/{tasks.py => runs.py} (53%) diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index 140ef4907e..855ddcc914 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -210,18 +210,18 @@ from open_webui.socket.main import ( from open_webui.socket.main import ( app as socket_app, ) -from open_webui.tasks import ( - cleanup_task, - create_task, +from open_webui.runs import ( + cleanup_run, + create_run, get_response_streams_by_chat_id, - has_active_tasks, - list_task_ids_by_item_id, - list_tasks, - redis_task_command_listener, - redis_task_heartbeat, - stop_item_tasks, - stop_task, -) # Import from tasks.py + has_active_runs, + list_run_ids_by_item_id, + list_runs, + redis_run_command_listener, + redis_run_heartbeat, + stop_item_runs, + stop_run, +) from open_webui.utils import logger from open_webui.utils.access_control import has_permission from open_webui.utils.access_control.folders import has_folder_write_access @@ -441,9 +441,9 @@ async def lifespan(app: FastAPI): await app_connections.start(app.state.redis) if app.state.redis is not None: - app.state.redis_task_command_listener = asyncio.create_task(redis_task_command_listener(app)) + app.state.redis_run_command_listener = asyncio.create_task(redis_run_command_listener(app)) if REDIS_TASK_TTL > 0: - app.state.redis_task_heartbeat = asyncio.create_task(redis_task_heartbeat(app)) + app.state.redis_run_heartbeat = asyncio.create_task(redis_run_heartbeat(app)) if WEBSOCKET_MANAGER == 'redis': # socket.io only starts listening on its first connect; event call answers need it earlier @@ -541,11 +541,11 @@ async def lifespan(app: FastAPI): await close_session() - if hasattr(app.state, 'redis_task_command_listener'): - app.state.redis_task_command_listener.cancel() + if hasattr(app.state, 'redis_run_command_listener'): + app.state.redis_run_command_listener.cancel() - if hasattr(app.state, 'redis_task_heartbeat'): - app.state.redis_task_heartbeat.cancel() + if hasattr(app.state, 'redis_run_heartbeat'): + app.state.redis_run_heartbeat.cancel() if hasattr(app.state, 'prefetch_tool_servers'): app.state.prefetch_tool_servers.cancel() @@ -1886,8 +1886,8 @@ async def chat_completion( chat_id = metadata.get('chat_id') run_id = metadata.get('run_id') if chat_id and run_id: - await cleanup_task(request.app.state.redis, run_id, chat_id) - if not await has_active_tasks(request.app.state.redis, chat_id): + await cleanup_run(request.app.state.redis, run_id, chat_id) + if not await has_active_runs(request.app.state.redis, chat_id): event_emitter = await get_event_emitter(metadata, update_db=False) if event_emitter: try: @@ -1912,7 +1912,7 @@ async def chat_completion( if ( chat_id and getattr(request.state, 'internal', False) is not True - and not await has_active_tasks(request.app.state.redis, chat_id) + and not await has_active_runs(request.app.state.redis, chat_id) ): from open_webui.utils.subagents import get_pending_run, process_pending_internal_messages @@ -1924,7 +1924,7 @@ async def chat_completion( # Fan out: one task per model if metadata.get('session_id') and metadata.get('chat_id'): - chat_tasks = {} + chat_runs = {} subagent_results = [] is_internal = getattr(request.state, 'internal', False) is True chat_id = metadata['chat_id'] @@ -1979,13 +1979,13 @@ async def chat_completion( subagent_results.append(await process) continue - run_id, task = await create_task( + run_id, task = await create_run( request.app.state.redis, process, id=chat_id, - task_id=per_model_metadata['run_id'], + run_id=per_model_metadata['run_id'], ) - chat_tasks[run_id] = task + chat_runs[run_id] = task if is_internal: return { @@ -1996,7 +1996,7 @@ async def chat_completion( } # Emit chat:active=true - if chat_tasks: + if chat_runs: event_emitter = await get_event_emitter( {**metadata, 'message_id': message_ids[0]['message_id']}, update_db=False, @@ -2007,11 +2007,11 @@ async def chat_completion( # Automation chat runs must finish before their caller records success. if metadata.get('automation_id'): - await asyncio.gather(*chat_tasks.values()) + await asyncio.gather(*chat_runs.values()) return { 'status': True, - 'run_ids': list(chat_tasks), + 'run_ids': list(chat_runs), 'chat_id': chat_id, } else: @@ -2271,7 +2271,7 @@ async def chat_action(request: Request, action_id: str, form_data: dict, user=De @app.post('/api/v1/runs/{run_id}/cancel') async def cancel_run_endpoint(request: Request, run_id: str, user=Depends(get_admin_user)): try: - result = await stop_task(request.app.state.redis, run_id) + result = await stop_run(request.app.state.redis, run_id) return result except ValueError as e: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) @@ -2279,7 +2279,7 @@ async def cancel_run_endpoint(request: Request, run_id: str, user=Depends(get_ad @app.get('/api/v1/runs') async def list_runs_endpoint(request: Request, user=Depends(get_admin_user)): - return {'runs': await list_tasks(request.app.state.redis)} + return {'runs': await list_runs(request.app.state.redis)} @app.get('/api/v1/chats/{chat_id:path}/runs') @@ -2295,7 +2295,7 @@ async def list_runs_by_chat_id_endpoint(request: Request, chat_id: str, user=Dep if chat is None: return {'run_ids': []} - run_ids = await list_task_ids_by_item_id(request.app.state.redis, chat_id) + run_ids = await list_run_ids_by_item_id(request.app.state.redis, chat_id) if not socket_id: run_ids = await Chats.filter_run_ids_by_user_id(chat, user.id, run_ids) @@ -2317,7 +2317,7 @@ async def resume_temporary_chat(request: Request, chat_id: str, form_data: dict, ): raise HTTPException(status_code=404, detail='Temporary chat expired or unavailable') return { - 'run_ids': await list_task_ids_by_item_id(request.app.state.redis, chat_id), + 'run_ids': await list_run_ids_by_item_id(request.app.state.redis, chat_id), 'streams': await get_response_streams_by_chat_id(request.app.state.redis, chat_id), } @@ -2336,16 +2336,16 @@ async def cancel_runs_by_chat_id_endpoint(request: Request, chat_id: str, user=D if chat is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) if socket_id: - result = await stop_item_tasks(request.app.state.redis, chat_id) + result = await stop_item_runs(request.app.state.redis, chat_id) else: run_ids = await Chats.filter_run_ids_by_user_id( - chat, user.id, await list_task_ids_by_item_id(request.app.state.redis, chat_id) + chat, user.id, await list_run_ids_by_item_id(request.app.state.redis, chat_id) ) - result = {'status': True, 'message': 'No tasks found.'} + result = {'status': True, 'message': 'No runs found.'} for run_id in run_ids: - result = await stop_task(request.app.state.redis, run_id) + result = await stop_run(request.app.state.redis, run_id) - if not socket_id and str(result.get('message', '')).startswith('No tasks found'): + if not socket_id and str(result.get('message', '')).startswith('No runs found'): messages_map = await Chats.get_messages_map_by_chat_id(chat_id) or {} for message_id, message in messages_map.items(): if (message.get('user_id') or chat.user_id) != user.id: diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index 01da4b971f..14dbf62ea2 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -21,7 +21,7 @@ from open_webui.models.automations import AutomationRun from open_webui.models.chat_messages import ChatMessage, ChatMessages from open_webui.models.folders import Folders from open_webui.models.tags import Tags, delete_resource_tags, get_tag_id, resource_tag_filter -from open_webui.tasks import has_active_tasks +from open_webui.runs import has_active_runs from open_webui.utils.misc import get_output_text, sanitize_data_for_db, sanitize_text_for_db from open_webui.utils.session_records import has_pending_tool_approval from pydantic import BaseModel, ConfigDict, field_validator @@ -2648,7 +2648,7 @@ class ChatTable: conditions.append(Chat.id.in_(pending_ids)) else: active_ids = { - chat_id for chat_id in {row[0] for row in unfinished} if await has_active_tasks(redis, chat_id) + chat_id for chat_id in {row[0] for row in unfinished} if await has_active_runs(redis, chat_id) } if activity == 'generating': conditions.append(Chat.id.in_(active_ids - pending_ids)) diff --git a/backend/open_webui/routers/channels.py b/backend/open_webui/routers/channels.py index 58d1b85dba..8a4cbc06aa 100644 --- a/backend/open_webui/routers/channels.py +++ b/backend/open_webui/routers/channels.py @@ -49,7 +49,7 @@ from open_webui.socket.main import ( leave_room_for_users, sio, ) -from open_webui.tasks import create_task +from open_webui.runs import create_run from open_webui.utils.access_control import filter_allowed_access_grants, has_permission, validate_access_grants from open_webui.utils.apps import ( check_app_channel_access, @@ -1508,7 +1508,7 @@ async def post_new_message( # holding database connections during slow operations (e.g., LLM calls). async def background_handler(): active_user_ids = await get_user_ids_from_room(f'channel:{channel.id}') - await create_task(None, app_channel_reply_handler(channel.id, message.id, user.id)) + await create_run(None, app_channel_reply_handler(channel.id, message.id, user.id)) await model_response_handler(request, channel, message, user) await send_notification( request, diff --git a/backend/open_webui/routers/chats.py b/backend/open_webui/routers/chats.py index 1cc8d2a47e..5c52a7a671 100644 --- a/backend/open_webui/routers/chats.py +++ b/backend/open_webui/routers/chats.py @@ -47,11 +47,11 @@ from open_webui.models.shared_chats import ChatShareMode, ShareChatForm, SharedC from open_webui.models.tags import TagModel, Tags, get_tag_id from open_webui.models.users import UserModel from open_webui.socket.main import get_event_emitter -from open_webui.tasks import ( +from open_webui.runs import ( get_response_streams_by_chat_id, - has_active_tasks, - list_task_ids_by_item_id, - stop_item_tasks, + has_active_runs, + list_run_ids_by_item_id, + stop_item_runs, ) from open_webui.utils.access_control import has_permission, validate_access_grants from open_webui.utils.access_control.folders import has_folder_move_access, has_folder_write_access @@ -237,7 +237,7 @@ async def add_active_state_to_chat_list( for chat in chat_list: chat.pending_approval = chat.id in pending_approval_ids chat.active = False - if not await has_active_tasks(request.app.state.redis, chat.id): + if not await has_active_runs(request.app.state.redis, chat.id): continue chat.active = await ChatMessages.has_unfinished_assistant_by_chat_id(chat.id, db=db) @@ -857,7 +857,7 @@ async def delete_all_user_chats( if result: # Delete first so stopped sub-agents have no chat to report back to. for chat_id in chat_ids: - await stop_item_tasks(request.app.state.redis, chat_id) + await stop_item_runs(request.app.state.redis, chat_id) await publish_event( request, @@ -1434,7 +1434,7 @@ async def compact_chat_by_id( if not chat: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND) - if await has_active_tasks(request.app.state.redis, id): + if await has_active_runs(request.app.state.redis, id): raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail='Wait for the current response to finish before compacting.', @@ -1493,7 +1493,7 @@ async def get_chat_children(request: Request, id: str, user=Depends(get_verified if child.id in waiting_ids: status = 'waiting' # Its task goes on after its reply, to hand over the report. - elif await has_active_tasks( + elif await has_active_runs( request.app.state.redis, child.id ) and await ChatMessages.has_unfinished_assistant_by_chat_id(child.id): status = 'running' @@ -1576,7 +1576,7 @@ async def get_chat_by_id( data['context_usage'] = await get_chat_context_usage(chat) data['run_ids'] = ( await Chats.filter_run_ids_by_user_id( - chat, user.id, await list_task_ids_by_item_id(request.app.state.redis, id) + chat, user.id, await list_run_ids_by_item_id(request.app.state.redis, id) ) if data['write_access'] else [] @@ -1943,7 +1943,7 @@ async def delete_chat_by_id( # Cancel any in-flight LLM tasks (streaming, title/tags generation) before # deleting the chat to prevent orphaned requests. - await stop_item_tasks(request.app.state.redis, id) + await stop_item_runs(request.app.state.redis, id) # Delete first so stopped sub-agents have no chat to report back to. if user.role == 'admin': @@ -1953,7 +1953,7 @@ async def delete_chat_by_id( # Cascade to internal child chats spawned from this one. for child_id in await Chats.get_internal_chat_ids_by_parent_id(id, chat.user_id): - await stop_item_tasks(request.app.state.redis, child_id) + await stop_item_runs(request.app.state.redis, child_id) await Chats.delete_chat_by_id_and_user_id(child_id, chat.user_id) if result: @@ -2031,7 +2031,7 @@ async def fork_chat_by_id( is_snapshot = chat.id == chat.share_id is_owner = chat.user_id == user.id - if not is_snapshot and await has_active_tasks(request.app.state.redis, chat.id): + if not is_snapshot and await has_active_runs(request.app.state.redis, chat.id): raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail='Wait for the current response to finish before forking.', @@ -2297,7 +2297,7 @@ async def archive_chat_by_id( response = await chat_response(chat, db=db) if chat.archived: # Cancel any in-flight LLM tasks before archiving - await stop_item_tasks(request.app.state.redis, id) + await stop_item_runs(request.app.state.redis, id) else: # Unarchived — ensure tag rows exist await Tags.ensure_tags_exist(response.meta.get('tags', []), user.id, db=db) diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py index f4b29d5f1f..0e8325daf0 100644 --- a/backend/open_webui/routers/folders.py +++ b/backend/open_webui/routers/folders.py @@ -36,7 +36,7 @@ from open_webui.models.users import Users from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT from open_webui.routers.notes import check_notes_access, truncate_note_data from open_webui.socket.main import close_note -from open_webui.tasks import has_active_tasks, stop_item_tasks +from open_webui.runs import has_active_runs, stop_item_runs from open_webui.utils.access_control import ( has_permission, validate_access_grants, @@ -200,7 +200,7 @@ async def get_active_folders( for chat_id, (folder_id, waiting, updated_at) in active_chats.items(): if waiting: active[folder_id].waiting = True - elif await has_active_tasks(request.app.state.redis, chat_id): + elif await has_active_runs(request.app.state.redis, chat_id): active[folder_id].running = True else: continue @@ -787,7 +787,7 @@ async def get_shared_folder_chats( chat['pending_approval'] = chat['id'] in pending_approval_ids if chat['user_id'] != user.id: chat['last_read_at'] = chat['updated_at'] - if await has_active_tasks(request.app.state.redis, chat['id']): + if await has_active_runs(request.app.state.redis, chat['id']): chat['active'] = await ChatMessages.has_unfinished_assistant_by_chat_id(chat['id'], db=db) response = { @@ -1132,7 +1132,7 @@ async def delete_folder_by_id( # Delete first so stopped sub-agents have no chat to report back to. await Chats.delete_chats_by_user_id_and_folder_id(folder_owner_id, folder_id, db=db) for chat_id in chat_ids: - await stop_item_tasks(request.app.state.redis, chat_id) + await stop_item_runs(request.app.state.redis, chat_id) for note in await Notes.get_notes_by_folder_id_and_user_id(folder_id, folder_owner_id, db=db): await Notes.delete_note_by_id(note.id, db=db) for chat_id in await Chats.get_internal_chat_ids_by_note_id(note.id, db=db): diff --git a/backend/open_webui/routers/scim.py b/backend/open_webui/routers/scim.py index 26351bc481..ddf9f23efe 100644 --- a/backend/open_webui/routers/scim.py +++ b/backend/open_webui/routers/scim.py @@ -24,7 +24,7 @@ from open_webui.models.auths import Auths from open_webui.models.chats import Chats from open_webui.models.groups import GroupModel, Groups, GroupHierarchyError from open_webui.models.users import UserModel, Users -from open_webui.tasks import stop_item_tasks +from open_webui.runs import stop_item_runs from open_webui.utils.auth import ( decode_token, get_admin_user, @@ -889,7 +889,7 @@ async def delete_user( # Delete first so stopped sub-agents have no chat to report back to. for chat_id in chat_ids: - await stop_item_tasks(request.app.state.redis, chat_id) + await stop_item_runs(request.app.state.redis, chat_id) await publish_event( request, diff --git a/backend/open_webui/routers/users.py b/backend/open_webui/routers/users.py index 2b84ba26c0..cf6305a9de 100644 --- a/backend/open_webui/routers/users.py +++ b/backend/open_webui/routers/users.py @@ -43,7 +43,7 @@ from open_webui.models.knowledge import Knowledges from open_webui.models.models import Models from open_webui.models.tools import Tools from open_webui.storage.provider import Storage -from open_webui.tasks import stop_item_tasks +from open_webui.runs import stop_item_runs from open_webui.utils.access_control import fill_missing_permissions, get_permissions, has_permission from open_webui.utils.auth import ( create_api_key, @@ -1236,7 +1236,7 @@ async def delete_user_by_id( if result: # Delete first so stopped sub-agents have no chat to report back to. for chat_id in chat_ids: - await stop_item_tasks(request.app.state.redis, chat_id) + await stop_item_runs(request.app.state.redis, chat_id) await publish_event( request, diff --git a/backend/open_webui/tasks.py b/backend/open_webui/runs.py similarity index 53% rename from backend/open_webui/tasks.py rename to backend/open_webui/runs.py index 53781438ea..c91af766e0 100644 --- a/backend/open_webui/tasks.py +++ b/backend/open_webui/runs.py @@ -1,4 +1,4 @@ -# tasks.py +# runs.py: background runs (model replies, sub-agents, saves) tracked per item, locally and in Redis. import asyncio import logging from contextlib import suppress @@ -15,21 +15,22 @@ from open_webui.utils.response import get_response_delta_key, handle_responses_s log = logging.getLogger(__name__) -# A dictionary to keep track of active tasks -tasks: dict[str, asyncio.Task] = {} -item_tasks = {} +# Active runs on this instance, by run id +runs: dict[str, asyncio.Task] = {} +item_runs = {} response_streams: dict[str, dict] = {} -REDIS_TASKS_KEY = f'{REDIS_KEY_PREFIX}:tasks' -REDIS_ITEM_TASKS_KEY = f'{REDIS_KEY_PREFIX}:tasks:item' +# The keys keep their old ':tasks' names, so runs in flight survive an upgrade. +REDIS_RUNS_KEY = f'{REDIS_KEY_PREFIX}:tasks' +REDIS_ITEM_RUNS_KEY = f'{REDIS_KEY_PREFIX}:tasks:item' REDIS_RESPONSE_STREAMS_KEY = f'{REDIS_KEY_PREFIX}:tasks:response_streams' REDIS_PUBSUB_CHANNEL = f'{REDIS_KEY_PREFIX}:tasks:commands' REDIS_PUBSUB_RECONNECT_INTERVAL = 1.0 REDIS_PUBSUB_MAX_RECONNECT_INTERVAL = 30.0 -async def redis_task_command_listener(app): +async def redis_run_command_listener(app): redis: Redis = app.state.redis reconnect_interval = REDIS_PUBSUB_RECONNECT_INTERVAL @@ -51,16 +52,16 @@ async def redis_task_command_listener(app): if command.get('action') != 'stop': continue - local_task = tasks.get(command.get('task_id')) - if local_task: - local_task.cancel() + local_run = runs.get(command.get('run_id')) + if local_run: + local_run.cancel() except Exception as e: - log.exception(f'Error handling distributed task command: {e}') - log.warning('Redis task command listener stopped. Retrying.') + log.exception(f'Error handling distributed run command: {e}') + log.warning('Redis run command listener stopped. Retrying.') except asyncio.CancelledError: raise except Exception as e: - log.exception(f'Redis task command listener failed. Retrying: {e}') + log.exception(f'Redis run command listener failed. Retrying: {e}') finally: if pubsub: with suppress(Exception): @@ -70,63 +71,63 @@ async def redis_task_command_listener(app): reconnect_interval = min(reconnect_interval * 2, REDIS_PUBSUB_MAX_RECONNECT_INTERVAL) -async def redis_task_heartbeat(app): +async def redis_run_heartbeat(app): redis: Redis = app.state.redis while True: await asyncio.sleep(REDIS_TASK_TTL / 4) try: pipe = redis.pipeline(transaction=False) - for task_id in list(tasks): - # EXPIRE cannot recreate a task already removed by cleanup. - pipe.expire(f'{REDIS_TASKS_KEY}:{task_id}', REDIS_TASK_TTL) + for run_id in list(runs): + # EXPIRE cannot recreate a run already removed by cleanup. + pipe.expire(f'{REDIS_RUNS_KEY}:{run_id}', REDIS_TASK_TTL) await pipe.execute() except Exception: - log.exception('Redis task heartbeat failed') + log.exception('Redis run heartbeat failed') # Redis-enabled handlers -async def redis_save_task(redis: Redis, task_id: str, item_id: str | None): +async def redis_save_run(redis: Redis, run_id: str, item_id: str | None): pipe = redis.pipeline(transaction=False) - pipe.set(f'{REDIS_TASKS_KEY}:{task_id}', '1', ex=REDIS_TASK_TTL or None) - pipe.hset(REDIS_TASKS_KEY, task_id, item_id or '') + pipe.set(f'{REDIS_RUNS_KEY}:{run_id}', '1', ex=REDIS_TASK_TTL or None) + pipe.hset(REDIS_RUNS_KEY, run_id, item_id or '') if item_id: - pipe.sadd(f'{REDIS_ITEM_TASKS_KEY}:{item_id}', task_id) + pipe.sadd(f'{REDIS_ITEM_RUNS_KEY}:{item_id}', run_id) await pipe.execute() -async def redis_cleanup_task(redis: Redis, task_id: str, item_id: str | None): +async def redis_cleanup_run(redis: Redis, run_id: str, item_id: str | None): pipe = redis.pipeline(transaction=False) - pipe.delete(f'{REDIS_TASKS_KEY}:{task_id}') - pipe.hdel(REDIS_TASKS_KEY, task_id) - pipe.hdel(REDIS_RESPONSE_STREAMS_KEY, task_id) - pipe.delete(f'{REDIS_RESPONSE_STREAMS_KEY}:{task_id}') + pipe.delete(f'{REDIS_RUNS_KEY}:{run_id}') + pipe.hdel(REDIS_RUNS_KEY, run_id) + pipe.hdel(REDIS_RESPONSE_STREAMS_KEY, run_id) + pipe.delete(f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}') if item_id: - pipe.srem(f'{REDIS_ITEM_TASKS_KEY}:{item_id}', task_id) + pipe.srem(f'{REDIS_ITEM_RUNS_KEY}:{item_id}', run_id) await pipe.execute() -async def redis_list_tasks(redis: Redis, item_id: str | None = None) -> list[str]: - task_ids = list( - await redis.smembers(f'{REDIS_ITEM_TASKS_KEY}:{item_id}') +async def redis_list_runs(redis: Redis, item_id: str | None = None) -> list[str]: + run_ids = list( + await redis.smembers(f'{REDIS_ITEM_RUNS_KEY}:{item_id}') if item_id is not None - else await redis.hkeys(REDIS_TASKS_KEY) + else await redis.hkeys(REDIS_RUNS_KEY) ) - if not task_ids or REDIS_TASK_TTL == 0: - return task_ids + if not run_ids or REDIS_TASK_TTL == 0: + return run_ids pipe = redis.pipeline(transaction=False) - for task_id in task_ids: - pipe.exists(f'{REDIS_TASKS_KEY}:{task_id}') + for run_id in run_ids: + pipe.exists(f'{REDIS_RUNS_KEY}:{run_id}') active = [] - for task_id, exists in zip(task_ids, await pipe.execute()): + for run_id, exists in zip(run_ids, await pipe.execute()): if exists: - active.append(task_id) + active.append(run_id) else: - task_item_id = item_id if item_id is not None else await redis.hget(REDIS_TASKS_KEY, task_id) - await redis_cleanup_task(redis, task_id, task_item_id or None) + run_item_id = item_id if item_id is not None else await redis.hget(REDIS_RUNS_KEY, run_id) + await redis_cleanup_run(redis, run_id, run_item_id or None) return active @@ -140,74 +141,74 @@ async def redis_send_command(redis: Redis, command: dict): await redis.publish(REDIS_PUBSUB_CHANNEL, command_json) -async def cleanup_task(redis, task_id: str, id=None): +async def cleanup_run(redis, run_id: str, id=None): """ - Remove a completed or canceled task from the global `tasks` dictionary. + Remove a completed or canceled run from the global `runs` dictionary. """ if redis: - await redis_cleanup_task(redis, task_id, id) + await redis_cleanup_run(redis, run_id, id) - tasks.pop(task_id, None) # Remove the task if it exists - response_streams.pop(task_id, None) + runs.pop(run_id, None) # Remove the run if it exists + response_streams.pop(run_id, None) - # If an ID is provided, remove the task from the item_tasks dictionary - if id and task_id in item_tasks.get(id, []): - item_tasks[id].remove(task_id) - if not item_tasks[id]: # If no tasks left for this ID, remove the entry - item_tasks.pop(id, None) + # If an ID is provided, remove the run from the item_runs dictionary + if id and run_id in item_runs.get(id, []): + item_runs[id].remove(run_id) + if not item_runs[id]: # If no runs left for this ID, remove the entry + item_runs.pop(id, None) -async def create_task(redis, coroutine, id=None, task_id=None): +async def create_run(redis, coroutine, id=None, run_id=None): """ - Create a new asyncio task and add it to the global task dictionary. + Start a coroutine as a run and add it to the global runs dictionary. """ - task_id = task_id or str(uuid4()) # Generate a unique ID for the task + run_id = run_id or str(uuid4()) # Generate a unique ID for the run task = asyncio.create_task(coroutine) # Create the task # Give the task a checkout routine before handing it the keys. - task.add_done_callback(lambda t: asyncio.create_task(cleanup_task(redis, task_id, id))) - tasks[task_id] = task + task.add_done_callback(lambda t: asyncio.create_task(cleanup_run(redis, run_id, id))) + runs[run_id] = task - # File this task under its item ID, if it came with a return address. + # File this run under its item ID, if it came with a return address. if id: - if item_tasks.get(id): - item_tasks[id].append(task_id) + if item_runs.get(id): + item_runs[id].append(run_id) else: - item_tasks[id] = [task_id] + item_runs[id] = [run_id] if redis: - await redis_save_task(redis, task_id, id) + await redis_save_run(redis, run_id, id) - return task_id, task + return run_id, task -async def list_tasks(redis): +async def list_runs(redis): """ - List all currently active task IDs. + List all currently active run IDs. """ if redis: - return await redis_list_tasks(redis) - return list(tasks.keys()) + return await redis_list_runs(redis) + return list(runs.keys()) -async def list_task_ids_by_item_id(redis, id): +async def list_run_ids_by_item_id(redis, id): """ - List all tasks associated with a specific ID. + List all runs associated with a specific ID. """ if redis: - return await redis_list_tasks(redis, id) - return list(item_tasks.get(id, [])) + return await redis_list_runs(redis, id) + return list(item_runs.get(id, [])) async def save_response_stream( redis, - task_id: str | None, + run_id: str | None, chat_id: str | None, message_id: str | None, output: list, ) -> int: """Save a snapshot and return its byte size; zero means it needs to be retried.""" - if not task_id or not chat_id or not message_id: + if not run_id or not chat_id or not message_id: return 0 data = { @@ -220,7 +221,7 @@ async def save_response_stream( snapshot = dumps_bytes(data) + b'\n' try: await redis.set( - f'{REDIS_RESPONSE_STREAMS_KEY}:{task_id}', + f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}', snapshot, ex=REDIS_RESPONSE_STREAM_TTL if REDIS_RESPONSE_STREAM_TTL > 0 else None, ) @@ -228,11 +229,11 @@ async def save_response_stream( return 0 return len(snapshot) else: - response_streams[task_id] = data + response_streams[run_id] = data return 0 -async def append_response_stream(redis: Redis, task_id: str, delta: bytes, size: int) -> bool: +async def append_response_stream(redis: Redis, run_id: str, delta: bytes, size: int) -> bool: """Append only to the snapshot we last wrote, including after a Redis retry.""" try: return bool( @@ -241,7 +242,7 @@ async def append_response_stream(redis: Redis, task_id: str, delta: bytes, size: "redis.call('append', KEYS[1], ARGV[2]) " "if tonumber(ARGV[3]) > 0 then redis.call('expire', KEYS[1], ARGV[3]) end return 1", 1, - f'{REDIS_RESPONSE_STREAMS_KEY}:{task_id}', + f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}', size, delta, REDIS_RESPONSE_STREAM_TTL, @@ -263,18 +264,18 @@ def load_response_stream(value: str | bytes) -> dict: async def get_response_streams_by_chat_id(redis, chat_id: str) -> list[dict]: - task_ids = await list_task_ids_by_item_id(redis, chat_id) - if not task_ids: + run_ids = await list_run_ids_by_item_id(redis, chat_id) + if not run_ids: return [] if redis: pipe = redis.pipeline(transaction=False) - for task_id in task_ids: - pipe.get(f'{REDIS_RESPONSE_STREAMS_KEY}:{task_id}') + for run_id in run_ids: + pipe.get(f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}') values = await pipe.execute() # Replies started on older instances still use the shared hash during an upgrade. if any(value is None for value in values): - legacy = await redis.hmget(REDIS_RESPONSE_STREAMS_KEY, task_ids) + legacy = await redis.hmget(REDIS_RESPONSE_STREAMS_KEY, run_ids) values = [value if value is not None else old for value, old in zip(values, legacy)] streams = [] for value in values: @@ -291,77 +292,77 @@ async def get_response_streams_by_chat_id(redis, chat_id: str) -> list[dict]: return [ {**stream, 'content': get_output_text(stream['output'])} - for task_id in task_ids - if (stream := response_streams.get(task_id)) and stream.get('chat_id') == chat_id + for run_id in run_ids + if (stream := response_streams.get(run_id)) and stream.get('chat_id') == chat_id ] -async def clear_response_stream(redis, task_id: str | None): - if not task_id: +async def clear_response_stream(redis, run_id: str | None): + if not run_id: return if redis: pipe = redis.pipeline(transaction=False) - pipe.delete(f'{REDIS_RESPONSE_STREAMS_KEY}:{task_id}') - pipe.hdel(REDIS_RESPONSE_STREAMS_KEY, task_id) + pipe.delete(f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}') + pipe.hdel(REDIS_RESPONSE_STREAMS_KEY, run_id) await pipe.execute() else: - response_streams.pop(task_id, None) + response_streams.pop(run_id, None) -async def stop_task(redis, task_id: str): +async def stop_run(redis, run_id: str): """ - Cancel a running task and remove it from the global task list. + Cancel a run and remove it from the global run list. """ if redis: # Look up the item_id before cleanup so we can remove the set entry too - item_id = await redis.hget(REDIS_TASKS_KEY, task_id) - # PUBSUB: All instances check if they have this task, and stop if so. + item_id = await redis.hget(REDIS_RUNS_KEY, run_id) + # PUBSUB: All instances check if they have this run, and stop if so. await redis_send_command( redis, { 'action': 'stop', - 'task_id': task_id, + 'run_id': run_id, }, ) # Always clean Redis directly — hdel/srem are idempotent, safe even # if the done_callback on the owning process also fires cleanup. - await redis_cleanup_task(redis, task_id, item_id or None) - return {'status': True, 'message': f'Task {task_id} stopped.'} + await redis_cleanup_run(redis, run_id, item_id or None) + return {'status': True, 'message': f'Run {run_id} stopped.'} - task = tasks.pop(task_id, None) + task = runs.pop(run_id, None) if not task: - return {'status': False, 'message': f'Task with ID {task_id} not found.'} + return {'status': False, 'message': f'Run with ID {run_id} not found.'} task.cancel() # Request task cancellation try: await task # Wait for the task to handle the cancellation except asyncio.CancelledError: - # Task successfully canceled - return {'status': True, 'message': f'Task {task_id} successfully stopped.'} + # Run successfully canceled + return {'status': True, 'message': f'Run {run_id} successfully stopped.'} if task.cancelled() or task.done(): - return {'status': True, 'message': f'Task {task_id} successfully cancelled.'} + return {'status': True, 'message': f'Run {run_id} successfully cancelled.'} - return {'status': True, 'message': f'Cancellation requested for {task_id}.'} + return {'status': True, 'message': f'Cancellation requested for {run_id}.'} -async def stop_item_tasks(redis: Redis, item_id: str): +async def stop_item_runs(redis: Redis, item_id: str): """ - Stop all tasks associated with a specific item ID. + Stop all runs associated with a specific item ID. """ - task_ids = await list_task_ids_by_item_id(redis, item_id) - if not task_ids: - return {'status': True, 'message': f'No tasks found for item {item_id}.'} + run_ids = await list_run_ids_by_item_id(redis, item_id) + if not run_ids: + return {'status': True, 'message': f'No runs found for item {item_id}.'} - # Cleanup mutates the local task list while cancellation is awaited. - for task_id in list(task_ids): - # A task that already finished needs no stopping; continue with the rest. - await stop_task(redis, task_id) + # Cleanup mutates the local run list while cancellation is awaited. + for run_id in list(run_ids): + # A run that already finished needs no stopping; continue with the rest. + await stop_run(redis, run_id) - return {'status': True, 'message': f'All tasks for item {item_id} stopped.'} + return {'status': True, 'message': f'All runs for item {item_id} stopped.'} -async def has_active_tasks(redis, chat_id: str) -> bool: - """Check if a chat has any active tasks.""" - task_ids = await list_task_ids_by_item_id(redis, chat_id) - return len(task_ids) > 0 +async def has_active_runs(redis, chat_id: str) -> bool: + """Check if a chat has any active runs.""" + run_ids = await list_run_ids_by_item_id(redis, chat_id) + return len(run_ids) > 0 diff --git a/backend/open_webui/socket/main.py b/backend/open_webui/socket/main.py index b19440365a..fcbe603858 100644 --- a/backend/open_webui/socket/main.py +++ b/backend/open_webui/socket/main.py @@ -45,13 +45,13 @@ from open_webui.models.users import UserNameResponse, Users from open_webui.socket.encryption import Relay from open_webui.socket.redis_room_channels import AsyncRedisRoomChannelManager from open_webui.socket.utils import SOCKET_EVENT_LOCKS, CachedRedisDict, RedisDict, RedisLock, YdocManager -from open_webui.tasks import ( +from open_webui.runs import ( REDIS_PUBSUB_MAX_RECONNECT_INTERVAL, REDIS_PUBSUB_RECONNECT_INTERVAL, - cleanup_task, - create_task, - has_active_tasks, - stop_item_tasks, + cleanup_run, + create_run, + has_active_runs, + stop_item_runs, ) from open_webui.utils.access_control import has_permission from open_webui.utils.access_control.files import has_access_to_note_files @@ -1064,7 +1064,7 @@ async def close_changed_note_documents(previous, current): ids.append(f'note:{previous.id}') for document_id in ids: async with YDOC_MANAGER.lock(document_id): - await stop_item_tasks(REDIS, document_id) + await stop_item_runs(REDIS, document_id) await sio.close_room(f'doc_{document_id}') for sid in list(await YDOC_MANAGER.get_users(document_id)): await YDOC_MANAGER.remove_user(document_id, sid) @@ -1355,7 +1355,7 @@ async def yjs_document_update(sid, data): return update if stored else None if data.get('flush'): - await stop_item_tasks(REDIS, document_id) + await stop_item_runs(REDIS, document_id) saved = await document_save_handler(document_id, data.get('data', {}), user) return {'ok': bool(saved)} @@ -1366,7 +1366,7 @@ async def yjs_document_update(sid, data): if not await YDOC_MANAGER.get_users(document_id): await YDOC_MANAGER.clear_document(document_id) # A waiting disconnect must see that this save has finished. - await cleanup_task(REDIS, task_id, document_id) + await cleanup_run(REDIS, run_id, document_id) if document_id.startswith('note:') and data.get('data'): # Only drop the pending save when a new one takes its place. @@ -1375,11 +1375,11 @@ async def yjs_document_update(sid, data): # save without scheduling a replacement, so the edits made just # before the resync never reach the database. try: - await stop_item_tasks(REDIS, document_id) + await stop_item_runs(REDIS, document_id) except Exception: pass - task_id, _ = await create_task(REDIS, debounced_save(), document_id) + run_id, _ = await create_run(REDIS, debounced_save(), document_id) except Exception as e: log.error(f'Error in yjs_document_update: {e}') @@ -1411,7 +1411,7 @@ async def yjs_document_leave(sid, data): room=f'doc_{document_id}', ) - if not await YDOC_MANAGER.get_users(document_id) and not await has_active_tasks(REDIS, document_id): + if not await YDOC_MANAGER.get_users(document_id) and not await has_active_runs(REDIS, document_id): log.debug('Cleaning up document %s as no users are left', document_id) await YDOC_MANAGER.clear_document(document_id) diff --git a/backend/open_webui/socket/utils.py b/backend/open_webui/socket/utils.py index fca156fdf9..6fbc08b958 100644 --- a/backend/open_webui/socket/utils.py +++ b/backend/open_webui/socket/utils.py @@ -11,7 +11,7 @@ from contextlib import asynccontextmanager import pycrdt as Y from open_webui.env import REDIS_KEY_PREFIX, WEBSOCKET_REDIS_LOCK_TIMEOUT -from open_webui.tasks import has_active_tasks +from open_webui.runs import has_active_runs from open_webui.utils.json_codec import JSONCodec from open_webui.utils.redis import get_redis_connection from redis.exceptions import RedisClusterException, RedisError @@ -416,7 +416,7 @@ class YdocManager: for document_id in document_ids: async with self.lock(document_id): await self.remove_user(document_id, user_id) - if not await self.get_users(document_id) and not await has_active_tasks(self._redis, document_id): + if not await self.get_users(document_id) and not await has_active_runs(self._redis, document_id): await self.clear_document(document_id) return list(document_ids) diff --git a/backend/open_webui/utils/agents/output.py b/backend/open_webui/utils/agents/output.py index d2dadbb849..64eed9d1f8 100644 --- a/backend/open_webui/utils/agents/output.py +++ b/backend/open_webui/utils/agents/output.py @@ -8,7 +8,7 @@ from uuid import uuid4 from open_webui.models.chats import Chats from open_webui.socket.main import get_event_emitter -from open_webui.tasks import clear_response_stream, save_response_stream +from open_webui.runs import clear_response_stream, save_response_stream from open_webui.utils.auth import create_token from open_webui.utils.misc import sanitize_data_for_db from open_webui.utils.redis import get_redis_client diff --git a/backend/open_webui/utils/apps.py b/backend/open_webui/utils/apps.py index 281fb3d9af..817f4d5838 100644 --- a/backend/open_webui/utils/apps.py +++ b/backend/open_webui/utils/apps.py @@ -26,7 +26,7 @@ from open_webui.models.channels import Channel, ChannelMember, ChannelModel, Cha from open_webui.models.config import Config from open_webui.models.messages import Message, MessageForm, Messages from open_webui.models.users import UserModel, Users -from open_webui.tasks import create_task +from open_webui.runs import create_run from sqlalchemy import and_, or_, select from sqlalchemy.ext.asyncio import AsyncSession @@ -341,7 +341,7 @@ async def publish_app_message_event(message, kind): if kind == 'channel.message.deleted': value = {k: value[k] for k in ('id', 'channel_id', 'parent_id', 'author', 'updated_at')} # shortcut: events are lost on failure/restart; add durable delivery only if replay becomes required. - await create_task(None, send_app_message_event(value, kind, time.time_ns())) + await create_run(None, send_app_message_event(value, kind, time.time_ns())) async def send_app_message_event(message, kind, created_at): diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index cf4e8de13b..445483eddb 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -80,7 +80,7 @@ from open_webui.socket.main import ( get_event_call, get_event_emitter, ) -from open_webui.tasks import append_response_stream, clear_response_stream, save_response_stream +from open_webui.runs import append_response_stream, clear_response_stream, save_response_stream from open_webui.utils.access_control import has_permission from open_webui.utils.access_control.files import get_owner_accessible_folder_files from open_webui.utils.access_control.folders import has_folder_access diff --git a/backend/open_webui/utils/subagents.py b/backend/open_webui/utils/subagents.py index 6192f01bfb..37ad14ee6d 100644 --- a/backend/open_webui/utils/subagents.py +++ b/backend/open_webui/utils/subagents.py @@ -15,7 +15,7 @@ from open_webui.models.chats import ChatForm, Chats from open_webui.models.config import Config from open_webui.models.auths import Auths from open_webui.models.users import UserModel, Users -from open_webui.tasks import create_task, has_active_tasks, list_task_ids_by_item_id +from open_webui.runs import create_run, has_active_runs, list_run_ids_by_item_id from open_webui.utils.auth import VERIFIED_USER_ROLES, create_token from open_webui.utils.chat_id import is_saved_chat_id from open_webui.utils.json_codec import JSONCodec @@ -118,7 +118,7 @@ async def queue_user_message( # Checked under the lock the reply's own cleanup takes, so the message can't be left unanswered. if not reply or not ( await ChatMessages.has_queued_message(chat_id, parent_id) - or (reply.get('done') is False and await has_active_tasks(request.app.state.redis, chat_id)) + or (reply.get('done') is False and await has_active_runs(request.app.state.redis, chat_id)) ): return False message = { @@ -174,7 +174,7 @@ async def has_upcoming_reply(request: Request, user_id: str, chat_id: str, messa # Replies after its report run as other tasks. for child in await Chats.get_children_by_parent_id(chat_id, user_id): meta = child.meta or {} - if meta.get('type') == 'subagent' and meta.get('delegation_id') in await list_task_ids_by_item_id( + if meta.get('type') == 'subagent' and meta.get('delegation_id') in await list_run_ids_by_item_id( request.app.state.redis, child.id ): return True @@ -261,7 +261,7 @@ async def process_pending_internal_messages( reply as soon as it is saved, without waiting for its follow-ups, title and other background work.""" lock = _parent_locks.setdefault(parent_chat_id, asyncio.Lock()) if reply_id is None: - while await has_active_tasks(source_request.app.state.redis, parent_chat_id): + while await has_active_runs(source_request.app.state.redis, parent_chat_id): await asyncio.sleep(0.25) else: # The turn started below asks whether its parent reply is still running, without taking this lock. @@ -270,7 +270,7 @@ async def process_pending_internal_messages( return async with lock: - if reply_id is None and await has_active_tasks(source_request.app.state.redis, parent_chat_id): + if reply_id is None and await has_active_runs(source_request.app.state.redis, parent_chat_id): return user = await Users.get_user_by_id(user_id) @@ -529,7 +529,7 @@ async def insert_internal_message( return messages = await ChatMessages.get_messages_map_by_chat_id(chat_id, db=session) or {} parent = messages.get(parent_id) - is_active = await has_active_tasks(request.app.state.redis, chat_id) + is_active = await has_active_runs(request.app.state.redis, chat_id) replies = [ reply for reply_id, reply in messages.items() @@ -557,7 +557,7 @@ async def insert_internal_message( {'chat_id': chat_id, 'message_id': message['id'], 'data': {'type': 'chat:reload'}}, room=f'user:{user.id}', ) - if not await has_active_tasks(request.app.state.redis, chat_id): + if not await has_active_runs(request.app.state.redis, chat_id): await process_pending_internal_messages(request, chat_id, user.id, run) @@ -953,11 +953,11 @@ async def delegate( return result try: - _, child_task = await create_task( + _, child_task = await create_run( request.app.state.redis, run_background() if background else run_reserved(), id=chat_id, - task_id=delegation_id, + run_id=delegation_id, ) except Exception as exc: if background: diff --git a/backend/open_webui/utils/timers.py b/backend/open_webui/utils/timers.py index cd1c287d8e..06e56428fc 100644 --- a/backend/open_webui/utils/timers.py +++ b/backend/open_webui/utils/timers.py @@ -17,7 +17,7 @@ from open_webui.internal.db import get_async_db from open_webui.models.chat_messages import ChatMessages from open_webui.models.chats import Chat, ChatForm, Chats from open_webui.models.users import UserModel, Users -from open_webui.tasks import has_active_tasks +from open_webui.runs import has_active_runs from open_webui.utils.auth import VERIFIED_USER_ROLES from open_webui.utils.json_codec import JSONCodec from open_webui.utils.misc import get_message_list @@ -293,7 +293,7 @@ async def execute_due_timer(app, timer_id: str, claim_id: str | None = None) -> if not parent: await _set_timer_state(timer_id, 'error', timer_error='parent chat no longer exists') return - if await has_active_tasks(app.state.redis, parent_chat_id): + if await has_active_runs(app.state.redis, parent_chat_id): timer_row = await db.get(Chat, timer_id) if timer_row: timer_meta = timer_row.meta or {} diff --git a/src/lib/components/chat/Settings/About/NightSky.svelte b/src/lib/components/chat/Settings/About/NightSky.svelte index 0e1866bb0f..a74fd0aeeb 100644 --- a/src/lib/components/chat/Settings/About/NightSky.svelte +++ b/src/lib/components/chat/Settings/About/NightSky.svelte @@ -37,6 +37,19 @@ phase: Math.random() * Math.PI * 2 })); + // One shooting star arcs across mid-night from the upper left, curving down as it falls. + const meteorAngle = Math.PI * (0.04 + Math.random() * 0.06); + const meteor = { + x: width * Math.random() * 0.15, + y: height * (0.05 + Math.random() * 0.25), + dx: Math.cos(meteorAngle), + dy: Math.sin(meteorAngle), + travel: width * 0.6, + tail: width * 0.25, + // By the end of its flight it has dropped this far below its starting line. + drop: width * 0.12 + }; + const start = performance.now(); let frame = 0; @@ -63,6 +76,23 @@ } } + // It glides across between 25% and 75% of the night, its tail tapering behind it. + const flight = (progress - 0.25) / 0.5; + if (flight > 0 && flight < 1) { + const travelled = meteor.travel * (1 - (1 - flight) ** 2); + const fade = Math.sin(Math.PI * flight); + for (let step = 0; step < meteor.tail; step++) { + const along = travelled - step; + if (along < 0) break; + const x = Math.round(meteor.x + meteor.dx * along); + const y = Math.round( + meteor.y + meteor.dy * along + meteor.drop * (along / meteor.travel) ** 2 + ); + if (x < 0 || y < 0 || x >= width || y >= height) continue; + light[y * width + x] += fade * (1 - step / meteor.tail) ** 2 * 0.6; + } + } + for (let i = 0; i < light.length; i++) { const x = i % width; const y = (i / width) | 0;