🙌 OpenHands: AI-Driven Development
feat: Add dynamic marketplace support for plugin registration (#14887)
HeyItsChloee64e1bd5d483
diff --git a/AGENTS.md b/AGENTS.mdindex c7f3d4dab0..a0f0320880 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -367,7 +367,7 @@ Your specialized knowledge and instructions here...- Add i18n translations for the setting name and any tooltips in `frontend/src/i18n/translation.json`- Add the translation key to `frontend/src/i18n/declaration.ts`2. Add the setting to the backend:- - Add the setting to the `Settings` model in `openhands/storage/data_models/settings.py`+ - Add the setting to the `Settings` model in `openhands/app_server/settings/settings_models.py`- Update any relevant backend code to apply the setting (e.g., in session creation)#### Settings UI Patterns:diff --git a/enterprise/migrations/versions/129_add_registered_marketplaces_to_org_settings.py b/enterprise/migrations/versions/129_add_registered_marketplaces_to_org_settings.pynew file mode 100644index 0000000000..802feaa877--- /dev/null+++ b/enterprise/migrations/versions/129_add_registered_marketplaces_to_org_settings.py@@ -0,0 +1,40 @@+"""Add registered_marketplaces and updated_at columns to org table.++This column stores marketplace registrations for organization-level+plugin resolution. Composable with instance defaults and user marketplaces.+Also adds updated_at for optimistic locking.++Revision ID: 129+Revises: 128+Create Date: 2026-06-18 16:34:00.000++"""++from typing import Union++import sqlalchemy as sa+from alembic import op++# revision identifiers, used by Alembic.+revision: str = '129'+down_revision: Union[str, None] = '128'+branch_labels: Union[str, None] = None+depends_on: Union[str, None] = None+++def upgrade() -> None:+ op.add_column('org', sa.Column('registered_marketplaces', sa.JSON(), nullable=True))+ op.add_column(+ 'org',+ sa.Column(+ 'updated_at',+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.text('NOW()'),+ ),+ )+++def downgrade() -> None:+ op.drop_column('org', 'updated_at')+ op.drop_column('org', 'registered_marketplaces')diff --git a/enterprise/migrations/versions/130_add_registered_marketplaces_to_user_settings.py b/enterprise/migrations/versions/130_add_registered_marketplaces_to_user_settings.pynew file mode 100644index 0000000000..b1008fde4e--- /dev/null+++ b/enterprise/migrations/versions/130_add_registered_marketplaces_to_user_settings.py@@ -0,0 +1,30 @@+"""Add registered_marketplaces column to user_settings table.++This column stores user's marketplace registrations for plugin resolution.++Revision ID: 130+Revises: 129+Create Date: 2026-06-18 16:35:00.000000++"""++from typing import Union++import sqlalchemy as sa+from alembic import op++# revision identifiers, used by Alembic.+revision: str = '130'+down_revision: Union[str, None] = '129'+branch_labels: Union[str, None] = None+depends_on: Union[str, None] = None+++def upgrade() -> None:+ op.add_column(+ 'user_settings', sa.Column('registered_marketplaces', sa.JSON(), nullable=True)+ )+++def downgrade() -> None:+ op.drop_column('user_settings', 'registered_marketplaces')diff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.pyindex ab63108592..6ee92a00ba 100644--- a/enterprise/server/auth/authorization.py+++ b/enterprise/server/auth/authorization.py@@ -346,6 +346,33 @@ def has_permission(return permission in get_role_permissions(user_role.name)+async def authorize_permission(+ request: Request, user_id: str, permission: Permission+) -> None:+ """Enforce that ``user_id`` has ``permission`` in the request's target org.++ Raises ``HTTPException(403)`` otherwise. Programmatic counterpart to+ :func:`require_permission` for handlers that must enforce a stricter+ permission for only part of a request (e.g. org-wide marketplace edits on an+ otherwise member-editable endpoint). Mirrors the org-role then super-role+ fallback used by ``require_permission``.+ """+ # Local import to avoid circular import via saas_user_auth.+ from server.auth.org_context import resolve_target_org_id_for_permission_check++ org_id = await resolve_target_org_id_for_permission_check(request)+ user_role = await get_user_org_role(user_id, org_id)+ if user_role and has_permission(user_role, permission):+ return+ super_role = await get_user_super_role(user_id)+ if super_role and has_permission(super_role, permission, is_super=True):+ return+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f'Missing required permission: {permission.value}',+ )++async def get_api_key_org_id_from_request(request: Request) -> UUID | None:"""Get the org_id bound to the API key used for authentication.diff --git a/enterprise/server/routes/org_models.py b/enterprise/server/routes/org_models.pyindex 4adb22a6e6..3cbf366fe0 100644--- a/enterprise/server/routes/org_models.py+++ b/enterprise/server/routes/org_models.py@@ -1,3 +1,4 @@+import loggingfrom datetime import datetimefrom typing import Annotated, Any@@ -16,8 +17,10 @@ from storage.org_member import OrgMemberfrom storage.role import Rolefrom openhands.app_server.settings.settings_models import (+ MarketplaceRegistration,_load_persisted_agent_settings,_load_persisted_conversation_settings,+ validate_and_convert_marketplaces,)from openhands.app_server.utils.llm import MASKED_API_KEY, resolve_llm_base_urlfrom openhands.sdk.settings import (@@ -26,6 +29,8 @@ from openhands.sdk.settings import (OpenHandsAgentSettings,)+logger = logging.getLogger(__name__)+class OrgCreationError(Exception):"""Base exception for organization creation errors."""@@ -94,6 +99,35 @@ class OrgNotFoundError(Exception):super().__init__(f'Organization with id "{org_id}" not found')+class OrgConcurrentModificationError(Exception):+ """Raised when a concurrent modification conflict is detected.++ This occurs when optimistic locking detects that the resource was modified+ by another request between when the client read it and when they attempted+ to update it. The client should re-fetch the latest data and retry.++ Note: The compared timestamp is generated and stored server-side; the client+ only echoes back the value it last read, so client/server clock skew does not+ affect conflict detection.+ """++ def __init__(+ self,+ org_id: str,+ expected_version: datetime,+ actual_version: datetime,+ ):+ self.org_id = org_id+ self.expected_version = expected_version+ self.actual_version = actual_version+ super().__init__(+ f'Organization "{org_id}" was modified by another request. '+ f'Expected version: {expected_version.isoformat()}, '+ f'actual version: {actual_version.isoformat()}. '+ 'Please refresh and retry.'+ )++class OrgMemberNotFoundError(Exception):"""Raised when a member is not found in an organization."""@@ -563,6 +597,9 @@ class OrgAppSettingsResponse(BaseModel):enable_proactive_conversation_starters: bool = Truemax_budget_per_task: float | None = None+ registered_marketplaces: list[MarketplaceRegistration] = Field(default_factory=list)+ # Include updated_at in response for optimistic locking+ updated_at: datetime | None = None@classmethoddef from_org(cls, org: Org) -> 'OrgAppSettingsResponse':@@ -574,11 +611,19 @@ class OrgAppSettingsResponse(BaseModel):Returns:OrgAppSettingsResponse with app settings"""+ # Get registered_marketplaces from dedicated column+ marketplaces = validate_and_convert_marketplaces(+ org.registered_marketplaces,+ source_name=f"org '{org.name}'",+ )+return cls(enable_proactive_conversation_starters=org.enable_proactive_conversation_startersif org.enable_proactive_conversation_starters is not Noneelse True,max_budget_per_task=org.max_budget_per_task,+ registered_marketplaces=marketplaces,+ updated_at=org.updated_at,)@@ -587,6 +632,11 @@ class OrgAppSettingsUpdate(BaseModel):enable_proactive_conversation_starters: bool | None = Nonemax_budget_per_task: float | None = None+ registered_marketplaces: list[MarketplaceRegistration] | None = None+ # Optimistic locking: client echoes back the server-generated updated_at it+ # last read. If it no longer matches the DB, someone else modified the record+ # and a 409 conflict is raised. (Server-generated, so clock skew is irrelevant.)+ last_known_updated_at: datetime | None = None@field_validator('max_budget_per_task')@classmethoddiff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.pyindex 5b21664e72..50ec790807 100644--- a/enterprise/server/routes/orgs.py+++ b/enterprise/server/routes/orgs.py@@ -4,10 +4,11 @@ from datetime import datetime, timezonefrom typing import Annotatedfrom uuid import UUID-from fastapi import APIRouter, Depends, HTTPException, Query, status+from fastapi import APIRouter, Depends, HTTPException, Query, Request, statusfrom fastapi.responses import StreamingResponsefrom server.auth.authorization import (Permission,+ authorize_permission,require_financial_data_access,require_permission,)@@ -26,6 +27,7 @@ from server.routes.org_models import (OrgAppSettingsResponse,OrgAppSettingsUpdate,OrgAuthorizationError,+ OrgConcurrentModificationError,OrgConversationPage,OrgConversationResponse,OrgConversationStats,@@ -457,39 +459,60 @@ async def get_org_app_settings(@org_router.post('/app',response_model=OrgAppSettingsResponse,- dependencies=[Depends(require_permission(Permission.MANAGE_APPLICATION_SETTINGS))],)async def update_org_app_settings(update_data: OrgAppSettingsUpdate,+ request: Request,service: OrgAppSettingsService = org_app_settings_service_dependency,+ user_id: str = Depends(require_permission(Permission.MANAGE_APPLICATION_SETTINGS)),) -> OrgAppSettingsResponse:"""Update organization app settings for the user's current organization.- This endpoint updates application settings for the authenticated user's- current organization. Access requires the MANAGE_APPLICATION_SETTINGS permission,- which is granted to all organization members (member, admin, and owner roles).+ Base access requires MANAGE_APPLICATION_SETTINGS (all members). Editing+ org-wide ``registered_marketplaces`` additionally requires EDIT_ORG_SETTINGS+ (admin/owner), since those defaults apply to every member.Args:update_data: App settings update data+ request: The incoming request (used to resolve the target org for the+ marketplace permission check)service: OrgAppSettingsService (injected by dependency)+ user_id: Authenticated user ID (injected by ``require_permission``)Returns:OrgAppSettingsResponse: The updated organization app settingsRaises:HTTPException: 401 if user is not authenticated- HTTPException: 403 if user lacks MANAGE_APPLICATION_SETTINGS permission+ HTTPException: 403 if user lacks the required permissionHTTPException: 404 if current organization not found- HTTPException: 422 if validation errors occur (handled by FastAPI)+ HTTPException: 409 if a concurrent modification is detected+ HTTPException: 400 if validation errors occur (e.g. duplicate names)HTTPException: 500 if update fails"""try:+ # Org-wide marketplaces are admin/owner-only, even though the other+ # settings on this endpoint are member-editable.+ if update_data.registered_marketplaces is not None:+ await authorize_permission(request, user_id, Permission.EDIT_ORG_SETTINGS)return await service.update_org_app_settings(update_data)+ except OrgConcurrentModificationError as e:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=str(e),+ )except OrgNotFoundError:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail='Current organization not found',)+ except ValueError as e:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=str(e),+ )+ except HTTPException:+ raiseexcept Exception as e:logger.exception('Unexpected error updating organization app settings',diff --git a/enterprise/server/services/org_app_settings_service.py b/enterprise/server/services/org_app_settings_service.pyindex 16387ea87b..c512fbe30b 100644--- a/enterprise/server/services/org_app_settings_service.py+++ b/enterprise/server/services/org_app_settings_service.py@@ -126,7 +126,7 @@ class OrgAppSettingsService:)if not updated_org:- raise OrgNotFoundError('current')+ raise OrgNotFoundError(str(org.id))logger.info('Organization app settings updated successfully',diff --git a/enterprise/storage/org.py b/enterprise/storage/org.pyindex 4ebbdc68e5..855d40fd22 100644--- a/enterprise/storage/org.py+++ b/enterprise/storage/org.py@@ -1,17 +1,18 @@-"""-SQLAlchemy model for Organization.-"""+"""SQLAlchemy model for Organization."""+from datetime import UTC, datetimefrom typing import TYPE_CHECKING, Anyfrom uuid import UUID, uuid4from pydantic import SecretStrfrom server.constants import DEFAULT_BILLING_MARGIN-from sqlalchemy import JSON, String+from sqlalchemy import JSON, DateTime, Stringfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom storage.base import Basefrom storage.encrypt_utils import EncryptedJSON, decrypt_value, encrypt_value+from openhands.app_server.settings.settings_models import MarketplaceRegistration+if TYPE_CHECKING:from storage.api_key import ApiKeyfrom storage.billing_session import BillingSession@@ -75,6 +76,18 @@ class Org(Base):# Marks the bootstrapped default org on OHE installs; a partial unique# index allows at most one default org per install.is_default: Mapped[bool] = mapped_column(nullable=False, default=False)+ # Marketplace registrations at org level for plugin resolution+ # Composable with instance defaults and user personal marketplaces+ registered_marketplaces: Mapped[+ list[dict[str, Any] | MarketplaceRegistration] | None+ ] = mapped_column(JSON, nullable=True)+ # Timestamp for optimistic locking - tracks last modification+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(UTC),+ onupdate=lambda: datetime.now(UTC),+ nullable=False,+ )# Relationshipsorg_members: Mapped[list['OrgMember']] = relationship(diff --git a/enterprise/storage/org_app_settings_store.py b/enterprise/storage/org_app_settings_store.pyindex 7c7b9f9caa..c5073b1f66 100644--- a/enterprise/storage/org_app_settings_store.py+++ b/enterprise/storage/org_app_settings_store.py@@ -2,7 +2,9 @@from __future__ import annotations+import loggingfrom dataclasses import dataclass+from datetime import timezonefrom uuid import UUIDfrom server.constants import (@@ -10,7 +12,10 @@ from server.constants import (get_default_llm_base_url,get_default_llm_model,)-from server.routes.org_models import OrgAppSettingsUpdate+from server.routes.org_models import (+ OrgAppSettingsUpdate,+ OrgConcurrentModificationError,+)from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom storage.org import Org@@ -97,13 +102,21 @@ class OrgAppSettingsStore:Only updates fields that are explicitly provided in update_data.Uses flush() - commit happens at request end via DbSessionInjector.+ Implements optimistic locking: if last_known_updated_at is provided and+ doesn't match the current DB version, raises OrgConcurrentModificationError.+Args:org_id: The organization's IDupdate_data: Pydantic model with fields to updateReturns:Org: The updated organization object, or None if not found++ Raises:+ OrgConcurrentModificationError: If optimistic locking detects a conflict"""+ logger = logging.getLogger(__name__)+result = await self.db_session.execute(select(Org).filter(Org.id == org_id).with_for_update())@@ -112,8 +125,88 @@ class OrgAppSettingsStore:if not org:return None- # Update only explicitly provided fields- for field, value in update_data.model_dump(exclude_unset=True).items():+ # Optimistic locking: check if record was modified since client read it+ if update_data.last_known_updated_at is not None:+ current_updated_at = org.updated_at+ expected_updated_at = update_data.last_known_updated_at++ # Ensure timezone-aware comparison+ if current_updated_at.tzinfo is None:+ current_updated_at = current_updated_at.replace(tzinfo=timezone.utc)+ if expected_updated_at.tzinfo is None:+ expected_updated_at = expected_updated_at.replace(tzinfo=timezone.utc)++ # Raise conflict error if versions don't match+ if current_updated_at != expected_updated_at:+ logger.warning(+ f"Org '{org.name}' concurrent modification detected. "+ f'Expected: {expected_updated_at.isoformat()}, '+ f'Current: {current_updated_at.isoformat()}. '+ f'Raising conflict error.'+ )+ raise OrgConcurrentModificationError(+ org_id=str(org.id),+ expected_version=expected_updated_at,+ actual_version=current_updated_at,+ )++ # Handle registered_marketplaces separately (dedicated column)+ update_dict = update_data.model_dump(+ exclude_unset=True,+ exclude={'last_known_updated_at'}, # Don't save this field+ )+ if 'registered_marketplaces' in update_dict:+ from openhands.app_server.settings.settings_models import (+ MarketplaceRegistration,+ MarketplaceScope,+ )++ # Inject scope='org' for all marketplaces saved at org level+ marketplaces = update_dict.pop('registered_marketplaces')+ validated_marketplaces: list[MarketplaceRegistration] = []+ for mp in marketplaces:+ if isinstance(mp, dict):+ # Strip scope from incoming request - backend will set it+ mp_dict = {k: v for k, v in mp.items() if k != 'scope'}+ # Ensure auto_load defaults to False if not provided+ if 'auto_load' not in mp_dict:+ mp_dict['auto_load'] = False+ mp_obj = MarketplaceRegistration.model_validate(mp_dict)+ mp_obj.scope = MarketplaceScope.ORG+ validated_marketplaces.append(mp_obj)+ elif isinstance(mp, MarketplaceRegistration):+ mp.scope = MarketplaceScope.ORG+ validated_marketplaces.append(mp)+ else:+ # Already validated dict from DB - reconstruct as MarketplaceRegistration+ db_mp = dict(mp) # Copy to avoid mutation+ db_mp['scope'] = MarketplaceScope.ORG+ if 'auto_load' not in db_mp:+ db_mp['auto_load'] = False+ validated_marketplaces.append(+ MarketplaceRegistration.model_validate(db_mp)+ )++ # Names are the marketplace identity; reject duplicates before persist+ # so a bad write can't break loading/resolution later.+ from openhands.app_server.settings.marketplace_composition import (+ duplicate_marketplace_names,+ )++ conflicts = duplicate_marketplace_names(validated_marketplaces)+ if conflicts:+ raise ValueError(+ 'Duplicate marketplace name(s) not allowed: '+ + ', '.join(sorted(conflicts))+ )++ # Convert to JSON-ready dicts for the JSON column.+ org.registered_marketplaces = [+ mp.model_dump(mode='json') for mp in validated_marketplaces+ ]++ # Update regular org fields+ for field, value in update_dict.items():setattr(org, field, value)# flush instead of commit - DbSessionInjector auto-commits at request enddiff --git a/enterprise/storage/saas_settings_store.py b/enterprise/storage/saas_settings_store.pyindex 96d4793e64..b7ff347232 100644--- a/enterprise/storage/saas_settings_store.py+++ b/enterprise/storage/saas_settings_store.py@@ -23,7 +23,9 @@ from storage.user_settings import UserSettingsfrom storage.user_store import UserStorefrom openhands.app_server.settings.llm_profiles import LLMProfiles-from openhands.app_server.settings.settings_models import Settings+from openhands.app_server.settings.settings_models import (+ Settings,+)from openhands.app_server.settings.settings_store import SettingsStorefrom openhands.app_server.utils.jsonpatch_compat import (WHOLESALE_REPLACEMENT_KEYS,@@ -224,6 +226,25 @@ class SaasSettingsStore(SettingsStore):# Apply default if git_full_clone is None in the database (pre-existing rows)if kwargs.get('git_full_clone') is None:kwargs.pop('git_full_clone', None)+ # Apply default if registered_marketplaces is None in the database+ if kwargs.get('registered_marketplaces') is None:+ kwargs.pop('registered_marketplaces', None)++ # Load personal registered_marketplaces from user_settings table+ user_settings = await self._get_user_settings_by_keycloak_id_async(self.user_id)+ if user_settings and user_settings.registered_marketplaces:+ # Normalize marketplaces: use 'personal' scope for legacy data without scope+ # The merge function will override with the correct scope value+ normalized_mps: list[dict[str, Any]] = []+ for mp in user_settings.registered_marketplaces:+ if isinstance(mp, dict):+ if mp.get('scope') is None:+ mp = {**mp, 'scope': 'personal'}+ normalized_mps.append(mp)+ else:+ # Convert MarketplaceRegistration to dict+ normalized_mps.append(mp.model_dump())+ kwargs['registered_marketplaces'] = normalized_mps# Profiles in SaaS live on the org (managed via# /api/organizations/{org_id}/profiles). Surface them through# Settings.llm_profiles so the chat-layer endpoints@@ -422,10 +443,24 @@ class SaasSettingsStore(SettingsStore):kwargs.pop('agent_settings', None)kwargs.pop('conversation_settings', None)+ # Get or create user_settings for this user+ user_settings_result = await session.execute(+ select(UserSettings).filter(+ UserSettings.keycloak_user_id == self.user_id+ )+ )+ user_settings = user_settings_result.scalars().first()+ if not user_settings:+ user_settings = UserSettings(keycloak_user_id=self.user_id)+ session.add(user_settings)+for key, value in kwargs.items():if hasattr(user, key):setattr(user, key, value)- if hasattr(org, key) and key not in {+ if key == 'registered_marketplaces':+ # Save personal marketplace settings to user_settings table+ user_settings.registered_marketplaces = value+ elif hasattr(org, key) and key not in {'llm_api_key','agent_settings','conversation_settings',@@ -502,6 +537,63 @@ class SaasSettingsStore(SettingsStore):logger.debug(f'saas_settings_store.get_instance::{user_id}')return SaasSettingsStore(user_id, effective_org_id=effective_org_id)+ async def get_org_marketplaces(self, user_id: str | None) -> list[dict]:+ """Get organization-level marketplaces from the org's registered_marketplaces.++ Uses the effective_org_id if set, otherwise resolves via user.current_org_id.+ Returns empty list if no org or org has no registered marketplaces.+ """+ if not user_id:+ return []++ try:+ user = await UserStore.get_user_by_id(user_id)+ if not user:+ logger.debug(f'No user found for ID {user_id}')+ return []++ org_id = self.effective_org_id or user.current_org_id+ if not org_id:+ logger.debug(f'No org_id for user {user_id}')+ return []++ # Validate org_id is a valid UUID before calling get_org_by_id_async+ try:+ from uuid import UUID++ UUID(str(org_id))+ except (ValueError, AttributeError, TypeError) as uuid_error:+ logger.warning(+ f'Invalid org_id format for user {user_id}: {org_id} - {uuid_error}'+ )+ return []++ org = await OrgStore.get_org_by_id_async(org_id)+ if not org:+ logger.debug(f'Org {org_id} not found for user {user_id}')+ return []++ if org.registered_marketplaces:+ # Normalize: use 'org' scope for legacy data without scope+ normalized: list[dict[str, Any]] = []+ for mp in org.registered_marketplaces:+ if isinstance(mp, dict):+ # Set scope='org' if missing (backward compatibility)+ if mp.get('scope') is None:+ mp = {**mp, 'scope': 'org'}+ # Ensure auto_load defaults to False if missing+ if 'auto_load' not in mp:+ mp = {**mp, 'auto_load': False}+ normalized.append(mp)+ else:+ # Convert MarketplaceRegistration to dict+ normalized.append(mp.model_dump())+ return normalized+ return []+ except Exception as e:+ logger.error(f'Error fetching org marketplaces: {e}')+ return []+async def _ensure_api_key(self, item: Settings, org_id: str, openhands_type: bool = False) -> None:diff --git a/enterprise/storage/user_settings.py b/enterprise/storage/user_settings.pyindex 9eca2b31f6..362903fce9 100644--- a/enterprise/storage/user_settings.py+++ b/enterprise/storage/user_settings.py@@ -1,5 +1,6 @@from __future__ import annotations+import loggingfrom datetime import datetimefrom typing import Any@@ -11,6 +12,10 @@ from sqlalchemy.orm import Mapped, mapped_columnfrom storage.base import Basefrom storage.encrypt_utils import decrypt_legacy_value, encrypt_legacy_value+from openhands.app_server.settings.settings_models import MarketplaceRegistration++logger = logging.getLogger(__name__)+class UserSettings(Base):__tablename__ = 'user_settings'@@ -84,11 +89,36 @@ class UserSettings(Base):already_migrated: Mapped[bool | None] = mapped_column(nullable=True, default=False) # False = not migrated, True = migrated+ registered_marketplaces: Mapped[+ list[dict[str, Any] | MarketplaceRegistration] | None+ ] = mapped_column(JSON, nullable=True)def to_settings(self):- from openhands.app_server.settings.settings_models import Settings+ from openhands.app_server.settings.settings_models import (+ Settings,+ validate_and_convert_marketplaces,+ )++ # Normalize marketplace data: ensure scope='personal' for legacy data+ normalized_marketplaces = []+ for mp in self.registered_marketplaces or []:+ if isinstance(mp, dict):+ # Set scope='personal' if missing (backward compatibility)+ if mp.get('scope') is None:+ mp = {**mp, 'scope': 'personal'}+ # Ensure auto_load defaults to False if missing+ if 'auto_load' not in mp:+ mp = {**mp, 'auto_load': False}+ normalized_marketplaces.append(mp)++ # Validate marketplace data using shared utility+ marketplaces = validate_and_convert_marketplaces(+ normalized_marketplaces,+ source_name='user settings',+ )return Settings(agent_settings=self.agent_settings or {},conversation_settings=self.conversation_settings or {},+ registered_marketplaces=marketplaces,)diff --git a/enterprise/tests/unit/server/routes/test_org_defaults_settings.py b/enterprise/tests/unit/server/routes/test_org_defaults_settings.pyindex dbc1c94f0b..715ab2bf14 100644--- a/enterprise/tests/unit/server/routes/test_org_defaults_settings.py+++ b/enterprise/tests/unit/server/routes/test_org_defaults_settings.py@@ -2,15 +2,18 @@from unittest.mock import MagicMock-from pydantic import SecretStr+import pytest+from pydantic import SecretStr, ValidationErrorfrom server.constants import LITE_LLM_API_URLfrom server.routes.org_models import (MASKED_API_KEY,+ OrgAppSettingsUpdate,OrgDefaultsSettingsResponse,OrgUpdate,)from storage.org import Org+from openhands.app_server.settings.settings_models import MarketplaceRegistrationfrom openhands.sdk.settings import ACPAgentSettings@@ -213,3 +216,134 @@ def test_from_org_keeps_custom_base_url_that_is_not_provider_default():== 'https://company-proxy.internal/anthropic')assert response.search_api_key == '****1234'+++# --- Tests for OrgAppSettingsUpdate registered_marketplaces ---+++class TestOrgAppSettingsUpdateMarketplaceValidation:+ """Tests for registered_marketplaces in OrgAppSettingsUpdate."""++ def test_valid_marketplace_list(self):+ """Test that OrgAppSettingsUpdate accepts valid marketplace list."""+ update = OrgAppSettingsUpdate(+ registered_marketplaces=[+ MarketplaceRegistration(name='test', source='github:owner/repo')+ ]+ )+ assert len(update.registered_marketplaces) == 1+ assert update.registered_marketplaces[0].name == 'test'+ assert update.registered_marketplaces[0].source == 'github:owner/repo'++ def test_null_marketplaces_allowed(self):+ """Test that None is allowed for PATCH semantics (field not updated)."""+ update = OrgAppSettingsUpdate()+ assert update.registered_marketplaces is None++ def test_empty_list_valid(self):+ """Test that empty list is valid (explicitly clear marketplaces)."""+ update = OrgAppSettingsUpdate(registered_marketplaces=[])+ assert update.registered_marketplaces == []++ def test_invalid_marketplace_rejected(self):+ """Test that invalid marketplace source is rejected."""+ with pytest.raises(ValidationError):+ OrgAppSettingsUpdate(+ registered_marketplaces=[{'name': 'test', 'source': 'invalid!!source'}]+ )++ def test_multiple_valid_marketplaces(self):+ """Test that multiple valid marketplaces are accepted."""+ update = OrgAppSettingsUpdate(+ registered_marketplaces=[+ MarketplaceRegistration(+ name='marketplace-1',+ source='github:owner/repo1',+ auto_load=True,+ ),+ MarketplaceRegistration(+ name='marketplace-2',+ source='github:owner/repo2',+ ),+ ]+ )+ assert len(update.registered_marketplaces) == 2++ def test_marketplace_with_all_fields(self):+ """Test marketplace with all optional fields."""+ update = OrgAppSettingsUpdate(+ registered_marketplaces=[+ MarketplaceRegistration(+ name='full-featured',+ source='github:owner/repo',+ ref='v1.0.0',+ repo_path='marketplaces/plugins',+ auto_load=True,+ ),+ ]+ )+ assert update.registered_marketplaces[0].name == 'full-featured'+ assert update.registered_marketplaces[0].ref == 'v1.0.0'+ assert update.registered_marketplaces[0].repo_path == 'marketplaces/plugins'+ assert update.registered_marketplaces[0].auto_load is True+++class TestUpdateOrgAppSettingsRoute:+ """Route-level behavior for the POST /orgs/app handler."""++ @pytest.mark.asyncio+ async def test_concurrent_modification_maps_to_409(self):+ """A concurrent-modification conflict surfaces as HTTP 409, not 500."""+ from datetime import datetime, timezone+ from unittest.mock import AsyncMock++ from fastapi import HTTPException+ from server.routes.org_models import OrgConcurrentModificationError+ from server.routes.orgs import update_org_app_settings++ # Arrange - service raises the conflict; no marketplaces => no admin gate.+ now = datetime.now(timezone.utc)+ service = MagicMock()+ service.update_org_app_settings = AsyncMock(+ side_effect=OrgConcurrentModificationError(+ org_id='o1', expected_version=now, actual_version=now+ )+ )+ update_data = OrgAppSettingsUpdate(enable_proactive_conversation_starters=False)++ # Act & Assert+ with pytest.raises(HTTPException) as exc:+ await update_org_app_settings(+ update_data, MagicMock(), service=service, user_id='u1'+ )+ assert exc.value.status_code == 409++ @pytest.mark.asyncio+ async def test_marketplace_edit_requires_admin(self, monkeypatch):+ """Editing org marketplaces without EDIT_ORG_SETTINGS is blocked (403)."""+ from unittest.mock import AsyncMock++ import server.routes.orgs as orgs_module+ from fastapi import HTTPException+ from server.routes.orgs import update_org_app_settings++ # Arrange - deny the marketplace permission; the write must not happen.+ async def _deny(request, user_id, permission):+ raise HTTPException(status_code=403, detail='forbidden')++ monkeypatch.setattr(orgs_module, 'authorize_permission', _deny)+ service = MagicMock()+ service.update_org_app_settings = AsyncMock()+ update_data = OrgAppSettingsUpdate(+ registered_marketplaces=[+ MarketplaceRegistration(name='team', source='github:o/team')+ ]+ )++ # Act & Assert+ with pytest.raises(HTTPException) as exc:+ await update_org_app_settings(+ update_data, MagicMock(), service=service, user_id='u1'+ )+ assert exc.value.status_code == 403+ service.update_org_app_settings.assert_not_called()diff --git a/enterprise/tests/unit/storage/test_org_app_settings_store.py b/enterprise/tests/unit/storage/test_org_app_settings_store.pyindex 5250e3e453..a5514323a4 100644--- a/enterprise/tests/unit/storage/test_org_app_settings_store.py+++ b/enterprise/tests/unit/storage/test_org_app_settings_store.py@@ -15,6 +15,8 @@ from storage.org import Orgfrom storage.org_app_settings_store import OrgAppSettingsStorefrom storage.user import User+from openhands.app_server.settings.settings_models import MarketplaceRegistration+@pytest.fixtureasync def async_engine():@@ -174,3 +176,233 @@ async def test_update_org_app_settings_org_not_found(async_session_maker):# Assertassert result is None+++# Optimistic Locking Tests (proper conflict detection)+++async def test_update_succeeds_when_last_known_updated_at_matches(async_session_maker):+ """+ GIVEN: An organization exists with updated_at timestamp+ WHEN: update_org_app_settings is called with matching last_known_updated_at+ THEN: The update succeeds and updated_at changes+ """+ # Arrange+ async with async_session_maker() as session:+ org = Org(+ name='test-org',+ enable_proactive_conversation_starters=True,+ max_budget_per_task=10.0,+ )+ session.add(org)+ await session.commit()+ await session.refresh(org)++ original_updated_at = org.updated_at+ org_id = org.id++ # Small delay to ensure timestamp differs+ await session.commit()++ update_data = OrgAppSettingsUpdate(+ enable_proactive_conversation_starters=False,+ last_known_updated_at=original_updated_at,+ )++ # Act+ store = OrgAppSettingsStore(db_session=session)+ result = await store.update_org_app_settings(org_id, update_data)++ # Assert+ assert result is not None+ assert result.enable_proactive_conversation_starters is False+ assert result.updated_at > original_updated_at+++async def test_update_succeeds_without_last_known_updated_at(async_session_maker):+ """+ GIVEN: An organization exists+ WHEN: update_org_app_settings is called without last_known_updated_at+ THEN: The update succeeds (backward compatibility - no lock check)+ """+ # Arrange+ async with async_session_maker() as session:+ org = Org(+ name='test-org',+ enable_proactive_conversation_starters=True,+ max_budget_per_task=10.0,+ )+ session.add(org)+ await session.commit()+ org_id = org.id++ update_data = OrgAppSettingsUpdate(+ enable_proactive_conversation_starters=False,+ last_known_updated_at=None, # No lock check+ )++ # Act+ store = OrgAppSettingsStore(db_session=session)+ result = await store.update_org_app_settings(org_id, update_data)++ # Assert+ assert result is not None+ assert result.enable_proactive_conversation_starters is False+++async def test_update_raises_conflict_when_stale_last_known_updated_at(+ async_session_maker,+):+ """+ GIVEN: An organization exists and another request modified it+ WHEN: update_org_app_settings is called with stale last_known_updated_at+ THEN: OrgConcurrentModificationError is raised+ """+ from server.routes.org_models import OrgConcurrentModificationError++ # Arrange+ async with async_session_maker() as session:+ org = Org(+ name='test-org',+ enable_proactive_conversation_starters=True,+ max_budget_per_task=10.0,+ )+ session.add(org)+ await session.commit()+ await session.refresh(org)++ # Record the original updated_at (simulating what client read)+ stale_updated_at = org.updated_at+ org_id = org.id++ # Simulate another request modifying the org+ org.name = 'modified-by-another-request'+ await session.commit()+ await session.refresh(org)++ # Now org.updated_at is newer than stale_updated_at++ update_data = OrgAppSettingsUpdate(+ enable_proactive_conversation_starters=False,+ last_known_updated_at=stale_updated_at, # Stale - should raise conflict+ )++ # Act & Assert+ store = OrgAppSettingsStore(db_session=session)+ with pytest.raises(OrgConcurrentModificationError) as exc_info:+ await store.update_org_app_settings(org_id, update_data)++ # Verify error details+ assert exc_info.value.org_id == str(org_id)+ # The expected_version should be the stale timestamp (what the client sent)+ # Both should be equal to stale_updated_at (normalize timezone for comparison)+ assert exc_info.value.expected_version.replace(+ tzinfo=None+ ) == stale_updated_at.replace(tzinfo=None)+ # The actual_version should be different (current DB state after modification)+ assert exc_info.value.actual_version.replace(+ tzinfo=None+ ) != stale_updated_at.replace(tzinfo=None)+++async def test_optimistic_lock_with_timezone_aware_dates(async_session_maker):+ """+ GIVEN: An organization exists with timezone-aware updated_at+ WHEN: update_org_app_settings is called with timezone-naive last_known_updated_at+ THEN: The update succeeds (timezone-naive dates are converted to UTC for comparison)+ """+ # Arrange+ async with async_session_maker() as session:+ org = Org(+ name='test-org',+ enable_proactive_conversation_starters=True,+ max_budget_per_task=10.0,+ )+ session.add(org)+ await session.commit()+ await session.refresh(org)++ original_updated_at = org.updated_at+ org_id = org.id++ # Create a naive datetime (no timezone info) - same instant+ naive_updated_at = original_updated_at.replace(tzinfo=None)++ update_data = OrgAppSettingsUpdate(+ enable_proactive_conversation_starters=False,+ last_known_updated_at=naive_updated_at,+ )++ # Act+ store = OrgAppSettingsStore(db_session=session)+ result = await store.update_org_app_settings(org_id, update_data)++ # Assert+ assert result is not None+ assert result.enable_proactive_conversation_starters is False+++async def test_update_persists_marketplaces_with_org_scope(async_session_maker):+ """+ GIVEN: An organization exists+ WHEN: update_org_app_settings persists marketplaces+ THEN: They are stored as JSON with scope forced to 'org'+ """+ # Arrange+ async with async_session_maker() as session:+ org = Org(name='test-org')+ session.add(org)+ await session.commit()+ org_id = org.id++ update_data = OrgAppSettingsUpdate(+ registered_marketplaces=[+ MarketplaceRegistration(+ name='team', source='github:o/team', auto_load=True+ ),+ ]+ )++ # Act+ store = OrgAppSettingsStore(db_session=session)+ result = await store.update_org_app_settings(org_id, update_data)++ # Assert+ assert result is not None+ assert len(result.registered_marketplaces) == 1+ stored = result.registered_marketplaces[0]+ assert stored['name'] == 'team'+ assert stored['scope'] == 'org'+ assert stored['auto_load'] is True+++async def test_update_rejects_duplicate_marketplace_names(async_session_maker):+ """+ GIVEN: An organization exists+ WHEN: update_org_app_settings is given marketplaces with duplicate names+ THEN: A ValueError is raised before persisting+ """+ # Arrange+ async with async_session_maker() as session:+ org = Org(name='test-org')+ session.add(org)+ await session.commit()+ org_id = org.id++ update_data = OrgAppSettingsUpdate(+ registered_marketplaces=[+ MarketplaceRegistration(name='dup', source='github:o/a'),+ MarketplaceRegistration(name='dup', source='github:o/b'),+ ]+ )++ # Act & Assert+ store = OrgAppSettingsStore(db_session=session)+ with pytest.raises(ValueError, match='Duplicate marketplace name'):+ await store.update_org_app_settings(org_id, update_data)diff --git a/enterprise/tests/unit/test_saas_settings_store.py b/enterprise/tests/unit/test_saas_settings_store.pyindex 148ebaf013..352d98fa2c 100644--- a/enterprise/tests/unit/test_saas_settings_store.py+++ b/enterprise/tests/unit/test_saas_settings_store.py@@ -167,6 +167,9 @@ def settings_store(async_session_maker):del item_dict['secrets_store']if 'llm_profiles' in item_dict:del item_dict['llm_profiles']+ # inherited_marketplaces is computed at runtime, not persisted+ if 'inherited_marketplaces' in item_dict:+ del item_dict['inherited_marketplaces']# Encrypt the data before storingfor key in ('llm_api_key', 'search_api_key', 'sandbox_api_key'):diff --git a/frontend/__tests__/components/features/settings/delete-confirmation-modal.test.tsx b/frontend/__tests__/components/features/settings/delete-confirmation-modal.test.tsxnew file mode 100644index 0000000000..acd42c448b--- /dev/null+++ b/frontend/__tests__/components/features/settings/delete-confirmation-modal.test.tsx@@ -0,0 +1,93 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi, beforeEach } from "vitest";+import { DeleteConfirmationModal } from "#/components/features/settings/delete-confirmation-modal";++const onClose = vi.fn();+const onDelete = vi.fn();++beforeEach(() => {+ onClose.mockReset();+ onDelete.mockReset();+});++describe("DeleteConfirmationModal", () => {+ it("renders nothing when not open", () => {+ const { container } = render(+ <DeleteConfirmationModal+ isOpen={false}+ itemName="test-item"+ onClose={vi.fn()}+ onDelete={vi.fn()}+ />,+ );++ expect(container).toBeEmptyDOMElement();+ });++ it("renders title and message with item name", () => {+ render(+ <DeleteConfirmationModal+ isOpen={true}+ itemName="my-marketplace"+ onClose={onClose}+ onDelete={onDelete}+ />,+ );++ expect(+ screen.getByText("SETTINGS$DELETE_CONFIRMATION_TITLE"),+ ).toBeInTheDocument();+ // The message contains the itemName via interpolation+ expect(+ screen.getByText(/SETTINGS\$DELETE_CONFIRMATION_MESSAGE/i),+ ).toBeInTheDocument();+ });++ it("calls onDelete when delete button is clicked", async () => {+ render(+ <DeleteConfirmationModal+ isOpen={true}+ itemName="test-item"+ onClose={onClose}+ onDelete={onDelete}+ />,+ );++ await userEvent.click(screen.getByTestId("confirm-delete-button"));++ expect(onDelete).toHaveBeenCalledTimes(1);+ expect(onClose).not.toHaveBeenCalled();+ });++ it("calls onClose when cancel button is clicked", async () => {+ render(+ <DeleteConfirmationModal+ isOpen={true}+ itemName="test-item"+ onClose={onClose}+ onDelete={onDelete}+ />,+ );++ await userEvent.click(screen.getByRole("button", { name: "BUTTON$CANCEL" }));++ expect(onClose).toHaveBeenCalledTimes(1);+ expect(onDelete).not.toHaveBeenCalled();+ });++ it("disables buttons when isDeleting is true", () => {+ render(+ <DeleteConfirmationModal+ isOpen={true}+ itemName="test-item"+ onClose={onClose}+ onDelete={onDelete}+ isDeleting={true}+ />,+ );++ expect(screen.getByTestId("confirm-delete-button")).toBeDisabled();+ expect(screen.getByRole("button", { name: "BUTTON$CANCEL" })).toBeDisabled();+ });+});diff --git a/frontend/__tests__/components/features/settings/marketplace-modal.test.tsx b/frontend/__tests__/components/features/settings/marketplace-modal.test.tsxnew file mode 100644index 0000000000..c88e3bb831--- /dev/null+++ b/frontend/__tests__/components/features/settings/marketplace-modal.test.tsx@@ -0,0 +1,264 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi, beforeEach } from "vitest";+import { MarketplaceModal } from "#/components/features/settings/marketplace-modal";++const onClose = vi.fn();+const onSave = vi.fn();++const baseProps = {+ isOpen: true,+ mode: "add" as const,+ onClose,+ onSave,+ isSaving: false,+};++beforeEach(() => {+ onClose.mockReset();+ onSave.mockReset();+});++describe("MarketplaceModal", () => {+ it("renders nothing when not open", () => {+ const { container } = render(+ <MarketplaceModal {...baseProps} isOpen={false} />,+ );++ expect(container).toBeEmptyDOMElement();+ });++ it("renders form fields in add mode", () => {+ render(<MarketplaceModal {...baseProps} />);++ // Form fields are identified by their text content+ expect(screen.getByText("SETTINGS$MARKETPLACE_NAME")).toBeInTheDocument();+ expect(screen.getByText("SETTINGS$MARKETPLACE_SOURCE")).toBeInTheDocument();+ expect(screen.getByText("SETTINGS$MARKETPLACE_REF")).toBeInTheDocument();+ expect(+ screen.getByText("SETTINGS$MARKETPLACE_REPO_PATH"),+ ).toBeInTheDocument();+ });++ it("shows name required error when name is empty", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ // Click save without entering anything+ await user.click(screen.getByTestId("marketplace-save-button"));++ expect(+ screen.getByText("SETTINGS$MARKETPLACE_NAME_REQUIRED"),+ ).toBeInTheDocument();+ expect(onSave).not.toHaveBeenCalled();+ });++ it("shows name invalid error for invalid name format", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ // Find the name input by placeholder+ const nameInput = screen.getByPlaceholderText("e.g., my-skills");+ await user.type(nameInput, "123-invalid");+ await user.click(screen.getByTestId("marketplace-save-button"));++ expect(+ screen.getByText("SETTINGS$MARKETPLACE_NAME_INVALID"),+ ).toBeInTheDocument();+ expect(onSave).not.toHaveBeenCalled();+ });++ it("validates that onSave is not called when source is empty", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ // Fill in name but not source+ const nameInput = screen.getByPlaceholderText("e.g., my-skills");+ await user.type(nameInput, "valid-name");+ await user.click(screen.getByTestId("marketplace-save-button"));++ // onSave should NOT have been called due to validation+ expect(onSave).not.toHaveBeenCalled();+ });++ it("clears name error when user starts typing", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ // Trigger name required error+ await user.click(screen.getByTestId("marketplace-save-button"));+ expect(+ screen.getByText("SETTINGS$MARKETPLACE_NAME_REQUIRED"),+ ).toBeInTheDocument();++ // Start typing in name field+ const nameInput = screen.getByPlaceholderText("e.g., my-skills");+ await user.type(nameInput, "a");++ // Error should be cleared+ expect(+ screen.queryByText("SETTINGS$MARKETPLACE_NAME_REQUIRED"),+ ).not.toBeInTheDocument();+ });++ it("validates source before calling onSave", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ // Fill name but not source+ const nameInput = screen.getByPlaceholderText("e.g., my-skills");+ await user.type(nameInput, "valid-name");+ await user.click(screen.getByTestId("marketplace-save-button"));++ // onSave should not be called+ expect(onSave).not.toHaveBeenCalled();++ // After filling source, onSave should be called+ const sourceInput = screen.getByPlaceholderText("github:owner/repo");+ await user.type(sourceInput, "github:owner/repo");+ await user.click(screen.getByTestId("marketplace-save-button"));++ expect(onSave).toHaveBeenCalledTimes(1);+ });++ it("calls onSave with correct data when form is valid", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ await user.type(+ screen.getByPlaceholderText("e.g., my-skills"),+ "my-marketplace",+ );+ await user.type(+ screen.getByPlaceholderText("github:owner/repo"),+ "github:owner/repo",+ );+ await user.click(screen.getByTestId("marketplace-save-button"));++ expect(onSave).toHaveBeenCalledWith({+ name: "my-marketplace",+ source: "github:owner/repo",+ ref: undefined,+ repo_path: undefined,+ auto_load: false,+ });+ });++ it("rejects a URL entered in the repository path field", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ await user.type(+ screen.getByPlaceholderText("e.g., my-skills"),+ "oh-extensions",+ );+ await user.type(+ screen.getByPlaceholderText("github:owner/repo"),+ "github:OpenHands/extensions",+ );+ await user.type(+ screen.getByPlaceholderText("e.g., marketplaces/internal"),+ "https://github.com/OpenHands/extensions",+ );+ await user.click(screen.getByTestId("marketplace-save-button"));++ expect(+ screen.getByText("SETTINGS$MARKETPLACE_REPO_PATH_INVALID"),+ ).toBeInTheDocument();+ expect(onSave).not.toHaveBeenCalled();+ });++ it("accepts a relative subdirectory as the repository path", async () => {+ render(<MarketplaceModal {...baseProps} />);+ const user = userEvent.setup();++ await user.type(screen.getByPlaceholderText("e.g., my-skills"), "team");+ await user.type(+ screen.getByPlaceholderText("github:owner/repo"),+ "github:acme/monorepo",+ );+ await user.type(+ screen.getByPlaceholderText("e.g., marketplaces/internal"),+ "marketplaces/internal",+ );+ await user.click(screen.getByTestId("marketplace-save-button"));++ expect(onSave).toHaveBeenCalledWith(+ expect.objectContaining({ repo_path: "marketplaces/internal" }),+ );+ });++ it("does not render scope selector unless scope selection is allowed", () => {+ render(<MarketplaceModal {...baseProps} />);++ expect(+ screen.queryByTestId("marketplace-scope-select"),+ ).not.toBeInTheDocument();+ });++ it("renders scope selector when scope selection is allowed (add mode)", () => {+ render(<MarketplaceModal {...baseProps} allowScopeSelection />);++ expect(screen.getByTestId("marketplace-scope-select")).toBeInTheDocument();+ });++ it("includes the chosen scope in onSave when scope selection is allowed", async () => {+ render(<MarketplaceModal {...baseProps} allowScopeSelection />);+ const user = userEvent.setup();++ await user.type(screen.getByPlaceholderText("e.g., my-skills"), "team");+ await user.type(+ screen.getByPlaceholderText("github:owner/repo"),+ "github:owner/repo",+ );+ await user.selectOptions(+ screen.getByTestId("marketplace-scope-select"),+ "org",+ );+ await user.click(screen.getByTestId("marketplace-save-button"));++ expect(onSave).toHaveBeenCalledWith(+ expect.objectContaining({ name: "team", scope: "org" }),+ );+ });++ it("calls onClose when cancel is clicked", async () => {+ render(<MarketplaceModal {...baseProps} />);++ await userEvent.click(+ screen.getByRole("button", { name: "BUTTON$CANCEL" }),+ );++ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("disables buttons when isSaving is true", () => {+ render(<MarketplaceModal {...baseProps} isSaving={true} />);++ expect(screen.getByTestId("marketplace-save-button")).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "BUTTON$CANCEL" }),+ ).toBeDisabled();+ });++ it("renders in edit mode with read-only source", () => {+ render(+ <MarketplaceModal+ {...baseProps}+ mode="edit"+ marketplace={{+ name: "test-marketplace",+ source: "github:owner/repo",+ scope: "personal",+ }}+ />,+ );++ // Source field should be disabled in edit mode+ const sourceInput = screen.getByDisplayValue("github:owner/repo");+ expect(sourceInput).toBeDisabled();+ expect(+ screen.getByText("SETTINGS$MARKETPLACE_SOURCE_READONLY"),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/__tests__/hooks/query/use-organization-app-settings.test.tsx b/frontend/__tests__/hooks/query/use-organization-app-settings.test.tsxnew file mode 100644index 0000000000..abfc2f2876--- /dev/null+++ b/frontend/__tests__/hooks/query/use-organization-app-settings.test.tsx@@ -0,0 +1,150 @@+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { describe, expect, it, vi, beforeEach } from "vitest";+import { ReactNode } from "react";+import { useOrganizationAppSettings } from "#/hooks/query/use-organization-app-settings";+import { organizationService } from "#/api/organization-service/organization-service.api";++vi.mock("#/api/organization-service/organization-service.api", () => ({+ organizationService: {+ getOrganizationAppSettings: vi.fn(),+ },+}));++vi.mock("#/context/use-selected-organization", () => ({+ useSelectedOrganizationId: vi.fn(),+}));++import { useSelectedOrganizationId } from "#/context/use-selected-organization";++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });+ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+};++const mockResponse = {+ enable_proactive_conversation_starters: true,+ max_budget_per_task: 100,+ registered_marketplaces: [+ {+ name: "test-marketplace",+ source: "github:owner/repo",+ auto_load: true,+ scope: "org" as const,+ },+ ],+ updated_at: "2024-01-01T00:00:00Z",+};++describe("useOrganizationAppSettings", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("does not fetch when orgId is null", async () => {+ vi.mocked(useSelectedOrganizationId).mockReturnValue({ organizationId: null, setOrganizationId: vi.fn() });++ const { result } = renderHook(+ () => useOrganizationAppSettings(),+ { wrapper: createWrapper() },+ );++ expect(organizationService.getOrganizationAppSettings).not.toHaveBeenCalled();+ expect(result.current.isLoading).toBe(false);+ expect(result.current.data).toBeUndefined();+ });++ it("does not fetch when orgId is undefined", async () => {+ vi.mocked(useSelectedOrganizationId).mockReturnValue({ organizationId: null, setOrganizationId: vi.fn() });++ const { result } = renderHook(+ () => useOrganizationAppSettings(),+ { wrapper: createWrapper() },+ );++ expect(organizationService.getOrganizationAppSettings).not.toHaveBeenCalled();+ expect(result.current.isLoading).toBe(false);+ });++ it("fetches org app settings when orgId is provided", async () => {+ vi.mocked(useSelectedOrganizationId).mockReturnValue({ organizationId: "org-123", setOrganizationId: vi.fn() });+ vi.mocked(organizationService.getOrganizationAppSettings).mockResolvedValue(+ mockResponse,+ );++ const { result } = renderHook(+ () => useOrganizationAppSettings(),+ { wrapper: createWrapper() },+ );++ await waitFor(() => expect(result.current.isLoading).toBe(false));++ expect(+ organizationService.getOrganizationAppSettings,+ ).toHaveBeenCalled();+ expect(result.current.data).toEqual(mockResponse);+ expect(result.current.data?.registered_marketplaces).toHaveLength(1);+ });++ it("uses different query keys for different orgs", async () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });++ vi.mocked(useSelectedOrganizationId).mockReturnValue({ organizationId: "org-123", setOrganizationId: vi.fn() });+ vi.mocked(organizationService.getOrganizationAppSettings).mockResolvedValue({+ ...mockResponse,+ registered_marketplaces: [{ name: "marketplace-123", source: "github:org/123", auto_load: true, scope: "org" as const }],+ });++ const wrapper1 = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );++ const { result: result1, rerender } = renderHook(+ () => useOrganizationAppSettings(),+ { wrapper: wrapper1 },+ );++ await waitFor(() => expect(result1.current.isLoading).toBe(false));+ expect(result1.current.data?.registered_marketplaces?.[0]?.name).toBe("marketplace-123");++ // Change org - should create new query with different key+ vi.mocked(useSelectedOrganizationId).mockReturnValue({ organizationId: "org-456", setOrganizationId: vi.fn() });+ vi.mocked(organizationService.getOrganizationAppSettings).mockResolvedValue({+ ...mockResponse,+ registered_marketplaces: [{ name: "marketplace-456", source: "github:org/456", auto_load: true, scope: "org" as const }],+ });+ rerender();++ await waitFor(() => expect(result1.current.isLoading).toBe(false));+ expect(result1.current.data?.registered_marketplaces?.[0]?.name).toBe("marketplace-456");+ });++ it("handles fetch error", async () => {+ vi.mocked(useSelectedOrganizationId).mockReturnValue({ organizationId: "org-123", setOrganizationId: vi.fn() });+ const error = new Error("Failed to fetch");+ vi.mocked(organizationService.getOrganizationAppSettings).mockRejectedValue(+ error,+ );++ const { result } = renderHook(+ () => useOrganizationAppSettings(),+ { wrapper: createWrapper() },+ );++ await waitFor(() => expect(result.current.isError).toBe(true));++ expect(result.current.error).toBe(error);+ });+});diff --git a/frontend/__tests__/routes/skills-settings.test.tsx b/frontend/__tests__/routes/skills-settings.test.tsxnew file mode 100644index 0000000000..fb78d00647--- /dev/null+++ b/frontend/__tests__/routes/skills-settings.test.tsx@@ -0,0 +1,164 @@+import { render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import userEvent from "@testing-library/user-event";+import { createRoutesStub, Outlet } from "react-router";+import SkillsSettingsScreen from "#/routes/skills-settings";+import SettingsService from "#/api/settings-service/settings-service.api";+import OptionService from "#/api/option-service/option-service.api";+import * as orgStore from "#/stores/selected-organization-store";+import { organizationService } from "#/api/organization-service/organization-service.api";+import { MOCK_PERSONAL_ORG, MOCK_TEAM_ORG_ACME } from "#/mocks/org-handlers";+import type { WebClientConfig } from "#/api/option-service/option.types";++// Mock hooks+vi.mock("#/hooks/mutation/use-marketplace-mutations", () => ({+ useMarketplaceMutations: () => ({+ savePersonal: { mutate: vi.fn(), isPending: false },+ saveOrg: { mutate: vi.fn(), isPending: false },+ deletePersonal: { mutate: vi.fn(), isPending: false },+ deleteOrg: { mutate: vi.fn(), isPending: false },+ }),+}));++vi.mock("#/hooks/mutation/use-skill-mutations", () => ({+ useSkillMutations: () => ({+ saveDisabledSkills: { mutate: vi.fn(), isPending: false },+ }),+}));++const mockConfig: WebClientConfig = {+ app_mode: "oss",+ posthog_client_key: null,+ feature_flags: {+ enable_billing: false,+ hide_llm_settings: false,+ enable_jira: false,+ enable_jira_dc: false,+ enable_linear: false,+ hide_users_page: false,+ hide_billing_page: false,+ hide_integrations_page: false,+ enable_onboarding: false,+ },+ providers_configured: [],+ maintenance_start_time: null,+ auth_url: null,+ recaptcha_site_key: null,+ faulty_models: [],+ error_message: null,+ updated_at: new Date().toISOString(),+ github_app_slug: null,+};++const renderSkillsSettings = () => {+ const RouterStub = createRoutesStub([+ {+ Component: () => <Outlet />,+ path: "/settings",+ children: [+ {+ Component: SkillsSettingsScreen,+ path: "/settings/skills",+ },+ {+ Component: () => <div data-testid="skills-settings-screen" />,+ path: "/settings/skills",+ },+ ],+ },+ ]);++ return render(<RouterStub initialEntries={["/settings/skills"]} />, {+ wrapper: ({ children }) => (+ <QueryClientProvider+ client={+ new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ }+ >+ {children}+ </QueryClientProvider>+ ),+ });+};++beforeEach(() => {+ vi.spyOn(OptionService, "getConfig").mockResolvedValue(mockConfig);++ vi.spyOn(organizationService, "getMe").mockResolvedValue({+ org_id: "org-1",+ user_id: "user-1",+ email: "[email protected]",+ role: "admin",+ llm_api_key: "",+ max_iterations: 100,+ llm_model: "gpt-4",+ llm_base_url: "",+ status: "active",+ });++ orgStore.useSelectedOrganizationStore.setState({+ organizationId: null,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("hasMarketplaceChanges - auto_load toggle bug fix", () => {+ it("should normalize null, undefined, and false to false for comparison", () => {+ // The fix uses Boolean() to normalize all values to true/false+ const normalizeValue = (val: boolean | null | undefined) => Boolean(val);++ // Original value from backend (null/undefined)+ expect(normalizeValue(undefined)).toBe(false);+ expect(normalizeValue(null)).toBe(false);+ // After toggle off+ expect(normalizeValue(false)).toBe(false);+ // After toggle on+ expect(normalizeValue(true)).toBe(true);++ // null, undefined, false all normalize to false (no change)+ expect(normalizeValue(null)).toBe(normalizeValue(false));+ expect(normalizeValue(undefined)).toBe(normalizeValue(null));+ });++ it("should not detect change when toggling auto_load back to original state", () => {+ // Simulates the Boolean comparison logic in hasMarketplaceChanges+ const normalizeAutoLoad = (val: boolean | null | undefined) => Boolean(val);++ // After save, original is null/false → normalized to false+ // After second toggle, value is true → normalized to true+ // Then toggle back to false → normalized to false+ const currentValue = normalizeAutoLoad(false);+ const originalValue = normalizeAutoLoad(null);++ // Both normalize to false, so no change detected+ const hasChange = currentValue !== originalValue;+ expect(hasChange).toBe(false);+ });++ it("should detect change when auto_load is different from original", () => {+ const normalizeAutoLoad = (val: boolean | null | undefined) => Boolean(val);++ const currentValue = normalizeAutoLoad(true);+ const originalValue = normalizeAutoLoad(null);++ const hasChange = currentValue !== originalValue;+ expect(hasChange).toBe(true);+ });+});++describe("hasSkillChanges - enabled toggle bug fix", () => {+ it("should normalize isEnabled comparison correctly", () => {+ const normalizeBool = (val: boolean | undefined | null) => val ?? false;++ // Both should normalize to false+ expect(normalizeBool(false)).toBe(false);+ expect(normalizeBool(undefined)).toBe(false);+ expect(normalizeBool(null)).toBe(false);+ });+});diff --git a/frontend/src/api/organization-service/organization-service.api.ts b/frontend/src/api/organization-service/organization-service.api.tsindex 15d90dfbdc..16b980dcef 100644--- a/frontend/src/api/organization-service/organization-service.api.ts+++ b/frontend/src/api/organization-service/organization-service.api.ts@@ -8,7 +8,7 @@ import {OrganizationUserRole,UpdateOrganizationMemberParams,} from "#/types/org";-import { Settings } from "#/types/settings";+import { Settings, MarketplaceRegistration } from "#/types/settings";import { openHands } from "../open-hands-axios";type OrganizationSettingsResponse = Pick<@@ -19,6 +19,21 @@ type OrganizationSettingsResponse = Pick<| "llm_api_key_set">;+export type OrganizationAppSettingsResponse = {+ enable_proactive_conversation_starters: boolean;+ max_budget_per_task: number | null;+ registered_marketplaces: MarketplaceRegistration[];+ updated_at: string | null;+};++export type OrganizationAppSettingsUpdate = {+ enable_proactive_conversation_starters?: boolean;+ max_budget_per_task?: number | null;+ registered_marketplaces?: MarketplaceRegistration[] | null;+ /** For optimistic locking - must match current updated_at */+ last_known_updated_at?: string | null;+};+export const organizationService = {getMe: async ({ orgId }: { orgId: string }) => {const { data } = await openHands.get<OrganizationMember>(@@ -251,6 +266,23 @@ export const organizationService = {await openHands.delete(`/api/organizations/${orgId}/git-claims/${claimId}`);},+ getOrganizationAppSettings: async () => {+ const { data } = await openHands.get<OrganizationAppSettingsResponse>(+ "/api/organizations/app",+ );+ return data;+ },++ saveOrganizationAppSettings: async (+ settings: OrganizationAppSettingsUpdate,+ ) => {+ const { data } = await openHands.post<OrganizationAppSettingsResponse>(+ "/api/organizations/app",+ settings,+ );+ return data;+ },+// Organization Conversation APIsgetConversationStats: async ({ orgId }: { orgId: string }) => {const { data } = await openHands.get<OrgConversationStats>(diff --git a/frontend/src/api/skills-service.ts b/frontend/src/api/skills-service.tsindex e1c57d3ce4..c1aa45ce1d 100644--- a/frontend/src/api/skills-service.ts+++ b/frontend/src/api/skills-service.ts@@ -1,11 +1,22 @@import { openHands } from "./open-hands-axios";-import { SkillInfo } from "#/types/settings";+import {+ MarketplaceRegistration,+ MarketplacePluginInfo,+ SkillInfo,+} from "#/types/settings";interface SkillPage {items: SkillInfo[];next_page_id: string | null;}+export interface MarketplaceSkillsResponse {+ skills: SkillInfo[];+ plugins: MarketplacePluginInfo[];+ marketplace_skills: Record<string, string[]>;+ errors: string[];+}+class SkillsService {/*** Search available skills (global + user skills) with pagination@@ -16,6 +27,22 @@ class SkillsService {});return data.items;}++ /**+ * Get skills from marketplace repositories+ *+ * This endpoint fetches and returns skill metadata from marketplace repos+ * without requiring an active sandbox session.+ */+ static async getMarketplaceSkills(+ marketplaces: MarketplaceRegistration[],+ ): Promise<MarketplaceSkillsResponse> {+ const { data } = await openHands.post<MarketplaceSkillsResponse>(+ "/api/v1/skills/marketplace-skills",+ marketplaces,+ );+ return data;+ }}export default SkillsService;diff --git a/frontend/src/components/features/settings/delete-confirmation-modal.tsx b/frontend/src/components/features/settings/delete-confirmation-modal.tsxnew file mode 100644index 0000000000..e1d5e3bdb4--- /dev/null+++ b/frontend/src/components/features/settings/delete-confirmation-modal.tsx@@ -0,0 +1,66 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { BrandButton } from "#/components/features/settings/brand-button";+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";+import { I18nKey } from "#/i18n/declaration";++interface DeleteConfirmationModalProps {+ isOpen: boolean;+ itemName: string;+ onClose: () => void;+ onDelete: () => void;+ isDeleting?: boolean;+}++export function DeleteConfirmationModal({+ isOpen,+ itemName,+ onClose,+ onDelete,+ isDeleting = false,+}: DeleteConfirmationModalProps) {+ const { t } = useTranslation();++ if (!isOpen) return null;++ return (+ <ModalBackdrop>+ <div+ className="bg-base p-6 rounded-xl flex flex-col gap-4 border border-tertiary"+ style={{ width: "400px" }}+ >+ <h3 className="text-xl font-bold">+ {t(I18nKey.SETTINGS$DELETE_CONFIRMATION_TITLE)}+ </h3>++ <p className="text-sm text-tertiary-alt">+ {t(I18nKey.SETTINGS$DELETE_CONFIRMATION_MESSAGE, {+ name: itemName,+ })}+ </p>++ <div className="w-full flex gap-2 mt-2">+ <BrandButton+ type="button"+ variant="secondary"+ className="grow"+ onClick={onClose}+ isDisabled={isDeleting}+ >+ {t(I18nKey.BUTTON$CANCEL)}+ </BrandButton>+ <BrandButton+ testId="confirm-delete-button"+ type="button"+ variant="danger"+ className="grow"+ onClick={onDelete}+ isDisabled={isDeleting}+ >+ {isDeleting ? <span>...</span> : t(I18nKey.BUTTON$DELETE)}+ </BrandButton>+ </div>+ </div>+ </ModalBackdrop>+ );+}diff --git a/frontend/src/components/features/settings/info-tooltip.tsx b/frontend/src/components/features/settings/info-tooltip.tsxnew file mode 100644index 0000000000..942dc00de3--- /dev/null+++ b/frontend/src/components/features/settings/info-tooltip.tsx@@ -0,0 +1,29 @@+import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";+import InfoCircleIcon from "#/icons/info-circle.svg?react";++interface InfoTooltipProps {+ /** Explanatory text shown on hover. Also used as the icon's aria-label. */+ content: string;+}++/**+ * A small info icon that reveals an explanatory tooltip on hover. Centralizes+ * the tooltip's width, font size, and icon styling so settings tooltips stay+ * visually consistent (and long text wraps instead of stretching full-width).+ */+export function InfoTooltip({ content }: InfoTooltipProps) {+ return (+ <StyledTooltip+ content={content}+ placement="top"+ tooltipClassName="max-w-xs whitespace-normal text-xs"+ >+ <InfoCircleIcon+ width={14}+ height={14}+ className="text-tertiary-alt"+ aria-label={content}+ />+ </StyledTooltip>+ );+}diff --git a/frontend/src/components/features/settings/marketplace-modal.tsx b/frontend/src/components/features/settings/marketplace-modal.tsxnew file mode 100644index 0000000000..9619404657--- /dev/null+++ b/frontend/src/components/features/settings/marketplace-modal.tsx@@ -0,0 +1,344 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { BrandButton } from "#/components/features/settings/brand-button";+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";+import { InfoTooltip } from "#/components/features/settings/info-tooltip";+import { MarketplaceRegistration } from "#/types/settings";+import { I18nKey } from "#/i18n/declaration";+import { Typography } from "#/ui/typography";+import { cn } from "#/utils/utils";++/**+ * Best-effort marketplace name from a repository source, mirroring the backend+ * `_derive_name_from_source` (marketplace_composition.py): strip a `provider:`+ * prefix, take the last path segment, drop a trailing `.git`. The result is then+ * sanitized to the valid name pattern (`^[a-zA-Z][a-zA-Z0-9_-]*$`) so the derived+ * default is usually accepted as-is; on-save validation still guards edge cases.+ */+export function deriveMarketplaceName(source: string): string {+ let s = (source || "").trim();+ if (!s) return "";+ if (s.includes(":")) s = s.slice(s.indexOf(":") + 1);+ if (s.includes("/")) s = s.replace(/\/+$/, "").split("/").pop() ?? "";+ s = s.replace(/\.git$/i, "");+ return s+ .replace(/[^a-zA-Z0-9_-]+/g, "-")+ .replace(/^[^a-zA-Z]+/, "")+ .replace(/-+$/g, "");+}++interface MarketplaceModalProps {+ isOpen: boolean;+ mode: "add" | "edit";+ marketplace?: MarketplaceRegistration | null;+ /**+ * When true (admin adding in an org context), the modal shows an org/personal+ * scope selector. Otherwise the marketplace is added as personal.+ */+ allowScopeSelection?: boolean;+ onClose: () => void;+ onSave: (data: {+ name: string;+ source: string;+ ref?: string;+ repo_path?: string;+ auto_load?: boolean;+ scope?: "org" | "personal";+ }) => void;+ isSaving?: boolean;+}++export function MarketplaceModal({+ isOpen,+ mode,+ marketplace,+ allowScopeSelection = false,+ onClose,+ onSave,+ isSaving = false,+}: MarketplaceModalProps) {+ const { t } = useTranslation();+ const [name, setName] = React.useState(marketplace?.name || "");+ const [source, setSource] = React.useState(marketplace?.source || "");+ const [ref, setRef] = React.useState(marketplace?.ref || "");+ const [repoPath, setRepoPath] = React.useState(marketplace?.repo_path || "");+ const [autoLoad, setAutoLoad] = React.useState(!!marketplace?.auto_load);+ const [scope, setScope] = React.useState<"org" | "personal">("personal");+ // Tracks whether the user has hand-edited Name, so auto-derivation from the+ // repository stops clobbering an intentional name.+ const [nameEdited, setNameEdited] = React.useState(false);+ const [nameError, setNameError] = React.useState<string | null>(null);+ const [sourceError, setSourceError] = React.useState<string | null>(null);+ const [repoPathError, setRepoPathError] = React.useState<string | null>(null);++ // Reset form when modal opens/closes or marketplace changes+ React.useEffect(() => {+ if (isOpen) {+ setName(marketplace?.name || "");+ setSource(marketplace?.source || "");+ setRef(marketplace?.ref || "");+ setRepoPath(marketplace?.repo_path || "");+ setAutoLoad(!!marketplace?.auto_load);+ // Default new marketplaces to personal; admins can opt into org.+ setScope(marketplace?.scope === "org" ? "org" : "personal");+ // An existing (edit) name counts as user-owned; a fresh add starts clean.+ setNameEdited(Boolean(marketplace?.name));+ setNameError(null);+ setSourceError(null);+ setRepoPathError(null);+ }+ }, [isOpen, marketplace]);++ // Scope selection only applies when adding and the caller allows it.+ const showScopeSelector = mode === "add" && allowScopeSelection;++ const handleSave = () => {+ // Validate name on click+ if (!name.trim()) {+ setNameError(t(I18nKey.SETTINGS$MARKETPLACE_NAME_REQUIRED));+ return;+ }+ if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name.trim())) {+ setNameError(t(I18nKey.SETTINGS$MARKETPLACE_NAME_INVALID));+ return;+ }+ if (!source.trim()) {+ setSourceError(t(I18nKey.SETTINGS$MARKETPLACE_SOURCE_REQUIRED));+ return;+ }+ // Repository Path is an optional subdirectory *within* the repository+ // (e.g. "marketplaces/internal"), not a URL or absolute path. Catch the+ // common mistake of pasting the repository URL here before it reaches the+ // backend, where it would fail with a confusing "Repo path not found".+ const trimmedRepoPath = repoPath.trim();+ if (+ trimmedRepoPath &&+ (trimmedRepoPath.includes("://") ||+ trimmedRepoPath.startsWith("/") ||+ trimmedRepoPath.startsWith("\\") ||+ trimmedRepoPath.includes(".."))+ ) {+ setRepoPathError(t(I18nKey.SETTINGS$MARKETPLACE_REPO_PATH_INVALID));+ return;+ }+ setNameError(null);+ setRepoPathError(null);++ onSave({+ name: name.trim(),+ source: source.trim(),+ ref: ref.trim() || undefined,+ repo_path: trimmedRepoPath || undefined,+ auto_load: autoLoad,+ scope: showScopeSelector ? scope : undefined,+ });+ };++ if (!isOpen) return null;++ const isEdit = mode === "edit";++ const footer = (+ <div className="w-full flex gap-2 mt-2">+ <BrandButton+ type="button"+ variant="secondary"+ className="grow"+ onClick={onClose}+ isDisabled={isSaving}+ >+ {t(I18nKey.BUTTON$CANCEL)}+ </BrandButton>+ <BrandButton+ testId="marketplace-save-button"+ type="button"+ variant="primary"+ className="grow"+ onClick={handleSave}+ isDisabled={isSaving}+ >+ {isSaving ? <span>...</span> : t(I18nKey.BUTTON$SAVE)}+ </BrandButton>+ </div>+ );++ return (+ <ModalBackdrop>+ <div+ className="bg-base p-6 rounded-xl flex flex-col gap-4 border border-tertiary"+ style={{ width: "500px" }}+ >+ <h3 className="text-xl font-bold">+ {isEdit+ ? t(I18nKey.SETTINGS$MARKETPLACE_EDIT_TITLE)+ : t(I18nKey.SETTINGS$MARKETPLACE_ADD_TITLE)}+ </h3>++ {/* Repository (source) field - required, no default. Shown first so the+ Name below can be derived from it. Read-only in edit mode. */}+ <div className="flex flex-col gap-2">+ <label className="text-sm font-medium text-tertiary-alt">+ {t(I18nKey.SETTINGS$MARKETPLACE_SOURCE)}+ </label>+ <input+ type="text"+ value={source}+ onChange={(e) => {+ const nextSource = e.target.value;+ setSource(nextSource);+ setSourceError(null);+ // Pre-fill Name from the repository until the user edits Name.+ if (!isEdit && !nameEdited) {+ setName(deriveMarketplaceName(nextSource));+ setNameError(null);+ }+ }}+ placeholder="github:owner/repo"+ disabled={isEdit}+ readOnly={isEdit}+ className={cn(+ "bg-tertiary border border-[#717888] h-10 w-full rounded-sm p-2 placeholder:italic placeholder:text-tertiary-alt disabled:opacity-50 disabled:cursor-not-allowed",+ sourceError && "border-red-500",+ )}+ />+ {sourceError && (+ <Typography.Paragraph className="text-xs text-red-400">+ {sourceError}+ </Typography.Paragraph>+ )}+ {!sourceError && isEdit && (+ <Typography.Paragraph className="text-xs text-tertiary-alt">+ {t(I18nKey.SETTINGS$MARKETPLACE_SOURCE_READONLY)}+ </Typography.Paragraph>+ )}+ </div>++ {/* Name field - defaults to a value derived from the repository above. */}+ <div className="flex flex-col gap-2">+ <label className="text-sm font-medium text-tertiary-alt">+ {t(I18nKey.SETTINGS$MARKETPLACE_NAME)}+ </label>+ <input+ type="text"+ value={name}+ onChange={(e) => {+ setName(e.target.value);+ setNameEdited(true);+ setNameError(null);+ }}+ placeholder="e.g., my-skills"+ className={cn(+ "bg-tertiary border border-[#717888] h-10 w-full rounded-sm p-2 placeholder:italic placeholder:text-tertiary-alt",+ nameError && "border-red-500",+ )}+ />+ {nameError && (+ <Typography.Paragraph className="text-xs text-red-400">+ {nameError}+ </Typography.Paragraph>+ )}+ </div>++ {/* Scope selector - only when an admin adds in an org context */}+ {showScopeSelector && (+ <div className="flex flex-col gap-2">+ <label className="text-sm font-medium text-tertiary-alt">+ {t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_LABEL)}+ </label>+ <select+ data-testid="marketplace-scope-select"+ value={scope}+ onChange={(e) => setScope(e.target.value as "org" | "personal")}+ className="bg-tertiary border border-[#717888] h-10 w-full rounded-sm p-2"+ >+ <option value="personal">+ {t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_PERSONAL)}+ </option>+ <option value="org">+ {t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_ORG)}+ </option>+ </select>+ </div>+ )}++ {/* Ref field (optional) */}+ <div className="flex flex-col gap-2">+ <label className="text-sm font-medium text-tertiary-alt">+ {t(I18nKey.SETTINGS$MARKETPLACE_REF)}+ <span className="text-tertiary-alt font-normal ml-1">+ ({t(I18nKey.SETTINGS$OPTIONAL)})+ </span>+ </label>+ <input+ type="text"+ value={ref}+ onChange={(e) => setRef(e.target.value)}+ placeholder="e.g., main, develop, v1.0.0"+ className="bg-tertiary border border-[#717888] h-10 w-full rounded-sm p-2 placeholder:italic placeholder:text-tertiary-alt"+ />+ </div>++ {/* Repo path field (optional) */}+ <div className="flex flex-col gap-2">+ <label className="text-sm font-medium text-tertiary-alt">+ {t(I18nKey.SETTINGS$MARKETPLACE_REPO_PATH)}+ <span className="text-tertiary-alt font-normal ml-1">+ ({t(I18nKey.SETTINGS$OPTIONAL)})+ </span>+ </label>+ <input+ type="text"+ value={repoPath}+ onChange={(e) => {+ setRepoPath(e.target.value);+ setRepoPathError(null);+ }}+ placeholder="e.g., marketplaces/internal"+ className={cn(+ "bg-tertiary border border-[#717888] h-10 w-full rounded-sm p-2 placeholder:italic placeholder:text-tertiary-alt",+ repoPathError && "border-red-500",+ )}+ />+ {repoPathError && (+ <Typography.Paragraph className="text-xs text-red-400">+ {repoPathError}+ </Typography.Paragraph>+ )}+ </div>++ {/* Auto-load toggle */}+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-1.5">+ <label className="text-sm font-medium text-tertiary-alt">+ {t(I18nKey.SETTINGS$MARKETPLACE_AUTO_LOAD)}+ </label>+ <InfoTooltip content={t(I18nKey.SETTINGS$AUTO_LOAD_TOOLTIP)} />+ </div>+ <button+ type="button"+ onClick={() => setAutoLoad(!autoLoad)}+ aria-label={t(I18nKey.SETTINGS$MARKETPLACE_AUTO_LOAD)}+ className="cursor-pointer"+ >+ <div+ className={cn(+ "w-12 h-6 rounded-xl flex items-center p-1.5",+ autoLoad && "justify-end bg-white",+ !autoLoad && "justify-start bg-base-secondary",+ )}+ >+ <div+ className={cn(+ "w-3 h-3 rounded-xl",+ autoLoad ? "bg-[#0D0F11]" : "bg-tertiary-light",+ )}+ />+ </div>+ </button>+ </div>++ {footer}+ </div>+ </ModalBackdrop>+ );+}diff --git a/frontend/src/components/features/settings/skills-settings/marketplace-table.tsx b/frontend/src/components/features/settings/skills-settings/marketplace-table.tsxnew file mode 100644index 0000000000..ca9f933db5--- /dev/null+++ b/frontend/src/components/features/settings/skills-settings/marketplace-table.tsx@@ -0,0 +1,204 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { MarketplaceRegistration } from "#/types/settings";+import { Toggle } from "#/components/shared/toggle/toggle";+import { InfoTooltip } from "#/components/features/settings/info-tooltip";+import { I18nKey } from "#/i18n/declaration";+import { cn } from "#/utils/utils";+import EditIcon from "#/icons/u-edit.svg?react";+import DeleteIcon from "#/icons/u-delete.svg?react";++interface MarketplaceTableProps {+ marketplaces: MarketplaceRegistration[];+ onToggleAutoLoad: (name: string) => void;+ onEdit: (marketplace: MarketplaceRegistration) => void;+ onDelete: (marketplace: MarketplaceRegistration) => void;+ canEdit: (marketplace: MarketplaceRegistration) => boolean;+ getAutoLoadTitle: (+ scope: "instance" | "org" | "personal",+ ) => string | undefined;+ isAdminOrOwner: boolean;+}++function ScopeBadge({ scope }: { scope: "instance" | "org" | "personal" }) {+ const { t } = useTranslation();+ const label = {+ instance: t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_INSTANCE),+ org: t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_ORG),+ personal: t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_PERSONAL),+ }[scope];++ return (+ <span+ className={cn(+ "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",+ scope === "instance" && "bg-tertiary/60 text-tertiary-light",+ scope === "org" && "bg-blue-500/15 text-blue-300",+ scope === "personal" && "bg-success/15 text-success",+ )}+ >+ {label}+ </span>+ );+}++const HEADER_CLASS =+ "px-4 py-3 text-left text-xs font-medium text-tertiary-alt whitespace-nowrap";+const CELL_CLASS = "px-4 py-3 align-middle";++export function MarketplaceTable({+ marketplaces,+ onToggleAutoLoad,+ onEdit,+ onDelete,+ canEdit,+ getAutoLoadTitle,+ isAdminOrOwner,+}: MarketplaceTableProps) {+ const { t } = useTranslation();++ return (+ <div className="overflow-hidden rounded-xl border border-tertiary bg-base-secondary/20 table-box-shadow">+ <div className="overflow-x-auto">+ <table className="w-full min-w-[760px] table-fixed border-collapse text-sm">+ <colgroup>+ <col className="w-[17%]" />+ <col className="w-[21%]" />+ <col className="w-[15%]" />+ <col className="w-[15%]" />+ <col className="w-[11%]" />+ <col className="w-[10%]" />+ <col className="w-[11%]" />+ </colgroup>+ <thead>+ <tr className="border-b border-tertiary bg-base-secondary/50">+ <th className={HEADER_CLASS}>+ {t(I18nKey.SETTINGS$MARKETPLACE_NAME)}+ </th>+ <th className={HEADER_CLASS}>+ {t(I18nKey.SETTINGS$MARKETPLACE_SOURCE)}+ </th>+ <th className={HEADER_CLASS}>+ {t(I18nKey.SETTINGS$MARKETPLACE_REF)}+ </th>+ <th className={HEADER_CLASS}>+ {t(I18nKey.SETTINGS$MARKETPLACE_REPO_PATH)}+ </th>+ <th className={HEADER_CLASS}>+ {t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_LABEL)}+ </th>+ <th className={HEADER_CLASS}>+ <span className="inline-flex items-center gap-1.5">+ {t(I18nKey.SETTINGS$AUTO_LOAD)}+ <InfoTooltip+ content={t(I18nKey.SETTINGS$AUTO_LOAD_TOOLTIP)}+ />+ </span>+ </th>+ <th className={cn(HEADER_CLASS, "text-right")}>+ {t(I18nKey.SETTINGS$ACTIONS)}+ </th>+ </tr>+ </thead>+ <tbody>+ {marketplaces.map((mp) => (+ <tr+ key={mp.name}+ className="border-t border-tertiary/60 transition-colors hover:bg-base-secondary/40"+ >+ <td+ className={cn(CELL_CLASS, "font-medium text-content-2")}+ title={mp.name}+ >+ <span className="block truncate">{mp.name}</span>+ </td>+ <td className={cn(CELL_CLASS, "text-tertiary-alt")}>+ <span className="block truncate" title={mp.source}>+ {mp.source}+ </span>+ </td>+ <td className={cn(CELL_CLASS, "text-tertiary-alt")}>+ <span className="block truncate" title={mp.ref || undefined}>+ {mp.ref || "—"}+ </span>+ </td>+ <td className={cn(CELL_CLASS, "text-tertiary-alt")}>+ <span+ className="block truncate"+ title={mp.repo_path || undefined}+ >+ {mp.repo_path || "—"}+ </span>+ </td>+ <td className={CELL_CLASS}>+ <ScopeBadge scope={mp.scope ?? "personal"} />+ </td>+ <td className={CELL_CLASS}>+ <Toggle+ checked={!!mp.auto_load}+ disabled={+ mp.scope === "instance" ||+ (mp.scope === "org" && !isAdminOrOwner)+ }+ onClick={+ mp.scope !== "instance" &&+ (mp.scope === "personal" || isAdminOrOwner)+ ? () => onToggleAutoLoad(mp.name)+ : undefined+ }+ title={getAutoLoadTitle(mp.scope ?? "personal")}+ aria-label={`Toggle auto-load for ${mp.name}`}+ />+ </td>+ <td className={CELL_CLASS}>+ <div className="flex items-center justify-end gap-1">+ <button+ type="button"+ onClick={() => onEdit(mp)}+ disabled={!canEdit(mp)}+ title={canEdit(mp) ? t(I18nKey.BUTTON$EDIT) : undefined}+ aria-label={`${t(I18nKey.BUTTON$EDIT)} ${mp.name}`}+ className={cn(+ "rounded-md p-1.5 transition-colors",+ canEdit(mp)+ ? "text-tertiary-light hover:bg-white/10 hover:text-content-2"+ : "cursor-not-allowed text-tertiary-alt opacity-40",+ )}+ >+ <EditIcon width={16} height={16} />+ </button>+ <button+ type="button"+ onClick={() => onDelete(mp)}+ disabled={!canEdit(mp)}+ title={canEdit(mp) ? t(I18nKey.BUTTON$DELETE) : undefined}+ aria-label={`${t(I18nKey.BUTTON$DELETE)} ${mp.name}`}+ className={cn(+ "rounded-md p-1.5 transition-colors",+ canEdit(mp)+ ? "text-danger hover:bg-danger/15"+ : "cursor-not-allowed text-tertiary-alt opacity-40",+ )}+ >+ <DeleteIcon width={16} height={16} />+ </button>+ </div>+ </td>+ </tr>+ ))}+ {marketplaces.length === 0 && (+ <tr className="border-t border-tertiary/60">+ <td+ colSpan={7}+ className="px-4 py-10 text-center text-sm text-tertiary-alt"+ >+ {t(I18nKey.SETTINGS$MARKETPLACE_ADD_FIRST)}+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/features/settings/skills-settings/skills-table.tsx b/frontend/src/components/features/settings/skills-settings/skills-table.tsxnew file mode 100644index 0000000000..752d7b4f18--- /dev/null+++ b/frontend/src/components/features/settings/skills-settings/skills-table.tsx@@ -0,0 +1,190 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { SkillWithState } from "#/types/settings";+import { Toggle } from "#/components/shared/toggle/toggle";+import { InfoTooltip } from "#/components/features/settings/info-tooltip";+import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";+import { I18nKey } from "#/i18n/declaration";+import { cn } from "#/utils/utils";++interface SkillsTableProps {+ skills: SkillWithState[];+ onToggle: (skillId: string) => void;+ typeOptions: { key: string; label: string }[];+ repositoryOptions: { key: string; label: string }[];+ searchQuery: string;+ onSearchChange: (query: string) => void;+ onTypeChange: (type: string | null) => void;+ onRepositoryChange: (repo: string | null) => void;+}++function ScopeBadge({ scope }: { scope: "instance" | "org" | "personal" }) {+ const { t } = useTranslation();+ const label = {+ instance: t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_INSTANCE),+ org: t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_ORG),+ personal: t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_PERSONAL),+ }[scope];++ return (+ <span+ className={cn(+ "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",+ scope === "instance" && "bg-tertiary/60 text-tertiary-light",+ scope === "org" && "bg-blue-500/15 text-blue-300",+ scope === "personal" && "bg-success/15 text-success",+ )}+ >+ {label}+ </span>+ );+}++const HEADER_CLASS =+ "px-4 py-3 text-left text-xs font-medium text-tertiary-alt whitespace-nowrap";+const CELL_CLASS = "px-4 py-3 align-middle";++export function SkillsTable({+ skills,+ onToggle,+ typeOptions,+ repositoryOptions,+ searchQuery,+ onSearchChange,+ onTypeChange,+ onRepositoryChange,+}: SkillsTableProps) {+ const { t } = useTranslation();++ return (+ <div className="flex flex-col gap-4">+ {/* Filters */}+ <div className="flex flex-col gap-3 sm:flex-row sm:items-end">+ <input+ data-testid="search-skills-input"+ type="text"+ placeholder={t(I18nKey.SETTINGS$SEARCH_PLACEHOLDER)}+ aria-label={t(I18nKey.SETTINGS$SEARCH_PLACEHOLDER)}+ value={searchQuery}+ onChange={(e) => onSearchChange(e.target.value)}+ className="h-10 w-full flex-1 rounded-sm border border-[#717888] bg-tertiary p-2 placeholder:italic placeholder:text-tertiary-alt focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"+ />+ <div className="w-full sm:w-52">+ <SettingsDropdownInput+ testId="type-filter-dropdown"+ name="type-filter"+ label={t(I18nKey.SETTINGS$TYPE)}+ items={typeOptions}+ defaultSelectedKey="all"+ onSelectionChange={(key) => onTypeChange(key?.toString() ?? null)}+ placeholder={t(I18nKey.SETTINGS$ALL_TYPES)}+ />+ </div>+ <div className="w-full sm:w-52">+ <SettingsDropdownInput+ testId="repository-filter-dropdown"+ name="repository-filter"+ label={t(I18nKey.SETTINGS$REPOSITORY)}+ items={repositoryOptions}+ defaultSelectedKey="all"+ onSelectionChange={(key) =>+ onRepositoryChange(key?.toString() ?? null)+ }+ placeholder={t(I18nKey.SETTINGS$ALL_REPOSITORIES)}+ />+ </div>+ </div>++ {/* Table */}+ <div className="overflow-hidden rounded-xl border border-tertiary bg-base-secondary/20 table-box-shadow">+ <div className="overflow-x-auto">+ <table className="w-full min-w-[640px] table-fixed border-collapse text-sm">+ <colgroup>+ <col className="w-[28%]" />+ <col className="w-[30%]" />+ <col className="w-[16%]" />+ <col className="w-[16%]" />+ <col className="w-[10%]" />+ </colgroup>+ <thead>+ <tr className="border-b border-tertiary bg-base-secondary/50">+ <th className={HEADER_CLASS}>{t(I18nKey.SETTINGS$NAME)}</th>+ <th className={HEADER_CLASS}>+ {t(I18nKey.SETTINGS$MARKETPLACE_SOURCE)}+ </th>+ <th className={HEADER_CLASS}>{t(I18nKey.SETTINGS$TYPE)}</th>+ <th className={HEADER_CLASS}>+ {t(I18nKey.SETTINGS$MARKETPLACE_SCOPE_LABEL)}+ </th>+ <th className={HEADER_CLASS}>+ <span className="inline-flex items-center gap-1.5">+ {t(I18nKey.SETTINGS$ENABLED)}+ <InfoTooltip+ content={t(I18nKey.SETTINGS$ENABLED_TOOLTIP)}+ />+ </span>+ </th>+ </tr>+ </thead>+ <tbody>+ {skills.map((skill) => (+ <tr+ key={skill.id}+ className="border-t border-tertiary/60 transition-colors hover:bg-base-secondary/40"+ >+ <td+ className={cn(CELL_CLASS, "font-medium text-content-2")}+ title={skill.name}+ >+ <span className="block truncate">{skill.name}</span>+ </td>+ <td className={cn(CELL_CLASS, "text-tertiary-alt")}>+ <span className="block truncate" title={skill.repository}>+ {skill.repository}+ </span>+ </td>+ <td className={CELL_CLASS}>+ <span className="inline-flex items-center rounded-full bg-tertiary/60 px-2.5 py-0.5 text-xs font-medium text-tertiary-light">+ {skill.type}+ </span>+ </td>+ <td className={CELL_CLASS}>+ <ScopeBadge scope={skill.scope} />+ </td>+ <td className={CELL_CLASS}>+ {skill.type === "plugin" ? (+ // Plugins are enabled via their marketplace's Auto-Load+ // toggle, so this reflects that state read-only.+ <Toggle+ checked={skill.isAutoLoad}+ disabled+ title={t(I18nKey.SETTINGS$PLUGIN_AUTOLOAD_READONLY)}+ aria-label={`Auto-load state for ${skill.name}`}+ />+ ) : (+ <Toggle+ checked={skill.isEnabled}+ onClick={() => onToggle(skill.id)}+ aria-label={`Toggle enabled for ${skill.name}`}+ />+ )}+ </td>+ </tr>+ ))}+ {skills.length === 0 && (+ <tr className="border-t border-tertiary/60">+ <td+ colSpan={5}+ className="px-4 py-10 text-center text-sm text-tertiary-alt"+ >+ {t(I18nKey.SETTINGS$NO_SKILLS_MATCH_FILTERS)}+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/shared/toggle/toggle.tsx b/frontend/src/components/shared/toggle/toggle.tsxnew file mode 100644index 0000000000..0625dcc375--- /dev/null+++ b/frontend/src/components/shared/toggle/toggle.tsx@@ -0,0 +1,44 @@+import { cn } from "#/utils/utils";++interface ToggleProps {+ checked: boolean;+ onClick?: () => void;+ disabled?: boolean;+ "aria-label"?: string;+ title?: string;+}++export function Toggle({+ checked,+ onClick,+ disabled,+ "aria-label": ariaLabel,+ title,+}: ToggleProps) {+ return (+ <button+ type="button"+ onClick={disabled ? undefined : onClick}+ className={cn("cursor-pointer", disabled && "cursor-not-allowed")}+ aria-label={ariaLabel}+ disabled={disabled}+ title={title}+ >+ <div+ className={cn(+ "w-12 h-6 rounded-xl flex items-center p-1.5",+ checked && "justify-end bg-white",+ !checked && "justify-start bg-base-secondary",+ disabled && "opacity-50",+ )}+ >+ <div+ className={cn(+ "w-3 h-3 rounded-xl",+ checked ? "bg-[#0D0F11]" : "bg-tertiary-light",+ )}+ />+ </div>+ </button>+ );+}diff --git a/frontend/src/hooks/mutation/use-get-marketplace-skills.ts b/frontend/src/hooks/mutation/use-get-marketplace-skills.tsnew file mode 100644index 0000000000..80bdf6edf5--- /dev/null+++ b/frontend/src/hooks/mutation/use-get-marketplace-skills.ts@@ -0,0 +1,11 @@+import { useMutation } from "@tanstack/react-query";+import SkillsService, { MarketplaceSkillsResponse } from "#/api/skills-service";+import { MarketplaceRegistration } from "#/types/settings";++export const useMarketplaceSkills = () =>+ useMutation({+ mutationFn: async (+ marketplaces: MarketplaceRegistration[],+ ): Promise<MarketplaceSkillsResponse> =>+ SkillsService.getMarketplaceSkills(marketplaces),+ });diff --git a/frontend/src/hooks/mutation/use-marketplace-mutations.ts b/frontend/src/hooks/mutation/use-marketplace-mutations.tsnew file mode 100644index 0000000000..6db0ba442d--- /dev/null+++ b/frontend/src/hooks/mutation/use-marketplace-mutations.ts@@ -0,0 +1,228 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { AxiosError } from "axios";+import SettingsService from "#/api/settings-service/settings-service.api";+import { organizationService } from "#/api/organization-service/organization-service.api";+import { MarketplaceRegistration } from "#/types/settings";+import {+ displayErrorToast,+ displaySuccessToast,+} from "#/utils/custom-toast-handlers";+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import { I18nKey } from "#/i18n/declaration";+import { useSelectedOrganizationId } from "#/context/use-selected-organization";+import {+ ORGANIZATION_APP_SETTINGS_KEYS,+ SETTINGS_QUERY_KEYS,+} from "#/hooks/query/query-keys";+import { useMarketplaceSkills } from "./use-get-marketplace-skills";++export interface MarketplaceMutationsOptions {+ onSuccess?: () => void;+ onSettled?: () => void;+}++export interface UseMarketplaceMutationsReturn {+ savePersonal: ReturnType<+ typeof useMutation<unknown, Error, MarketplaceRegistration[]>+ >;+ saveOrg: ReturnType<+ typeof useMutation<+ unknown,+ AxiosError,+ {+ marketplaces: MarketplaceRegistration[];+ lastKnownUpdatedAt: string | null;+ }+ >+ >;+ deletePersonal: ReturnType<typeof useMutation<unknown, Error, string>>;+ deleteOrg: ReturnType<+ typeof useMutation<+ unknown,+ AxiosError,+ { marketplaceName: string; lastKnownUpdatedAt: string | null }+ >+ >;+}++/**+ * Hook for marketplace CRUD operations.+ * Handles both personal (user settings) and org (app settings) marketplaces.+ * Follows repo pattern: onSuccess/onError callbacks, meta: { disableToast: true }+ */+export function useMarketplaceMutations(+ options: MarketplaceMutationsOptions = {},+): UseMarketplaceMutationsReturn {+ const queryClient = useQueryClient();+ const { t } = useTranslation();+ const { organizationId } = useSelectedOrganizationId();+ const marketplaceSkillsMutation = useMarketplaceSkills();++ // Save personal marketplace mutation+ const savePersonal = useMutation({+ mutationFn: async (marketplaces: MarketplaceRegistration[]) => {+ // Validate marketplace before saving+ if (marketplaces.length > 0) {+ const preview =+ await marketplaceSkillsMutation.mutateAsync(marketplaces);+ if (preview.errors?.length) {+ throw new Error(`Validation failed: ${preview.errors.join(", ")}`);+ }+ }+ // Backend will automatically set scope='personal' for user settings+ await SettingsService.saveSettings({+ registered_marketplaces: marketplaces,+ });+ },+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.SETTINGS$SAVED));+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });+ queryClient.invalidateQueries({ queryKey: ["skills"] });+ options.onSuccess?.();+ },+ onError: (error: Error) => {+ // Surface the backend detail (e.g. duplicate-name) for Axios errors;+ // fall back to the thrown message for local validation errors.+ const message =+ error instanceof AxiosError+ ? retrieveAxiosErrorMessage(error)+ : error.message;+ displayErrorToast(message || t(I18nKey.ERROR$GENERIC));+ },+ onSettled: options.onSettled,+ meta: { disableToast: true },+ });++ // Save org marketplace mutation with 409 conflict handling+ const saveOrg = useMutation({+ mutationFn: async ({+ marketplaces,+ lastKnownUpdatedAt,+ }: {+ marketplaces: MarketplaceRegistration[];+ lastKnownUpdatedAt: string | null;+ }) => {+ // Validate marketplace before saving+ if (marketplaces.length > 0) {+ const preview =+ await marketplaceSkillsMutation.mutateAsync(marketplaces);+ if (preview.errors?.length) {+ throw new Error(`Validation failed: ${preview.errors.join(", ")}`);+ }+ }+ // Backend will automatically set scope='org' for org settings+ return organizationService.saveOrganizationAppSettings({+ registered_marketplaces: marketplaces,+ last_known_updated_at: lastKnownUpdatedAt,+ });+ },+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.SETTINGS$SAVED));+ // Invalidate both org settings and user settings (which has inherited_marketplaces)+ queryClient.invalidateQueries({+ queryKey: ORGANIZATION_APP_SETTINGS_KEYS.byOrg(organizationId),+ });+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });+ queryClient.invalidateQueries({ queryKey: ["skills"] });+ options.onSuccess?.();+ },+ onError: (error: AxiosError) => {+ if (error.response?.status === 409) {+ // Concurrent modification - refetch and retry once+ queryClient.invalidateQueries({+ queryKey: ORGANIZATION_APP_SETTINGS_KEYS.byOrg(organizationId),+ });+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });+ displayErrorToast("Settings were modified. Please retry.");+ } else {+ displayErrorToast(+ retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),+ );+ }+ },+ onSettled: options.onSettled,+ meta: { disableToast: true },+ });++ // Delete personal marketplace mutation+ // Fetches fresh state at mutation time to avoid stale closure issues+ const deletePersonal = useMutation({+ mutationFn: async (marketplaceName: string) => {+ const settings = await SettingsService.getSettings();+ // Name is the marketplace identity (unique across scopes).+ const updated = (settings.registered_marketplaces || []).filter(+ (mp) => mp.name !== marketplaceName,+ );+ // Backend will automatically set scope='personal' for user settings+ await SettingsService.saveSettings({+ registered_marketplaces: updated,+ });+ },+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.SETTINGS$SAVED));+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });+ queryClient.invalidateQueries({ queryKey: ["skills"] });+ options.onSuccess?.();+ },+ onError: (error: Error) => {+ const message =+ error instanceof AxiosError+ ? retrieveAxiosErrorMessage(error)+ : error.message;+ displayErrorToast(message || t(I18nKey.ERROR$GENERIC));+ },+ onSettled: options.onSettled,+ meta: { disableToast: true },+ });++ // Delete org marketplace mutation with 409 conflict handling+ // Fetches fresh state at mutation time to avoid stale closure issues+ const deleteOrg = useMutation({+ mutationFn: async ({+ marketplaceName,+ lastKnownUpdatedAt,+ }: {+ marketplaceName: string;+ lastKnownUpdatedAt: string | null;+ }) => {+ const settings = await organizationService.getOrganizationAppSettings();+ // Name is the marketplace identity (unique across scopes).+ const updated = (settings.registered_marketplaces || []).filter(+ (mp) => mp.name !== marketplaceName,+ );+ // Backend will automatically set scope='org' for org settings+ return organizationService.saveOrganizationAppSettings({+ registered_marketplaces: updated,+ last_known_updated_at: lastKnownUpdatedAt,+ });+ },+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.SETTINGS$SAVED));+ // Invalidate both org settings and user settings (which has inherited_marketplaces)+ queryClient.invalidateQueries({+ queryKey: ORGANIZATION_APP_SETTINGS_KEYS.byOrg(organizationId),+ });+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });+ queryClient.invalidateQueries({ queryKey: ["skills"] });+ options.onSuccess?.();+ },+ onError: (error: AxiosError) => {+ if (error.response?.status === 409) {+ queryClient.invalidateQueries({+ queryKey: ORGANIZATION_APP_SETTINGS_KEYS.byOrg(organizationId),+ });+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });+ displayErrorToast("Settings were modified. Please retry.");+ } else {+ displayErrorToast(+ retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),+ );+ }+ },+ onSettled: options.onSettled,+ meta: { disableToast: true },+ });++ return { savePersonal, saveOrg, deletePersonal, deleteOrg };+}diff --git a/frontend/src/hooks/mutation/use-skill-mutations.ts b/frontend/src/hooks/mutation/use-skill-mutations.tsnew file mode 100644index 0000000000..d853a07c99--- /dev/null+++ b/frontend/src/hooks/mutation/use-skill-mutations.ts@@ -0,0 +1,47 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { AxiosError } from "axios";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ displaySuccessToast,+ displayErrorToast,+} from "#/utils/custom-toast-handlers";+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import { I18nKey } from "#/i18n/declaration";+import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";++export interface UseSkillMutationsReturn {+ saveDisabledSkills: ReturnType<+ typeof useMutation<unknown, AxiosError, string[]>+ >;+}++/**+ * Hook for skill-related mutations.+ * Handles saving disabled_skills state.+ */+export function useSkillMutations(+ options: { onSettled?: () => void } = {},+): UseSkillMutationsReturn {+ const queryClient = useQueryClient();+ const { t } = useTranslation();++ const saveDisabledSkills = useMutation({+ mutationFn: async (disabledSkills: string[]) => {+ await SettingsService.saveSettings({ disabled_skills: disabledSkills });+ },+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.SETTINGS$SAVED));+ queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });+ },+ onError: (error: AxiosError) => {+ displayErrorToast(+ retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),+ );+ },+ onSettled: options.onSettled,+ meta: { disableToast: true },+ });++ return { saveDisabledSkills };+}diff --git a/frontend/src/hooks/query/query-keys.ts b/frontend/src/hooks/query/query-keys.tsindex ab5ceaa8c8..9243edc4f7 100644--- a/frontend/src/hooks/query/query-keys.ts+++ b/frontend/src/hooks/query/query-keys.ts@@ -18,6 +18,11 @@ export const SETTINGS_QUERY_KEYS = {["settings", "personal", organizationId] as const,} as const;+export const ORGANIZATION_APP_SETTINGS_KEYS = {+ byOrg: (organizationId: string | null | undefined) =>+ ["organization-app-settings", organizationId] as const,+} as const;+/** Cache configuration shared across all config-related queries */export const CONFIG_CACHE_OPTIONS = {staleTime: 1000 * 60 * 5, // 5 minutesdiff --git a/frontend/src/hooks/query/use-organization-app-settings.ts b/frontend/src/hooks/query/use-organization-app-settings.tsnew file mode 100644index 0000000000..b5be1b1362--- /dev/null+++ b/frontend/src/hooks/query/use-organization-app-settings.ts@@ -0,0 +1,14 @@+import { useQuery } from "@tanstack/react-query";+import { useSelectedOrganizationId } from "#/context/use-selected-organization";+import { organizationService } from "#/api/organization-service/organization-service.api";+import { ORGANIZATION_APP_SETTINGS_KEYS } from "#/hooks/query/query-keys";++export const useOrganizationAppSettings = () => {+ const { organizationId } = useSelectedOrganizationId();++ return useQuery({+ queryKey: ORGANIZATION_APP_SETTINGS_KEYS.byOrg(organizationId),+ queryFn: () => organizationService.getOrganizationAppSettings(),+ enabled: !!organizationId,+ });+};diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex 4d4573498d..ec9207f8a5 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -1637,4 +1637,58 @@ export enum I18nKey {ORG$AUTO_ADD_ENABLED_HINT = "ORG$AUTO_ADD_ENABLED_HINT",ORG$COPY_INVITE_LINK = "ORG$COPY_INVITE_LINK",ORG$INVITE_LINK_COPIED = "ORG$INVITE_LINK_COPIED",+ SETTINGS$REPOSITORY = "SETTINGS$REPOSITORY",+ SETTINGS$TYPE = "SETTINGS$TYPE",+ SETTINGS$SOURCE = "SETTINGS$SOURCE",+ SETTINGS$ENABLED = "SETTINGS$ENABLED",+ SETTINGS$ENABLED_TOOLTIP = "SETTINGS$ENABLED_TOOLTIP",+ SETTINGS$AUTO_LOAD = "SETTINGS$AUTO_LOAD",+ SETTINGS$AUTO_LOAD_TOOLTIP = "SETTINGS$AUTO_LOAD_TOOLTIP",+ SETTINGS$MARKETPLACE_ADD = "SETTINGS$MARKETPLACE_ADD",+ SETTINGS$MARKETPLACE_ADD_FIRST = "SETTINGS$MARKETPLACE_ADD_FIRST",+ SETTINGS$SKILLS_EMPTY_HINT = "SETTINGS$SKILLS_EMPTY_HINT",+ SETTINGS$SKILLS_PERMISSIONS = "SETTINGS$SKILLS_PERMISSIONS",+ SETTINGS$SKILLS_PERMISSIONS_DESCRIPTION = "SETTINGS$SKILLS_PERMISSIONS_DESCRIPTION",+ SETTINGS$MARKETPLACE_SOURCE = "SETTINGS$MARKETPLACE_SOURCE",+ SETTINGS$MARKETPLACE_ENABLED = "SETTINGS$MARKETPLACE_ENABLED",+ SETTINGS$CONNECT_REPOSITORIES = "SETTINGS$CONNECT_REPOSITORIES",+ SETTINGS$CONNECT_REPOSITORIES_DESCRIPTION = "SETTINGS$CONNECT_REPOSITORIES_DESCRIPTION",+ SETTINGS$MARKETPLACES = "SETTINGS$MARKETPLACES",+ SETTINGS$MARKETPLACES_DESCRIPTION = "SETTINGS$MARKETPLACES_DESCRIPTION",+ SETTINGS$CONNECT_MARKETPLACES = "SETTINGS$CONNECT_MARKETPLACES",+ SETTINGS$CONNECT_MARKETPLACES_DESCRIPTION = "SETTINGS$CONNECT_MARKETPLACES_DESCRIPTION",+ SETTINGS$SKILLS = "SETTINGS$SKILLS",+ SETTINGS$MARKETPLACE_SOURCE_PLACEHOLDER = "SETTINGS$MARKETPLACE_SOURCE_PLACEHOLDER",+ SETTINGS$SEARCH_PLACEHOLDER = "SETTINGS$SEARCH_PLACEHOLDER",+ SETTINGS$ALL_TYPES = "SETTINGS$ALL_TYPES",+ SETTINGS$ALL_REPOSITORIES = "SETTINGS$ALL_REPOSITORIES",+ SETTINGS$NO_SKILLS_MATCH_FILTERS = "SETTINGS$NO_SKILLS_MATCH_FILTERS",+ SETTINGS$ORG_SKILLS_TITLE = "SETTINGS$ORG_SKILLS_TITLE",+ SETTINGS$ORG_SKILLS_DESCRIPTION = "SETTINGS$ORG_SKILLS_DESCRIPTION",+ SETTINGS$MARKETPLACE_SCOPE_INSTANCE = "SETTINGS$MARKETPLACE_SCOPE_INSTANCE",+ SETTINGS$MARKETPLACE_SCOPE_PERSONAL = "SETTINGS$MARKETPLACE_SCOPE_PERSONAL",+ SETTINGS$MARKETPLACE_SCOPE_ORG = "SETTINGS$MARKETPLACE_SCOPE_ORG",+ SETTINGS$MARKETPLACE_SCOPE_LABEL = "SETTINGS$MARKETPLACE_SCOPE_LABEL",+ SETTINGS$MARKETPLACE_ADD_TITLE = "SETTINGS$MARKETPLACE_ADD_TITLE",+ SETTINGS$MARKETPLACE_EDIT_TITLE = "SETTINGS$MARKETPLACE_EDIT_TITLE",+ SETTINGS$MARKETPLACE_NAME = "SETTINGS$MARKETPLACE_NAME",+ SETTINGS$MARKETPLACE_REF = "SETTINGS$MARKETPLACE_REF",+ SETTINGS$MARKETPLACE_REPO_PATH = "SETTINGS$MARKETPLACE_REPO_PATH",+ SETTINGS$AVAILABLE_SKILLS = "SETTINGS$AVAILABLE_SKILLS",+ SETTINGS$SKILLS_AND_PLUGINS = "SETTINGS$SKILLS_AND_PLUGINS",+ SETTINGS$PLUGIN_AUTOLOAD_READONLY = "SETTINGS$PLUGIN_AUTOLOAD_READONLY",+ SETTINGS$UNSAVED_CHANGES = "SETTINGS$UNSAVED_CHANGES",+ SETTINGS$MARKETPLACE_REPO_PATH_INVALID = "SETTINGS$MARKETPLACE_REPO_PATH_INVALID",+ SETTINGS$MARKETPLACE_AUTO_LOAD = "SETTINGS$MARKETPLACE_AUTO_LOAD",+ SETTINGS$MARKETPLACE_SOURCE_READONLY = "SETTINGS$MARKETPLACE_SOURCE_READONLY",+ SETTINGS$MARKETPLACE_INSTANCE_READONLY = "SETTINGS$MARKETPLACE_INSTANCE_READONLY",+ SETTINGS$MARKETPLACE_ORG_REQUIRES_ADMIN = "SETTINGS$MARKETPLACE_ORG_REQUIRES_ADMIN",+ SETTINGS$MARKETPLACE_ORG_REQUIRE_ADMIN = "SETTINGS$MARKETPLACE_ORG_REQUIRE_ADMIN",+ SETTINGS$OPTIONAL = "SETTINGS$OPTIONAL",+ SETTINGS$MARKETPLACE_NAME_INVALID = "SETTINGS$MARKETPLACE_NAME_INVALID",+ SETTINGS$MARKETPLACE_NAME_REQUIRED = "SETTINGS$MARKETPLACE_NAME_REQUIRED",+ SETTINGS$DELETE_CONFIRMATION_TITLE = "SETTINGS$DELETE_CONFIRMATION_TITLE",+ SETTINGS$DELETE_CONFIRMATION_MESSAGE = "SETTINGS$DELETE_CONFIRMATION_MESSAGE",+ BUTTON$EDIT = "BUTTON$EDIT",+ SETTINGS$MARKETPLACE_SOURCE_REQUIRED = "SETTINGS$MARKETPLACE_SOURCE_REQUIRED",}diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.jsonindex a87422318d..92077e350e 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -12003,19 +12003,19 @@},"BUTTON$DELETE": {"en": "Delete",- "uk": "Видалити","ja": "削除","zh-CN": "删除","zh-TW": "刪除","ko-KR": "삭제","no": "Slett",- "ar": "حذف",- "de": "Löschen",- "fr": "Supprimer","it": "Elimina","pt": "Excluir","es": "Eliminar",+ "ar": "حذف",+ "fr": "Supprimer","tr": "Sil",+ "de": "Löschen",+ "uk": "Видалити","ca": "Elimina"},"BUTTON$COPY_TO_CLIPBOARD": {@@ -23290,21 +23290,21 @@"ca": "Habilitats"},"SETTINGS$SKILLS_DESCRIPTION": {- "en": "Enable or disable default skills. Disabled skills will not be loaded into agent context.",- "ja": "デフォルトスキル(マイクロエージェント)を有効または無効にします。無効なスキルはエージェントコンテキストに読み込まれません。",- "zh-CN": "启用或禁用默认技能(微代理)。禁用的技能不会加载到代理上下文中。",- "zh-TW": "啟用或停用預設技能(微代理)。停用的技能不會載入到代理上下文中。",- "ko-KR": "기본 스킬(마이크로에이전트)을 활성화하거나 비활성화합니다. 비활성화된 스킬은 에이전트 컨텍스트에 로드되지 않습니다.",- "no": "Aktiver eller deaktiver standardferdigheter (mikroagenter). Deaktiverte ferdigheter lastes ikke inn i agentkonteksten.",- "ar": "تفعيل أو تعطيل المهارات الافتراضية (الوكلاء الصغار). لن يتم تحميل المهارات المعطلة في سياق الوكيل.",- "de": "Standard-Fähigkeiten (Mikroagenten) aktivieren oder deaktivieren. Deaktivierte Fähigkeiten werden nicht in den Agentenkontext geladen.",- "fr": "Activer ou désactiver les compétences par défaut (micro-agents). Les compétences désactivées ne seront pas chargées dans le contexte de l'agent.",- "it": "Abilita o disabilita le competenze predefinite (micro-agenti). Le competenze disabilitate non verranno caricate nel contesto dell'agente.",- "pt": "Ativar ou desativar habilidades padrão (micro-agentes). Habilidades desativadas não serão carregadas no contexto do agente.",- "es": "Habilitar o deshabilitar habilidades predeterminadas (micro-agentes). Las habilidades deshabilitadas no se cargarán en el contexto del agente.",- "tr": "Varsayılan yetenekleri (mikro ajanlar) etkinleştirin veya devre dışı bırakın. Devre dışı bırakılan yetenekler ajan bağlamına yüklenmez.",- "uk": "Увімкніть або вимкніть навички за замовчуванням (мікроагенти). Вимкнені навички не завантажуватимуться в контекст агента.",- "ca": "Activeu o desactiveu les habilitats predeterminades. Les habilitats desactivades no es carregaran al context de l'agent."+ "en": "Skills and plugins available to the agent, from your marketplaces and built-in sources. Toggle individual skills on or off; a plugin's availability follows its marketplace's Auto-Load setting.",+ "ja": "マーケットプレイスと組み込みソースから、エージェントが利用できるスキルとプラグインです。個々のスキルはオン・オフを切り替えられます。プラグインの利用可否は、そのマーケットプレイスの自動読み込み設定に従います。",+ "zh-CN": "来自您的市场和内置来源、可供代理使用的技能和插件。可逐个开启或关闭技能;插件的可用性取决于其市场的自动加载设置。",+ "zh-TW": "來自您的市場和內建來源、可供代理使用的技能和外掛。可逐一開啟或關閉技能;外掛的可用性取決於其市場的自動載入設定。",+ "ko-KR": "마켓플레이스와 기본 제공 소스에서 에이전트가 사용할 수 있는 스킬과 플러그인입니다. 개별 스킬을 켜거나 끌 수 있으며, 플러그인의 사용 가능 여부는 해당 마켓플레이스의 자동 로드 설정을 따릅니다.",+ "no": "Ferdigheter og plugins som er tilgjengelige for agenten, fra markedsplassene dine og innebygde kilder. Slå enkeltferdigheter av eller på; en plugins tilgjengelighet følger markedsplassens Automatisk lasting-innstilling.",+ "ar": "المهارات والمكونات الإضافية المتاحة للوكيل من أسواقك والمصادر المدمجة. يمكنك تشغيل أو إيقاف كل مهارة على حدة؛ ويعتمد توفّر المكوّن الإضافي على إعداد التحميل التلقائي الخاص بسوقه.",+ "de": "Skills und Plugins, die dem Agenten aus Ihren Marktplätzen und integrierten Quellen zur Verfügung stehen. Schalten Sie einzelne Skills ein oder aus; die Verfügbarkeit eines Plugins richtet sich nach der Einstellung Automatisch laden seines Marktplatzes.",+ "fr": "Compétences et plugins disponibles pour l'agent, provenant de vos places de marché et des sources intégrées. Activez ou désactivez chaque compétence ; la disponibilité d'un plugin dépend du paramètre Chargement auto de sa place de marché.",+ "it": "Competenze e plugin disponibili per l'agente, dai tuoi marketplace e dalle fonti integrate. Attiva o disattiva le singole competenze; la disponibilità di un plugin dipende dall'impostazione Caricamento auto del suo marketplace.",+ "pt": "Habilidades e plugins disponíveis para o agente, dos seus mercados e de fontes integradas. Ative ou desative habilidades individuais; a disponibilidade de um plugin segue a configuração de Carregamento automático do seu mercado.",+ "es": "Habilidades y plugins disponibles para el agente, desde tus mercados y fuentes integradas. Activa o desactiva habilidades individuales; la disponibilidad de un plugin depende de la configuración de Carga automática de su mercado.",+ "ca": "Habilitats i connectors disponibles per a l'agent, dels teus mercats i de fonts integrades. Activa o desactiva habilitats individuals; la disponibilitat d'un connector depèn de la configuració de Càrrega automàtica del seu mercat.",+ "tr": "Pazaryerlerinizden ve yerleşik kaynaklardan aracıya sunulan beceriler ve eklentiler. Becerileri tek tek açıp kapatabilirsiniz; bir eklentinin kullanılabilirliği, pazaryerinin Otomatik yükleme ayarına bağlıdır.",+ "uk": "Навички та плагіни, доступні агенту з ваших маркетплейсів і вбудованих джерел. Вмикайте або вимикайте окремі навички; доступність плагіна залежить від налаштування Автозавантаження його маркетплейсу."},"SETTINGS$SKILLS_NO_SKILLS": {"en": "No skills found.",@@ -27827,5 +27827,923 @@"uk": "Запрошення скопійовано","zh-CN": "邀请链接已复制","zh-TW": "邀請連結已複製"+ },+ "SETTINGS$REPOSITORY": {+ "en": "Repository",+ "ja": "リポジトリ",+ "zh-CN": "仓库",+ "zh-TW": "儲存庫",+ "ko-KR": "저장소",+ "no": "Repository",+ "ar": "المستودع",+ "de": "Repository",+ "fr": "Dépôt",+ "it": "Repository",+ "pt": "Repositório",+ "es": "Repositorio",+ "ca": "Repositori",+ "tr": "Depo",+ "uk": "Репозиторій"+ },+ "SETTINGS$TYPE": {+ "en": "Type",+ "ja": "タイプ",+ "zh-CN": "类型",+ "zh-TW": "類型",+ "ko-KR": "유형",+ "no": "Type",+ "ar": "النوع",+ "de": "Typ",+ "fr": "Type",+ "it": "Tipo",+ "pt": "Tipo",+ "es": "Tipo",+ "ca": "Tipus",+ "tr": "Tür",+ "uk": "Тип"+ },+ "SETTINGS$SOURCE": {+ "en": "SOURCE",+ "ja": "ソース",+ "zh-CN": "来源",+ "zh-TW": "來源",+ "ko-KR": "소스",+ "no": "SOURCE",+ "ar": "المصدر",+ "de": "QUELLE",+ "fr": "SOURCE",+ "it": "ORIGINE",+ "pt": "FONTE",+ "es": "FUENTE",+ "ca": "FONT",+ "tr": "KAYNAK",+ "uk": "ДЖЕРЕЛО"+ },+ "SETTINGS$ENABLED": {+ "en": "Enabled",+ "ja": "有効",+ "zh-CN": "已启用",+ "zh-TW": "已啟用",+ "ko-KR": "활성화됨",+ "no": "Aktivert",+ "ar": "مُمكَّن",+ "de": "Aktiviert",+ "fr": "Activé",+ "it": "Abilitato",+ "pt": "Ativado",+ "es": "Habilitado",+ "ca": "Habilitat",+ "tr": "Etkin",+ "uk": "Увімкнено"+ },+ "SETTINGS$ENABLED_TOOLTIP": {+ "en": "When on, this skill is available to the agent during conversations. When off, it is excluded.",+ "ja": "オンの場合、このスキルは会話中にエージェントが利用できます。オフの場合、除外されます。",+ "zh-CN": "开启时,此技能在对话期间可供代理使用。关闭时,将被排除。",+ "zh-TW": "開啟時,此技能在對話期間可供代理使用。關閉時,將被排除。",+ "ko-KR": "켜져 있으면 이 스킬을 대화 중에 에이전트가 사용할 수 있습니다. 꺼져 있으면 제외됩니다.",+ "no": "Når aktivert er denne ferdigheten tilgjengelig for agenten under samtaler. Når deaktivert utelates den.",+ "ar": "عند التفعيل، تكون هذه المهارة متاحة للوكيل أثناء المحادثات. عند إيقاف التفعيل، يتم استبعادها.",+ "de": "Wenn aktiviert, steht dieser Skill dem Agenten während Unterhaltungen zur Verfügung. Wenn deaktiviert, wird er ausgeschlossen.",+ "fr": "Lorsque cette option est activée, cette compétence est disponible pour l'agent pendant les conversations. Lorsqu'elle est désactivée, elle est exclue.",+ "it": "Se attivato, questa competenza è disponibile per l'agente durante le conversazioni. Se disattivato, viene esclusa.",+ "pt": "Quando ativado, esta habilidade fica disponível para o agente durante as conversas. Quando desativado, ela é excluída.",+ "es": "Cuando está activado, esta habilidad está disponible para el agente durante las conversaciones. Cuando está desactivado, se excluye.",+ "ca": "Quan està activat, aquesta habilitat està disponible per a l'agent durant les converses. Quan està desactivat, s'exclou.",+ "tr": "Açık olduğunda, bu beceri konuşmalar sırasında aracıya sunulur. Kapalı olduğunda, hariç tutulur.",+ "uk": "Коли увімкнено, ця навичка доступна агенту під час розмов. Коли вимкнено, вона виключається."+ },+ "SETTINGS$AUTO_LOAD": {+ "en": "Auto-Load",+ "ja": "自動読み込み",+ "zh-CN": "自动加载",+ "zh-TW": "自動載入",+ "ko-KR": "자동 로드",+ "no": "Automatisk lasting",+ "ar": "التحميل التلقائي",+ "de": "Automatisch laden",+ "fr": "Chargement auto",+ "it": "Caricamento auto",+ "pt": "Carregamento automático",+ "es": "Carga automática",+ "ca": "Càrrega automàtica",+ "tr": "Otomatik yükleme",+ "uk": "Автозавантаження"+ },+ "SETTINGS$AUTO_LOAD_TOOLTIP": {+ "en": "When on, this marketplace's plugins are loaded automatically at the start of every conversation. When off, the marketplace stays registered and its plugins can be loaded on demand.",+ "ja": "オンの場合、このマーケットプレイスのプラグインはすべての会話の開始時に自動的に読み込まれます。オフの場合、マーケットプレイスは登録されたままになり、そのプラグインは必要に応じて読み込むことができます。",+ "zh-CN": "开启时,此市场的插件会在每次对话开始时自动加载。关闭时,市场仍保持注册状态,其插件可按需加载。",+ "zh-TW": "開啟時,此市場的外掛會在每次對話開始時自動載入。關閉時,市場仍保持註冊狀態,其外掛可依需求載入。",+ "ko-KR": "켜져 있으면 이 마켓플레이스의 플러그인이 모든 대화 시작 시 자동으로 로드됩니다. 꺼져 있으면 마켓플레이스는 등록된 상태로 유지되며 해당 플러그인은 필요할 때 로드할 수 있습니다.",+ "no": "Når aktivert lastes denne markedsplassens plugins automatisk ved starten av hver samtale. Når deaktivert forblir markedsplassen registrert, og pluginene kan lastes ved behov.",+ "ar": "عند التفعيل، يتم تحميل مكونات هذا السوق الإضافية تلقائيًا في بداية كل محادثة. عند إيقاف التفعيل، يبقى السوق مسجَّلًا ويمكن تحميل مكوناته الإضافية عند الطلب.",+ "de": "Wenn aktiviert, werden die Plugins dieses Marktplatzes automatisch zu Beginn jeder Unterhaltung geladen. Wenn deaktiviert, bleibt der Marktplatz registriert und seine Plugins können bei Bedarf geladen werden.",+ "fr": "Lorsque cette option est activée, les plugins de cette place de marché sont chargés automatiquement au début de chaque conversation. Lorsqu'elle est désactivée, la place de marché reste enregistrée et ses plugins peuvent être chargés à la demande.",+ "it": "Se attivato, i plugin di questo marketplace vengono caricati automaticamente all'inizio di ogni conversazione. Se disattivato, il marketplace rimane registrato e i suoi plugin possono essere caricati su richiesta.",+ "pt": "Quando ativado, os plugins deste mercado são carregados automaticamente no início de cada conversa. Quando desativado, o mercado permanece registrado e seus plugins podem ser carregados sob demanda.",+ "es": "Cuando está activado, los plugins de este mercado se cargan automáticamente al inicio de cada conversación. Cuando está desactivado, el mercado permanece registrado y sus plugins se pueden cargar bajo demanda.",+ "ca": "Quan està activat, els connectors d'aquest mercat es carreguen automàticament a l'inici de cada conversa. Quan està desactivat, el mercat continua registrat i els seus connectors es poden carregar sota demanda.",+ "tr": "Açık olduğunda, bu pazaryerinin eklentileri her konuşmanın başında otomatik olarak yüklenir. Kapalı olduğunda, pazaryeri kayıtlı kalır ve eklentileri istendiğinde yüklenebilir.",+ "uk": "Коли увімкнено, плагіни цього маркетплейсу завантажуються автоматично на початку кожної розмови. Коли вимкнено, маркетплейс залишається зареєстрованим, а його плагіни можна завантажити за потреби."+ },+ "SETTINGS$MARKETPLACE_ADD": {+ "en": "+ Add Repository",+ "ja": "+ リポジトリを追加",+ "zh-CN": "+ 添加仓库",+ "zh-TW": "+ 新增儲存庫",+ "ko-KR": "+ 저장소 추가",+ "no": "+ Legg til repository",+ "ar": "+ إضافة مستودع",+ "de": "+ Repository hinzufügen",+ "fr": "+ Ajouter un dépôt",+ "it": "+ Aggiungi repository",+ "pt": "+ Adicionar repositório",+ "es": "+ Añadir repositorio",+ "ca": "+ Afegir repositori",+ "tr": "+ Depo ekle",+ "uk": "+ Додати репозиторій"+ },+ "SETTINGS$MARKETPLACE_ADD_FIRST": {+ "en": "No repositories connected",+ "ja": "接続されたリポジトリはありません",+ "zh-CN": "没有连接的仓库",+ "zh-TW": "沒有連接的儲存庫",+ "ko-KR": "연결된 저장소 없음",+ "no": "Ingen repositories tilkoblet",+ "ar": "لا توجد مستودعات متصلة",+ "de": "Keine Repositories verbunden",+ "fr": "Aucun dépôt connecté",+ "it": "Nessun repository connesso",+ "pt": "Nenhum repositório conectado",+ "es": "No hay repositorios conectados",+ "ca": "No hi ha repositoris connectats",+ "tr": "Bağlı depo yok",+ "uk": "Немає підключених репозиторіїв"+ },+ "SETTINGS$SKILLS_EMPTY_HINT": {+ "en": "Skills will appear here once configured",+ "ja": "スキルは構成されるとここに表示されます",+ "zh-CN": "技能配置后将显示在这里",+ "zh-TW": "技能設定後將顯示在這裡",+ "ko-KR": "스킬이 구성되면 여기에 표시됩니다",+ "no": "Ferdommer vil vises her når de er konfigurert",+ "ar": "ستظهر المهارات هنا بمجرد تكوينها",+ "de": "Skills werden hier angezeigt, sobald sie konfiguriert sind",+ "fr": "Les compétences apparaîtront ici une fois configurées",+ "it": "Le competenze appariranno qui una volta configurate",+ "pt": "As habilidades aparecerão aqui quando configuradas",+ "es": "Las habilidades aparecerán aquí una vez configuradas",+ "ca": "Les habilitats apareixeran aquí un cop configurades",+ "tr": "Beceriler yapılandırıldığında burada görünecektir",+ "uk": "Навички з'являться тут після налаштування"+ },+ "SETTINGS$SKILLS_PERMISSIONS": {+ "en": "Skills Permissions",+ "ja": "スキル権限",+ "zh-CN": "技能权限",+ "zh-TW": "技能權限",+ "ko-KR": "스킬 권한",+ "no": "Ferdighetstillatelser",+ "ar": "أذونات المهارات",+ "de": "Skills-Berechtigungen",+ "fr": "Permissions des compétences",+ "it": "Permessi delle competenze",+ "pt": "Permissões de habilidades",+ "es": "Permisos de habilidades",+ "ca": "Permisos d'habilitats",+ "tr": "Beceri İzinleri",+ "uk": "Дозволи навичок"+ },+ "SETTINGS$SKILLS_PERMISSIONS_DESCRIPTION": {+ "en": "Configure which skills are enabled and auto-loaded",+ "ja": "有効化および自動読み込みされるスキルを設定します",+ "zh-CN": "配置哪些技能已启用并自动加载",+ "zh-TW": "設定哪些技能已啟用並自動載入",+ "ko-KR": "활성화되고 자동 로드되는 스킬을 구성합니다",+ "no": "Konfigurer hvilke ferdigheter som er aktivert og automatisk lastet",+ "ar": "تكوين المهارات المُفعَّلة والمحملة تلقائيًا",+ "de": "Konfigurieren Sie, welche Skills aktiviert und automatisch geladen werden",+ "fr": "Configurer quelles compétences sont activées et chargées automatiquement",+ "it": "Configura quali competenze sono abilitate e caricate automaticamente",+ "pt": "Configure quais habilidades estão ativadas e carregadas automaticamente",+ "es": "Configurar qué habilidades están habilitadas y se cargan automáticamente",+ "ca": "Configura quines habilitats estan habilitades i es carreguen automàticament",+ "tr": "Hangi becerilerin etkinleştirildiğini ve otomatik yüklendiğini yapılandırın",+ "uk": "Налаштуйте, які навички увімкнено та автоматично завантажуються"+ },+ "SETTINGS$MARKETPLACE_SOURCE": {+ "en": "Repository",+ "ja": "リポジトリ",+ "zh-CN": "仓库",+ "zh-TW": "儲存庫",+ "ko-KR": "저장소",+ "no": "Repository",+ "ar": "المستودع",+ "de": "Repository",+ "fr": "Dépôt",+ "it": "Repository",+ "pt": "Repositório",+ "es": "Repositorio",+ "ca": "Repositori",+ "tr": "Depo",+ "uk": "Репозиторій"+ },+ "SETTINGS$MARKETPLACE_ENABLED": {+ "en": "Actions",+ "ja": "アクション",+ "zh-CN": "操作",+ "zh-TW": "操作",+ "ko-KR": "작업",+ "no": "Handlinger",+ "ar": "الإجراءات",+ "de": "Aktionen",+ "fr": "Actions",+ "it": "Azioni",+ "pt": "Ações",+ "es": "Acciones",+ "ca": "Accions",+ "tr": "Eylemler",+ "uk": "Дії"+ },+ "SETTINGS$CONNECT_REPOSITORIES": {+ "en": "Connect Skills Repositories",+ "ja": "スキルリポジトリを接続",+ "zh-CN": "连接技能仓库",+ "zh-TW": "連接技能儲存庫",+ "ko-KR": "스킬 저장소 연결",+ "no": "Koble til ferdighetsrepositoryer",+ "ar": "توصيل مستودعات المهارات",+ "de": "Skills-Repositories verbinden",+ "fr": "Connecter les dépôts de compétences",+ "it": "Connetti repository di competenze",+ "pt": "Conectar repositórios de habilidades",+ "es": "Conectar repositorios de habilidades",+ "ca": "Connectar repositoris d'habilitats",+ "tr": "Beceri Depolarını Bağla",+ "uk": "Підключити репозиторії навичок"+ },+ "SETTINGS$CONNECT_REPOSITORIES_DESCRIPTION": {+ "en": "Add repository URLs to load skills from external sources",+ "ja": "外部ソースからスキルをロードするためのリポジトリURLを追加します",+ "zh-CN": "添加仓库URL以从外部源加载技能",+ "zh-TW": "新增儲存庫URL以從外部來源載入技能",+ "ko-KR": "외부 소스에서 스킬을 로드하기 위해 저장소 URL을 추가합니다",+ "no": "Legg til repository-URLer for å laste ferdigheter fra eksterne kilder",+ "ar": "إضافة عناوين URL للمستودعات لتحميل المهارات من مصادر خارجية",+ "de": "Repository-URLs hinzufügen, um Skills aus externen Quellen zu laden",+ "fr": "Ajouter des URL de dépôt pour charger des compétences à partir de sources externes",+ "it": "Aggiungi URL di repository per caricare competenze da fonti esterne",+ "pt": "Adicionar URLs de repositório para carregar habilidades de fontes externas",+ "es": "Añadir URLs de repositorio para cargar habilidades de fuentes externas",+ "ca": "Afegir URLs de repositori per carregar habilitats de fonts externes",+ "tr": "Harici kaynaklardan beceri yüklemek için depo URL'leri ekleyin",+ "uk": "Додайте URL-адреси репозиторіїв для завантаження навичок із зовнішніх джерел"+ },+ "SETTINGS$MARKETPLACES": {+ "en": "Marketplaces",+ "ja": "マーケットプレイス",+ "zh-CN": "市场",+ "zh-TW": "市場",+ "ko-KR": "마켓플레이스",+ "no": "Markedsplasser",+ "ar": "الأسواق",+ "de": "Märkte",+ "fr": "Places de marché",+ "it": "Marketplace",+ "pt": "Mercados",+ "es": "Mercados",+ "ca": "Mercats",+ "tr": "Pazaryerleri",+ "uk": "Маркетплейси"+ },+ "SETTINGS$MARKETPLACES_DESCRIPTION": {+ "en": "Connect skill repositories from Git URLs, manage org-wide skill visibility, and set which skills are enabled by default in conversations",+ "ja": "Git URLからスキルリポジトリを接続し、組織全体のスキル可視性を管理し、デフォルトで有効にするスキルを設定します",+ "zh-CN": "从Git URL连接技能仓库,管理组织范围的技能可见性,并设置默认在对话中启用的技能",+ "zh-TW": "從Git URL連接技能儲存庫,管理組織範圍的技能可見性,並設定預設在對話中啟用的技能",+ "ko-KR": "Git URL에서 스킬 저장소를 연결하고 조직 전체 스킬 가시성을 관리하며 대화에서 기본적으로 활성화할 스킬을 설정합니다",+ "no": "Koble til ferdighetsrepositoryer fra Git-URLer, administrer synlighet for ferdigheter på tvers av organisasjonen, og angi hvilke ferdigheter som er aktivert som standard i samtaler",+ "ar": "قم بتوصيل مستودعات المهارات من عناوين URL الخاصة بـ Git، وإدارة رؤية المهارات على مستوى المؤسسة، وتعيين المهارات المفعلة افتراضيًا في المحادثات",+ "de": "Verbinden Sie Skill-Repositories über Git-URLs, verwalten Sie die Sichtbarkeit von Skills organisationsübergreifend und legen Sie fest, welche Skills standardmäßig in Unterhaltungen aktiviert sind",+ "fr": "Connectez les dépôts de compétences à partir des URL Git, gérez la visibilité des compétences à l'échelle de l'organisation et définissez les compétences activées par défaut dans les conversations",+ "it": "Connetti repository di competenze da URL Git, gestisci la visibilità delle competenze a livello di organizzazione e imposta quali competenze sono attivate per impostazione predefinita nelle conversazioni",+ "pt": "Conecte repositórios de habilidades de URLs Git, gerencie a visibilidade de habilidades em toda a organização e defina quais habilidades estão habilitadas por padrão nas conversas",+ "es": "Conecte repositorios de habilidades desde URLs de Git, administre la visibilidad de habilidades en toda la organización y establezca qué habilidades están habilitadas por defecto en las conversaciones",+ "ca": "Connecteu els dipòsits d'habilitats des d'URLs Git, gestioneu la visibilitat de les habilitats a nivell d'organització i establiu quines habilitats estan habilitades per defecte a les converses",+ "tr": "Git URL'lerinden beceri depolarını bağlayın, kuruluş genelinde beceri görünürlüğünü yönetin ve konuşmalarda varsayılan olarak etkinleştirilen becerileri ayarlayın",+ "uk": "Підключіть репозиторії навичок через Git URL-адреси, керуйте видимістю навичок в організації та визначте, які навички увімкнено за замовчуванням у розмовах"+ },+ "SETTINGS$CONNECT_MARKETPLACES": {+ "en": "Connect Marketplaces",+ "ja": "マーケットプレイスを接続",+ "zh-CN": "连接市场",+ "zh-TW": "連接市場",+ "ko-KR": "마켓플레이스 연결",+ "no": "Koble til markedsplasser",+ "ar": "توصيل الأسواق",+ "de": "Märkte verbinden",+ "fr": "Connecter les places de marché",+ "it": "Connetti marketplace",+ "pt": "Conectar mercados",+ "es": "Conectar mercados",+ "ca": "Connectar mercats",+ "tr": "Pazaryerlerini Bağla",+ "uk": "Підключити маркетплейси"+ },+ "SETTINGS$CONNECT_MARKETPLACES_DESCRIPTION": {+ "en": "Register marketplaces — git repositories that provide plugins and skills. Turn on Auto-Load to load a marketplace's plugins automatically at the start of every conversation.",+ "ja": "プラグインとスキルを提供する git リポジトリであるマーケットプレイスを登録します。自動読み込みをオンにすると、そのマーケットプレイスのプラグインがすべての会話の開始時に自動的に読み込まれます。",+ "zh-CN": "注册市场——提供插件和技能的 git 仓库。开启自动加载后,该市场的插件会在每次对话开始时自动加载。",+ "zh-TW": "註冊市場——提供外掛和技能的 git 儲存庫。開啟自動載入後,該市場的外掛會在每次對話開始時自動載入。",+ "ko-KR": "플러그인과 스킬을 제공하는 git 저장소인 마켓플레이스를 등록합니다. 자동 로드를 켜면 해당 마켓플레이스의 플러그인이 모든 대화 시작 시 자동으로 로드됩니다.",+ "no": "Registrer markedsplasser – git-repositorier som tilbyr plugins og ferdigheter. Slå på Automatisk lasting for å laste en markedsplass' plugins automatisk ved starten av hver samtale.",+ "ar": "سجّل الأسواق — مستودعات git التي توفّر مكونات إضافية ومهارات. فعّل التحميل التلقائي لتحميل مكونات السوق الإضافية تلقائيًا في بداية كل محادثة.",+ "de": "Registrieren Sie Marktplätze – Git-Repositories, die Plugins und Skills bereitstellen. Aktivieren Sie Automatisch laden, um die Plugins eines Marktplatzes automatisch zu Beginn jeder Unterhaltung zu laden.",+ "fr": "Enregistrez des places de marché — des dépôts git qui fournissent des plugins et des compétences. Activez le Chargement auto pour charger automatiquement les plugins d'une place de marché au début de chaque conversation.",+ "it": "Registra marketplace — repository git che forniscono plugin e competenze. Attiva il Caricamento auto per caricare automaticamente i plugin di un marketplace all'inizio di ogni conversazione.",+ "pt": "Registre mercados — repositórios git que fornecem plugins e habilidades. Ative o Carregamento automático para carregar automaticamente os plugins de um mercado no início de cada conversa.",+ "es": "Registra mercados: repositorios git que proporcionan plugins y habilidades. Activa la Carga automática para cargar automáticamente los plugins de un mercado al inicio de cada conversación.",+ "ca": "Registra mercats: dipòsits git que proporcionen connectors i habilitats. Activa la Càrrega automàtica per carregar automàticament els connectors d'un mercat a l'inici de cada conversa.",+ "tr": "Pazaryerlerini kaydedin — eklentiler ve beceriler sağlayan git depoları. Bir pazaryerinin eklentilerini her konuşmanın başında otomatik olarak yüklemek için Otomatik yükleme'yi açın.",+ "uk": "Реєструйте маркетплейси — git-репозиторії, що надають плагіни та навички. Увімкніть Автозавантаження, щоб плагіни маркетплейсу автоматично завантажувалися на початку кожної розмови."+ },+ "SETTINGS$SKILLS": {+ "en": "Skills",+ "ja": "スキル",+ "zh-CN": "技能",+ "zh-TW": "技能",+ "ko-KR": "스킬",+ "no": "Ferdigheter",+ "ar": "المهارات",+ "de": "Skills",+ "fr": "Compétences",+ "it": "Competenze",+ "pt": "Habilidades",+ "es": "Habilidades",+ "ca": "Habilitats",+ "tr": "Beceriler",+ "uk": "Навички"+ },+ "SETTINGS$MARKETPLACE_SOURCE_PLACEHOLDER": {+ "en": "https://github.com/username/skills-repo",+ "ja": "https://github.com/username/skills-repo",+ "zh-CN": "https://github.com/用户名/skills-repo",+ "zh-TW": "https://github.com/使用者名稱/skills-repo",+ "ko-KR": "https://github.com/사용자명/skills-repo",+ "no": "https://github.com/brukernavn/skills-repo",+ "ar": "https://github.com/اسم المستخدم/skills-repo",+ "de": "https://github.com/Benutzername/skills-repo",+ "fr": "https://github.com/nomutilisateur/skills-repo",+ "it": "https://github.com/nomeutente/skills-repo",+ "pt": "https://github.com/nomedeusuario/skills-repo",+ "es": "https://github.com/nombredeusuario/skills-repo",+ "ca": "https://github.com/nomdusuari/skills-repo",+ "tr": "https://github.com/kullaniciadi/skills-repo",+ "uk": "https://github.com/username/skills-repo"+ },+ "SETTINGS$SEARCH_PLACEHOLDER": {+ "en": "Search skills...",+ "ja": "スキルを検索...",+ "zh-CN": "搜索技能...",+ "zh-TW": "搜尋技能...",+ "ko-KR": "스킬 검색...",+ "no": "Søk i ferdigheter...",+ "ar": "البحث عن المهارات...",+ "de": "Skills suchen...",+ "fr": "Rechercher des compétences...",+ "it": "Cerca competenze...",+ "pt": "Buscar habilidades...",+ "es": "Buscar habilidades...",+ "ca": "Cercar habilitats...",+ "tr": "Becerileri ara...",+ "uk": "Пошук навичок..."+ },+ "SETTINGS$ALL_TYPES": {+ "en": "All Types",+ "ja": "すべてのタイプ",+ "zh-CN": "所有类型",+ "zh-TW": "所有類型",+ "ko-KR": "すべての 유형",+ "no": "Alle typer",+ "ar": "جميع الأنواع",+ "de": "Alle Typen",+ "fr": "Tous les types",+ "it": "Tutti i tipi",+ "pt": "Todos os tipos",+ "es": "Todos los tipos",+ "ca": "Tots els tipus",+ "tr": "Tüm Türler",+ "uk": "Всі типи"+ },+ "SETTINGS$ALL_REPOSITORIES": {+ "en": "All Repositories",+ "ja": "すべてのリポジトリ",+ "zh-CN": "所有仓库",+ "zh-TW": "所有儲存庫",+ "ko-KR": "すべての저장소",+ "no": "Alle repositories",+ "ar": "جميع المستودعات",+ "de": "Alle Repositories",+ "fr": "Tous les dépôts",+ "it": "Tutti i repository",+ "pt": "Todos os repositórios",+ "es": "Todos los repositorios",+ "ca": "Tots els repositoris",+ "tr": "Tüm Depolar",+ "uk": "Всі репозиторії"+ },+ "SETTINGS$NO_SKILLS_MATCH_FILTERS": {+ "en": "No skills match your filters",+ "ja": "フィルターに一致するスキルがありません",+ "zh-CN": "没有技能符合您的过滤器",+ "zh-TW": "沒有技能符合您的篩選條件",+ "ko-KR": "필터와 일치하는 스킬이 없습니다",+ "no": "Ingen ferdigheter samsvarer med filtrene dine",+ "ar": "لا توجد مهارات تطابق عوامل التصفية الخاصة بك",+ "de": "Keine Skills entsprechen Ihren Filtern",+ "fr": "Aucune compétence ne correspond à vos filtres",+ "it": "Nessuna competenza corrisponde ai tuoi filtri",+ "pt": "Nenhuma habilidade corresponde aos seus filtros",+ "es": "Ninguna habilidad coincide con tus filtros",+ "ca": "Cap habilitat coincideix amb els teus filtres",+ "tr": "Filtrelerinizle eşleşen beceri yok",+ "uk": "Жодна навичка не відповідає вашим фільтрам"+ },+ "SETTINGS$ORG_SKILLS_TITLE": {+ "en": "Organization Skills",+ "ja": "オーガニゼーションスキル",+ "zh-CN": "组织技能",+ "zh-TW": "組織技能",+ "ko-KR": "조직 스킬",+ "no": "Organisasjonsferdigheter",+ "ar": "مهارات المؤسسة",+ "de": "Organisations-Skills",+ "fr": "Compétences de l'organisation",+ "it": "Competenze dell'organizzazione",+ "pt": "Habilidades da organização",+ "es": "Habilidades de la organización",+ "ca": "Habilitats de l'organització",+ "tr": "Kuruluş Becerileri",+ "uk": "Навички організації"+ },+ "SETTINGS$ORG_SKILLS_DESCRIPTION": {+ "en": "Manage skills available to your organization",+ "ja": "オーガニゼーションで利用できるスキルを管理します",+ "zh-CN": "管理您的组织可用的技能",+ "zh-TW": "管理您的組織可用的技能",+ "ko-KR": "조직에서 사용할 수 있는 스킬을 관리합니다",+ "no": "Administrer ferdigheter tilgjengelig for din organisasjon",+ "ar": "إدارة المهارات المتاحة لمؤسستك",+ "de": "Verwalten Sie für Ihre Organisation verfügbare Skills",+ "fr": "Gérer les compétences disponibles pour votre organisation",+ "it": "Gestisci le competenze disponibili per la tua organizzazione",+ "pt": "Gerenciar habilidades disponíveis para sua organização",+ "es": "Gestionar las habilidades disponibles para su organización",+ "ca": "Gestionar les habilitats disponibles per a la teva organització",+ "tr": "Kuruluşunuz için kullanılabilir becerileri yönetin",+ "uk": "Керування навичками, доступними для вашої організації"+ },+ "SETTINGS$MARKETPLACE_SCOPE_INSTANCE": {+ "en": "Instance",+ "ja": "インスタンス",+ "zh-CN": "实例",+ "zh-TW": "執行個體",+ "ko-KR": "인스턴스",+ "no": "Instans",+ "ar": "الن Instance",+ "de": "Instanz",+ "fr": "Instance",+ "it": "Istanza",+ "pt": "Instância",+ "es": "Instancia",+ "ca": "Instància",+ "tr": "Örnek",+ "uk": "Екземпляр"+ },+ "SETTINGS$MARKETPLACE_SCOPE_PERSONAL": {+ "en": "Personal",+ "ja": "パーソナル",+ "zh-CN": "个人",+ "zh-TW": "個人",+ "ko-KR": "개인",+ "no": "Personlig",+ "ar": "شخصي",+ "de": "Persönlich",+ "fr": "Personnel",+ "it": "Personale",+ "pt": "Pessoal",+ "es": "Personal",+ "ca": "Personal",+ "tr": "Kişisel",+ "uk": "Особистий"+ },+ "SETTINGS$MARKETPLACE_SCOPE_ORG": {+ "en": "Organization",+ "ja": "オーガナイゼーション",+ "zh-CN": "组织",+ "zh-TW": "組織",+ "ko-KR": "조직",+ "no": "Organisasjon",+ "ar": "مؤسسة",+ "de": "Organisation",+ "fr": "Organisation",+ "it": "Organizzazione",+ "pt": "Organização",+ "es": "Organización",+ "ca": "Organització",+ "tr": "Kuruluş",+ "uk": "Організація"+ },+ "SETTINGS$MARKETPLACE_SCOPE_LABEL": {+ "en": "Scope",+ "ja": "スコープ",+ "zh-CN": "范围",+ "zh-TW": "範圍",+ "ko-KR": "범위",+ "no": "Omfang",+ "ar": "النطاق",+ "de": "Bereich",+ "fr": "Portée",+ "it": "Ambito",+ "pt": "Escopo",+ "es": "Ámbito",+ "ca": "Abast",+ "tr": "Kapsam",+ "uk": "Обсяг"+ },+ "SETTINGS$MARKETPLACE_ADD_TITLE": {+ "en": "Add Marketplace",+ "ja": "マーケットプレイスの追加",+ "zh-CN": "添加市场",+ "zh-TW": "新增市場",+ "ko-KR": "마켓플레이스 추가",+ "no": "Legg til markedsplass",+ "ar": "إضافة السوق",+ "de": "Marktplatz hinzufügen",+ "fr": "Ajouter une marketplace",+ "it": "Aggiungi marketplace",+ "pt": "Adicionar marketplace",+ "es": "Añadir marketplace",+ "ca": "Afegir marketplace",+ "tr": "Pazar ekle",+ "uk": "Додати маркетплейс"+ },+ "SETTINGS$MARKETPLACE_EDIT_TITLE": {+ "en": "Edit Marketplace",+ "ja": "マーケットプレイスの編集",+ "zh-CN": "编辑市场",+ "zh-TW": "編輯市場",+ "ko-KR": "마켓플레이스 편집",+ "no": "Rediger markedsplass",+ "ar": "تعديل السوق",+ "de": "Marktplatz bearbeiten",+ "fr": "Modifier la marketplace",+ "it": "Modifica marketplace",+ "pt": "Editar marketplace",+ "es": "Editar marketplace",+ "ca": "Edita marketplace",+ "tr": "Pazarı düzenle",+ "uk": "Редагувати маркетплейс"+ },+ "SETTINGS$MARKETPLACE_NAME": {+ "en": "Name",+ "ja": "名前",+ "zh-CN": "名称",+ "zh-TW": "名稱",+ "ko-KR": "이름",+ "no": "Navn",+ "ar": "اسم",+ "de": "Name",+ "fr": "Nom",+ "it": "Nome",+ "pt": "Nome",+ "es": "Nombre",+ "ca": "Nom",+ "tr": "İsim",+ "uk": "Ім'я"+ },+ "SETTINGS$MARKETPLACE_REF": {+ "en": "Branch/Tag/Commit",+ "ja": "ブランチ/タグ/コミット",+ "zh-CN": "分支/标签/提交",+ "zh-TW": "分支/標籤/提交",+ "ko-KR": "브랜치/태그/커밋",+ "no": "Branch/Tag/Commit",+ "ar": "الفرع/العلامة/الالتزام",+ "de": "Branch/Tag/Commit",+ "fr": "Branche/Tag/Commit",+ "it": "Branch/Tag/Commit",+ "pt": "Branch/Tag/Commit",+ "es": "Branch/Tag/Commit",+ "ca": "Branch/Tag/Commit",+ "tr": "Branch/Tag/Commit",+ "uk": "Гілка/Тег/Коміт"+ },+ "SETTINGS$MARKETPLACE_REPO_PATH": {+ "en": "Repository Path",+ "ja": "リポジトリパス",+ "zh-CN": "仓库路径",+ "zh-TW": "儲存庫路徑",+ "ko-KR": "저장소 경로",+ "no": "Repository-sti",+ "ar": "مسار المستودع",+ "de": "Repository-Pfad",+ "fr": "Chemin du dépôt",+ "it": "Percorso repository",+ "pt": "Caminho do repositório",+ "es": "Ruta del repositorio",+ "ca": "Ruta del repositori",+ "tr": "Depo yolu",+ "uk": "Шлях до репозиторію"+ },+ "SETTINGS$AVAILABLE_SKILLS": {+ "en": "Available Skills",+ "ja": "利用可能なスキル",+ "zh-CN": "可用技能",+ "zh-TW": "可用技能",+ "ko-KR": "사용 가능한 스킬",+ "no": "Tilgjengelige ferdigheter",+ "ar": "المهارات المتاحة",+ "de": "Verfügbare Fähigkeiten",+ "fr": "Compétences disponibles",+ "it": "Competenze disponibili",+ "pt": "Habilidades disponíveis",+ "es": "Habilidades disponibles",+ "ca": "Habilitats disponibles",+ "tr": "Kullanılabilir beceriler",+ "uk": "Доступні навички"+ },+ "SETTINGS$SKILLS_AND_PLUGINS": {+ "en": "Skills & Plugins",+ "ja": "スキルとプラグイン",+ "zh-CN": "技能与插件",+ "zh-TW": "技能與外掛",+ "ko-KR": "스킬 및 플러그인",+ "no": "Ferdigheter og plugins",+ "ar": "المهارات والمكونات الإضافية",+ "de": "Skills & Plugins",+ "fr": "Compétences et plugins",+ "it": "Competenze e plugin",+ "pt": "Habilidades e plugins",+ "es": "Habilidades y plugins",+ "ca": "Habilitats i connectors",+ "tr": "Beceriler ve Eklentiler",+ "uk": "Навички та плагіни"+ },+ "SETTINGS$PLUGIN_AUTOLOAD_READONLY": {+ "en": "A plugin's availability is controlled by its marketplace's Auto-Load setting.",+ "ja": "プラグインの利用可否は、そのマーケットプレイスの自動読み込み設定によって制御されます。",+ "zh-CN": "插件的可用性由其市场的自动加载设置控制。",+ "zh-TW": "外掛的可用性由其市場的自動載入設定控制。",+ "ko-KR": "플러그인의 사용 가능 여부는 해당 마켓플레이스의 자동 로드 설정에 따라 제어됩니다.",+ "no": "Tilgjengeligheten til en plugin styres av markedsplassens Automatisk lasting-innstilling.",+ "ar": "يتم التحكم في توفّر المكوّن الإضافي من خلال إعداد التحميل التلقائي الخاص بسوقه.",+ "de": "Die Verfügbarkeit eines Plugins wird durch die Automatisch-laden-Einstellung seines Marktplatzes gesteuert.",+ "fr": "La disponibilité d'un plugin est contrôlée par le paramètre Chargement auto de sa place de marché.",+ "it": "La disponibilità di un plugin è controllata dall'impostazione Caricamento auto del suo marketplace.",+ "pt": "A disponibilidade de um plugin é controlada pela configuração de Carregamento automático do seu mercado.",+ "es": "La disponibilidad de un plugin está controlada por la configuración de Carga automática de su mercado.",+ "ca": "La disponibilitat d'un connector està controlada per la configuració de Càrrega automàtica del seu mercat.",+ "tr": "Bir eklentinin kullanılabilirliği, pazaryerinin Otomatik yükleme ayarına göre denetlenir.",+ "uk": "Доступність плагіна визначається налаштуванням «Автозавантаження» його маркетплейсу."+ },+ "SETTINGS$UNSAVED_CHANGES": {+ "en": "You have unsaved changes",+ "ja": "保存されていない変更があります",+ "zh-CN": "您有未保存的更改",+ "zh-TW": "您有未儲存的變更",+ "ko-KR": "저장되지 않은 변경 사항이 있습니다",+ "no": "Du har ulagrede endringer",+ "ar": "لديك تغييرات غير محفوظة",+ "de": "Sie haben ungespeicherte Änderungen",+ "fr": "Vous avez des modifications non enregistrées",+ "it": "Hai modifiche non salvate",+ "pt": "Você tem alterações não salvas",+ "es": "Tienes cambios sin guardar",+ "ca": "Tens canvis sense desar",+ "tr": "Kaydedilmemiş değişiklikleriniz var",+ "uk": "У вас є незбережені зміни"+ },+ "SETTINGS$MARKETPLACE_REPO_PATH_INVALID": {+ "en": "Repository Path must be a folder inside the repository (e.g., marketplaces/internal), not a URL or absolute path",+ "ja": "リポジトリパスは、URL や絶対パスではなく、リポジトリ内のフォルダ(例: marketplaces/internal)である必要があります",+ "zh-CN": "仓库路径必须是仓库内的文件夹(例如 marketplaces/internal),而不是 URL 或绝对路径",+ "zh-TW": "儲存庫路徑必須是儲存庫內的資料夾(例如 marketplaces/internal),而不是 URL 或絕對路徑",+ "ko-KR": "저장소 경로는 URL이나 절대 경로가 아니라 저장소 내부의 폴더(예: marketplaces/internal)여야 합니다",+ "no": "Repository-sti må være en mappe inne i repositoryet (f.eks. marketplaces/internal), ikke en URL eller absolutt sti",+ "ar": "يجب أن يكون مسار المستودع مجلدًا داخل المستودع (مثل marketplaces/internal)، وليس عنوان URL أو مسارًا مطلقًا",+ "de": "Der Repository-Pfad muss ein Ordner innerhalb des Repositorys sein (z. B. marketplaces/internal), keine URL oder ein absoluter Pfad",+ "fr": "Le chemin du dépôt doit être un dossier à l'intérieur du dépôt (par ex. marketplaces/internal), et non une URL ou un chemin absolu",+ "it": "Il percorso repository deve essere una cartella all'interno del repository (es. marketplaces/internal), non un URL o un percorso assoluto",+ "pt": "O caminho do repositório deve ser uma pasta dentro do repositório (por exemplo, marketplaces/internal), não uma URL ou caminho absoluto",+ "es": "La ruta del repositorio debe ser una carpeta dentro del repositorio (por ejemplo, marketplaces/internal), no una URL ni una ruta absoluta",+ "ca": "La ruta del repositori ha de ser una carpeta dins del repositori (p. ex. marketplaces/internal), no una URL ni una ruta absoluta",+ "tr": "Depo yolu, bir URL veya mutlak yol değil, deponun içindeki bir klasör olmalıdır (ör. marketplaces/internal)",+ "uk": "Шлях до репозиторію має бути текою всередині репозиторію (наприклад, marketplaces/internal), а не URL-адресою чи абсолютним шляхом"+ },+ "SETTINGS$MARKETPLACE_AUTO_LOAD": {+ "en": "Auto-Load",+ "ja": "自動ロード",+ "zh-CN": "自动加载",+ "zh-TW": "自動載入",+ "ko-KR": "자동 로드",+ "no": "Automatisk lasting",+ "ar": "التحميل التلقائي",+ "de": "Automatisch laden",+ "fr": "Chargement automatique",+ "it": "Caricamento automatico",+ "pt": "Carregamento automático",+ "es": "Carga automática",+ "ca": "Càrrega automàtica",+ "tr": "Otomatik yükleme",+ "uk": "Автозавантаження"+ },+ "SETTINGS$MARKETPLACE_SOURCE_READONLY": {+ "en": "Source cannot be changed after creation",+ "ja": "ソースは作成後に変更できません",+ "zh-CN": "创建后无法更改源",+ "zh-TW": "建立後無法變更來源",+ "ko-KR": "생성 후 소스를 변경할 수 없습니다",+ "no": "Kilde kan ikke endres etter opprettelse",+ "ar": "لا يمكن تغيير المصدر بعد الإنشاء",+ "de": "Quelle kann nach Erstellung nicht geändert werden",+ "fr": "La source ne peut pas être modifiée après la création",+ "it": "La fonte non può essere modificata dopo la creazione",+ "pt": "A fonte não pode ser alterada após a criação",+ "es": "La fuente no se puede cambiar después de la creación",+ "ca": "El origen no es pot canviar després de la creació",+ "tr": "Kaynaktan sonra kaynak değiştirilemez",+ "uk": "Джерело не можна змінити після створення"+ },+ "SETTINGS$MARKETPLACE_INSTANCE_READONLY": {+ "en": "Instance marketplaces are configured by environment variables",+ "ja": "インスタンスマーケットプレイスは環境変数で構成されています",+ "zh-CN": "实例市场通过环境变量配置",+ "zh-TW": "執行個體市場透過環境變數配置",+ "ko-KR": "인스턴스 마켓플레이스는 환경 변수로 구성됩니다",+ "no": "Instansmarkedsplasser er konfigurert av miljøvariabler",+ "ar": "يتم تكوين أسواق المثيل بواسطة متغيرات البيئة",+ "de": "Instanz-Marktplätze werden durch Umgebungsvariablen konfiguriert",+ "fr": "Les marketplaces d'instance sont configurées par des variables d'environnement",+ "it": "Le marketplace di istanza sono configurate da variabili di ambiente",+ "pt": "As marketplaces de instância são configuradas por variáveis de ambiente",+ "es": "Las marketplaces de instancia se configuran mediante variables de entorno",+ "ca": "Els marketplaces d'instància es configuren mitjançant variables d'entorn",+ "tr": "Örnek pazar yerleri ortam değişkenleriyle yapılandırılır",+ "uk": "Маркетплейси екземплярів налаштовуються через змінні середовища"+ },+ "SETTINGS$MARKETPLACE_ORG_REQUIRES_ADMIN": {+ "en": "Only organization admins can modify this",+ "ja": "オーガナイゼーション管理者のみが変更できます",+ "zh-CN": "只有组织管理员可以修改",+ "zh-TW": "只有組織管理員可以修改",+ "ko-KR": "조직 관리자만 수정할 수 있습니다",+ "no": "Bare organisasjonsadministratorer kan endre dette",+ "ar": "فقط مشرفو المؤسسة يمكنهم تعديل هذا",+ "de": "Nur Organisationsadministratoren können dies ändern",+ "fr": "Seuls les administrateurs de l'organisation peuvent modifier ceci",+ "it": "Solo gli amministratori dell'organizzazione possono modificare questo",+ "pt": "Apenas administradores da organização podem modificar isto",+ "es": "Solo los administradores de la organización pueden modificar esto",+ "ca": "Només els administradors de l'organització poden modificar això",+ "tr": "Bunu yalnızca kuruluş yöneticileri değiştirebilir",+ "uk": "Лише адміністратори організації можуть це змінити"+ },+ "SETTINGS$MARKETPLACE_ORG_REQUIRE_ADMIN": {+ "en": "Organization admin or owner required to add org-level marketplace",+ "ja": "オーガナイゼーション管理者または所有者が Org レベルマーケットプレイスを追加する必要があります",+ "zh-CN": "需要组织管理员或所有者来添加组织级市场",+ "zh-TW": "需要組織管理員或所有者來新增組織級市場",+ "ko-KR": "조직 수준 마켓플레이스를 추가하려면 조직 관리자 또는 소유자가 필요합니다",+ "no": "Organisasjonsadministrator eller eier kreves for å legge til organisasjonsnivå markedsplass",+ "ar": "مشرف أو مالك المؤسسة مطلوب لإضافة سوق على مستوى المؤسسة",+ "de": "Organisationsadministrator oder Eigentümer erforderlich, um Marktplatz auf Organisationsebene hinzuzufügen",+ "fr": "Administrateur ou propriétaire de l'organisation requis pour ajouter une marketplace au niveau de l'organisation",+ "it": "Amministratore o proprietario dell'organizzazione richiesto per aggiungere marketplace a livello di organizzazione",+ "pt": "Administrador ou proprietário da organização necessário para adicionar marketplace de nível de organização",+ "es": "Se requiere administrador o propietario de la organización para agregar marketplace de nivel de organización",+ "ca": "Es requereix administrador o propietari de l'organització per afegir marketplace de nivell d'organització",+ "tr": "Kuruluş düzeyinde pazar eklemek için kuruluş yöneticisi veya sahibi gereklidir",+ "uk": "Для додавання маркетплейсу рівня організації потрібен адміністратор або власник організації"+ },+ "SETTINGS$OPTIONAL": {+ "en": "optional",+ "ja": "オプション",+ "zh-CN": "可选",+ "zh-TW": "可選",+ "ko-KR": "선택적",+ "no": "valgfri",+ "ar": "اختياري",+ "de": "optional",+ "fr": "optionnel",+ "it": "opzionale",+ "pt": "opcional",+ "es": "opcional",+ "ca": "opcional",+ "tr": "isteğe bağlı",+ "uk": "необов'язковий"+ },+ "SETTINGS$MARKETPLACE_NAME_INVALID": {+ "en": "Name must start with a letter and contain only letters, numbers, hyphens, and underscores",+ "ja": "名前は文字で始まり、文字、数字、ハイフン、アンダースコアのみを含めることができます",+ "zh-CN": "名称必须以字母开头,只能包含字母、数字、连字符和下划线",+ "zh-TW": "名稱必須以字母開頭,只能包含字母、數字、連字符和底線",+ "ko-KR": "이름은 문자로 시작해야 하며 문자, 숫자, 하이픈, 밑줄만 포함할 수 있습니다",+ "no": "Navnet må starte med en bokstav og bare inneholde bokstaver, tall, bindestreker og understrekninger",+ "ar": "يجب أن يبدأ الاسم بحرف وأن يحتوي فقط على أحرف وأرقام وواصلات وشرطات سفلية",+ "de": "Der Name muss mit einem Buchstaben beginnen und darf nur Buchstaben, Zahlen, Bindestriche und Unterstriche enthalten",+ "fr": "Le nom doit commencer par une lettre et ne contenir que des lettres, des chiffres, des tirets et des tirets bas",+ "it": "Il nome deve iniziare con una lettera e contenere solo lettere, numeri, trattini e trattini bassi",+ "pt": "O nome deve começar com uma letra e conter apenas letras, números, hifens e sublinhados",+ "es": "El nombre debe comenzar con una letra y contener solo letras, números, guiones y guiones bajos",+ "ca": "El nom ha de començar amb una lletra i contenir només lletres, números, guions i guions baixos",+ "tr": "İsim bir harfle başlamalı ve yalnızca harf, rakam, tire ve alt çizgi içermelidir",+ "uk": "Ім'я має починатися з літери та містити лише літери, цифри, дефіси та підкреслення"+ },+ "SETTINGS$MARKETPLACE_NAME_REQUIRED": {+ "en": "Name is required",+ "ja": "名前は必須です",+ "zh-CN": "名称是必填项",+ "zh-TW": "名稱是必填項",+ "ko-KR": "이름은 필수입니다",+ "no": "Navn er påkrevd",+ "ar": "الاسم مطلوب",+ "de": "Name ist erforderlich",+ "fr": "Le nom est requis",+ "it": "Il nome è obbligatorio",+ "pt": "Nome é obrigatório",+ "es": "El nombre es obligatorio",+ "ca": "El nom és obligatori",+ "tr": "İsim gereklidir",+ "uk": "Ім'я є обов'язковим"+ },+ "SETTINGS$DELETE_CONFIRMATION_TITLE": {+ "en": "Confirm Delete",+ "ja": "削除の確認",+ "zh-CN": "确认删除",+ "zh-TW": "確認刪除",+ "ko-KR": "삭제 확인",+ "no": "Bekreft sletting",+ "ar": "تأكيد الحذف",+ "de": "Löschen bestätigen",+ "fr": "Confirmer la suppression",+ "it": "Conferma eliminazione",+ "pt": "Confirmar exclusão",+ "es": "Confirmar eliminación",+ "ca": "Confirmar eliminació",+ "tr": "Silmeyi onayla",+ "uk": "Підтвердити видалення"+ },+ "SETTINGS$DELETE_CONFIRMATION_MESSAGE": {+ "en": "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.",+ "ja": "「{{name}}」を削除してもよろしいですか?この操作は元に戻せません。",+ "zh-CN": "您确定要删除“{{name}}”吗?此操作无法撤消。",+ "zh-TW": "您確定要刪除「{{name}}」嗎?此操作無法撤銷。",+ "ko-KR": "\"{{name}}\"을(를) 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.",+ "no": "Er du sikker på at du vil slette \"{{name}}\"? Denne handlingen kan ikke angres.",+ "ar": "هل أنت متأكد من أنك تريد حذف \"{{name}}\"؟ لا يمكن التراجع عن هذا الإجراء.",+ "de": "Sind Sie sicher, dass Sie \"{{name}}\" löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.",+ "fr": "Êtes-vous sûr de vouloir supprimer \"{{name}}\" ? Cette action est irréversible.",+ "it": "Sei sicuro di voler eliminare \"{{name}}\"? Questa azione non può essere annullata.",+ "pt": "Tem certeza de que deseja excluir \"{{name}}\"? Esta ação não pode ser desfeita.",+ "es": "¿Está seguro de que desea eliminar \"{{name}}\"? Esta acción no se puede deshacer.",+ "ca": "Esteu segur que voleu eliminar \"{{name}}\"? Aquesta acció no es pot desfer.",+ "tr": "\"{{name}}\" dosyasını silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.",+ "uk": "Ви впевнені, що хочете видалити \"{{name}}\"? Цю дію не можна скасувати."+ },+ "BUTTON$EDIT": {+ "en": "Edit",+ "ja": "編集",+ "zh-CN": "编辑",+ "zh-TW": "編輯",+ "ko-KR": "편집",+ "no": "Rediger",+ "it": "Modifica",+ "pt": "Editar",+ "es": "Editar",+ "ar": "تحرير",+ "fr": "Modifier",+ "tr": "Düzenle",+ "de": "Bearbeiten",+ "uk": "Редагувати",+ "ca": "Edita"+ },+ "SETTINGS$MARKETPLACE_SOURCE_REQUIRED": {+ "en": "Source is required",+ "ja": "ソースは必須です",+ "zh-CN": "源是必填项",+ "zh-TW": "來源是必填項",+ "ko-KR": "소스가 필수입니다",+ "no": "Kilde er påkrevd",+ "ar": "المصدر مطلوب",+ "de": "Quelle ist erforderlich",+ "fr": "La source est requise",+ "it": "La fonte è obbligatoria",+ "pt": "A fonte é obrigatória",+ "es": "La fuente es obligatoria",+ "ca": "L'origen és obligatori",+ "tr": "Kaynak gereklidir",+ "uk": "Джерело є обов'язковим"}}diff --git a/frontend/src/routes/skills-settings.tsx b/frontend/src/routes/skills-settings.tsxindex 6504cb0438..b0458b4a77 100644--- a/frontend/src/routes/skills-settings.tsx+++ b/frontend/src/routes/skills-settings.tsx@@ -1,128 +1,664 @@-import React from "react";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useState,+ useRef,+} from "react";import { useTranslation } from "react-i18next";-import { useSaveSettings } from "#/hooks/mutation/use-save-settings";+import { BrandButton } from "#/components/features/settings/brand-button";+import { Typography } from "#/ui/typography";+import { MarketplaceModal } from "#/components/features/settings/marketplace-modal";+import { DeleteConfirmationModal } from "#/components/features/settings/delete-confirmation-modal";import { useSettings } from "#/hooks/query/use-settings";import { useSkills } from "#/hooks/query/use-skills";-import { BrandButton } from "#/components/features/settings/brand-button";-import { SettingsSwitch } from "#/components/features/settings/settings-switch";+import { useMe } from "#/hooks/query/use-me";+import { useOrganizationAppSettings } from "#/hooks/query/use-organization-app-settings";+import { useOrganization } from "#/hooks/query/use-organization";+import { useMarketplaceMutations } from "#/hooks/mutation/use-marketplace-mutations";+import { useSkillMutations } from "#/hooks/mutation/use-skill-mutations";+import { MarketplaceTable } from "#/components/features/settings/skills-settings/marketplace-table";+import { SkillsTable } from "#/components/features/settings/skills-settings/skills-table";+import { MarketplaceRegistration, SkillWithState } from "#/types/settings";import { I18nKey } from "#/i18n/declaration";-import {- displayErrorToast,- displaySuccessToast,-} from "#/utils/custom-toast-handlers";-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import SkillsService from "#/api/skills-service";+import { displayErrorToast } from "#/utils/custom-toast-handlers";function SkillsSettingsScreen() {const { t } = useTranslation();- const { mutate: saveSettings, isPending } = useSaveSettings();+ // Query data+ const { data: user } = useMe();const { data: settings, isLoading: settingsLoading } = useSettings();const { data: skills, isLoading: skillsLoading } = useSkills();+ const { data: orgAppSettings } = useOrganizationAppSettings();+ const { data: currentOrganization } = useOrganization();- // Local state: set of skill names the user has toggled off- const [disabledSet, setDisabledSet] = React.useState<Set<string>>(new Set());- const [hasChanges, setHasChanges] = React.useState(false);+ // Permissions+ const userRole = user?.role ?? "member";+ const isAdminOrOwner = userRole === "admin" || userRole === "owner";- // Sync local state with server settings when data first arrives- React.useEffect(() => {- if (settings?.disabled_skills) {- setDisabledSet(new Set(settings.disabled_skills));+ // Active scope derived from current organization+ const activeScope = useMemo((): "org" | "personal" => {+ if (!currentOrganization || currentOrganization.is_personal) {+ return "personal";}- }, [settings?.disabled_skills]);+ return "org";+ }, [currentOrganization]);++ // State for skills+ const [skillsState, setSkillsState] = useState<SkillWithState[]>([]);+ const originalSkillsRef = useRef<SkillWithState[]>([]);++ // State for marketplaces+ const [allMarketplaces, setAllMarketplaces] = useState<+ MarketplaceRegistration[]+ >([]);+ const originalMarketplacesRef = useRef<MarketplaceRegistration[]>([]);+ const [lastKnownUpdatedAt, setLastKnownUpdatedAt] = useState<string | null>(+ null,+ );++ // Modal state+ const [isModalOpen, setIsModalOpen] = useState(false);+ const [modalMode, setModalMode] = useState<"add" | "edit">("add");+ const [selectedMarketplace, setSelectedMarketplace] =+ useState<MarketplaceRegistration | null>(null);+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);+ const [marketplaceToDelete, setMarketplaceToDelete] =+ useState<MarketplaceRegistration | null>(null);- const handleToggle = (skillName: string, enabled: boolean) => {- setDisabledSet((prev) => {- const next = new Set(prev);- if (enabled) {- next.delete(skillName);+ // Filter state+ const [searchQuery, setSearchQuery] = useState("");+ const [selectedType, setSelectedType] = useState<string | null>(null);+ const [selectedRepository, setSelectedRepository] = useState<string | null>(+ null,+ );++ // Mutations from hooks+ const marketplaceMutations = useMarketplaceMutations();+ const skillMutations = useSkillMutations();++ // Derive saving state from mutations+ const isSaving =+ marketplaceMutations.savePersonal.isPending ||+ marketplaceMutations.saveOrg.isPending ||+ skillMutations.saveDisabledSkills.isPending;++ const isDeleting =+ marketplaceMutations.deletePersonal.isPending ||+ marketplaceMutations.deleteOrg.isPending;++ // Change detection+ const hasSkillChanges = useMemo(() => {+ const original = originalSkillsRef.current;+ if (skillsState.length !== original.length) return false;+ const originalById = new Map(original.map((s) => [s.id, s]));+ return skillsState.some((skill) => {+ const orig = originalById.get(skill.id);+ return orig?.isEnabled !== skill.isEnabled;+ });+ }, [skillsState]);++ const hasMarketplaceChanges = useMemo(() => {+ const original = originalMarketplacesRef.current;+ if (allMarketplaces.length !== original.length) return false;+ // Name is the marketplace identity (unique across scopes).+ const originalByName = new Map(original.map((mp) => [mp.name, mp]));+ return allMarketplaces.some((mp) => {+ if (mp.scope === "instance") return false;+ const orig = originalByName.get(mp.name);+ return Boolean(mp.auto_load) !== Boolean(orig?.auto_load);+ });+ }, [allMarketplaces]);++ // Update lastKnownUpdatedAt when settings changes (org settings updated_at)+ useEffect(() => {+ // Use updated_at from orgAppSettings for 409 conflict handling+ if (orgAppSettings?.updated_at) {+ setLastKnownUpdatedAt(orgAppSettings.updated_at);+ }+ }, [orgAppSettings?.updated_at]);++ // Data loading effect - depends on settings and skills+ useEffect(() => {+ if (!settings || !skills) return undefined;+ // Guards against out-of-order async results when settings/skills change+ // (or the component unmounts) before the marketplace preview resolves.+ let cancelled = false;++ // Backend returns scope directly on all marketplaces+ const all: MarketplaceRegistration[] = [+ ...(settings.inherited_marketplaces || []),+ ...(settings.registered_marketplaces || []),+ ];+ setAllMarketplaces(all);+ originalMarketplacesRef.current = all;++ // Marketplace lookup for skills (keyed by source; scope comes from backend).+ const marketplaceMap = new Map<+ string,+ { source: string; auto_load?: boolean; scope: string }+ >();+ for (const mp of all) {+ marketplaceMap.set(mp.source, {+ source: mp.source,+ auto_load: mp.auto_load,+ scope: mp.scope ?? "personal",+ });+ }++ // Map global/user/repo skills with marketplace info+ const disabledSet = new Set(settings.disabled_skills || []);+ const mappedSkills: SkillWithState[] = skills.map((skill) => {+ let repoUrl = skill.source;+ let skillScope: "instance" | "org" | "personal" = "personal";++ if (skill.source === "global") {+ skillScope = "instance";+ } else if (skill.source === "user") {+ skillScope = "personal";} else {- next.add(skillName);+ const marketplace =+ marketplaceMap.get(skill.name) || marketplaceMap.get(skill.source);+ if (marketplace) {+ repoUrl = marketplace.source;+ skillScope = marketplace.scope as "instance" | "org" | "personal";+ }+ }++ return {+ ...skill,+ id: skill.name,+ repository: repoUrl,+ scope: skillScope,+ isEnabled: !disabledSet.has(skill.name),+ isAutoLoad: !!marketplaceMap.get(skill.name)?.auto_load,+ };+ });++ // Fetch marketplace skills and merge with global/user skills+ const fetchMarketplaceSkills = async () => {+ if (all.length === 0) {+ if (!cancelled) {+ setSkillsState(mappedSkills);+ originalSkillsRef.current = mappedSkills;+ }+ return;+ }++ try {+ const preview = await SkillsService.getMarketplaceSkills(all);+ if (cancelled) return;++ if (preview.errors && preview.errors.length > 0) {+ preview.errors.forEach((error) => {+ displayErrorToast(`Marketplace error: ${error}`);+ });+ }++ // Seed with global/user/repo names so a marketplace skill sharing a name+ // with an existing skill never creates a duplicate row / React key.+ const seenSkillNames = new Set<string>(mappedSkills.map((s) => s.name));+ const marketplaceSkills: SkillWithState[] = [];++ for (const skill of preview.skills) {+ if (!seenSkillNames.has(skill.name)) {+ seenSkillNames.add(skill.name);++ const marketplace = all.find(+ (mp) => skill.source === `marketplace:${mp.name}`,+ );+ const mpWithScope = marketplace+ ? marketplaceMap.get(marketplace.source)+ : undefined;+ const skillScope =+ (mpWithScope?.scope as "instance" | "org" | "personal") ||+ "personal";++ marketplaceSkills.push({+ ...skill,+ id: skill.name,+ repository: marketplace?.source || skill.source,+ scope: skillScope,+ isEnabled: !disabledSet.has(skill.name),+ isAutoLoad: !!marketplace?.auto_load,+ });+ }+ }++ // Plugins advertised by marketplace manifests, shown at the plugin+ // level (bundled skills are not expanded). Enablement/auto-load is+ // governed by the parent marketplace, so these rows are read-only here.+ const marketplacePlugins: SkillWithState[] = (+ preview.plugins ?? []+ ).map((plugin) => {+ const mp = marketplaceMap.get(plugin.source);+ const pluginScope =+ (mp?.scope as "instance" | "org" | "personal") || "personal";+ const autoLoad = !!mp?.auto_load;+ return {+ name: plugin.name,+ type: "plugin",+ source: `marketplace:${plugin.marketplace}`,+ id: `plugin:${plugin.marketplace}:${plugin.name}`,+ repository: plugin.source,+ scope: pluginScope,+ isEnabled: autoLoad,+ isAutoLoad: autoLoad,+ };+ });++ const combinedSkills = [+ ...mappedSkills,+ ...marketplaceSkills,+ ...marketplacePlugins,+ ];+ setSkillsState(combinedSkills);+ originalSkillsRef.current = combinedSkills;+ } catch {+ if (!cancelled) {+ setSkillsState(mappedSkills);+ originalSkillsRef.current = mappedSkills;+ }}- return next;+ };++ fetchMarketplaceSkills();+ return () => {+ cancelled = true;+ };+ }, [settings, skills]);++ const filteredSkills = useMemo(+ () =>+ skillsState.filter((skill) => {+ const matchesSearch =+ !searchQuery ||+ skill.name.toLowerCase().includes(searchQuery.toLowerCase());+ const matchesType =+ !selectedType ||+ selectedType === "all" ||+ skill.type.toLowerCase() === selectedType.toLowerCase();+ const matchesRepo =+ !selectedRepository ||+ selectedRepository === "all" ||+ skill.repository === selectedRepository;+ return matchesSearch && matchesType && matchesRepo;+ }),+ [skillsState, searchQuery, selectedType, selectedRepository],+ );++ const typeOptions = useMemo(() => {+ const types = new Set(skillsState.map((s) => s.type));+ return [+ { key: "all", label: t(I18nKey.SETTINGS$ALL_TYPES) },+ ...Array.from(types).map((type) => ({+ key: type.toLowerCase(),+ label: type.charAt(0).toUpperCase() + type.slice(1),+ })),+ ];+ }, [skillsState, t]);++ const repositoryOptions = useMemo(() => {+ const repos = new Set(skillsState.map((s) => s.repository));+ return [+ { key: "all", label: t(I18nKey.SETTINGS$ALL_REPOSITORIES) },+ ...Array.from(repos).map((repo) => ({+ key: repo,+ label: repo,+ })),+ ];+ }, [skillsState, t]);++ // Handlers with useCallback+ const handleToggleSkillEnabled = useCallback((skillId: string) => {+ setSkillsState((prev) =>+ prev.map((s) =>+ s.id === skillId ? { ...s, isEnabled: !s.isEnabled } : s,+ ),+ );+ }, []);++ const handleSaveSkillChanges = useCallback(() => {+ // Plugin rows are read-only previews whose toggle mirrors the marketplace's+ // auto-load; they must never leak into the user's disabled_skills list.+ const disabledSkills = skillsState+ .filter((s) => s.type !== "plugin" && !s.isEnabled)+ .map((s) => s.name);++ skillMutations.saveDisabledSkills.mutate(disabledSkills, {+ onSuccess: () => {+ originalSkillsRef.current = skillsState;+ },});- setHasChanges(true);- };+ }, [skillsState, skillMutations]);- const handleSave = () => {- saveSettings(- { disabled_skills: Array.from(disabledSet) },- {+ const handleToggleMarketplaceAutoLoad = useCallback((name: string) => {+ setAllMarketplaces((prev) =>+ prev.map((m) =>+ m.name === name ? { ...m, auto_load: !m.auto_load } : m,+ ),+ );+ }, []);++ const handleSaveMarketplaceChanges = useCallback(() => {+ const original = originalMarketplacesRef.current;+ const origByName = new Map(original.map((mp) => [mp.name, mp]));+ const autoLoadChanged = (mp: MarketplaceRegistration) =>+ Boolean(mp.auto_load) !== Boolean(origByName.get(mp.name)?.auto_load);++ // Never send the backend-derived `scope`.+ const toPayload = (mp: MarketplaceRegistration) => ({+ name: mp.name,+ source: mp.source,+ ref: mp.ref,+ repo_path: mp.repo_path,+ auto_load: mp.auto_load,+ });++ // Only persist a scope whose toggles actually changed, so a personal edit+ // never re-writes the org list (churning org.updated_at / causing conflicts).+ const personalChanged = allMarketplaces.some(+ (mp) => mp.scope === "personal" && autoLoadChanged(mp),+ );+ const orgChanged = allMarketplaces.some(+ (mp) => mp.scope === "org" && autoLoadChanged(mp),+ );++ if (personalChanged) {+ const personal = allMarketplaces+ .filter((mp) => mp.scope === "personal")+ .map(toPayload);+ marketplaceMutations.savePersonal.mutate(personal, {onSuccess: () => {- displaySuccessToast(t(I18nKey.SETTINGS$SAVED));- setHasChanges(false);+ originalMarketplacesRef.current = allMarketplaces;},- onError: (error) => {- const errorMessage = retrieveAxiosErrorMessage(error);- displayErrorToast(errorMessage || t(I18nKey.ERROR$GENERIC));+ });+ }++ // Org marketplaces are admin/owner-only (also enforced server-side).+ if (orgChanged && isAdminOrOwner) {+ const org = allMarketplaces+ .filter((mp) => mp.scope === "org")+ .map(toPayload);+ marketplaceMutations.saveOrg.mutate(+ { marketplaces: org, lastKnownUpdatedAt },+ {+ onSuccess: () => {+ originalMarketplacesRef.current = allMarketplaces;+ },},- },- );- };+ );+ }+ }, [+ allMarketplaces,+ isAdminOrOwner,+ lastKnownUpdatedAt,+ marketplaceMutations,+ ]);++ const openAddModal = useCallback(() => {+ setModalMode("add");+ setSelectedMarketplace(null);+ setIsModalOpen(true);+ }, []);++ const openEditModal = useCallback((marketplace: MarketplaceRegistration) => {+ setModalMode("edit");+ setSelectedMarketplace(marketplace);+ setIsModalOpen(true);+ }, []);++ const openDeleteModal = useCallback(+ (marketplace: MarketplaceRegistration) => {+ setMarketplaceToDelete(marketplace);+ setIsDeleteModalOpen(true);+ },+ [],+ );++ const handleSaveMarketplace = useCallback(+ (data: {+ name: string;+ source: string;+ ref?: string;+ repo_path?: string;+ auto_load?: boolean;+ scope?: "org" | "personal";+ }) => {+ // Edit keeps the item's existing scope; add uses the chosen scope+ // (admins in an org) or defaults to personal.+ const targetScope: "org" | "personal" =+ modalMode === "edit" && selectedMarketplace+ ? (selectedMarketplace.scope as "org" | "personal")+ : data.scope || "personal";++ const entry: MarketplaceRegistration = {+ name: data.name,+ source: data.source,+ ref: data.ref,+ repo_path: data.repo_path,+ auto_load: data.auto_load,+ scope: targetScope,+ };++ // Never send the backend-derived `scope`.+ const toPayload = (mp: MarketplaceRegistration) => ({+ name: mp.name,+ source: mp.source,+ ref: mp.ref,+ repo_path: mp.repo_path,+ auto_load: mp.auto_load,+ });++ const scopeList = allMarketplaces.filter(+ (mp) => mp.scope === targetScope,+ );+ // On edit, replace the row identified by its original name (name is the+ // identity and may itself be edited); on add, append.+ const updatedList =+ modalMode === "edit" && selectedMarketplace+ ? scopeList.map((mp) =>+ mp.name === selectedMarketplace.name ? entry : mp,+ )+ : [...scopeList, entry];+ const updated = updatedList.map(toPayload);++ if (targetScope === "org") {+ marketplaceMutations.saveOrg.mutate(+ { marketplaces: updated, lastKnownUpdatedAt },+ { onSuccess: () => setIsModalOpen(false) },+ );+ } else {+ marketplaceMutations.savePersonal.mutate(updated, {+ onSuccess: () => setIsModalOpen(false),+ });+ }+ },+ [+ modalMode,+ selectedMarketplace,+ allMarketplaces,+ lastKnownUpdatedAt,+ marketplaceMutations,+ ],+ );++ const handleDeleteMarketplace = useCallback(() => {+ if (!marketplaceToDelete) return;++ if (marketplaceToDelete.scope === "org") {+ marketplaceMutations.deleteOrg.mutate(+ { marketplaceName: marketplaceToDelete.name, lastKnownUpdatedAt },+ {+ onSuccess: () => {+ setIsDeleteModalOpen(false);+ setMarketplaceToDelete(null);+ },+ },+ );+ } else if (marketplaceToDelete.scope === "personal") {+ marketplaceMutations.deletePersonal.mutate(marketplaceToDelete.name, {+ onSuccess: () => {+ setIsDeleteModalOpen(false);+ setMarketplaceToDelete(null);+ },+ });+ }+ }, [marketplaceToDelete, lastKnownUpdatedAt, marketplaceMutations]);++ // Permission helpers+ const canEditMarketplace = useCallback(+ (mp: MarketplaceRegistration) => {+ if (mp.scope === "instance") return false;+ if (mp.scope === "org") return isAdminOrOwner;+ return true;+ },+ [isAdminOrOwner],+ );++ const getAutoLoadToggleTitle = useCallback(+ (scope: "instance" | "org" | "personal") => {+ if (scope === "instance")+ return t(I18nKey.SETTINGS$MARKETPLACE_INSTANCE_READONLY);+ if (scope === "org" && !isAdminOrOwner)+ return t(I18nKey.SETTINGS$MARKETPLACE_ORG_REQUIRES_ADMIN);+ return undefined;+ },+ [isAdminOrOwner, t],+ );const isLoading = settingsLoading || skillsLoading || !settings;+ if (isLoading) {+ return (+ <div className="flex h-64 items-center justify-center">+ <div className="animate-pulse text-sm text-tertiary-alt">+ Loading...+ </div>+ </div>+ );+ }++ const hasUnsavedChanges = hasSkillChanges || hasMarketplaceChanges;+return (- <div data-testid="skills-settings-screen" className="flex flex-col h-full">- <p className="text-xs mb-4">{t(I18nKey.SETTINGS$SKILLS_DESCRIPTION)}</p>-- <div className="flex-1 overflow-auto custom-scrollbar-always">- {isLoading && (- <div className="flex flex-col gap-4">- {[1, 2, 3].map((i) => (- <div- key={i}- className="h-8 w-64 rounded bg-tertiary animate-pulse"- />- ))}+ <div className="flex min-h-full flex-col">+ <div className="flex flex-col gap-10 pb-6">+ {/* Marketplaces */}+ <section className="flex flex-col gap-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="flex flex-col gap-1">+ <Typography.H2>{t(I18nKey.SETTINGS$MARKETPLACES)}</Typography.H2>+ <Typography.Paragraph className="max-w-2xl text-sm text-tertiary-alt">+ {t(I18nKey.SETTINGS$CONNECT_MARKETPLACES_DESCRIPTION)}+ </Typography.Paragraph>+ </div>+ <BrandButton+ testId="add-marketplace-button"+ variant="primary"+ type="button"+ onClick={() => openAddModal()}+ >+ {t(I18nKey.SETTINGS$MARKETPLACE_ADD)}+ </BrandButton></div>- )}- {!isLoading && (!skills || skills.length === 0) && (- <p className="text-sm text-tertiary">- {t(I18nKey.SETTINGS$SKILLS_NO_SKILLS)}- </p>- )}+ <MarketplaceTable+ marketplaces={allMarketplaces}+ onToggleAutoLoad={handleToggleMarketplaceAutoLoad}+ onEdit={openEditModal}+ onDelete={openDeleteModal}+ canEdit={canEditMarketplace}+ getAutoLoadTitle={getAutoLoadToggleTitle}+ isAdminOrOwner={isAdminOrOwner}+ />+ </section>- {!isLoading && skills && skills.length > 0 && (- <div className="flex flex-col gap-4">- {skills.map((skill) => (- <div key={skill.name} className="flex flex-col gap-0.5">- <SettingsSwitch- testId={`skill-toggle-${skill.name}`}- isToggled={!disabledSet.has(skill.name)}- onToggle={(enabled) => handleToggle(skill.name, enabled)}- >- {skill.name}- </SettingsSwitch>- {skill.triggers && skill.triggers.length > 0 && (- <span className="text-xs text-neutral-500 ml-14">- {t(I18nKey.SETTINGS$SKILLS_TRIGGERS, {- triggers: skill.triggers.join(", "),- interpolation: { escapeValue: false },- })}- </span>- )}- <span className="text-xs text-neutral-500 ml-14">- {skill.source} / {skill.type}- </span>- </div>- ))}+ {/* Available Skills */}+ <section className="flex flex-col gap-4">+ <div className="flex flex-col gap-1">+ <Typography.H2>+ {t(I18nKey.SETTINGS$SKILLS_AND_PLUGINS)}+ </Typography.H2>+ <Typography.Paragraph className="max-w-2xl text-sm text-tertiary-alt">+ {t(I18nKey.SETTINGS$SKILLS_DESCRIPTION)}+ </Typography.Paragraph></div>- )}++ <SkillsTable+ skills={filteredSkills}+ onToggle={handleToggleSkillEnabled}+ typeOptions={typeOptions}+ repositoryOptions={repositoryOptions}+ searchQuery={searchQuery}+ onSearchChange={setSearchQuery}+ onTypeChange={setSelectedType}+ onRepositoryChange={setSelectedRepository}+ />+ </section></div>- <div className="flex gap-6 p-6 justify-end">+ {/* Sticky action bar — keeps Save reachable without scrolling to the end */}+ <div className="sticky bottom-0 z-10 mt-auto flex items-center justify-end gap-4 border-t border-tertiary bg-base/95 py-4 backdrop-blur-sm">+ {hasUnsavedChanges && (+ <span className="text-sm text-tertiary-alt">+ {t(I18nKey.SETTINGS$UNSAVED_CHANGES)}+ </span>+ )}<BrandButtontestId="skills-save-button"variant="primary"type="button"- isDisabled={isPending || !hasChanges}- onClick={handleSave}+ isDisabled={isSaving || !hasUnsavedChanges}+ onClick={() => {+ if (hasSkillChanges) handleSaveSkillChanges();+ if (hasMarketplaceChanges) handleSaveMarketplaceChanges();+ }}>- {!isPending && t(I18nKey.SETTINGS$SAVE_CHANGES)}- {isPending && t(I18nKey.SETTINGS$SAVING)}+ {isSaving+ ? t(I18nKey.SETTINGS$SAVING)+ : t(I18nKey.SETTINGS$SAVE_CHANGES)}</BrandButton></div>++ {/* Marketplace Modal */}+ <MarketplaceModal+ isOpen={isModalOpen}+ mode={modalMode}+ allowScopeSelection={isAdminOrOwner && activeScope === "org"}+ marketplace={+ selectedMarketplace+ ? {+ name: selectedMarketplace.name,+ source: selectedMarketplace.source,+ ref: selectedMarketplace.ref,+ repo_path: selectedMarketplace.repo_path,+ auto_load: selectedMarketplace.auto_load,+ scope: selectedMarketplace.scope,+ }+ : null+ }+ onClose={() => setIsModalOpen(false)}+ onSave={handleSaveMarketplace}+ isSaving={+ marketplaceMutations.saveOrg.isPending ||+ marketplaceMutations.savePersonal.isPending+ }+ />++ {/* Delete Confirmation Modal */}+ <DeleteConfirmationModal+ isOpen={isDeleteModalOpen}+ itemName={marketplaceToDelete?.name || ""}+ onClose={() => {+ setIsDeleteModalOpen(false);+ setMarketplaceToDelete(null);+ }}+ onDelete={handleDeleteMarketplace}+ isDeleting={isDeleting}+ /></div>);}diff --git a/frontend/src/types/settings.ts b/frontend/src/types/settings.tsindex 678e326300..afbc43734a 100644--- a/frontend/src/types/settings.ts+++ b/frontend/src/types/settings.ts@@ -113,8 +113,36 @@ export type SkillInfo = {triggers?: string[];};+// A plugin advertised by a marketplace manifest. The UI operates at the plugin+// level, so a plugin's bundled skills are not expanded into this shape.+export type MarketplacePluginInfo = {+ name: string;+ description?: string | null;+ source: string; // the marketplace registration source (e.g. github:owner/repo)+ marketplace: string; // the marketplace registration name+};+export type SettingsScope = "personal" | "org";+export type MarketplaceRegistration = {+ name: string;+ source: string;+ ref?: string;+ repo_path?: string;+ auto_load?: boolean;+ // Backend-derived; present on reads, omitted from write payloads (the backend+ // sets scope per storage layer). Optional so save payloads need not include it.+ scope?: "instance" | "org" | "personal";+};++export interface SkillWithState extends SkillInfo {+ id: string;+ repository: string;+ scope: "instance" | "org" | "personal";+ isEnabled: boolean;+ isAutoLoad: boolean;+}+export type Settings = {llm_model: string;llm_base_url: string;@@ -150,5 +178,8 @@ export type Settings = {conversation_settings_schema?: SettingsSchema | null;conversation_settings?: Record<string, SettingsValue> | null;sandbox_grouping_strategy?: SandboxGroupingStrategy;+ registered_marketplaces?: MarketplaceRegistration[];+ inherited_marketplaces?: MarketplaceRegistration[];+ updated_at?: string;default_sandbox_spec_id?: string | null;};diff --git a/openhands/app_server/app_conversation/app_conversation_service_base.py b/openhands/app_server/app_conversation/app_conversation_service_base.pyindex 06e69a14fe..c39171b252 100644--- a/openhands/app_server/app_conversation/app_conversation_service_base.py+++ b/openhands/app_server/app_conversation/app_conversation_service_base.py@@ -30,6 +30,7 @@ from openhands.app_server.app_conversation.skill_loader import (from openhands.app_server.integrations.service_types import ProviderTypefrom openhands.app_server.sandbox import workspace_archivefrom openhands.app_server.sandbox.sandbox_models import SandboxInfo+from openhands.app_server.settings.settings_models import MarketplaceRegistrationfrom openhands.app_server.user.user_context import UserContextfrom openhands.app_server.utils.auth import looks_like_jwtfrom openhands.app_server.utils.git import ensure_valid_git_branch_name@@ -103,6 +104,7 @@ class AppConversationServiceBase(AppConversationService, ABC):selected_repository: str | None,project_dir: str,agent_server_url: str,+ registered_marketplaces: list[MarketplaceRegistration] | None = None,) -> list[Skill]:"""Load skills from all sources via the agent-server.@@ -113,12 +115,16 @@ class AppConversationServiceBase(AppConversationService, ABC):- Organization skills (from {org}/.openhands repo)- Project/repo skills (from repo .agents/skills/, .openhands/microagents/, and legacy .openhands/skills/)- Sandbox skills (from exposed URLs)+ - Registered marketplaces (from user settings)Args:sandbox: SandboxInfo containing exposed URLs and agent-server URLselected_repository: Repository name or Noneproject_dir: Project root directory (resolved via get_project_dir).agent_server_url: Agent-server URL (required)+ registered_marketplaces: Optional list of MarketplaceRegistration objects+ from user settings. Marketplaces with auto_load=True will have+ their plugins loaded automatically.Returns:List of merged Skill objects from all sources, or empty list on failure@@ -149,6 +155,7 @@ class AppConversationServiceBase(AppConversationService, ABC):load_user=True,load_project=True,load_org=True,+ registered_marketplaces=registered_marketplaces,)_logger.info(@@ -218,6 +225,7 @@ class AppConversationServiceBase(AppConversationService, ABC):selected_repository: str | None,project_dir: str,disabled_skills: list[str] | None = None,+ registered_marketplaces: list[MarketplaceRegistration] | None = None,):"""Load all skills and update agent with them.@@ -227,6 +235,8 @@ class AppConversationServiceBase(AppConversationService, ABC):selected_repository: Repository name or None (used for org config)project_dir: Project root directory (already resolved via get_project_dir).disabled_skills: Optional list of skill names to exclude+ registered_marketplaces: Optional composed marketplaces (instance ++ org + user) whose auto_load plugins the agent-server should load.Returns:Updated agent with skills loaded into context@@ -237,6 +247,7 @@ class AppConversationServiceBase(AppConversationService, ABC):selected_repository,project_dir,agent_server_url,+ registered_marketplaces=registered_marketplaces,)# Filter out disabled skillsdiff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.pyindex 32265bd620..201bb3f6f3 100644--- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py+++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py@@ -98,7 +98,14 @@ from openhands.app_server.sandbox.sandbox_spec_service import (from openhands.app_server.services.injector import InjectorStatefrom openhands.app_server.services.jwt_service import JwtServicefrom openhands.app_server.settings.llm_profiles import resolve_profile_llm-from openhands.app_server.settings.settings_models import grouped_workspace_dir+from openhands.app_server.settings.marketplace_composition import (+ load_composed_marketplaces,+ marketplace_plugin_loading_enabled,+)+from openhands.app_server.settings.settings_models import (+ MarketplaceRegistration,+ grouped_workspace_dir,+)from openhands.app_server.user.user_context import UserContextfrom openhands.app_server.user.user_models import UserInfofrom openhands.app_server.utils.docker_utils import (@@ -1616,6 +1623,11 @@ class LiveStatusAppConversationService(AppConversationServiceBase):"""user = await self.user_context.get_user_info()+ # Compose instance + org + user marketplaces once for both arms below.+ # Enabled by default; inert (None) only when ENABLE_MARKETPLACE_PLUGIN_LOADING+ # is explicitly disabled or no marketplaces are configured.+ registered_marketplaces = await self._resolve_registered_marketplaces(user)+# Route ACP agent settings to the ACP-specific builderif isinstance(user.agent_settings, ACPAgentSettings):acp_request = await self._build_acp_start_conversation_request(@@ -1640,6 +1652,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):selected_repository,get_project_dir(working_dir, selected_repository),user.disabled_skills,+ registered_marketplaces,)return acp_request@@ -1842,10 +1855,38 @@ class LiveStatusAppConversationService(AppConversationServiceBase):selected_repository,project_dir,user.disabled_skills,+ registered_marketplaces,)return request+ async def _resolve_registered_marketplaces(+ self, user: UserInfo+ ) -> list[MarketplaceRegistration] | None:+ """Compose instance + org + user marketplaces for conversation start.++ Enabled by default; returns ``None`` (feature inert) when+ ENABLE_MARKETPLACE_PLUGIN_LOADING is explicitly disabled. Never raises:+ any failure degrades to no marketplaces so it can never block+ conversation creation.+ """+ if not marketplace_plugin_loading_enabled():+ return None+ try:+ from openhands.app_server.shared import SettingsStoreImpl++ user_id = await self.user_context.get_user_id()+ settings_store = await SettingsStoreImpl.get_instance(user_id)+ composed = await load_composed_marketplaces(+ user_id, user.registered_marketplaces, settings_store+ )+ return composed.all or None+ except Exception as e:+ _logger.warning(+ 'Failed to compose marketplaces for conversation start: %s', e+ )+ return None+async def _load_skills_onto_request(self,request: StartConversationRequest,@@ -1854,6 +1895,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):selected_repository: str | None,project_dir: str,disabled_skills: list[str] | None,+ registered_marketplaces: list[MarketplaceRegistration] | None = None,) -> StartConversationRequest:"""Load workspace skills onto a conversation request's agent.@@ -1869,6 +1911,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):selected_repository,project_dir,disabled_skills=disabled_skills,+ registered_marketplaces=registered_marketplaces,)return request.model_copy(update={'agent': updated_agent})except Exception as e:diff --git a/openhands/app_server/app_conversation/skill_loader.py b/openhands/app_server/app_conversation/skill_loader.pyindex 4364c62a72..089878d53b 100644--- a/openhands/app_server/app_conversation/skill_loader.py+++ b/openhands/app_server/app_conversation/skill_loader.py@@ -12,6 +12,7 @@ All source-specific skill loading is handled by the agent-server.import asyncioimport logging+from typing import Anyimport httpxfrom pydantic import BaseModel@@ -19,6 +20,7 @@ from pydantic import BaseModelfrom openhands.app_server.integrations.provider import ProviderHandler, ProviderTypefrom openhands.app_server.integrations.service_types import AuthenticationErrorfrom openhands.app_server.sandbox.sandbox_models import SandboxInfo+from openhands.app_server.settings.settings_models import MarketplaceRegistrationfrom openhands.app_server.user.user_context import UserContextfrom openhands.sdk.skills import KeywordTrigger, Skill, TaskTrigger@@ -400,6 +402,7 @@ async def load_skills_from_agent_server(load_user: bool = True,load_project: bool = True,load_org: bool = True,+ registered_marketplaces: list[MarketplaceRegistration] | None = None,) -> list[Skill]:"""Load all skills from the agent-server.@@ -416,6 +419,7 @@ async def load_skills_from_agent_server(load_user: Whether to load user skills (default: True)load_project: Whether to load project skills (default: True)load_org: Whether to load organization skills (default: True)+ registered_marketplaces: List of marketplace registrations (optional)Returns:List of Skill objects merged from all sources.@@ -425,7 +429,7 @@ async def load_skills_from_agent_server(# Build request payload. ``org_configs`` is the current list form;# ``org_config`` (the first entry) is kept for backward compatibility# with older agent-server images that only understand a single config.- payload = {+ payload: dict[str, Any] = {'load_public': load_public,'load_user': load_user,'load_project': load_project,@@ -438,6 +442,17 @@ async def load_skills_from_agent_server('sandbox_config': sandbox_config.model_dump() if sandbox_config else None,}+ # Only include ``registered_marketplaces`` when we actually have a value.+ # The agent-server field is a non-Optional ``list`` with a default, so an+ # explicit ``null`` fails validation (422) and would drop *all* skills.+ # Omitting the key lets the agent-server apply its own default, and older+ # agent-servers without the field simply ignore an absent key.+ if registered_marketplaces is not None:+ payload['registered_marketplaces'] = [+ reg.model_dump(exclude_none=True, exclude={'scope'})+ for reg in registered_marketplaces+ ]+# Build headersheaders = {'Content-Type': 'application/json'}if session_api_key:diff --git a/openhands/app_server/settings/file_settings_store.py b/openhands/app_server/settings/file_settings_store.pyindex c4928362cb..663fb0f6c4 100644--- a/openhands/app_server/settings/file_settings_store.py+++ b/openhands/app_server/settings/file_settings_store.py@@ -54,3 +54,10 @@ class FileSettingsStore(SettingsStore):file_store = get_global_config().file_storereturn FileSettingsStore(file_store)++ async def get_org_marketplaces(self, user_id: str | None) -> list[dict]:+ """Get organization-level marketplaces.++ OSS mode has no org concept, so returns empty list.+ """+ return []diff --git a/openhands/app_server/settings/marketplace_composition.py b/openhands/app_server/settings/marketplace_composition.pynew file mode 100644index 0000000000..867bf0e0c0--- /dev/null+++ b/openhands/app_server/settings/marketplace_composition.py@@ -0,0 +1,270 @@+"""Composition of plugin marketplaces across instance/org/user scopes.++Marketplaces compose additively with precedence ``Instance < Org < User``.+Identity is the marketplace **name** (the stable, user-facing identifier and the+key used by ``plugin-name@marketplace-name`` resolution). Narrower scopes cannot+override broader ones:++- Org entries may override an instance entry of the *same name* (e.g. to flip+ ``auto_load``); a new org name is simply added.+- A user entry whose name already exists at the instance/org level is dropped+ (users add only). A new user name becomes a personal marketplace.++This module is the single source of truth for composition. It is used both by the+settings API (to render inherited/personal for the UI) and by conversation start+(to decide which marketplaces to hand to the agent-server for plugin loading).+"""++from __future__ import annotations++import json+import logging+import os+from dataclasses import dataclass, field+from typing import Any, Iterable, Sequence++from pydantic import ValidationError++from openhands.app_server.settings.settings_models import (+ MarketplaceRegistration,+ MarketplaceScope,+)++logger = logging.getLogger(__name__)++INSTANCE_MARKETPLACES_ENV = 'INSTANCE_DEFAULT_MARKETPLACES'+MARKETPLACE_LOADING_ENV = 'ENABLE_MARKETPLACE_PLUGIN_LOADING'++_RawMarketplace = dict[str, Any] | MarketplaceRegistration+++def marketplace_plugin_loading_enabled() -> bool:+ """Whether composed marketplaces are sent to the agent-server at conversation+ start so their ``auto_load`` plugins are loaded.++ Enabled by default: the agent-server ``/api/skills`` support for+ ``registered_marketplaces`` ships in the pinned SDK (>=1.30.0). Set+ ``ENABLE_MARKETPLACE_PLUGIN_LOADING`` to a falsy value (``0``/``false``/+ ``no``/``off``) to disable the loading path as a kill switch. Storage and the+ settings UI work regardless of this flag.+ """+ raw = os.environ.get(MARKETPLACE_LOADING_ENV)+ if raw is None or not raw.strip():+ return True+ return raw.strip().lower() in (+ '1',+ 'true',+ 'yes',+ 'on',+ )+++@dataclass+class ComposedMarketplaces:+ """Result of composing marketplaces across scopes.++ ``inherited`` (instance + org) is read-only for users; ``personal`` is the+ user's own set. ``all`` is the combined set used for plugin loading.+ """++ inherited: list[MarketplaceRegistration] = field(default_factory=list)+ personal: list[MarketplaceRegistration] = field(default_factory=list)++ @property+ def all(self) -> list[MarketplaceRegistration]:+ return [*self.inherited, *self.personal]+++def _derive_name_from_source(source: str) -> str:+ """Best-effort marketplace name from a source string.++ ``github:owner/repo`` / ``.../owner/repo`` -> ``repo``. Falls back to the+ raw source when no separator is present.+ """+ source = (source or '').strip()+ if ':' in source:+ source = source.split(':', 1)[-1]+ if '/' in source:+ return source.rstrip('/').split('/')[-1]+ return source+++def _parse_instance_marketplaces_env(env_value: str) -> list[dict[str, Any]]:+ """Parse the raw ``INSTANCE_DEFAULT_MARKETPLACES`` value into raw dicts.++ Two formats are supported. JSON is tried on the *whole* value first so that+ arrays/objects containing commas parse correctly:++ - JSON: ``{"source": ...}`` or ``[{"source": ...}, ...]``+ - Comma-separated ``#``-delimited entries: ``source#name#ref#repo_path``++ Raises on malformed JSON; callers degrade to an empty list.+ """+ if env_value[0] in '[{':+ data = json.loads(env_value)+ if isinstance(data, dict):+ return [data]+ if isinstance(data, list):+ return [entry for entry in data if isinstance(entry, dict)]+ raise ValueError('JSON must be an object or a list of objects')++ entries: list[dict[str, Any]] = []+ for definition in env_value.split(','):+ definition = definition.strip()+ if not definition:+ continue+ parts = definition.split('#')+ entry: dict[str, Any] = {'source': parts[0].strip()}+ if len(parts) > 1 and parts[1].strip():+ entry['name'] = parts[1].strip()+ if len(parts) > 2 and parts[2].strip():+ entry['ref'] = parts[2].strip()+ if len(parts) > 3 and parts[3].strip():+ entry['repo_path'] = parts[3].strip()+ entries.append(entry)+ return entries+++def get_instance_default_marketplaces() -> list[dict[str, Any]]:+ """Instance-level default marketplaces from the environment.++ Instance defaults auto-load by default. Parsing/validation never raises: a+ bad value is logged and yields an empty list so a single operator typo can+ never break settings loading for every user.+ """+ env_value = os.environ.get(INSTANCE_MARKETPLACES_ENV, '').strip()+ if not env_value:+ return []++ try:+ raw_entries = _parse_instance_marketplaces_env(env_value)+ except Exception as e: # noqa: BLE001 - degrade gracefully on any bad config+ logger.warning(+ 'Failed to parse %s; ignoring instance defaults: %s',+ INSTANCE_MARKETPLACES_ENV,+ e,+ )+ return []++ validated: list[dict[str, Any]] = []+ for raw in raw_entries:+ entry = dict(raw)+ entry.setdefault('auto_load', True)+ if not entry.get('name'):+ entry['name'] = _derive_name_from_source(entry.get('source', ''))+ try:+ reg = MarketplaceRegistration.model_validate(entry)+ except (ValidationError, ValueError) as e:+ logger.warning(+ 'Invalid marketplace in %s: %s', INSTANCE_MARKETPLACES_ENV, e+ )+ continue+ validated.append(reg.model_dump())+ return validated+++def _name_of(mp: _RawMarketplace) -> str:+ name = mp.get('name') if isinstance(mp, dict) else getattr(mp, 'name', None)+ return (name or '').strip()+++def duplicate_marketplace_names(+ marketplaces: Sequence[_RawMarketplace] | None,+ reserved_names: Iterable[str] = (),+) -> list[str]:+ """Names duplicated within ``marketplaces`` or already in ``reserved_names``.++ ``name`` is the marketplace identity (used by ``plugin@marketplace``+ resolution), so writes must keep it unique. For a personal write,+ ``reserved_names`` are the inherited instance/org names the user cannot+ shadow. Returned in first-seen order.+ """+ reserved = {n.strip() for n in reserved_names if n and n.strip()}+ seen: set[str] = set()+ conflicts: list[str] = []+ for mp in marketplaces or []:+ name = _name_of(mp)+ if not name:+ continue+ if (name in reserved or name in seen) and name not in conflicts:+ conflicts.append(name)+ seen.add(name)+ return conflicts+++def _coerce(raw: _RawMarketplace) -> MarketplaceRegistration | None:+ """Validate a raw entry into a model, or None (logged) if invalid."""+ try:+ if isinstance(raw, MarketplaceRegistration):+ return raw+ return MarketplaceRegistration.model_validate(raw)+ except (ValidationError, ValueError) as e:+ logger.warning('Skipping invalid marketplace entry: %s', e)+ return None+++def compose_marketplaces(+ instance_marketplaces: Sequence[_RawMarketplace] | None,+ org_marketplaces: Sequence[_RawMarketplace] | None,+ user_marketplaces: Sequence[_RawMarketplace] | None,+) -> ComposedMarketplaces:+ """Compose marketplaces from the three scopes, keyed on ``name``.++ Precedence is Instance < Org < User for identity; org overrides an instance+ entry of the same name, and a user entry is dropped when its name already+ exists at a broader scope. Invalid entries are skipped. Order is preserved+ (instance, then org additions, then user additions).+ """++ def _stamp(+ reg: MarketplaceRegistration, scope: MarketplaceScope+ ) -> MarketplaceRegistration:+ return reg.model_copy(update={'scope': scope})++ # name -> registration; dict preserves insertion order and dedupes by name.+ inherited: dict[str, MarketplaceRegistration] = {}+ for raw in instance_marketplaces or []:+ reg = _coerce(raw)+ if reg is not None:+ inherited[reg.name] = _stamp(reg, MarketplaceScope.INSTANCE)+ for raw in org_marketplaces or []:+ reg = _coerce(raw)+ if reg is not None:+ # Same name as an instance entry -> org override; new name -> add.+ inherited[reg.name] = _stamp(reg, MarketplaceScope.ORG)++ personal: dict[str, MarketplaceRegistration] = {}+ for raw in user_marketplaces or []:+ reg = _coerce(raw)+ if reg is None:+ continue+ if reg.name in inherited:+ logger.debug(+ "User marketplace '%s' shadows an inherited one; ignoring", reg.name+ )+ continue+ personal[reg.name] = _stamp(reg, MarketplaceScope.PERSONAL)++ return ComposedMarketplaces(+ inherited=list(inherited.values()),+ personal=list(personal.values()),+ )+++async def load_composed_marketplaces(+ user_id: str | None,+ user_marketplaces: Sequence[_RawMarketplace] | None,+ settings_store: Any,+) -> ComposedMarketplaces:+ """Gather instance + org + user marketplaces and compose them.++ ``settings_store`` must expose ``get_org_marketplaces(user_id)`` (all+ ``SettingsStore`` implementations do; OSS returns ``[]``).+ """+ instance = get_instance_default_marketplaces()+ try:+ org = await settings_store.get_org_marketplaces(user_id)+ except Exception as e: # noqa: BLE001 - org lookup must never break composition+ logger.warning('Failed to load org marketplaces: %s', e)+ org = []+ return compose_marketplaces(instance, org, user_marketplaces)diff --git a/openhands/app_server/settings/settings_models.py b/openhands/app_server/settings/settings_models.pyindex 6ccc3e3490..d4b2cd379e 100644--- a/openhands/app_server/settings/settings_models.py+++ b/openhands/app_server/settings/settings_models.py@@ -10,8 +10,10 @@ This module contains:from __future__ import annotations+import logging+import refrom enum import Enum-from typing import Annotated, Any+from typing import Annotated, Any, Sequencefrom fastmcp.mcp_config import MCPConfigfrom fastmcp.mcp_config import MCPConfig as SDKMCPConfig@@ -21,7 +23,9 @@ from pydantic import (Field,SecretStr,SerializationInfo,+ ValidationError,field_serializer,+ field_validator,model_validator,)@@ -39,6 +43,214 @@ from openhands.sdk.settings import (validate_agent_settings,)+logger = logging.getLogger(__name__)++# Valid source patterns for MarketplaceRegistration+# - github:owner/repo format+_GITHUB_SOURCE_PATTERN = re.compile(r'^github:[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$')+# - Git URLs (https, git, ssh protocols)+_GIT_URL_PATTERN = re.compile(+ r'^(https?://|git@|ssh://|git://)[a-zA-Z0-9_.-]+[:/][a-zA-Z0-9_./-]+$'+)+# - Relative local paths (no absolute paths, no parent traversal)+_LOCAL_PATH_PATTERN = re.compile(r'^[a-zA-Z0-9_][a-zA-Z0-9_./-]*$')+++class MarketplaceScope(str, Enum):+ """Scope of a marketplace registration."""++ INSTANCE = 'instance'+ ORG = 'org'+ PERSONAL = 'personal'+++class MarketplaceRegistration(BaseModel):+ """Registration for a plugin marketplace.++ Represents a marketplace that can be registered for plugin resolution.+ Marketplaces can be auto-loaded (plugins loaded at conversation start)+ or registered only (available for explicit plugin references).++ Wire-compatible with ``openhands.sdk.marketplace.MarketplaceRegistration``+ (the model the agent-server ``/api/skills`` endpoint consumes): dumping this+ model with ``exclude={'scope'}`` yields exactly the SDK model's fields+ (``name``/``source``/``ref``/``repo_path``/``auto_load``), and our ``bool``+ ``auto_load`` and stricter field validators are a subset of what the SDK+ accepts, so any value we produce validates upstream.++ This is intentionally kept as a separate model rather than importing the SDK+ one, because it carries a backend-only ``scope`` (set per storage layer for+ API responses/UI, stripped at the wire boundary and re-derived during+ composition) and enforces input validation the SDK model does not (source /+ ``repo_path`` traversal guards, name format).++ Examples:+ >>> # Auto-load all plugins from a marketplace+ >>> MarketplaceRegistration(+ ... name="public",+ ... source="github:OpenHands/skills",+ ... auto_load=True+ ... )++ >>> # Register marketplace without auto-loading+ >>> MarketplaceRegistration(+ ... name="experimental",+ ... source="github:acme/experimental"+ ... )++ >>> # Marketplace in monorepo subdirectory+ >>> MarketplaceRegistration(+ ... name="team",+ ... source="github:acme/monorepo",+ ... repo_path="marketplaces/internal",+ ... auto_load=True+ ... )+ """++ name: str = Field(description='Identifier for this marketplace registration')+ source: str = Field(+ description="Marketplace source: 'github:owner/repo', git URL, or local path"+ )+ ref: str | None = Field(+ default=None,+ description='Optional branch, tag, or commit (only for git sources)',+ )+ repo_path: str | None = Field(+ default=None,+ description=(+ 'Subdirectory path within the git repository containing the marketplace '+ "(e.g., 'marketplaces/internal' for monorepos). "+ 'Only relevant for git sources, not local paths.'+ ),+ )+ auto_load: bool = Field(+ default=False,+ description=(+ 'Auto-load behavior for this marketplace. '+ 'True = load all plugins at conversation start. '+ 'False = registered for resolution but not auto-loaded.'+ ),+ )+ scope: 'MarketplaceScope | None' = Field(+ default=None,+ description=(+ 'Scope of this marketplace registration. '+ 'Set automatically by backend based on storage layer: '+ '"instance" for system defaults, "org" for organization-level, '+ '"personal" for user-level. '+ 'Frontend should NOT send this field in save requests.'+ ),+ )++ @field_validator('name')+ @classmethod+ def validate_name(cls, v: str) -> str:+ """Validate name is non-empty and contains only valid identifier characters."""+ if not v or not v.strip():+ raise ValueError('name cannot be empty')+ v = v.strip()+ # Name should be a valid identifier (alphanumeric, hyphens, underscores)+ if not re.match(r'^[a-zA-Z][a-zA-Z0-9_-]*$', v):+ raise ValueError(+ 'name must start with a letter and contain only '+ 'letters, numbers, hyphens, and underscores'+ )+ return v++ @field_validator('source')+ @classmethod+ def validate_source(cls, v: str) -> str:+ """Validate source matches expected patterns (github:owner/repo, git URL, or local path)."""+ if not v or not v.strip():+ raise ValueError('source cannot be empty')+ v = v.strip()++ # Check for valid source patterns+ if _GITHUB_SOURCE_PATTERN.match(v):+ return v+ if _GIT_URL_PATTERN.match(v):+ return v+ # Local path: must be relative, no parent traversal+ if v.startswith('/'):+ raise ValueError('local path source must be relative, not absolute')+ if '..' in v:+ raise ValueError("source cannot contain '..' (parent directory traversal)")+ if _LOCAL_PATH_PATTERN.match(v):+ return v++ raise ValueError(+ "source must be 'github:owner/repo', a git URL "+ '(https/git/ssh), or a relative local path'+ )++ @field_validator('repo_path')+ @classmethod+ def validate_repo_path(cls, v: str | None) -> str | None:+ """Validate repo_path is a safe relative path within the repository."""+ if v is None:+ return v+ # A common mistake is pasting the repository URL here; repo_path is a+ # subdirectory *within* the already-specified source repository.+ if '://' in v:+ raise ValueError(+ 'repo_path must be a subdirectory within the repository, not a URL'+ )+ # Must be relative (no absolute paths)+ if v.startswith('/'):+ raise ValueError('repo_path must be relative, not absolute')+ # No parent directory traversal+ if '..' in v:+ raise ValueError(+ "repo_path cannot contain '..' (parent directory traversal)"+ )+ return v+++def validate_and_convert_marketplaces(+ raw_marketplaces: Sequence[dict[str, Any] | MarketplaceRegistration] | None,+ source_name: str = 'marketplaces',+) -> list[MarketplaceRegistration]:+ """Validate and convert raw marketplace data to MarketplaceRegistration objects.++ This function handles the common pattern of validating marketplace data+ that comes from database storage (stored as dicts) or direct model instances.+ Invalid entries are logged and skipped (graceful degradation).++ Args:+ raw_marketplaces: List of raw marketplace data (dicts or model instances)+ source_name: Descriptive name for logging (e.g., "org", "user settings")++ Returns:+ List of validated MarketplaceRegistration objects.++ Example:+ >>> data = [{'name': 'test', 'source': 'github:owner/repo'}]+ >>> registrations = validate_and_convert_marketplaces(data, "my-org")+ >>> len(registrations)+ 1+ """+ if not raw_marketplaces:+ return []++ validated = []+ for i, mp in enumerate(raw_marketplaces):+ try:+ if isinstance(mp, dict):+ validated.append(MarketplaceRegistration.model_validate(mp))+ elif isinstance(mp, MarketplaceRegistration):+ validated.append(mp)+ else:+ raise ValueError(+ f'Expected dict or MarketplaceRegistration, got {type(mp).__name__}'+ )+ except (ValidationError, ValueError) as e:+ logger.warning(+ f'Skipping invalid marketplace at index {i} in {source_name}: {e}'+ )+ continue++ return validated+def _coerce_value(value: Any) -> Any:"""Unwrap SecretStr to plain values."""@@ -163,9 +375,36 @@ class Settings(BaseModel):'See ``LLMProfiles`` for the profile-management API.'),)+ # Marketplace registrations for plugin resolution+ # Users can register multiple marketplaces with different auto-load behaviors+ registered_marketplaces: list[MarketplaceRegistration] = Field(+ default_factory=list,+ description=(+ 'List of marketplace registrations for plugin resolution. '+ 'Marketplaces with auto_load=True will have their plugins loaded '+ 'automatically at conversation start. '+ 'See MarketplaceRegistration for details.'+ ),+ )+ # Inherited marketplaces from instance/org level (read-only for user)+ # This is computed at runtime from environment variables and org settings+ inherited_marketplaces: list[MarketplaceRegistration] = Field(+ default_factory=list,+ description=(+ 'Marketplaces inherited from instance or organization level. '+ 'These are read-only and cannot be modified by the user. '+ 'Computed at runtime: Instance defaults + Org defaults.'+ ),+ )model_config = ConfigDict(populate_by_name=True)+ # NOTE: marketplace name uniqueness is enforced on the write paths (personal+ # settings + org store) and deduplicated defensively during composition+ # (``marketplace_composition``). It is intentionally NOT a model validator:+ # validating on construction would run on every ``load()`` and could lock a+ # user out of settings entirely if legacy stored data contained a duplicate.+def __init__(self, **data: Any):# Import Secrets here to avoid circular importsfrom openhands.app_server.secrets.secrets_models import Secrets@@ -274,6 +513,35 @@ class Settings(BaseModel):and SecretStr in getattr(annotation, '__args__', ())):value = SecretStr(value) if value else None+ # Validate registered_marketplaces before setting+ if key == 'registered_marketplaces' and value is not None:+ validated = []+ for i, mp in enumerate(value):+ try:+ if isinstance(mp, dict):+ # Strip scope from incoming request - backend will set it+ mp_dict = {k: v for k, v in mp.items() if k != 'scope'}+ # Ensure auto_load defaults to False if not provided+ if 'auto_load' not in mp_dict:+ mp_dict['auto_load'] = False+ mp_obj = MarketplaceRegistration.model_validate(mp_dict)+ # Set scope='personal' for user-level settings+ mp_obj.scope = MarketplaceScope.PERSONAL+ validated.append(mp_obj)+ elif isinstance(mp, MarketplaceRegistration):+ # Set scope='personal' for user-level settings+ mp.scope = MarketplaceScope.PERSONAL+ validated.append(mp)+ else:+ raise ValueError(+ f'Expected dict or MarketplaceRegistration, '+ f'got {type(mp).__name__}'+ )+ except ValidationError as e:+ raise ValueError(+ f'Invalid marketplace at index {i}: {e.errors()[0]["msg"]}'+ ) from e+ value = validatedsetattr(self, key, value)self.reconcile_active_profile()diff --git a/openhands/app_server/settings/settings_router.py b/openhands/app_server/settings/settings_router.pyindex 2cf8a3ea37..07e1d12f2b 100644--- a/openhands/app_server/settings/settings_router.py+++ b/openhands/app_server/settings/settings_router.py@@ -26,6 +26,11 @@ from openhands.app_server.settings.llm_profiles import (StrictLLM,has_real_api_key,)+from openhands.app_server.settings.marketplace_composition import (+ compose_marketplaces,+ duplicate_marketplace_names,+ get_instance_default_marketplaces,+)from openhands.app_server.settings.settings_models import (GETSettingsModel,Settings,@@ -56,6 +61,36 @@ LITE_LLM_API_URL = os.environ.get('LITE_LLM_API_URL', 'https://llm-proxy.app.all-hands.dev')++def _get_instance_default_marketplaces() -> list[dict[str, Any]]:+ """Instance-level default marketplaces from the environment.++ Thin wrapper over :func:`marketplace_composition.get_instance_default_marketplaces`+ (the single source of truth), kept for import stability.+ """+ return get_instance_default_marketplaces()+++def _merge_marketplaces(+ instance_marketplaces: list[dict[str, Any]],+ org_marketplaces: list[dict[str, Any]],+ user_marketplaces: list[dict[str, Any]],+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Compose marketplaces across scopes, keyed on ``name`` (additive).++ Thin wrapper over :func:`marketplace_composition.compose_marketplaces`.+ Returns ``(inherited, personal)`` as JSON-ready dicts (instance + org are+ inherited/read-only; user-only names are personal).+ """+ composed = compose_marketplaces(+ instance_marketplaces, org_marketplaces, user_marketplaces+ )+ return (+ [mp.model_dump(mode='json') for mp in composed.inherited],+ [mp.model_dump(mode='json') for mp in composed.personal],+ )++# Create router with /api/v1/settings prefixrouter = APIRouter(prefix='/settings',@@ -98,6 +133,7 @@ async def load_settings(settings_store: SettingsStore = Depends(get_user_settings_store),settings: Settings = Depends(get_user_settings),secrets_store: SecretsStore = Depends(get_secrets_store),+ user_id: str | None = Depends(get_user_id),) -> GETSettingsModel | JSONResponse:"""Load user settings.@@ -158,6 +194,19 @@ async def load_settings(resp_llm.api_key = Nonesettings_with_token_data.search_api_key = Nonesettings_with_token_data.sandbox_api_key = None++ # Marketplace composition: Instance -> Org -> User (additive, name-keyed).+ # ``inherited`` (instance + org) is read-only; ``personal`` is the user's+ # own set. Composition validates + dedupes defensively so a bad stored row+ # can never break settings loading.+ composed = compose_marketplaces(+ get_instance_default_marketplaces(),+ await settings_store.get_org_marketplaces(user_id),+ settings.registered_marketplaces,+ )+ settings_with_token_data.inherited_marketplaces = composed.inherited+ settings_with_token_data.registered_marketplaces = composed.personal+return settings_with_token_dataexcept Exception as e:logger.warning(f'Invalid token: {e}')@@ -217,6 +266,28 @@ async def store_settings(settings = existing_settings.model_copy() if existing_settings else Settings()settings.update(payload)+ # When the user edits their marketplaces, reject names that duplicate each+ # other or collide with inherited (instance/org) names. Enforcing this on+ # write (the model validator does not run on model_copy/setattr) prevents a+ # bad row that would later break settings loading (self-lockout).+ if 'registered_marketplaces' in payload:+ inherited_names = [+ name+ for mp in (+ *get_instance_default_marketplaces(),+ *(await settings_store.get_org_marketplaces(user_id)),+ )+ if (name := mp.get('name'))+ ]+ conflicts = duplicate_marketplace_names(+ settings.registered_marketplaces, inherited_names+ )+ if conflicts:+ raise ValueError(+ 'Marketplace name(s) already in use or duplicated: '+ + ', '.join(sorted(conflicts))+ )+_post_merge_llm_fixups(settings)if existing_settings:@@ -256,6 +327,13 @@ async def store_settings(status_code=status.HTTP_200_OK,content={'message': 'Settings stored'},)+ except ValueError as e:+ # Validation errors (e.g., invalid marketplace data) return 400+ logger.warning(f'Settings validation error: {e}')+ return JSONResponse(+ status_code=status.HTTP_400_BAD_REQUEST,+ content={'error': str(e)},+ )except Exception as e:logger.warning(f'Something went wrong storing settings: {e}')return JSONResponse(diff --git a/openhands/app_server/settings/settings_store.py b/openhands/app_server/settings/settings_store.pyindex e910d03978..c9b671c53b 100644--- a/openhands/app_server/settings/settings_store.py+++ b/openhands/app_server/settings/settings_store.py@@ -34,3 +34,12 @@ class SettingsStore(ABC):TODO: This method should be replaced with dependency injection."""++ @abstractmethod+ async def get_org_marketplaces(self, user_id: str | None) -> list[dict]:+ """Get organization-level marketplaces.++ Returns:+ List of marketplace dictionaries from the org's registered_marketplaces.+ Returns empty list if no org marketplaces are available (OSS mode) or if user_id is None.+ """diff --git a/openhands/app_server/user/skills_router.py b/openhands/app_server/user/skills_router.pyindex a54074db0f..d757e6ebac 100644--- a/openhands/app_server/user/skills_router.py+++ b/openhands/app_server/user/skills_router.py@@ -1,15 +1,30 @@+from __future__ import annotations++import shutil+import subprocess+import tempfilefrom pathlib import Path-from typing import Annotated+from types import MappingProxyType+from typing import Annotated, castimport yaml-from fastapi import APIRouter, Query+from fastapi import APIRouter, HTTPException, Queryfrom pydantic import BaseModelimport openhands+from openhands.app_server.config import depends_user_context+from openhands.app_server.integrations.provider import (+ PROVIDER_TOKEN_TYPE,+ ProviderHandler,+)+from openhands.app_server.settings.settings_models import MarketplaceRegistration+from openhands.app_server.user.user_context import UserContextfrom openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.app_server.utils.logger import openhands_logger as logger+from openhands.sdk.marketplace import Marketplacerouter = APIRouter(prefix='/skills', tags=['Skills'], dependencies=get_dependencies())+user_context_dependency = depends_user_context()# skills/ is at the repo root, two levels above the openhands package __file__GLOBAL_SKILLS_DIR = Path(openhands.__file__).parent.parent / 'skills'@@ -32,6 +47,28 @@ class SkillPage(BaseModel):next_page_id: str | None = None+class MarketplacePluginPreview(BaseModel):+ """A plugin advertised by a marketplace manifest.++ The UI operates at the plugin level, so a plugin's bundled skills are not+ expanded here; only the plugin itself is surfaced.+ """++ name: str+ description: str | None = None+ source: str # the marketplace registration source (e.g. 'github:owner/repo')+ marketplace: str # the marketplace registration name this plugin belongs to+++class MarketplaceSkillsPreviewResponse(BaseModel):+ """Response for marketplace skills preview endpoint."""++ skills: list[SkillInfo]+ plugins: list[MarketplacePluginPreview]+ marketplace_skills: dict[str, list[str]] # marketplace_name -> skill names+ errors: list[str]++def _parse_skill_frontmatter(file_path: Path) -> dict | None:"""Parse YAML frontmatter from a skill markdown file.@@ -153,3 +190,310 @@ async def search_skills()return SkillPage(items=page, next_page_id=next_page_id)+++def _parse_marketplace_source(source: str) -> tuple[str, str]:+ """Parse marketplace source into provider and repo path.++ Args:+ source: Marketplace source (e.g., 'github:owner/repo', 'gitlab:owner/repo',+ 'https://github.com/owner/repo.git')++ Returns:+ Tuple of (provider, repo_path) where provider is 'github', 'gitlab', etc.+ """+ # Handle github:owner/repo format+ if source.startswith('github:'):+ return ('github', source[7:].lstrip('/'))+ if source.startswith('gitlab:'):+ return ('gitlab', source[7:].lstrip('/'))+ if source.startswith('bitbucket:'):+ return ('bitbucket', source[10:].lstrip('/'))+ if source.startswith('azure-devops:'):+ return ('azure-devops', source[13:].lstrip('/'))++ # Handle URL format+ lower = source.lower()+ if 'github.com' in lower:+ path = source.split('github.com', 1)[1].lstrip('/').rstrip('/')+ # Remove .git suffix if present (use removesuffix to avoid character-by-character stripping)+ if path.endswith('.git'):+ path = path[:-4]+ return ('github', path)+ if 'gitlab.com' in lower or 'gitlab' in lower:+ path = (+ source.split(('gitlab.com' if 'gitlab.com' in lower else 'gitlab'), 1)[1]+ .lstrip('/')+ .rstrip('/')+ )+ if path.endswith('.git'):+ path = path[:-4]+ return ('gitlab', path)+ if 'bitbucket.org' in lower:+ path = source.split('bitbucket.org', 1)[1].lstrip('/').rstrip('/')+ if path.endswith('.git'):+ path = path[:-4]+ return ('bitbucket', path)++ # Default to github+ path = source.rstrip('/')+ if path.endswith('.git'):+ path = path[:-4]+ return ('github', path)+++async def _clone_marketplace_repo(+ marketplace: MarketplaceRegistration,+ user_context: UserContext,+) -> tuple[Path | None, str]:+ """Clone a marketplace repository to a temporary directory.++ Args:+ marketplace: MarketplaceRegistration with source, ref, and repo_path+ user_context: UserContext for accessing provider tokens++ Returns:+ Tuple of (cloned_path or None, error_message or '')+ """+ provider, repo_path = _parse_marketplace_source(marketplace.source)++ # Validate repo path format+ if not repo_path or '/' not in repo_path:+ return None, f'Invalid repository path: {repo_path}'++ # Build fallback URLs for public repositories+ provider_domain_map = {+ 'github': 'github.com',+ 'gitlab': 'gitlab.com',+ 'bitbucket': 'bitbucket.org',+ }+ fallback_url = (+ f'https://{provider_domain_map.get(provider, "github.com")}/{repo_path}.git'+ )++ # Get authenticated URL from provider handler+ authenticated_url = None+ try:+ provider_tokens = await user_context.get_provider_tokens()+ if not provider_tokens:+ logger.info(+ f'No provider tokens available for {provider}, will try unauthenticated clone'+ )+ else:+ # Cast to expected type - user_context may return dict[str, str] in some contexts+ typed_provider_tokens = cast(PROVIDER_TOKEN_TYPE, provider_tokens)+ client = ProviderHandler(+ provider_tokens=MappingProxyType(typed_provider_tokens),+ external_auth_id=await user_context.get_user_id(),+ )+ authenticated_url = await client.get_authenticated_git_url(repo_path)+ except Exception as e:+ logger.warning(+ f'Failed to get authenticated URL for {repo_path}: {e}, will try unauthenticated clone'+ )++ # Use authenticated URL if available, otherwise fallback to public URL+ clone_url = authenticated_url or fallback_url++ # Create unique temporary directory for this clone using tempfile.mkdtemp+ try:+ clone_dir = Path(+ tempfile.mkdtemp(prefix=f'openhands_marketplace_{marketplace.name}_')+ )++ # Run git without a shell (argv form) and use ``--`` so a source/ref+ # that begins with '-' can never be parsed as a git option (argument+ # injection). Reject leading-'-' values outright as defense in depth.+ if clone_url.startswith('-'):+ _cleanup_clone_dir(clone_dir)+ return None, f'Invalid clone URL: {clone_url}'++ result = subprocess.run(+ ['git', 'clone', '--', clone_url, str(clone_dir)],+ capture_output=True,+ text=True,+ timeout=120,+ )++ if result.returncode != 0:+ _cleanup_clone_dir(clone_dir)+ return None, f'Git clone failed: {result.stderr}'++ # Checkout ref if specified+ if marketplace.ref:+ if marketplace.ref.startswith('-'):+ _cleanup_clone_dir(clone_dir)+ return None, f'Invalid ref: {marketplace.ref}'+ checkout_result = subprocess.run(+ ['git', '-C', str(clone_dir), 'checkout', marketplace.ref],+ capture_output=True,+ text=True,+ timeout=60,+ )+ if checkout_result.returncode != 0:+ _cleanup_clone_dir(clone_dir)+ return None, f'Git checkout failed: {checkout_result.stderr}'++ # Navigate to repo_path if specified+ if marketplace.repo_path:+ skills_path = clone_dir / marketplace.repo_path+ if not skills_path.exists():+ _cleanup_clone_dir(clone_dir)+ return None, f'Repo path not found: {marketplace.repo_path}'+ return skills_path, ''++ return clone_dir, ''++ except subprocess.TimeoutExpired:+ return None, 'Git clone timed out'+ except Exception as e:+ return None, f'Clone failed: {str(e)}'+++def _cleanup_clone_dir(clone_dir: Path) -> None:+ """Clean up a cloned repository directory."""+ try:+ if clone_dir.exists():+ shutil.rmtree(clone_dir)+ except Exception as e:+ logger.debug(f'Failed to clean up clone directory {clone_dir}: {e}')+++ '/marketplace-skills',+ response_model=MarketplaceSkillsPreviewResponse,+)+async def get_marketplace_skills(+ marketplaces: list[MarketplaceRegistration],+ user_context: UserContext = user_context_dependency,+) -> MarketplaceSkillsPreviewResponse:+ """Get skills from marketplace repositories.++ This endpoint fetches and returns skill metadata from marketplace repos+ without requiring an active sandbox session. Useful for previewing what+ skills a marketplace provides before or after adding it.++ Each call clones the marketplace repos fresh; this endpoint is admin-only+ and low-traffic, so caching the git clones here would buy little for the+ cross-user / pod-local complexity a shared cache introduces.++ Args:+ marketplaces: List of marketplace registrations to fetch skills from.++ Returns:+ MarketplaceSkillsPreviewResponse with skill metadata and any errors.+ """+ all_skills: list[SkillInfo] = []+ plugins: list[MarketplacePluginPreview] = []+ marketplace_skills: dict[str, list[str]] = {}+ errors: list[str] = []++ # Track cloned directories for cleanup+ cloned_dirs: list[Path] = []++ try:+ for marketplace in marketplaces:+ # Clone the marketplace repo+ clone_path, error = await _clone_marketplace_repo(marketplace, user_context)++ if error:+ errors.append(f'{marketplace.name}: {error}')+ continue++ if clone_path is None:+ errors.append(f'{marketplace.name}: Failed to clone repository')+ continue++ cloned_dirs.append(clone_path)++ # Prefer the marketplace manifest so we operate at the *plugin* level.+ # ``Marketplace.load`` parses ``.plugin/marketplace.json`` (or+ # ``.claude-plugin/marketplace.json``) and exposes the plugins and any+ # standalone skills the marketplace advertises. A plugin's bundled+ # skills are intentionally not expanded — the UI shows plugins, not+ # their internals.+ skill_names: list[str] = []+ loaded_marketplace: Marketplace | None = None+ try:+ loaded_marketplace = Marketplace.load(clone_path)+ except FileNotFoundError:+ # No manifest: this is a plain skills repo, not a plugin+ # marketplace. Fall back to a loose-skill scan below.+ loaded_marketplace = None+ except Exception as e:+ logger.warning(+ f'Failed to parse marketplace manifest for {marketplace.name}: {e}'+ )+ errors.append(f'{marketplace.name}: invalid marketplace manifest')+ loaded_marketplace = None++ if loaded_marketplace is not None:+ for plugin_entry in loaded_marketplace.plugins:+ plugins.append(+ MarketplacePluginPreview(+ name=plugin_entry.name,+ description=plugin_entry.description,+ source=marketplace.source,+ marketplace=marketplace.name,+ )+ )+ # Standalone skills declared in the manifest (not plugin-bundled).+ for skill_entry in loaded_marketplace.skills:+ all_skills.append(+ SkillInfo(+ name=skill_entry.name,+ type='knowledge',+ source=f'marketplace:{marketplace.name}',+ triggers=None,+ )+ )+ skill_names.append(skill_entry.name)+ else:+ # No manifest: surface loose skills from skills/ and .skills/.+ # Bundled plugin skills under plugins/*/skills/ are deliberately+ # not flattened — a plugin marketplace should ship a manifest.+ skills_dirs = [+ d+ for d in (clone_path / 'skills', clone_path / '.skills')+ if d.is_dir()+ ]+ for skills_dir in skills_dirs:+ try:+ for skill in _load_skills_from_dir(+ skills_dir, marketplace.source+ ):+ all_skills.append(+ SkillInfo(+ name=skill.name,+ type=skill.type,+ source=f'marketplace:{marketplace.name}',+ triggers=skill.triggers,+ )+ )+ skill_names.append(skill.name)+ except Exception as e:+ logger.warning(f'Failed to load skills from {skills_dir}: {e}')++ marketplace_skills[marketplace.name] = skill_names++ except Exception as e:+ logger.exception(f'Unexpected error in marketplace-skills endpoint: {e}')+ errors.append(f'Internal error: {str(e)}')+ # Clean up before raising+ for clone_dir in cloned_dirs:+ _cleanup_clone_dir(clone_dir)+ # Raise HTTP 500 for critical errors+ raise HTTPException(status_code=500, detail=str(e))+ finally:+ # Clean up cloned directories+ for clone_dir in cloned_dirs:+ _cleanup_clone_dir(clone_dir)++ result = MarketplaceSkillsPreviewResponse(+ skills=all_skills,+ plugins=plugins,+ marketplace_skills=marketplace_skills,+ errors=errors,+ )++ return resultdiff --git a/tests/unit/app_server/test_app_conversation_service_base.py b/tests/unit/app_server/test_app_conversation_service_base.pyindex 7e3e4eff9b..a1d562802c 100644--- a/tests/unit/app_server/test_app_conversation_service_base.py+++ b/tests/unit/app_server/test_app_conversation_service_base.py@@ -1279,6 +1279,8 @@ class TestLoadAndMergeAllSkills:assert call_kwargs['agent_server_url'] == 'http://localhost:8000'assert call_kwargs['session_api_key'] == 'test-api-key'assert call_kwargs['project_dir'] == '/workspace/repo'+ # Verify registered_marketplaces is passed (can be None or a list)+ assert 'registered_marketplaces' in call_kwargs@pytest.mark.asyncio@patch(@@ -1401,3 +1403,46 @@ class TestLoadAndMergeAllSkills:# Assertassert result == []+++class TestLoadSkillsAndUpdateAgent:+ """_load_skills_and_update_agent threads marketplaces into skill loading."""++ @pytest.mark.asyncio+ async def test_forwards_registered_marketplaces(self):+ """Registered marketplaces reach load_and_merge_all_skills at startup."""+ # Arrange+ from openhands.app_server.settings.settings_models import (+ MarketplaceRegistration,+ )++ mock_user_context = Mock(spec=UserContext)+ with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):+ service = AppConversationServiceBase(+ init_git_in_empty_workspace=True, user_context=mock_user_context+ )+ service.load_and_merge_all_skills = AsyncMock(return_value=[])+ service._create_agent_with_skills = Mock(return_value='updated-agent')++ remote_workspace = AsyncMock()+ remote_workspace.host = 'http://agent:8000'+ marketplaces = [+ MarketplaceRegistration(name='team', source='github:o/team')+ ]++ # Act+ result = await service._load_skills_and_update_agent(+ Mock(spec=SandboxInfo),+ Mock(),+ remote_workspace,+ 'owner/repo',+ '/workspace/repo',+ registered_marketplaces=marketplaces,+ )++ # Assert+ assert result == 'updated-agent'+ forwarded = service.load_and_merge_all_skills.call_args.kwargs[+ 'registered_marketplaces'+ ]+ assert forwarded == marketplacesdiff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.pyindex 5d47864016..0d6922485b 100644--- a/tests/unit/app_server/test_live_status_app_conversation_service.py+++ b/tests/unit/app_server/test_live_status_app_conversation_service.py@@ -123,6 +123,20 @@ class _TestUserInfo(SimpleNamespace):def llm_profiles(self, value):object.__setattr__(self, '_llm_profiles_override', value)+ @property+ def registered_marketplaces(self) -> list:+ # Real UserInfo (via Settings) always carries registered_marketplaces,+ # defaulting to an empty list. Mirror that so marketplace composition at+ # conversation start doesn't raise AttributeError on the fake.+ override = getattr(self, '_registered_marketplaces_override', None)+ if override is not None:+ return override+ return []++ @registered_marketplaces.setter+ def registered_marketplaces(self, value):+ object.__setattr__(self, '_registered_marketplaces_override', value)+@propertydef conversation_settings(self) -> ConversationSettings:kwargs: dict = {diff --git a/tests/unit/app_server/test_marketplace_composition.py b/tests/unit/app_server/test_marketplace_composition.pynew file mode 100644index 0000000000..57f935d939--- /dev/null+++ b/tests/unit/app_server/test_marketplace_composition.py@@ -0,0 +1,265 @@+"""Tests for marketplace composition.++Covers :mod:`openhands.app_server.settings.marketplace_composition`: instance+env parsing, name-keyed additive composition across scopes, duplicate detection,+and the loading feature flag.+"""++from __future__ import annotations++import pytest++from openhands.app_server.settings.marketplace_composition import (+ compose_marketplaces,+ duplicate_marketplace_names,+ get_instance_default_marketplaces,+ load_composed_marketplaces,+ marketplace_plugin_loading_enabled,+)+from openhands.app_server.settings.settings_models import MarketplaceScope++ENV = 'INSTANCE_DEFAULT_MARKETPLACES'+FLAG = 'ENABLE_MARKETPLACE_PLUGIN_LOADING'+++class TestGetInstanceDefaultMarketplaces:+ """Parsing of the INSTANCE_DEFAULT_MARKETPLACES environment variable."""++ def test_unset_returns_empty(self, monkeypatch):+ # Arrange+ monkeypatch.delenv(ENV, raising=False)+ # Act / Assert+ assert get_instance_default_marketplaces() == []++ def test_hash_format_parses_all_fields_and_auto_loads(self, monkeypatch):+ # Arrange+ monkeypatch.setenv(ENV, 'github:owner/repo#team#main#marketplaces/internal')+ # Act+ result = get_instance_default_marketplaces()+ # Assert+ assert result == [+ {+ 'name': 'team',+ 'source': 'github:owner/repo',+ 'ref': 'main',+ 'repo_path': 'marketplaces/internal',+ 'auto_load': True,+ 'scope': None,+ }+ ]++ def test_name_derived_from_source_when_omitted(self, monkeypatch):+ # Arrange+ monkeypatch.setenv(ENV, 'github:owner/my-repo')+ # Act+ result = get_instance_default_marketplaces()+ # Assert+ assert result[0]['name'] == 'my-repo'++ def test_multiple_comma_separated_entries(self, monkeypatch):+ # Arrange+ monkeypatch.setenv(ENV, 'github:a/one#one, github:b/two#two')+ # Act+ result = get_instance_default_marketplaces()+ # Assert+ assert [m['name'] for m in result] == ['one', 'two']++ def test_json_object_with_commas_is_parsed_whole(self, monkeypatch):+ # Arrange - a JSON object contains commas; it must not be comma-split.+ monkeypatch.setenv(+ ENV, '{"source": "github:acme/plugins", "name": "team", "ref": "main"}'+ )+ # Act+ result = get_instance_default_marketplaces()+ # Assert+ assert len(result) == 1+ assert result[0]['name'] == 'team'+ assert result[0]['ref'] == 'main'++ def test_json_list_defaults_auto_load_true(self, monkeypatch):+ # Arrange+ monkeypatch.setenv(ENV, '[{"source": "github:acme/plugins", "name": "team"}]')+ # Act+ result = get_instance_default_marketplaces()+ # Assert+ assert result[0]['auto_load'] is True++ def test_invalid_config_degrades_to_empty(self, monkeypatch):+ # Arrange - malformed JSON (non-dict list) must not raise.+ monkeypatch.setenv(ENV, '["not-an-object"]')+ # Act / Assert+ assert get_instance_default_marketplaces() == []+++class TestComposeMarketplaces:+ """Name-keyed additive composition across instance/org/user scopes."""++ def test_instance_entries_are_inherited_with_instance_scope(self):+ # Arrange+ instance = [{'name': 'pub', 'source': 'github:o/pub', 'auto_load': True}]+ # Act+ composed = compose_marketplaces(instance, [], [])+ # Assert+ assert [(m.name, m.scope) for m in composed.inherited] == [+ ('pub', MarketplaceScope.INSTANCE)+ ]+ assert composed.personal == []++ def test_instance_and_org_are_additive(self):+ # Arrange+ instance = [{'name': 'pub', 'source': 'github:o/pub'}]+ org = [{'name': 'team', 'source': 'github:o/team'}]+ # Act+ composed = compose_marketplaces(instance, org, [])+ # Assert+ assert [m.name for m in composed.inherited] == ['pub', 'team']++ def test_org_overrides_instance_by_name(self):+ # Arrange - org re-declares 'pub' to flip auto_load (AC #7).+ instance = [{'name': 'pub', 'source': 'github:o/pub', 'auto_load': True}]+ org = [{'name': 'pub', 'source': 'github:o/pub', 'auto_load': False}]+ # Act+ composed = compose_marketplaces(instance, org, [])+ # Assert+ assert len(composed.inherited) == 1+ assert composed.inherited[0].scope == MarketplaceScope.ORG+ assert composed.inherited[0].auto_load is False++ def test_user_adds_new_personal_marketplace(self):+ # Arrange+ user = [{'name': 'mine', 'source': 'github:o/mine'}]+ # Act+ composed = compose_marketplaces([], [], user)+ # Assert+ assert [(m.name, m.scope) for m in composed.personal] == [+ ('mine', MarketplaceScope.PERSONAL)+ ]++ def test_user_cannot_shadow_inherited_name(self):+ # Arrange - user 'team' collides with an org marketplace of the same name.+ org = [{'name': 'team', 'source': 'github:o/team'}]+ user = [{'name': 'team', 'source': 'github:o/fork'}]+ # Act+ composed = compose_marketplaces([], org, user)+ # Assert - org wins, user entry dropped.+ assert composed.inherited[0].source == 'github:o/team'+ assert composed.personal == []++ def test_invalid_entry_is_skipped(self):+ # Arrange - instance entry missing required name.+ composed = compose_marketplaces(+ [{'source': 'github:o/x'}], [], [{'name': 'ok', 'source': 'github:o/ok'}]+ )+ # Assert+ assert composed.inherited == []+ assert [m.name for m in composed.personal] == ['ok']++ def test_duplicate_names_deduped_defensively(self):+ # Arrange - two personal entries share a name (bad stored data).+ user = [+ {'name': 'dup', 'source': 'github:o/a'},+ {'name': 'dup', 'source': 'github:o/b'},+ ]+ # Act - must not raise; last one wins.+ composed = compose_marketplaces([], [], user)+ # Assert+ assert len(composed.personal) == 1+ assert composed.personal[0].source == 'github:o/b'++ def test_all_combines_inherited_and_personal(self):+ # Arrange+ instance = [{'name': 'pub', 'source': 'github:o/pub'}]+ user = [{'name': 'mine', 'source': 'github:o/mine'}]+ # Act+ composed = compose_marketplaces(instance, [], user)+ # Assert+ assert [m.name for m in composed.all] == ['pub', 'mine']+++class TestDuplicateMarketplaceNames:+ """Detection of duplicate / reserved marketplace names for write validation."""++ def test_duplicates_within_list(self):+ # Arrange+ marketplaces = [{'name': 'a', 'source': 'x'}, {'name': 'a', 'source': 'y'}]+ # Act / Assert+ assert duplicate_marketplace_names(marketplaces) == ['a']++ def test_reserved_name_conflict(self):+ # Arrange+ marketplaces = [{'name': 'team', 'source': 'x'}]+ # Act / Assert+ assert duplicate_marketplace_names(marketplaces, reserved_names=['team']) == [+ 'team'+ ]++ def test_no_conflicts(self):+ # Arrange+ marketplaces = [{'name': 'a', 'source': 'x'}, {'name': 'b', 'source': 'y'}]+ # Act / Assert+ assert duplicate_marketplace_names(marketplaces, reserved_names=['c']) == []+++class TestMarketplaceLoadingFlag:+ """The ENABLE_MARKETPLACE_PLUGIN_LOADING gate."""++ def test_enabled_by_default(self, monkeypatch):+ # Arrange+ monkeypatch.delenv(FLAG, raising=False)+ # Act / Assert+ assert marketplace_plugin_loading_enabled() is True++ def test_disabled_when_falsy(self, monkeypatch):+ # Arrange+ monkeypatch.setenv(FLAG, 'false')+ # Act / Assert+ assert marketplace_plugin_loading_enabled() is False++ def test_enabled_when_truthy(self, monkeypatch):+ # Arrange+ monkeypatch.setenv(FLAG, 'true')+ # Act / Assert+ assert marketplace_plugin_loading_enabled() is True+++class _FakeStore:+ """Minimal settings store exposing get_org_marketplaces."""++ def __init__(self, org_marketplaces):+ self._org = org_marketplaces++ async def get_org_marketplaces(self, user_id):+ return self._org+++class TestLoadComposedMarketplaces:+ """The async gatherer that pulls instance + org + user and composes them."""++ @pytest.mark.asyncio+ async def test_gathers_all_three_scopes(self, monkeypatch):+ # Arrange+ monkeypatch.setenv(ENV, 'github:o/pub#pub')+ store = _FakeStore([{'name': 'team', 'source': 'github:o/team'}])+ user = [{'name': 'mine', 'source': 'github:o/mine'}]+ # Act+ composed = await load_composed_marketplaces('user-1', user, store)+ # Assert+ assert {m.name for m in composed.inherited} == {'pub', 'team'}+ assert [m.name for m in composed.personal] == ['mine']++ @pytest.mark.asyncio+ async def test_org_lookup_failure_degrades(self, monkeypatch):+ # Arrange - org lookup raising must not break composition.+ monkeypatch.delenv(ENV, raising=False)++ class _BrokenStore:+ async def get_org_marketplaces(self, user_id):+ raise RuntimeError('db down')++ # Act+ composed = await load_composed_marketplaces(+ 'user-1', [{'name': 'mine', 'source': 'github:o/mine'}], _BrokenStore()+ )+ # Assert+ assert composed.inherited == []+ assert [m.name for m in composed.personal] == ['mine']diff --git a/tests/unit/app_server/test_settings_api.py b/tests/unit/app_server/test_settings_api.pyindex 35e570e9d0..ac627afae0 100644--- a/tests/unit/app_server/test_settings_api.py+++ b/tests/unit/app_server/test_settings_api.py@@ -202,6 +202,12 @@ async def test_settings_api_endpoints(test_client):# V1 API sets api_key to None for security and uses llm_api_key_set flag insteadassert vals['llm']['api_key'] is Noneassert response_data['llm_api_key_set'] is True+ # Verify marketplace fields are present in response+ assert 'inherited_marketplaces' in response_data+ assert 'registered_marketplaces' in response_data+ # Both should be lists (may be empty)+ assert isinstance(response_data['inherited_marketplaces'], list)+ assert isinstance(response_data['registered_marketplaces'], list)# Test updating with partial settings — legacy flat fields should preserve existingpartial_settings = {@@ -328,3 +334,21 @@ async def test_disabled_skills_persistence(test_client):assert response.status_code == 200data = response.json()assert data['disabled_skills'] == []+++def test_store_settings_rejects_duplicate_personal_marketplace_names(test_client):+ """Saving personal marketplaces with duplicate names is rejected (400)."""+ # Arrange / Act+ response = test_client.post(+ '/api/v1/settings',+ json={+ 'registered_marketplaces': [+ {'name': 'dup', 'source': 'github:o/a'},+ {'name': 'dup', 'source': 'github:o/b'},+ ]+ },+ )++ # Assert+ assert response.status_code == 400+ assert 'dup' in response.json()['error']diff --git a/tests/unit/app_server/test_skill_loader.py b/tests/unit/app_server/test_skill_loader.pyindex e920b5a58f..9566a581a2 100644--- a/tests/unit/app_server/test_skill_loader.py+++ b/tests/unit/app_server/test_skill_loader.py@@ -857,3 +857,153 @@ class TestGetOrgRepositoryUrl:# Assertassert result is None+++# ===== Tests for registered_marketplaces support =====+++class TestLoadSkillsWithMarketplaces:+ """Test load_skills_from_agent_server with registered_marketplaces parameter."""++ @pytest.mark.asyncio+ @patch('httpx.AsyncClient')+ async def test_passes_registered_marketplaces_in_payload(self, mock_client_class):+ """Test that registered_marketplaces is included in the API payload."""+ from openhands.app_server.settings.settings_models import (+ MarketplaceRegistration,+ )++ # Arrange+ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'skills': [],+ 'sources': {},+ }+ mock_response.raise_for_status = MagicMock()++ mock_client = AsyncMock()+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=None)+ mock_client.post = AsyncMock(return_value=mock_response)+ mock_client_class.return_value = mock_client++ marketplaces = [+ MarketplaceRegistration(+ name='public',+ source='github:OpenHands/skills',+ auto_load=True,+ ),+ MarketplaceRegistration(+ name='team',+ source='github:acme/plugins',+ ref='v1.0.0',+ repo_path='marketplaces/internal',+ ),+ ]++ # Act+ await load_skills_from_agent_server(+ agent_server_url='http://localhost:8000',+ session_api_key='test-key',+ project_dir='/workspace/project',+ registered_marketplaces=marketplaces,+ )++ # Assert+ mock_client.post.assert_called_once()+ call_args = mock_client.post.call_args+ payload = call_args[1]['json']++ assert 'registered_marketplaces' in payload+ assert len(payload['registered_marketplaces']) == 2++ # Verify first marketplace+ mp1 = payload['registered_marketplaces'][0]+ assert mp1['name'] == 'public'+ assert mp1['source'] == 'github:OpenHands/skills'+ assert mp1['auto_load']+ # None values are stripped by model_dump()+ assert 'ref' not in mp1+ assert 'repo_path' not in mp1++ # Verify second marketplace+ mp2 = payload['registered_marketplaces'][1]+ assert mp2['name'] == 'team'+ assert mp2['source'] == 'github:acme/plugins'+ assert mp2['ref'] == 'v1.0.0'+ assert mp2['repo_path'] == 'marketplaces/internal'+ # auto_load=False is included (not stripped like None values)+ assert mp2['auto_load'] is False++ @pytest.mark.asyncio+ @patch('httpx.AsyncClient')+ async def test_handles_none_registered_marketplaces(self, mock_client_class):+ """None registered_marketplaces omits the key entirely from the payload.++ The agent-server field is a non-optional list, so sending ``null`` would+ fail validation and drop all skills; omitting the key uses its default.+ """+ # Arrange+ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'skills': [],+ 'sources': {},+ }+ mock_response.raise_for_status = MagicMock()++ mock_client = AsyncMock()+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=None)+ mock_client.post = AsyncMock(return_value=mock_response)+ mock_client_class.return_value = mock_client++ # Act+ await load_skills_from_agent_server(+ agent_server_url='http://localhost:8000',+ session_api_key='test-key',+ project_dir='/workspace/project',+ registered_marketplaces=None,+ )++ # Assert+ mock_client.post.assert_called_once()+ call_args = mock_client.post.call_args+ payload = call_args[1]['json']++ # The key is omitted entirely (not sent as null) when not provided.+ assert 'registered_marketplaces' not in payload++ @pytest.mark.asyncio+ @patch('httpx.AsyncClient')+ async def test_handles_empty_registered_marketplaces(self, mock_client_class):+ """Test that empty registered_marketplaces list is handled correctly."""+ # Arrange+ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'skills': [],+ 'sources': {},+ }+ mock_response.raise_for_status = MagicMock()++ mock_client = AsyncMock()+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=None)+ mock_client.post = AsyncMock(return_value=mock_response)+ mock_client_class.return_value = mock_client++ # Act+ await load_skills_from_agent_server(+ agent_server_url='http://localhost:8000',+ session_api_key='test-key',+ project_dir='/workspace/project',+ registered_marketplaces=[],+ )++ # Assert+ mock_client.post.assert_called_once()+ call_args = mock_client.post.call_args+ payload = call_args[1]['json']++ # Empty list is now preserved (semantic distinction from None)+ # Empty list = "explicitly no marketplaces", None = "not specified"+ assert payload.get('registered_marketplaces') == []diff --git a/tests/unit/server/routes/test_skills_api.py b/tests/unit/server/routes/test_skills_api.pyindex ee09e6cf21..8d2103f14a 100644--- a/tests/unit/server/routes/test_skills_api.py+++ b/tests/unit/server/routes/test_skills_api.py@@ -1,4 +1,5 @@import os+import subprocessfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock, patch@@ -14,7 +15,12 @@ from openhands.app_server.integrations.service_types import UserGitInfofrom openhands.app_server.secrets.secrets_models import Secretsfrom openhands.app_server.secrets.secrets_store import SecretsStorefrom openhands.app_server.settings.file_settings_store import FileSettingsStore+from openhands.app_server.settings.settings_models import MarketplaceRegistrationfrom openhands.app_server.settings.settings_store import SettingsStore+from openhands.app_server.user.skills_router import (+ GLOBAL_SKILLS_DIR,+ _clone_marketplace_repo,+)from openhands.app_server.user_auth.user_auth import UserAuth@@ -242,8 +248,6 @@ def test_global_skills_dir_points_to_repo_root():to the skills/ directory at the repo root. This prevents regressions like theone introduced in fb98faf4a where an incorrect path caused no skills to load."""- from openhands.app_server.user.skills_router import GLOBAL_SKILLS_DIR-# The directory should existassert GLOBAL_SKILLS_DIR.exists(), (f'GLOBAL_SKILLS_DIR does not exist: {GLOBAL_SKILLS_DIR}'@@ -267,3 +271,164 @@ def test_global_skills_dir_points_to_repo_root():f'Expected skill file not found: {expected_skill}. 'f'GLOBAL_SKILLS_DIR may be pointing to wrong location.')+++# Tests for marketplace-skills endpoint git clone failures+++class TestMarketplaceSkillsCloneFailures:+ """Tests for git clone failure scenarios in marketplace-skills endpoint."""++ @pytest.mark.asyncio+ async def test_clone_invalid_repo_path(self):+ """Test that invalid repository path returns appropriate error."""+ mock_user_context = MagicMock()+ mock_user_context.get_provider_tokens = AsyncMock(return_value=None)+ mock_user_context.get_user_id = AsyncMock(return_value='test-user')++ marketplace = MarketplaceRegistration(+ name='test-marketplace',+ source='github:owner/valid-repo',+ )++ # Mock _parse_marketplace_source to return invalid path (empty = parse failure)+ with patch(+ 'openhands.app_server.user.skills_router._parse_marketplace_source',+ return_value=('github', ''),+ ):+ result = await _clone_marketplace_repo(marketplace, mock_user_context)++ assert result[0] is None+ assert 'Invalid repository path' in result[1]++ @pytest.mark.asyncio+ async def test_clone_network_timeout(self):+ """Test that network timeout returns appropriate error."""++ mock_user_context = MagicMock()+ mock_user_context.get_provider_tokens = AsyncMock(return_value=None)+ mock_user_context.get_user_id = AsyncMock(return_value='test-user')++ marketplace = MarketplaceRegistration(+ name='test-marketplace',+ source='github:owner/nonexistent-repo-12345',+ )++ # Mock subprocess.run to raise TimeoutExpired+ with patch(+ 'openhands.app_server.user.skills_router.subprocess.run'+ ) as mock_run:+ mock_run.side_effect = subprocess.TimeoutExpired(+ cmd='git clone', timeout=120+ )+ result = await _clone_marketplace_repo(marketplace, mock_user_context)++ assert result[0] is None+ assert 'timed out' in result[1]++ @pytest.mark.asyncio+ async def test_clone_git_failure_returns_error(self):+ """Test that git clone failure returns error message."""+ mock_user_context = MagicMock()+ mock_user_context.get_provider_tokens = AsyncMock(return_value=None)+ mock_user_context.get_user_id = AsyncMock(return_value='test-user')++ marketplace = MarketplaceRegistration(+ name='test-marketplace',+ source='github:owner/nonexistent-repo-xyz',+ )++ # Mock subprocess.run to return error+ mock_result = MagicMock()+ mock_result.returncode = 128+ mock_result.stderr = 'Repository not found'++ with patch(+ 'openhands.app_server.user.skills_router.subprocess.run'+ ) as mock_run:+ mock_run.return_value = mock_result+ result = await _clone_marketplace_repo(marketplace, mock_user_context)++ assert result[0] is None+ assert 'Git clone failed' in result[1]+ assert 'not found' in result[1].lower()++ @pytest.mark.asyncio+ async def test_clone_with_ref_checkout_failure(self):+ """Test that checkout ref failure returns appropriate error."""+ mock_user_context = MagicMock()+ mock_user_context.get_provider_tokens = AsyncMock(return_value=None)+ mock_user_context.get_user_id = AsyncMock(return_value='test-user')++ marketplace = MarketplaceRegistration(+ name='test-marketplace',+ source='github:owner/valid-repo',+ ref='nonexistent-branch',+ )++ # Mock subprocess.run for clone success, checkout failure+ mock_clone_result = MagicMock()+ mock_clone_result.returncode = 0++ mock_checkout_result = MagicMock()+ mock_checkout_result.returncode = 128+ mock_checkout_result.stderr = " pathspec 'nonexistent-branch' did not match"++ def run_side_effect(cmd, *args, **kwargs):+ if 'checkout' in cmd:+ return mock_checkout_result+ return mock_clone_result++ with patch(+ 'openhands.app_server.user.skills_router.subprocess.run'+ ) as mock_run:+ with patch('openhands.app_server.user.skills_router._cleanup_clone_dir'):+ with patch('tempfile.mkdtemp', return_value=Path('/tmp/test_clone')):+ mock_run.side_effect = run_side_effect+ result = await _clone_marketplace_repo(+ marketplace, mock_user_context+ )++ assert result[0] is None+ assert 'Git checkout failed' in result[1]++ @pytest.mark.asyncio+ async def test_clone_repo_path_not_found(self):+ """Test that non-existent repo_path returns appropriate error."""+ mock_user_context = MagicMock()+ mock_user_context.get_provider_tokens = AsyncMock(return_value=None)+ mock_user_context.get_user_id = AsyncMock(return_value='test-user')++ marketplace = MarketplaceRegistration(+ name='test-marketplace',+ source='github:owner/valid-repo',+ repo_path='nonexistent/skills/dir',+ )++ mock_clone_result = MagicMock()+ mock_clone_result.returncode = 0++ def run_side_effect(cmd, *args, **kwargs):+ return mock_clone_result++ with patch(+ 'openhands.app_server.user.skills_router.subprocess.run'+ ) as mock_run:+ with patch(+ 'openhands.app_server.user.skills_router.Path.exists'+ ) as mock_exists:+ with patch(+ 'openhands.app_server.user.skills_router._cleanup_clone_dir'+ ):+ with patch(+ 'tempfile.mkdtemp', return_value=Path('/tmp/test_clone')+ ):+ mock_run.side_effect = run_side_effect+ # First call is clone, exists() returns False for repo_path+ mock_exists.return_value = False+ result = await _clone_marketplace_repo(+ marketplace, mock_user_context+ )++ assert result[0] is None+ assert 'Repo path not found' in result[1]diff --git a/tests/unit/storage/data_models/test_settings.py b/tests/unit/storage/data_models/test_settings.pyindex 518e394f40..9a66210c33 100644--- a/tests/unit/storage/data_models/test_settings.py+++ b/tests/unit/storage/data_models/test_settings.py@@ -4,11 +4,14 @@ from unittest.mock import patchimport pytestfrom fastmcp.mcp_config import MCPConfig-from pydantic import SecretStr+from pydantic import SecretStr, ValidationErrorimport openhands.app_server.settings.settings_models as settings_modulefrom openhands.app_server.settings.llm_profiles import ProfileNotFoundError-from openhands.app_server.settings.settings_models import Settings+from openhands.app_server.settings.settings_models import (+ MarketplaceRegistration,+ Settings,+)from openhands.app_server.settings.settings_router import LITE_LLM_API_URLfrom openhands.sdk.llm import LLMfrom openhands.sdk.settings import (@@ -532,6 +535,428 @@ def test_openhands_model_display_does_not_reverse_map():assert api_data['llm']['model'] == settings.agent_settings.llm.model+# --- Tests for MarketplaceRegistration ---+++class TestMarketplaceRegistration:+ """Tests for MarketplaceRegistration model."""++ def test_basic_registration(self):+ """Test creating a basic marketplace registration."""+ reg = MarketplaceRegistration(+ name='test-marketplace',+ source='github:owner/repo',+ )+ assert reg.name == 'test-marketplace'+ assert reg.source == 'github:owner/repo'+ assert reg.ref is None+ assert reg.repo_path is None+ assert reg.auto_load is False # Defaults to False, not None++ def test_registration_with_auto_load(self):+ """Test registration with auto_load=True."""+ reg = MarketplaceRegistration(+ name='public',+ source='github:OpenHands/skills',+ auto_load=True,+ )+ assert reg.auto_load++ def test_registration_with_ref(self):+ """Test registration with specific ref."""+ reg = MarketplaceRegistration(+ name='versioned',+ source='github:owner/repo',+ ref='v1.0.0',+ )+ assert reg.ref == 'v1.0.0'++ def test_registration_with_repo_path(self):+ """Test registration with repo_path for monorepos."""+ reg = MarketplaceRegistration(+ name='monorepo-marketplace',+ source='github:acme/monorepo',+ repo_path='marketplaces/internal',+ )+ assert reg.repo_path == 'marketplaces/internal'++ def test_repo_path_validation_rejects_absolute(self):+ """Test that absolute repo_path is rejected."""+ with pytest.raises(ValidationError, match='must be relative'):+ MarketplaceRegistration(+ name='test',+ source='github:owner/repo',+ repo_path='/absolute/path',+ )++ def test_repo_path_validation_rejects_traversal(self):+ """Test that parent directory traversal is rejected."""+ with pytest.raises(ValidationError, match="cannot contain '..'"):+ MarketplaceRegistration(+ name='test',+ source='github:owner/repo',+ repo_path='../escape/path',+ )++ def test_repo_path_validation_rejects_url(self):+ """A repository URL pasted into repo_path is rejected (not a subdir)."""+ with pytest.raises(ValidationError, match='not a URL'):+ MarketplaceRegistration(+ name='test',+ source='github:OpenHands/extensions',+ repo_path='https://github.com/OpenHands/extensions',+ )++ def test_serialization(self):+ """Test that MarketplaceRegistration serializes with standard pydantic."""+ reg = MarketplaceRegistration(+ name='test',+ source='github:owner/repo',+ ref='main',+ repo_path='plugins',+ auto_load=True,+ )+ data = reg.model_dump()+ assert data == {+ 'name': 'test',+ 'source': 'github:owner/repo',+ 'ref': 'main',+ 'repo_path': 'plugins',+ 'auto_load': True,+ 'scope': None,+ }++ def test_serialization_excludes_none_for_wire_payload(self):+ """exclude_none drops unset optional fields (as sent to the agent-server)."""+ reg = MarketplaceRegistration(name='test', source='github:owner/repo')+ assert reg.model_dump(exclude_none=True, exclude={'scope'}) == {+ 'name': 'test',+ 'source': 'github:owner/repo',+ 'auto_load': False,+ }++ # --- Name validation tests ---++ def test_name_validation_rejects_empty(self):+ """Test that empty name is rejected."""+ with pytest.raises(ValidationError, match='name cannot be empty'):+ MarketplaceRegistration(name='', source='github:owner/repo')++ def test_name_validation_rejects_whitespace_only(self):+ """Test that whitespace-only name is rejected."""+ with pytest.raises(ValidationError, match='name cannot be empty'):+ MarketplaceRegistration(name=' ', source='github:owner/repo')++ def test_name_validation_rejects_invalid_chars(self):+ """Test that names with invalid characters are rejected."""+ with pytest.raises(ValidationError, match='must start with a letter'):+ MarketplaceRegistration(name='123-invalid', source='github:owner/repo')++ def test_name_validation_rejects_spaces(self):+ """Test that names with spaces are rejected."""+ with pytest.raises(ValidationError, match='must start with a letter'):+ MarketplaceRegistration(name='invalid name', source='github:owner/repo')++ def test_name_validation_strips_whitespace(self):+ """Test that name whitespace is stripped."""+ reg = MarketplaceRegistration(name=' valid-name ', source='github:owner/repo')+ assert reg.name == 'valid-name'++ # --- Source validation tests ---++ def test_source_validation_github_format(self):+ """Test valid github:owner/repo source."""+ reg = MarketplaceRegistration(name='test', source='github:my-org/my-repo')+ assert reg.source == 'github:my-org/my-repo'++ def test_source_validation_https_url(self):+ """Test valid HTTPS git URL source."""+ reg = MarketplaceRegistration(+ name='test', source='https://github.com/owner/repo'+ )+ assert reg.source == 'https://github.com/owner/repo'++ def test_source_validation_ssh_url(self):+ """Test valid SSH git URL source."""+ reg = MarketplaceRegistration(name='test', source='[email protected]:owner/repo')+ assert reg.source == '[email protected]:owner/repo'++ def test_source_validation_relative_path(self):+ """Test valid relative local path source."""+ reg = MarketplaceRegistration(name='test', source='local/path/to/skills')+ assert reg.source == 'local/path/to/skills'++ def test_source_validation_rejects_empty(self):+ """Test that empty source is rejected."""+ with pytest.raises(ValidationError, match='source cannot be empty'):+ MarketplaceRegistration(name='test', source='')++ def test_source_validation_rejects_absolute_path(self):+ """Test that absolute local path is rejected."""+ with pytest.raises(ValidationError, match='must be relative'):+ MarketplaceRegistration(name='test', source='/absolute/path')++ def test_source_validation_rejects_parent_traversal(self):+ """Test that parent directory traversal in source is rejected."""+ with pytest.raises(ValidationError, match="cannot contain '..'"):+ MarketplaceRegistration(name='test', source='../escape/path')+++# --- Tests for Settings.registered_marketplaces ---+++class TestSettingsRegisteredMarketplaces:+ """Tests for registered_marketplaces field in Settings."""++ def test_settings_default_empty_registered_marketplaces(self):+ """Test that Settings defaults to empty registered_marketplaces."""+ settings = Settings()+ assert settings.registered_marketplaces == []++ def test_settings_with_registered_marketplaces(self):+ """Test Settings with registered_marketplaces configured."""+ marketplaces = [+ MarketplaceRegistration(+ name='public',+ source='github:OpenHands/skills',+ auto_load=True,+ ),+ MarketplaceRegistration(+ name='team',+ source='github:acme/plugins',+ ),+ ]+ settings = Settings(registered_marketplaces=marketplaces)++ assert len(settings.registered_marketplaces) == 2+ assert settings.registered_marketplaces[0].name == 'public'+ assert settings.registered_marketplaces[0].auto_load is True+ assert settings.registered_marketplaces[1].name == 'team'+ assert (+ settings.registered_marketplaces[1].auto_load is False+ ) # Defaults to False++ def test_settings_serialization_with_registered_marketplaces(self):+ """Test Settings serialization includes registered_marketplaces."""+ marketplaces = [+ MarketplaceRegistration(+ name='test',+ source='github:owner/repo',+ auto_load=True,+ ),+ ]+ settings = Settings(registered_marketplaces=marketplaces)+ data = settings.model_dump()++ assert 'registered_marketplaces' in data+ assert len(data['registered_marketplaces']) == 1+ assert data['registered_marketplaces'][0]['name'] == 'test'+ assert data['registered_marketplaces'][0]['auto_load']++ def test_settings_from_dict_with_registered_marketplaces(self):+ """Test creating Settings from dict with registered_marketplaces."""+ data = {+ 'registered_marketplaces': [+ {+ 'name': 'custom',+ 'source': 'github:custom/repo',+ 'ref': 'v1.0.0',+ 'auto_load': True,+ }+ ]+ }+ settings = Settings.model_validate(data)++ assert len(settings.registered_marketplaces) == 1+ assert settings.registered_marketplaces[0].name == 'custom'+ assert settings.registered_marketplaces[0].ref == 'v1.0.0'++ def test_settings_allows_unique_marketplace_names(self):+ """Test that unique marketplace names are allowed."""+ settings = Settings(+ registered_marketplaces=[+ MarketplaceRegistration(+ name='first',+ source='github:owner/repo1',+ ),+ MarketplaceRegistration(+ name='second',+ source='github:owner/repo2',+ ),+ ]+ )+ assert len(settings.registered_marketplaces) == 2++ def test_settings_with_mixed_marketplaces(self):+ """Test Settings with marketplace containing all optional fields."""+ settings = Settings(+ registered_marketplaces=[+ MarketplaceRegistration(+ name='full-featured',+ source='github:owner/repo',+ ref='v1.0.0',+ repo_path='marketplaces/internal',+ auto_load=True,+ ),+ MarketplaceRegistration(+ name='minimal',+ source='github:owner/minimal',+ ),+ MarketplaceRegistration(+ name='auto-load-only',+ source='github:owner/auto',+ auto_load=True,+ ),+ ]+ )+ assert len(settings.registered_marketplaces) == 3++ # Verify full-featured marketplace+ full = settings.registered_marketplaces[0]+ assert full.name == 'full-featured'+ assert full.ref == 'v1.0.0'+ assert full.repo_path == 'marketplaces/internal'+ assert full.auto_load++ # Verify minimal marketplace has None for optional fields and False for auto_load+ minimal = settings.registered_marketplaces[1]+ assert minimal.ref is None+ assert minimal.repo_path is None+ assert minimal.auto_load is False # Defaults to False, not None++ def test_settings_registered_marketplaces_serialization_roundtrip(self):+ """Test that marketplace data survives serialization roundtrip."""+ original = Settings(+ registered_marketplaces=[+ MarketplaceRegistration(+ name='test',+ source='github:owner/repo',+ ref='main',+ auto_load=True,+ ),+ ]+ )++ # Serialize to dict+ data = original.model_dump()+ assert 'registered_marketplaces' in data+ assert len(data['registered_marketplaces']) == 1++ # Deserialize back+ restored = Settings.model_validate(data)+ assert len(restored.registered_marketplaces) == 1+ assert restored.registered_marketplaces[0].name == 'test'+ assert restored.registered_marketplaces[0].ref == 'main'+ assert restored.registered_marketplaces[0].auto_load+++class TestMarketplaceRegistrationValidationEdgeCases:+ """Edge case tests for MarketplaceRegistration validation."""++ def test_name_with_hyphens_and_underscores(self):+ """Test that names with hyphens and underscores are valid."""+ reg = MarketplaceRegistration(+ name='my_marketplace-name', source='github:owner/repo'+ )+ assert reg.name == 'my_marketplace-name'++ def test_name_with_numbers(self):+ """Test that names with numbers are valid."""+ reg = MarketplaceRegistration(name='marketplace123', source='github:owner/repo')+ assert reg.name == 'marketplace123'++ def test_name_strips_surrounding_whitespace(self):+ """Test that surrounding whitespace is stripped from name."""+ reg = MarketplaceRegistration(name=' trimmed ', source='github:owner/repo')+ assert reg.name == 'trimmed'++ def test_source_strips_surrounding_whitespace(self):+ """Test that surrounding whitespace is stripped from source."""+ reg = MarketplaceRegistration(name='test', source=' github:owner/repo ')+ assert reg.source == 'github:owner/repo'++ def test_local_path_with_subdirectories(self):+ """Test that local paths with subdirectories are valid."""+ reg = MarketplaceRegistration(+ name='nested',+ source='marketplaces/team/internal',+ )+ assert reg.source == 'marketplaces/team/internal'++ def test_source_validation_rejects_leading_dot(self):+ """Test that sources starting with dot are rejected (hidden files)."""+ with pytest.raises(ValidationError, match='source must be'):+ MarketplaceRegistration(name='test', source='.hidden/repo')++ def test_source_validation_rejects_double_dot_in_middle(self):+ """Test that sources with .. in middle are rejected."""+ with pytest.raises(ValidationError, match="cannot contain '..'"):+ MarketplaceRegistration(name='test', source='path/../escape')++ def test_source_validation_rejects_git_protocol(self):+ """Test that git:// protocol URLs are valid."""+ reg = MarketplaceRegistration(+ name='test',+ source='git://github.com/owner/repo',+ )+ assert reg.source == 'git://github.com/owner/repo'++ def test_repo_path_validation_rejects_double_dot(self):+ """Test that repo_path with .. is rejected."""+ with pytest.raises(ValidationError, match="cannot contain '..'"):+ MarketplaceRegistration(+ name='test',+ source='github:owner/repo',+ repo_path='path/../escape',+ )+++class TestSettingsDuplicateMarketplaceNames:+ """Settings construction and marketplace name handling.++ Uniqueness is enforced on the write paths (not on model construction), so a+ legacy row with duplicate names can never lock a user out of settings.+ """++ def test_settings_tolerates_duplicate_marketplace_names(self):+ """Constructing Settings from duplicate stored names must not raise."""+ # Arrange / Act - duplicate names (e.g. legacy data) must load cleanly.+ settings = Settings(+ registered_marketplaces=[+ MarketplaceRegistration(name='plugins', source='github:owner/repo1'),+ MarketplaceRegistration(name='plugins', source='github:owner/repo2'),+ ]+ )+ # Assert+ assert len(settings.registered_marketplaces) == 2++ def test_settings_allows_same_source_different_names(self):+ """Test that same source with different names is allowed."""+ settings = Settings(+ registered_marketplaces=[+ MarketplaceRegistration(+ name='plugins-1',+ source='github:owner/repo',+ ),+ MarketplaceRegistration(+ name='plugins-2', # Different name, same source+ source='github:owner/repo',+ ),+ ]+ )+ assert len(settings.registered_marketplaces) == 2++ def test_settings_allows_empty_marketplaces(self):+ """Test that Settings allows empty registered_marketplaces."""+ settings = Settings(registered_marketplaces=[])+ assert settings.registered_marketplaces == []++ def test_settings_allows_none_marketplaces(self):+ """Test that Settings allows None registered_marketplaces (uses default)."""+ settings = Settings()+ assert settings.registered_marketplaces == []++def test_git_full_clone_defaults_to_false_and_updates():settings = Settings()