From 7de92922fa71e7819981e02085158d9e16df8aef Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 5 Dec 2026 06:57:35 +0400 Subject: [PATCH] refac --- backend/open_webui/config.py | 3 + backend/open_webui/events.py | 12 + backend/open_webui/main.py | 4 + .../versions/d8f2a6c41e7b_add_tasks.py | 91 +++ backend/open_webui/models/chat_views.py | 2 +- backend/open_webui/models/chats.py | 7 + backend/open_webui/models/comments.py | 2 +- backend/open_webui/models/folders.py | 2 + backend/open_webui/models/notifications.py | 5 + backend/open_webui/models/tags.py | 2 +- backend/open_webui/models/tasks.py | 645 ++++++++++++++++++ backend/open_webui/models/users.py | 3 + backend/open_webui/routers/auths.py | 2 + backend/open_webui/routers/chats.py | 12 + backend/open_webui/routers/folders.py | 24 + backend/open_webui/routers/tasks.py | 513 ++++++++++++++ backend/open_webui/tools/builtin.py | 358 ++++++++++ .../open_webui/utils/access_control/tasks.py | 44 ++ backend/open_webui/utils/comments.py | 9 + backend/open_webui/utils/inbox.py | 7 + backend/open_webui/utils/tools.py | 15 + src/lib/apis/chats/index.ts | 7 +- src/lib/apis/comments/index.ts | 2 +- src/lib/apis/notifications/inbox.ts | 1 + src/lib/apis/tasks/index.ts | 173 +++++ .../components/admin/Settings/Features.svelte | 8 + src/lib/components/chat/Chat.svelte | 9 +- .../chat/Messages/builtinToolLabels.ts | 10 + src/lib/components/chat/Navbar.svelte | 2 + .../chat/Placeholder/ChatList.svelte | 33 +- .../chat/Placeholder/FolderOverview.svelte | 56 +- .../chat/Placeholder/FolderPlaceholder.svelte | 147 ++-- .../chat/Placeholder/FolderStatusIcon.svelte | 16 +- .../chat/Placeholder/FolderStatusTime.svelte | 9 +- .../Placeholder/FolderStatusesModal.svelte | 27 +- .../chat/Placeholder/FolderTags.svelte | 11 +- .../chat/Placeholder/FolderTitle.svelte | 3 + src/lib/components/chat/Tabs.svelte | 2 + src/lib/components/chat/Tabs/Page.svelte | 6 + src/lib/components/chat/Tabs/tabs.ts | 2 +- src/lib/components/chat/TagPicker.svelte | 73 +- .../components/comments/CommentsPanel.svelte | 8 +- src/lib/components/layout/InboxHost.svelte | 2 + src/lib/components/layout/Sidebar.svelte | 13 + .../layout/Sidebar/RecursiveFolder.svelte | 3 + .../components/layout/Sidebar/UserMenu.svelte | 54 ++ .../components/tasks/FolderTaskCount.svelte | 22 + src/lib/components/tasks/MyTasks.svelte | 54 ++ src/lib/components/tasks/Task.svelte | 435 ++++++++++++ src/lib/components/tasks/TaskAssignee.svelte | 129 ++++ src/lib/components/tasks/TaskBoard.svelte | 119 ++++ src/lib/components/tasks/TaskChip.svelte | 35 + src/lib/components/tasks/TaskDueDate.svelte | 66 ++ src/lib/components/tasks/TaskFolder.svelte | 109 +++ src/lib/components/tasks/TaskGroupIcon.svelte | 33 + src/lib/components/tasks/TaskList.svelte | 209 ++++++ src/lib/components/tasks/TaskModal.svelte | 225 ++++++ src/lib/components/tasks/TaskPriority.svelte | 63 ++ src/lib/components/tasks/TaskStatus.svelte | 86 +++ .../components/tasks/TaskStatusTime.svelte | 23 + .../components/tasks/TaskStatusesModal.svelte | 48 ++ src/lib/components/tasks/Tasks.svelte | 531 ++++++++++++++ src/lib/components/tasks/groups.ts | 111 +++ .../workspace/Models/BuiltinTools.svelte | 5 + src/lib/i18n/locales/ar-BH/translation.json | 68 ++ src/lib/i18n/locales/ar/translation.json | 68 ++ src/lib/i18n/locales/az-AZ/translation.json | 68 ++ src/lib/i18n/locales/bg-BG/translation.json | 68 ++ src/lib/i18n/locales/bn-BD/translation.json | 68 ++ src/lib/i18n/locales/bo-TB/translation.json | 68 ++ src/lib/i18n/locales/bs-BA/translation.json | 68 ++ src/lib/i18n/locales/ca-ES/translation.json | 68 ++ src/lib/i18n/locales/ceb-PH/translation.json | 68 ++ src/lib/i18n/locales/cs-CZ/translation.json | 68 ++ src/lib/i18n/locales/da-DK/translation.json | 68 ++ src/lib/i18n/locales/de-DE/translation.json | 68 ++ src/lib/i18n/locales/dg-DG/translation.json | 68 ++ src/lib/i18n/locales/el-GR/translation.json | 68 ++ src/lib/i18n/locales/en-GB/translation.json | 68 ++ src/lib/i18n/locales/en-US/translation.json | 68 ++ src/lib/i18n/locales/es-ES/translation.json | 68 ++ src/lib/i18n/locales/et-EE/translation.json | 68 ++ src/lib/i18n/locales/eu-ES/translation.json | 68 ++ src/lib/i18n/locales/fa-IR/translation.json | 68 ++ src/lib/i18n/locales/fi-FI/translation.json | 68 ++ src/lib/i18n/locales/fil-PH/translation.json | 68 ++ src/lib/i18n/locales/fo-FO/translation.json | 68 ++ src/lib/i18n/locales/fr-CA/translation.json | 68 ++ src/lib/i18n/locales/fr-FR/translation.json | 68 ++ src/lib/i18n/locales/gl-ES/translation.json | 68 ++ src/lib/i18n/locales/he-IL/translation.json | 68 ++ src/lib/i18n/locales/hi-IN/translation.json | 68 ++ src/lib/i18n/locales/hr-HR/translation.json | 68 ++ src/lib/i18n/locales/hu-HU/translation.json | 68 ++ src/lib/i18n/locales/id-ID/translation.json | 68 ++ src/lib/i18n/locales/ie-GA/translation.json | 68 ++ src/lib/i18n/locales/it-IT/translation.json | 68 ++ src/lib/i18n/locales/ja-JP/translation.json | 68 ++ src/lib/i18n/locales/ka-GE/translation.json | 68 ++ src/lib/i18n/locales/kab-DZ/translation.json | 68 ++ src/lib/i18n/locales/ko-KR/translation.json | 68 ++ src/lib/i18n/locales/lt-LT/translation.json | 68 ++ src/lib/i18n/locales/lv-LV/translation.json | 68 ++ src/lib/i18n/locales/ms-MY/translation.json | 68 ++ src/lib/i18n/locales/nb-NO/translation.json | 68 ++ src/lib/i18n/locales/nl-NL/translation.json | 68 ++ src/lib/i18n/locales/pa-IN/translation.json | 68 ++ src/lib/i18n/locales/pl-PL/translation.json | 68 ++ src/lib/i18n/locales/pt-BR/translation.json | 68 ++ src/lib/i18n/locales/pt-PT/translation.json | 68 ++ src/lib/i18n/locales/ro-RO/translation.json | 68 ++ src/lib/i18n/locales/ru-RU/translation.json | 68 ++ src/lib/i18n/locales/sk-SK/translation.json | 68 ++ src/lib/i18n/locales/sl-SI/translation.json | 68 ++ src/lib/i18n/locales/sr-RS/translation.json | 68 ++ src/lib/i18n/locales/sv-SE/translation.json | 68 ++ src/lib/i18n/locales/ta-IN/translation.json | 68 ++ src/lib/i18n/locales/th-TH/translation.json | 68 ++ src/lib/i18n/locales/tk-TM/translation.json | 68 ++ src/lib/i18n/locales/tr-TR/translation.json | 68 ++ src/lib/i18n/locales/ug-CN/translation.json | 68 ++ src/lib/i18n/locales/uk-UA/translation.json | 68 ++ src/lib/i18n/locales/ur-PK/translation.json | 68 ++ .../i18n/locales/uz-Cyrl-UZ/translation.json | 68 ++ .../i18n/locales/uz-Latn-UZ/translation.json | 68 ++ src/lib/i18n/locales/vi-VN/translation.json | 68 ++ src/lib/i18n/locales/zh-CN/translation.json | 68 ++ src/lib/i18n/locales/zh-TW/translation.json | 68 ++ src/lib/stores/index.ts | 1 + src/lib/utils/folders.ts | 23 +- src/lib/utils/index.ts | 1 + src/lib/utils/tasks.ts | 71 ++ src/lib/utils/ui-visibility.ts | 1 + src/routes/(app)/tasks/+page.svelte | 1 + src/routes/(app)/tasks/[id]/+page.svelte | 1 + 135 files changed, 9068 insertions(+), 125 deletions(-) create mode 100644 backend/open_webui/migrations/versions/d8f2a6c41e7b_add_tasks.py create mode 100644 backend/open_webui/models/tasks.py create mode 100644 backend/open_webui/routers/tasks.py create mode 100644 backend/open_webui/utils/access_control/tasks.py create mode 100644 src/lib/apis/tasks/index.ts create mode 100644 src/lib/components/tasks/FolderTaskCount.svelte create mode 100644 src/lib/components/tasks/MyTasks.svelte create mode 100644 src/lib/components/tasks/Task.svelte create mode 100644 src/lib/components/tasks/TaskAssignee.svelte create mode 100644 src/lib/components/tasks/TaskBoard.svelte create mode 100644 src/lib/components/tasks/TaskChip.svelte create mode 100644 src/lib/components/tasks/TaskDueDate.svelte create mode 100644 src/lib/components/tasks/TaskFolder.svelte create mode 100644 src/lib/components/tasks/TaskGroupIcon.svelte create mode 100644 src/lib/components/tasks/TaskList.svelte create mode 100644 src/lib/components/tasks/TaskModal.svelte create mode 100644 src/lib/components/tasks/TaskPriority.svelte create mode 100644 src/lib/components/tasks/TaskStatus.svelte create mode 100644 src/lib/components/tasks/TaskStatusTime.svelte create mode 100644 src/lib/components/tasks/TaskStatusesModal.svelte create mode 100644 src/lib/components/tasks/Tasks.svelte create mode 100644 src/lib/components/tasks/groups.ts create mode 100644 src/lib/utils/tasks.ts create mode 100644 src/routes/(app)/tasks/+page.svelte create mode 100644 src/routes/(app)/tasks/[id]/+page.svelte diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index 28e578948e..50e232af29 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -2110,6 +2110,8 @@ ENABLE_CHANNELS = os.getenv('ENABLE_CHANNELS', 'False').lower() == 'true' ENABLE_TEAMS = os.getenv('ENABLE_TEAMS', 'False').lower() == 'true' +ENABLE_TASKS = os.getenv('ENABLE_TASKS', 'False').lower() == 'true' + ENABLE_ENCRYPTED_CHANNELS = os.getenv('ENABLE_ENCRYPTED_CHANNELS', 'False').lower() == 'true' ENABLE_APPS = os.getenv('ENABLE_APPS', 'False').lower() == 'true' @@ -3307,6 +3309,7 @@ DEFAULT_CONFIG = { 'folders.max_file_count': FOLDER_MAX_FILE_COUNT, 'channels.enable': ENABLE_CHANNELS, 'teams.enable': ENABLE_TEAMS, + 'tasks.enable': ENABLE_TASKS, 'channels.encryption.enable': ENABLE_ENCRYPTED_CHANNELS, 'apps.enable': ENABLE_APPS, 'channels.model_response_mode': CHANNEL_MODEL_RESPONSE_MODE, diff --git a/backend/open_webui/events.py b/backend/open_webui/events.py index 0eda7e74ab..0598549edc 100644 --- a/backend/open_webui/events.py +++ b/backend/open_webui/events.py @@ -419,6 +419,18 @@ class EventDefinitions(BaseModel): NOTE_DELETED: EventDefinition = EventDefinition( name='note.deleted', description='A note was deleted.', message='Note deleted' ) + TASK_CREATED: EventDefinition = EventDefinition( + name='task.created', description='A task was created.', message='Task created' + ) + TASK_UPDATED: EventDefinition = EventDefinition( + name='task.updated', description='A task was updated.', message='Task updated' + ) + TASK_ASSIGNED: EventDefinition = EventDefinition( + name='task.assigned', description='A task was assigned to someone.', message='Task assigned' + ) + TASK_DELETED: EventDefinition = EventDefinition( + name='task.deleted', description='A task was deleted.', message='Task deleted' + ) MEMORY_CREATED: EventDefinition = EventDefinition( name='memory.created', description='A memory was created.', message='Memory created' ) diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index e037417cd6..88500833e9 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -187,6 +187,7 @@ from open_webui.routers import ( search, skills, system_model, + tasks, teams, tools, users, @@ -893,6 +894,7 @@ app.include_router(memories.router, prefix='/api/v1/memories', tags=['memories'] app.include_router(folders.router, prefix='/api/v1/folders', tags=['folders']) app.include_router(groups.router, prefix='/api/v1/groups', tags=['groups']) app.include_router(teams.router, prefix='/api/v1/teams', tags=['teams']) +app.include_router(tasks.router, prefix='/api/v1/tasks', tags=['tasks']) app.include_router(files.router, prefix='/api/v1/files', tags=['files']) app.include_router(functions.router, prefix='/api/v1/functions', tags=['functions']) app.include_router(evaluations.router, prefix='/api/v1/evaluations', tags=['evaluations']) @@ -2478,6 +2480,7 @@ async def get_app_config(request: Request): 'channels.enable', 'channels.encryption.enable', 'teams.enable', + 'tasks.enable', 'apps.enable', 'calendar.enable', 'automations.enable', @@ -2590,6 +2593,7 @@ async def get_app_config(request: Request): 'folder_max_file_count': config.get('folders.max_file_count'), 'enable_channels': config.get('channels.enable'), 'enable_teams': config.get('teams.enable'), + 'enable_tasks': config.get('tasks.enable'), 'enable_encrypted_channels': config.get('channels.encryption.enable'), 'enable_apps': config.get('apps.enable'), 'enable_calendar': config.get('calendar.enable'), diff --git a/backend/open_webui/migrations/versions/d8f2a6c41e7b_add_tasks.py b/backend/open_webui/migrations/versions/d8f2a6c41e7b_add_tasks.py new file mode 100644 index 0000000000..dd85834b7d --- /dev/null +++ b/backend/open_webui/migrations/versions/d8f2a6c41e7b_add_tasks.py @@ -0,0 +1,91 @@ +"""add tasks + +Revision ID: d8f2a6c41e7b +Revises: b7e4c2a9d1f3 +Create Date: 2026-12-04 12:00:00 + +A task is a unit of work that lives in a folder, numbered per folder from the folder's +task_counter, so a number is never reused. Its status is an id from the folder's statuses, +which also say its category. Its history keeps one row per changed field, as Jira does: +the value the task held, and the name it went by then when that value is an id. +A chat started from a task points back to it with task_id. +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = 'd8f2a6c41e7b' +down_revision: str | None = 'b7e4c2a9d1f3' +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + inspector = sa.inspect(op.get_bind()) + existing_tables = set(inspector.get_table_names()) + + if 'task' not in existing_tables: + op.create_table( + 'task', + sa.Column('id', sa.Text(), primary_key=True, nullable=False), + sa.Column('folder_id', sa.Text(), nullable=False), + sa.Column('number', sa.BigInteger(), nullable=False), + sa.Column('user_id', sa.Text(), nullable=False), + sa.Column('title', sa.Text(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.Text(), nullable=False), + sa.Column('priority', sa.Text(), nullable=True), + sa.Column('assignee_id', sa.Text(), nullable=True), + sa.Column('due_date', sa.Text(), nullable=True), + sa.Column('status_at', sa.BigInteger(), nullable=False), + sa.Column('status_durations', sa.JSON(), nullable=True), + sa.Column('started_at', sa.BigInteger(), nullable=True), + sa.Column('completed_at', sa.BigInteger(), nullable=True), + sa.Column('canceled_at', sa.BigInteger(), nullable=True), + sa.Column('data', sa.JSON(), nullable=True), + sa.Column('meta', sa.JSON(), nullable=True), + sa.Column('created_at', sa.BigInteger(), nullable=False), + sa.Column('updated_at', sa.BigInteger(), nullable=False), + sa.UniqueConstraint('folder_id', 'number', name='uq_task_folder_number'), + ) + op.create_index('ix_task_assignee_id', 'task', ['assignee_id']) + op.create_index('ix_task_user_id', 'task', ['user_id']) + + if 'task_history' not in existing_tables: + op.create_table( + 'task_history', + sa.Column('id', sa.Text(), primary_key=True, nullable=False), + sa.Column('task_id', sa.Text(), sa.ForeignKey('task.id', ondelete='CASCADE'), nullable=False), + sa.Column('user_id', sa.Text(), nullable=True), + sa.Column('field', sa.Text(), nullable=False), + sa.Column('old_value', sa.Text(), nullable=True), + sa.Column('new_value', sa.Text(), nullable=True), + sa.Column('old_name', sa.Text(), nullable=True), + sa.Column('new_name', sa.Text(), nullable=True), + sa.Column('created_at', sa.BigInteger(), nullable=False), + ) + op.create_index('ix_task_history_task_id_created_at', 'task_history', ['task_id', 'created_at']) + + folder_columns = {column['name'] for column in inspector.get_columns('folder')} + if 'task_counter' not in folder_columns: + op.add_column('folder', sa.Column('task_counter', sa.BigInteger(), nullable=False, server_default='0')) + + chat_columns = {column['name'] for column in inspector.get_columns('chat')} + if 'task_id' not in chat_columns: + op.add_column('chat', sa.Column('task_id', sa.Text(), nullable=True)) + op.create_index('ix_chat_task_id', 'chat', ['task_id']) + + +def downgrade() -> None: + op.drop_index('ix_chat_task_id', table_name='chat') + with op.batch_alter_table('chat') as batch: + batch.drop_column('task_id') + with op.batch_alter_table('folder') as batch: + batch.drop_column('task_counter') + op.drop_index('ix_task_history_task_id_created_at', table_name='task_history') + op.drop_table('task_history') + op.drop_index('ix_task_user_id', table_name='task') + op.drop_index('ix_task_assignee_id', table_name='task') + op.drop_table('task') diff --git a/backend/open_webui/models/chat_views.py b/backend/open_webui/models/chat_views.py index 28705f9c8a..b2c7d3fa58 100644 --- a/backend/open_webui/models/chat_views.py +++ b/backend/open_webui/models/chat_views.py @@ -118,7 +118,7 @@ class PanelTabs(ViewModel): class FolderPage(ViewModel): """What a folder's own page showed: its section and the directory browsed in Files.""" - section: Literal['overview', 'files', 'chats', 'notes', 'automations', 'knowledge'] + section: Literal['overview', 'files', 'chats', 'tasks', 'notes', 'automations', 'knowledge'] directory: str | None = None diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index 14dbf62ea2..6cb34b1f89 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -209,6 +209,8 @@ class Chat(Base): # database table mapping for chat entity meta = Column(JSON, server_default='{}') variables = Column(JSON, nullable=True) folder_id = Column(Text, nullable=True) + # The task this chat was started from, if any. + task_id = Column(Text, nullable=True) todos = Column(JSON, nullable=True) summary = Column(Text, nullable=True) @@ -220,6 +222,7 @@ class Chat(Base): # database table mapping for chat entity __table_args__ = ( # Performance indexes for common queries Index('folder_id_idx', 'folder_id'), + Index('ix_chat_task_id', 'task_id'), Index('user_id_pinned_idx', 'user_id', 'pinned'), Index('user_id_archived_idx', 'user_id', 'archived'), Index('updated_at_user_id_idx', 'updated_at', 'user_id'), @@ -261,6 +264,7 @@ class ChatModel(BaseModel): meta: dict = {} variables: dict = {} folder_id: str | None = None + task_id: str | None = None todos: list | None = None summary: str | None = None @@ -312,6 +316,7 @@ class ChatForm(BaseModel): chat: dict variables: dict | None = None folder_id: str | None = None + task_id: str | None = None class ChatImportForm(ChatForm): @@ -344,6 +349,7 @@ class ChatResponse(BaseModel): meta: dict = {} variables: dict = {} folder_id: str | None = None + task_id: str | None = None todos: list | None = None summary: str | None = None @@ -731,6 +737,7 @@ class ChatTable: ), 'chat': self._clean_null_bytes(form_data.chat), 'folder_id': form_data.folder_id, + 'task_id': form_data.task_id, 'meta': internal_meta or {}, 'timer_at': timer_at, 'variables': form_data.variables or {}, diff --git a/backend/open_webui/models/comments.py b/backend/open_webui/models/comments.py index 4255536867..5a6beeca8f 100644 --- a/backend/open_webui/models/comments.py +++ b/backend/open_webui/models/comments.py @@ -9,7 +9,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator from sqlalchemy import JSON, BigInteger, Column, Index, Text, UniqueConstraint, case, delete, func, select, update from sqlalchemy.ext.asyncio import AsyncSession -ResourceType = Literal['model', 'knowledge', 'prompt', 'skill', 'tool', 'note', 'chat'] +ResourceType = Literal['model', 'knowledge', 'prompt', 'skill', 'tool', 'note', 'chat', 'task'] class Comment(Base): diff --git a/backend/open_webui/models/folders.py b/backend/open_webui/models/folders.py index c238d5f9f4..3f64d6e50c 100644 --- a/backend/open_webui/models/folders.py +++ b/backend/open_webui/models/folders.py @@ -27,6 +27,8 @@ class Folder(Base): meta = Column(JSON, nullable=True) data = Column(JSON, nullable=True) is_expanded = Column(Boolean, default=False) + # The last task number given out here; tasks take the next one, so numbers are never reused. + task_counter = Column(BigInteger, nullable=False, server_default='0') created_at = Column(BigInteger) updated_at = Column(BigInteger) diff --git a/backend/open_webui/models/notifications.py b/backend/open_webui/models/notifications.py index bc647d21ba..273dc876b1 100644 --- a/backend/open_webui/models/notifications.py +++ b/backend/open_webui/models/notifications.py @@ -59,6 +59,10 @@ class ChatMentionData(NotificationData): model_name: str +class TaskAssignedData(NotificationData): + number: int + + class SystemData(NotificationData): message: str = Field(min_length=1, max_length=2000) @@ -72,6 +76,7 @@ DATA_TYPES = { 'channel.replied': NotificationData, 'calendar.alert_triggered': ReminderData, 'automation.run_failed': NotificationData, + 'task.assigned': TaskAssignedData, 'system.announcement': SystemData, } diff --git a/backend/open_webui/models/tags.py b/backend/open_webui/models/tags.py index 0d9e87866f..e5ea13a4b1 100644 --- a/backend/open_webui/models/tags.py +++ b/backend/open_webui/models/tags.py @@ -51,7 +51,7 @@ class ResourceTag(Base): __tablename__ = 'resource_tag' id = Column(Text, primary_key=True) - resource_type = Column(Text, nullable=False) # "chat" or "note" + resource_type = Column(Text, nullable=False) # "chat", "note" or "task" resource_id = Column(Text, nullable=False) tag_id = Column(Text, nullable=False) user_id = Column(Text, nullable=False) # the resource's owner, whose tag this is diff --git a/backend/open_webui/models/tasks.py b/backend/open_webui/models/tasks.py new file mode 100644 index 0000000000..c00e2f6b35 --- /dev/null +++ b/backend/open_webui/models/tasks.py @@ -0,0 +1,645 @@ +import re +import time +import uuid +from datetime import date +from typing import Literal, Optional + +from open_webui.internal.db import Base, get_async_db_context +from open_webui.models.comments import delete_resource_comments +from open_webui.models.folders import Folder +from open_webui.models.notifications import emit_changes +from open_webui.models.tags import Tags, delete_resource_tags, get_tag_id, resource_tag_filter +from open_webui.models.users import User +from pydantic import BaseModel, ConfigDict, Field, field_validator +from sqlalchemy import ( + JSON, + BigInteger, + Column, + ForeignKey, + Index, + Text, + UniqueConstraint, + and_, + case, + delete, + false, + func, + or_, + select, + update, +) +from sqlalchemy.ext.asyncio import AsyncSession + +# Priorities are the folder chats' scale, most urgent first; a task without one stores null. +TASK_PRIORITIES = ('urgent', 'high', 'medium', 'low') +TaskPriority = Literal['urgent', 'high', 'medium', 'low'] + +# A status's glyph is its category: views across folders group by it, moves map by it, and it sets +# the started, completed and canceled times. It's optional: a status without one has no category, +# and its tasks have none of those times. +STATUS_GLYPHS = ('backlog', 'todo', 'in_progress', 'waiting', 'done', 'canceled') +STARTED_GLYPHS = ('in_progress', 'waiting') + +# The workflow of a folder that has no statuses of its own. It isn't written to the folder; +# the ids are the glyph names, so tasks keep their status if the folder later saves these. +DEFAULT_TASK_STATUSES = [ + {'id': 'backlog', 'name': 'Backlog', 'glyph': 'backlog', 'color': 'gray'}, + {'id': 'todo', 'name': 'To do', 'glyph': 'todo', 'color': 'gray'}, + {'id': 'in_progress', 'name': 'In progress', 'glyph': 'in_progress', 'color': 'amber'}, + {'id': 'done', 'name': 'Done', 'glyph': 'done', 'color': 'violet'}, + {'id': 'canceled', 'name': 'Canceled', 'glyph': 'canceled', 'color': 'gray'}, +] + +TASK_PAGE_SIZE = 50 # FOLDER_PAGE_SIZE in src/lib/utils/folders.ts +TASK_SORT_KEYS = ('updated_at', 'created_at', 'priority', 'due_date', 'title') +# Linear leaves edits made in an issue's first three minutes out of its history. +HISTORY_GRACE_SECONDS = 3 * 60 + + +def task_statuses(folder_meta: dict | None) -> list[dict]: + """The folder's statuses in order, or the default workflow when it has none.""" + statuses = [] + for item in (folder_meta or {}).get('statuses') or []: + if ( + isinstance(item, dict) + and isinstance(item.get('id'), str) + and 0 < len(item['id']) <= 64 + and item['id'] != 'none' + and all(status['id'] != item['id'] for status in statuses) + ): + glyph = item.get('glyph') if item.get('glyph') in STATUS_GLYPHS else None + statuses.append({**item, 'glyph': glyph}) + return statuses or DEFAULT_TASK_STATUSES + + +def status_glyph(statuses: list[dict], status: str | None) -> str | None: + return next((item['glyph'] for item in statuses if item['id'] == status), None) + + +def default_status(statuses: list[dict]) -> str: + """Where new tasks start: the first status to do, else the first status.""" + return next((item['id'] for item in statuses if item['glyph'] == 'todo'), statuses[0]['id']) + + +def matching_status(statuses: list[dict], glyph: str | None) -> str: + """The first status with this glyph, for a task whose status is gone or that changes folder.""" + return next((item['id'] for item in statuses if item['glyph'] == glyph), default_status(statuses)) + + +def parse_due_date(value: str | None) -> str | None: + if value is None: + return None + return date.fromisoformat(value).isoformat() + + +# Task DB Schema + + +class Task(Base): + __tablename__ = 'task' + + id = Column(Text, primary_key=True) + folder_id = Column(Text, nullable=False) + number = Column(BigInteger, nullable=False) + user_id = Column(Text, nullable=False) + + title = Column(Text, nullable=False) + description = Column(Text, nullable=True) + status = Column(Text, nullable=False) + priority = Column(Text, nullable=True) + assignee_id = Column(Text, nullable=True) + due_date = Column(Text, nullable=True) + + # Time in status works as it does for folder chats: seconds banked per status, plus when the current one began. + status_at = Column(BigInteger, nullable=False) + status_durations = Column(JSON, nullable=True) + started_at = Column(BigInteger, nullable=True) + completed_at = Column(BigInteger, nullable=True) + canceled_at = Column(BigInteger, nullable=True) + + data = Column(JSON, nullable=True) + meta = Column(JSON, nullable=True) + + created_at = Column(BigInteger, nullable=False) + updated_at = Column(BigInteger, nullable=False) + + __table_args__ = ( + UniqueConstraint('folder_id', 'number', name='uq_task_folder_number'), + Index('ix_task_assignee_id', 'assignee_id'), + Index('ix_task_user_id', 'user_id'), + ) + + +class TaskHistory(Base): + __tablename__ = 'task_history' + + id = Column(Text, primary_key=True) + task_id = Column(Text, ForeignKey('task.id', ondelete='CASCADE'), nullable=False) + user_id = Column(Text, nullable=True) + # One row per changed field. The value is what the task's column held; when it's an id + # (a status, person or folder), the name is what that was called then. + field = Column(Text, nullable=False) + old_value = Column(Text, nullable=True) + new_value = Column(Text, nullable=True) + old_name = Column(Text, nullable=True) + new_name = Column(Text, nullable=True) + created_at = Column(BigInteger, nullable=False) + + __table_args__ = (Index('ix_task_history_task_id_created_at', 'task_id', 'created_at'),) + + +class TaskModel(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: str + folder_id: str + number: int + user_id: str + + title: str + description: Optional[str] = None + status: str + priority: Optional[str] = None + assignee_id: Optional[str] = None + due_date: Optional[str] = None + + status_at: int + status_durations: Optional[dict] = None + started_at: Optional[int] = None + completed_at: Optional[int] = None + canceled_at: Optional[int] = None + + data: Optional[dict] = None + meta: Optional[dict] = None + + created_at: int + updated_at: int + + +class TaskHistoryModel(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: str + task_id: str + user_id: Optional[str] = None + field: str + old_value: Optional[str] = None + new_value: Optional[str] = None + old_name: Optional[str] = None + new_name: Optional[str] = None + created_at: int + + +class TaskForm(BaseModel): + folder_id: str + title: str = Field(min_length=1) + description: Optional[str] = None + status: Optional[str] = None + priority: Optional[TaskPriority] = None + assignee_id: Optional[str] = None + due_date: Optional[str] = None + # Tag names; they're kept in the folder owner's tags, as a shared note's are in its owner's. + tags: list[str] = Field(default_factory=list, max_length=50) + + @field_validator('tags') + @classmethod + def check_tags(cls, value: list[str]) -> list[str]: + names = list(dict.fromkeys(name.strip() for name in value if name.strip())) + if any(len(name) > 64 for name in names): + raise ValueError('A tag name can be at most 64 characters') + # 'none' is how filters name untagged tasks. + if any(get_tag_id(name) == 'none' for name in names): + raise ValueError('Tag name cannot be "None"') + return names + + @field_validator('title') + @classmethod + def strip_title(cls, value: str) -> str: + if not value.strip(): + raise ValueError('A task needs a title') + return value.strip() + + @field_validator('due_date') + @classmethod + def check_due_date(cls, value): + return parse_due_date(value) + + +class TaskUpdateForm(BaseModel): + """Every field is optional: a missing field stays as it is, and null clears it.""" + + folder_id: Optional[str] = None + title: Optional[str] = None + description: Optional[str] = None + status: Optional[str] = None + priority: Optional[TaskPriority] = None + assignee_id: Optional[str] = None + due_date: Optional[str] = None + + @field_validator('title') + @classmethod + def strip_title(cls, value): + if value is not None and not value.strip(): + raise ValueError('A task needs a title') + return value.strip() if value is not None else None + + @field_validator('due_date') + @classmethod + def check_due_date(cls, value): + return parse_due_date(value) + + +def apply_category(task: Task, glyph: str | None, now: int) -> None: + """Set the started, completed and canceled times a task's category implies.""" + if glyph in STARTED_GLYPHS: + task.started_at = task.started_at or now + task.completed_at = None + task.canceled_at = None + elif glyph == 'done': + task.completed_at = task.completed_at or now + task.canceled_at = None + elif glyph == 'canceled': + task.canceled_at = task.canceled_at or now + task.completed_at = None + else: + task.started_at = None + task.completed_at = None + task.canceled_at = None + + +def set_status(task: Task, status: str, statuses: list[dict], now: int, old_statuses: list[dict] | None = None) -> None: + """Move a task to a status, banking the time spent in the old one, as folder chats do. + + `old_statuses` are the ones its current status is from, when they're not `statuses`. + """ + if task.status == status: + return + durations = dict(task.status_durations or {}) + if task.status and task.status_at is not None: + durations[task.status] = int(durations.get(task.status) or 0) + max(0, now - task.status_at) + task.status_durations = durations + previous_glyph = status_glyph(old_statuses or statuses, task.status) + task.status = status + task.status_at = now + glyph = status_glyph(statuses, status) + if glyph != previous_glyph: + # Entering done or canceled again starts its clock again. + task.completed_at = task.completed_at if glyph != 'done' else None + task.canceled_at = task.canceled_at if glyph != 'canceled' else None + apply_category(task, glyph, now) + + +def priority_rank(): + """Most urgent first when sorted ascending; no priority last.""" + return case( + *[(Task.priority == priority, index) for index, priority in enumerate(TASK_PRIORITIES)], + else_=len(TASK_PRIORITIES), + ) + + +async def history_rows( + db: AsyncSession, + task_id: str, + user_id: str, + changes: dict, + statuses: list[dict], + now: int, + old_statuses: list[dict] | None = None, +) -> list[TaskHistory]: + """One row per changed field, with the names its ids went by at the time.""" + ids = {value for field in ('assignee_id', 'folder_id') for value in changes.get(field, []) if value} + people = dict((await db.execute(select(User.id, User.name).where(User.id.in_(ids)))).all()) if ids else {} + folders = dict((await db.execute(select(Folder.id, Folder.name).where(Folder.id.in_(ids)))).all()) if ids else {} + + def name(field, item, statuses): + if item is None: + return None + if field == 'status': + return next((status.get('name') for status in statuses if status['id'] == item), None) + if field == 'assignee_id': + return people.get(item) + if field == 'folder_id': + return folders.get(item) + return None + + def value(item): + return None if item is None else str(item) + + return [ + TaskHistory( + id=str(uuid.uuid4()), + task_id=task_id, + user_id=user_id, + field=field, + old_value=value(old), + new_value=value(new), + old_name=name(field, old, old_statuses or statuses), + new_name=name(field, new, statuses), + created_at=now, + ) + for field, (old, new) in changes.items() + ] + + +class TasksTable: + async def next_number(self, folder_id: str, db: AsyncSession) -> int: + """Take the folder's next task number; the caller's transaction keeps it.""" + return await db.scalar( + update(Folder) + .where(Folder.id == folder_id) + .values(task_counter=Folder.task_counter + 1) + .returning(Folder.task_counter) + ) + + async def insert_new_task( + self, user_id: str, form: TaskForm, statuses: list[dict], db: Optional[AsyncSession] = None + ) -> TaskModel: + async with get_async_db_context(db) as db: + now = int(time.time()) + task = Task( + id=str(uuid.uuid4()), + folder_id=form.folder_id, + number=await self.next_number(form.folder_id, db), + user_id=user_id, + title=form.title, + description=form.description, + priority=form.priority, + assignee_id=form.assignee_id, + due_date=form.due_date, + status_durations={}, + created_at=now, + updated_at=now, + ) + set_status(task, form.status or default_status(statuses), statuses, now) + db.add(task) + await db.commit() + return TaskModel.model_validate(task) + + async def get_task_by_id(self, id: str, db: Optional[AsyncSession] = None) -> Optional[TaskModel]: + async with get_async_db_context(db) as db: + task = await db.get(Task, id) + return TaskModel.model_validate(task) if task else None + + async def get_task_by_number( + self, folder_id: str, number: int, db: Optional[AsyncSession] = None + ) -> Optional[TaskModel]: + async with get_async_db_context(db) as db: + task = await db.scalar(select(Task).where(Task.folder_id == folder_id, Task.number == number)) + return TaskModel.model_validate(task) if task else None + + async def get_tasks( + self, + readable_folder_ids, + *, + folder_id: Optional[str] = None, + assignee_id: Optional[str] = None, + creator_id: Optional[str] = None, + statuses: Optional[list[str]] = None, + categories: Optional[list[str]] = None, + priorities: Optional[list[str]] = None, + assignee_ids: Optional[list[str]] = None, + folder_ids: Optional[list[str]] = None, + tag_ids: Optional[list[str]] = None, + search: Optional[str] = None, + sort_by: str = 'updated_at', + sort_dir: str = 'desc', + page: int = 1, + limit: int = TASK_PAGE_SIZE, + db: Optional[AsyncSession] = None, + ) -> dict: + """A page of the tasks in folders the caller may read (`readable_folder_ids`, a select of ids). + + In the list filters, 'none' stands for an unset priority or assignee, or no tags. + """ + conditions = [Task.folder_id.in_(readable_folder_ids)] + if folder_id: + conditions.append(Task.folder_id == folder_id) + if folder_ids: + conditions.append(Task.folder_id.in_(folder_ids)) + if tag_ids: + conditions.append(resource_tag_filter('task', Task.id, tag_ids)) + if assignee_id: + conditions.append(Task.assignee_id == assignee_id) + if creator_id: + conditions.append(Task.user_id == creator_id) + if statuses: + conditions.append(Task.status.in_(statuses)) + for column, values in ((Task.priority, priorities), (Task.assignee_id, assignee_ids)): + if values: + named = [value for value in values if value != 'none'] + conditions.append(or_(column.in_(named), column.is_(None)) if 'none' in values else column.in_(named)) + if search and search.strip(): + text = search.strip() + matches = [Task.title.ilike(f'%{text}%')] + if number := re.fullmatch(r'#?(\d{1,18})', text): + matches.append(Task.number == int(number.group(1))) + conditions.append(or_(*matches)) + + ascending = sort_dir == 'asc' + + def direction(column, up): + return column.asc() if up else column.desc() + + if sort_by == 'priority': + # Descending puts the most urgent first. + order = [direction(priority_rank(), not ascending)] + elif sort_by == 'due_date': + order = [Task.due_date.is_(None), direction(Task.due_date, ascending)] + elif sort_by == 'title': + order = [direction(func.lower(Task.title), ascending)] + else: + order = [direction(Task.created_at if sort_by == 'created_at' else Task.updated_at, ascending)] + order.append(Task.number.desc()) + + async with get_async_db_context(db) as db: + if categories: + # Categories live on each folder's statuses, so they become those statuses, folder by folder. + in_folders = select(Task.folder_id).where(*conditions).distinct() + folders = (await db.execute(select(Folder.id, Folder.meta).where(Folder.id.in_(in_folders)))).all() + matches = [] + for folder_id, meta in folders: + ids = [item['id'] for item in task_statuses(meta) if (item['glyph'] or 'none') in categories] + if ids: + matches.append(and_(Task.folder_id == folder_id, Task.status.in_(ids))) + conditions.append(or_(false(), *matches)) + total = await db.scalar(select(func.count(Task.id)).where(*conditions)) + rows = ( + await db.scalars( + select(Task).where(*conditions).order_by(*order).offset((page - 1) * limit).limit(limit) + ) + ).all() + return { + 'tasks': [TaskModel.model_validate(task) for task in rows], + 'total': total, + 'has_more': page * limit < total, + } + + async def update_task( + self, + id: str, + user_id: str, + changes: dict, + statuses: list[dict], + db: Optional[AsyncSession] = None, + ) -> Optional[TaskModel]: + """Apply checked changes and record what changed; `changes` holds only the fields to set.""" + async with get_async_db_context(db) as db: + task = await db.get(Task, id) + if task is None: + return None + now = int(time.time()) + recorded = {} + for field, value in changes.items(): + previous = getattr(task, field) + if previous == value: + continue + if field == 'status': + set_status(task, value, statuses, now) + else: + setattr(task, field, value) + # The description has no history of its own; its changes aren't listed. + if field != 'description': + recorded[field] = [previous, value] + if recorded or 'description' in changes: + task.updated_at = now + if recorded and not (task.user_id == user_id and now - task.created_at < HISTORY_GRACE_SECONDS): + db.add_all(await history_rows(db, id, user_id, recorded, statuses, now)) + await db.commit() + return TaskModel.model_validate(task) + + async def move_task( + self, + id: str, + user_id: str, + folder_id: str, + statuses: list[dict], + keep_assignee: bool, + db: Optional[AsyncSession] = None, + ) -> Optional[TaskModel]: + """Move a task to another folder, with that folder's next number and its matching status.""" + async with get_async_db_context(db) as db: + task = await db.get(Task, id) + if task is None or task.folder_id == folder_id: + return TaskModel.model_validate(task) if task else None + now = int(time.time()) + old_folder = await db.get(Folder, task.folder_id) + old_statuses = task_statuses(old_folder.meta if old_folder else None) + recorded = {'folder_id': [task.folder_id, folder_id]} + number = await self.next_number(folder_id, db) + if number != task.number: + recorded['number'] = [task.number, number] + task.folder_id = folder_id + task.number = number + category = status_glyph(old_statuses, task.status) + status = ( + task.status + if any(item['id'] == task.status for item in statuses) + and status_glyph(statuses, task.status) == category + else matching_status(statuses, category) + ) + if status != task.status: + recorded['status'] = [task.status, status] + set_status(task, status, statuses, now, old_statuses) + elif status_glyph(statuses, status) != category: + apply_category(task, status_glyph(statuses, status), now) + if task.assignee_id and not keep_assignee: + recorded['assignee_id'] = [task.assignee_id, None] + task.assignee_id = None + task.updated_at = now + db.add_all(await history_rows(db, id, user_id, recorded, statuses, now, old_statuses)) + await db.commit() + new_folder = await db.get(Folder, folder_id) + if old_folder and new_folder and old_folder.user_id != new_folder.user_id: + # Tags are the folder owner's, so a task moving to someone else's folder takes its tags into theirs. + tags = (await Tags.get_tags_by_resources('task', [id], db=db)).get(id, []) + await delete_resource_tags('task', [id], db) + await db.commit() + await Tags.set_resource_tags('task', id, [tag['name'] for tag in tags], new_folder.user_id, db=db) + return TaskModel.model_validate(task) + + async def remap_statuses( + self, + folder_id: str, + old_statuses: list[dict], + statuses: list[dict], + db: Optional[AsyncSession] = None, + ) -> None: + """After a folder's statuses change, move tasks off removed statuses and refresh their times.""" + async with get_async_db_context(db) as db: + now = int(time.time()) + ids = {item['id'] for item in statuses} + for task in (await db.scalars(select(Task).where(Task.folder_id == folder_id))).all(): + category = status_glyph(old_statuses, task.status) + if task.status not in ids: + set_status(task, matching_status(statuses, category), statuses, now, old_statuses) + task.updated_at = now + elif status_glyph(statuses, task.status) != category: + # Same status with a new category: its clock keeps running, and the times follow. + apply_category(task, status_glyph(statuses, task.status), now) + task.updated_at = now + await db.commit() + + async def unassign( + self, + *, + folder_ids: Optional[list[str]] = None, + keep_user_ids: Optional[set[str]] = None, + user_id: Optional[str] = None, + db: Optional[AsyncSession] = None, + ) -> None: + """Clear assignees: in folders, those not in keep_user_ids; or one user everywhere.""" + conditions = [Task.assignee_id.is_not(None)] + if folder_ids is not None: + conditions.append(Task.folder_id.in_(folder_ids)) + if keep_user_ids is not None: + conditions.append(Task.assignee_id.not_in(keep_user_ids)) + if user_id is not None: + conditions.append(Task.assignee_id == user_id) + async with get_async_db_context(db) as db: + await db.execute(update(Task).where(*conditions).values(assignee_id=None)) + await db.commit() + + async def delete_tasks(self, ids: list[str], db: Optional[AsyncSession] = None) -> None: + """Delete tasks with their history, comments, tags and notifications; their chats stay, unlinked.""" + if not ids: + return + from open_webui.models.chats import Chat + + async with get_async_db_context(db) as db: + await db.execute(update(Chat).where(Chat.task_id.in_(ids)).values(task_id=None)) + recipients = await delete_resource_comments('task', ids, db=db) + await delete_resource_tags('task', ids, db) + await db.execute(delete(TaskHistory).where(TaskHistory.task_id.in_(ids))) + await db.execute(delete(Task).where(Task.id.in_(ids))) + await db.commit() + await emit_changes(recipients) + + async def delete_tasks_by_folder_ids(self, folder_ids: list[str], db: Optional[AsyncSession] = None) -> None: + async with get_async_db_context(db) as session: + ids = list((await session.scalars(select(Task.id).where(Task.folder_id.in_(folder_ids)))).all()) + await self.delete_tasks(ids, db=db) + + async def count_tasks_by_folder_ids(self, folder_ids: list[str], db: Optional[AsyncSession] = None) -> int: + async with get_async_db_context(db) as db: + return await db.scalar(select(func.count(Task.id)).where(Task.folder_id.in_(folder_ids))) or 0 + + async def get_history(self, task_id: str, db: Optional[AsyncSession] = None) -> list[TaskHistoryModel]: + async with get_async_db_context(db) as db: + rows = await db.scalars( + select(TaskHistory).where(TaskHistory.task_id == task_id).order_by(TaskHistory.created_at) + ) + return [TaskHistoryModel.model_validate(row) for row in rows.all()] + + async def get_chat_counts(self, task_ids: list[str], db: Optional[AsyncSession] = None) -> dict[str, int]: + if not task_ids: + return {} + from open_webui.models.chats import Chat + + async with get_async_db_context(db) as db: + rows = await db.execute( + select(Chat.task_id, func.count(Chat.id)).where(Chat.task_id.in_(task_ids)).group_by(Chat.task_id) + ) + return dict(rows.all()) + + +Tasks = TasksTable() diff --git a/backend/open_webui/models/users.py b/backend/open_webui/models/users.py index 6656b461f2..33e1367409 100644 --- a/backend/open_webui/models/users.py +++ b/backend/open_webui/models/users.py @@ -899,6 +899,9 @@ class UsersTable: from open_webui.models.access_grants import AccessGrant await session.execute(delete(AccessGrant).filter_by(principal_type='user', principal_id=id)) + from open_webui.models.tasks import Task + + await session.execute(update(Task).where(Task.assignee_id == id).values(assignee_id=None)) await session.execute(delete(User).where(User.id == id)) await session.commit() return True diff --git a/backend/open_webui/routers/auths.py b/backend/open_webui/routers/auths.py index c1feebb062..073194e701 100644 --- a/backend/open_webui/routers/auths.py +++ b/backend/open_webui/routers/auths.py @@ -136,6 +136,7 @@ ADMIN_CONFIG_KEYS = { 'ENABLE_AUTOMATION_WEBHOOKS': 'automations.webhooks.enable', 'ENABLE_CHANNELS': 'channels.enable', 'ENABLE_TEAMS': 'teams.enable', + 'ENABLE_TASKS': 'tasks.enable', 'ENABLE_COMMENTS': 'comments.enable', 'ENABLE_NOTIFICATIONS': 'notifications.enable', 'ENABLE_ENCRYPTED_CHANNELS': 'channels.encryption.enable', @@ -1196,6 +1197,7 @@ class AdminConfig(MfaConfigForm): ENABLE_AUTOMATION_WEBHOOKS: bool = True ENABLE_CHANNELS: bool ENABLE_TEAMS: bool = False + ENABLE_TASKS: bool = False ENABLE_COMMENTS: bool = False ENABLE_NOTIFICATIONS: bool = True ENABLE_ENCRYPTED_CHANNELS: bool = False diff --git a/backend/open_webui/routers/chats.py b/backend/open_webui/routers/chats.py index 5c52a7a671..a4969157f4 100644 --- a/backend/open_webui/routers/chats.py +++ b/backend/open_webui/routers/chats.py @@ -920,6 +920,18 @@ async def create_new_chat( status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND, ) + if form_data.task_id is not None: + # A chat started from a task runs in the task's folder. + from open_webui.models.tasks import Tasks + from open_webui.utils.access_control.tasks import has_task_access + + task = await Tasks.get_task_by_id(form_data.task_id, db=db) + if ( + task is None + or task.folder_id != form_data.folder_id + or not await has_task_access(user.id, task, 'read', db) + ): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) normalize_machine_id(form_data.chat) await require_chat_folder_machine(form_data.folder_id, machine_id_of(form_data.chat)) directory = await get_folder_directory(form_data.folder_id) diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py index 0e8325daf0..f4ef253f97 100644 --- a/backend/open_webui/routers/folders.py +++ b/backend/open_webui/routers/folders.py @@ -32,6 +32,7 @@ from open_webui.models.groups import Groups from open_webui.models.memories import Memories from open_webui.models.notes import NoteListResponse, Notes, NoteUserResponse from open_webui.models.shared_chats import ChatShareMode +from open_webui.models.tasks import Tasks, task_statuses 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 @@ -58,6 +59,7 @@ FolderActivity = Literal['unread', 'generating', 'waiting_for_approval', 'idle'] from open_webui.utils.access_control.folders import has_folder_access as _has_folder_access +from open_webui.utils.access_control.tasks import folder_user_ids async def get_folder_unread_counts(user_id: str, db: AsyncSession | None = None) -> dict[str, int]: @@ -78,6 +80,14 @@ async def get_folder_unread_counts(user_id: str, db: AsyncSession | None = None) return unread_counts +async def unassign_tasks_without_access(folder_ids: list[str], db: AsyncSession) -> None: + """Tasks keep only assignees who can still edit their folder.""" + for folder in await Folders.get_folders_by_ids(folder_ids, db=db): + writers = await folder_user_ids(folder, 'write', db) + if writers is not None: + await Tasks.unassign(folder_ids=[folder.id], keep_user_ids=writers, db=db) + + async def check_folders_permission(request: Request, user, db=None): """Verify the folders feature is enabled and the user has permission.""" config = await Config.get_many('folders.enable', 'user.permissions') @@ -495,7 +505,11 @@ async def update_folder_name_by_id( ) try: + old_statuses = task_statuses(folder.meta) folder = await Folders.update_folder_by_id_and_user_id(id, folder.user_id, form_data, db=db) + if form_data.meta and 'statuses' in form_data.meta: + # Tasks on a removed status move to the nearest one left. + await Tasks.remap_statuses(id, old_statuses, task_statuses(folder.meta), db=db) await publish_event( request, EVENTS.FOLDER_UPDATED, @@ -557,6 +571,10 @@ async def update_folder_parent_id_by_id( try: folder = await Folders.update_folder_parent_id_by_id_and_user_id(id, user.id, form_data.parent_id, db=db) + # A new parent can change who inherits access. + await unassign_tasks_without_access( + await Folders.get_folder_ids_by_id_and_user_id_in_subtree(id, user.id, db=db), db + ) await publish_event( request, EVENTS.FOLDER_PARENT_UPDATED, @@ -667,6 +685,9 @@ async def update_folder_access_by_id( id, folder.user_id, FolderUpdateForm(data={'share_mode': form_data.share_mode}), db=db ) + await unassign_tasks_without_access( + await Folders.get_folder_ids_by_id_and_user_id_in_subtree(id, folder.user_id, db=db), db + ) grants = await AccessGrants.get_grants_by_resource('folder', id, db=db) await publish_event( request, @@ -1111,6 +1132,9 @@ async def delete_folder_by_id( detail=ERROR_MESSAGES.ACCESS_PROHIBITED, ) + # Tasks live only in folders, so they go with the folder whatever happens to its chats and notes. + await Tasks.delete_tasks_by_folder_ids(folder_ids, db=db) + folders = [] folders.append(folder) while folders: diff --git a/backend/open_webui/routers/tasks.py b/backend/open_webui/routers/tasks.py new file mode 100644 index 0000000000..b08a93f319 --- /dev/null +++ b/backend/open_webui/routers/tasks.py @@ -0,0 +1,513 @@ +import logging +import time +from typing import Literal, Optional + +from fastapi import APIRouter, Depends, HTTPException, Query, Request, status +from open_webui.constants import ERROR_MESSAGES +from open_webui.events import EVENTS, publish_event +from open_webui.internal.db import get_async_db_context, get_async_session +from open_webui.models.chats import Chat, ChatTitleIdResponse +from open_webui.models.config import Config +from open_webui.models.folders import Folders +from open_webui.models.groups import Groups +from open_webui.models.notifications import emit_changes, insert_notifications +from open_webui.models.tags import TagModel, Tags, get_tag_id +from open_webui.models.tasks import ( + TASK_SORT_KEYS, + STATUS_GLYPHS, + Task, + TaskForm, + TaskHistoryModel, + TaskModel, + Tasks, + TaskUpdateForm, + task_statuses, +) +from open_webui.models.users import Users +from open_webui.routers.chats import add_active_state_to_chat_list +from open_webui.routers.folders import check_folders_permission +from open_webui.socket.main import emit_to_users +from open_webui.utils.access_control.folders import accessible_folder_ids, has_folder_access +from open_webui.utils.access_control.tasks import folder_user_ids, has_task_access +from open_webui.utils.auth import get_verified_user +from pydantic import BaseModel, Field +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +log = logging.getLogger(__name__) + +router = APIRouter() + + +async def check_tasks_enabled(request: Request, user=Depends(get_verified_user)): + if not await Config.get('tasks.enable'): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.FEATURE_DISABLED('Tasks')) + # Tasks live in folders, so they need folders too. + await check_folders_permission(request, user) + + +class TaskResponse(TaskModel): + folder: Optional[dict] = None + user: Optional[dict] = None + assignee: Optional[dict] = None + chat_count: int = 0 + write_access: Optional[bool] = None + # The task's tags as list rows show them: id, name and color. + tags: list[dict] = [] + + +class TaskListResponse(BaseModel): + tasks: list[TaskResponse] + total: int + has_more: bool + + +class TaskHistoryResponse(TaskHistoryModel): + user: Optional[dict] = None + + +class TaskChatResponse(ChatTitleIdResponse): + user_id: str + owner_name: Optional[str] = None + + +async def task_responses(tasks: list[TaskModel], db: AsyncSession, user=None) -> list[TaskResponse]: + """Tasks with their folder, creator and assignee, fetched once for the whole list. + + With a user, each task also says whether that user may edit it, checked once per folder. + """ + folders = { + folder.id: folder for folder in await Folders.get_folders_by_ids(list({t.folder_id for t in tasks}), db=db) + } + writable = ( + {id: await has_folder_access(user.id, folder, 'write', db) for id, folder in folders.items()} if user else {} + ) + user_ids = {t.user_id for t in tasks} | {t.assignee_id for t in tasks if t.assignee_id} + users = {u.id: {'id': u.id, 'name': u.name} for u in await Users.get_users_by_user_ids(list(user_ids), db=db)} + chat_counts = await Tasks.get_chat_counts([t.id for t in tasks], db=db) + tags = await Tags.get_tags_by_resources('task', [t.id for t in tasks], db=db) + responses = [] + for task in tasks: + folder = folders.get(task.folder_id) + responses.append( + TaskResponse( + **task.model_dump(), + folder=( + { + 'id': folder.id, + 'name': folder.name, + 'icon': (folder.meta or {}).get('icon'), + 'statuses': (folder.meta or {}).get('statuses') or [], + } + if folder + else None + ), + user=users.get(task.user_id), + assignee=users.get(task.assignee_id) if task.assignee_id else None, + chat_count=chat_counts.get(task.id, 0), + write_access=writable.get(task.folder_id) if user else None, + tags=tags.get(task.id, []), + ) + ) + return responses + + +async def get_readable_task(id: str, user, db: AsyncSession, permission: str = 'read') -> TaskModel: + task = await Tasks.get_task_by_id(id, db=db) + if task is None or not await has_task_access(user.id, task, 'read', db): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + if permission == 'write' and not await has_task_access(user.id, task, 'write', db): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + return task + + +async def get_writable_folder(folder_id: str, user, db: AsyncSession): + folder = await Folders.get_folder_by_id(folder_id, db=db) + if folder is None or not await has_folder_access(user.id, folder, 'write', db): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + return folder + + +def check_status(statuses: list[dict], value: str | None) -> None: + if value is not None and all(item['id'] != value for item in statuses): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Unknown status for this folder') + + +async def check_assignee(folder, assignee_id: str | None, db: AsyncSession) -> None: + if assignee_id is None: + return + writers = await folder_user_ids(folder, 'write', db) + if writers is None: + if not await Users.get_user_by_id(assignee_id, db=db): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Unknown assignee') + elif assignee_id not in writers: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail='The assignee must be able to edit the folder' + ) + + +async def notify_task_change(task: TaskModel, actor_id: str, db: AsyncSession) -> None: + """Refresh open task lists and pages of everyone who can read the task's folder.""" + folder = await Folders.get_folder_by_id(task.folder_id, db=db) + readers = await folder_user_ids(folder, 'read', db) if folder else None + [response] = await task_responses([task], db) + await emit_to_users( + 'events', + {'data': {'type': 'task:changed', 'data': {'task': response.model_dump()}}}, + list(readers if readers is not None else {actor_id}), + ) + + +async def notify_assignee(task: TaskModel, actor_id: str) -> None: + if not task.assignee_id or task.assignee_id == actor_id: + return + async with get_async_db_context() as db: + recipients = await insert_notifications( + recipients={task.assignee_id: 'task.assigned'}, + event_key=f'task.assigned:{task.id}:{time.time_ns()}', + actor_id=actor_id, + resource_type='task', + resource_id=task.id, + object_type='task', + object_id=task.id, + data={'number': task.number}, + db=db, + ) + await db.commit() + await emit_changes(recipients) + + +############################ +# Tasks +############################ + + +@router.get('/', response_model=TaskListResponse, dependencies=[Depends(check_tasks_enabled)]) +async def get_tasks( + folder_id: Optional[str] = None, + assigned_to_me: bool = False, + created_by_me: bool = False, + search: Optional[str] = Query(default=None, max_length=256), + status_ids: list[str] = Query(default=[], alias='status'), + # 'none' keeps tasks whose status has no category. + categories: list[Literal[(*STATUS_GLYPHS, 'none')]] = Query(default=[], alias='category'), + priorities: list[str] = Query(default=[], alias='priority'), + assignee_ids: list[str] = Query(default=[], alias='assignee_id'), + folder_ids: list[str] = Query(default=[], alias='folder'), + # 'none' keeps untagged tasks. + tag_ids: list[str] = Query(default=[], alias='tag'), + sort_by: str = 'updated_at', + sort_dir: Literal['asc', 'desc'] = 'desc', + page: int = Query(default=1, ge=1), + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + if sort_by not in TASK_SORT_KEYS: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Unknown sort') + group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, db=db, include_inherited=True)} + page_data = await Tasks.get_tasks( + accessible_folder_ids(user.id, group_ids, 'read'), + folder_id=folder_id, + assignee_id=user.id if assigned_to_me else None, + creator_id=user.id if created_by_me else None, + statuses=status_ids, + categories=categories, + priorities=priorities, + assignee_ids=assignee_ids, + folder_ids=folder_ids, + tag_ids=tag_ids, + search=search, + sort_by=sort_by, + sort_dir=sort_dir, + page=page, + db=db, + ) + return TaskListResponse( + tasks=await task_responses(page_data['tasks'], db, user), + total=page_data['total'], + has_more=page_data['has_more'], + ) + + +@router.get('/assignees', dependencies=[Depends(check_tasks_enabled)]) +async def get_task_assignees( + folder_id: str, + query: str = Query(default='', max_length=256), + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + """Who a task in this folder can be assigned to: everyone who can edit the folder.""" + folder = await Folders.get_folder_by_id(folder_id, db=db) + if folder is None or not await has_folder_access(user.id, folder, 'read', db): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + writers = await folder_user_ids(folder, 'write', db) + if writers is None: + # Open to everyone: search the users instead of listing them all. + result = await Users.get_users(filter={'query': query}, limit=30, db=db) + users = result['users'] + else: + users = await Users.get_users_by_user_ids(list(writers), db=db) + text = query.strip().lower() + users = [u for u in users if not text or text in u.name.lower() or text in (u.email or '').lower()] + return sorted( + [{'id': u.id, 'name': u.name} for u in users], + key=lambda entry: (entry['id'] != user.id, entry['name'].casefold()), + ) + + +@router.get('/tags', dependencies=[Depends(check_tasks_enabled)]) +async def get_task_tag_counts( + folder_id: Optional[str] = None, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + """Tags on the tasks the user can read, or a folder's, with how many carry each; for filters and pickers.""" + group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, db=db, include_inherited=True)} + task_ids = select(Task.id).where(Task.folder_id.in_(accessible_folder_ids(user.id, group_ids, 'read'))) + if folder_id: + task_ids = task_ids.where(Task.folder_id == folder_id) + return await Tags.get_tag_counts('task', task_ids, db=db) + + +@router.get('/count', dependencies=[Depends(check_tasks_enabled)]) +async def count_folder_tasks( + folder_id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + """How many tasks a folder and its subfolders hold; they go with the folder when it's deleted.""" + folder = await Folders.get_folder_by_id(folder_id, db=db) + if folder is None or not await has_folder_access(user.id, folder, 'read', db): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + folder_ids = await Folders.get_folder_ids_by_id_and_user_id_in_subtree(folder_id, folder.user_id, db=db) + return {'count': await Tasks.count_tasks_by_folder_ids(folder_ids, db=db)} + + +@router.post('/create', response_model=TaskResponse, dependencies=[Depends(check_tasks_enabled)]) +async def create_task( + request: Request, + form_data: TaskForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + folder = await get_writable_folder(form_data.folder_id, user, db) + statuses = task_statuses(folder.meta) + check_status(statuses, form_data.status) + await check_assignee(folder, form_data.assignee_id, db) + + task = await Tasks.insert_new_task(user.id, form_data, statuses, db=db) + if form_data.tags: + await Tags.set_resource_tags('task', task.id, form_data.tags, folder.user_id, db=db) + await publish_event( + request, + EVENTS.TASK_CREATED, + actor=user, + subject_id=task.id, + data={'title': task.title, 'folder_id': task.folder_id, 'number': task.number}, + ) + await notify_assignee(task, user.id) + await notify_task_change(task, user.id, db) + [response] = await task_responses([task], db, user) + return response + + +@router.get('/id/{id}', response_model=TaskResponse, dependencies=[Depends(check_tasks_enabled)]) +async def get_task_by_id(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + task = await get_readable_task(id, user, db) + [response] = await task_responses([task], db, user) + return response + + +class TaskTagForm(BaseModel): + name: str = Field(min_length=1, max_length=64) + + +class TaskTagColorForm(TaskTagForm): + # A palette name chosen by the frontend, e.g. 'blue'; the server only stores it. + color: str = Field(min_length=1, max_length=32, pattern=r'^[a-z][a-z0-9-]*$') + + +async def get_tag_owner(task: TaskModel, db: AsyncSession) -> str: + """Whose tags a task's are: its folder owner's, so every task in a folder shares one set.""" + folder = await Folders.get_folder_by_id(task.folder_id, db=db) + if folder is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + return folder.user_id + + +@router.get('/id/{id}/tags', response_model=list[TagModel], dependencies=[Depends(check_tasks_enabled)]) +async def get_task_tags(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + await get_readable_task(id, user, db) + return await Tags.get_tags_by_resource('task', id, db=db) + + +@router.post('/id/{id}/tags', response_model=list[TagModel], dependencies=[Depends(check_tasks_enabled)]) +async def add_task_tag( + id: str, + form_data: TaskTagForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + task = await get_readable_task(id, user, db, 'write') + # 'none' is how filters name untagged tasks. + if get_tag_id(form_data.name) == 'none': + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT('Tag name cannot be "None"') + ) + await Tags.add_tag_to_resource('task', id, form_data.name, await get_tag_owner(task, db), db=db) + await notify_task_change(task, user.id, db) + return await Tags.get_tags_by_resource('task', id, db=db) + + +@router.delete('/id/{id}/tags', response_model=list[TagModel], dependencies=[Depends(check_tasks_enabled)]) +async def remove_task_tag( + id: str, + form_data: TaskTagForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + task = await get_readable_task(id, user, db, 'write') + await Tags.remove_tag_from_resource('task', id, form_data.name, await get_tag_owner(task, db), db=db) + await notify_task_change(task, user.id, db) + return await Tags.get_tags_by_resource('task', id, db=db) + + +@router.patch('/id/{id}/tags', response_model=list[TagModel], dependencies=[Depends(check_tasks_enabled)]) +async def update_task_tag_color( + id: str, + form_data: TaskTagColorForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + task = await get_readable_task(id, user, db, 'write') + tags = await Tags.get_tags_by_resources('task', [id], db=db) + if get_tag_id(form_data.name) not in [tag['id'] for tag in tags.get(id, [])]: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + owner = await get_tag_owner(task, db) + if not await Tags.update_tag_color_by_name_and_user_id(form_data.name, owner, form_data.color, db=db): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + await notify_task_change(task, user.id, db) + return await Tags.get_tags_by_resource('task', id, db=db) + + +@router.post('/id/{id}/update', response_model=TaskResponse, dependencies=[Depends(check_tasks_enabled)]) +async def update_task_by_id( + request: Request, + id: str, + form_data: TaskUpdateForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + task = await get_readable_task(id, user, db, 'write') + changes = form_data.model_dump(include=form_data.model_fields_set) + if 'title' in changes and changes['title'] is None: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='A task needs a title') + if 'status' in changes and changes['status'] is None: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='A task needs a status') + + folder_id = changes.pop('folder_id', None) or task.folder_id + folder = await get_writable_folder(folder_id, user, db) + statuses = task_statuses(folder.meta) + check_status(statuses, changes.get('status')) + if changes.get('assignee_id'): + await check_assignee(folder, changes['assignee_id'], db) + + previous_assignee = task.assignee_id + if folder_id != task.folder_id: + # The assignee comes along only if they can edit the new folder too. + if 'assignee_id' in changes: + keep = changes['assignee_id'] is not None + else: + writers = await folder_user_ids(folder, 'write', db) + keep = task.assignee_id is not None and (writers is None or task.assignee_id in writers) + task = await Tasks.move_task(id, user.id, folder_id, statuses, keep, db=db) + + task = await Tasks.update_task(id, user.id, changes, statuses, db=db) + await publish_event( + request, + EVENTS.TASK_UPDATED, + actor=user, + subject_id=task.id, + data={'title': task.title, 'folder_id': task.folder_id, 'number': task.number}, + ) + if task.assignee_id != previous_assignee and task.assignee_id: + await publish_event( + request, + EVENTS.TASK_ASSIGNED, + actor=user, + subject_id=task.id, + data={'title': task.title, 'assignee_id': task.assignee_id}, + ) + await notify_assignee(task, user.id) + await notify_task_change(task, user.id, db) + [response] = await task_responses([task], db, user) + return response + + +@router.delete('/id/{id}/delete', response_model=bool, dependencies=[Depends(check_tasks_enabled)]) +async def delete_task_by_id( + request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + task = await get_readable_task(id, user, db, 'write') + folder = await Folders.get_folder_by_id(task.folder_id, db=db) + if user.role != 'admin' and user.id not in {task.user_id, folder.user_id if folder else None}: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + await Tasks.delete_tasks([task.id], db=db) + await publish_event( + request, + EVENTS.TASK_DELETED, + actor=user, + subject_id=task.id, + data={'title': task.title, 'folder_id': task.folder_id}, + ) + readers = await folder_user_ids(folder, 'read', db) if folder else None + await emit_to_users( + 'events', + {'data': {'type': 'task:deleted', 'data': {'id': task.id, 'folder_id': task.folder_id}}}, + list(readers if readers is not None else {user.id}), + ) + return True + + +@router.get('/id/{id}/history', response_model=list[TaskHistoryResponse], dependencies=[Depends(check_tasks_enabled)]) +async def get_task_history(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + await get_readable_task(id, user, db) + history = await Tasks.get_history(id, db=db) + user_ids = list({row.user_id for row in history if row.user_id}) + users = {u.id: u.name for u in await Users.get_users_by_user_ids(user_ids, db=db)} + return [ + TaskHistoryResponse( + **row.model_dump(), + user={'id': row.user_id, 'name': users[row.user_id]} if row.user_id in users else None, + ) + for row in history + ] + + +@router.get('/id/{id}/chats', response_model=list[TaskChatResponse], dependencies=[Depends(check_tasks_enabled)]) +async def get_task_chats( + request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + """The chats started from this task that the caller can open, newest first.""" + from open_webui.models.chats import Chats + + await get_readable_task(id, user, db) + rows = ( + await db.execute( + select(Chat.id, Chat.title, Chat.user_id, Chat.meta, Chat.folder_id, Chat.updated_at, Chat.created_at) + .where(Chat.task_id == id, Chat.archived.is_(False)) + .order_by(Chat.updated_at.desc()) + ) + ).all() + visible = [row for row in rows if await Chats.has_chat_access(row.id, user, db=db, chat=row)] + owners = {u.id: u.name for u in await Users.get_users_by_user_ids(list({row.user_id for row in visible}), db=db)} + chats = [ + TaskChatResponse( + id=row.id, + title=row.title, + updated_at=row.updated_at, + created_at=row.created_at, + user_id=row.user_id, + owner_name=owners.get(row.user_id), + ) + for row in visible + ] + return await add_active_state_to_chat_list(request, chats, db=db) diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py index 65fee50032..805b570290 100644 --- a/backend/open_webui/tools/builtin.py +++ b/backend/open_webui/tools/builtin.py @@ -5066,6 +5066,364 @@ async def delete_automation( return JSONCodec.dumps({'error': str(e)}) +# Task tools + + +async def _task_context(user_id: str, chat_id: str | None, folder: str | None): + """The user, the folders they can read, and the chat's folder and task, for the task tools.""" + from open_webui.utils.access_control.folders import accessible_folder_ids + + user = await Users.get_user_by_id(user_id) + group_ids = {group.id for group in await Groups.get_groups_by_member_id(user_id, include_inherited=True)} + readable = accessible_folder_ids(user_id, group_ids, 'read') + chat = await Chats.get_chat_by_id(chat_id) if is_saved_chat_id(chat_id) else None + folder_id = None + if folder and folder.strip(): + from open_webui.internal.db import get_async_db_context + from open_webui.models.folders import Folder + from sqlalchemy import func, select + + async with get_async_db_context() as db: + rows = ( + await db.execute( + select(Folder.id, Folder.name).where( + Folder.id.in_(readable), func.lower(Folder.name) == folder.strip().lower() + ) + ) + ).all() + if not rows: + raise ValueError(f'No folder named "{folder}" that you can open') + if len(rows) > 1: + raise ValueError(f'More than one folder is named "{folder}"; rename one to tell them apart') + folder_id = rows[0].id + elif chat and chat.folder_id: + folder_id = chat.folder_id + return user, readable, folder_id, chat + + +async def _find_task(readable, folder_id: str | None, number, chat): + from open_webui.models.tasks import Tasks + + if number in (None, ''): + if chat and chat.task_id: + task = await Tasks.get_task_by_id(chat.task_id) + if task: + return task + raise ValueError('Give the task number') + if not folder_id: + raise ValueError('Give the folder the task is in') + try: + value = int(str(number).strip().lstrip('#')) + except ValueError: + raise ValueError(f'"{number}" is not a task number') + task = await Tasks.get_task_by_number(folder_id, value) + if task is None: + raise ValueError(f'No task #{value} in that folder') + return task + + +def _match_status(statuses: list[dict], value: str) -> str: + text = value.strip().lower() + for item in statuses: + if text in (item['id'].lower(), str(item.get('name') or '').lower()): + return item['id'] + names = ', '.join(str(item.get('name') or item['id']) for item in statuses) + raise ValueError(f'Unknown status "{value}". This folder has: {names}') + + +async def _match_assignee(folder, value: str, user) -> str | None: + from open_webui.utils.access_control.tasks import folder_user_ids + + text = value.strip().lower() + if text in ('', 'none', 'nobody', 'unassigned'): + return None + if text in ('me', 'myself'): + return user.id + writers = await folder_user_ids(folder, 'write') + if writers is None: + result = await Users.get_users(filter={'query': value.strip()}, limit=10) + candidates = result['users'] + else: + candidates = await Users.get_users_by_user_ids(list(writers)) + matches = [u for u in candidates if text in (u.name.lower(), (u.email or '').lower())] + if len(matches) != 1: + raise ValueError(f'No single person named "{value}" can edit this folder') + return matches[0].id + + +async def _task_summary(task, folder_name: str | None = None, statuses: list[dict] | None = None) -> dict: + from open_webui.models.folders import Folders + from open_webui.models.tasks import task_statuses + + if folder_name is None or statuses is None: + folder = await Folders.get_folder_by_id(task.folder_id) + folder_name = folder.name if folder else None + statuses = task_statuses(folder.meta if folder else None) + from open_webui.models.tags import Tags + + assignee = await Users.get_user_by_id(task.assignee_id) if task.assignee_id else None + tags = (await Tags.get_tags_by_resources('task', [task.id])).get(task.id, []) + return { + 'number': task.number, + 'folder': folder_name, + 'title': task.title, + 'status': next((item.get('name') for item in statuses if item['id'] == task.status), task.status), + 'priority': task.priority, + 'assignee': assignee.name if assignee else None, + 'due_date': task.due_date, + 'tags': [tag['name'] for tag in tags], + 'url': f'/tasks/{task.id}', + } + + +async def search_tasks( + query: str = '', + folder: str = '', + status: str = '', + assignee: str = '', + tag: str = '', + count: int = 10, + __user__: dict = None, + __chat_id__: str = None, +) -> str: + """ + Search tasks in folders the user can open. Each task has a number within its folder, like #12. + + :param query: Words in the title, or a task number like "#12"; empty lists recent tasks + :param folder: Folder name to search in; empty searches the chat's folder, or every folder outside one + :param status: Status category to keep: backlog, todo, in_progress, waiting, done or canceled + :param assignee: "me" for tasks assigned to the user + :param tag: Tag name to keep, like "bug" + :param count: Maximum number of tasks to return (default: 10) + :return: JSON list of tasks with number, folder, title, status, priority, assignee, due date and tags + """ + if not __user__: + return JSONCodec.dumps({'error': 'User context not available'}) + try: + from open_webui.models.tags import get_tag_id + from open_webui.models.tasks import STATUS_GLYPHS, Tasks + + user, readable, folder_id, _ = await _task_context(__user__['id'], __chat_id__, folder) + categories = [status.strip()] if status and status.strip() in STATUS_GLYPHS else [] + page = await Tasks.get_tasks( + readable, + folder_id=folder_id, + assignee_id=user.id if assignee.strip().lower() in ('me', 'myself') else None, + categories=categories, + tag_ids=[get_tag_id(tag)] if tag.strip() else None, + search=query, + limit=max(1, min(count, 50)), + ) + return JSONCodec.dumps([await _task_summary(task) for task in page['tasks']]) + except ValueError as e: + return JSONCodec.dumps({'error': str(e)}) + except Exception as e: + log.exception(f'search_tasks error: {e}') + return JSONCodec.dumps({'error': str(e)}) + + +async def get_task( + number: Optional[str] = None, + folder: str = '', + __user__: dict = None, + __chat_id__: str = None, +) -> str: + """ + Get one task with its description. + + :param number: The task's number in its folder, like "12" or "#12"; empty means the task this chat is for + :param folder: The task's folder name; empty means the chat's folder + :return: JSON task with number, folder, title, status, priority, assignee, due date and description + """ + if not __user__: + return JSONCodec.dumps({'error': 'User context not available'}) + try: + _, readable, folder_id, chat = await _task_context(__user__['id'], __chat_id__, folder) + task = await _find_task(readable, folder_id, number, chat) + from open_webui.utils.access_control.tasks import has_task_access + + if not await has_task_access(__user__['id'], task, 'read'): + return JSONCodec.dumps({'error': 'Task not found'}) + return JSONCodec.dumps({**await _task_summary(task), 'description': task.description}) + except ValueError as e: + return JSONCodec.dumps({'error': str(e)}) + except Exception as e: + log.exception(f'get_task error: {e}') + return JSONCodec.dumps({'error': str(e)}) + + +async def create_task( + title: str, + folder: str = '', + description: str = '', + status: str = '', + priority: str = '', + assignee: str = '', + due_date: str = '', + tags: str = '', + __request__: Request = None, + __user__: dict = None, + __chat_id__: str = None, +) -> str: + """ + Create a task in a folder. Use it for follow-up work the user wants tracked. + + :param title: Short title of the task + :param folder: Folder name to create it in; empty means the chat's folder + :param description: Optional details, in markdown + :param status: Optional status name from the folder's workflow, like "Backlog"; empty starts it in Todo + :param priority: Optional priority: urgent, high, medium or low + :param assignee: Optional person who can edit the folder, by name or email, or "me" + :param due_date: Optional due date as YYYY-MM-DD + :param tags: Optional tag names, separated by commas, like "bug, frontend" + :return: JSON with the created task's number, folder, title, status, tags and link + """ + if not __user__: + return JSONCodec.dumps({'error': 'User context not available'}) + try: + from open_webui.models.folders import Folders + from open_webui.models.tasks import TASK_PRIORITIES, TaskForm, Tasks, task_statuses + from open_webui.utils.access_control.folders import has_folder_access + + user, _, folder_id, _ = await _task_context(__user__['id'], __chat_id__, folder) + if not folder_id: + return JSONCodec.dumps({'error': 'Give the folder to create the task in'}) + target = await Folders.get_folder_by_id(folder_id) + if not target or not await has_folder_access(user.id, target, 'write', None): + return JSONCodec.dumps({'error': 'You cannot add tasks to that folder'}) + statuses = task_statuses(target.meta) + if priority and priority.strip().lower() not in TASK_PRIORITIES: + return JSONCodec.dumps({'error': 'Priority must be urgent, high, medium or low'}) + form = TaskForm( + folder_id=folder_id, + title=title, + description=description or None, + status=_match_status(statuses, status) if status.strip() else None, + priority=priority.strip().lower() or None, + assignee_id=await _match_assignee(target, assignee, user) if assignee.strip() else None, + due_date=due_date.strip() or None, + tags=tags.split(','), + ) + task = await Tasks.insert_new_task(user.id, form, statuses) + if form.tags: + from open_webui.models.tags import Tags + + await Tags.set_resource_tags('task', task.id, form.tags, target.user_id) + from open_webui.routers.tasks import notify_assignee + + if __request__ is not None: + await publish_event( + __request__, + EVENTS.TASK_CREATED, + actor=user, + subject_id=task.id, + data={'title': task.title, 'folder_id': task.folder_id, 'number': task.number}, + ) + await notify_assignee(task, user.id) + from open_webui.internal.db import get_async_db_context + from open_webui.routers.tasks import notify_task_change + + async with get_async_db_context() as db: + await notify_task_change(task, user.id, db) + return JSONCodec.dumps(await _task_summary(task, target.name, statuses)) + except ValueError as e: + return JSONCodec.dumps({'error': str(e)}) + except Exception as e: + log.exception(f'create_task error: {e}') + return JSONCodec.dumps({'error': str(e)}) + + +async def update_task( + number: Optional[str] = None, + folder: str = '', + title: Optional[str] = None, + description: Optional[str] = None, + status: Optional[str] = None, + priority: Optional[str] = None, + assignee: Optional[str] = None, + due_date: Optional[str] = None, + tags: Optional[str] = None, + __request__: Request = None, + __user__: dict = None, + __chat_id__: str = None, +) -> str: + """ + Change a task. Leave a field out to keep it; pass an empty string to clear priority, assignee or due date. + + :param number: The task's number in its folder, like "12"; empty means the task this chat is for + :param folder: The task's folder name; empty means the chat's folder + :param title: New title + :param description: New description, in markdown; replaces the old one + :param status: Status name from the folder's workflow, like "In Progress" or "Done" + :param priority: urgent, high, medium or low, or empty to clear + :param assignee: Person who can edit the folder, by name or email, "me", or empty to unassign + :param due_date: Due date as YYYY-MM-DD, or empty to clear + :param tags: Tag names separated by commas; replaces the task's tags, or empty to remove them all + :return: JSON with the updated task + """ + if not __user__: + return JSONCodec.dumps({'error': 'User context not available'}) + try: + from open_webui.models.folders import Folders + from open_webui.models.tasks import TASK_PRIORITIES, Tasks, TaskUpdateForm, task_statuses + from open_webui.utils.access_control.tasks import has_task_access + + user, readable, folder_id, chat = await _task_context(__user__['id'], __chat_id__, folder) + task = await _find_task(readable, folder_id, number, chat) + if not await has_task_access(user.id, task, 'write'): + return JSONCodec.dumps({'error': 'You cannot change that task'}) + target = await Folders.get_folder_by_id(task.folder_id) + statuses = task_statuses(target.meta if target else None) + changes = {} + if title is not None: + changes['title'] = title + if description is not None: + changes['description'] = description or None + if status is not None: + changes['status'] = _match_status(statuses, status) + if priority is not None: + value = priority.strip().lower() or None + if value is not None and value not in TASK_PRIORITIES: + return JSONCodec.dumps({'error': 'Priority must be urgent, high, medium or low'}) + changes['priority'] = value + if assignee is not None: + changes['assignee_id'] = await _match_assignee(target, assignee, user) + if due_date is not None: + changes['due_date'] = due_date.strip() or None + form = TaskUpdateForm(**changes) + previous_assignee = task.assignee_id + task = await Tasks.update_task(task.id, user.id, form.model_dump(include=set(changes)), statuses) + if tags is not None and target: + from open_webui.models.tags import Tags + from open_webui.models.tasks import TaskForm + + # The same checks as a new task's tags; they're the folder owner's. + names = TaskForm(folder_id=task.folder_id, title=task.title, tags=tags.split(',')).tags + await Tags.set_resource_tags('task', task.id, names, target.user_id) + from open_webui.routers.tasks import notify_assignee, notify_task_change + + if __request__ is not None: + await publish_event( + __request__, + EVENTS.TASK_UPDATED, + actor=user, + subject_id=task.id, + data={'title': task.title, 'folder_id': task.folder_id, 'number': task.number}, + ) + if task.assignee_id and task.assignee_id != previous_assignee: + await notify_assignee(task, user.id) + from open_webui.internal.db import get_async_db_context + + async with get_async_db_context() as db: + await notify_task_change(task, user.id, db) + return JSONCodec.dumps(await _task_summary(task, target.name if target else None, statuses)) + except ValueError as e: + return JSONCodec.dumps({'error': str(e)}) + except Exception as e: + log.exception(f'update_task error: {e}') + return JSONCodec.dumps({'error': str(e)}) + + # Calendar tools diff --git a/backend/open_webui/utils/access_control/tasks.py b/backend/open_webui/utils/access_control/tasks.py new file mode 100644 index 0000000000..f9c6811890 --- /dev/null +++ b/backend/open_webui/utils/access_control/tasks.py @@ -0,0 +1,44 @@ +from open_webui.models.access_grants import AccessGrants +from open_webui.models.folders import FolderModel, Folders +from open_webui.models.groups import Groups +from open_webui.models.tasks import TaskModel +from open_webui.models.teams import Teams +from open_webui.utils.access_control.folders import has_folder_access +from sqlalchemy.ext.asyncio import AsyncSession + + +async def has_task_access(user_id: str, task: TaskModel, permission: str, db: AsyncSession | None = None) -> bool: + """A task is open to whoever has the same access to its folder.""" + folder = await Folders.get_folder_by_id(task.folder_id, db=db) + return bool(folder) and await has_folder_access(user_id, folder, permission, db) + + +async def folder_user_ids(folder: FolderModel, permission: str, db: AsyncSession | None = None) -> set[str] | None: + """Everyone with this access to the folder: its owner plus whoever its grants, and its parents', reach. + + Read access counts write grants too. None means a grant is open to everyone. + """ + permissions = {'write'} if permission == 'write' else {'read', 'write'} + user_ids, group_ids, team_ids = set(), set(), set() + seen = set() + while folder and folder.id not in seen: + seen.add(folder.id) + user_ids.add(folder.user_id) + for grant in await AccessGrants.get_grants_by_resource('folder', folder.id, db=db): + if grant.permission not in permissions: + continue + if grant.principal_type == 'user': + if grant.principal_id == '*': + return None + user_ids.add(grant.principal_id) + elif grant.principal_type == 'group': + group_ids.add(grant.principal_id) + elif grant.principal_type == 'team': + team_ids.add(grant.principal_id) + folder = await Folders.get_folder_by_id(folder.parent_id, db=db) if folder.parent_id else None + if group_ids: + members = await Groups.get_group_user_ids_by_ids(list(group_ids), db=db, include_inherited=True) + user_ids.update(user_id for ids in members.values() for user_id in ids) + if team_ids: + user_ids.update(await Teams.get_user_ids_by_team_ids(list(team_ids), db=db)) + return user_ids diff --git a/backend/open_webui/utils/comments.py b/backend/open_webui/utils/comments.py index 4c585a6d11..9429bea9a2 100644 --- a/backend/open_webui/utils/comments.py +++ b/backend/open_webui/utils/comments.py @@ -19,6 +19,7 @@ def resource_models(): from open_webui.models.notes import Note from open_webui.models.prompts import Prompt from open_webui.models.skills import Skill + from open_webui.models.tasks import Task from open_webui.models.tools import Tool return dict( @@ -29,6 +30,7 @@ def resource_models(): tool=Tool, note=Note, chat=Chat, + task=Task, ) @@ -65,6 +67,13 @@ async def comment_resource(resource_type, resource_id, user, db, *, lock=False, from open_webui.models.chats import Chats allowed = await Chats.has_chat_access(resource_id, user, db=db, chat=resource) + elif resource_type == 'task': + from open_webui.models.tasks import TaskModel + from open_webui.utils.access_control.tasks import has_task_access + + allowed = await Config.get('tasks.enable') and await has_task_access( + user.id, TaskModel.model_validate(resource), 'read', db + ) else: if resource_type == 'note': if not await Config.get('notes.enable') or ( diff --git a/backend/open_webui/utils/inbox.py b/backend/open_webui/utils/inbox.py index 0e4f81cfa1..1fc3299bf7 100644 --- a/backend/open_webui/utils/inbox.py +++ b/backend/open_webui/utils/inbox.py @@ -70,6 +70,8 @@ async def validate_source(event_type, resource_type, resource_id, object_type, o and obj.automation_id == resource_id and obj.status == 'error' ) + elif event_type == 'task.assigned': + valid = object_type == 'task' and resource_type == 'task' and obj.id == resource_id elif event_type == 'calendar.alert_triggered': valid = ( object_type == 'calendar_event' @@ -92,6 +94,7 @@ async def resource_access(user_ids, db): 'channels.enable', 'calendar.enable', 'automations.enable', + 'tasks.enable', 'user.permissions', db=db, ) @@ -185,6 +188,9 @@ def resource_queries(user, user_groups, config): if enabled('automations'): model = models['automation'] queries['automation'] = select(model.id).where(model.user_id == user.id) + if config.get('tasks.enable'): + model = models['task'] + queries['task'] = select(model.id).where(model.folder_id.in_(select(folders.c.id))) return queries @@ -234,6 +240,7 @@ async def visible_clause(user, db): ('chat_message', 'chat_id', ['chat.mentioned']), ('automation_run', 'automation_id', ['automation.run_failed']), ('calendar_event', 'calendar_id', ['calendar.alert_triggered']), + ('task', 'id', ['task.assigned']), ): model = models[kind] conditions = [model.id == Notification.object_id, getattr(model, parent_column) == Notification.resource_id] diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index 6eb9f6c545..e64f762b0a 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -53,6 +53,7 @@ from open_webui.tools.builtin import ( calculate_timestamp, create_automation, create_calendar_event, + create_task, create_todos, create_tool, delegate_task, @@ -66,6 +67,7 @@ from open_webui.tools.builtin import ( generate_image, generate_video, get_current_timestamp, + get_task, grep_chat_files, grep_knowledge_files, kb_exec, @@ -92,6 +94,7 @@ from open_webui.tools.builtin import ( search_knowledge_files, search_memories, search_notes, + search_tasks, search_users, search_web, send_message, @@ -100,6 +103,7 @@ from open_webui.tools.builtin import ( update_automation, update_calendar_event, update_memory, + update_task, update_todo, view_channel_message, view_channel_thread, @@ -722,6 +726,8 @@ async def get_builtin_tools( 'notes.enable', 'channels.enable', 'automations.enable', + 'tasks.enable', + 'folders.enable', 'calendar.enable', 'ui.enable_user_webhooks', 'subagents.enable', @@ -1002,6 +1008,15 @@ async def get_builtin_tools( [create_automation, update_automation, list_automations, toggle_automation, delete_automation] ) + # Task tools - find, read, create and change the tasks in folders + if ( + is_builtin_tool_enabled('tasks') + and config.get('tasks.enable') + and config.get('folders.enable') is not False + and await has_user_permission('folders') + ): + builtin_functions.extend([search_tasks, get_task, create_task, update_task]) + # Calendar tools - search/create/update/delete events if is_builtin_tool_enabled('calendar') and config.get('calendar.enable') and await has_user_permission('calendar'): builtin_functions.extend( diff --git a/src/lib/apis/chats/index.ts b/src/lib/apis/chats/index.ts index 0ece5383ef..bd34cfb740 100644 --- a/src/lib/apis/chats/index.ts +++ b/src/lib/apis/chats/index.ts @@ -70,7 +70,9 @@ export const createNewChat = async ( token: string, chat: object, folderId: string | null, - variables: object | null = null + variables: object | null = null, + // The task the chat is started from; it must be in the same folder. + taskId: string | null = null ) => { let error = null; @@ -84,7 +86,8 @@ export const createNewChat = async ( body: JSON.stringify({ chat: chat, ...(variables !== null ? { variables } : {}), - folder_id: folderId ?? null + folder_id: folderId ?? null, + ...(taskId ? { task_id: taskId } : {}) }) }) .then(async (res) => { diff --git a/src/lib/apis/comments/index.ts b/src/lib/apis/comments/index.ts index 37ac440614..ef47fbfdcf 100644 --- a/src/lib/apis/comments/index.ts +++ b/src/lib/apis/comments/index.ts @@ -1,7 +1,7 @@ import { WEBUI_API_BASE_URL } from '$lib/constants'; export type CommentResource = { - resource_type: 'model' | 'knowledge' | 'prompt' | 'skill' | 'tool' | 'note' | 'chat'; + resource_type: 'model' | 'knowledge' | 'prompt' | 'skill' | 'tool' | 'note' | 'chat' | 'task'; resource_id: string; }; export type CommentAnchor = { diff --git a/src/lib/apis/notifications/inbox.ts b/src/lib/apis/notifications/inbox.ts index 7eb7a746e3..dc8e1258eb 100644 --- a/src/lib/apis/notifications/inbox.ts +++ b/src/lib/apis/notifications/inbox.ts @@ -63,5 +63,6 @@ export const inboxLabels: Record = { 'channel.replied': '{{name}} replied', 'calendar.alert_triggered': 'Upcoming event', 'automation.run_failed': 'Automation failed', + 'task.assigned': '{{name}} assigned you a task', 'system.announcement': 'Announcement' }; diff --git a/src/lib/apis/tasks/index.ts b/src/lib/apis/tasks/index.ts new file mode 100644 index 0000000000..b1c7cce335 --- /dev/null +++ b/src/lib/apis/tasks/index.ts @@ -0,0 +1,173 @@ +import { WEBUI_API_BASE_URL } from '$lib/constants'; +import type { StatusGlyph } from '$lib/utils/folders'; +import type { FolderTag } from '$lib/utils/tags'; + +export type TaskPriority = 'urgent' | 'high' | 'medium' | 'low'; + +export type TaskPerson = { id: string; name: string }; + +export type Task = { + id: string; + folder_id: string; + // Numbered per folder (#12); a moved task takes its new folder's next number. + number: number; + user_id: string; + title: string; + description: string | null; + // An id from its folder's statuses, which also say its category (`folder.statuses`). + status: string; + priority: TaskPriority | null; + assignee_id: string | null; + // A plain date, YYYY-MM-DD. + due_date: string | null; + // Time in status, as folder chats keep it: when the current status began, and seconds banked per status. + status_at: number; + status_durations: Record | null; + // Set by the status's category: started on in progress or waiting, then done or canceled. + started_at: number | null; + completed_at: number | null; + canceled_at: number | null; + data: Record | null; + meta: Record | null; + created_at: number; + updated_at: number; + folder: { + id: string; + name: string; + icon?: string | null; + statuses: unknown[]; + } | null; + user: TaskPerson | null; + assignee: TaskPerson | null; + chat_count: number; + write_access?: boolean | null; + // Its folder owner's tags, so every task in a folder shares one set. + tags: FolderTag[]; +}; + +export type TaskPage = { tasks: Task[]; total: number; has_more: boolean }; + +export type TaskQuery = { + folder_id?: string; + assigned_to_me?: boolean; + created_by_me?: boolean; + search?: string; + status?: string[]; + category?: string[]; + priority?: string[]; + assignee_id?: string[]; + folder?: string[]; + // Tag ids; 'none' keeps untagged tasks. + tag?: string[]; + sort_by?: string; + sort_dir?: 'asc' | 'desc'; + page?: number; +}; + +export type TaskChanges = Partial< + Pick< + Task, + 'folder_id' | 'title' | 'description' | 'status' | 'priority' | 'assignee_id' | 'due_date' + > +>; + +export type TaskHistoryEntry = { + id: string; + task_id: string; + user_id: string | null; + // One changed field. A value is what the task's field held; when it's an id + // (status, assignee_id, folder_id), the name is what that was called then. + field: string; + old_value: string | null; + new_value: string | null; + old_name: string | null; + new_name: string | null; + created_at: number; + user: TaskPerson | null; +}; + +export type TaskChat = { + id: string; + title: string; + updated_at: number; + created_at: number; + user_id: string; + owner_name: string | null; + active: boolean; + pending_approval: boolean; +}; + +// Throws the server's `detail`, as the other API clients do, so callers can toast it. +async function request(token: string, path: string, method = 'GET', body?: object): Promise { + const res = await fetch(`${WEBUI_API_BASE_URL}/tasks${path}`, { + method, + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + }, + ...(body ? { body: JSON.stringify(body) } : {}) + }); + const json = await res.json().catch(() => null); + if (!res.ok) { + console.error(json); + throw json?.detail ?? `${res.status}`; + } + return json; +} + +export const getTasks = (token: string, query: TaskQuery = {}) => { + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(query)) { + if (Array.isArray(value)) value.forEach((item) => params.append(key, item)); + else if (value !== undefined && value !== null && value !== '' && value !== false) + params.set(key, String(value)); + } + return request(token, `/?${params}`); +}; + +export const getTaskAssignees = (token: string, folderId: string, query = '') => + request(token, `/assignees?${new URLSearchParams({ folder_id: folderId, query })}`); + +// Tasks in a folder and its subfolders; they're deleted with the folder. +export const countFolderTasks = (token: string, folderId: string) => + request<{ count: number }>(token, `/count?${new URLSearchParams({ folder_id: folderId })}`); + +export const createTask = ( + token: string, + form: TaskChanges & { folder_id: string; title: string; tags?: string[] } +) => request(token, '/create', 'POST', form); + +// Tags on the tasks the user can read, or one folder's, with how many tasks carry each. +export const getTaskTags = (token: string, folderId: string | null = null) => + request( + token, + `/tags?${new URLSearchParams(folderId ? { folder_id: folderId } : {})}` + ); + +export const getTaskTagsById = (token: string, id: string) => + request(token, `/id/${id}/tags`); + +export const addTaskTagById = (token: string, id: string, name: string) => + request(token, `/id/${id}/tags`, 'POST', { name }); + +export const deleteTaskTagById = (token: string, id: string, name: string) => + request(token, `/id/${id}/tags`, 'DELETE', { name }); + +export const updateTaskTagColorById = (token: string, id: string, name: string, color: string) => + request(token, `/id/${id}/tags`, 'PATCH', { name, color }); + +export const getTaskById = (token: string, id: string) => request(token, `/id/${id}`); + +// Only the fields given change; null clears one. +export const updateTaskById = (token: string, id: string, changes: TaskChanges) => + request(token, `/id/${id}/update`, 'POST', changes); + +export const deleteTaskById = (token: string, id: string) => + request(token, `/id/${id}/delete`, 'DELETE'); + +export const getTaskHistory = (token: string, id: string) => + request(token, `/id/${id}/history`); + +export const getTaskChats = (token: string, id: string) => + request(token, `/id/${id}/chats`); diff --git a/src/lib/components/admin/Settings/Features.svelte b/src/lib/components/admin/Settings/Features.svelte index d7419c646d..fafa040251 100644 --- a/src/lib/components/admin/Settings/Features.svelte +++ b/src/lib/components/admin/Settings/Features.svelte @@ -80,6 +80,7 @@ ENABLE_NOTIFICATIONS: $i18n.t('settings.admin.general.notifications.label'), ENABLE_CHANNELS: $i18n.t('settings.admin.general.channels.label'), ENABLE_TEAMS: $i18n.t('settings.admin.general.teams.label'), + ENABLE_TASKS: $i18n.t('settings.admin.general.tasks.label'), ENABLE_ENCRYPTED_CHANNELS: $i18n.t('settings.admin.general.encryptedChannels.label'), CHANNEL_MODEL_RESPONSE_MODE: $i18n.t('settings.admin.general.modelResponseMode.label'), ENABLE_APPS: $i18n.t('settings.admin.general.apps.label'), @@ -318,6 +319,13 @@ > + + + message.role === 'assistant')) { @@ -6484,6 +6490,7 @@ id: $chatId, archived: chat?.archived ?? false, folder_id: chat?.folder_id, + task_id: chat?.task_id, chat: { title: $chatTitle, models: selectedModels, diff --git a/src/lib/components/chat/Messages/builtinToolLabels.ts b/src/lib/components/chat/Messages/builtinToolLabels.ts index fe1e2ac396..70e150f022 100644 --- a/src/lib/components/chat/Messages/builtinToolLabels.ts +++ b/src/lib/components/chat/Messages/builtinToolLabels.ts @@ -147,6 +147,16 @@ const labels = (t: Translate, name: string): Labels | null => { case 'update_todo': return [t('Updating to-do'), t('Updated to-do'), t('Failed to update to-do')]; + // Tasks + case 'search_tasks': + return [t('Searching tasks'), t('Searched tasks'), t('Failed to search tasks')]; + case 'get_task': + return [t('Reading task'), t('Read task'), t('Failed to read task')]; + case 'create_task': + return [t('Creating task'), t('Created task'), t('Failed to create task')]; + case 'update_task': + return [t('Updating task'), t('Updated task'), t('Failed to update task')]; + // Automations case 'create_automation': return [t('Creating automation'), t('Created automation'), t('Failed to create automation')]; diff --git a/src/lib/components/chat/Navbar.svelte b/src/lib/components/chat/Navbar.svelte index 04e2d370d3..290aba5888 100644 --- a/src/lib/components/chat/Navbar.svelte +++ b/src/lib/components/chat/Navbar.svelte @@ -33,6 +33,7 @@ import SplitPanel from '../icons/SplitPanel.svelte'; import { isTemporaryChatId } from '$lib/utils/chatId'; import ChatParticipants from '$lib/components/common/ChatParticipants.svelte'; + import TaskChip from '$lib/components/tasks/TaskChip.svelte'; const i18n: any = getContext('i18n'); @@ -204,6 +205,7 @@ {title || chat?.chat?.title || $i18n.t('New Chat')} {/if} + {#if chat?.task_id}{/if} {#if !$temporaryChat && ($user?.role === 'admin' || ($user?.permissions?.chat?.delete ?? true))} + {#if group.status} {:else if group.priority} @@ -182,14 +185,14 @@ > {/if} -

+ {group.label} -

+ {group.page?.total ?? ''} - - + + {/if} {#if !collapsed[group.id]} diff --git a/src/lib/components/chat/Placeholder/FolderOverview.svelte b/src/lib/components/chat/Placeholder/FolderOverview.svelte index c8548d1d17..99e4e689a7 100644 --- a/src/lib/components/chat/Placeholder/FolderOverview.svelte +++ b/src/lib/components/chat/Placeholder/FolderOverview.svelte @@ -2,9 +2,12 @@ import { getContext } from 'svelte'; import { goto } from '$app/navigation'; - import { folders, models, teams } from '$lib/stores'; + import { config, folders, models, teams } from '$lib/stores'; import { loadFolderChatPage, type FolderDetails } from '$lib/stores/folderStates'; import type { FolderAutomation } from '$lib/apis/automations'; + import { getTasks, type Task } from '$lib/apis/tasks'; + import { taskStatusDef } from '$lib/utils/tasks'; + import StatusIcon from './FolderStatusIcon.svelte'; import type { AppLayoutContext } from '$lib/types'; import type { WorkspaceChat } from '$lib/utils/folders'; import { openFolderChat } from './folderChat'; @@ -55,6 +58,24 @@ .catch(() => {}); } + // Open tasks, newest first, when tasks are on. + let tasks: Task[] = []; + let tasksFor = ''; + $: if ($config?.features?.enable_tasks && folder.id !== tasksFor) { + tasksFor = folder.id; + tasks = []; + const folderId = folder.id; + getTasks(localStorage.token, { + folder_id: folderId, + category: ['backlog', 'todo', 'in_progress', 'waiting', 'none'], + sort_by: 'updated_at' + }) + .then((page) => { + if (folder.id === folderId) tasks = page.tasks.slice(0, RECENT); + }) + .catch(() => {}); + } + // Notes and automations open in a page tab, as their own tabs open them. const openPage = (event: MouseEvent, href: string, label: string) => { if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) @@ -258,6 +279,39 @@ {/if} + {#if tasks.length} +
+ {@render groupHeader('tasks', $i18n.t('Tasks'))} + {#if !folded.tasks} + + {/if} +
+ {/if} + {#if notes?.length}
{@render groupHeader('notes', $i18n.t('Notes'))} diff --git a/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte b/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte index 9d484d32f0..0817eb316e 100644 --- a/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte +++ b/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte @@ -2,6 +2,7 @@ import { getContext, onMount, setContext, tick } from 'svelte'; import { writable } from 'svelte/store'; import { toast } from 'svelte-sonner'; + import { page } from '$app/stores'; // @ts-expect-error The installed SortableJS package has no type declarations. import Sortable from 'sortablejs'; import { @@ -45,6 +46,7 @@ NO_STATUS, NO_PRIORITY, statusDefs, + customStatuses, groupedStatusDefs, priorityDefs, priorityKey, @@ -87,6 +89,7 @@ import FolderNotes from './FolderNotes.svelte'; import FolderKnowledge from './FolderKnowledge.svelte'; import FolderOverview from './FolderOverview.svelte'; + import Tasks from '$lib/components/tasks/Tasks.svelte'; import KnowledgeSelector from '$lib/components/workspace/Models/Knowledge/KnowledgeSelector.svelte'; import { getFolderAutomations, type FolderAutomation } from '$lib/apis/automations'; import AdjustmentsHorizontal from '$lib/components/icons/AdjustmentsHorizontal.svelte'; @@ -204,6 +207,9 @@ $: if (!canUseAutomations && folderSection === 'automations') folderSection = 'overview'; + $: canUseTasks = !!$config?.features?.enable_tasks; + $: if (!canUseTasks && folderSection === 'tasks') folderSection = 'overview'; + let knowledgeView: FolderKnowledge; let knowledgeItems: any[] = []; let showKnowledgePicker = false; @@ -214,6 +220,7 @@ 'overview', 'files', 'chats', + 'tasks', 'notes', 'knowledge', 'automations' @@ -229,6 +236,7 @@ overview: $i18n.t('Overview'), files: $i18n.t('Files'), chats: $i18n.t('Chats'), + tasks: $i18n.t('Tasks'), notes: $i18n.t('Notes'), automations: $i18n.t('Automations'), knowledge: $i18n.t('Knowledge') @@ -239,6 +247,7 @@ (id) => (id !== 'files' || filesTarget) && (id !== 'notes' || canUseNotes) && + (id !== 'tasks' || canUseTasks) && (id !== 'automations' || canUseAutomations) ); // Overview is always shown. @@ -419,6 +428,9 @@ setContext('folder-statuses', defsStore); setContext('folder-statuses-manage', manageStore); let showStatuses = false; + // The task list's statuses, when it opens the editor for a folder that has none yet. + let taskStatusSeed: StatusDef[] | null = null; + $: if (!showStatuses) taskStatusSeed = null; $: defs = statusDefs(folder?.meta, (key) => $i18n.t(key)); $: defsStore.set(defs); $: manageStore.set(readOnly ? null : () => (showStatuses = true)); @@ -510,7 +522,6 @@ let currentFolderId = ''; let section: HTMLElement; let searchInput: HTMLInputElement; - let searchOpen = false; let search = ''; let appliedSearch = ''; @@ -1043,8 +1054,6 @@ } async function openSearch() { - searchOpen = true; - await tick(); searchInput?.focus(); } @@ -1138,6 +1147,8 @@ function shortcuts(event: KeyboardEvent) { if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return; if (!section?.offsetParent) return; + // The task list has its own keys. + if (folderSection === 'tasks') return; const target = event.target as HTMLElement | null; if ( target?.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]') || @@ -1210,7 +1221,6 @@ const state = getFolderState(folder.id); search = ''; appliedSearch = ''; - searchOpen = false; statusFilter = []; priorityFilter = []; selectedTags = []; @@ -1239,7 +1249,11 @@ restoredFolderId = folder.id; const saved = folderView?.state.folderPage; filesDirectory = saved?.directory ?? null; - if (saved) showSection(saved.section, false); + // Arriving with a prompt (a task's New chat) keeps a page that shows the message box. + const prompted = + !!$page.url.searchParams.get('q') && + !['overview', 'chats', 'files'].includes(saved?.section ?? ''); + if (saved && !prompted) showSection(saved.section, false); } // Backstop: tag groups that appear later (e.g. a tag created while open) get their chats. @@ -1432,6 +1446,8 @@ {:else if folderSection === 'files'} + {:else if folderSection === 'tasks'} + {:else if folderSection === 'notes'} {#if !readOnly} - {/if} - - {:else} + {/if} + + + + {#if folderSection === 'chats'} + +
+ +
- {/if} +
- + {/if} {#if filterCount && folderSection === 'chats'}
@@ -1912,6 +1921,30 @@ onReload={() => loadNotes()} onMore={loadMoreNotes} /> + {:else if folderSection === 'tasks' && folder} + {#key JSON.stringify(folder.meta?.statuses ?? null)} + { + // A folder without statuses starts from the ones its tasks use. + taskStatusSeed = customStatuses(folder?.meta).length + ? null + : [ + ...list.map((item) => ({ ...item, custom: true })), + statusDefs(null, (key) => $i18n.t(key))[0] + ]; + showStatuses = true; + }} + /> + {/key} {:else if folderSection === 'automations'} $i18n.t(key))} + statuses={taskStatusSeed ?? groupedStatusDefs(folder?.meta, (key) => $i18n.t(key))} onSave={saveStatuses} /> diff --git a/src/lib/components/chat/Placeholder/FolderStatusIcon.svelte b/src/lib/components/chat/Placeholder/FolderStatusIcon.svelte index abb237c282..703ce6693a 100644 --- a/src/lib/components/chat/Placeholder/FolderStatusIcon.svelte +++ b/src/lib/components/chat/Placeholder/FolderStatusIcon.svelte @@ -17,12 +17,14 @@ export let glyph: StatusGlyph | undefined = undefined; export let color: TagColor | undefined = undefined; export let emoji: string | undefined = undefined; + /** A status without a glyph: a dot in its color. */ + export let dot = false; export let className = 'size-3.5'; const defs = getContext | undefined>('folder-statuses'); $: def = glyph || emoji ? undefined : $defs?.find((item) => item.id === status); $: shownEmoji = emoji ?? def?.icon; - $: shape = glyph ?? def?.glyph ?? (status === NO_STATUS || !def ? null : 'todo'); + $: shape = glyph ?? def?.glyph ?? (dot || def ? 'dot' : null); $: tone = glyphColor[color ?? def?.color ?? 'gray']; @@ -40,7 +42,9 @@ {:else}
{$i18n.t('Icon')}
+ {#each statusGlyphs as glyph} + {/each} +
+
+ {#key tab} + + {/key} +
+
diff --git a/src/lib/components/tasks/Task.svelte b/src/lib/components/tasks/Task.svelte new file mode 100644 index 0000000000..538fd34249 --- /dev/null +++ b/src/lib/components/tasks/Task.svelte @@ -0,0 +1,435 @@ + + + + +{#if task} + + +{/if} + +{#if missing} +
+ {$i18n.t('This task was deleted, or you no longer have access to it.')} +
+{:else if !task} +
+{:else} + {@const editable = !!task.write_access} + +
+ +
+
+
+ {task.folder?.name ?? ''} + + #{task.number} + {#if editable} + + + + + {#if $user?.role === 'admin' || task.user_id === $user?.id} + + {/if} + + + {/if} +
+ + {#if editable} + { + if (event.key === 'Enter') (event.currentTarget as HTMLInputElement).blur(); + }} + /> +