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, updated_at_gte: Optional[int] = 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 updated_at_gte is not None: conditions.append(Task.updated_at >= updated_at_gte) 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()