From 8cf761d363783ed7e15f3ff2f66579819f0df037 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 3 Dec 2026 23:56:09 +0400 Subject: [PATCH] refac --- backend/open_webui/config.py | 10 + backend/open_webui/events.py | 26 + backend/open_webui/main.py | 4 + .../versions/96798982c779_add_team_tables.py | 77 ++ backend/open_webui/models/access_grants.py | 29 +- backend/open_webui/models/folders.py | 3 +- backend/open_webui/models/teams.py | 729 ++++++++++++++++ backend/open_webui/models/users.py | 4 +- backend/open_webui/routers/auths.py | 2 + backend/open_webui/routers/channels.py | 6 + backend/open_webui/routers/search.py | 3 +- backend/open_webui/routers/teams.py | 351 ++++++++ backend/open_webui/routers/tools.py | 3 + backend/open_webui/routers/users.py | 2 + .../utils/access_control/__init__.py | 4 + src/lib/apis/teams/index.ts | 147 ++++ src/lib/components/AddMachineModal.svelte | 7 +- src/lib/components/AddToolServerModal.svelte | 2 +- .../admin/Settings/Apps/AppModal.svelte | 1 + .../admin/Settings/ExternalKnowledge.svelte | 1 + .../components/admin/Settings/Features.svelte | 8 + .../Images/ImageConnectionModal.svelte | 2 +- .../Settings/Models/RouterModelModal.svelte | 7 +- .../Videos/VideoConnectionModal.svelte | 2 +- .../admin/Users/Groups/Permissions.svelte | 39 + src/lib/components/chat/Chat.svelte | 28 +- .../chat/Placeholder/FolderPlaceholder.svelte | 33 +- src/lib/components/chat/Tabs.svelte | 13 +- .../components/chat/UserMachinesModal.svelte | 1 + src/lib/components/icons/ChatLines.svelte | 23 + src/lib/components/icons/FolderAlt.svelte | 21 + src/lib/components/icons/Tools.svelte | 36 + src/lib/components/layout/Sidebar.svelte | 119 ++- .../components/layout/Sidebar/ChatItem.svelte | 2 +- .../components/layout/Sidebar/TeamItem.svelte | 192 +++++ .../teams/AddTeamMembersModal.svelte | 75 ++ src/lib/components/teams/AddTeamMenu.svelte | 111 +++ src/lib/components/teams/Team.svelte | 800 ++++++++++++++++++ src/lib/components/teams/TeamIcon.svelte | 14 + src/lib/components/teams/TeamItemIcon.svelte | 47 + src/lib/components/teams/TeamMenu.svelte | 82 ++ src/lib/components/teams/TeamModal.svelte | 267 ++++++ src/lib/components/teams/TeamPinPicker.svelte | 130 +++ .../workspace/common/AccessControl.svelte | 113 ++- .../common/AccessControlModal.svelte | 4 +- .../workspace/common/AddAccessModal.svelte | 9 +- .../workspace/common/MemberSelector.svelte | 78 +- src/lib/constants/permissions.ts | 4 +- src/lib/i18n/locales/ar-BH/translation.json | 32 + src/lib/i18n/locales/ar/translation.json | 32 + src/lib/i18n/locales/az-AZ/translation.json | 32 + src/lib/i18n/locales/bg-BG/translation.json | 32 + src/lib/i18n/locales/bn-BD/translation.json | 32 + src/lib/i18n/locales/bo-TB/translation.json | 32 + src/lib/i18n/locales/bs-BA/translation.json | 32 + src/lib/i18n/locales/ca-ES/translation.json | 32 + src/lib/i18n/locales/ceb-PH/translation.json | 32 + src/lib/i18n/locales/cs-CZ/translation.json | 32 + src/lib/i18n/locales/da-DK/translation.json | 32 + src/lib/i18n/locales/de-DE/translation.json | 32 + src/lib/i18n/locales/dg-DG/translation.json | 32 + src/lib/i18n/locales/el-GR/translation.json | 32 + src/lib/i18n/locales/en-GB/translation.json | 32 + src/lib/i18n/locales/en-US/translation.json | 32 + src/lib/i18n/locales/es-ES/translation.json | 32 + src/lib/i18n/locales/et-EE/translation.json | 32 + src/lib/i18n/locales/eu-ES/translation.json | 32 + src/lib/i18n/locales/fa-IR/translation.json | 32 + src/lib/i18n/locales/fi-FI/translation.json | 32 + src/lib/i18n/locales/fil-PH/translation.json | 32 + src/lib/i18n/locales/fo-FO/translation.json | 32 + src/lib/i18n/locales/fr-CA/translation.json | 32 + src/lib/i18n/locales/fr-FR/translation.json | 32 + src/lib/i18n/locales/gl-ES/translation.json | 32 + src/lib/i18n/locales/he-IL/translation.json | 32 + src/lib/i18n/locales/hi-IN/translation.json | 32 + src/lib/i18n/locales/hr-HR/translation.json | 32 + src/lib/i18n/locales/hu-HU/translation.json | 32 + src/lib/i18n/locales/id-ID/translation.json | 32 + src/lib/i18n/locales/ie-GA/translation.json | 32 + src/lib/i18n/locales/it-IT/translation.json | 32 + src/lib/i18n/locales/ja-JP/translation.json | 32 + src/lib/i18n/locales/ka-GE/translation.json | 32 + src/lib/i18n/locales/kab-DZ/translation.json | 32 + src/lib/i18n/locales/ko-KR/translation.json | 32 + src/lib/i18n/locales/lt-LT/translation.json | 32 + src/lib/i18n/locales/lv-LV/translation.json | 32 + src/lib/i18n/locales/ms-MY/translation.json | 32 + src/lib/i18n/locales/nb-NO/translation.json | 32 + src/lib/i18n/locales/nl-NL/translation.json | 32 + src/lib/i18n/locales/pa-IN/translation.json | 32 + src/lib/i18n/locales/pl-PL/translation.json | 32 + src/lib/i18n/locales/pt-BR/translation.json | 32 + src/lib/i18n/locales/pt-PT/translation.json | 32 + src/lib/i18n/locales/ro-RO/translation.json | 32 + src/lib/i18n/locales/ru-RU/translation.json | 32 + src/lib/i18n/locales/sk-SK/translation.json | 32 + src/lib/i18n/locales/sl-SI/translation.json | 32 + src/lib/i18n/locales/sr-RS/translation.json | 32 + src/lib/i18n/locales/sv-SE/translation.json | 32 + src/lib/i18n/locales/ta-IN/translation.json | 32 + src/lib/i18n/locales/th-TH/translation.json | 32 + src/lib/i18n/locales/tk-TM/translation.json | 32 + src/lib/i18n/locales/tr-TR/translation.json | 32 + src/lib/i18n/locales/ug-CN/translation.json | 32 + src/lib/i18n/locales/uk-UA/translation.json | 32 + src/lib/i18n/locales/ur-PK/translation.json | 32 + .../i18n/locales/uz-Cyrl-UZ/translation.json | 32 + .../i18n/locales/uz-Latn-UZ/translation.json | 32 + src/lib/i18n/locales/vi-VN/translation.json | 32 + src/lib/i18n/locales/zh-CN/translation.json | 32 + src/lib/i18n/locales/zh-TW/translation.json | 32 + src/lib/stores/index.ts | 5 + src/routes/(app)/+layout.svelte | 9 +- src/routes/(app)/teams/[id]/+page.svelte | 1 + 115 files changed, 5680 insertions(+), 54 deletions(-) create mode 100644 backend/open_webui/migrations/versions/96798982c779_add_team_tables.py create mode 100644 backend/open_webui/models/teams.py create mode 100644 backend/open_webui/routers/teams.py create mode 100644 src/lib/apis/teams/index.ts create mode 100644 src/lib/components/icons/ChatLines.svelte create mode 100644 src/lib/components/icons/FolderAlt.svelte create mode 100644 src/lib/components/icons/Tools.svelte create mode 100644 src/lib/components/layout/Sidebar/TeamItem.svelte create mode 100644 src/lib/components/teams/AddTeamMembersModal.svelte create mode 100644 src/lib/components/teams/AddTeamMenu.svelte create mode 100644 src/lib/components/teams/Team.svelte create mode 100644 src/lib/components/teams/TeamIcon.svelte create mode 100644 src/lib/components/teams/TeamItemIcon.svelte create mode 100644 src/lib/components/teams/TeamMenu.svelte create mode 100644 src/lib/components/teams/TeamModal.svelte create mode 100644 src/lib/components/teams/TeamPinPicker.svelte create mode 100644 src/routes/(app)/teams/[id]/+page.svelte diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index bca3ee8755..c51b3c6aa5 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -1877,6 +1877,9 @@ USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_USERS = ( USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_GROUPS = ( os.getenv('USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_GROUPS', 'True').lower() == 'true' ) +USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_TEAMS = ( + os.getenv('USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_TEAMS', 'True').lower() == 'true' +) USER_PERMISSIONS_CHAT_CONTROLS = os.getenv('USER_PERMISSIONS_CHAT_CONTROLS', 'True').lower() == 'true' @@ -1957,6 +1960,8 @@ USER_PERMISSIONS_FEATURES_NOTES = os.getenv('USER_PERMISSIONS_FEATURES_NOTES', ' USER_PERMISSIONS_FEATURES_CHANNELS = os.getenv('USER_PERMISSIONS_FEATURES_CHANNELS', 'True').lower() == 'true' +USER_PERMISSIONS_FEATURES_TEAMS = os.getenv('USER_PERMISSIONS_FEATURES_TEAMS', 'False').lower() == 'true' + USER_PERMISSIONS_FEATURES_ENCRYPTED_CHANNELS = ( os.getenv('USER_PERMISSIONS_FEATURES_ENCRYPTED_CHANNELS', 'False').lower() == 'true' ) @@ -2018,6 +2023,7 @@ DEFAULT_USER_PERMISSIONS = { 'access_grants': { 'allow_users': USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_USERS, 'allow_groups': USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_GROUPS, + 'allow_teams': USER_PERMISSIONS_ACCESS_GRANTS_ALLOW_TEAMS, }, 'chat': { 'controls': USER_PERMISSIONS_CHAT_CONTROLS, @@ -2049,6 +2055,7 @@ DEFAULT_USER_PERMISSIONS = { 'notes': USER_PERMISSIONS_FEATURES_NOTES, 'folders': USER_PERMISSIONS_FEATURES_FOLDERS, 'channels': USER_PERMISSIONS_FEATURES_CHANNELS, + 'teams': USER_PERMISSIONS_FEATURES_TEAMS, 'encrypted_channels': USER_PERMISSIONS_FEATURES_ENCRYPTED_CHANNELS, # Chat features 'web_search': USER_PERMISSIONS_FEATURES_WEB_SEARCH, @@ -2099,6 +2106,8 @@ if TOOL_SANDBOX_ENGINE not in ('monty',): ENABLE_CHANNELS = os.getenv('ENABLE_CHANNELS', 'False').lower() == 'true' +ENABLE_TEAMS = os.getenv('ENABLE_TEAMS', 'False').lower() == 'true' + ENABLE_ENCRYPTED_CHANNELS = os.getenv('ENABLE_ENCRYPTED_CHANNELS', 'False').lower() == 'true' ENABLE_APPS = os.getenv('ENABLE_APPS', 'False').lower() == 'true' @@ -3291,6 +3300,7 @@ DEFAULT_CONFIG = { 'folders.enable': ENABLE_FOLDERS, 'folders.max_file_count': FOLDER_MAX_FILE_COUNT, 'channels.enable': ENABLE_CHANNELS, + 'teams.enable': ENABLE_TEAMS, '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 4921144c6f..0eda7e74ab 100644 --- a/backend/open_webui/events.py +++ b/backend/open_webui/events.py @@ -216,6 +216,32 @@ class EventDefinitions(BaseModel): GROUP_MEMBER_REMOVED: EventDefinition = EventDefinition( name='group.member_removed', description='A user was removed from a group.', message='Group member removed' ) + TEAM_CREATED: EventDefinition = EventDefinition( + name='team.created', description='A team was created.', message='Team created' + ) + TEAM_UPDATED: EventDefinition = EventDefinition( + name='team.updated', description='A team was updated.', message='Team updated' + ) + TEAM_DELETED: EventDefinition = EventDefinition( + name='team.deleted', description='A team was deleted.', message='Team deleted' + ) + TEAM_ARCHIVED: EventDefinition = EventDefinition( + name='team.archived', description='A team was archived.', message='Team archived' + ) + TEAM_RESTORED: EventDefinition = EventDefinition( + name='team.restored', description='An archived team was restored.', message='Team restored' + ) + TEAM_MEMBER_ADDED: EventDefinition = EventDefinition( + name='team.member_added', description='A user was added to a team.', message='Team member added' + ) + TEAM_MEMBER_REMOVED: EventDefinition = EventDefinition( + name='team.member_removed', description='A user was removed from a team.', message='Team member removed' + ) + TEAM_MEMBER_ROLE_UPDATED: EventDefinition = EventDefinition( + name='team.member_role_updated', + description="A team member's role was changed.", + message='Team member role updated', + ) CHAT_CREATED: EventDefinition = EventDefinition( name='chat.created', description='A chat was created.', message='Chat created' ) diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index 3bfda67d9e..0a17ea8a3a 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -183,6 +183,7 @@ from open_webui.routers import ( search, skills, tasks, + teams, tools, users, utils, @@ -865,6 +866,7 @@ app.include_router(skills.router, prefix='/api/v1/skills', tags=['skills']) 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(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']) @@ -2448,6 +2450,7 @@ async def get_app_config(request: Request): 'folders.max_file_count', 'channels.enable', 'channels.encryption.enable', + 'teams.enable', 'apps.enable', 'calendar.enable', 'automations.enable', @@ -2559,6 +2562,7 @@ async def get_app_config(request: Request): 'enable_folders': config.get('folders.enable'), 'folder_max_file_count': config.get('folders.max_file_count'), 'enable_channels': config.get('channels.enable'), + 'enable_teams': config.get('teams.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/96798982c779_add_team_tables.py b/backend/open_webui/migrations/versions/96798982c779_add_team_tables.py new file mode 100644 index 0000000000..c9f819a725 --- /dev/null +++ b/backend/open_webui/migrations/versions/96798982c779_add_team_tables.py @@ -0,0 +1,77 @@ +"""add team tables + +Revision ID: 96798982c779 +Revises: 59d393357c0c +Create Date: 2026-12-03 01:35:42 + +Teams are user-managed sets of people that items can be shared with. They are kept apart +from groups, which stay admin-only and carry permissions. A team may sit under a parent team, and may have a short +identifier (like a Jira project key) that is unique across teams. Its permissions record which actions +owners have opened to all members. A public team can be found and joined by anyone who can see its parent; a +private one only by invitation. +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = '96798982c779' +down_revision: str | None = '59d393357c0c' +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + existing_tables = set(sa.inspect(op.get_bind()).get_table_names()) + + if 'team' not in existing_tables: + op.create_table( + 'team', + sa.Column('id', sa.Text(), primary_key=True, nullable=False), + sa.Column( + 'parent_id', + sa.Text(), + sa.ForeignKey('team.id', name='fk_team_parent', ondelete='SET NULL'), + nullable=True, + ), + sa.Column('user_id', sa.Text(), nullable=False), + sa.Column('name', sa.Text(), nullable=False), + sa.Column('identifier', sa.Text(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('is_private', sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column('permissions', sa.JSON(), 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.Column('archived_at', sa.BigInteger(), nullable=True), + sa.Column('archived_by', sa.Text(), nullable=True), + sa.Column('deleted_at', sa.BigInteger(), nullable=True), + sa.Column('deleted_by', sa.Text(), nullable=True), + sa.UniqueConstraint('identifier', name='uq_team_identifier'), + ) + op.create_index('ix_team_parent_id', 'team', ['parent_id']) + + if 'team_member' not in existing_tables: + op.create_table( + 'team_member', + sa.Column('id', sa.Text(), primary_key=True, nullable=False), + sa.Column('team_id', sa.Text(), sa.ForeignKey('team.id', ondelete='CASCADE'), nullable=False), + sa.Column('user_id', sa.Text(), sa.ForeignKey('user.id', ondelete='CASCADE'), nullable=False), + sa.Column('role', sa.Text(), nullable=False, server_default='member'), + sa.Column('status', sa.Text(), nullable=True), + sa.Column('invited_at', sa.BigInteger(), nullable=True), + sa.Column('invited_by', sa.Text(), nullable=True), + sa.Column('created_at', sa.BigInteger(), nullable=False), + sa.Column('updated_at', sa.BigInteger(), nullable=False), + sa.UniqueConstraint('team_id', 'user_id', name='uq_team_member_team_user'), + ) + op.create_index('ix_team_member_user_id_team_id', 'team_member', ['user_id', 'team_id']) + + +def downgrade() -> None: + op.drop_index('ix_team_member_user_id_team_id', table_name='team_member') + op.drop_table('team_member') + op.drop_index('ix_team_parent_id', table_name='team') + op.drop_table('team') diff --git a/backend/open_webui/models/access_grants.py b/backend/open_webui/models/access_grants.py index 5d7e977249..3716b8170e 100644 --- a/backend/open_webui/models/access_grants.py +++ b/backend/open_webui/models/access_grants.py @@ -5,7 +5,7 @@ from typing import Optional from open_webui.internal.db import Base, get_async_db_context from pydantic import BaseModel, ConfigDict -from sqlalchemy import BigInteger, Column, Text, UniqueConstraint, and_, delete, or_, select +from sqlalchemy import BigInteger, Column, Text, UniqueConstraint, and_, delete, false, or_, select from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.asyncio import AsyncSession @@ -13,6 +13,7 @@ log = logging.getLogger(__name__) PRINCIPAL_TYPE_ANYONE = 'anyone' PRINCIPAL_TYPE_GROUP = 'group' +PRINCIPAL_TYPE_TEAM = 'team' PRINCIPAL_TYPE_USER = 'user' WILDCARD_PRINCIPAL_ID = '*' @@ -164,7 +165,12 @@ def normalize_access_grants(access_grants: Optional[list]) -> list[dict]: principal_id = grant.get('principal_id') permission = grant.get('permission') - if principal_type not in (PRINCIPAL_TYPE_USER, PRINCIPAL_TYPE_GROUP, PRINCIPAL_TYPE_ANYONE): + if principal_type not in ( + PRINCIPAL_TYPE_USER, + PRINCIPAL_TYPE_GROUP, + PRINCIPAL_TYPE_TEAM, + PRINCIPAL_TYPE_ANYONE, + ): continue if permission not in ('read', 'write'): continue @@ -269,6 +275,18 @@ def strip_anyone_access_grants(access_grants: Optional[list]) -> list: ] +def team_principal(user_id: Optional[str]): + """SQL condition matching grants to any team the user belongs to.""" + if not user_id: + return false() + from open_webui.models.teams import JOINED, TeamMember + + return and_( + AccessGrant.principal_type == PRINCIPAL_TYPE_TEAM, + AccessGrant.principal_id.in_(select(TeamMember.team_id).where(TeamMember.user_id == user_id, JOINED)), + ) + + def grants_to_access_control(grants: list) -> Optional[dict]: """ Convert a list of grant objects (AccessGrantModel or AccessGrantResponse) @@ -637,6 +655,7 @@ class AccessGrantsTable: AccessGrant.principal_id.in_(user_group_ids), ) ) + conditions.append(team_principal(user_id)) result = await db.execute( select(AccessGrant.resource_id) @@ -689,11 +708,13 @@ class AccessGrantsTable: ) -> set[str]: """Get user IDs with the specified permission, including public and group grants.""" from open_webui.models.groups import Groups + from open_webui.models.teams import Teams from open_webui.models.users import Users async with get_async_db_context(db) as db: user_ids = set() group_ids = [] + team_ids = [] for grant in access_grants: if grant.permission != permission: continue @@ -704,11 +725,14 @@ class AccessGrantsTable: user_ids.add(grant.principal_id) elif grant.principal_type == PRINCIPAL_TYPE_GROUP: group_ids.append(grant.principal_id) + elif grant.principal_type == PRINCIPAL_TYPE_TEAM: + team_ids.append(grant.principal_id) if group_ids: group_user_ids = await Groups.get_group_user_ids_by_ids(group_ids, db=db, include_inherited=True) for members in group_user_ids.values(): user_ids.update(members) + user_ids.update(await Teams.get_user_ids_by_team_ids(team_ids, db=db)) return user_ids async def get_revoked_user_ids_by_resource( @@ -751,6 +775,7 @@ class AccessGrantsTable: AccessGrant.principal_id.in_(['*', user_id] if user_id else ['*']), ), and_(AccessGrant.principal_type == 'group', AccessGrant.principal_id.in_(user_group_ids or ())), + team_principal(user_id), ), ) .correlate_except(AccessGrant) diff --git a/backend/open_webui/models/folders.py b/backend/open_webui/models/folders.py index a5be251b90..c238d5f9f4 100644 --- a/backend/open_webui/models/folders.py +++ b/backend/open_webui/models/folders.py @@ -184,7 +184,7 @@ class FolderTable: Returns {folder_id: highest_permission} for folders shared with or by user. Checks direct user grants, group grants, and public (user:*) grants. """ - from open_webui.models.access_grants import AccessGrant + from open_webui.models.access_grants import AccessGrant, team_principal async with get_async_db_context(db) as db: conditions = [ @@ -196,6 +196,7 @@ class FolderTable: conditions.append( and_(AccessGrant.principal_type == 'group', AccessGrant.principal_id.in_(user_group_ids)) ) + conditions.append(team_principal(user_id)) result = await db.execute( select(AccessGrant).filter( AccessGrant.resource_type == 'folder', diff --git a/backend/open_webui/models/teams.py b/backend/open_webui/models/teams.py new file mode 100644 index 0000000000..2580a73aa4 --- /dev/null +++ b/backend/open_webui/models/teams.py @@ -0,0 +1,729 @@ +import re +import time +import uuid +from typing import Literal, Optional + +from open_webui.internal.db import Base, get_async_db_context +from open_webui.models.access_grants import AccessGrant +from open_webui.models.groups import refresh_group_sessions +from open_webui.models.users import User +from pydantic import BaseModel, ConfigDict, field_validator +from sqlalchemy import ( + JSON, + BigInteger, + Boolean, + Column, + ForeignKey, + Index, + Text, + UniqueConstraint, + delete, + func, + or_, + select, + update, +) +from sqlalchemy.ext.asyncio import AsyncSession + +# Team DB Schema + + +class Team(Base): + __tablename__ = 'team' + + id = Column(Text, primary_key=True) + parent_id = Column( + Text, ForeignKey('team.id', name='fk_team_parent', ondelete='SET NULL'), nullable=True, index=True + ) + user_id = Column(Text, nullable=False) + + name = Column(Text, nullable=False) + # A short key like OWUI, unique across teams (see IDENTIFIER_PATTERN). + identifier = Column(Text, nullable=True, unique=True) + description = Column(Text, nullable=True) + + # A private team is invite-only; a public one can be found and joined (see is_visible). + is_private = Column(Boolean, nullable=False, default=True) + # The lowest team role allowed for each action owners can open to members (TeamPermissions). + permissions = Column(JSON, nullable=True) + data = Column(JSON, nullable=True) + meta = Column(JSON, nullable=True) + + created_at = Column(BigInteger, nullable=False) + updated_at = Column(BigInteger, nullable=False) + + # An archived team is read-only and hidden from team lists until restored. + archived_at = Column(BigInteger, nullable=True) + archived_by = Column(Text, nullable=True) + + # Deletes are immediate for now; these are set once deleted teams get a grace period. + deleted_at = Column(BigInteger, nullable=True) + deleted_by = Column(Text, nullable=True) + + +class TeamModel(BaseModel): + id: str + parent_id: Optional[str] = None + user_id: str + + name: str + identifier: Optional[str] = None + description: Optional[str] = None + + is_private: bool = True + permissions: Optional[dict] = None + data: Optional[dict] = None + meta: Optional[dict] = None + + created_at: int # timestamp in epoch + updated_at: int # timestamp in epoch + + archived_at: Optional[int] = None + archived_by: Optional[str] = None + deleted_at: Optional[int] = None + deleted_by: Optional[str] = None + + model_config = ConfigDict(from_attributes=True) + + +class TeamMember(Base): + __tablename__ = 'team_member' + __table_args__ = ( + UniqueConstraint('team_id', 'user_id', name='uq_team_member_team_user'), + Index('ix_team_member_user_id_team_id', 'user_id', 'team_id'), + ) + + id = Column(Text, primary_key=True) + team_id = Column(Text, ForeignKey('team.id', ondelete='CASCADE'), nullable=False) + user_id = Column(Text, nullable=False) + role = Column(Text, nullable=False, default='member') + # 'joined' or 'invited', as on channel_member. Every write sets 'joined'; there is no invite flow yet. + status = Column(Text, nullable=True, default='joined') + invited_at = Column(BigInteger, nullable=True) + invited_by = Column(Text, nullable=True) + created_at = Column(BigInteger, nullable=False) + updated_at = Column(BigInteger, nullable=False) + + +class TeamMemberModel(BaseModel): + id: str + team_id: str + user_id: str + role: str + status: Optional[str] = None + invited_at: Optional[int] = None + invited_by: Optional[str] = None + created_at: int + updated_at: int + + model_config = ConfigDict(from_attributes=True) + + +# Invited rows never count: not for access, roles, lists or counts. +JOINED = or_(TeamMember.status.is_(None), TeamMember.status != 'invited') + +# Forms + +TeamRole = Literal['member', 'owner'] + +# What can be pinned to a team's Overview: the kinds of item that can be shared with a team. +PIN_TYPES = ('folder', 'model', 'knowledge', 'prompt', 'tool', 'skill') + + +class TeamPermissions(BaseModel): + """What owners may open to all members, each set to the lowest team role allowed, as Linear's team + securitySettings are. Unset means owners only; archiving, deleting, moving and roles stay with owners.""" + + manage_team: Optional[TeamRole] = None + manage_pins: Optional[TeamRole] = None + manage_members: Optional[TeamRole] = None + + +def team_permission(team: TeamModel, permission: str) -> TeamRole: + return (team.permissions or {}).get(permission) or 'owner' + + +# Linear doesn't publish its team identifier rules, so these follow Jira's project keys: an uppercase +# letter, then uppercase letters, digits or underscores, 2 to 10 characters in all. +IDENTIFIER_PATTERN = re.compile(r'[A-Z][A-Z0-9_]{1,9}') + + +class TeamForm(BaseModel): + name: str + identifier: Optional[str] = None + description: Optional[str] = None + parent_id: Optional[str] = None + is_private: Optional[bool] = None + # Updates change only the permissions sent; the others keep their value. + permissions: Optional[TeamPermissions] = None + data: Optional[dict] = None + meta: Optional[dict] = None + + @field_validator('name') + @classmethod + def validate_name(cls, name: str) -> str: + name = name.strip() + if not name: + raise ValueError('Team name cannot be empty.') + return name + + @field_validator('identifier') + @classmethod + def validate_identifier(cls, identifier: Optional[str]) -> Optional[str]: + # The format is checked with uniqueness (check_identifier), so both errors read as plain messages. + return (identifier or '').strip().upper() or None + + @field_validator('data') + @classmethod + def validate_data(cls, data: Optional[dict]) -> Optional[dict]: + # Team settings; for now only the Overview's pins, as an ordered list of {type, id}. + if data is None: + return None + pinned, seen = [], set() + for pin in data.get('pinned') or []: + if not isinstance(pin, dict) or pin.get('type') not in PIN_TYPES or not isinstance(pin.get('id'), str): + continue + key = (pin['type'], pin['id']) + if key not in seen: + seen.add(key) + pinned.append({'type': pin['type'], 'id': pin['id']}) + return {'pinned': pinned} + + @field_validator('meta') + @classmethod + def validate_meta(cls, meta: Optional[dict]) -> Optional[dict]: + # Only the icon is stored; anything else a client sends is dropped. + if meta is None: + return None + icon = meta.get('icon') + return {'icon': icon if isinstance(icon, str) and icon else None} + + +class TeamResponse(TeamModel): + member_count: int = 0 + # The caller's role: 'owner' also when they own an ancestor team; None when they are not a member. + role: Optional[str] = None + + +class TeamInfoResponse(BaseModel): + id: str + name: str + meta: Optional[dict] = None + + +class TeamMemberUserResponse(BaseModel): + id: str + name: str + email: str + role: str + + +class TeamMemberListResponse(BaseModel): + items: list[TeamMemberUserResponse] = [] + total: int = 0 + + +class TeamMembershipError(ValueError): + pass + + +def member_count(): + return ( + select(func.count(TeamMember.id)) + .where(TeamMember.team_id == Team.id, JOINED) + .correlate(Team) + .scalar_subquery() + .label('member_count') + ) + + +def ancestor_teams(team_ids): + """These teams and every team above them. UNION also terminates on externally introduced cycles.""" + chain = select(Team.id.label('team_id')).where(Team.id.in_(team_ids)).cte(recursive=True) + return chain.union(select(Team.parent_id).join(chain, Team.id == chain.c.team_id).where(Team.parent_id.isnot(None))) + + +def descendant_teams(team_ids): + """These teams and every team below them.""" + chain = select(Team.id.label('team_id')).where(Team.id.in_(team_ids)).cte(recursive=True) + return chain.union(select(Team.id).join(chain, Team.parent_id == chain.c.team_id)) + + +async def check_owner_remains( + db, team_id: str, removed: frozenset[str] = frozenset(), demoted: frozenset[str] = frozenset() +) -> None: + """Raise before writing when this would leave a top-level team without an owner. + A sub-team is owned through its parent, so it may have no owner of its own.""" + team = await db.get(Team, team_id) + if team is None or team.parent_id: + return + rows = ( + await db.execute(select(TeamMember.user_id, TeamMember.role).where(TeamMember.team_id == team_id, JOINED)) + ).all() + if not any(role == 'owner' and user_id not in removed | demoted for user_id, role in rows): + raise TeamMembershipError('A team needs at least one owner. Make someone else an owner first.') + + +async def add_to_teams(db, team_ids, user_ids: set[str], now: int, role: str = 'member') -> set[str]: + """Add users to these teams where they are missing. Returns the users added anywhere.""" + if not user_ids: + return set() + team_ids = list(team_ids) + rows = ( + await db.execute( + select(TeamMember.team_id, TeamMember.user_id, TeamMember.status).where( + TeamMember.team_id.in_(team_ids), TeamMember.user_id.in_(user_ids) + ) + ) + ).all() + existing = {(tid, uid) for tid, uid, _ in rows} + invited = [(tid, uid) for tid, uid, status in rows if status == 'invited'] + for tid, uid in invited: + await db.execute( + update(TeamMember) + .where(TeamMember.team_id == tid, TeamMember.user_id == uid) + .values(status='joined', updated_at=now) + ) + missing = [(tid, uid) for tid in team_ids for uid in user_ids if (tid, uid) not in existing] + db.add_all( + [ + TeamMember( + id=str(uuid.uuid4()), + team_id=tid, + user_id=uid, + role=role, + status='joined', + created_at=now, + updated_at=now, + ) + for tid, uid in missing + ] + ) + changed = missing + invited + if changed: + await db.execute(update(Team).where(Team.id.in_({tid for tid, _ in changed})).values(updated_at=now)) + return {uid for _, uid in changed} + + +async def team_chain_ids(db, team_id: str) -> list[str]: + chain = ancestor_teams([team_id]) + return list((await db.execute(select(chain.c.team_id))).scalars()) + + +def is_visible(team, teams_by_id: dict, member_team_ids: set[str]) -> bool: + """Members see their team. Others see it while it and every team above it, up to one they are in, is public + and active: a private team hides everything inside it.""" + while team is not None: + if team.id in member_team_ids: + return True + if team.is_private or team.archived_at: + return False + team = teams_by_id.get(team.parent_id) + return True + + +async def check_identifier(db, identifier: Optional[str], team_id: Optional[str] = None) -> None: + if identifier is None: + return + if not IDENTIFIER_PATTERN.fullmatch(identifier): + raise TeamMembershipError('An identifier starts with a letter and has 2 to 10 letters, digits or underscores.') + taken = select(Team.id).where(Team.identifier == identifier) + if team_id: + taken = taken.where(Team.id != team_id) + if (await db.execute(taken.limit(1))).first(): + raise TeamMembershipError(f'Another team already uses the identifier {identifier}.') + + +class TeamsTable: + async def insert_new_team(self, user_id: str, form_data: TeamForm, db: Optional[AsyncSession] = None) -> TeamModel: + """Create a team owned by its creator. Under a parent, the creator also joins every ancestor.""" + now = int(time.time()) + async with get_async_db_context(db) as db: + if form_data.parent_id and not await db.get(Team, form_data.parent_id): + raise TeamMembershipError('Parent team not found.') + await check_identifier(db, form_data.identifier) + team = Team( + id=str(uuid.uuid4()), + parent_id=form_data.parent_id, + user_id=user_id, + name=form_data.name, + identifier=form_data.identifier, + description=form_data.description, + is_private=form_data.is_private is not False, + permissions=form_data.permissions.model_dump(exclude_unset=True) if form_data.permissions else None, + data=form_data.data, + meta=form_data.meta, + created_at=now, + updated_at=now, + ) + db.add(team) + await db.flush() + await add_to_teams(db, [team.id], {user_id}, now, role='owner') + joined = ( + await add_to_teams(db, await team_chain_ids(db, form_data.parent_id), {user_id}, now) + if form_data.parent_id + else set() + ) + await db.commit() + await db.refresh(team) + result = TeamModel.model_validate(team) + await refresh_group_sessions(joined) + return result + + async def get_team_by_id(self, id: str, db: Optional[AsyncSession] = None) -> Optional[TeamModel]: + async with get_async_db_context(db) as db: + team = await db.get(Team, id) + return TeamModel.model_validate(team) if team else None + + async def is_team_owner(self, team_id: str, user_id: str, db: Optional[AsyncSession] = None) -> bool: + """Owners of a team are its own owners and the owners of every team above it.""" + async with get_async_db_context(db) as db: + chain = ancestor_teams([team_id]) + return ( + await db.execute( + select(TeamMember.id) + .where( + TeamMember.user_id == user_id, + TeamMember.role == 'owner', + JOINED, + TeamMember.team_id.in_(select(chain.c.team_id)), + ) + .limit(1) + ) + ).first() is not None + + async def get_team_response( + self, id: str, user_id: str, db: Optional[AsyncSession] = None + ) -> Optional[TeamResponse]: + async with get_async_db_context(db) as db: + role = select(TeamMember.role).where(TeamMember.team_id == Team.id, TeamMember.user_id == user_id, JOINED) + row = ( + await db.execute( + select(Team, member_count(), role.correlate(Team).scalar_subquery()).where(Team.id == id) + ) + ).first() + if not row: + return None + team, count, member_role = row + if member_role != 'owner' and await self.is_team_owner(id, user_id, db=db): + member_role = 'owner' + return TeamResponse(**TeamModel.model_validate(team).model_dump(), member_count=count, role=member_role) + + async def get_teams_by_member_id( + self, user_id: str, db: Optional[AsyncSession] = None, *, archived: bool = False + ) -> list[TeamResponse]: + """The user's teams: active ones, or only archived ones with archived=True.""" + async with get_async_db_context(db) as db: + owned = descendant_teams( + select(TeamMember.team_id).where(TeamMember.user_id == user_id, TeamMember.role == 'owner', JOINED) + ) + owned_ids = set((await db.execute(select(owned.c.team_id))).scalars()) + rows = await db.execute( + select(Team, member_count(), TeamMember.role) + .join(TeamMember, TeamMember.team_id == Team.id) + .where( + TeamMember.user_id == user_id, + JOINED, + Team.archived_at.isnot(None) if archived else Team.archived_at.is_(None), + ) + .order_by(func.lower(Team.name), Team.id) + ) + return [ + TeamResponse( + **TeamModel.model_validate(team).model_dump(), + member_count=count, + role='owner' if team.id in owned_ids else role, + ) + for team, count, role in rows + ] + + async def get_sub_teams(self, id: str, db: Optional[AsyncSession] = None) -> list[TeamResponse]: + async with get_async_db_context(db) as db: + rows = await db.execute( + select(Team, member_count()) + .where(Team.parent_id == id, Team.archived_at.is_(None)) + .order_by(func.lower(Team.name), Team.id) + ) + return [ + TeamResponse(**TeamModel.model_validate(team).model_dump(), member_count=count) for team, count in rows + ] + + async def can_see_team(self, team_id: str, user_id: str, db: Optional[AsyncSession] = None) -> bool: + async with get_async_db_context(db) as db: + chain = ancestor_teams([team_id]) + teams_by_id = { + team.id: team + for team in (await db.execute(select(Team).where(Team.id.in_(select(chain.c.team_id))))).scalars() + } + if team_id not in teams_by_id: + return False + member_team_ids = await self.get_team_ids_by_member_id(user_id, db=db) + return is_visible(teams_by_id[team_id], teams_by_id, member_team_ids) + + async def get_joinable_teams(self, user_id: str, db: Optional[AsyncSession] = None) -> list[TeamResponse]: + """Active teams the user can see but is not in, to browse and join.""" + async with get_async_db_context(db) as db: + rows = ( + await db.execute( + select(Team, member_count()) + .where(Team.archived_at.is_(None)) + .order_by(func.lower(Team.name), Team.id) + ) + ).all() + teams_by_id = {team.id: team for team, _ in rows} + member_team_ids = await self.get_team_ids_by_member_id(user_id, db=db) + return [ + TeamResponse(**TeamModel.model_validate(team).model_dump(), member_count=count) + for team, count in rows + if team.id not in member_team_ids and is_visible(team, teams_by_id, member_team_ids) + ] + + async def get_team_ids_by_member_id(self, user_id: str, db: Optional[AsyncSession] = None) -> set[str]: + async with get_async_db_context(db) as db: + return set( + (await db.execute(select(TeamMember.team_id).where(TeamMember.user_id == user_id, JOINED))) + .scalars() + .all() + ) + + async def get_user_ids_by_team_ids(self, team_ids: list[str], db: Optional[AsyncSession] = None) -> set[str]: + if not team_ids: + return set() + async with get_async_db_context(db) as db: + return set( + (await db.execute(select(TeamMember.user_id).where(TeamMember.team_id.in_(team_ids), JOINED))) + .scalars() + .all() + ) + + async def get_team_members( + self, + team_id: str, + query: str = '', + page: int = 1, + db: Optional[AsyncSession] = None, + ) -> TeamMemberListResponse: + async with get_async_db_context(db) as db: + stmt = select(User.id, User.name, User.email, TeamMember.role).join( + TeamMember, TeamMember.user_id == User.id + ) + stmt = stmt.where(TeamMember.team_id == team_id, JOINED) + if query: + stmt = stmt.where(or_(User.name.ilike(f'%{query}%'), User.email.ilike(f'%{query}%'))) + total = (await db.execute(select(func.count()).select_from(stmt.subquery()))).scalar_one() + rows = await db.execute( + stmt.order_by((TeamMember.role == 'owner').desc(), User.name, User.id).offset((page - 1) * 30).limit(30) + ) + return TeamMemberListResponse( + items=[ + TeamMemberUserResponse(id=id, name=name, email=email, role=role) for id, name, email, role in rows + ], + total=total, + ) + + async def add_members(self, team_id: str, user_ids: list[str], db: Optional[AsyncSession] = None) -> list[str]: + """Add existing, non-pending users to this team and to every team above it they are not in. + Returns the IDs newly added to this team.""" + now = int(time.time()) + async with get_async_db_context(db) as db: + valid = set( + (await db.execute(select(User.id).where(User.id.in_(user_ids or []), User.role != 'pending'))).scalars() + ) + previous = set( + (await db.execute(select(TeamMember.user_id).where(TeamMember.team_id == team_id, JOINED))).scalars() + ) + joined = await add_to_teams(db, await team_chain_ids(db, team_id), valid, now) + await db.commit() + await refresh_group_sessions(joined) + return sorted(valid - previous) + + async def remove_members(self, team_id: str, user_ids: list[str], db: Optional[AsyncSession] = None) -> list[str]: + """Remove members from this team and every team below it. Returns the IDs removed from this team.""" + async with get_async_db_context(db) as db: + removed = list( + ( + await db.execute( + select(TeamMember.user_id).where( + TeamMember.team_id == team_id, TeamMember.user_id.in_(user_ids or []) + ) + ) + ).scalars() + ) + await check_owner_remains(db, team_id, removed=frozenset(removed)) + below = descendant_teams([team_id]) + await db.execute( + delete(TeamMember).where( + TeamMember.team_id.in_(select(below.c.team_id)), TeamMember.user_id.in_(removed) + ) + ) + await db.execute(update(Team).where(Team.id == team_id).values(updated_at=int(time.time()))) + await db.commit() + await refresh_group_sessions(removed) + return removed + + async def set_member_role( + self, team_id: str, user_ids: list[str], role: TeamRole, db: Optional[AsyncSession] = None + ) -> list[str]: + """Change the role of existing members. Returns the IDs whose role changed.""" + now = int(time.time()) + async with get_async_db_context(db) as db: + members = ( + ( + await db.execute( + select(TeamMember).where( + TeamMember.team_id == team_id, + TeamMember.user_id.in_(user_ids or []), + TeamMember.role != role, + ) + ) + ) + .scalars() + .all() + ) + if role == 'member': + await check_owner_remains(db, team_id, demoted=frozenset(member.user_id for member in members)) + for member in members: + member.role = role + member.updated_at = now + await db.execute(update(Team).where(Team.id == team_id).values(updated_at=now)) + await db.commit() + return [member.user_id for member in members] + + async def update_team_by_id( + self, id: str, form_data: TeamForm, db: Optional[AsyncSession] = None + ) -> Optional[TeamModel]: + """Update a team. A new parent must not sit below it; its members join the parent's teams.""" + now = int(time.time()) + joined = set() + async with get_async_db_context(db) as db: + team = await db.get(Team, id) + if team is None: + return None + fields = form_data.model_fields_set + if 'parent_id' in fields and form_data.parent_id != team.parent_id: + parent_id = form_data.parent_id + if parent_id: + if not await db.get(Team, parent_id): + raise TeamMembershipError('Parent team not found.') + below = descendant_teams([id]) + if (await db.execute(select(below.c.team_id).where(below.c.team_id == parent_id))).first(): + raise TeamMembershipError('A team cannot be placed under itself or one of its sub-teams.') + members = set( + (await db.execute(select(TeamMember.user_id).where(TeamMember.team_id == id, JOINED))).scalars() + ) + joined = await add_to_teams(db, await team_chain_ids(db, parent_id), members, now) + else: + owner = ( + await db.execute( + select(TeamMember.id) + .where(TeamMember.team_id == id, TeamMember.role == 'owner', JOINED) + .limit(1) + ) + ).first() + if owner is None: + raise TeamMembershipError('Make someone an owner of this team before moving it to the top.') + team.parent_id = parent_id + team.name = form_data.name + if 'identifier' in fields and form_data.identifier != team.identifier: + await check_identifier(db, form_data.identifier, id) + team.identifier = form_data.identifier + team.description = form_data.description + if form_data.is_private is not None: + team.is_private = form_data.is_private + if form_data.permissions is not None: + team.permissions = { + **(team.permissions or {}), + **form_data.permissions.model_dump(exclude_unset=True), + } + if 'data' in fields: + team.data = form_data.data + if form_data.meta is not None: + team.meta = form_data.meta + team.updated_at = now + await db.commit() + await db.refresh(team) + result = TeamModel.model_validate(team) + await refresh_group_sessions(joined) + return result + + async def set_archived( + self, id: str, archived_by: Optional[str], db: Optional[AsyncSession] = None + ) -> Optional[TeamModel]: + """Archive a team (archived_by set) or restore it (None). As in Linear, sub-teams are archived + before their parent, and a parent is restored before its sub-teams.""" + async with get_async_db_context(db) as db: + team = await db.get(Team, id) + if team is None: + return None + if archived_by: + active_child = ( + await db.execute(select(Team.id).where(Team.parent_id == id, Team.archived_at.is_(None)).limit(1)) + ).first() + if active_child: + raise TeamMembershipError('Archive its sub-teams first.') + elif team.parent_id: + parent = await db.get(Team, team.parent_id) + if parent is not None and parent.archived_at: + raise TeamMembershipError('Restore its parent team first.') + now = int(time.time()) + team.archived_at = now if archived_by else None + team.archived_by = archived_by + team.updated_at = now + await db.commit() + await db.refresh(team) + return TeamModel.model_validate(team) + + async def delete_team_by_id(self, id: str, db: Optional[AsyncSession] = None) -> bool: + """Delete a team; its sub-teams move up to its parent. Sub-teams that become top-level teams + keep their owners: the deleted team's owners, who owned them through it, become their owners.""" + now = int(time.time()) + async with get_async_db_context(db) as db: + team = await db.get(Team, id) + if team is None: + return False + members = list( + (await db.execute(select(TeamMember.user_id).where(TeamMember.team_id == id, JOINED))).scalars() + ) + children = list((await db.execute(select(Team.id).where(Team.parent_id == id))).scalars()) + if children and team.parent_id is None: + owners = set( + ( + await db.execute( + select(TeamMember.user_id).where( + TeamMember.team_id == id, TeamMember.role == 'owner', JOINED + ) + ) + ).scalars() + ) + owned = set( + ( + await db.execute( + select(TeamMember.team_id).where( + TeamMember.team_id.in_(children), TeamMember.role == 'owner', JOINED + ) + ) + ).scalars() + ) + for child_id in set(children) - owned: + await db.execute( + update(TeamMember) + .where(TeamMember.team_id == child_id, TeamMember.user_id.in_(owners)) + .values(role='owner', updated_at=now) + ) + await add_to_teams(db, [child_id], owners, now, role='owner') + await db.execute(update(Team).where(Team.parent_id == id).values(parent_id=team.parent_id, updated_at=now)) + await db.execute(delete(AccessGrant).filter_by(principal_type='team', principal_id=id)) + await db.execute(delete(TeamMember).where(TeamMember.team_id == id)) + await db.execute(delete(Team).where(Team.id == id)) + await db.commit() + await refresh_group_sessions(members) + return True + + async def remove_user_from_all_teams(self, user_id: str, db: Optional[AsyncSession] = None) -> None: + # Unlike leaving, deleting a user may leave a team without an owner; admins act as owners. + async with get_async_db_context(db) as db: + await db.execute(delete(TeamMember).where(TeamMember.user_id == user_id)) + await db.commit() + + +Teams = TeamsTable() diff --git a/backend/open_webui/models/users.py b/backend/open_webui/models/users.py index 37d0549266..644544eac8 100644 --- a/backend/open_webui/models/users.py +++ b/backend/open_webui/models/users.py @@ -872,9 +872,11 @@ class UsersTable: async def delete_user_by_id(self, id: str, db: AsyncSession | None = None) -> bool: from open_webui.models.chats import Chats from open_webui.models.groups import Groups + from open_webui.models.teams import Teams - # Remove User from Groups + # Remove User from Groups and Teams await Groups.remove_user_from_all_groups(id) + await Teams.remove_user_from_all_teams(id) # Delete User Chats async with get_async_db_context(db) as session: diff --git a/backend/open_webui/routers/auths.py b/backend/open_webui/routers/auths.py index 3c60f23792..c1feebb062 100644 --- a/backend/open_webui/routers/auths.py +++ b/backend/open_webui/routers/auths.py @@ -135,6 +135,7 @@ ADMIN_CONFIG_KEYS = { 'ENABLE_AUTOMATIONS': 'automations.enable', 'ENABLE_AUTOMATION_WEBHOOKS': 'automations.webhooks.enable', 'ENABLE_CHANNELS': 'channels.enable', + 'ENABLE_TEAMS': 'teams.enable', 'ENABLE_COMMENTS': 'comments.enable', 'ENABLE_NOTIFICATIONS': 'notifications.enable', 'ENABLE_ENCRYPTED_CHANNELS': 'channels.encryption.enable', @@ -1194,6 +1195,7 @@ class AdminConfig(MfaConfigForm): ENABLE_AUTOMATIONS: bool ENABLE_AUTOMATION_WEBHOOKS: bool = True ENABLE_CHANNELS: bool + ENABLE_TEAMS: bool = False ENABLE_COMMENTS: bool = False ENABLE_NOTIFICATIONS: bool = True ENABLE_ENCRYPTED_CHANNELS: bool = False diff --git a/backend/open_webui/routers/channels.py b/backend/open_webui/routers/channels.py index 8c9530a740..58d1b85dba 100644 --- a/backend/open_webui/routers/channels.py +++ b/backend/open_webui/routers/channels.py @@ -25,6 +25,7 @@ from open_webui.models.channels import ( ) from open_webui.models.config import Config from open_webui.models.groups import Groups +from open_webui.models.teams import Teams from open_webui.models.messages import ( Message, MessageForm, @@ -116,18 +117,22 @@ def get_channel_permitted_group_and_user_ids( user_ids = [] group_ids = [] + team_ids = [] for grant in channel.access_grants: if grant.permission != permission: continue if grant.principal_type == 'group': group_ids.append(grant.principal_id) + elif grant.principal_type == 'team': + team_ids.append(grant.principal_id) elif grant.principal_type == 'user' and grant.principal_id != '*': user_ids.append(grant.principal_id) return { 'user_ids': list(dict.fromkeys(user_ids)), 'group_ids': list(dict.fromkeys(group_ids)), + 'team_ids': list(dict.fromkeys(team_ids)), } @@ -144,6 +149,7 @@ async def get_channel_member_user_ids( if group_ids: for member_ids in (await Groups.get_group_user_ids_by_ids(group_ids, db=db, include_inherited=True)).values(): user_ids.extend(member_ids) + user_ids.extend(await Teams.get_user_ids_by_team_ids(permitted_ids.get('team_ids') or [], db=db)) return list(dict.fromkeys([*user_ids, channel.user_id])) diff --git a/backend/open_webui/routers/search.py b/backend/open_webui/routers/search.py index 4cb6632014..1500f4c6d0 100644 --- a/backend/open_webui/routers/search.py +++ b/backend/open_webui/routers/search.py @@ -6,7 +6,7 @@ from urllib.parse import urlencode from fastapi import APIRouter, Depends, Query from open_webui.internal.db import get_async_session, strip_nul_from_json -from open_webui.models.access_grants import AccessGrant, AccessGrants +from open_webui.models.access_grants import AccessGrant, AccessGrants, team_principal from open_webui.models.channels import ChannelMember, Channels from open_webui.models.chat_messages import ChatMessage from open_webui.models.chats import Chat, chat_message_list, chat_search_content_query @@ -137,6 +137,7 @@ async def search_workspace( # noqa: C901 — keep permission scoping and source principal = or_( and_(AccessGrant.principal_type == 'user', AccessGrant.principal_id == user.id), and_(AccessGrant.principal_type == 'group', AccessGrant.principal_id.in_(groups)), + team_principal(user.id), ) def granted(resource, resource_id, public=False): diff --git a/backend/open_webui/routers/teams.py b/backend/open_webui/routers/teams.py new file mode 100644 index 0000000000..fa41eebeab --- /dev/null +++ b/backend/open_webui/routers/teams.py @@ -0,0 +1,351 @@ +import logging +from typing import 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_session +from open_webui.models.access_grants import AccessGrant +from open_webui.models.config import Config +from open_webui.models.folders import Folder +from open_webui.models.knowledge import Knowledge +from open_webui.models.models import Model +from open_webui.models.prompts import Prompt +from open_webui.models.skills import Skill +from open_webui.models.teams import ( + TeamForm, + TeamInfoResponse, + TeamMemberListResponse, + TeamMembershipError, + TeamResponse, + TeamRole, + Teams, + team_permission, +) +from open_webui.models.tools import Tool +from open_webui.utils.access_control import has_permission +from open_webui.utils.auth import get_verified_user +from pydantic import BaseModel +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +log = logging.getLogger(__name__) + +router = APIRouter() + + +async def check_teams_enabled(): + if not await Config.get('teams.enable'): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + + +async def require_team( + id: str, + user, + db, + *, + owner: bool = False, + permission: Optional[str] = None, + visible: bool = False, + writable: bool = False, +) -> TeamResponse: + """Return the team for a member or owner; owners of a parent team and admins act as owners. + A permission (TeamPermissions) takes an owner unless the owners opened it to all members. + With visible, anyone who can see the team (a public one) gets it too. Others get a 404.""" + team = await Teams.get_team_response(id, user.id, db=db) + if team is not None and permission: + owner = team_permission(team, permission) == 'owner' + allowed = team is not None and (user.role == 'admin' or (team.role == 'owner' if owner else team.role is not None)) + if not allowed and visible and team is not None and not owner: + allowed = await Teams.can_see_team(id, user.id, db=db) + if not allowed: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + if writable and team.archived_at: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail='This team is archived. Restore it to make changes.' + ) + return team + + +async def require_parent_owner(parent_id: Optional[str], user, db) -> None: + """Placing a team under a parent takes owning that parent too.""" + if parent_id: + await require_team(parent_id, user, db, owner=True, writable=True) + + +class UserIdsForm(BaseModel): + user_ids: list[str] = [] + + +class MemberRoleForm(UserIdsForm): + role: TeamRole + + +@router.get('/', response_model=list[TeamResponse], dependencies=[Depends(check_teams_enabled)]) +async def get_teams( + archived: bool = False, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + return await Teams.get_teams_by_member_id(user.id, db=db, archived=archived) + + +@router.post('/create', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def create_team( + request: Request, + form_data: TeamForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + if user.role != 'admin' and not await has_permission( + user.id, 'features.teams', await Config.get('user.permissions'), db=db + ): + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.UNAUTHORIZED) + + await require_parent_owner(form_data.parent_id, user, db) + try: + team = await Teams.insert_new_team(user.id, form_data, db=db) + except TeamMembershipError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e + await publish_event(request, EVENTS.TEAM_CREATED, actor=user, subject_id=team.id, data={'name': team.name}) + return await Teams.get_team_response(team.id, user.id, db=db) + + +@router.get('/joinable', response_model=list[TeamResponse], dependencies=[Depends(check_teams_enabled)]) +async def get_joinable_teams(user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + return await Teams.get_joinable_teams(user.id, db=db) + + +@router.get('/id/{id}', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def get_team_by_id(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + return await require_team(id, user, db, visible=True) + + +@router.get('/id/{id}/info', response_model=TeamInfoResponse, dependencies=[Depends(check_teams_enabled)]) +async def get_team_info_by_id(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + team = await Teams.get_team_by_id(id, db=db) + if not team: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND) + return TeamInfoResponse(id=team.id, name=team.name, meta=team.meta) + + +@router.get('/id/{id}/members', response_model=TeamMemberListResponse, dependencies=[Depends(check_teams_enabled)]) +async def get_team_members( + id: str, + query: str = '', + page: int = Query(default=1, ge=1), + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + await require_team(id, user, db, visible=True) + return await Teams.get_team_members(id, query=query, page=page, db=db) + + +# What is shared with a team, by resource type: (table, extra columns returned with id and name). +TEAM_ITEM_TYPES = { + 'folder': (Folder, {'icon': lambda row: (row.meta or {}).get('icon')}), + 'model': (Model, {'profile_image_url': lambda row: (row.meta or {}).get('profile_image_url')}), + 'knowledge': (Knowledge, {}), + 'prompt': (Prompt, {'command': lambda row: row.command}), + 'tool': (Tool, {}), + 'skill': (Skill, {}), +} + + +@router.get('/id/{id}/items', dependencies=[Depends(check_teams_enabled)]) +async def get_team_items(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)): + await require_team(id, user, db) + grants = ( + await db.execute( + select(AccessGrant.resource_type, AccessGrant.resource_id) + .where(AccessGrant.principal_type == 'team', AccessGrant.principal_id == id) + .distinct() + ) + ).all() + + items = {} + for resource_type, (table, extra) in TEAM_ITEM_TYPES.items(): + ids = [resource_id for grant_type, resource_id in grants if grant_type == resource_type] + rows = ( + (await db.execute(select(table).where(table.id.in_(ids)).order_by(table.name))).scalars().all() + if ids + else [] + ) + items[resource_type] = [ + {'id': row.id, 'name': row.name, **{key: get(row) for key, get in extra.items()}} for row in rows + ] + # Pins in the owners' order, keeping only those still shared with the team. + team = await Teams.get_team_by_id(id, db=db) + shared = {(kind, item['id']): item for kind in TEAM_ITEM_TYPES for item in items[kind]} + items['pinned'] = [ + {**shared[(pin['type'], pin['id'])], 'type': pin['type']} + for pin in ((team.data or {}).get('pinned') or []) + if (pin.get('type'), pin.get('id')) in shared + ] + # Sub-teams are listed, not merged: their items stay on their own pages. + items['team'] = [ + {'id': team.id, 'name': team.name, 'meta': team.meta, 'member_count': team.member_count} + for team in await Teams.get_sub_teams(id, db=db) + ] + return items + + +@router.post('/id/{id}/update', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def update_team_by_id( + request: Request, + id: str, + form_data: TeamForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + current = await require_team(id, user, db, writable=True) + moved = 'parent_id' in form_data.model_fields_set and form_data.parent_id != current.parent_id + if user.role != 'admin' and current.role != 'owner': + # Members change only what the owners opened to them; moving and permissions stay with owners. + settings_changed = ( + form_data.name != current.name + or (form_data.description or '') != (current.description or '') + or ('identifier' in form_data.model_fields_set and form_data.identifier != current.identifier) + or (form_data.meta is not None and form_data.meta.get('icon') != (current.meta or {}).get('icon')) + ) + changes = {'manage_team': settings_changed, 'manage_pins': form_data.data is not None} + if ( + moved + or (form_data.is_private is not None and form_data.is_private != current.is_private) + or form_data.permissions is not None + or any(changed and team_permission(current, key) != 'member' for key, changed in changes.items()) + ): + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + if moved: + await require_parent_owner(form_data.parent_id, user, db) + try: + team = await Teams.update_team_by_id(id, form_data, db=db) + except TeamMembershipError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e + await publish_event( + request, + EVENTS.TEAM_UPDATED, + actor=user, + subject_id=id, + data={'name': team.name, 'parent_id': team.parent_id}, + ) + return await Teams.get_team_response(id, user.id, db=db) + + +@router.post('/id/{id}/members/add', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def add_team_members( + request: Request, + id: str, + form_data: UserIdsForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + await require_team(id, user, db, permission='manage_members', writable=True) + added = await Teams.add_members(id, form_data.user_ids, db=db) + if added: + await publish_event(request, EVENTS.TEAM_MEMBER_ADDED, actor=user, subject_id=id, data={'user_ids': added}) + return await Teams.get_team_response(id, user.id, db=db) + + +@router.post('/id/{id}/join', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def join_team_by_id( + request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + # Anyone who can see a team can join it; joining also joins the teams above it. + team = await require_team(id, user, db, visible=True, writable=True) + if team.role is None and await Teams.add_members(id, [user.id], db=db): + await publish_event(request, EVENTS.TEAM_MEMBER_ADDED, actor=user, subject_id=id, data={'user_ids': [user.id]}) + return await Teams.get_team_response(id, user.id, db=db) + + +@router.post( + '/id/{id}/members/remove', response_model=Optional[TeamResponse], dependencies=[Depends(check_teams_enabled)] +) +async def remove_team_members( + request: Request, + id: str, + form_data: UserIdsForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + # Any member may remove themselves (leave). Removing others takes member management, + # and only owners remove owners. + leaving = form_data.user_ids == [user.id] + team = await require_team(id, user, db, permission=None if leaving else 'manage_members', writable=True) + if not leaving and user.role != 'admin' and team.role != 'owner': + for user_id in form_data.user_ids: + if await Teams.is_team_owner(id, user_id, db=db): + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + try: + removed = await Teams.remove_members(id, form_data.user_ids, db=db) + except TeamMembershipError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e + if removed: + await publish_event(request, EVENTS.TEAM_MEMBER_REMOVED, actor=user, subject_id=id, data={'user_ids': removed}) + return await Teams.get_team_response(id, user.id, db=db) + + +@router.post('/id/{id}/members/role', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def update_team_member_role( + request: Request, + id: str, + form_data: MemberRoleForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + await require_team(id, user, db, owner=True, writable=True) + try: + changed = await Teams.set_member_role(id, form_data.user_ids, form_data.role, db=db) + except TeamMembershipError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e + if changed: + await publish_event( + request, + EVENTS.TEAM_MEMBER_ROLE_UPDATED, + actor=user, + subject_id=id, + data={'user_ids': changed, 'role': form_data.role}, + ) + return await Teams.get_team_response(id, user.id, db=db) + + +async def set_team_archived(request: Request, id: str, user, db, archived: bool): + await require_team(id, user, db, owner=True) + try: + team = await Teams.set_archived(id, user.id if archived else None, db=db) + except TeamMembershipError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e + await publish_event( + request, + EVENTS.TEAM_ARCHIVED if archived else EVENTS.TEAM_RESTORED, + actor=user, + subject_id=id, + data={'name': team.name}, + ) + return await Teams.get_team_response(id, user.id, db=db) + + +@router.post('/id/{id}/archive', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def archive_team_by_id( + request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + return await set_team_archived(request, id, user, db, archived=True) + + +@router.post('/id/{id}/restore', response_model=TeamResponse, dependencies=[Depends(check_teams_enabled)]) +async def restore_team_by_id( + request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) +): + return await set_team_archived(request, id, user, db, archived=False) + + +@router.delete('/id/{id}/delete', response_model=bool, dependencies=[Depends(check_teams_enabled)]) +async def delete_team_by_id( + request: Request, + id: str, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + team = await require_team(id, user, db, owner=True) + result = await Teams.delete_team_by_id(id, db=db) + if result: + await publish_event(request, EVENTS.TEAM_DELETED, actor=user, subject_id=id, data={'name': team.name}) + return result diff --git a/backend/open_webui/routers/tools.py b/backend/open_webui/routers/tools.py index 67c8d20ef8..7139253bba 100644 --- a/backend/open_webui/routers/tools.py +++ b/backend/open_webui/routers/tools.py @@ -22,6 +22,7 @@ from open_webui.internal.db import get_async_session from open_webui.models.access_grants import AccessGrants from open_webui.models.config import Config from open_webui.models.groups import Groups +from open_webui.models.teams import Teams from open_webui.models.oauth_sessions import OAuthSessions from open_webui.models.tool_history import ToolHistories, tool_diff from open_webui.models.tools import ( @@ -379,6 +380,7 @@ async def get_tool_list(user=Depends(get_verified_user), db: AsyncSession = Depe if bypass_access_control else {group.id for group in await Groups.get_groups_by_member_id(user.id, db=db, include_inherited=True)} ) + user_team_ids = set() if bypass_access_control else await Teams.get_team_ids_by_member_id(user.id, db=db) tools = await Tools.get_tools( defer_content=True, db=db, @@ -396,6 +398,7 @@ async def get_tool_list(user=Depends(get_verified_user), db: AsyncSession = Depe and ( (g.principal_type == 'user' and (g.principal_id == user.id or g.principal_id == '*')) or (g.principal_type == 'group' and g.principal_id in user_group_ids) + or (g.principal_type == 'team' and g.principal_id in user_team_ids) ) for g in tool.access_grants ) diff --git a/backend/open_webui/routers/users.py b/backend/open_webui/routers/users.py index eff37caf5b..7bb3d969f0 100644 --- a/backend/open_webui/routers/users.py +++ b/backend/open_webui/routers/users.py @@ -256,6 +256,7 @@ class SharingPermissions(BaseModel): class AccessGrantsPermissions(BaseModel): allow_users: bool = True allow_groups: bool = True + allow_teams: bool = True class ChatPermissions(BaseModel): @@ -290,6 +291,7 @@ class FeaturesPermissions(BaseModel): notes: bool = True channels: bool = True encrypted_channels: bool = False + teams: bool = False folders: bool = True web_search: bool = True diff --git a/backend/open_webui/utils/access_control/__init__.py b/backend/open_webui/utils/access_control/__init__.py index 119c8030ad..237f2c767d 100644 --- a/backend/open_webui/utils/access_control/__init__.py +++ b/backend/open_webui/utils/access_control/__init__.py @@ -258,6 +258,9 @@ async def filter_allowed_access_grants( access_grants = [ grant for grant in access_grants if (grant['principal_type'], grant['principal_id']) != ('user', '*') ] + # Machine templates are admin-configured and checked in memory against groups only. + if resource_type in ('machine', 'terminal'): + access_grants = [grant for grant in access_grants if grant['principal_type'] != 'team'] if user_role == 'admin' or not access_grants: return access_grants @@ -278,6 +281,7 @@ async def filter_allowed_access_grants( 'public': allowed(public_permission_key), 'user': allowed('access_grants.allow_users'), 'group': allowed('access_grants.allow_groups'), + 'team': allowed('access_grants.allow_teams'), } return [ grant diff --git a/src/lib/apis/teams/index.ts b/src/lib/apis/teams/index.ts new file mode 100644 index 0000000000..8023a755f7 --- /dev/null +++ b/src/lib/apis/teams/index.ts @@ -0,0 +1,147 @@ +import { WEBUI_API_BASE_URL } from '$lib/constants'; + +export type TeamRole = 'member' | 'owner'; + +// The lowest team role allowed for each action owners can open to members; unset means owners only. +export type TeamPermissions = Partial< + Record<'manage_team' | 'manage_pins' | 'manage_members', TeamRole | null> +>; + +export type Team = { + id: string; + parent_id: string | null; + user_id: string; + name: string; + // A short key like OWUI, unique across teams: an uppercase letter, then up to 9 letters, digits or _. + identifier: string | null; + description: string | null; + // Private teams are invite-only; public ones can be found and joined by anyone who can see the team above. + is_private: boolean; + permissions: TeamPermissions | null; + data: Record | null; + meta: { icon?: string | null } | null; + created_at: number; + updated_at: number; + // Archived teams are read-only and left out of team lists until restored. + archived_at: number | null; + archived_by: string | null; + member_count: number; + role: TeamRole | null; +}; + +export type TeamInfo = Pick; + +export type TeamMember = { + id: string; + name: string; + email: string; + role: TeamRole; +}; + +export type TeamItem = { + id: string; + name: string; + icon?: string | null; + profile_image_url?: string | null; + command?: string; +}; + +export type TeamItemType = 'folder' | 'model' | 'knowledge' | 'prompt' | 'tool' | 'skill'; + +export type TeamPin = { type: TeamItemType; id: string }; + +// What is shared with a team, by type, plus its owners' pins (in order) and its sub-teams. +export type TeamItems = Record & { + pinned: (TeamItem & { type: TeamItemType })[]; + team: Pick[]; +}; + +// 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}/teams${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; +} + +// Your active teams, or only your archived ones. +export const getTeams = (token: string, archived = false) => + request(token, archived ? '/?archived=true' : '/'); + +// Teams the user can see but isn't in, to browse and join. +export const getJoinableTeams = (token: string) => request(token, '/joinable'); + +export const joinTeamById = (token: string, id: string) => + request(token, `/id/${id}/join`, 'POST'); + +export const createNewTeam = ( + token: string, + team: { + name: string; + identifier?: string | null; + description?: string | null; + parent_id?: string | null; + is_private?: boolean; + permissions?: TeamPermissions; + data?: Team['data']; + meta?: Team['meta']; + } +) => request(token, '/create', 'POST', team); + +export const getTeamById = (token: string, id: string) => request(token, `/id/${id}`); + +export const getTeamInfoById = (token: string, id: string) => + request(token, `/id/${id}/info`); + +export const getTeamMembers = (token: string, id: string, query = '', page = 1) => + request<{ items: TeamMember[]; total: number }>( + token, + `/id/${id}/members?${new URLSearchParams({ query, page: String(page) })}` + ); + +export const getTeamItems = (token: string, id: string) => + request(token, `/id/${id}/items`); + +export const updateTeamById = ( + token: string, + id: string, + team: { + name: string; + identifier?: string | null; + description?: string | null; + parent_id?: string | null; + is_private?: boolean; + permissions?: TeamPermissions; + data?: Team['data']; + meta?: Team['meta']; + } +) => request(token, `/id/${id}/update`, 'POST', team); + +export const addTeamMembers = (token: string, id: string, userIds: string[]) => + request(token, `/id/${id}/members/add`, 'POST', { user_ids: userIds }); + +export const removeTeamMembers = (token: string, id: string, userIds: string[]) => + request(token, `/id/${id}/members/remove`, 'POST', { user_ids: userIds }); + +export const setTeamMemberRole = (token: string, id: string, userIds: string[], role: TeamRole) => + request(token, `/id/${id}/members/role`, 'POST', { user_ids: userIds, role }); + +export const archiveTeamById = (token: string, id: string) => + request(token, `/id/${id}/archive`, 'POST'); + +export const restoreTeamById = (token: string, id: string) => + request(token, `/id/${id}/restore`, 'POST'); + +export const deleteTeamById = (token: string, id: string) => + request(token, `/id/${id}/delete`, 'DELETE'); diff --git a/src/lib/components/AddMachineModal.svelte b/src/lib/components/AddMachineModal.svelte index aea0c58927..c6c75194fd 100644 --- a/src/lib/components/AddMachineModal.svelte +++ b/src/lib/components/AddMachineModal.svelte @@ -1012,7 +1012,12 @@ chevronStrokeWidth="2" >
- {}} /> + {}} + />
diff --git a/src/lib/components/AddToolServerModal.svelte b/src/lib/components/AddToolServerModal.svelte index 9ba90c5ca3..d1488fc242 100644 --- a/src/lib/components/AddToolServerModal.svelte +++ b/src/lib/components/AddToolServerModal.svelte @@ -1084,7 +1084,7 @@
- + {/if} + + + - + - + - + {/if} + + {#if $config?.features?.enable_teams} +
+
+
+ {$i18n.t('Allow Sharing With Teams')} +
+ +
+ {#if defaultPermissions?.access_grants?.allow_teams && !permissions.access_grants.allow_teams} +
+
+ {$i18n.t('This is a default user permission and will remain enabled.')} +
+
+ {/if} +
+ {/if}
@@ -1065,6 +1086,24 @@ {/if} + {#if $config?.features?.enable_teams} +
+
+
+ {$i18n.t('Create Teams')} +
+ +
+ {#if defaultPermissions?.features?.teams && !permissions.features.teams} +
+
+ {$i18n.t('This is a default user permission and will remain enabled.')} +
+
+ {/if} +
+ {/if} + {#if $config?.features?.enable_channels && $config?.features?.enable_encrypted_channels}
diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 37ad508609..4d26950f9e 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -53,6 +53,7 @@ machines, functions, selectedFolder as _selectedFolder, + teams, folders as _folders, showEmbeds as _showEmbeds, selectedMachineId as _selectedMachineId, @@ -180,6 +181,7 @@ import DeleteConfirmDialog from '../common/ConfirmDialog.svelte'; import WebSearchConfirmDialog from '../common/ConfirmDialog.svelte'; import Placeholder from './Placeholder.svelte'; + import Team from '$lib/components/teams/Team.svelte'; import FilesOverlay from './MessageInput/FilesOverlay.svelte'; import NotificationToast from '../NotificationToast.svelte'; import Spinner from '../common/Spinner.svelte'; @@ -206,6 +208,10 @@ export let chatIdProp = ''; export let initialPage = ''; let mainChatHref = '/'; + // A team's page fills the main tab, as a folder's does. + $: mainTeamId = + !embedded && $page.route.id === '/(app)/teams/[id]' ? ($page.params.id ?? null) : null; + $: mainTeam = $teams.find((team) => team.id === mainTeamId); // Unsaved chats have no /c/ page, so they keep the new-chat address set by initNewChat. $: if (isSavedChatId($chatId)) mainChatHref = `/c/${$chatId}`; export let embedded = false; @@ -2960,6 +2966,11 @@ if ($page.data.folder) void refreshFolder($page.data.folder.id); // On a first load the input is on screen before set-up, so what was entered there stays. await initNewChat({ preserveTabs, preserveInput: !preserveTabs, url: $page.url }); + } else if (mainTeamId) { + selectedFolder.set(null); + await initNewChat({ preserveTabs }); + mainChatHref = $page.url.pathname + $page.url.search; + tabs?.focusMainChat(); } else if (initialPage) { if (!preserveTabs) await initNewChat(); loading = false; @@ -6400,7 +6411,9 @@ aria-labelledby={fullWidthTabs ? 'chat-panel-main-chat' : undefined} > - {#if loading && (embedded || $page.url.pathname !== '/' || history.currentId)} + {#if mainTeamId} + + {:else if loading && (embedded || $page.url.pathname !== '/' || history.currentId)} {#if !fullWidthTabs && !embeddedCollapsed}
@@ -6918,6 +6931,13 @@ bind:mainChatStyle bind:mainChatGroupId title={$chatTitle || $i18n.t('New Chat')} + mainTabTeam={mainTeamId + ? { + id: mainTeamId, + name: mainTeam?.name ?? '', + icon: mainTeam?.meta?.icon + } + : null} mainTabFolder={!$chatId && $selectedFolder ? { id: $selectedFolder.id, @@ -6929,15 +6949,15 @@ $selectedFolder.write_access } : null} - tabTitleEditor={loading ? undefined : tabTitleEditor} + tabTitleEditor={loading || mainTeamId ? undefined : tabTitleEditor} onRenameMainTab={startRename} onRenameFolder={renameFolder} - tabActions={loading + tabActions={loading || mainTeamId ? undefined : !$chatId && $selectedFolder ? folderTabActions : tabActions} - tabBarActions={loading ? undefined : tabBarActions} + tabBarActions={loading || mainTeamId ? undefined : tabBarActions} {machineContext} bind:chatHistory={history} bind:files diff --git a/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte b/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte index 7d6671582b..c46aa41702 100644 --- a/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte +++ b/src/lib/components/chat/Placeholder/FolderPlaceholder.svelte @@ -2,7 +2,15 @@ import { getContext, onMount, setContext, tick } from 'svelte'; import { writable } from 'svelte/store'; import { toast } from 'svelte-sonner'; - import { config, machines, showFileNavPath, socket, selectedFolder, user } from '$lib/stores'; + import { + config, + machines, + showFileNavPath, + socket, + selectedFolder, + teams, + user + } from '$lib/stores'; import type { AppLayoutContext } from '$lib/types'; import { resolveMachineTarget } from '$lib/apis/machines'; import { machineIdOf } from '$lib/utils/machines'; @@ -85,6 +93,7 @@ import { WEBUI_API_BASE_URL } from '$lib/constants'; import Icon from '$lib/components/chat/FileNav/Icon.svelte'; import Emoji from '$lib/components/common/Emoji.svelte'; + import TeamIcon from '$lib/components/teams/TeamIcon.svelte'; import EmojiPicker from '$lib/components/common/EmojiPicker.svelte'; const i18n = getContext('i18n'); @@ -95,6 +104,13 @@ /** Which part of the folder is showing: its files, chats, notes, automations or knowledge. */ export let folderSection: FolderSection = 'chats'; + // The team this folder is shared with leads its breadcrumb, as a team's folders do in Linear. + $: folderTeam = $teams.find((team) => + (folder?.access_grants ?? []).some( + (grant) => grant.principal_type === 'team' && grant.principal_id === team.id + ) + ); + // The page is saved with the folder's tabs, so it opens exactly as it was left. $: folderView = folder?.id && $user?.id ? chatViewEntry($user.id, folderSessionId(folder.id, $user.id)) : null; @@ -1295,7 +1311,20 @@ class="flex h-6.5 min-w-0 items-center gap-1 px-1 text-sm text-base-900 select-none dark:text-base-100" aria-live="polite" > - + + {#if folderTeam} + + + {folderTeam.name} + + + {/if} {#if readOnly} {@render folderIcon()} diff --git a/src/lib/components/chat/Tabs.svelte b/src/lib/components/chat/Tabs.svelte index acc655084f..dda2a460f4 100644 --- a/src/lib/components/chat/Tabs.svelte +++ b/src/lib/components/chat/Tabs.svelte @@ -95,6 +95,7 @@ import DropdownMenu from '../common/DropdownMenu.svelte'; import Icon from './FileNav/Icon.svelte'; import Emoji from '$lib/components/common/Emoji.svelte'; + import TeamIcon from '$lib/components/teams/TeamIcon.svelte'; import Annotation from '$lib/components/icons/Annotation.svelte'; import Map from '$lib/components/icons/Map.svelte'; import FolderIcon from '$lib/components/icons/Folder.svelte'; @@ -181,6 +182,12 @@ icon?: string | null; canEdit?: boolean; } | null = null; + /** The team whose page fills the main tab. */ + export let mainTabTeam: { + id: string; + name: string; + icon?: string | null; + } | null = null; /** Double-clicking the folder tab renames the folder inline. */ export let onRenameFolder: ((folderId: string, name: string) => Promise) | null = null; let isRenamingFolder = false; @@ -201,7 +208,7 @@ if (name && name !== mainTabFolder.name) await onRenameFolder?.(mainTabFolder.id, name); }; $: if (!mainTabFolder) isRenamingFolder = false; - $: mainTabTitle = mainTabFolder?.name ?? title; + $: mainTabTitle = mainTabFolder?.name ?? mainTabTeam?.name ?? title; /** What the open tabs belong to: the folder on screen, or the chat. */ $: panelChatId = mainTabFolder && $user ? folderSessionId(mainTabFolder.id, $user.id) : chatId; export let getEmbeddedDraft: ( @@ -2747,12 +2754,14 @@ if (tab.kind === 'chat') void chatViews[tab.id]?.startRename(); if (tab.id !== mainChatTabId) return; if (mainTabFolder) void startFolderRename(); - else onRenameMainTab?.(); + else if (!mainTabTeam) onRenameMainTab?.(); }} > {#if (tab.id === mainChatTabId && chatStreaming) || (tab.kind === 'chat' && chatStreamingStates[tab.id])} {$i18n.t('Generating...')} + {:else if tab.id === mainChatTabId && mainTabTeam} + {:else if tab.id === mainChatTabId && mainTabFolder} {#if mainTabFolder.icon} diff --git a/src/lib/components/chat/UserMachinesModal.svelte b/src/lib/components/chat/UserMachinesModal.svelte index c7f9d0467c..7a4f7df197 100644 --- a/src/lib/components/chat/UserMachinesModal.svelte +++ b/src/lib/components/chat/UserMachinesModal.svelte @@ -792,6 +792,7 @@
+ // Iconoir "chat-lines". + export let className = 'w-4 h-4'; + export let strokeWidth = '1.5'; + + + diff --git a/src/lib/components/icons/FolderAlt.svelte b/src/lib/components/icons/FolderAlt.svelte new file mode 100644 index 0000000000..caac7ead0b --- /dev/null +++ b/src/lib/components/icons/FolderAlt.svelte @@ -0,0 +1,21 @@ + + + diff --git a/src/lib/components/icons/Tools.svelte b/src/lib/components/icons/Tools.svelte new file mode 100644 index 0000000000..9898105f6a --- /dev/null +++ b/src/lib/components/icons/Tools.svelte @@ -0,0 +1,36 @@ + + + diff --git a/src/lib/components/layout/Sidebar.svelte b/src/lib/components/layout/Sidebar.svelte index 3567bd02c2..736e606551 100644 --- a/src/lib/components/layout/Sidebar.svelte +++ b/src/lib/components/layout/Sidebar.svelte @@ -21,6 +21,7 @@ pinnedChats, pinnedNotes, channels, + teams, socket, onSocketRestored, config, @@ -109,6 +110,10 @@ import Folders from './Sidebar/Folders.svelte'; import SharedFolderItem from './Sidebar/SharedFolderItem.svelte'; import { getChannels, createNewChannel } from '$lib/apis/channels'; + import { getJoinableTeams, getTeams, updateTeamById, type Team } from '$lib/apis/teams'; + import TeamModal from '$lib/components/teams/TeamModal.svelte'; + import AddTeamMenu from '$lib/components/teams/AddTeamMenu.svelte'; + import TeamItem from './Sidebar/TeamItem.svelte'; import ChannelModal from './Sidebar/ChannelModal.svelte'; import ChannelItem from './Sidebar/ChannelItem.svelte'; import SearchModal from './SearchModal.svelte'; @@ -139,7 +144,7 @@ import MobileSwipePanel from '../common/MobileSwipePanel.svelte'; const DEFAULT_PINNED_ITEMS = ['notes', 'workspace']; - const SIDEBAR_SECTIONS = ['models', 'notes', 'channels', 'folders', 'chats']; + const SIDEBAR_SECTIONS = ['teams', 'models', 'notes', 'channels', 'folders', 'chats']; let scrollTop = 0; @@ -281,6 +286,16 @@ let showPinnedModels = true; let showPinnedNotes = false; let showChannels = false; + let showTeams = true; + let showArchivedTeams = false; + // Public teams the user can join, listed in the Teams section's + menu. + let joinableTeams: Team[] = []; + // Teams joined since the last load (from a team's page) drop out without another request. + $: browsableTeams = joinableTeams.filter((team) => !$teams.some((mine) => mine.id === team.id)); + // Archived teams leave the tree; their sub-teams are archived first, so none are left orphaned. + $: activeTeams = $teams.filter((team) => !team.archived_at); + $: archivedTeams = $teams.filter((team) => team.archived_at); + let showCreateTeam = false; $: channelGroups = [ $channels.filter((channel) => channel.type !== 'group' && channel.type !== 'dm'), $channels.filter((channel) => channel.type === 'group'), @@ -496,10 +511,12 @@ } }; - $: sectionOrder = [ - ...($settings?.sidebarSectionOrder ?? []).filter((id) => SIDEBAR_SECTIONS.includes(id)), - ...SIDEBAR_SECTIONS.filter((id) => !($settings?.sidebarSectionOrder ?? []).includes(id)) - ]; + // A saved order wins; a section it doesn't know yet (a new one, like Teams) takes its default place. + $: sectionOrder = SIDEBAR_SECTIONS.reduce( + (order, id, index) => + order.includes(id) ? order : [...order.slice(0, index), id, ...order.slice(index)], + ($settings?.sidebarSectionOrder ?? []).filter((id) => SIDEBAR_SECTIONS.includes(id)) + ); $: visibleSections = sectionOrder.filter((id) => { switch (id) { @@ -516,6 +533,8 @@ $config?.features?.enable_channels && ($user?.role === 'admin' || ($user?.permissions?.features?.channels ?? true)) ); + case 'teams': + return canUseTeams && ($teams.length > 0 || browsableTeams.length > 0 || canCreateTeams); case 'folders': return ( $config?.features?.enable_folders && @@ -711,6 +730,37 @@ } }; + $: canUseTeams = $config?.features?.enable_teams ?? false; + $: canCreateTeams = + canUseTeams && ($user?.role === 'admin' || ($user?.permissions?.features?.teams ?? false)); + $: if (canUseTeams) initTeams(); + + const initTeams = async () => { + if (!canUseTeams) return; + // The store keeps archived teams too, for the sidebar's Archived list; pickers leave them out. + const [active, archived, joinable] = await Promise.all([ + getTeams(localStorage.token).catch(() => null), + getTeams(localStorage.token, true).catch(() => []), + getJoinableTeams(localStorage.token).catch(() => []) + ]); + if (active) teams.set([...active, ...(archived ?? [])]); + joinableTeams = joinable ?? []; + }; + + const moveTeam = async (id: string, parentId: string | null) => { + const team = $teams.find((item) => item.id === id); + if (!team) return; + const res = await updateTeamById(localStorage.token, id, { + name: team.name, + description: team.description, + parent_id: parentId + }).catch((error) => { + toast.error(`${error}`); + return null; + }); + if (res) await initTeams(); + }; + const initChatList = async () => { // Mark the chat list as loading while tags, pinned notes, and chats refresh. console.log('initChatList'); @@ -1007,6 +1057,7 @@ onMount(() => onSocketRestored(() => { initChannels(); + initTeams(); refreshChatRows(); }) ); @@ -1294,6 +1345,15 @@ }} /> + { + await initTeams(); + showTeams = true; + goto(`/teams/${team.id}`); + }} +/> + {#if $config?.features?.enable_folders && ($user?.role === 'admin' || ($user?.permissions?.features?.folders ?? true))} @@ -1807,6 +1867,55 @@ {/each} {/each} + {:else if sectionId === 'teams'} + { + // A sub-team dropped on the section heading moves to the top level. + const { type, id } = e.detail; + if (type === 'team' && $teams.find((team) => team.id === id)?.parent_id) { + moveTeam(id, null); + } + }} + > + + + {#if canCreateTeams || browsableTeams.length > 0} + (showCreateTeam = true) : null} + onOpen={(team) => goto(`/teams/${team.id}`)} + onJoined={async () => { + await initTeams(); + showTeams = true; + }} + /> + {/if} + + {#each activeTeams.filter((team) => !activeTeams.some((parent) => parent.id === team.parent_id)) as team (team.id)} + + {/each} + {#if archivedTeams.length > 0} + + {#if showArchivedTeams} +
+ {#each archivedTeams as team (team.id)} + + {/each} +
+ {/if} + {/if} +
{:else if sectionId === 'folders'}
- {:else if !readonly && shiftKey && mouseOver && !chatSelection} + {:else if !readonly && shiftKey && mouseOver}
{#if $visibleControls['chat.archive']} + // Drag data can't be read until the drop, so the dragged team is kept here, as folders do. + let draggedTeamId: string | null = null; + + + + +{#if dragged && x && y} + +
+
+ +
{team.name}
+
+
+
+{/if} + + + +
draggedTeamId && e.stopPropagation()} + on:drop={(e) => draggedTeamId && e.stopPropagation()} +> + +
{ + x = e.clientX; + y = e.clientY; + }} + on:dragend={onDragEnd} + on:dragover={onDragOver} + on:dragleave={() => (draggedOver = false)} + on:drop={onDrop} + > + {#if draggedOver} +
+ {/if} + {#if subTeams.length} + + {:else} + + {/if} + +
{team.name}
+
+
+ + {#if open && subTeams.length} +
+ {#each subTeams as subTeam (subTeam.id)} + + {/each} +
+ {/if} +
diff --git a/src/lib/components/teams/AddTeamMembersModal.svelte b/src/lib/components/teams/AddTeamMembersModal.svelte new file mode 100644 index 0000000000..507f5650a0 --- /dev/null +++ b/src/lib/components/teams/AddTeamMembersModal.svelte @@ -0,0 +1,75 @@ + + + +
+
+
{$i18n.t('Add Members')}
+ +
+ +
+
+ ({ principal_type: 'user', principal_id: id }))} + /> +
+ +
+ +
+
+
+
diff --git a/src/lib/components/teams/AddTeamMenu.svelte b/src/lib/components/teams/AddTeamMenu.svelte new file mode 100644 index 0000000000..835ce6fddf --- /dev/null +++ b/src/lib/components/teams/AddTeamMenu.svelte @@ -0,0 +1,111 @@ + + + + { + if (!state) return; + query = ''; + await tick(); + searchInput?.focus(); + }} +> + + +
+ + {#if teams.length > 0} +
+ + +
+
+ {#each shown as team (team.id)} + + + {:else} +
+ {$i18n.t('No results found')} +
+ {/each} +
+ {#if onCreate}
{/if} + {/if} + {#if onCreate} + + {/if} +
+
+
diff --git a/src/lib/components/teams/Team.svelte b/src/lib/components/teams/Team.svelte new file mode 100644 index 0000000000..6d0a57ddbb --- /dev/null +++ b/src/lib/components/teams/Team.svelte @@ -0,0 +1,800 @@ + + + +{#snippet toolbar( + placeholder: string, + onSearch: () => void, + onCreate: (() => void) | null, + createLabel: string +)} +
+
+
+ + {#if query} +
+ +
+ {/if} +
+ {#if onCreate} + + {/if} +
+{/snippet} + + +{#snippet listState(title: string, description: string)} +
+
+
{title}
+
{description}
+
+
+{/snippet} + + +{#snippet groupHeader(group: string, label: string, onAdd: (() => void) | null)} +
+

+ +

+ {#if onAdd} + + {/if} +
+{/snippet} + +{#if team} + + + + + + {#if items} + + {/if} + member.id)} + onAdded={() => Promise.all([loadMembers(), load(id)])} + /> + +
+ {$i18n.t(`Are you sure you want to delete "{{NAME}}"?`, { NAME: team.name })} +
+
+{/if} + +
+ {#if notFound} +
{$i18n.t('Not found')}
+ {:else if !team} +
+ {:else} + + + + +
+
+ {#if tab === 'members'} + {@render toolbar( + $i18n.t('Search Members'), + () => { + clearTimeout(searchTimer); + searchTimer = setTimeout(() => { + membersPage = 1; + loadMembers(); + }, 300); + }, + canManageMembers ? () => (showAddMembers = true) : null, + $i18n.t('Add Members') + )} + {#if members === null} +
+ {:else if members.length === 0} + {@render listState( + $i18n.t('No results found'), + $i18n.t('Try adjusting your search or filter to find what you are looking for.') + )} + {:else} + +
+
{$i18n.t('Name')}
+ +
{$i18n.t('Role')}
+ {#if canManageMembers}
{/if} +
+
    + {#each members as member (member.id)} +
  • +
    + + {member.name} + {#if member.id === $user?.id} + {$i18n.t('You')} + {/if} +
    + +
    + {#if canEdit} + + changeMembers(() => + setTeamMemberRole( + localStorage.token, + id, + [member.id], + (e.target as HTMLSelectElement).value as TeamRole + ) + )} + > + + + + {:else} + {member.role === 'owner' ? $i18n.t('Owner') : $i18n.t('Member')} + {/if} +
    + {#if canManageMembers && (canEdit || member.role !== 'owner')} + + {:else if canManageMembers} +
    + {/if} +
  • + {/each} +
+ {#if membersTotal > 30} + + {/if} + {/if} + {:else if items === null && !visitor} +
+ {:else} + +
+
+
+ {#if canManageTeam} + + + + {:else} + + {/if} +

+ {team.name} +

+ (showFolderModal = true) : null} + onEdit={canManageTeam ? () => (showEditModal = true) : null} + onArchive={canEdit ? () => setArchived(true) : null} + onUnarchive={isOwner && archived ? () => setArchived(false) : null} + onLeave={team.role && !archived ? leaveHandler : null} + onDelete={isOwner ? () => (showDeleteConfirm = true) : null} + > +
+
+ {#if visitor && !archived} + + {/if} +
+ {#if team.description?.trim()} +

+ {team.description.trim()} +

+ {/if} + {#if archived} +

+ {$i18n.t('This team is archived.')} + {#if isOwner} + + {/if} +

+ {/if} + + {#if visitor} +

+ {$i18n.t("Join the team to see what's shared with it.")} +

+ {:else if items} +
+ {#if items.pinned.length || canPin} +
+ {@render groupHeader( + 'pinned', + $i18n.t('Pinned'), + canPin ? () => (showPinPicker = true) : null + )} + {#if !folded.pinned} + {#if items.pinned.length} +
    + {#each items.pinned as pin (`${pin.type}:${pin.id}`)} +
  • + + + {pin.name} + + {#if canPin} + + {/if} +
  • + {/each} +
+ {:else} +

+ {$i18n.t('Pin what your team uses most.')} +

+ {/if} + {/if} +
+ {/if} + + + {#each sharedGroups as { kind, label } (kind)} +
+ {@render groupHeader(kind, $i18n.t(label), null)} + {#if !folded[kind]} + + {/if} +
+ {/each} +
+ + {#if overviewEmpty && !canPin} +

+ {$i18n.t('Items shared with the team will appear here.')} +

+ {/if} + {/if} +
+ + + +
+ {/if} +
+
+ {/if} +
diff --git a/src/lib/components/teams/TeamIcon.svelte b/src/lib/components/teams/TeamIcon.svelte new file mode 100644 index 0000000000..bf45231822 --- /dev/null +++ b/src/lib/components/teams/TeamIcon.svelte @@ -0,0 +1,14 @@ + + +{#if team.meta?.icon} + +{:else} + +{/if} diff --git a/src/lib/components/teams/TeamItemIcon.svelte b/src/lib/components/teams/TeamItemIcon.svelte new file mode 100644 index 0000000000..0c126f4f63 --- /dev/null +++ b/src/lib/components/teams/TeamItemIcon.svelte @@ -0,0 +1,47 @@ + + + + + {#if type === 'folder'} + {#if item.icon} + {:else}{/if} + {:else if type === 'model'} + { + // LICENSE covers this Open WebUI fallback logo. + // Do not alter, remove, obscure, or replace it except as LICENSE permits: + // https://docs.openwebui.com/license. + (e.currentTarget as HTMLImageElement).src = '/favicon.png'; + }} + /> + {:else if type === 'knowledge'} + + {:else if type === 'prompt'} + + {:else if type === 'tool'} + + {:else} + + {/if} + diff --git a/src/lib/components/teams/TeamMenu.svelte b/src/lib/components/teams/TeamMenu.svelte new file mode 100644 index 0000000000..ac432c5d1d --- /dev/null +++ b/src/lib/components/teams/TeamMenu.svelte @@ -0,0 +1,82 @@ + + + + + + + +
+ + + {#if onNewFolder} + + {/if} + {#if onNewFolder && (onEdit || onArchive || onUnarchive)} +
+ {/if} + {#if onEdit} + + {/if} + {#if onArchive} + + {/if} + {#if onUnarchive} + + {/if} + {#if (onLeave || onDelete) && (onNewFolder || onEdit || onArchive || onUnarchive)} +
+ {/if} + {#if onLeave} + + {/if} + {#if onDelete} + + {/if} +
+
+
diff --git a/src/lib/components/teams/TeamModal.svelte b/src/lib/components/teams/TeamModal.svelte new file mode 100644 index 0000000000..209e3731c9 --- /dev/null +++ b/src/lib/components/teams/TeamModal.svelte @@ -0,0 +1,267 @@ + + + +
+
+ {team ? $i18n.t('Edit Team') : $i18n.t('Create Team')} +
+ +
+ +
+
+
+ +
+ (icon = value ?? '')} + > + + + +
+
+ + +
+ + +
+ +
+ +