From 06491f013286e9edbc707aff9ae847226a8db6ff Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 13 Nov 2026 22:40:53 +0900 Subject: [PATCH] refac --- backend/open_webui/models/chats.py | 365 +++- backend/open_webui/models/folders.py | 15 + backend/open_webui/models/tags.py | 15 +- backend/open_webui/routers/chats.py | 19 + backend/open_webui/routers/folders.py | 120 +- backend/open_webui/socket/main.py | 6 +- src/lib/apis/chats/index.ts | 38 + src/lib/apis/folders/index.ts | 109 +- src/lib/components/chat/Chat.svelte | 10 +- src/lib/components/chat/MessageInput.svelte | 8 +- .../chat/Messages/ContentRenderer.svelte | 17 +- .../chat/Messages/ResponseMessage.svelte | 5 +- src/lib/components/chat/Navbar.svelte | 7 +- src/lib/components/chat/Placeholder.svelte | 172 +- .../chat/Placeholder/ChatList.svelte | 611 ++++--- .../chat/Placeholder/FolderBoard.svelte | 371 ++++ .../chat/Placeholder/FolderChatMenu.svelte | 133 ++ .../chat/Placeholder/FolderPlaceholder.svelte | 1517 +++++++++++++++-- .../chat/Placeholder/FolderStatus.svelte | 70 + .../chat/Placeholder/FolderStatusIcon.svelte | 68 + .../chat/Placeholder/FolderStatusTime.svelte | 69 + .../Placeholder/FolderStatusesModal.svelte | 261 +++ .../chat/Placeholder/FolderTags.svelte | 242 +++ .../chat/Placeholder/FolderTitle.svelte | 178 +- .../components/chat/Placeholder/folderChat.ts | 39 + src/lib/components/chat/Tabs.svelte | 28 +- src/lib/components/common/EmojiPicker.svelte | 2 +- src/lib/components/layout/Sidebar.svelte | 3 + .../layout/Sidebar/FolderHoverPreview.svelte | 2 +- .../layout/Sidebar/Folders/FolderModal.svelte | 40 +- .../layout/Sidebar/RecursiveFolder.svelte | 2 +- src/lib/components/workspace/Workspace.svelte | 2 +- src/lib/i18n/locales/en-US/translation.json | 1 + src/lib/stores/folderStates.ts | 41 +- src/lib/utils/folders.ts | 95 ++ src/lib/utils/index.ts | 28 + src/lib/utils/tags.ts | 42 + .../(app)/folders/[folderId]/+page.svelte | 6 +- 38 files changed, 4032 insertions(+), 725 deletions(-) create mode 100644 src/lib/components/chat/Placeholder/FolderBoard.svelte create mode 100644 src/lib/components/chat/Placeholder/FolderChatMenu.svelte create mode 100644 src/lib/components/chat/Placeholder/FolderStatus.svelte create mode 100644 src/lib/components/chat/Placeholder/FolderStatusIcon.svelte create mode 100644 src/lib/components/chat/Placeholder/FolderStatusTime.svelte create mode 100644 src/lib/components/chat/Placeholder/FolderStatusesModal.svelte create mode 100644 src/lib/components/chat/Placeholder/FolderTags.svelte create mode 100644 src/lib/components/chat/Placeholder/folderChat.ts create mode 100644 src/lib/utils/folders.ts diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index 49301a76e7..ae22fd0cdc 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -21,7 +21,9 @@ from open_webui.models.automations import AutomationRun from open_webui.models.chat_messages import ChatMessage, ChatMessages from open_webui.models.folders import Folders from open_webui.models.tags import Tag, TagModel, Tags +from open_webui.tasks import has_active_tasks from open_webui.utils.misc import get_output_text, sanitize_data_for_db, sanitize_text_for_db +from open_webui.utils.session_records import has_pending_tool_approval from pydantic import BaseModel, ConfigDict, field_validator from sqlalchemy import ( JSON, @@ -49,6 +51,28 @@ from sqlalchemy.sql.expression import bindparam log = logging.getLogger(__name__) ACTIVE_CHAT_GAP_SECONDS = 30 * 60 +# Filter token for chats without a folder status. The status itself is stored and returned as null; +# only query strings, which can't carry null, need a name for it. +NO_FOLDER_STATUS = 'none' + + +def _as_seconds(value): + # Older rows may hold numbers as strings; chats set before tracking have none. + try: + return int(value) + except (TypeError, ValueError): + return None + + +def folder_status_since(meta: dict, status: str | None): + """When the chat would have entered `status` had all its time there been one stretch. + + Earlier stretches in the same status count, so moving away and back doesn't reset it. + """ + started = _as_seconds(meta.get('folder_status_at')) + if status is None or started is None: + return None + return started - (_as_seconds((meta.get('folder_status_durations') or {}).get(status)) or 0) CHAT_SEARCH_FILTER_PREFIXES = ('tag:', 'folder:', 'pinned:', 'archived:', 'shared:') @@ -2106,6 +2130,7 @@ class ChatTable: folder_ids: list[str], db: AsyncSession | None = None, ) -> dict[str, int]: + """Count unread or approval-pending chats for folder notification badges.""" if not folder_ids: return {} @@ -2129,7 +2154,27 @@ class ChatTable: ) .group_by(Chat.folder_id) ) - return {folder_id: count for folder_id, count in result.all() if folder_id} + counts = {folder_id: count for folder_id, count in result.all() if folder_id} + result = await session.execute( + select(Chat.folder_id, Chat.id, ChatMessage.output) + .join(ChatMessage, ChatMessage.chat_id == Chat.id) + .where( + Chat.user_id == user_id, + Chat.folder_id.in_(folder_ids), + Chat.archived == False, + ChatMessage.role == 'assistant', + ChatMessage.done.is_(False), + ) + ) + # Unfinished chats are excluded above; count each approval-pending chat once. + pending_chats = { + (folder_id, chat_id) + for folder_id, chat_id, output in result.all() + if has_pending_tool_approval(output) + } + for folder_id, _ in pending_chats: + counts[folder_id] = counts.get(folder_id, 0) + 1 + return counts async def get_chats(self, skip: int = 0, limit: int = 50, db: AsyncSession | None = None) -> list[ChatModel]: async with get_async_db_context(db) as session: @@ -2604,6 +2649,324 @@ class ChatTable: participants[chat_id].append(author_id) return participants + def _folder_chat_conditions( + self, + folder_id: str, + dialect_name: str, + search: str = '', + tag_ids: list[str] | None = None, + status_ids: list[str] | None = None, + valid_status_ids: tuple[str, ...] = (), + ) -> list: + conditions = [ + Chat.folder_id == folder_id, + Chat.archived.is_(False), + Chat.meta['internal'].as_boolean().is_not(True), + ] + + # Same matching as the sidebar search: the phrase, or every term. + phrase = chat_search_content_query(search) + if phrase: + + def match(key: str, value: str): + return or_( + Chat.title.ilike(f'%{value}%'), + text(chat_search_message_content_match_sql(dialect_name, key)).bindparams(**{key: value}), + ) + + terms = [term for term in chat_search_terms(phrase) if term != phrase] + phrase_match = match('folder_phrase', phrase) + conditions.append( + or_(phrase_match, and_(*[match(f'folder_term_{i}', term) for i, term in enumerate(terms)])) + if terms + else phrase_match + ) + + # 'none' means untagged, as in the sidebar search's tag:none. + tag_ids = set(tag_ids or []) + if tag_ids: + if dialect_name == 'sqlite': + tags = "json_each(CASE WHEN json_type(chat.meta, '$.tags') = 'array' THEN json_extract(chat.meta, '$.tags') ELSE '[]' END)" + else: + tags = "json_array_elements_text(CASE WHEN json_typeof(chat.meta->'tags') = 'array' THEN chat.meta->'tags' ELSE '[]'::json END)" + named = sorted(tag_ids - {'none'}) + matches = [text(f'NOT EXISTS (SELECT 1 FROM {tags} tag)')] if 'none' in tag_ids else [] + if named: + matches.append( + text(f'EXISTS (SELECT 1 FROM {tags} tag WHERE tag.value IN :folder_tag_ids)').bindparams( + bindparam('folder_tag_ids', named, expanding=True) + ) + ) + conditions.append(or_(*matches)) + + # 'not_started' was the default status's earlier name. + status_ids = {NO_FOLDER_STATUS if value == 'not_started' else value for value in status_ids or []} + if status_ids: + stored = Chat.meta['folder_status'].as_string() + named = sorted(status_ids - {NO_FOLDER_STATUS}) + matches = [stored.in_(named)] if named else [] + if NO_FOLDER_STATUS in status_ids: + # Unknown or deleted statuses read as no status. + matches.append( + or_(stored.is_(None), stored.not_in(list(valid_status_ids))) + ) + conditions.append(or_(*matches)) + return conditions + + async def get_folder_chat_page( + self, + folder_id: str, + user_id: str, + skip: int = 0, + limit: int = 50, + search: str = '', + tag_ids: list[str] | None = None, + status_ids: list[str] | None = None, + valid_status_ids: tuple[str, ...] = (), + user_ids: list[str] | None = None, + activity: str | None = None, + updated_at_gte: int | None = None, + sort_by: str = 'updated_at', + sort_dir: str = 'desc', + redis=None, + db: AsyncSession | None = None, + ) -> tuple[list[dict], int]: + """A page of a folder's chats for the list and board views, filtered before paging.""" + async with get_async_db_context(db) as session: + dialect_name = (await session.connection()).dialect.name + conditions = self._folder_chat_conditions( + folder_id, dialect_name, search, tag_ids, status_ids, valid_status_ids + ) + + if user_ids: + # Participants come from message history, so match them over this folder's chats. + wanted = set(user_ids) + rows = (await session.execute(select(Chat.id, Chat.user_id).where(*conditions))).all() + authors = await self.get_participant_ids_by_chat_ids([row[0] for row in rows], db=session) + conditions.append( + Chat.id.in_( + [ + chat_id + for chat_id, owner in rows + if owner in wanted or wanted.intersection(authors.get(chat_id, ())) + ] + ) + ) + + if updated_at_gte is not None: + conditions.append(Chat.updated_at >= updated_at_gte) + + if activity: + # Same precedence as the sidebar markers: approval > generating > unread. + unfinished = ( + await session.execute( + select(ChatMessage.chat_id, ChatMessage.output) + .join(Chat, Chat.id == ChatMessage.chat_id) + .where(*conditions, ChatMessage.role == 'assistant', ChatMessage.done.is_(False)) + ) + ).all() + pending_ids = {chat_id for chat_id, output in unfinished if has_pending_tool_approval(output)} + if activity == 'waiting_for_approval': + conditions.append(Chat.id.in_(pending_ids)) + else: + active_ids = { + chat_id for chat_id in {row[0] for row in unfinished} if await has_active_tasks(redis, chat_id) + } + if activity == 'generating': + conditions.append(Chat.id.in_(active_ids - pending_ids)) + elif activity == 'unread': + conditions.extend( + [ + Chat.user_id == user_id, + or_( + Chat.last_read_at.is_(None), + Chat.last_read_at == 0, + Chat.updated_at > Chat.last_read_at, + ), + Chat.id.not_in(active_ids | pending_ids), + ] + ) + elif activity == 'idle': + # Everything the other three leave out. + conditions.extend( + [ + Chat.id.not_in(active_ids | pending_ids), + or_( + Chat.user_id != user_id, + and_( + Chat.last_read_at.is_not(None), + Chat.last_read_at != 0, + Chat.updated_at <= Chat.last_read_at, + ), + ), + ] + ) + + total = (await session.execute(select(func.count(Chat.id)).where(*conditions))).scalar_one() + rows = ( + ( + await session.execute( + select( + Chat.id, + Chat.title, + Chat.user_id, + Chat.updated_at, + Chat.created_at, + Chat.last_read_at, + Chat.meta, + ) + .where(*conditions) + .order_by(*chat_list_order(sort_by, sort_dir, user_id)) + .offset(skip) + .limit(limit) + ) + ) + .mappings() + .all() + ) + + tag_ids = {tag_id for row in rows for tag_id in (row['meta'] or {}).get('tags', [])} + owners = {row['user_id'] for row in rows} + labels = ( + { + (tag.user_id, tag.id): tag + for tag in ( + await session.execute(select(Tag).where(Tag.user_id.in_(owners), Tag.id.in_(tag_ids))) + ) + .scalars() + .all() + } + if tag_ids + else {} + ) + + bodies = {} + if chat_search_content_query(search) and rows: + bodies = dict( + ( + await session.execute( + select(Chat.id, Chat.chat).where(Chat.id.in_([row['id'] for row in rows])) + ) + ).all() + ) + + terms = chat_search_content_query(search).split() + chats = [] + for row in rows: + chat = dict(row) + meta = chat.pop('meta') or {} + chat['tags'] = [] + for tag_id in dict.fromkeys(meta.get('tags', [])): + tag = labels.get((chat['user_id'], tag_id)) + chat['tags'].append( + { + 'id': tag_id, + 'name': tag.name if tag else tag_id.replace('_', ' '), + # The palette and default color live in the frontend. + 'color': (tag.meta or {}).get('color') if tag else None, + } + ) + status = meta.get('folder_status') + chat['status'] = status if status in valid_status_ids else None + chat['status_since'] = folder_status_since(meta, chat['status']) + # For the time-in-status tooltip: when the current stretch began, and earlier + # time per status (statuses the folder no longer has are left out). + chat['status_entered_at'] = ( + _as_seconds(meta.get('folder_status_at')) if chat['status'] else None + ) + chat['status_durations'] = { + key: seconds + for key, value in (meta.get('folder_status_durations') or {}).items() + if key in valid_status_ids and (seconds := _as_seconds(value)) + } + chat['can_edit_tags'] = chat['can_edit_status'] = chat['user_id'] == user_id + # Only explain matches the title doesn't already show. + chat['search_snippet'] = ( + chat_search_snippet(bodies.get(chat['id']) or {}, search) + if terms and not all(term in chat['title'].lower() for term in terms) + else None + ) + chats.append(chat) + return chats, total + + async def get_participant_counts_by_folder_id( + self, folder_id: str, db: AsyncSession | None = None + ) -> dict[str, int]: + """How many of a folder's chats each person owns or wrote in.""" + async with get_async_db_context(db) as session: + dialect_name = (await session.connection()).dialect.name + rows = ( + await session.execute( + select(Chat.id, Chat.user_id).where(*self._folder_chat_conditions(folder_id, dialect_name)) + ) + ).all() + authors = await self.get_participant_ids_by_chat_ids([row[0] for row in rows], db=session) + counts: dict[str, int] = {} + for chat_id, owner in rows: + for participant_id in {owner, *authors.get(chat_id, ())}: + counts[participant_id] = counts.get(participant_id, 0) + 1 + return counts + + async def get_tag_counts_by_folder_id(self, folder_id: str, db: AsyncSession | None = None) -> list[dict]: + """Tags used in a folder with chat counts, aggregated in SQL without loading chats.""" + async with get_async_db_context(db) as session: + dialect_name = (await session.connection()).dialect.name + if dialect_name == 'sqlite': + source = "json_each(chat.meta, '$.tags')" + internal = "COALESCE(json_extract(chat.meta, '$.internal'), 0) != 1" + else: + source = "json_array_elements_text(chat.meta->'tags')" + internal = "COALESCE((chat.meta->>'internal')::boolean, false) = false" + query = text(f""" + SELECT tag.value AS id, MIN(COALESCE(label.name, tag.value)) AS name, + COUNT(DISTINCT chat.id) AS count + FROM chat CROSS JOIN {source} tag + LEFT JOIN tag label ON label.id = tag.value AND label.user_id = chat.user_id + WHERE chat.folder_id = :folder_id AND chat.archived = false AND {internal} + GROUP BY tag.value ORDER BY name + """) + result = await session.execute(query, {'folder_id': folder_id}) + return [dict(row) for row in result.mappings()] + + async def update_chat_folder_status_by_id_and_user_id( + self, id: str, folder_id: str, user_id: str, status: str | None, db: AsyncSession | None = None + ) -> bool: + """Set (or with None, clear) a chat's folder status, banking the time spent in its previous one. + + Time adds up per status, so moving away and coming back doesn't reset it. + """ + async with get_async_db_context(db) as session: + row = ( + await session.execute( + select(Chat.meta).filter_by(id=id, folder_id=folder_id, user_id=user_id) + ) + ).one_or_none() + if row is None: + return False + meta = dict(row[0] or {}) + previous = meta.get('folder_status') + if previous == status: + return True # Same status: keep its clock running. + now = int(time.time()) + started = _as_seconds(meta.get('folder_status_at')) + durations = dict(meta.get('folder_status_durations') or {}) + if previous and previous != 'none' and started is not None: # 'none' was stored by older builds + durations[previous] = (_as_seconds(durations.get(previous)) or 0) + max(0, now - started) + await session.execute( + update(Chat) + .filter_by(id=id) + .values( + meta={ + # No status means no stored status, like chats that never had one. + **{key: value for key, value in meta.items() if key not in ('folder_status', 'folder_status_at')}, + **({'folder_status': status, 'folder_status_at': now} if status is not None else {}), + 'folder_status_durations': durations, + } + ) + ) + await session.commit() + return True + async def count_all_chats_by_folder_id( self, folder_id: str, diff --git a/backend/open_webui/models/folders.py b/backend/open_webui/models/folders.py index 7973c9efed..aa2fef8ffd 100644 --- a/backend/open_webui/models/folders.py +++ b/backend/open_webui/models/folders.py @@ -79,6 +79,21 @@ class SharedFolderResponse(BaseModel): # Forms +def folder_status_ids(meta: dict | None) -> tuple[str, ...]: + """The statuses this folder defines in meta.statuses, in order. Chats may also have none (null).""" + ids: list[str] = [] + for item in (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 item['id'] not in ids + ): + ids.append(item['id']) + return tuple(ids) + + class FolderForm(BaseModel): name: str data: Optional[dict] = None diff --git a/backend/open_webui/models/tags.py b/backend/open_webui/models/tags.py index 2db4d0c8af..6b11e5b238 100644 --- a/backend/open_webui/models/tags.py +++ b/backend/open_webui/models/tags.py @@ -9,12 +9,11 @@ import uuid # local imports from open_webui.internal.db import Base, JSONField, get_async_db_context from pydantic import BaseModel, ConfigDict -from sqlalchemy import JSON, BigInteger, Column, Index, PrimaryKeyConstraint, String, delete, select +from sqlalchemy import JSON, BigInteger, Column, Index, PrimaryKeyConstraint, String, delete, select, update from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) - class Tag(Base): # database table mapping for tag entity __tablename__ = 'tag' id = Column(String) @@ -91,6 +90,18 @@ class TagTable: result = await db.execute(select(Tag).filter(Tag.id.in_(ids), Tag.user_id == user_id)) return [TagModel.model_validate(tag) for tag in result.scalars().all()] + async def update_tag_color_by_name_and_user_id( + self, name: str, user_id: str, color: str, db: AsyncSession | None = None + ) -> bool: + async with get_async_db_context(db) as db: + id = name.replace(' ', '_').lower() + meta = (await db.execute(select(Tag.meta).filter_by(id=id, user_id=user_id))).one_or_none() + if meta is None: + return False + await db.execute(update(Tag).filter_by(id=id, user_id=user_id).values(meta={**(meta[0] or {}), 'color': color})) + await db.commit() + return True + async def delete_tag_by_name_and_user_id(self, name: str, user_id: str, db: AsyncSession | None = None) -> bool: try: async with get_async_db_context(db) as db: diff --git a/backend/open_webui/routers/chats.py b/backend/open_webui/routers/chats.py index 01ad242128..349709f953 100644 --- a/backend/open_webui/routers/chats.py +++ b/backend/open_webui/routers/chats.py @@ -2454,3 +2454,22 @@ async def delete_tag_by_id_and_tag_name( return await Tags.get_tags_by_ids_and_user_id(tags, user.id, db=db) else: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND) + + +class TagColorForm(BaseModel): + name: str + # 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-]*$') + + +@router.patch('/{id}/tags', response_model=list[TagModel]) +async def update_chat_tag_color(request: Request, id: str, form_data: TagColorForm, + user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + tag_id = form_data.name.replace(' ', '_').lower() + chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db) + if not chat or tag_id not in (chat.meta or {}).get('tags', []): + raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + if not await Tags.update_tag_color_by_name_and_user_id(form_data.name, user.id, form_data.color, db=db): + raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + await publish_event(request, EVENTS.CHAT_UPDATED, actor=user, subject_id=id, data={'tag': form_data.name}) + return await Tags.get_tags_by_ids_and_user_id((chat.meta or {}).get('tags', []), user.id, db=db) diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py index 011f064384..552f62971a 100644 --- a/backend/open_webui/routers/folders.py +++ b/backend/open_webui/routers/folders.py @@ -4,7 +4,7 @@ import os import shutil import uuid from pathlib import Path -from typing import Optional +from typing import Literal, Optional from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status from fastapi.responses import FileResponse, StreamingResponse @@ -23,6 +23,7 @@ from open_webui.models.folders import ( FolderNameIdResponse, Folders, FolderUpdateForm, + folder_status_ids, ) from open_webui.models.groups import Groups from open_webui.models.shared_chats import ChatShareMode @@ -34,7 +35,7 @@ from open_webui.utils.access_control import ( ) from open_webui.utils.access_control.files import can_read_all_folder_files, get_accessible_folder_files from open_webui.utils.auth import get_admin_user, get_verified_user -from pydantic import BaseModel +from pydantic import BaseModel, Field from sqlalchemy.ext.asyncio import AsyncSession log = logging.getLogger(__name__) @@ -42,6 +43,10 @@ log = logging.getLogger(__name__) router = APIRouter() +# Folder list and board views page through a folder's chats this many at a time. +FOLDER_PAGE_SIZE = 50 +FolderActivity = Literal['unread', 'generating', 'waiting_for_approval', 'idle'] + from open_webui.utils.access_control.folders import has_folder_access as _has_folder_access @@ -578,6 +583,14 @@ async def get_shared_folder_chats( page: int | None = Query(None, ge=1), sort_by: str = Query('unread_updated_at'), sort_dir: str = Query('desc'), + workspace: bool = False, + search: str = Query('', max_length=256), + tag_ids: list[str] = Query(default=[]), + user_ids: list[str] = Query(default=[]), + # `status` is taken by fastapi's status module here, hence the alias. + status_filter: list[str] = Query(default=[], alias='status'), + activity: FolderActivity | None = None, + updated_at_gte: int | None = Query(None, ge=0), user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): @@ -601,19 +614,45 @@ async def get_shared_folder_chats( detail=ERROR_MESSAGES.ACCESS_PROHIBITED, ) - limit = 10 + limit = FOLDER_PAGE_SIZE if workspace else 10 skip = (page - 1) * limit if page is not None else 0 - chats = await Chats.get_all_chats_by_folder_id( - id, - skip=skip, - limit=limit if page is not None else 60, - sort_by=sort_by, - sort_dir=sort_dir, - unread_for_user_id=user.id, - db=db, - ) - total = await Chats.count_all_chats_by_folder_id(id, db=db) if page is not None else len(chats) - + if workspace: + if sort_by not in ('title', 'updated_at', 'unread_updated_at') or sort_dir not in ('asc', 'desc'): + raise HTTPException(status_code=422, detail='Invalid sort') + if len(tag_ids) > 50 or len(user_ids) > 50: + raise HTTPException(status_code=422, detail='Too many filters') + statuses = folder_status_ids(folder.meta) + # 'none' (or the older 'not_started') filters for chats without a status. + if any(value not in (*statuses, 'none', 'not_started') for value in status_filter): + raise HTTPException(status_code=422, detail='Invalid status') + chats, total = await Chats.get_folder_chat_page( + id, + user.id, + skip=skip, + limit=limit, + search=search.strip(), + tag_ids=tag_ids, + status_ids=status_filter, + valid_status_ids=statuses, + user_ids=user_ids, + activity=activity, + updated_at_gte=updated_at_gte, + sort_by=sort_by, + sort_dir=sort_dir, + redis=request.app.state.redis, + db=db, + ) + else: + chats = await Chats.get_all_chats_by_folder_id( + id, + skip=skip, + limit=limit if page is not None else 60, + sort_by=sort_by, + sort_dir=sort_dir, + unread_for_user_id=user.id, + db=db, + ) + total = await Chats.count_all_chats_by_folder_id(id, db=db) if page is not None else len(chats) participant_ids = await Chats.get_participant_ids_by_chat_ids([chat['id'] for chat in chats], db=db) user_ids = {chat['user_id'] for chat in chats} user_ids.update(uid for ids in participant_ids.values() for uid in ids) @@ -686,6 +725,59 @@ async def mark_folder_chats_read_by_id( } +async def check_folder_read_access(request: Request, id: str, user, db: AsyncSession) -> FolderModel: + """Return the folder if the user may read it (owner, admin or shared), else raise.""" + await check_folders_permission(request, user, db=db) + folder = await Folders.get_folder_by_id(id, db=db) + if not folder: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=ERROR_MESSAGES.NOT_FOUND, + ) + if user.role != 'admin' and folder.user_id != user.id and not await _has_folder_access(user.id, folder, 'read', db): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=ERROR_MESSAGES.ACCESS_PROHIBITED, + ) + return folder + + +@router.get('/{id}/users') +async def get_folder_users(request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + await check_folder_read_access(request, id, user, db) + counts = await Chats.get_participant_counts_by_folder_id(id, db=db) + users = await Users.get_users_by_user_ids(list(counts), db=db) if counts else [] + names = {u.id: u.name for u in users} + return sorted( + [{'id': user_id, 'name': names.get(user_id) or 'Unknown', 'count': count} for user_id, count in counts.items()], + key=lambda entry: (entry['id'] != user.id, entry['name'].casefold()), + ) + + +@router.get('/{id}/tags') +async def get_folder_tags(request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + await check_folder_read_access(request, id, user, db) + return await Chats.get_tag_counts_by_folder_id(id, db=db) + + +class FolderChatStatusForm(BaseModel): + # null clears the status. + status: str | None = Field(default=None, min_length=1, max_length=64) + + +@router.patch('/{id}/chats/{chat_id}/status') +async def update_folder_chat_status(request: Request, id: str, chat_id: str, form_data: FolderChatStatusForm, + user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + folder = await check_folder_read_access(request, id, user, db) + if form_data.status is not None and form_data.status not in folder_status_ids(folder.meta): + raise HTTPException(status_code=422, detail='Invalid status') + if not await Chats.update_chat_folder_status_by_id_and_user_id(chat_id, id, user.id, form_data.status, db=db): + raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + await publish_event(request, EVENTS.CHAT_UPDATED, actor=user, subject_id=chat_id, + data={'folder_id': id, 'folder_status': form_data.status}) + return {'id': chat_id, 'status': form_data.status} + + # Delete Folder By Id diff --git a/backend/open_webui/socket/main.py b/backend/open_webui/socket/main.py index 6aed3f1003..69c21e5b2a 100644 --- a/backend/open_webui/socket/main.py +++ b/backend/open_webui/socket/main.py @@ -1591,7 +1591,11 @@ async def get_event_emitter(request_info, update_db=True): pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat_id]) event_data = { **event_data, - 'data': {**(event_data.get('data') or {}), 'pending_approval': chat_id in pending_approval_ids}, + 'data': { + **(event_data.get('data') or {}), + 'pending_approval': chat_id in pending_approval_ids, + **({'folder_unread_counts': await get_folder_unread_counts(user_id)} if not internal else {}), + }, } room = f'user:{user_id}' diff --git a/src/lib/apis/chats/index.ts b/src/lib/apis/chats/index.ts index 4a14afa5ea..04ec6ddce5 100644 --- a/src/lib/apis/chats/index.ts +++ b/src/lib/apis/chats/index.ts @@ -1561,6 +1561,44 @@ export const addTagById = async (token: string, id: string, tagName: string) => return res; }; +export const updateTagColorById = async ( + token: string, + id: string, + tagName: string, + color: string +) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/tags`, { + method: 'PATCH', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + }, + body: JSON.stringify({ + name: tagName, + color + }) + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + error = getErrorDetail(err); + + console.error(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + export const deleteTagById = async (token: string, id: string, tagName: string) => { let error = null; diff --git a/src/lib/apis/folders/index.ts b/src/lib/apis/folders/index.ts index 8055f81b4b..6c53974d4c 100644 --- a/src/lib/apis/folders/index.ts +++ b/src/lib/apis/folders/index.ts @@ -334,10 +334,8 @@ export type ChatParticipant = { export const getSharedFolderChats = async ( token: string, folderId: string, - params: { + params: Omit & { page?: number | null; - sortBy?: 'title' | 'updated_at' | 'unread_updated_at'; - sortDir?: 'asc' | 'desc'; } = {} ) => { let error = null; @@ -352,6 +350,14 @@ export const getSharedFolderChats = async ( if (params.sortDir) { searchParams.append('sort_dir', params.sortDir); } + if (params.workspace) searchParams.set('workspace', 'true'); + if (params.search?.trim()) searchParams.set('search', params.search.trim()); + for (const tag of params.tagIds ?? []) searchParams.append('tag_ids', tag); + for (const id of params.userIds ?? []) searchParams.append('user_ids', id); + for (const status of [params.status ?? []].flat()) searchParams.append('status', status); + if (params.activity) searchParams.set('activity', params.activity); + if (params.updatedAtGte !== undefined) + searchParams.set('updated_at_gte', String(params.updatedAtGte)); const query = searchParams.toString(); const res = await fetch( @@ -383,3 +389,100 @@ export const getSharedFolderChats = async ( return res; }; + +export const getFolderUsers = async (token: string, id: string, signal?: AbortSignal) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/folders/${encodeURIComponent(id)}/users`, { + signal, + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + if (signal?.aborted) return null; + error = err.detail; + console.error(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const getFolderTags = async (token: string, id: string, signal?: AbortSignal) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/folders/${encodeURIComponent(id)}/tags`, { + signal, + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + if (signal?.aborted) return null; + error = err.detail; + console.error(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const updateFolderChatStatus = async ( + token: string, + folderId: string, + chatId: string, + status: string | null +) => { + let error = null; + + const res = await fetch( + `${WEBUI_API_BASE_URL}/folders/${encodeURIComponent(folderId)}/chats/${encodeURIComponent(chatId)}/status`, + { + method: 'PATCH', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + }, + body: JSON.stringify({ status }) + } + ) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + error = err.detail; + console.error(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 1da533932c..85426d3eb6 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -4218,6 +4218,8 @@ let mainChatGroupId = ''; let tabTitleEditor: import('svelte').Snippet | undefined; let tabActions: import('svelte').Snippet | undefined; + let folderTabActions: import('svelte').Snippet | undefined; + let tabBarActions: import('svelte').Snippet | undefined; let initializedTerminalChatId: string | null = null; @@ -5786,7 +5788,7 @@ }} /> {/if} -
+
{liveStatus}
{#if (!side && $settings?.landingPageMode === 'chat' && !$selectedFolder) || (!contextOnly && createMessagesList(history, history.currentId).length > 0)}
{:else} -
+
@@ -2040,7 +2040,7 @@
@@ -2235,8 +2235,8 @@ id={inputId === 'chat-input' ? 'message-input-container' : `${inputId}-wrapper`} data-composer-id={inputId} class="flex-1 flex flex-col relative w-full shadow-[0_6px_24px_-4px_rgba(0,0,0,0.1)] rounded-3xl border {isTemporary - ? 'border-dashed border-gray-200 dark:border-gray-800' - : ' border-gray-200 dark:border-gray-800'} {($settings?.highContrastMode ?? + ? 'border-dashed border-gray-200 dark:border-gray-850' + : ' border-gray-200 dark:border-gray-850'} {($settings?.highContrastMode ?? false) ? 'focus-within:outline focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-blue-500 [&_.ProseMirror:focus-visible]:outline-none!' : ''} transition px-0.5 bg-white/5 dark:bg-gray-500/5 backdrop-blur-sm dark:text-gray-100" diff --git a/src/lib/components/chat/Messages/ContentRenderer.svelte b/src/lib/components/chat/Messages/ContentRenderer.svelte index 187bf6000c..25eb934538 100644 --- a/src/lib/components/chat/Messages/ContentRenderer.svelte +++ b/src/lib/components/chat/Messages/ContentRenderer.svelte @@ -11,6 +11,7 @@ import Markdown from './Markdown.svelte'; import StructuredOutputRenderer from './StructuredOutputRenderer.svelte'; + import { getOutputText } from './structuredOutput'; import FloatingButtons from '../ContentRenderer/FloatingButtons.svelte'; import { createMessagesList, replaceOutsideCode } from '$lib/utils'; @@ -146,7 +147,12 @@ ) : messageContent; - let autoOpenedArtifactIds = new Set(); + const initialContent = content; + const initialOutputText = getOutputText(output); + // The final code fence can render after the response is marked done. + let hasStreamed = !done; + $: if (!done) hasStreamed = true; + const seenArtifactIds = new Set(); /** @type {ReturnType} */ let commentSelection = null; @@ -163,17 +169,18 @@ ['html', 'svg'].includes(normalizedLang) || (normalizedLang === 'xml' && code.toLowerCase().includes(' - {#if hasResponseContent && message.error !== true} + {#if message.error !== true} +
- {#if !history.currentId && !$chatId && ($banners.length > 0 || ($config?.license_metadata?.type ?? null) === 'trial' || (($config?.license_metadata?.seats ?? null) !== null && $config?.user_count > $config?.license_metadata?.seats))} + {#if !$selectedFolder && !history.currentId && !$chatId && ($banners.length > 0 || ($config?.license_metadata?.type ?? null) === 'trial' || (($config?.license_metadata?.seats ?? null) !== null && $config?.user_count > $config?.license_metadata?.seats))}
-
+{#snippet composer(placeholder = '')} + { + dispatch('submit', e.detail); + }} + /> +{/snippet} + +
{#if $temporaryChatEnabled} {/if} -
-
- {#if $selectedFolder} - { - await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]); - }} - onDelete={async (deletedFolder: { id: string }) => { - await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]); + {#if $selectedFolder} +
+ messageInput?.focus()} + /> - if ($selectedFolder?.id === deletedFolder.id) selectedFolder.set(null); - }} - /> - {:else} + {#if !folderReadOnly} + +
+
+ {@render composer()} +
+
+ {/if} +
+ {:else} +
+
@@ -257,67 +329,17 @@ {/if}
- {/if} - -
- {#if !($selectedFolder && folderReadOnly)} - { - dispatch('submit', e.detail); - }} - /> - {/if}
-
- {#if $selectedFolder} -
- +
+ {@render composer($i18n.t('How can I help you today?'))}
- {:else} +
diff --git a/src/lib/components/chat/Placeholder/ChatList.svelte b/src/lib/components/chat/Placeholder/ChatList.svelte index 6aaf3173a0..ae3f84bbbc 100644 --- a/src/lib/components/chat/Placeholder/ChatList.svelte +++ b/src/lib/components/chat/Placeholder/ChatList.svelte @@ -1,307 +1,352 @@ -{#if chatList} - {#if chatList.length > 0} -
- + {#if group.status} + + {:else if group.spinner} + + {:else if group.dot} + {/if} +

+ {group.label} +

+ {group.page?.total ?? ''}
- - -
- {/if} - -
- {#if chatList.length === 0} -
- {$i18n.t('No chats found')}
{/if} - {#each chatList as chat, idx (chat.id)} - {@const unread = - chat.id !== $chatId && - !chat.active && - (chat.last_read_at == null || - (chat.updated_at != null && chat.updated_at > chat.last_read_at))} - {#if (idx === 0 || (idx > 0 && chat.time_range !== chatList[idx - 1].time_range)) && chat?.time_range} -
- {$i18n.t(chat.time_range)} - -
- {/if} + {#if !collapsed[group.id]} +
    + {#each chats as chat (chat.id)} + {@const unread = chat.id !== $chatId && !chat.active && isChatUnread(chat)} + +
  • open(event, chat)} + > +
    + + {#if showStatusTime} + + + {/if} + + {#if chat.pending_approval || chat.active || unread} + + {#if chat.pending_approval} + + {:else if chat.active} + + {:else if unread} + + {/if} + + {/if} +
    -
    - {#if (showOwnerInfo && chat.user_id) || (chat.participants?.length ?? 0) > 1} -
    - +
    + {#if renaming === chat.id} + saveRename(chat)} + on:keydown={(event) => { + if (event.isComposing || event.keyCode === 229) return; + if (event.key === 'Enter') { + event.preventDefault(); + void saveRename(chat); + } else if (event.key === 'Escape') { + event.preventDefault(); + renaming = ''; + } + }} + /> + {:else} + openFolderChat(chat, appLayout, event)}>{chat.title} + {/if} + {#if chat.search_snippet} + + {/if} +
    + +
    + + + +
    + + + +
    + startRename(chat)} + onChange={onTagsChange} + /> +
    +
    +
    +
  • + {/each} +
+ + {#if group.page?.has_more} + {#if group.label} + + {:else} +
+ {#if loadingGroup === group.id}{/if}
{/if} - - markChatRead(chat, unread)} - > -
- {#if chat.active} -
- -
- {:else if unread} -
-
-
- {/if} - -
- {chat?.title} -
-
- - -
-
- {/each} - - {#if totalPages > 1} -
- - - {#each pages as item, index (item === 'ellipsis' ? `ellipsis-${index}` : item)} - {#if item === 'ellipsis'} - - ... - - {:else} - - {/if} - {/each} - - -
+ {/if} {/if} -
-{/if} + {/each} +
+ + diff --git a/src/lib/components/chat/Placeholder/FolderBoard.svelte b/src/lib/components/chat/Placeholder/FolderBoard.svelte new file mode 100644 index 0000000000..b73afc676b --- /dev/null +++ b/src/lib/components/chat/Placeholder/FolderBoard.svelte @@ -0,0 +1,371 @@ + + +{#snippet groupIcon(group: BoardGroup)} + {#if group.status} + + {:else if group.spinner} + + {:else if group.dot} + + {/if} +{/snippet} + +{#snippet columnHeader(column: BoardGroup)} +
+ {@render groupIcon(column)} +

+ {column.label} +

+ {column.page?.total ?? ''} +
+{/snippet} + +{#snippet more(column: BoardGroup)} + {#if column.page?.has_more} + + {/if} +{/snippet} + +{#snippet card(chat: WorkspaceChat)} + {@const unread = chat.id !== $chatId && !chat.active && isChatUnread(chat)} + +
open(event, chat)} + on:dragstart={(event) => { + dragged = chat; + event.dataTransfer?.setData('text/plain', chat.id); + if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move'; + }} + on:dragend={() => { + dragged = null; + over = ''; + }} + > +
+
+ +
+ + {#if chat.status_since && chat.status} + + {/if} + {#if chat.pending_approval || chat.active || unread} + + + {#if chat.pending_approval} + + {:else if chat.active} + + {:else} + + {/if} + + {/if} + openFolderChat(chat, appLayout, event)}>{chat.title} +
+ + {#if chat.search_snippet} +

+ {chat.search_snippet} +

+ {/if} + +
+
+ +
+ + + + +
+
+{/snippet} + +{#snippet emptyCell(column: string, row: string | null)} +
+ {$i18n.t('No conversations')} +
+{/snippet} + +{#snippet addStatus()} + {#if onAddStatus} + + {/if} +{/snippet} + +{#if !rows} + +
+ {#each columns as column (column.id)} + {@const chats = column.page?.chats ?? []} + {@const zone = dropzone(column.id, null)} +
+ {@render columnHeader(column)} +
+ {#each chats as chat (chat.id)} + {@render card(chat)} + {/each} + {#if !loading && !chats.length} + {@render emptyCell(column.id, null)} + {/if} + {@render more(column)} +
+
+ {/each} + {@render addStatus()} +
+{:else} + +
+
+
+ {#each columns as column (column.id)} +
+ {@render columnHeader(column)} +
+ {/each} + {@render addStatus()} +
+ + {#each rows as row (row.id)} + {@const count = rowCount(row)} + {#if count} +
+ + {@render groupIcon(row)} + {row.label} + {count} +
+ + {#if !collapsed[row.id]} +
+ {#each columns as column (column.id)} + {@const chats = cellChats(column, row)} + {@const zone = dropzone(column.id, row.id)} +
+ {#each chats as chat (chat.id)} + {@render card(chat)} + {/each} + {#if !chats.length} +
+ {/if} +
+ {/each} +
+ {/if} + {/if} + {/each} + +
+ {#each columns as column (column.id)} +
{@render more(column)}
+ {/each} +
+
+
+{/if} diff --git a/src/lib/components/chat/Placeholder/FolderChatMenu.svelte b/src/lib/components/chat/Placeholder/FolderChatMenu.svelte new file mode 100644 index 0000000000..d0ab4288b2 --- /dev/null +++ b/src/lib/components/chat/Placeholder/FolderChatMenu.svelte @@ -0,0 +1,133 @@ + + + + + +
+ {$i18n.t('This will delete')} {chat.title}. +
+
+ + (showShare = true)} + moveChatHandler={move} + archiveChatHandler={archive} + renameHandler={onRename} + deleteHandler={() => (showDelete = true)} + markUnreadHandler={markUnread} + onOpen={() => (open = true)} + onClose={() => (open = false)} + onPinChange={() => onChange()} +> + + diff --git a/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte b/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte index cf3be2bf6a..2119f06a5e 100644 --- a/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte +++ b/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte @@ -1,216 +1,1383 @@ -
- + {/each} + +{/snippet} -
- {#if selectedTab === 'knowledge'} - - {:else if selectedTab === 'chats'} - {#if chats !== null} - - {:else if loadError} - - {:else} -
- -
+{#snippet folderIcon()} + {#if folder?.meta?.icon} + + {:else} + + {/if} +{/snippet} + +{#snippet chip( + id: Facet, + values: { label: string; dot?: string; status?: FolderStatus; avatar?: string }[] +)} +
+ + {@render facetIcon(id)}{$i18n.t(facets.find((item) => item.id === id)?.label ?? '')} + + + {values.length > 1 ? $i18n.t('is any of') : $i18n.t('is')} + + + +
+{/snippet} + +
+ { + await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]); + }} + onDelete={async (deletedFolder: { id: string }) => { + await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]); + if ($selectedFolder?.id === deletedFolder.id) selectedFolder.set(null); + }} + /> + +
+

+ + + {#if readOnly} + {@render folderIcon()} + {:else} + + + + {/if} + {#if readOnly} + {folder?.name} + {:else} + + {/if} + + + {$i18n.t('Chats')} + {#if loading && hasData} + + {:else if hasData && !error} + {formatNumber(total)} {/if} +

+ +
+ {#if searchOpen || search} +
+ + { + if (!search) searchOpen = false; + }} + on:keydown={(event) => { + if (event.key === 'Enter') apply(); + if (event.key === 'Escape') { + search = ''; + apply(); + searchOpen = false; + searchInput.blur(); + } + }} + /> + {#if search} + + {/if} +
+ {:else} + + {/if} + + (tagQuery = '')}> + + + + {#each facets as item (item.id)} + + + + {#if (item.id === 'tags' && options.length > 8) || (item.id === 'users' && folderUsers.length > 8)} +
+ + +
+ {/if} + {#if optionsError && item.id === 'tags'} + + {/if} + {#each facetOptions(item.id, item.id === 'tags' || item.id === 'users' ? tagQuery : '') as option (`${option.facet}:${option.value}`)} + + {:else} +
+ {$i18n.t('No results')} +
+ {/each} +
+ {/each} + {#if filterCount} +
+ + {/if} +
+
+ + + + + +
+ {$i18n.t('Layout')} +
+ {#each [['list', 'List', 'list'], ['board', 'Board', 'grid']] as const as [value, label, icon]} + + {/each} + +
+ + {#if view === 'list'} + {@render groupMenu( + $i18n.t('Grouping'), + grouping, + ['none', 'status', 'tags', 'activity'], + (value) => setGrouping(value) + )} + {:else} + {@render groupMenu( + $i18n.t('Columns'), + columnsBy, + ['status', 'tags', 'activity'], + (value) => setColumns(value as Exclude) + )} + {@render groupMenu( + $i18n.t('Rows'), + rowsBy, + (['none', 'status', 'tags', 'activity'] as const).filter( + (value) => value !== columnsBy + ), + (value) => setRows(value) + )} + {/if} + + + + {#each [['updated_at', 'Updated'], ['title', 'Title']] as const as [value, label]} + + {/each} +
+ {#each [['asc', 'Ascending'], ['desc', 'Descending']] as const as [value, label]} + + {/each} +
+ + {#if view === 'list' && grouping !== 'none'} + + {/if} +
+
+
+
+ + + {#if folder?.data?.description?.trim()} +

+ {folder.data.description.trim()} +

+ {/if} + + {#if filterCount} +
+ {#if statusFilter.length} + {@render chip( + 'status', + defs + .filter((status) => statusFilter.includes(status.id)) + .map((status) => ({ label: status.name, status: status.id })) + )} + {/if} + {#if selectedTags.length} + {@render chip( + 'tags', + selectedTags.map((id) => { + if (id === UNTAGGED) + return { label: $i18n.t('Untagged'), dot: 'border border-dashed border-gray-400' }; + const tag = options.find((item) => item.id === id) ?? { + id, + name: id.replaceAll('_', ' ') + }; + return { label: tag.name, dot: tagDot(tag) }; + }) + )} + {/if} + {#if selectedUsers.length} + {@render chip( + 'users', + selectedUsers.map((id) => ({ + label: folderUsers.find((entry) => entry.id === id)?.name ?? $i18n.t('Unknown'), + avatar: `${WEBUI_API_BASE_URL}/users/${id}/profile/image` + })) + )} + {/if} + {#if activity} + {@render chip('activity', [ + { label: $i18n.t(activityOptions.find(([value]) => value === activity)?.[1] ?? '') } + ])} + {/if} + {#if updatedRange} + {@render chip('updated', [ + { label: $i18n.t(updatedOptions.find(([value]) => value === updatedRange)?.[1] ?? '') } + ])} + {/if} + +
+ {/if} + + {#if error} + + {/if} + +
+ {#if loading && !hasData} +
+ +
+ {:else if hasData && !total && !error && view === 'list'} +
+
+ {filtered ? $i18n.t('No matching conversations') : $i18n.t('No conversations yet')} +
+
+ {filtered + ? $i18n.t('Try a different search or remove a filter.') + : readOnly + ? $i18n.t('Conversations in this folder will show up here.') + : $i18n.t('Ask anything below to start one.')} +
+ {#if filtered} + + {/if} +
+ {:else if view === 'board'} + (showStatuses = true)} + columns={boardColumns} + rows={boardRows} + {rowOf} + {dropStatus} + {saving} + {loading} + {loadingGroup} + onMore={loadMore} + onMove={move} + onTagsChange={changed} + /> + {:else} + {/if}
-
+ + + diff --git a/src/lib/components/chat/Placeholder/FolderStatus.svelte b/src/lib/components/chat/Placeholder/FolderStatus.svelte new file mode 100644 index 0000000000..db3c90e920 --- /dev/null +++ b/src/lib/components/chat/Placeholder/FolderStatus.svelte @@ -0,0 +1,70 @@ + + + + {#if chat.can_edit_status} + + + + {#each $defs ?? [] as status (status.id)} + + {/each} + {#if $manage} +
+ + {/if} +
+
+ {:else} + + + + {/if} +
diff --git a/src/lib/components/chat/Placeholder/FolderStatusIcon.svelte b/src/lib/components/chat/Placeholder/FolderStatusIcon.svelte new file mode 100644 index 0000000000..1ac08291b1 --- /dev/null +++ b/src/lib/components/chat/Placeholder/FolderStatusIcon.svelte @@ -0,0 +1,68 @@ + + +{#if shownEmoji} + +{:else if !shape} + + +{:else} + +{/if} diff --git a/src/lib/components/chat/Placeholder/FolderStatusTime.svelte b/src/lib/components/chat/Placeholder/FolderStatusTime.svelte new file mode 100644 index 0000000000..033ada5a12 --- /dev/null +++ b/src/lib/components/chat/Placeholder/FolderStatusTime.svelte @@ -0,0 +1,69 @@ + + +{#if chat.status_since && chat.status} + + {formatElapsedShort(chat.status_since)} + +{/if} diff --git a/src/lib/components/chat/Placeholder/FolderStatusesModal.svelte b/src/lib/components/chat/Placeholder/FolderStatusesModal.svelte new file mode 100644 index 0000000000..1546917092 --- /dev/null +++ b/src/lib/components/chat/Placeholder/FolderStatusesModal.svelte @@ -0,0 +1,261 @@ + + + +
+
+
{$i18n.t('Statuses')}
+ +
+ +
+
+
+ + + {$i18n.t('No status')} + {$i18n.t('Default')} +
+ + {#each draft as item (item.id)} + +
{ + if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move'; + }} + on:dragover|preventDefault={() => reorder(item.id)} + on:dragend={() => (dragId = '')} + > + (dragId = item.id)} + on:pointerup={() => (dragId = '')} + > + + + + + + +
+ {$i18n.t('Icon')} +
+
+ {#each statusGlyphs as glyph} + + {/each} +
+
+ {$i18n.t('Color')} +
+
+ {#each tagColors as color} + + {/each} +
+
+ update(item.id, { icon: icon ?? undefined })} + > + + +
+
+ + update(item.id, { name: event.currentTarget.value })} + /> + +
+ {/each} + + +
+ +

+ {$i18n.t('Chats in a deleted status go back to “No status”.')} +

+ +
+ +
+
+
+
diff --git a/src/lib/components/chat/Placeholder/FolderTags.svelte b/src/lib/components/chat/Placeholder/FolderTags.svelte new file mode 100644 index 0000000000..5e811589a1 --- /dev/null +++ b/src/lib/components/chat/Placeholder/FolderTags.svelte @@ -0,0 +1,242 @@ + + +{#snippet pills()} + {#each assigned.slice(0, max) as tag (tag.id)} + + + {tag.name} + + {/each} + {#if assigned.length > max} + tag.name) + .join(', ')}>+{assigned.length - max} + {/if} +{/snippet} + +{#if chat.can_edit_tags} + + + + +
{ + const exact = options.find((tag) => tag.name.toLowerCase() === needle); + if (exact) void toggle(exact); + else if (canCreate) + void mutate(() => addTagById(localStorage.token, chat.id, query.trim()), true); + }} + > + +
+ +
+ {#each options as tag (tag.id)} + {@const checked = isAssigned(tag)} +
+ + {#if checked} + + +
+ {#each tagColors as color} + + {/each} +
+
+ {/if} +
+ {/each} + + {#if canCreate} + + {:else if !options.length} +
+ {$i18n.t('No tags yet. Type to create one.')} +
+ {/if} +
+
+
+{:else if assigned.length} +
{@render pills()}
+{/if} + + diff --git a/src/lib/components/chat/Placeholder/FolderTitle.svelte b/src/lib/components/chat/Placeholder/FolderTitle.svelte index 898df4b20c..da5833ef86 100644 --- a/src/lib/components/chat/Placeholder/FolderTitle.svelte +++ b/src/lib/components/chat/Placeholder/FolderTitle.svelte @@ -2,8 +2,6 @@ import { getContext } from 'svelte'; const i18n = getContext('i18n'); - import DOMPurify from 'dompurify'; - import fileSaver from 'file-saver'; const { saveAs } = fileSaver; @@ -14,33 +12,28 @@ loadFolderDetails, updateFolderDetails, removeFolderState, - type FolderDetails, + type FolderDetails } from '$lib/stores/folderStates'; - import { - deleteFolderById, - updateFolderById, - createNewFolder - } from '$lib/apis/folders'; + import { deleteFolderById, updateFolderById, createNewFolder } from '$lib/apis/folders'; import { getChatsByFolderId } from '$lib/apis/chats'; import FolderModal from '$lib/components/layout/Sidebar/Folders/FolderModal.svelte'; - import Folder from '$lib/components/icons/Folder.svelte'; - import XMark from '$lib/components/icons/XMark.svelte'; import FolderMenu from '$lib/components/layout/Sidebar/Folders/FolderMenu.svelte'; import EllipsisHorizontal from '$lib/components/icons/EllipsisHorizontal.svelte'; import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte'; - import Emoji from '$lib/components/common/Emoji.svelte'; - import EmojiPicker from '$lib/components/common/EmojiPicker.svelte'; export let folder: FolderDetails | null = null; export let readOnly: boolean = false; + export let onNewChat: () => void = () => {}; + export let folderTabActions: import('svelte').Snippet | undefined = undefined; + $: folderTabActions = renderFolderActions; export let onUpdate: Function = (folderId) => {}; export let onDelete: Function = (folderId) => {}; - let showFolderModal = false; + export let showFolderModal = false; let showCreateSubFolderModal = false; let showDeleteConfirm = false; let deleteFolderContents = true; @@ -78,39 +71,12 @@ toast.success($i18n.t('Folder updated successfully')); - const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch((error) => { - toast.error(`${error}`); - return null; - }); - - const updatedFolder = { ...targetFolder, ..._folder }; - if ($selectedFolder?.id === targetFolder.id) selectedFolder.set(updatedFolder); - onUpdate(updatedFolder); - } - }; - - const updateIconHandler = async (iconName) => { - const targetFolder = folder; - if (!targetFolder) return; - const res = await updateFolderById(localStorage.token, targetFolder.id, { - meta: { - icon: iconName ?? '' - } - }).catch((error) => { - toast.error(`${error}`); - return null; - }); - - if (res) { - updateFolderDetails(targetFolder.id, res); - targetFolder.meta = { ...targetFolder.meta, icon: iconName ?? '' }; - - toast.success($i18n.t('Folder updated successfully')); - - const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch((error) => { - toast.error(`${error}`); - return null; - }); + const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch( + (error) => { + toast.error(`${error}`); + return null; + } + ); const updatedFolder = { ...targetFolder, ..._folder }; if ($selectedFolder?.id === targetFolder.id) selectedFolder.set(updatedFolder); @@ -121,12 +87,14 @@ const deleteHandler = async () => { const targetFolder = folder; if (!targetFolder) return; - const res = await deleteFolderById(localStorage.token, targetFolder.id, deleteFolderContents).catch( - (error) => { - toast.error(`${error}`); - return null; - } - ); + const res = await deleteFolderById( + localStorage.token, + targetFolder.id, + deleteFolderContents + ).catch((error) => { + toast.error(`${error}`); + return null; + }); if (res) { removeFolderState(targetFolder.id); @@ -175,6 +143,35 @@ }; +{#snippet renderFolderActions()} + {#if folder && !readOnly} +
+ { + showFolderModal = true; + }} + onDelete={() => { + showDeleteConfirm = true; + }} + onExport={() => { + exportHandler(); + }} + onCreateSubFolder={() => { + showCreateSubFolderModal = true; + }} + > +
+ +
+
+
+ {/if} +{/snippet} + {#if folder}
- -
-
- {#if readOnly} -
- {#if folder?.meta?.icon} - - {:else} - - {/if} -
- {:else} - {}} - selected={folder?.meta?.icon ?? null} - onSubmit={(name) => { - console.log(name); - updateIconHandler(name); - }} - > - - - {/if} - -
- {folder.name} -
-
- - {#if !readOnly} -
- { - showFolderModal = true; - }} - onDelete={() => { - showDeleteConfirm = true; - }} - onExport={() => { - exportHandler(); - }} - onCreateSubFolder={() => { - showCreateSubFolderModal = true; - }} - > -
- -
-
-
- {/if} -
- - {#if folder.data?.description} - -
-

{folder.data.description}

-
- {/if} {/if} diff --git a/src/lib/components/chat/Placeholder/folderChat.ts b/src/lib/components/chat/Placeholder/folderChat.ts new file mode 100644 index 0000000000..aa4aad2e72 --- /dev/null +++ b/src/lib/components/chat/Placeholder/folderChat.ts @@ -0,0 +1,39 @@ +import { goto } from '$app/navigation'; +import { get } from 'svelte/store'; +import { socket, selectedFolder } from '$lib/stores'; +import { updateFolderChatLists } from '$lib/stores/folderStates'; +import type { AppLayoutContext } from '$lib/types'; +import type { WorkspaceChat } from '$lib/utils/folders'; + +const wantsBrowserTab = (event?: MouseEvent) => + !!event && (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0); + +function markRead(chat: WorkspaceChat) { + updateFolderChatLists({ id: chat.id, last_read_at: Date.now() / 1000 }); + get(socket)?.emit('events:chat', { chat_id: chat.id, data: { type: 'last_read_at' } }); +} + +/** + * Opens a chat from the folder view in an internal tab beside it, the same way mention + * links open pages. Modifier clicks keep the browser's new-tab behaviour. + */ +export function openFolderChat( + chat: WorkspaceChat, + appLayout: AppLayoutContext | undefined, + event?: MouseEvent +) { + markRead(chat); + const href = `/c/${chat.id}`; + if (wantsBrowserTab(event)) { + // A link handles its own modifier click; anywhere else on the row needs a hand. + if (!(event?.target as Element | null)?.closest('a')) window.open(href, '_blank', 'noopener'); + return; + } + event?.preventDefault(); + if (appLayout?.openPageTab) { + appLayout.openPageTab({ href, label: chat.title }); + } else { + selectedFolder.set(null); + void goto(href); + } +} diff --git a/src/lib/components/chat/Tabs.svelte b/src/lib/components/chat/Tabs.svelte index bbf717bf6d..5de60ee356 100644 --- a/src/lib/components/chat/Tabs.svelte +++ b/src/lib/components/chat/Tabs.svelte @@ -87,6 +87,7 @@ import Dropdown from '../common/Dropdown.svelte'; import DropdownMenu from '../common/DropdownMenu.svelte'; import Icon from './FileNav/Icon.svelte'; + import Emoji from '$lib/components/common/Emoji.svelte'; import Annotation from '$lib/components/icons/Annotation.svelte'; import HomeIcon from '$lib/components/icons/Home.svelte'; import HashtagIcon from '$lib/components/icons/Hashtag.svelte'; @@ -159,6 +160,8 @@ export let mainChatGroupId = ''; let paneCanvas: HTMLDivElement; export let title = ''; + export let mainTabFolder: { id: string; name: string; icon?: string | null } | null = null; + $: mainTabTitle = mainTabFolder?.name ?? title; export let mainChatHref = '/'; export let tabTitleEditor: import('svelte').Snippet | undefined = undefined; export let tabActions: import('svelte').Snippet | undefined = undefined; @@ -293,7 +296,7 @@ if (version !== switchVersion) return; // The chat restores its terminal and directory together; layouts must not override them. owner.state.selectedTerminalId = $selectedTerminalId; - owner.state.panels = setMainChatTab(owner.state.panels, true, title); + owner.state.panels = setMainChatTab(owner.state.panels, true, mainTabTitle); tabs = owner.state.panels; dirtyFiles = {}; fileContexts = {}; @@ -2184,10 +2187,11 @@ {/if}
{/each} - {#if viewReady && !chatLoading && !viewError && !tabs.tabs.length && canOpenNewTab}
+ {#if viewReady && !chatLoading && !viewError && !displayTabs.tabs.length && (canOpenNewTab || !largeScreen)}
- {$i18n.t('Open a tab using the + menu.')} + {canOpenNewTab ? $i18n.t('Open a tab using the + menu.') : $i18n.t('No open tabs')}
{/if}
@@ -2246,13 +2250,19 @@ aria-controls={`${domId(tab.id)}-view`} aria-selected={group.activeId === tab.id} tabindex={group.activeId === tab.id ? 0 : -1} - title={tab.kind === 'chat' ? title : (tab.directory ?? tab.path ?? tabLabel(tab))} - aria-label={tab.kind === 'chat' ? title : undefined} + title={tab.kind === 'chat' ? mainTabTitle : (tab.directory ?? tab.path ?? tabLabel(tab))} + aria-label={tab.kind === 'chat' ? mainTabTitle : undefined} class="flex h-full items-center gap-1.5 min-w-0" > {#if (tab.kind === 'chat' && chatStreaming) || (tab.kind === 'side' && sideChatStreaming[tab.id])} {$i18n.t('Generating...')} + {:else if tab.kind === 'chat' && mainTabFolder} + {#if mainTabFolder.icon} + + {:else} + + {/if} {:else if tab.kind === 'file'} {:else if tab.kind === 'comments'} @@ -2262,9 +2272,9 @@ {:else} {/if} - {#if tab.kind !== 'chat' || !tabTitleEditor} + {#if tab.kind !== 'chat' || !tabTitleEditor || mainTabFolder} {tab.kind === 'chat' ? title : tabLabel(tab)}{tab.kind === 'chat' ? mainTabTitle : tabLabel(tab)} {/if} {#if tab.kind === 'comments' && commentCount}{/if} {#if tab.kind === 'chat'} - {@render tabTitleEditor?.()} + {#if !mainTabFolder}{@render tabTitleEditor?.()}{/if} {@render tabActions?.()} {:else}
diff --git a/src/lib/components/layout/Sidebar/Folders/FolderModal.svelte b/src/lib/components/layout/Sidebar/Folders/FolderModal.svelte index 045ab50f95..38f46913f7 100644 --- a/src/lib/components/layout/Sidebar/Folders/FolderModal.svelte +++ b/src/lib/components/layout/Sidebar/Folders/FolderModal.svelte @@ -9,6 +9,9 @@ import Modal from '$lib/components/common/Modal.svelte'; import AccessButton from '$lib/components/common/AccessButton.svelte'; import FolderShareModal from './FolderShareModal.svelte'; + import EmojiPicker from '$lib/components/common/EmojiPicker.svelte'; + import Emoji from '$lib/components/common/Emoji.svelte'; + import FolderIcon from '$lib/components/icons/Folder.svelte'; import XMark from '../icons/XMark.svelte'; import { toast } from 'svelte-sonner'; @@ -35,8 +38,9 @@ let folder = null; let name = ''; - let meta = { - background_image_url: null + let meta: { background_image_url: string | null; icon: string; [key: string]: unknown } = { + background_image_url: null, + icon: '' }; let data = { description: '', @@ -135,8 +139,10 @@ if (!folder) return; name = folder.name; - meta = folder.meta || { - background_image_url: null + meta = { + background_image_url: null, + icon: '', + ...folder.meta }; data = { system_prompt: '', @@ -173,7 +179,8 @@ $: if (!show && !edit) { name = ''; meta = { - background_image_url: null + background_image_url: null, + icon: '' }; data = { description: '', @@ -225,10 +232,29 @@ >{$i18n.t('Folder Name')} -
+
+ { meta = { ...meta, icon: icon ?? '' }; }} + > + + 0}
{formatUnreadCount(folders[folderId].unread_count)}
diff --git a/src/lib/components/workspace/Workspace.svelte b/src/lib/components/workspace/Workspace.svelte index 97404992b9..7b3acf5485 100644 --- a/src/lib/components/workspace/Workspace.svelte +++ b/src/lib/components/workspace/Workspace.svelte @@ -134,7 +134,7 @@ : ''} max-w-full" >
-