Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(agents): store an optional human display name

raullopez-sandbox4c6cf4cc4f62
diff --git a/core/switch_core/agent_display_name.py b/core/switch_core/agent_display_name.py
new file mode 100644
index 000000000..2cd8ce8d8
--- /dev/null
+++ b/core/switch_core/agent_display_name.py
@@ -0,0 +1,80 @@
+"""Validation for an agent's human display name.
+
+An agent's `name` is a machine identifier — lowercase, no spaces — because it
+is addressed, mentioned and matched on. A display name is the other half: the
+label a person reads ("Switch Dev" beside "switchdev"), so uppercase, spaces
+and punctuation are exactly what it exists to allow.
+
+It is rendered into message headers on the collaboration bridges, which is what
+the rules below constrain: a newline or a control character in a header is a
+way to forge a line the platform never sent, and length has to fit the
+narrowest consumer rather than the widest.
+"""
+
+from typing import NoReturn
+
+# Discord caps a webhook username at 80 characters; the other platforms sit at
+# or above that. 64 is a safe intersection with room to spare, and short enough
+# that a display name stays a label rather than a sentence.
+MAX_DISPLAY_NAME_LENGTH = 64
+
+
+class InvalidDisplayName(ValueError):
+ """Raised when a display name is empty, over-long, or unsafe to render."""
+
+
+def _reject(reason: str) -> NoReturn:
+ raise InvalidDisplayName(f"Invalid agent display name: {reason}")
+
+
+def _is_control_or_line_break(character: str) -> bool:
+ """True for C0, DEL, C1, and the Unicode line terminators.
+
+ U+2028, U+2029 and U+0085 are not C0 controls but end a line for the
+ consumers a display name reaches — Python's own `splitlines`, and JSON and
+ JavaScript on the bridge side — so they are line breaks for this purpose.
+ """
+ code_point = ord(character)
+ return (
+ code_point < 0x20 or 0x7F <= code_point <= 0x9F or character in "\u2028\u2029"
+ )
+
+
+def validate_display_name(value: str) -> str:
+ """Return `value` stripped, or raise `InvalidDisplayName`.
+
+ Accepts any printable text — uppercase, spaces and punctuation are the
+ point. Rejects a blank value, one longer than `MAX_DISPLAY_NAME_LENGTH`,
+ and any control character or line break.
+ """
+ if not isinstance(value, str):
+ _reject("must be a string")
+
+ candidate = value.strip()
+ if not candidate:
+ _reject("must not be empty")
+
+ if len(candidate) > MAX_DISPLAY_NAME_LENGTH:
+ _reject(f"must be at most {MAX_DISPLAY_NAME_LENGTH} characters")
+
+ if any(_is_control_or_line_break(character) for character in candidate):
+ _reject("must not contain line breaks or control characters")
+
+ return candidate
+
+
+def normalise_display_name(value: str | None) -> str | None:
+ """Validate an optional display name, treating blank as "no display name".
+
+ Callers accept `None` to mean "leave unset" and an empty string to mean
+ "clear it"; both collapse to `None` so a cleared display name is stored as
+ NULL rather than as an empty string the display layer would have to
+ special-case.
+ """
+ if value is None:
+ return None
+
+ if not value.strip():
+ return None
+
+ return validate_display_name(value)
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index e70627ea8..da877182a 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -159,6 +159,7 @@ async def register_agent_endpoint(
name=req.name,
description=req.description,
icon_url=req.icon_url,
+ display_name=req.display_name,
connector_type=req.connector_type,
integration_profile=req.integration_profile,
tools=req.tools,
@@ -183,6 +184,7 @@ async def _register_known(
name: str,
description: str,
icon_url: str | None,
+ display_name: str | None,
options_raw: dict,
parent_agent_id: str | None,
overwrite: bool,
@@ -217,6 +219,7 @@ async def _register_known(
name=name,
description=description,
icon_url=icon_url,
+ display_name=display_name,
connector_type=spec.connector_type,
integration_profile=integration_profile,
tools=spec.tools,
@@ -247,6 +250,7 @@ async def register_known_agent_endpoint(
name=req.name,
description=req.description,
icon_url=req.icon_url,
+ display_name=req.display_name,
options_raw=req.options,
parent_agent_id=req.parent_agent_id,
overwrite=req.overwrite,
@@ -337,6 +341,10 @@ async def register_known_agents_bulk_endpoint(
# no icon lets each fall back to something derived from its own
# name. An individual subagent can still be given one afterwards.
icon_url=None,
+ # Nor a display name: the whole point of a subagent's derived
+ # `<parent>.<child>` identifier is that it says which parent it
+ # belongs to, and one shared human label would erase that.
+ display_name=None,
options_raw=options,
parent_agent_id=req.parent_agent_id,
overwrite=req.overwrite,
diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.py
index 5faa1e8dc..31343fe47 100644
--- a/core/switch_core/bridges/agent/api/schemas.py
+++ b/core/switch_core/bridges/agent/api/schemas.py
@@ -21,6 +21,7 @@ class RegisterAgentRequest(BaseModel):
name: str
description: str
icon_url: str | None = None
+ display_name: str | None = None
connector_type: str
integration_profile: IntegrationProfile
tools: list[ToolSpec] = []
@@ -39,6 +40,7 @@ class RegisterKnownAgentRequest(BaseModel):
name: str
description: str
icon_url: str | None = None
+ display_name: str | None = None
options: dict[str, Any] = {}
# When set, register this agent as a child of `parent_agent_id` (e.g. a
# Claude Code subagent under the user's main agent). None = top-level.
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 7930bc4d4..5630bb43a 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -1551,10 +1551,12 @@ async def list_agents(
Returns:
A list of agent summaries (sorted by name), each
- {id, name, description, icon_url, connector_type, connection_model,
- tool_count, model_count, owner_id, owner_name, oauth_client_id,
- created_at, parent_agent_id, known_agent_type, known_agent_options}.
- `icon_url` is null when the agent has no icon set.
+ {id, name, description, icon_url, display_name, connector_type,
+ connection_model, tool_count, model_count, owner_id, owner_name,
+ oauth_client_id, created_at, parent_agent_id, known_agent_type,
+ known_agent_options}.
+ `icon_url` is null when the agent has no icon set. `display_name` is
+ null when the agent has no display name set; fall back to `name`.
Use `get_agent_detail` for the full detail of one agent.
"""
agent_id = get_agent_id()
@@ -1576,12 +1578,13 @@ async def get_agent_detail(agent_id: str) -> dict[str, Any]:
`list_all_rooms`/`get_room_detail`).
Returns:
- {id, name, description, icon_url, connector_type, connection_model,
- tool_count, model_count, owner_id, owner_name, oauth_client_id,
- created_at, parent_agent_id, known_agent_type, known_agent_options,
- agent_type, integration_profile, tools, models, rooms, sessions,
- children}.
- `icon_url` is null when the agent has no icon set.
+ {id, name, description, icon_url, display_name, connector_type,
+ connection_model, tool_count, model_count, owner_id, owner_name,
+ oauth_client_id, created_at, parent_agent_id, known_agent_type,
+ known_agent_options, agent_type, integration_profile, tools, models,
+ rooms, sessions, children}.
+ `icon_url` is null when the agent has no icon set. `display_name` is
+ null when the agent has no display name set; fall back to `name`.
"""
caller_id = get_agent_id()
protocol = get_protocol()
diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.py
index c313850b2..2beb93cf9 100644
--- a/core/switch_core/bridges/agent/protocol/agent_detail.py
+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py
@@ -62,6 +62,7 @@ async def build_agent_summary(
name=agent.name,
description=agent.description,
icon_url=agent.icon_url,
+ display_name=agent.display_name,
connector_type=agent.connector_type,
connection_model=profile.get("connection_model"),
tool_count=len(tools),
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index b29d75e09..16940ba97 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -26,6 +26,7 @@ from switch_core.addressing import (
owner_only_policy,
parse_policy,
)
+from switch_core.agent_display_name import normalise_display_name
from switch_core.agent_icon import normalise_icon_url, validate_icon_url
from switch_core.aliases import check_alias_collisions, validate_alias_format
from switch_core.authz import Action, Principal, require, require_manage
@@ -113,7 +114,9 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-_VALID_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
+# \A and \Z rather than ^ and $: Python's $ also matches before a single
+# trailing newline, which would let an identifier carry a line break.
+_VALID_NAME_RE = re.compile(r"\A[a-z0-9][a-z0-9._-]*\Z")
# History pagination. The homeserver caps a /messages page regardless of what
# we ask for, and state events consume it without ever reaching the caller, so
@@ -189,6 +192,7 @@ class ProtocolService:
name: str,
description: str,
icon_url: str | None = None,
+ display_name: str | None = None,
connector_type: str,
integration_profile: IntegrationProfile,
tools: list[ToolSpec] | None = None,
@@ -227,10 +231,15 @@ class ProtocolService:
than clearing it, so re-registering an agent does not silently discard
a picture the owner chose.
+ ``display_name`` is the human-readable label shown beside the machine
+ identifier ``name``, or None for none. It behaves like ``icon_url`` on
+ re-registration: None keeps whatever the agent already has.
+
Raises:
ValueError: name is invalid (lowercase alphanumeric, dots, hyphens,
or underscores — no spaces).
InvalidIconUrl: ``icon_url`` is malformed or points somewhere unsafe.
+ InvalidDisplayName: ``display_name`` is over-long or unsafe to render.
AgentExistsError: agent with this name exists and ``overwrite`` is
False.
"""
@@ -241,6 +250,7 @@ class ProtocolService:
)
validated_icon_url = normalise_icon_url(icon_url)
+ validated_display_name = normalise_display_name(display_name)
tool_specs = tools or []
model_specs = models or []
@@ -267,6 +277,7 @@ class ProtocolService:
encrypted_key=encrypted_key,
description=description,
icon_url=validated_icon_url,
+ display_name=validated_display_name,
agent_type=agent_type,
connector_type=connector_type,
integration_profile=profile_data,
@@ -284,6 +295,7 @@ class ProtocolService:
name=name,
description=description,
icon_url=validated_icon_url,
+ display_name=validated_display_name,
agent_type=agent_type,
connector_type=connector_type,
integration_profile=profile_data,
@@ -317,6 +329,7 @@ class ProtocolService:
registration_token: str,
name: str,
description: str,
+ display_name: str | None = None,
connector_type: str,
integration_profile: IntegrationProfile,
tools: list[ToolSpec] | None = None,
@@ -340,6 +353,7 @@ class ProtocolService:
return await self.register_agent(
name=name,
description=description,
+ display_name=display_name,
connector_type=connector_type,
integration_profile=integration_profile,
tools=tools,
@@ -358,6 +372,7 @@ class ProtocolService:
name: str,
description: str,
icon_url: str | None,
+ display_name: str | None,
agent_type: str,
connector_type: str,
integration_profile: dict[str, Any],
@@ -380,6 +395,11 @@ class ProtocolService:
)
await self.api_key_store.create(session, api_key_record)
+ # The Matrix client's display name is the agent's identifier, never its
+ # human display name: it is stamped on every event as `sender_name`, and
+ # the collaboration bridges match on it to recognise an agent's own echo
+ # coming back from a platform. A human name here would make an agent
+ # re-import its own messages as a stranger.
client_record = await self.client_lifecycle.create_client(
client_type="agent",
display_name=name,
@@ -389,6 +409,7 @@ class ProtocolService:
name=name,
description=description,
icon_url=icon_url,
+ display_name=display_name,
agent_type=agent_type,
connector_type=connector_type,
integration_profile=integration_profile,
@@ -439,6 +460,7 @@ class ProtocolService:
encrypted_key: str,
description: str,
icon_url: str | None,
+ display_name: str | None,
agent_type: str,
connector_type: str,
integration_profile: dict[str, Any],
@@ -463,6 +485,11 @@ class ProtocolService:
# rotates credentials and rebuilds the profile, and callers that know
# nothing about icons must not wipe one the owner chose.
icon_fields = {} if icon_url is None else {"icon_url": icon_url}
+ # Same for the display name: a connector re-registers on every startup
+ # and knows nothing about it.
+ display_name_fields = (
+ {} if display_name is None else {"display_name": display_name}
+ )
await self.agent_store.update(
session,
existing.id,
@@ -475,6 +502,7 @@ class ProtocolService:
oauth_client_id=oauth_client_id,
parent_agent_id=parent_agent_id,
**icon_fields,
+ **display_name_fields,
)
await self.api_key_store.delete(session, old_api_key_id)
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 0599a658d..ce9181412 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -105,6 +105,12 @@ class Agent(Base):
# means no icon was chosen, and the display layer supplies the fallback, so
# that fallback can change without touching stored rows.
icon_url: Mapped[str | None] = mapped_column(Text, nullable=True)
+ # Human-readable name shown to people ("Switch Dev") next to the machine
+ # identifier `name` carries ("switchdev"). NULL means none was chosen and
+ # the display layer falls back to `name`. Never the Matrix client display
+ # name: that stays the identifier, because it is what bridges match on to
+ # recognise an agent's own echo.
+ display_name: Mapped[str | None] = mapped_column(Text, nullable=True)
agent_type: Mapped[str] = mapped_column(Text, nullable=False)
connector_type: Mapped[str] = mapped_column(Text, nullable=False)
integration_profile: Mapped[dict] = mapped_column(JSONB, nullable=False)
diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.py
index 7ed680c0b..e5316c2e5 100644
--- a/core/switch_core/gateway/agents.py
+++ b/core/switch_core/gateway/agents.py
@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends, HTTPException
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.agent_display_name import InvalidDisplayName, normalise_display_name
from switch_core.agent_icon import InvalidIconUrl, normalise_icon_url
from switch_core.authz import Principal, require_manage
from switch_core.bridges.agent.protocol.agent_detail import (
@@ -45,6 +46,7 @@ from switch_core.gateway.schemas import (
RegisterKnownSubagentsResponse,
RegisterOtherAgentRequest,
UpdateAddressingPolicyRequest,
+ UpdateAgentDisplayNameRequest,
UpdateAgentIconRequest,
UpdateAgentOptionsRequest,
)
@@ -161,6 +163,7 @@ async def register_known_agent(
name=req.name,
description=req.description,
icon_url=req.icon_url,
+ display_name=req.display_name,
connector_type=spec.connector_type,
integration_profile=integration_profile,
tools=spec.tools,
@@ -394,6 +397,56 @@ async def update_agent_icon(
return await build_agent_summary(session, agent_store, agent, owner_name)
[email protected]("/{agent_id}/display-name")
+async def update_agent_display_name(
+ agent_id: str,
+ req: UpdateAgentDisplayNameRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> AgentSummary:
+ """Set, change, or clear an agent's human display name.
+
+ ``display_name: null`` (or a blank string) clears it, leaving the agent
+ with only its identifier. Only the agent's owner (or an admin) may change
+ it. Like the icon, this applies to every agent regardless of how it was
+ registered.
+
+ A name that is over-long or carries a line break is refused with 400 rather
+ than stored to break a message header later.
+ """
+ agent = await agent_store.get(session, agent_id)
+ if agent is None:
+ raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")
+
+ try:
+ require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)
+ except PermissionError:
+ raise HTTPException(
+ status_code=403,
+ detail="Only the agent's owner or an admin can change its display name.",
+ )
+
+ try:
+ display_name = normalise_display_name(req.display_name)
+ except InvalidDisplayName as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ await agent_store.update(session, agent_id, display_name=display_name)
+ await session.commit()
+ await session.refresh(agent)
+
+ logger.info(
+ "%s agent %s display name by user %s",
+ "Cleared" if display_name is None else "Set",
+ agent.name,
+ user.name,
+ )
+
+ owner_name = user.name if agent.owner_id == user.id else None
+ return await build_agent_summary(session, agent_store, agent, owner_name)
+
+
@router.post("/register-other")
async def register_other_agent(
req: RegisterOtherAgentRequest,
@@ -416,6 +469,7 @@ async def register_other_agent(
name=req.name,
description=req.description,
icon_url=req.icon_url,
+ display_name=req.display_name,
connector_type="external",
integration_profile=default_profile,
owner_id=user.id,
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index f2931cdee..bf3e10893 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -218,6 +218,10 @@ class AgentSummary(BaseModel):
# not an error: the caller renders its own fallback rather than Switch
# inventing a default, so the fallback can change without a data migration.
icon_url: str | None = None
+ # Human-readable label for the agent, or null when none is set. The caller
+ # falls back to `name`, which is the machine identifier the agent is
+ # addressed by and stays what every bridge matches on.
+ display_name: str | None = None
connector_type: str
connection_model: str | None
tool_count: int
@@ -318,6 +322,17 @@ class UpdateAgentIconRequest(BaseModel):
icon_url: str | None
+class UpdateAgentDisplayNameRequest(BaseModel):
+ """Set (or clear) an agent's human display name.
+
+ ``display_name: null`` (or a blank string) clears it — the agent falls back
+ to its identifier. The field is required rather than defaulted so that
+ clearing a display name is always something the client said, never
+ something it forgot to send."""
+
+ display_name: str | None
+
+
class KnownAgentType(BaseModel):
key: str
connector_type: str
@@ -333,6 +348,9 @@ class RegisterKnownAgentRequest(BaseModel):
# re-registration that omits it keeps whatever icon the agent already has
# rather than clearing it.
icon_url: str | None = None
+ # Optional at registration, and re-registration that omits it keeps
+ # whatever the agent already has, exactly like `icon_url`.
+ display_name: str | None = None
options: dict[str, Any] = {}
overwrite: bool = False
@@ -393,6 +411,7 @@ class RegisterOtherAgentRequest(BaseModel):
name: str
description: str
icon_url: str | None = None
+ display_name: str | None = None
overwrite: bool = False
diff --git a/core/switch_core/migrations/versions/d3f7b1c95e42_add_display_name_to_agents.py b/core/switch_core/migrations/versions/d3f7b1c95e42_add_display_name_to_agents.py
new file mode 100644
index 000000000..affee7279
--- /dev/null
+++ b/core/switch_core/migrations/versions/d3f7b1c95e42_add_display_name_to_agents.py
@@ -0,0 +1,26 @@
+"""add display_name to agents
+
+Revision ID: d3f7b1c95e42
+Revises: a2171c0de1f4
+Create Date: 2026-09-01 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "d3f7b1c95e42"
+down_revision: str | None = "a2171c0de1f4"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column("agents", sa.Column("display_name", sa.Text(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("agents", "display_name")
diff --git a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
new file mode 100644
index 000000000..a9494e6f8
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
@@ -0,0 +1,97 @@
+"""A ProtocolService wired up far enough to run `register_agent`.
+
+Registration touches a Matrix client lifecycle and the collaboration bridges;
+tests about what registration *records* need neither, so the service is built
+by hand with fakes in place of both.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.bridges.agent.protocol.types import (
+ IntegrationProfile,
+ TaskProtocolConfig,
+)
+from switch_core.db.models import Client, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.api_key_store import ApiKeyStore
+
+PROFILE = IntegrationProfile(
+ connection_model="session_passive",
+ message_exchange=True,
+ pre_invocation_mediation=[],
+ post_invocation_mediation=[],
+ event_reporting=[],
+ task_protocol=TaskProtocolConfig(can_delegate=False, can_accept=False),
+)
+
+
+class FakeClientLifecycle:
+ """Creates the Client row `_create_agent` attaches the Agent to, recording
+ the display name it was asked for; the real lifecycle also starts a Matrix
+ sync loop, which these tests do not need."""
+
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
+ self._session_factory = session_factory
+ self.requested_display_names: list[str] = []
+ self.started: list[str] = []
+
+ async def create_client(self, *, client_type: str, display_name: str) -> Client:
+ self.requested_display_names.append(display_name)
+ async with self._session_factory() as session:
+ client = Client(
+ matrix_user_id=f"@{display_name}:test",
+ display_name=display_name,
+ type=client_type,
+ password="x",
+ )
+ session.add(client)
+ await session.commit()
+ return client
+
+ def start_client(self, client: Client) -> None:
+ self.started.append(client.id)
+
+
+class NoBridges:
+ def all_bridges(self) -> list[object]:
+ return []
+
+
+def make_service(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> ProtocolService:
+ svc = object.__new__(ProtocolService)
+ svc.session_factory = session_factory # type: ignore[attr-defined]
+ svc.agent_store = AgentStore() # type: ignore[attr-defined]
+ svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]
+ svc.client_lifecycle = FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
+ svc.collab_lifecycle = NoBridges() # type: ignore[attr-defined]
+ svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]
+ return svc
+
+
+async def make_owner(session_factory: async_sessionmaker[AsyncSession]) -> str:
+ async with session_factory() as session:
+ user = User(name="owner", email="owner@test", role="user", password_hash="x")
+ session.add(user)
+ await session.commit()
+ return user.id
+
+
+async def register(
+ svc: ProtocolService, name: str, owner_id: str, **kwargs: object
+) -> str:
+ result = await svc.register_agent(
+ name=name,
+ description=f"{name} desc",
+ connector_type="test",
+ integration_profile=PROFILE,
+ owner_id=owner_id,
+ **kwargs, # type: ignore[arg-type]
+ )
+ return result.agent_id
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_name_validation.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_name_validation.py
new file mode 100644
index 000000000..48d559bda
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_name_validation.py
@@ -0,0 +1,58 @@
+"""What an agent identifier may be.
+
+`name` is the machine identifier: it is addressed, mentioned, derived into
+subagent names, and used as the Matrix display name every bridge matches on.
+The shape it accepts is therefore load-bearing, and pinned here so a widening
+(a space, an uppercase letter) has to be a deliberate edit to this file rather
+than a side effect of loosening the pattern.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from switch_core.bridges.agent.protocol.service import _VALID_NAME_RE
+
+
+ "name",
+ [
+ "switchdev",
+ "a",
+ "9",
+ "switch-dev",
+ "switch_dev",
+ "switch.dev",
+ "claude-code.reviewer",
+ "agent2",
+ ],
+)
+def test_accepts_lowercase_identifiers(name: str) -> None:
+ assert _VALID_NAME_RE.match(name) is not None
+
+
+ "name",
+ [
+ "",
+ "Switch Dev",
+ "SwitchDev",
+ "switch dev",
+ "-switch",
+ "_switch",
+ ".switch",
+ "switch/dev",
+ "switch:dev",
+ "switch@dev",
+ "switch\ndev",
+ "switch\tdev",
+ " switchdev",
+ "switchdev ",
+ "switchdev\n",
+ "switch-dev\n",
+ "switchdev\r",
+ "swítchdev",
+ ],
+)
+def test_rejects_anything_else(name: str) -> None:
+ assert _VALID_NAME_RE.match(name) is None
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
index d28006b33..ebb2c1a7b 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
@@ -8,84 +8,12 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.addressing import parse_policy
from switch_core.bridges.agent.protocol.service import ProtocolService
-from switch_core.bridges.agent.protocol.types import (
- IntegrationProfile,
- TaskProtocolConfig,
+from tests.switch_core.bridges.agent.protocol.registration_harness import (
+ PROFILE,
+ make_owner,
+ make_service,
+ register,
)
-from switch_core.db.models import Client, User
-from switch_core.db.stores.agent_store import AgentStore
-from switch_core.db.stores.api_key_store import ApiKeyStore
-
-_PROFILE = IntegrationProfile(
- connection_model="session_passive",
- message_exchange=True,
- pre_invocation_mediation=[],
- post_invocation_mediation=[],
- event_reporting=[],
- task_protocol=TaskProtocolConfig(can_delegate=False, can_accept=False),
-)
-
-
-class _FakeClientLifecycle:
- """Creates the Client row `_create_agent` attaches the Agent to; the real
- lifecycle also starts a Matrix sync loop, which a policy test does not need."""
-
- def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
- self._session_factory = session_factory
- self.started: list[str] = []
-
- async def create_client(self, *, client_type: str, display_name: str) -> Client:
- async with self._session_factory() as session:
- client = Client(
- matrix_user_id=f"@{display_name}:test",
- display_name=display_name,
- type=client_type,
- password="x",
- )
- session.add(client)
- await session.commit()
- return client
-
- def start_client(self, client: Client) -> None:
- self.started.append(client.id)
-
-
-class _NoBridges:
- def all_bridges(self) -> list[object]:
- return []
-
-
-def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:
- svc = object.__new__(ProtocolService)
- svc.session_factory = session_factory # type: ignore[attr-defined]
- svc.agent_store = AgentStore() # type: ignore[attr-defined]
- svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]
- svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
- svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
- svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]
- return svc
-
-
-async def _make_owner(session_factory: async_sessionmaker[AsyncSession]) -> str:
- async with session_factory() as session:
- user = User(name="owner", email="owner@test", role="user", password_hash="x")
- session.add(user)
- await session.commit()
- return user.id
-
-
-async def _register(
- svc: ProtocolService, name: str, owner_id: str, **kwargs: object
-) -> str:
- result = await svc.register_agent(
- name=name,
- description=f"{name} desc",
- connector_type="test",
- integration_profile=_PROFILE,
- owner_id=owner_id,
- **kwargs, # type: ignore[arg-type]
- )
- return result.agent_id
async def _policy_of(
@@ -103,9 +31,9 @@ class TestRegistrationDefaultPolicy:
async def test_new_agent_is_owner_only(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- svc = _service(session_factory)
- owner_id = await _make_owner(session_factory)
- agent_id = await _register(svc, "fresh", owner_id)
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(svc, "fresh", owner_id)
raw = await _policy_of(svc, session_factory, agent_id)
policy = parse_policy(raw)
@@ -140,9 +68,9 @@ class TestRegistrationDefaultPolicy:
async def test_addressable_by_agent_ids_are_admitted(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- svc = _service(session_factory)
- owner_id = await _make_owner(session_factory)
- agent_id = await _register(
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(
svc, "dispatched", owner_id, addressable_by_agent_ids=["dispatcher"]
)
@@ -177,9 +105,9 @@ class TestRegistrationDefaultPolicy:
) -> None:
# A service the deployment offers everyone (a server-side connector
# agent) is owned by someone only in the bookkeeping sense.
- svc = _service(session_factory)
- owner_id = await _make_owner(session_factory)
- agent_id = await _register(svc, "shared", owner_id, owner_only=False)
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(svc, "shared", owner_id, owner_only=False)
raw = await _policy_of(svc, session_factory, agent_id)
assert raw is None
@@ -188,9 +116,9 @@ class TestRegistrationDefaultPolicy:
async def test_reregistration_leaves_the_policy_alone(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- svc = _service(session_factory)
- owner_id = await _make_owner(session_factory)
- agent_id = await _register(svc, "kept", owner_id, owner_only=False)
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(svc, "kept", owner_id, owner_only=False)
async with session_factory() as session:
await svc.agent_store.update(
@@ -200,7 +128,7 @@ class TestRegistrationDefaultPolicy:
)
await session.commit()
- again = await _register(svc, "kept", owner_id, overwrite=True)
+ again = await register(svc, "kept", owner_id, overwrite=True)
assert again == agent_id
raw = await _policy_of(svc, session_factory, agent_id)
assert raw == {"rules": [{"users": ["ext-3"], "agents": []}]}
@@ -210,8 +138,8 @@ class TestRegisterWithTokenPassesThrough:
async def test_token_registration_defaults_to_owner_only(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- svc = _service(session_factory)
- owner_id = await _make_owner(session_factory)
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
captured: dict[str, object] = {}
async def _register_agent(**kwargs: object) -> object:
@@ -228,7 +156,7 @@ class TestRegisterWithTokenPassesThrough:
name="tokenised",
description="d",
connector_type="test",
- integration_profile=_PROFILE,
+ integration_profile=PROFILE,
)
assert captured["owner_only"] is True
assert captured["addressable_by_agent_ids"] is None
@@ -236,8 +164,8 @@ class TestRegisterWithTokenPassesThrough:
async def test_token_registration_forwards_the_overrides(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- svc = _service(session_factory)
- owner_id = await _make_owner(session_factory)
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
captured: dict[str, object] = {}
async def _register_agent(**kwargs: object) -> object:
@@ -254,7 +182,7 @@ class TestRegisterWithTokenPassesThrough:
name="tokenised",
description="d",
connector_type="test",
- integration_profile=_PROFILE,
+ integration_profile=PROFILE,
owner_only=False,
addressable_by_agent_ids=["dispatcher"],
)
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py b/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py
new file mode 100644
index 000000000..ee7170dc9
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_display_name.py
@@ -0,0 +1,134 @@
+"""Registration and the agent's human display name.
+
+Two things are load-bearing here. First, that the Matrix client keeps the
+*identifier* as its display name: the bridges recognise an agent's own echo
+coming back from a platform by matching `sender_name`, so a human name on the
+client would make an agent re-import its own messages as a stranger and appear
+in the room twice. Second, that a re-registration which says nothing about the
+icon or the display name keeps both — server-side connectors re-register with
+`overwrite=True` on every startup.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.agent_display_name import InvalidDisplayName
+from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.db.models import Agent, Client
+from tests.switch_core.bridges.agent.protocol.registration_harness import (
+ FakeClientLifecycle,
+ make_owner,
+ make_service,
+ register,
+)
+
+_ICON = "https://cdn.example.com/9.x/bottts/png?seed=switchdev"
+
+
+async def _agent(
+ svc: ProtocolService,
+ session_factory: async_sessionmaker[AsyncSession],
+ agent_id: str,
+) -> Agent:
+ async with session_factory() as session:
+ agent = await svc.agent_store.get(session, agent_id)
+ assert agent is not None
+ return agent
+
+
+class TestMatrixIdentityStaysTheIdentifier:
+ async def test_a_display_name_does_not_reach_the_matrix_client(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(svc, "switchdev", owner_id, display_name="Switch Dev")
+
+ agent = await _agent(svc, session_factory, agent_id)
+ assert agent.display_name == "Switch Dev"
+ assert agent.name == "switchdev"
+
+ # What the bridges match on is the identifier, not the human name.
+ lifecycle = svc.client_lifecycle
+ assert isinstance(lifecycle, FakeClientLifecycle)
+ assert lifecycle.requested_display_names == ["switchdev"]
+
+ async with session_factory() as session:
+ client = await session.get(Client, agent.client_id)
+ assert client is not None
+ assert client.display_name == "switchdev"
+
+ async def test_registering_without_one_stores_null(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(svc, "plain", owner_id)
+
+ agent = await _agent(svc, session_factory, agent_id)
+ assert agent.display_name is None
+
+
+class TestDisplayNameValidationAtRegistration:
+ async def test_blank_collapses_to_null(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(svc, "blank", owner_id, display_name=" ")
+
+ agent = await _agent(svc, session_factory, agent_id)
+ assert agent.display_name is None
+
+ async def test_a_newline_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ with pytest.raises(InvalidDisplayName):
+ await register(svc, "forged", owner_id, display_name="Switch\nDev")
+
+
+class TestReregistrationKeepsWhatItWasNotTold:
+ async def test_omitting_both_preserves_icon_and_display_name(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # A server-side connector re-registers with overwrite=True on every
+ # startup and knows nothing about either field.
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(
+ svc, "connected", owner_id, icon_url=_ICON, display_name="Switch Dev"
+ )
+
+ again = await register(svc, "connected", owner_id, overwrite=True)
+ assert again == agent_id
+
+ agent = await _agent(svc, session_factory, agent_id)
+ assert agent.icon_url == _ICON
+ assert agent.display_name == "Switch Dev"
+
+ async def test_supplying_them_replaces_them(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ owner_id = await make_owner(session_factory)
+ agent_id = await register(
+ svc, "renamed", owner_id, icon_url=_ICON, display_name="Switch Dev"
+ )
+
+ other_icon = "https://cdn.example.com/9.x/shapes/png?seed=switchdev"
+ await register(
+ svc,
+ "renamed",
+ owner_id,
+ overwrite=True,
+ icon_url=other_icon,
+ display_name="Switch Reviewer",
+ )
+
+ agent = await _agent(svc, session_factory, agent_id)
+ assert agent.icon_url == other_icon
+ assert agent.display_name == "Switch Reviewer"
diff --git a/core/tests/switch_core/gateway/agent_route_harness.py b/core/tests/switch_core/gateway/agent_route_harness.py
new file mode 100644
index 000000000..89f20d95a
--- /dev/null
+++ b/core/tests/switch_core/gateway/agent_route_harness.py
@@ -0,0 +1,62 @@
+"""Rows the agent-route tests write straight into Postgres.
+
+An Agent cannot exist without a Client and an ApiKey, and the routes under test
+care about neither, so both are built here at their minimum shape.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import Agent, ApiKey, Client, User
+
+
+async def add_user(session: AsyncSession, *, name: str, role: str = "user") -> User:
+ user = User(name=name, email=f"{name}@example.com", role=role)
+ session.add(user)
+ await session.flush()
+ return user
+
+
+async def add_agent(
+ session: AsyncSession,
+ *,
+ name: str,
+ owner_id: str | None,
+ icon_url: str | None = None,
+ display_name: str | None = None,
+) -> Agent:
+ client = Client(
+ type="agent",
+ matrix_user_id=f"@{name}:test",
+ display_name=name,
+ password=f"pw-{name}",
+ )
+ session.add(client)
+ await session.flush()
+
+ api_key = ApiKey(
+ type="agent",
+ key_hash=f"hash-{name}",
+ encrypted_key=f"enc-{name}",
+ label=name,
+ user_id=owner_id,
+ )
+ session.add(api_key)
+ await session.flush()
+
+ agent = Agent(
+ name=name,
+ description=f"{name} desc",
+ icon_url=icon_url,
+ display_name=display_name,
+ agent_type="session_passive",
+ connector_type="external",
+ integration_profile={"connection_model": "session_passive"},
+ client_id=client.id,
+ api_key_id=api_key.id,
+ owner_id=owner_id,
+ )
+ session.add(agent)
+ await session.flush()
+ return agent
diff --git a/core/tests/switch_core/gateway/test_agent_display_name_route.py b/core/tests/switch_core/gateway/test_agent_display_name_route.py
new file mode 100644
index 000000000..d461993d2
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_agent_display_name_route.py
@@ -0,0 +1,197 @@
+"""The gateway route that sets, changes, and clears an agent's display name.
+
+Exercised against real Postgres with real stores, like the other gateway route
+tests: ownership is enforced, a name that would break a message header is
+refused at write time, and clearing is expressible and lands as NULL.
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.agent_display_name import MAX_DISPLAY_NAME_LENGTH
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.gateway.agents import update_agent_display_name
+from switch_core.gateway.schemas import UpdateAgentDisplayNameRequest
+from tests.switch_core.gateway.agent_route_harness import add_agent, add_user
+
+_AGENT_STORE = AgentStore()
+
+_NAME = "Switch Dev"
+_OTHER_NAME = "Switch Reviewer"
+
+
+class TestUpdateAgentDisplayName:
+ async def test_owner_can_set_a_display_name(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(session, name="switchdev", owner_id=owner.id)
+
+ summary = await update_agent_display_name(
+ agent.id,
+ UpdateAgentDisplayNameRequest(display_name=_NAME),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert summary.display_name == _NAME
+ # The identifier is untouched: it is what the agent is addressed by.
+ assert summary.name == "switchdev"
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.display_name == _NAME
+
+ async def test_surrounding_whitespace_is_trimmed(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(session, name="switchdev", owner_id=owner.id)
+
+ summary = await update_agent_display_name(
+ agent.id,
+ UpdateAgentDisplayNameRequest(display_name=" Switch Dev "),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert summary.display_name == _NAME
+
+ async def test_owner_can_change_an_existing_display_name(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(
+ session, name="switchdev", owner_id=owner.id, display_name=_NAME
+ )
+
+ summary = await update_agent_display_name(
+ agent.id,
+ UpdateAgentDisplayNameRequest(display_name=_OTHER_NAME),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert summary.display_name == _OTHER_NAME
+
+ @pytest.mark.parametrize("cleared", [None, " "])
+ async def test_null_or_blank_clears_it(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ cleared: str | None,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(
+ session, name="switchdev", owner_id=owner.id, display_name=_NAME
+ )
+
+ summary = await update_agent_display_name(
+ agent.id,
+ UpdateAgentDisplayNameRequest(display_name=cleared),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert summary.display_name is None
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.display_name is None
+
+ async def test_non_owner_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ other = await add_user(session, name="other")
+ agent = await add_agent(session, name="switchdev", owner_id=owner.id)
+
+ with pytest.raises(HTTPException) as exc:
+ await update_agent_display_name(
+ agent.id,
+ UpdateAgentDisplayNameRequest(display_name=_NAME),
+ session,
+ _AGENT_STORE,
+ other,
+ )
+
+ assert exc.value.status_code == 403
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.display_name is None
+
+ async def test_admin_can_set_one_on_an_agent_they_do_not_own(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ admin = await add_user(session, name="admin", role="admin")
+ agent = await add_agent(session, name="switchdev", owner_id=owner.id)
+
+ summary = await update_agent_display_name(
+ agent.id,
+ UpdateAgentDisplayNameRequest(display_name=_NAME),
+ session,
+ _AGENT_STORE,
+ admin,
+ )
+
+ assert summary.display_name == _NAME
+
+ async def test_unknown_agent_is_404(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+
+ with pytest.raises(HTTPException) as exc:
+ await update_agent_display_name(
+ "no-such-agent",
+ UpdateAgentDisplayNameRequest(display_name=_NAME),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert exc.value.status_code == 404
+
+ @pytest.mark.parametrize(
+ "bad_name",
+ [
+ "Switch\nDev",
+ "Switch\rDev",
+ "Switch\x00Dev",
+ "S" * (MAX_DISPLAY_NAME_LENGTH + 1),
+ ],
+ )
+ async def test_unsafe_names_are_400_not_stored(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ bad_name: str,
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(session, name="switchdev", owner_id=owner.id)
+
+ with pytest.raises(HTTPException) as exc:
+ await update_agent_display_name(
+ agent.id,
+ UpdateAgentDisplayNameRequest(display_name=bad_name),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert exc.value.status_code == 400
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.display_name is None
diff --git a/core/tests/switch_core/gateway/test_agent_icon_route.py b/core/tests/switch_core/gateway/test_agent_icon_route.py
index e564043f5..673541a56 100644
--- a/core/tests/switch_core/gateway/test_agent_icon_route.py
+++ b/core/tests/switch_core/gateway/test_agent_icon_route.py
@@ -12,10 +12,10 @@ import pytest
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.db.models import Agent, ApiKey, Client, User
from switch_core.db.stores.agent_store import AgentStore
from switch_core.gateway.agents import update_agent_icon
from switch_core.gateway.schemas import UpdateAgentIconRequest
+from tests.switch_core.gateway.agent_route_harness import add_agent, add_user
_AGENT_STORE = AgentStore()
@@ -23,62 +23,13 @@ _ICON = "https://cdn.example.com/9.x/bottts/png?seed=switch-worker"
_OTHER_ICON = "https://cdn.example.com/9.x/shapes/png?seed=switch-worker"
-async def _add_user(session: AsyncSession, *, name: str, role: str = "user") -> User:
- user = User(name=name, email=f"{name}@example.com", role=role)
- session.add(user)
- await session.flush()
- return user
-
-
-async def _add_agent(
- session: AsyncSession,
- *,
- name: str,
- owner_id: str | None,
- icon_url: str | None = None,
-) -> Agent:
- client = Client(
- type="agent",
- matrix_user_id=f"@{name}:test",
- display_name=name,
- password=f"pw-{name}",
- )
- session.add(client)
- await session.flush()
-
- api_key = ApiKey(
- type="agent",
- key_hash=f"hash-{name}",
- encrypted_key=f"enc-{name}",
- label=name,
- user_id=owner_id,
- )
- session.add(api_key)
- await session.flush()
-
- agent = Agent(
- name=name,
- description=f"{name} desc",
- icon_url=icon_url,
- agent_type="session_passive",
- connector_type="external",
- integration_profile={"connection_model": "session_passive"},
- client_id=client.id,
- api_key_id=api_key.id,
- owner_id=owner_id,
- )
- session.add(agent)
- await session.flush()
- return agent
-
-
class TestUpdateAgentIcon:
async def test_owner_can_set_an_icon(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- agent = await _add_agent(session, name="a1", owner_id=owner.id)
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(session, name="a1", owner_id=owner.id)
summary = await update_agent_icon(
agent.id,
@@ -97,8 +48,8 @@ class TestUpdateAgentIcon:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- agent = await _add_agent(
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(
session, name="a1", owner_id=owner.id, icon_url=_ICON
)
@@ -118,8 +69,8 @@ class TestUpdateAgentIcon:
"""Clearing has to be expressible — the whole reason this is a separate
route rather than another optional field on the agent update."""
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- agent = await _add_agent(
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(
session, name="a1", owner_id=owner.id, icon_url=_ICON
)
@@ -140,8 +91,8 @@ class TestUpdateAgentIcon:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- agent = await _add_agent(
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(
session, name="a1", owner_id=owner.id, icon_url=_ICON
)
@@ -159,9 +110,9 @@ class TestUpdateAgentIcon:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- other = await _add_user(session, name="other")
- agent = await _add_agent(session, name="a1", owner_id=owner.id)
+ owner = await add_user(session, name="owner")
+ other = await add_user(session, name="other")
+ agent = await add_agent(session, name="a1", owner_id=owner.id)
with pytest.raises(HTTPException) as exc:
await update_agent_icon(
@@ -181,9 +132,9 @@ class TestUpdateAgentIcon:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- admin = await _add_user(session, name="admin", role="admin")
- agent = await _add_agent(session, name="a1", owner_id=owner.id)
+ owner = await add_user(session, name="owner")
+ admin = await add_user(session, name="admin", role="admin")
+ agent = await add_agent(session, name="a1", owner_id=owner.id)
summary = await update_agent_icon(
agent.id,
@@ -199,7 +150,7 @@ class TestUpdateAgentIcon:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
+ owner = await add_user(session, name="owner")
with pytest.raises(HTTPException) as exc:
await update_agent_icon(
@@ -231,8 +182,8 @@ class TestUpdateAgentIcon:
and never stored at all, since Switch itself dereferences the URL when
a bridge needs the image as bytes."""
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- agent = await _add_agent(session, name="a1", owner_id=owner.id)
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(session, name="a1", owner_id=owner.id)
with pytest.raises(HTTPException) as exc:
await update_agent_icon(
@@ -252,8 +203,8 @@ class TestUpdateAgentIcon:
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
async with session_factory() as session:
- owner = await _add_user(session, name="owner")
- agent = await _add_agent(
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(
session, name="a1", owner_id=owner.id, icon_url=_ICON
)
diff --git a/core/tests/switch_core/test_agent_display_name.py b/core/tests/switch_core/test_agent_display_name.py
new file mode 100644
index 000000000..8743403d9
--- /dev/null
+++ b/core/tests/switch_core/test_agent_display_name.py
@@ -0,0 +1,79 @@
+"""Display name validation.
+
+The acceptance cases matter as much as the rejections here: the point of a
+display name is to allow what an agent identifier cannot — capitals, spaces,
+punctuation — so a rule that quietly narrowed it would defeat the field.
+"""
+
+import pytest
+
+from switch_core.agent_display_name import (
+ MAX_DISPLAY_NAME_LENGTH,
+ InvalidDisplayName,
+ normalise_display_name,
+ validate_display_name,
+)
+
+
+ "value",
+ [
+ "Switch Dev",
+ "SWITCH",
+ "Ana's Reviewer",
+ "Switch Dev (staging)",
+ "Réviseur",
+ "研究員",
+ "Switch — Dev",
+ "S" * MAX_DISPLAY_NAME_LENGTH,
+ ],
+)
+def test_accepts_human_readable_names(value: str) -> None:
+ assert validate_display_name(value) == value
+
+
+ "value",
+ [
+ " Switch Dev ",
+ "Switch Dev\n",
+ "\tSwitch Dev",
+ ],
+)
+def test_strips_surrounding_whitespace(value: str) -> None:
+ assert validate_display_name(value) == "Switch Dev"
+
+
+ "value",
+ [
+ "",
+ " ",
+ "S" * (MAX_DISPLAY_NAME_LENGTH + 1),
+ # A display name is rendered into a message header, so a line break is
+ # a way to forge a line the platform never sent.
+ "Switch\nDev",
+ "Switch\rDev",
+ "Switch\x00Dev",
+ "Switch\x1bDev",
+ "Switch\x7fDev",
+ "Switch\x9bDev",
+ "Switch\x85Dev",
+ "Switch\u2028Dev",
+ "Switch\u2029Dev",
+ ],
+)
+def test_rejects_blank_overlong_and_control_characters(value: str) -> None:
+ with pytest.raises(InvalidDisplayName):
+ validate_display_name(value)
+
+
[email protected]("value", [None, "", " ", "\n"])
+def test_normalise_collapses_absent_and_blank_to_none(value: str | None) -> None:
+ assert normalise_display_name(value) is None
+
+
+def test_normalise_validates_anything_else() -> None:
+ assert normalise_display_name(" Switch Dev ") == "Switch Dev"
+ with pytest.raises(InvalidDisplayName):
+ normalise_display_name("Switch\nDev")