Skip to content

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

Take a deleted account's name off what it sent, and let admins erase it

Petr Bauch786e3e62ae89
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.py
index 09be7dcb1..d894a0ff4 100644
--- a/core/switch_core/accounts/deletion.py
+++ b/core/switch_core/accounts/deletion.py
@@ -7,6 +7,14 @@ stay, with no owner, for the workspace's admins to manage, and the invitations,
join domains and messaging installs they set up pass to another admin of the
workspace.
+What they said in rooms stays, as part of everyone else's conversations, but
+no longer under their name: their messages, the copies stored for agents, the
+member client that sent them and the Console chat descriptions that listed
+them all name a `FORMER_MEMBER_NAME` instead. Invitations addressed to their
+e-mail address are deleted in every workspace. A workspace admin can erase
+the messages themselves (`retention/erasure.py`); the audit log keeps the
+account's id (`docs/design/data-retention.md`).
+
Nothing is deleted until every refusal has been checked, so a refused deletion
leaves the account exactly as it was. The refusals are the cases where going
ahead would strand something nobody else could reach:
@@ -60,6 +68,7 @@ from switch_core.db.models import (
AgentControllerEnrollmentCode,
AgentControllerOperation,
AgentDefinition,
+ Client,
CloudMachine,
Document,
Invitation,
@@ -87,6 +96,7 @@ from switch_core.db.models import (
)
from switch_core.db.rls_ddl import GLOBAL_TABLES
from switch_core.db.session_scope import organization_session, tenant_session
+from switch_core.db.stores.erasure_store import FORMER_MEMBER_NAME, ErasureStore
from switch_core.db.tenant_lookup import all_tenant_ids
from switch_core.tenant_context import tenant_scope
@@ -157,7 +167,7 @@ USER_REFERENCES: dict[tuple[str, str], Handling] = {
("chat_reads", "user_id"): "database cascades",
("service_connections", "user_id"): "database cascades",
("sign_in_flows", "user_id"): "database cascades",
- ("clients", "user_id"): "database clears",
+ ("clients", "user_id"): "cleared",
("organization_app_credentials", "updated_by"): "database clears",
("organization_service_settings", "updated_by"): "database clears",
("tenant_retention_policies", "updated_by_user_id"): "database clears",
@@ -165,6 +175,9 @@ USER_REFERENCES: dict[tuple[str, str], Handling] = {
}
+#: How many of the person's messages are renamed per transaction.
+RENAME_BATCH = 1000
+
# The role recorded for a workspace the person is no longer a member of.
FORMER_MEMBER = "former member"
@@ -403,8 +416,9 @@ class AccountDeletion:
completed: list[Workspace] = []
try:
for workspace in workspaces:
- await self._leave_workspace(user_id, workspace, actor_id)
+ await self._leave_workspace(user, workspace, actor_id)
completed.append(workspace)
+ await self._delete_invitations_to(user.email)
await self._hand_over_server_settings(session, user_id)
await session.execute(
delete(OidcIdentity).where(OidcIdentity.user_id == user_id)
@@ -512,8 +526,9 @@ class AccountDeletion:
)
async def _leave_workspace(
- self, user_id: str, workspace: Workspace, actor_id: str
+ self, user: User, workspace: Workspace, actor_id: str
) -> None:
+ user_id = user.id
tenant_id = workspace.id
async with tenant_session(self.session_factory, tenant_id) as session:
agent_ids = [
@@ -549,8 +564,12 @@ class AccountDeletion:
if controller_ids:
await self._revoke_controllers(tenant_id, user_id, controller_ids)
+ member = await self._rename_messages(user_id, tenant_id)
+
async with tenant_session(self.session_factory, tenant_id) as session:
await self._still_not_the_last_admin(session, user_id, workspace)
+ if member is not None:
+ await self._retire_member(session, member, user.name)
successor = await self._successor(session, user_id)
try:
removed_services = await self.broker.remove_connections(
@@ -613,6 +632,74 @@ class AccountDeletion:
if workspace.role != FORMER_MEMBER and successor is None:
await self._close_if_empty(user_id, tenant_id, actor_id)
+ async def _rename_messages(self, user_id: str, tenant_id: str) -> Client | None:
+ """Rename what the person sent in the workspace from Switch Console,
+ in batches of their own transactions so a long history holds no long
+ lock. Returns their member client, or None if they never used one."""
+ erasures = ErasureStore()
+ async with tenant_session(self.session_factory, tenant_id) as session:
+ member = await erasures.member_client_of(session, user_id)
+ if member is None:
+ return None
+ while True:
+ async with (
+ tenant_session(self.session_factory, tenant_id) as session,
+ session.begin(),
+ ):
+ renamed = await erasures.rename_sent_by(
+ session,
+ transport_user_id=member.transport_user_id,
+ name=FORMER_MEMBER_NAME,
+ limit=RENAME_BATCH,
+ )
+ if renamed < RENAME_BATCH:
+ return member
+
+ async def _retire_member(
+ self, session: AsyncSession, member: Client, user_name: str
+ ) -> None:
+ """In the transaction that takes the person out of the workspace:
+ rename anything sent since the batches, the agents' copies and the
+ Console chat descriptions, then the member client itself, which
+ unlinks it from the account."""
+ erasures = ErasureStore()
+ while (
+ await erasures.rename_sent_by(
+ session,
+ transport_user_id=member.transport_user_id,
+ name=FORMER_MEMBER_NAME,
+ limit=RENAME_BATCH,
+ )
+ == RENAME_BATCH
+ ):
+ pass
+ await erasures.rename_agent_copies(
+ session, transport_user_id=member.transport_user_id, name=FORMER_MEMBER_NAME
+ )
+ await erasures.rename_in_console_chats(
+ session,
+ client_id=member.id,
+ old_names={user_name, member.display_name},
+ name=FORMER_MEMBER_NAME,
+ )
+ await erasures.retire_member_client(session, member.id, FORMER_MEMBER_NAME)
+
+ async def _delete_invitations_to(self, email: str) -> None:
+ """Delete every invitation addressed to `email`, in every workspace,
+ live or not: they would otherwise keep the address of someone who
+ has left Switch."""
+ for tenant_id in sorted(await all_tenant_ids(self.session_factory)):
+ async with (
+ tenant_session(self.session_factory, tenant_id) as session,
+ session.begin(),
+ ):
+ await session.execute(
+ delete(Invitation).where(
+ Invitation.tenant_id == tenant_id,
+ func.lower(Invitation.email) == email.lower(),
+ )
+ )
+
async def _close_if_empty(
self, user_id: str, tenant_id: str, actor_id: str
) -> None:
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 153a7f1fe..e6de67b75 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -4115,10 +4115,12 @@ class PersonErasure(TenantScoped, Base):
`external_user_ids` names the platform identities to erase: one row of
`external_users` per platform the person was seen on. `former_sender_ids`
names people from a chat app that has since been disconnected, by the
- transport id their messages still carry. Erasing them deletes
- every message they sent, the files those carried, their identity records
- and the client standing in for each, and their name on approval answers
- (`retention/erasure.py`). Queued here and worked by a background loop, so
+ transport id their messages still carry. `member_client_ids` names the
+ member clients through which people took part from Switch Console, a
+ current member or a deleted account's. Erasing any of them deletes every
+ message they sent, the files those carried, and their name on approval
+ answers; a platform identity's records and client go too, while a member
+ client stays, since its account may still be in use (`retention/erasure.py`). Queued here and worked by a background loop, so
a person with years of history cannot time out the request that asked.
Nothing here names the person once they are erased: the ids are internal
@@ -4141,6 +4143,10 @@ class PersonErasure(TenantScoped, Base):
former_sender_ids: Mapped[list] = mapped_column(
JSONB, nullable=False, server_default=text("'[]'::jsonb")
)
+ # Member clients: people in rooms through Switch Console, by client id.
+ member_client_ids: Mapped[list] = mapped_column(
+ JSONB, nullable=False, server_default=text("'[]'::jsonb")
+ )
state: Mapped[str] = mapped_column(Text, nullable=False, default="queued")
requested_by_user_id: Mapped[str | None] = mapped_column(
Text, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
diff --git a/core/switch_core/db/stores/erasure_store.py b/core/switch_core/db/stores/erasure_store.py
index c0bba8907..1d21c28ba 100644
--- a/core/switch_core/db/stores/erasure_store.py
+++ b/core/switch_core/db/stores/erasure_store.py
@@ -3,8 +3,13 @@ that are not messages, for the bound tenant.
A person in a room is a chat-platform identity: an `external_users` row on
one bridge, standing behind a `clients` row that is the room participant.
-One person seen on two platforms is two identities. Message deletion itself
-is `MessageStore.delete_sent_by`, which keeps the room's numbering intact.
+One person seen on two platforms is two identities. Someone who takes part
+from Switch Console does so through a member client instead, one per account
+per workspace. Message deletion itself is `MessageStore.delete_sent_by`,
+which keeps the room's numbering intact.
+
+Also the renaming a deleted account's messages get (`FORMER_MEMBER_NAME`,
+used by `accounts/deletion.py`).
"""
from __future__ import annotations
@@ -31,6 +36,7 @@ from sqlalchemy import cast as cast_
from sqlalchemy.dialects.postgresql import array
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.chats import MEMBER_CLIENT_TYPE
from switch_core.db.models import (
AgentEventRow,
ApprovalRequest,
@@ -51,6 +57,13 @@ from switch_core.db.stores.retention_store import UNREFERENCED_BLOB
ERASED_ANSWERER = "erased"
#: What stands in for an erased person's name in a direct room's name.
ERASED_NAME = "erased person"
+#: The name a deleted account's messages, and the member client that sent
+#: them, carry from then on.
+FORMER_MEMBER_NAME = "Former member"
+#: How Switch Console describes a chat it creates (`ChatService`): this,
+#: then the agents and people in it, joined by `CONSOLE_CHAT_SEPARATOR`.
+CONSOLE_CHAT_PREFIX = "Switch Console chat with "
+CONSOLE_CHAT_SEPARATOR = ", "
ACTIVE_STATES = ("queued", "running")
#: A `running` request whose progress has not moved for this long is taken to
@@ -114,6 +127,19 @@ class FormerParticipant:
message_count: int
+@dataclass(frozen=True)
+class Member:
+ """Someone who took part in rooms from Switch Console, through their
+ member client. `user_id` is None once their account has been deleted,
+ and `name` is then `FORMER_MEMBER_NAME`."""
+
+ client_id: str
+ transport_user_id: str
+ name: str
+ user_id: str | None
+ message_count: int
+
+
def _rowcount(result: Result[Any]) -> int:
return cast("CursorResult[Any]", result).rowcount
@@ -259,12 +285,61 @@ class ErasureStore:
)
return former
+ async def list_members(self, session: AsyncSession) -> list[Member]:
+ """Every member client in the bound tenant."""
+ return await self._members(session, None)
+
+ async def members_with_ids(
+ self, session: AsyncSession, client_ids: Collection[str]
+ ) -> list[Member]:
+ """The named member clients that are in the bound tenant."""
+ return await self._members(session, list(client_ids))
+
+ async def _members(
+ self, session: AsyncSession, client_ids: list[str] | None
+ ) -> list[Member]:
+ tenant_id = require_tenant_id()
+ message_count = (
+ select(func.count())
+ .select_from(Message)
+ .where(
+ Message.tenant_id == tenant_id,
+ Message.sender_id == Client.transport_user_id,
+ )
+ .correlate(Client)
+ .scalar_subquery()
+ )
+ query = (
+ select(
+ Client.id,
+ Client.transport_user_id,
+ Client.display_name,
+ Client.user_id,
+ message_count,
+ )
+ .where(Client.tenant_id == tenant_id, Client.type == MEMBER_CLIENT_TYPE)
+ .order_by(func.lower(Client.display_name), Client.id)
+ )
+ if client_ids is not None:
+ query = query.where(Client.id.in_(client_ids))
+ return [
+ Member(
+ client_id=row[0],
+ transport_user_id=row[1],
+ name=row[2],
+ user_id=row[3],
+ message_count=int(row[4]),
+ )
+ for row in (await session.execute(query)).all()
+ ]
+
async def queue(
self,
session: AsyncSession,
*,
external_user_ids: list[str],
former_sender_ids: list[str],
+ member_client_ids: list[str],
requested_by_user_id: str,
) -> PersonErasure:
"""Queue the erasure of these identities, or raise.
@@ -292,13 +367,21 @@ class ErasureStore:
f.sender_id
for f in await self.former_with_ids(session, former_sender_ids)
}
- unknown = (set(external_user_ids) | set(former_sender_ids)) - known
+ if member_client_ids:
+ known |= {
+ m.client_id
+ for m in await self.members_with_ids(session, member_client_ids)
+ }
+ unknown = (
+ set(external_user_ids) | set(former_sender_ids) | set(member_client_ids)
+ ) - known
if unknown:
raise UnknownIdentity(", ".join(sorted(unknown)))
overlaps = []
for column, ids in (
(PersonErasure.external_user_ids, external_user_ids),
(PersonErasure.former_sender_ids, former_sender_ids),
+ (PersonErasure.member_client_ids, member_client_ids),
):
if ids:
overlaps.append(column.op("?|")(cast_(array(ids), ARRAY(Text))))
@@ -316,6 +399,7 @@ class ErasureStore:
erasure = PersonErasure(
external_user_ids=list(external_user_ids),
former_sender_ids=list(former_sender_ids),
+ member_client_ids=list(member_client_ids),
state="queued",
requested_by_user_id=requested_by_user_id,
)
@@ -537,3 +621,143 @@ class ErasureStore:
{"t": require_tenant_id(), "uris": list(uris)},
)
return _rowcount(result)
+
+ async def member_client_of(
+ self, session: AsyncSession, user_id: str
+ ) -> Client | None:
+ """The member client through which `user_id` takes part in the bound
+ tenant's rooms from Switch Console, if they ever have."""
+ return (
+ await session.execute(
+ select(Client).where(
+ Client.tenant_id == require_tenant_id(),
+ Client.user_id == user_id,
+ Client.type == MEMBER_CLIENT_TYPE,
+ )
+ )
+ ).scalar_one_or_none()
+
+ async def rename_sent_by(
+ self, session: AsyncSession, *, transport_user_id: str, name: str, limit: int
+ ) -> int:
+ """Give up to `limit` of this sender's messages `name` as their sender's
+ name, in the column and in the stored event (`sender_name`, and the
+ `user_name` a command carries), and return how many changed.
+
+ Rows already named so are skipped, so repeating this until it returns
+ less than `limit` renames every one. Only the sender's own rows
+ change: someone else quoting or mentioning them keeps their words.
+ """
+ result = await session.execute(
+ text(
+ """
+ UPDATE messages m SET
+ sender_name = :name,
+ content = CASE WHEN m.content ? 'user_name'
+ THEN jsonb_set(named.content, '{user_name}', to_jsonb(CAST(:name AS text)))
+ ELSE named.content END
+ FROM (
+ SELECT id, CASE WHEN content ? 'sender_name'
+ THEN jsonb_set(content, '{sender_name}', to_jsonb(CAST(:name AS text)))
+ ELSE content END AS content
+ FROM messages
+ WHERE tenant_id = :t AND sender_id = :sender
+ AND (sender_name IS DISTINCT FROM :name
+ OR (content ? 'sender_name' AND content->>'sender_name' IS DISTINCT FROM :name)
+ OR (content ? 'user_name' AND content->>'user_name' IS DISTINCT FROM :name))
+ ORDER BY id
+ LIMIT :limit
+ ) named
+ WHERE m.id = named.id
+ """
+ ),
+ {
+ "t": require_tenant_id(),
+ "sender": transport_user_id,
+ "name": name,
+ "limit": limit,
+ },
+ )
+ return _rowcount(result)
+
+ async def rename_agent_copies(
+ self, session: AsyncSession, *, transport_user_id: str, name: str
+ ) -> int:
+ """Give this participant `name` in the copies of events stored for
+ agents (`agent_events`): as the sender of a message, the issuer of a
+ command, or the member who joined."""
+ result = await session.execute(
+ text(
+ """
+ UPDATE agent_events SET payload = CASE
+ WHEN payload->'payload'->>'sender' = :who
+ AND payload->'payload' ? 'sender_name'
+ THEN jsonb_set(payload, '{payload,sender_name}', to_jsonb(CAST(:name AS text)))
+ WHEN payload->'payload'->>'user_id' = :who
+ AND payload->'payload' ? 'user_name'
+ THEN jsonb_set(payload, '{payload,user_name}', to_jsonb(CAST(:name AS text)))
+ WHEN payload->'payload'->>'member' = :who
+ AND payload->'payload' ? 'member_name'
+ THEN jsonb_set(payload, '{payload,member_name}', to_jsonb(CAST(:name AS text)))
+ ELSE payload END
+ WHERE tenant_id = :t
+ AND (payload->'payload'->>'sender' = :who
+ OR payload->'payload'->>'user_id' = :who
+ OR payload->'payload'->>'member' = :who)
+ """
+ ),
+ {"t": require_tenant_id(), "who": transport_user_id, "name": name},
+ )
+ return _rowcount(result)
+
+ async def rename_in_console_chats(
+ self,
+ session: AsyncSession,
+ *,
+ client_id: str,
+ old_names: Collection[str],
+ name: str,
+ ) -> int:
+ """Replace `old_names` with `name` in the descriptions Switch Console
+ gave the chats this client is in, which list who was in each. Must
+ run while the client's room memberships still stand. A name is
+ replaced only as a whole entry of that list, never inside another
+ name or anything a person wrote."""
+ member_of = select(ClientRoom.room_id).where(
+ ClientRoom.tenant_id == require_tenant_id(),
+ ClientRoom.client_id == client_id,
+ )
+ rooms = (
+ await session.execute(
+ select(Room).where(
+ Room.tenant_id == require_tenant_id(),
+ Room.id.in_(member_of),
+ Room.description.startswith(CONSOLE_CHAT_PREFIX, autoescape=True),
+ )
+ )
+ ).scalars()
+ replaced = set(old_names)
+ renamed = 0
+ for room in rooms:
+ entries = room.description.removeprefix(CONSOLE_CHAT_PREFIX).split(
+ CONSOLE_CHAT_SEPARATOR
+ )
+ updated = [name if entry in replaced else entry for entry in entries]
+ if updated != entries:
+ room.description = CONSOLE_CHAT_PREFIX + CONSOLE_CHAT_SEPARATOR.join(
+ updated
+ )
+ renamed += 1
+ await session.flush()
+ return renamed
+
+ async def retire_member_client(
+ self, session: AsyncSession, client_id: str, name: str
+ ) -> None:
+ """Rename a deleted account's member client to `name` and unlink it
+ from the account. The client stays, as the sender its messages name."""
+ await session.execute(
+ update(Client)
+ .where(Client.tenant_id == require_tenant_id(), Client.id == client_id)
+ .values(display_name=name, user_id=None)
+ )
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 44559471c..a9c41a128 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -2057,16 +2057,19 @@ class ClaimantDetail(BaseModel):
class PersonDetail(BaseModel):
- """Someone seen in the workspace's rooms through a chat app.
-
- `kind` is `identity` for a person on a connected app, where `id` is their
- platform identity, or `former` for a person on an app since disconnected,
- where `id` is the transport id their messages carry and `bridge_name` is
- null. Erase by passing `id` in the matching list of the request.
+ """Someone seen in the workspace's rooms.
+
+ `kind` is `identity` for a person on a connected chat app, where `id` is
+ their platform identity; `former` for a person on an app since
+ disconnected, where `id` is the transport id their messages carry and
+ `bridge_name` is null; or `member` for a person taking part from Switch
+ Console, where `id` is their member client, `platform` is `switch` and
+ `bridge_name` is null (a deleted account's shows as "Former member").
+ Erase by passing `id` in the matching list of the request.
"""
id: str
- kind: Literal["identity", "former"]
+ kind: Literal["identity", "former", "member"]
username: str
platform: str
bridge_name: str | None
@@ -2077,10 +2080,15 @@ class PersonDetail(BaseModel):
class ErasureCreateRequest(BaseModel):
external_user_ids: list[str] = Field(default_factory=list, max_length=50)
former_sender_ids: list[str] = Field(default_factory=list, max_length=50)
+ member_client_ids: list[str] = Field(default_factory=list, max_length=50)
@model_validator(mode="after")
def _names_someone(self) -> ErasureCreateRequest:
- if not self.external_user_ids and not self.former_sender_ids:
+ if (
+ not self.external_user_ids
+ and not self.former_sender_ids
+ and not self.member_client_ids
+ ):
raise ValueError("name at least one person to erase")
return self
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 9f84ce84c..200a0cc31 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -913,11 +913,17 @@ async def clear_retention_policy(
return _retention_response(None, None, None)
+#: The `platform` a person taking part from Switch Console is listed under.
+SWITCH_CONSOLE_PLATFORM = "switch"
+
+
def _erasure_detail(erasure: PersonErasure) -> ErasureDetail:
return ErasureDetail(
id=erasure.id,
state=erasure.state, # type: ignore[arg-type]
- identities=len(erasure.external_user_ids) + len(erasure.former_sender_ids),
+ identities=len(erasure.external_user_ids)
+ + len(erasure.former_sender_ids)
+ + len(erasure.member_client_ids),
identities_erased=erasure.identities_erased,
messages_deleted=erasure.messages_deleted,
files_deleted=erasure.files_deleted,
@@ -948,10 +954,11 @@ async def list_people(
user: Annotated[User, Depends(require_tenant_admin)],
user_store: Annotated[UserStore, Depends(get_user_store)],
) -> list[PersonDetail]:
- """Everyone seen in the bound tenant's rooms through a chat app, with how
+ """Everyone seen in the bound tenant's rooms: through a chat app, with how
many messages each sent and which members claim them, including former
- participants from apps since disconnected. Admins only, by their own admin
- membership: this is the list a person is erased from."""
+ participants from apps since disconnected, and from Switch Console,
+ including deleted accounts. Admins only, by their own admin membership:
+ this is the list a person is erased from."""
_require_bound_tenant(tenant_id)
await _require_admin_membership(session, user_store, tenant_id, user)
people = [
@@ -981,6 +988,18 @@ async def list_people(
)
for former in await erasure_store.list_former_participants(session)
]
+ people += [
+ PersonDetail(
+ id=member.client_id,
+ kind="member",
+ username=member.name,
+ platform=SWITCH_CONSOLE_PLATFORM,
+ bridge_name=None,
+ message_count=member.message_count,
+ claimed_by=[],
+ )
+ for member in await erasure_store.list_members(session)
+ ]
return sorted(people, key=lambda p: (p.username.lower(), p.id))
@@ -1011,8 +1030,8 @@ async def create_erasure(
user_store: Annotated[UserStore, Depends(get_user_store)],
) -> ErasureDetail:
"""Queue the erasure of one person: every message the named identities
- sent, their files, and the identities themselves. Admins only, by their
- own admin membership.
+ and member clients sent, their files, and the platform identities
+ themselves. Admins only, by their own admin membership.
Answered once queued; the work runs in the background within seconds and
`GET .../erasures` reports its progress. 404 names an identity that is not
@@ -1022,11 +1041,13 @@ async def create_erasure(
await _require_admin_membership(session, user_store, tenant_id, user)
ids = list(dict.fromkeys(body.external_user_ids))
former_ids = list(dict.fromkeys(body.former_sender_ids))
+ member_ids = list(dict.fromkeys(body.member_client_ids))
try:
erasure = await erasure_store.queue(
session,
external_user_ids=ids,
former_sender_ids=former_ids,
+ member_client_ids=member_ids,
requested_by_user_id=user.id,
)
except UnknownIdentity as exc:
@@ -1044,7 +1065,11 @@ async def create_erasure(
action=AuditAction.PERSON_ERASURE_REQUESTED,
target_type="person_erasure",
target_id=erasure.id,
- details={"external_user_ids": ids, "former_participants": len(former_ids)},
+ details={
+ "external_user_ids": ids,
+ "former_participants": len(former_ids),
+ "member_client_ids": member_ids,
+ },
)
await session.commit()
return _erasure_detail(erasure)
diff --git a/core/switch_core/migrations/versions/e5c1b7a93d28_person_erasures.py b/core/switch_core/migrations/versions/e5c1b7a93d28_person_erasures.py
index 112b0fec5..e4eac166b 100644
--- a/core/switch_core/migrations/versions/e5c1b7a93d28_person_erasures.py
+++ b/core/switch_core/migrations/versions/e5c1b7a93d28_person_erasures.py
@@ -64,6 +64,12 @@ def upgrade() -> None:
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
+ sa.Column(
+ "member_client_ids",
+ postgresql.JSONB(astext_type=sa.Text()),
+ server_default=sa.text("'[]'::jsonb"),
+ nullable=False,
+ ),
sa.Column("state", sa.Text(), nullable=False),
sa.Column("requested_by_user_id", sa.Text(), nullable=True),
sa.Column(
diff --git a/core/switch_core/retention/erasure.py b/core/switch_core/retention/erasure.py
index 4917b8cb0..d3e57ea18 100644
--- a/core/switch_core/retention/erasure.py
+++ b/core/switch_core/retention/erasure.py
@@ -4,7 +4,11 @@ A workspace admin queues a request naming one or more platform identities
(`ErasureStore.queue`), and any former participants: people from a chat app
since disconnected, whose identity rows went with it. For those only their
messages, files, approval answers and direct-room names are left to erase
-(`_erase_former`). `erasure_loop` works the queue: for each identity it
+(`_erase_former`). A request can also name member clients, through which
+people take part from Switch Console: what such a client sent is erased the
+same way, and the client stays, because its account may still be in use, or
+is a deleted account's, already renamed (`_erase_member`). `erasure_loop`
+works the queue: for each identity it
1. deletes every message the identity sent, in every room, archived ones
included, in batches with their attachments, bridge post mappings and the
@@ -40,6 +44,7 @@ from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.erasure_store import (
ErasureStore,
FormerParticipant,
+ Member,
Person,
)
from switch_core.db.stores.message_store import MessageStore
@@ -109,6 +114,13 @@ class ErasureService:
)
for participant in former:
await self._erase_former(tenant_id, erasure.id, participant)
+ if erasure.member_client_ids:
+ async with tenant_session(self._sessions, tenant_id) as db:
+ members = await self._erasures.members_with_ids(
+ db, erasure.member_client_ids
+ )
+ for member in members:
+ await self._erase_member(tenant_id, erasure.id, member)
except Exception as exc:
logger.exception("Erasure %s in tenant %s failed", erasure.id, tenant_id)
error = f"{type(exc).__name__}: {exc}"
@@ -240,6 +252,41 @@ class ErasureService:
exc_info=True,
)
+ async def _erase_member(
+ self, tenant_id: str, erasure_id: str, member: Member
+ ) -> None:
+ """Erase what a member client sent: its messages, their files, and its
+ answers to approvals. The client and its room memberships stay; a
+ person whose account is still in use can go on writing."""
+ uris: set[str] = set()
+ room_ids: set[str] = set()
+ while True:
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ count = await self._delete_batch(
+ db, erasure_id, member.transport_user_id, uris, room_ids
+ )
+ if count < MESSAGE_BATCH:
+ break
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ await self._erasures.scrub_approval_answers(db, member.transport_user_id)
+ await self._erasures.add_progress(
+ db, erasure_id, messages=0, files=0, identities=1
+ )
+ try:
+ async with tenant_session(self._sessions, tenant_id) as db, db.begin():
+ files = await self._erasures.delete_unreferenced_media(db, uris)
+ await self._erasures.add_progress(
+ db, erasure_id, messages=0, files=files, identities=0
+ )
+ except Exception:
+ logger.warning(
+ "Erasure %s: could not delete the files of member client %s; the "
+ "hourly sweep deletes them a day later",
+ erasure_id,
+ member.client_id,
+ exc_info=True,
+ )
+
async def _delete_batch(
self,
db: AsyncSession,
diff --git a/core/tests/switch_core/accounts/test_account_deletion.py b/core/tests/switch_core/accounts/test_account_deletion.py
index 35baeef09..23e2a6fc1 100644
--- a/core/tests/switch_core/accounts/test_account_deletion.py
+++ b/core/tests/switch_core/accounts/test_account_deletion.py
@@ -28,11 +28,14 @@ from switch_core.bridges.resource.service import ResourceService
from switch_core.db.models import (
TENANT_ZERO_ID,
Agent,
+ AgentEventRow,
ApiKey,
AuditEvent,
Client,
+ ClientRoom,
CloudMachine,
Invitation,
+ Message,
MessagingInstall,
OidcIdentity,
Organization,
@@ -51,6 +54,7 @@ from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.document_store import DocumentStore
+from switch_core.db.stores.message_store import MessageStore
from switch_core.db.stores.organization_store import OrganizationStore
from switch_core.db.stores.package_store import PackageStore
from switch_core.db.stores.reference_store import ReferenceStore
@@ -905,3 +909,219 @@ async def test_the_successor_is_the_longest_standing_admin_then_the_lowest_id(
async with tenant_session(session_factory, TENANT_ZERO_ID) as session:
assert await deletion._successor(session, leaving_id) == expected
+
+
+async def test_a_deleted_accounts_messages_stay_under_former_member(
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Their name leaves everything they sent from Switch Console, the agents'
+ copies, the member client and the Console chat descriptions; what anyone
+ else wrote, mentions and quotes of them included, is untouched."""
+ monkeypatch.setattr(deletion_module, "RENAME_BATCH", 2)
+ deletion, _, _ = _deletion(session_factory)
+ async with session_factory() as session:
+ admin = await _user(session, "admin")
+ leaving = await _user(session, "leaving")
+ await _member(session, TENANT_ZERO_ID, admin, "admin")
+ await _member(session, TENANT_ZERO_ID, leaving, "member")
+ agent = await _agent(session, TENANT_ZERO_ID, admin, "helper")
+ theirs = Client(
+ transport_user_id=f"@switch-member-{leaving.id}:test",
+ display_name="leaving",
+ type="member",
+ user_id=leaving.id,
+ )
+ admins = Client(
+ transport_user_id=f"@switch-member-{admin.id}:test",
+ display_name="admin",
+ type="member",
+ user_id=admin.id,
+ )
+ chat = Room(
+ transport_room_id=f"!{uuid.uuid4().hex}:test",
+ name="Chat",
+ description="Switch Console chat with helper, leaving, admin",
+ )
+ other_chat = Room(
+ transport_room_id=f"!{uuid.uuid4().hex}:test",
+ name="Other",
+ description="Switch Console chat with helper, leaving",
+ )
+ session.add_all([theirs, admins, chat, other_chat])
+ await session.flush()
+ session.add(ClientRoom(client_id=theirs.id, room_id=chat.id))
+ store = MessageStore()
+
+ async def say(sender: Client, event_id: str, content: dict[str, Any]) -> None:
+ await store.create(
+ session,
+ Message(
+ room_id=chat.id,
+ transport_event_id=event_id,
+ sender_id=sender.transport_user_id,
+ sender_client_id=sender.id,
+ sender_name=sender.display_name,
+ event_type="m.room.message",
+ content=content,
+ ),
+ [],
+ )
+
+ for i in range(3):
+ await say(theirs, f"$mine-{i}", {"body": "hi", "sender_name": "leaving"})
+ await say(
+ theirs,
+ "$command",
+ {
+ "command": "stop",
+ "user_id": theirs.transport_user_id,
+ "user_name": "leaving",
+ },
+ )
+ await say(theirs, "$custom", {"com.switch.marker": True})
+ await say(
+ admins,
+ "$admin",
+ {"body": "as leaving said", "sender_name": "admin", "quote": "leaving"},
+ )
+ session.add(
+ AgentEventRow(
+ agent_id=agent.id,
+ seq=1,
+ room_id=chat.id,
+ room_seq=1,
+ message_key="$mine-0",
+ type="message",
+ payload={
+ "type": "message",
+ "payload": {
+ "sender": theirs.transport_user_id,
+ "sender_name": "leaving",
+ "body": "hi",
+ },
+ },
+ notifiable=True,
+ )
+ )
+ await session.commit()
+ ids = {
+ "leaving": leaving.id,
+ "theirs": theirs.id,
+ "chat": chat.id,
+ "other_chat": other_chat.id,
+ }
+
+ async with session_factory() as session:
+ user = await session.get(User, ids["leaving"])
+ assert user is not None
+ workspaces = await deletion.with_former_workspaces(
+ user.id, [Workspace(id=TENANT_ZERO_ID, name="Zero", role="member")]
+ )
+ await deletion.delete(session, user, workspaces, actor_id=user.id)
+
+ async with session_factory() as session:
+ rows = {
+ m.transport_event_id: (m.sender_name, m.content)
+ for m in (await session.execute(select(Message))).scalars()
+ }
+ client = await session.get(Client, ids["theirs"])
+ chat_after = await session.get(Room, ids["chat"])
+ other_after = await session.get(Room, ids["other_chat"])
+ copy = (await session.execute(select(AgentEventRow))).scalar_one()
+ for i in range(3):
+ assert rows[f"$mine-{i}"] == (
+ "Former member",
+ {"body": "hi", "sender_name": "Former member"},
+ )
+ assert rows["$command"][1]["user_name"] == "Former member"
+ assert rows["$custom"] == ("Former member", {"com.switch.marker": True})
+ assert rows["$admin"] == (
+ "admin",
+ {"body": "as leaving said", "sender_name": "admin", "quote": "leaving"},
+ )
+ assert client is not None
+ assert (client.display_name, client.user_id) == ("Former member", None)
+ assert chat_after is not None and other_after is not None
+ assert (
+ chat_after.description
+ == "Switch Console chat with helper, Former member, admin"
+ )
+ assert other_after.description == "Switch Console chat with helper, leaving"
+ assert copy.payload["payload"]["sender_name"] == "Former member"
+
+
+async def test_invitations_addressed_to_a_deleted_account_go_everywhere(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ """Live, expired or revoked, in a workspace they were in or one that only
+ invited them; an invitation to anyone else stays."""
+ deletion, _, _ = _deletion(session_factory)
+ elsewhere = f"elsewhere-{uuid.uuid4().hex[:6]}"
+ async with session_factory() as session:
+ session.add(Tenant(id=elsewhere, slug=elsewhere, name="Elsewhere"))
+ await session.flush()
+ admin = await _user(session, "admin")
+ leaving = await _user(session, "leaving")
+ await _member(session, TENANT_ZERO_ID, admin, "admin")
+ await _member(session, TENANT_ZERO_ID, leaving, "member")
+ await session.commit()
+ ids = {"admin": admin.id, "leaving": leaving.id}
+
+ def invitation(tenant_id: str, email: str, **kwargs: Any) -> Invitation:
+ return Invitation(
+ tenant_id=tenant_id,
+ role="member",
+ email=email,
+ token_hash=uuid.uuid4().hex,
+ expires_at=kwargs.get("expires_at", datetime.now(UTC) + timedelta(days=7)),
+ revoked_at=kwargs.get("revoked_at"),
+ uses_remaining=1,
+ created_by=ids["admin"],
+ )
+
+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:
+ session.add_all(
+ [
+ invitation(TENANT_ZERO_ID, "[email protected]"),
+ invitation(TENANT_ZERO_ID, "[email protected]"),
+ ]
+ )
+ await session.commit()
+ async with tenant_session(session_factory, elsewhere) as session:
+ await _member(session, elsewhere, admin, "admin")
+ session.add_all(
+ [
+ invitation(
+ elsewhere,
+ expires_at=datetime.now(UTC) - timedelta(days=1),
+ ),
+ invitation(
+ elsewhere, "[email protected]", revoked_at=datetime.now(UTC)
+ ),
+ ]
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ user = await session.get(User, ids["leaving"])
+ assert user is not None
+ workspaces = await deletion.with_former_workspaces(
+ user.id, [Workspace(id=TENANT_ZERO_ID, name="Zero", role="member")]
+ )
+ await deletion.delete(session, user, workspaces, actor_id=user.id)
+
+ left: list[str | None] = []
+ for tenant_id in (TENANT_ZERO_ID, elsewhere):
+ async with tenant_session(session_factory, tenant_id) as session:
+ left += list(
+ (
+ await session.execute(
+ select(Invitation.email).where(
+ Invitation.tenant_id == tenant_id
+ )
+ )
+ ).scalars()
+ )
+ assert left == ["[email protected]"]
diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.py
index a28036324..dfe13a3d8 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -2926,7 +2926,11 @@ class TestErasureRoutes:
assert actions == [
(
"person_erasure.requested",
- {"external_user_ids": [person_id], "former_participants": 0},
+ {
+ "external_user_ids": [person_id],
+ "former_participants": 0,
+ "member_client_ids": [],
+ },
)
]
@@ -2976,6 +2980,35 @@ class TestErasureRoutes:
assert queued.status_code == 202
assert queued.json()["identities"] == 1
+ async def test_a_switch_console_member_is_listed_and_erased(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ token = await self._member(session_factory, "erase-console", "admin")
+ async with tenant_session(session_factory, TENANT_A) as session:
+ member = Client(
+ transport_user_id=f"@switch-member-{uuid.uuid4()}:test",
+ display_name="Former member",
+ type="member",
+ )
+ session.add(member)
+ await session.commit()
+ member_id = member.id
+
+ async with _client(_app(session_factory), token) as client:
+ people = await client.get(f"/tenants/{TENANT_A}/people")
+ queued = await client.post(
+ f"/tenants/{TENANT_A}/erasures",
+ json={"member_client_ids": [member_id]},
+ )
+
+ assert [
+ (p["id"], p["kind"], p["username"], p["platform"], p["message_count"])
+ for p in people.json()
+ ] == [(member_id, "member", "Former member", "switch", 0)]
+ assert queued.status_code == 202
+ assert queued.json()["identities"] == 1
+
async def test_a_member_or_an_operator_without_admin_membership_cannot_erase(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/retention/test_erasure.py b/core/tests/switch_core/retention/test_erasure.py
index 0f965b11e..ccf03d252 100644
--- a/core/tests/switch_core/retention/test_erasure.py
+++ b/core/tests/switch_core/retention/test_erasure.py
@@ -193,6 +193,7 @@ async def _queue(
session_factory: async_sessionmaker[AsyncSession],
external_user_ids: list[str],
former_sender_ids: list[str] | None = None,
+ member_client_ids: list[str] | None = None,
) -> str:
async with session_factory() as session:
owner = User(
@@ -206,6 +207,7 @@ async def _queue(
session,
external_user_ids=external_user_ids,
former_sender_ids=former_sender_ids or [],
+ member_client_ids=member_client_ids or [],
requested_by_user_id=owner.id,
)
await session.commit()
@@ -704,3 +706,108 @@ class TestFormerParticipants:
with pytest.raises(UnknownIdentity):
await _queue(session_factory, [], [live_sender])
+
+
+async def _member_client(session: AsyncSession, name: str, *, linked: bool) -> Client:
+ """A Switch Console member client, as `ChatService.member_actor` makes it;
+ unlinked, as a deleted account's is left."""
+ user = User(
+ name=name, email=f"{name}-{uuid.uuid4().hex[:6]}@example.invalid", role="user"
+ )
+ session.add(user)
+ await session.flush()
+ client = Client(
+ transport_user_id=f"@switch-member-{user.id}:test",
+ display_name=name if linked else "Former member",
+ type="member",
+ user_id=user.id if linked else None,
+ )
+ session.add(client)
+ await session.flush()
+ return client
+
+
+class TestMembers:
+ async def test_what_a_member_sent_goes_and_their_client_stays(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ cleo = await _member_client(session, "cleo", linked=True)
+ ana = await _person(session, await _bridge(session), "ana")
+ ana_client = await _client_of(session, ana)
+ agent = await _agent(session)
+ room = await _room(session, "r", archived=True)
+ await _blob(session, "mxc://test/cleo-only")
+ await _blob(session, "mxc://test/shared")
+ await _say(session, room, cleo, "$c1", "mxc://test/cleo-only")
+ await _say(session, room, cleo, "$c2", "mxc://test/shared")
+ await _say(session, room, ana_client, "$a1", "mxc://test/shared")
+ session.add(
+ ApprovalRequest(
+ agent_id=agent.id,
+ session_id="s",
+ request_id="q",
+ turn_id="t",
+ kind="questions",
+ title="t",
+ options=[],
+ questions=[],
+ state="answered",
+ answered_by=cleo.transport_user_id,
+ answers=[{"question_id": "q1", "custom_text": "private"}],
+ )
+ )
+ await session.commit()
+ cleo_id = cleo.id
+ await _queue(session_factory, [], [], [cleo_id])
+
+ finished = await ErasureService(
+ session_factory, _Clients(), _Bridges()
+ ).work_once(datetime.now(UTC))
+
+ assert finished is not None
+ assert (finished.state, finished.error) == ("done", None)
+ assert (
+ finished.messages_deleted,
+ finished.files_deleted,
+ finished.identities_erased,
+ ) == (2, 1, 1)
+ async with session_factory() as session:
+ left = (await session.execute(select(Message.transport_event_id))).scalars()
+ blobs = (await session.execute(select(MediaBlob.uri))).scalars()
+ approval = (await session.execute(select(ApprovalRequest))).scalar_one()
+ client_after = await session.get(Client, cleo_id)
+ assert list(left) == ["$a1"]
+ assert list(blobs) == ["mxc://test/shared"]
+ assert approval.answered_by == ERASED_ANSWERER
+ assert approval.answers == [{"question_id": "q1"}]
+ assert client_after is not None and client_after.user_id is not None
+
+ async def test_members_are_listed_with_message_counts_deleted_accounts_too(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ cleo = await _member_client(session, "cleo", linked=True)
+ gone = await _member_client(session, "gone", linked=False)
+ room = await _room(session, "r")
+ await _say(session, room, gone, "$g1")
+ await _say(session, room, gone, "$g2")
+ await session.commit()
+ members = await ErasureStore().list_members(session)
+ assert [
+ (m.client_id, m.name, m.user_id is None, m.message_count) for m in members
+ ] == [
+ (cleo.id, "cleo", False, 0),
+ (gone.id, "Former member", True, 2),
+ ]
+
+ async def test_a_client_that_is_not_a_member_client_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ ana = await _person(session, await _bridge(session), "ana")
+ await session.commit()
+ ana_client_id = ana.client_id
+
+ with pytest.raises(UnknownIdentity):
+ await _queue(session_factory, [], [], [ana_client_id])
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 88fe66289..42262fb7f 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1535,10 +1535,12 @@ export interface PersonClaimant {
/** `identity`: someone on a connected app, `id` is their platform identity.
* `former`: someone on an app since disconnected, `id` is the sender id their
- * messages carry, and `bridge_name` is null. */
+ * messages carry, and `bridge_name` is null. `member`: someone taking part
+ * from Switch Console, `id` is their member client, `platform` is `switch` and
+ * `bridge_name` is null; a deleted account's is named "Former member". */
export interface Person {
id: string;
- kind: "identity" | "former";
+ kind: "identity" | "former" | "member";
username: string;
platform: string;
bridge_name: string | null;
@@ -1573,6 +1575,7 @@ export async function erasePeople(tenantId: string, people: Person[]): Promise<E
return jsonRequest<Erasure>(`/tenants/${encodeURIComponent(tenantId)}/erasures`, "POST", {
external_user_ids: people.filter((p) => p.kind === "identity").map((p) => p.id),
former_sender_ids: people.filter((p) => p.kind === "former").map((p) => p.id),
+ member_client_ids: people.filter((p) => p.kind === "member").map((p) => p.id),
});
}
diff --git a/gateway/src/pages/workspace/EraseDialog.test.tsx b/gateway/src/pages/workspace/EraseDialog.test.tsx
index 1d96b463e..dd86bfcab 100644
--- a/gateway/src/pages/workspace/EraseDialog.test.tsx
+++ b/gateway/src/pages/workspace/EraseDialog.test.tsx
@@ -80,7 +80,11 @@ describe("EraseDialog", () => {
await waitFor(() => expect(onQueued).toHaveBeenCalled());
const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
- expect(JSON.parse(String(init.body))).toEqual({ external_user_ids: ["a"], former_sender_ids: [] });
+ expect(JSON.parse(String(init.body))).toEqual({
+ external_user_ids: ["a"],
+ former_sender_ids: [],
+ member_client_ids: [],
+ });
});
it("keeps what was ticked and typed when the people list refreshes", async () => {
@@ -97,7 +101,11 @@ describe("EraseDialog", () => {
fireEvent.click(screen.getByRole("button", { name: "Erase" }));
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
- expect(JSON.parse(String(init.body))).toEqual({ external_user_ids: ["a", "b"], former_sender_ids: [] });
+ expect(JSON.parse(String(init.body))).toEqual({
+ external_user_ids: ["a", "b"],
+ former_sender_ids: [],
+ member_client_ids: [],
+ });
});
it("erases a former participant by the sender id their messages carry", async () => {
@@ -130,6 +138,44 @@ describe("EraseDialog", () => {
expect(JSON.parse(String(init.body))).toEqual({
external_user_ids: [],
former_sender_ids: ["@switch-slack-x-dee:example.org"],
+ member_client_ids: [],
+ });
+ });
+
+ it("erases what a Switch Console member sent, keeping their account", async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({}), { status: 202 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const member: Person = {
+ id: "client-1",
+ kind: "member",
+ username: "Former member",
+ platform: "switch",
+ bridge_name: null,
+ message_count: 7,
+ claimed_by: [],
+ };
+ render(
+ <EraseDialog
+ tenantId="t1"
+ person={member}
+ people={[member, ana]}
+ onClose={() => {}}
+ onQueued={() => {}}
+ />,
+ );
+
+ expect(screen.getByText(/7 messages they sent from Switch Console/)).toBeTruthy();
+ expect(screen.getByText(/they can go on writing/)).toBeTruthy();
+ fireEvent.change(screen.getByLabelText("Type Former member to confirm"), {
+ target: { value: "Former member" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Erase" }));
+ await waitFor(() => expect(fetchMock).toHaveBeenCalled());
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(JSON.parse(String(init.body))).toEqual({
+ external_user_ids: [],
+ former_sender_ids: [],
+ member_client_ids: ["client-1"],
});
});
});
diff --git a/gateway/src/pages/workspace/EraseDialog.tsx b/gateway/src/pages/workspace/EraseDialog.tsx
index 3089cab76..1cedf60ff 100644
--- a/gateway/src/pages/workspace/EraseDialog.tsx
+++ b/gateway/src/pages/workspace/EraseDialog.tsx
@@ -94,17 +94,34 @@ export default function EraseDialog({ tenantId, person, people, onClose, onQueue
<DialogTitle>Erase {person.username}?</DialogTitle>
<DialogContent>
<Stack spacing={2}>
- <DialogContentText>
- This permanently deletes {plural(messages, "message")} they sent in every room of
- this workspace, archived rooms included, with their files and their identity. It
- cannot be undone.
- </DialogContentText>
- <DialogContentText>
- What other people wrote, including replies that quote them, is kept. Copies in{" "}
- {person.bridge_name ?? "the disconnected app"} and other chat apps are not
- deleted; remove those in the app. Their Switch account and membership, if any, are
- not affected.
- </DialogContentText>
+ {person.kind === "member" ? (
+ <>
+ <DialogContentText>
+ This permanently deletes {plural(messages, "message")} they sent from Switch
+ Console in every room of this workspace, archived rooms included, with their
+ files. It cannot be undone.
+ </DialogContentText>
+ <DialogContentText>
+ What other people wrote, including replies that quote them, is kept. Copies a
+ chat app received are not deleted; remove those in the app. Their Switch account
+ and membership, if any, are not affected, and they can go on writing.
+ </DialogContentText>
+ </>
+ ) : (
+ <>
+ <DialogContentText>
+ This permanently deletes {plural(messages, "message")} they sent in every room
+ of this workspace, archived rooms included, with their files and their identity.
+ It cannot be undone.
+ </DialogContentText>
+ <DialogContentText>
+ What other people wrote, including replies that quote them, is kept. Copies in{" "}
+ {person.bridge_name ?? "the disconnected app"} and other chat apps are not
+ deleted; remove those in the app. Their Switch account and membership, if any,
+ are not affected.
+ </DialogContentText>
+ </>
+ )}
{related.length > 0 && (
<Stack spacing={0.5}>
<Typography variant="subtitle2">
diff --git a/gateway/src/pages/workspace/PeopleSection.tsx b/gateway/src/pages/workspace/PeopleSection.tsx
index 0d9acf850..c8d5a62e5 100644
--- a/gateway/src/pages/workspace/PeopleSection.tsx
+++ b/gateway/src/pages/workspace/PeopleSection.tsx
@@ -85,7 +85,9 @@ export default function PeopleSection({ tenantId }: { tenantId: string }) {
flex: 1,
minWidth: 160,
valueGetter: (_value, row) =>
- `${row.bridge_name ?? "Disconnected app"} (${titleCase(row.platform)})`,
+ row.kind === "member"
+ ? "Switch Console"
+ : `${row.bridge_name ?? "Disconnected app"} (${titleCase(row.platform)})`,
},
{ field: "message_count", headerName: "Messages", width: 110, type: "number" },
{
@@ -119,8 +121,9 @@ export default function PeopleSection({ tenantId }: { tenantId: string }) {
<Stack spacing={1.5}>
<Typography variant="h6">People</Typography>
<Typography variant="body2" sx={{ color: "text.secondary" }}>
- Everyone seen in this workspace&apos;s rooms through a chat app, including apps since
- disconnected. Erasing
+ Everyone seen in this workspace&apos;s rooms, through a chat app (including apps since
+ disconnected) or Switch Console (including deleted accounts, shown as Former member).
+ Erasing
someone permanently deletes every message they sent and their files, for example to
answer a GDPR erasure request. Only workspace admins can see this list.
</Typography>