From 58ca879b017da62e77f40752d8d94fef3f315a1e Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Fri, 28 Aug 2026 10:09:38 +0200 Subject: feat(hub): group names unique per owner, shown as name@owner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A group's identity stays its UUID. What changes is that "the name is unique" — until now an unenforced expectation — becomes real, scoped to the owner account, and the owner's username is surfaced so two groups called "photos" on different nodes can be told apart. Hub: - `groups` gains a functional unique index `uq_groups_owner_name` on `(admin_id, lower(name))` (model + migration c3d4e5f6a7b8). The migration pre-flights: if the data already clashes it aborts and lists the offending (admin_id, name) pairs rather than renaming anyone's group. meshbay.org checked clean. - `create_group` trims the name, rejects blank (422) and an owner-scoped case-insensitive clash (409), with an IntegrityError backstop for the race, and returns `owner_username`. - `owner_username` added to `/v1/groups/mine`, `GET /v1/groups` (local rows), `POST /v1/groups/{id}/join`, `GET /v1/admin/groups`. SPA: - new `static/group-name.js` — `` renders the name with the `@owner` handle on a smaller grey line under it. - used in the sidebar, the group-page header, Explore cards, the Admin groups table, and cross-group Search (via a widened `cacheGroupIndex` carrying the owner). Delete/leave confirmations show `name@owner` inline. - federated Explore rows show `@` instead of an account. Design record and the locked decisions: ~/next/groupnames.md (out of repo). MNP unchanged. Tests: test_group_name_unique.py, test_group_name_migration.py. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_018gKJ85aZyvEwarXMFzFEwi --- packages/meshbay-hub/src/meshbay_hub/api/admin.py | 6 ++ packages/meshbay-hub/src/meshbay_hub/api/groups.py | 62 +++++++++++++---- .../c3d4e5f6a7b8_group_name_unique_per_owner.py | 45 +++++++++++++ packages/meshbay-hub/src/meshbay_hub/db/models.py | 11 ++- packages/meshbay-hub/src/meshbay_hub/static/app.js | 19 +++--- .../src/meshbay_hub/static/group-name.js | 22 ++++++ .../src/meshbay_hub/static/group-page.js | 11 ++- .../src/meshbay_hub/static/group-settings.js | 8 ++- .../src/meshbay_hub/static/hub-client.js | 4 +- .../meshbay-hub/src/meshbay_hub/static/style.css | 20 ++++++ .../meshbay-hub/tests/test_group_name_migration.py | 64 ++++++++++++++++++ .../meshbay-hub/tests/test_group_name_unique.py | 78 ++++++++++++++++++++++ 12 files changed, 320 insertions(+), 30 deletions(-) create mode 100644 packages/meshbay-hub/src/meshbay_hub/db/migrations/versions/c3d4e5f6a7b8_group_name_unique_per_owner.py create mode 100644 packages/meshbay-hub/src/meshbay_hub/static/group-name.js create mode 100644 packages/meshbay-hub/tests/test_group_name_migration.py create mode 100644 packages/meshbay-hub/tests/test_group_name_unique.py diff --git a/packages/meshbay-hub/src/meshbay_hub/api/admin.py b/packages/meshbay-hub/src/meshbay_hub/api/admin.py index 4141c79..ab6fa07 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/admin.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/admin.py @@ -301,12 +301,18 @@ async def admin_list_groups( total = (await db.execute(select(func.count()).select_from(Group))).scalar_one() + owner_ids = {g.admin_id for g, _ in rows} + owner_by_id = dict((await db.execute( + select(User.id, User.username).where(User.id.in_(owner_ids)))).all()) \ + if owner_ids else {} + return { "groups": [ { "id": g.id, "name": g.name, "admin_id": g.admin_id, + "owner_username": owner_by_id.get(g.admin_id), "visibility": g.visibility, "description": g.description or "", "status": g.status, diff --git a/packages/meshbay-hub/src/meshbay_hub/api/groups.py b/packages/meshbay-hub/src/meshbay_hub/api/groups.py index 91aa9c4..49902de 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/groups.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/groups.py @@ -4,6 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel from datetime import datetime, timezone from sqlalchemy import func, or_, select, update +from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from meshbay_hub import hub_settings @@ -31,8 +32,9 @@ async def my_groups( from meshbay_hub.api.revocation import get_online_nodes_for_group result = await db.execute( - select(Group) + select(Group, User.username) .join(GroupMember, Group.id == GroupMember.group_id) + .join(User, User.id == Group.admin_id) # the owner, for the @handle .where(GroupMember.user_id == current_user.id, Group.status == "active", # A group nobody hosts yet is the owner's business alone. Someone # added to it before a node exists would see a name they cannot @@ -40,7 +42,9 @@ async def my_groups( or_(Group.hosted_at.is_not(None), Group.admin_id == current_user.id)) .order_by(Group.last_activity_at.desc()) ) - groups = result.scalars().all() + rows = result.all() + groups = [g for g, _ in rows] + owner_by_id = {g.id: owner for g, owner in rows} muted_rows = await db.execute( select(GroupMember.group_id, GroupMember.muted) .where(GroupMember.user_id == current_user.id)) @@ -50,6 +54,7 @@ async def my_groups( { "id": g.id, "name": g.name, + "owner_username": owner_by_id.get(g.id), "visibility": g.visibility, "muted": muted_map.get(g.id, False), "join_policy": g.join_policy, @@ -147,22 +152,24 @@ async def list_public_groups( # Unhosted groups are absent from the directory: until a node announces it, # a group has no files, no key and nothing to connect to, so listing it only # produces a dead end. Its owner still sees it in /mine while they set it up. - query = select(Group).where(Group.visibility == "public", - Group.status == "active", - Group.hosted_at.is_not(None)) + query = (select(Group, User.username) + .join(User, User.id == Group.admin_id) + .where(Group.visibility == "public", + Group.status == "active", + Group.hosted_at.is_not(None))) if q: query = query.where(Group.name.ilike(f"%{q}%")) result = await db.execute( query.order_by(Group.created_at.desc()).limit(limit).offset(offset) ) - local = result.scalars().all() + local = result.all() groups = [ { "id": g.id, "name": g.name, "join_policy": g.join_policy, - "description": g.description or "", + "owner_username": owner, "description": g.description or "", "created_at": g.created_at.isoformat(), "source": "local", } - for g in local + for g, owner in local ] if include_federated: @@ -306,7 +313,9 @@ async def join_group( db.add(IPLog(user_id=current_user.id, event="group_join", ip_address=client_ip(request), detail=group.name)) await db.commit() - return {"status": "joined", "group_id": group_id, "name": group.name} + owner = await db.scalar(select(User.username).where(User.id == group.admin_id)) + return {"status": "joined", "group_id": group_id, "name": group.name, + "owner_username": owner} class GroupCreateRequest(BaseModel): @@ -386,6 +395,25 @@ async def create_group( status_code=422, detail="A private group is invite-only. Make it public if you want " "anyone to be able to join.") + + name = body.name.strip() + if not name: + raise HTTPException(status_code=422, detail="A group needs a name.") + # One name per owner, case-insensitively. Two *different* owners may each + # have a "photos" — that is why the check is scoped to `admin_id` and why + # the group's real identity stays its UUID. The DB has a unique index too + # (uq_groups_owner_name); this is the friendly error, that is the race + # backstop below. + clash = await db.scalar( + select(Group.id).where( + Group.admin_id == current_user.id, + func.lower(Group.name) == name.lower())) + if clash: + raise HTTPException( + status_code=409, + detail=f"You already have a group called “{name}”. Pick another name " + "— names only have to be unique among your own groups.") + if body.visibility == "public": if not await hub_settings.public_groups_allowed(db): # Instance policy, set by a hub admin in the panel. Absolute — staff @@ -399,7 +427,7 @@ async def create_group( desc = (body.description or "")[:512] if body.description else None group = Group( - name=body.name, + name=name, admin_id=current_user.id, visibility=body.visibility, join_policy=body.join_policy, @@ -410,10 +438,18 @@ async def create_group( db.add(GroupMember(group_id=group.id, user_id=current_user.id)) db.add(IPLog(user_id=current_user.id, event="group_create", - ip_address=client_ip(request), detail=body.name)) - await db.commit() + ip_address=client_ip(request), detail=name)) + try: + await db.commit() + except IntegrityError: + # Two creates for the same owner+name raced past the check above. + await db.rollback() + raise HTTPException( + status_code=409, + detail=f"You already have a group called “{name}”.") await db.refresh(group) - return {"group_id": group.id, "name": group.name} + return {"group_id": group.id, "name": group.name, + "owner_username": current_user.username} @router.delete("/{group_id}/members/{username}") diff --git a/packages/meshbay-hub/src/meshbay_hub/db/migrations/versions/c3d4e5f6a7b8_group_name_unique_per_owner.py b/packages/meshbay-hub/src/meshbay_hub/db/migrations/versions/c3d4e5f6a7b8_group_name_unique_per_owner.py new file mode 100644 index 0000000..6fc5b73 --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/db/migrations/versions/c3d4e5f6a7b8_group_name_unique_per_owner.py @@ -0,0 +1,45 @@ +"""group_name_unique_per_owner + +Revision ID: c3d4e5f6a7b8 +Revises: b1c2d3e4f5a6 +Create Date: 2026-08-28 14:00:00.000000 + +One group name per owner, case-insensitively. The group's identity is still +its UUID — this only makes `name@owner` a dependable handle. + +Pre-flight: abort if the data already violates it, with the offending +(admin_id, name) pairs listed, rather than silently renaming anyone's group. +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +revision: str = 'c3d4e5f6a7b8' +down_revision: Union[str, Sequence[str], None] = 'b1c2d3e4f5a6' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + bind = op.get_bind() + dupes = bind.execute(sa.text( + "SELECT admin_id, lower(name) AS n, count(*) AS c " + "FROM groups GROUP BY admin_id, lower(name) HAVING count(*) > 1" + )).fetchall() + if dupes: + listed = ", ".join(f"{r.admin_id[:8]}/{r.n!r}×{r.c}" for r in dupes) + raise RuntimeError( + "Cannot add uq_groups_owner_name: an owner already has two groups " + f"with the same name (case-insensitively): {listed}. " + "Rename or delete one of each pair, then re-run the migration." + ) + op.create_index( + "uq_groups_owner_name", "groups", + ["admin_id", sa.text("lower(name)")], unique=True, + ) + + +def downgrade() -> None: + op.drop_index("uq_groups_owner_name", table_name="groups") diff --git a/packages/meshbay-hub/src/meshbay_hub/db/models.py b/packages/meshbay-hub/src/meshbay_hub/db/models.py index 0c337c1..dbabfc2 100644 --- a/packages/meshbay-hub/src/meshbay_hub/db/models.py +++ b/packages/meshbay-hub/src/meshbay_hub/db/models.py @@ -15,7 +15,7 @@ from datetime import datetime, timezone from sqlalchemy import ( Boolean, DateTime, ForeignKey, Index, Integer, - String, Text, UniqueConstraint, + String, Text, UniqueConstraint, text, ) from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship @@ -109,7 +109,14 @@ class Group(Base): members: Mapped[list["GroupMember"]] = relationship(back_populates="group") - __table_args__ = (Index("ix_groups_name", "name"),) + __table_args__ = ( + Index("ix_groups_name", "name"), + # One name per owner, case-insensitively. The group's identity stays its + # UUID; this is what makes `name@owner` a handle a human can rely on + # (two different owners may still both have a "photos"). Enforced in the + # DB so a race cannot slip a second one past the check in create_group. + Index("uq_groups_owner_name", "admin_id", text("lower(name)"), unique=True), + ) class GroupMember(Base): diff --git a/packages/meshbay-hub/src/meshbay_hub/static/app.js b/packages/meshbay-hub/src/meshbay_hub/static/app.js index 9164a4d..18f34fc 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/app.js @@ -16,6 +16,7 @@ import { refreshAccessToken, } from './hub-client.js'; import { GroupPage } from './group-page.js'; +import { GroupName } from './group-name.js'; import { APPS } from './apps.js'; // ── Constants ──────────────────────────────────────────────────────────────── @@ -352,7 +353,9 @@ function Sidebar({ groups, presence, indexProgressPct, route, menuOpen, role, ha - ${g.name} + + <${GroupName} name=${g.name} owner=${g.owner_username} /> + `; }) @@ -699,13 +702,11 @@ function ExplorePage({ token, myGroupIds, allowPublicGroups = true }) { ${groups.map(g => html`
-

${g.name}

+

<${GroupName} name=${g.name} + owner=${g.source && g.source !== 'local' ? g.source : g.owner_username} />

${g.description && html`

${g.description}

`}
${g.join_policy} - ${g.source && g.source !== 'local' && html` - ${' '}${g.source} - `} ${' '} ${isMember(g.id) ? html`${t('explore.member')}` @@ -1331,7 +1332,7 @@ function SearchPage() { if (e.name.toLowerCase().includes(term) || (e.path && e.path.toLowerCase().includes(term))) { hits.push({ ...e, groupId: idx.groupId, groupName: idx.groupName, - syncedAt: idx.cachedAt }); + groupOwner: idx.groupOwner, syncedAt: idx.cachedAt }); } } } @@ -1376,7 +1377,9 @@ function SearchPage() { ${formatSize(r.size)} - ${r.groupName || r.groupId.slice(0, 8)} + ${r.groupName + ? html`<${GroupName} name=${r.groupName} owner=${r.groupOwner} inline=${true} />` + : r.groupId.slice(0, 8)} ${r.syncedAt && html`
${t('search.synced', { ago: formatAgo(r.syncedAt) })} @@ -2175,7 +2178,7 @@ function AdminPage({ token, role }) { ${groups.length === 0 && html`${t('admin.no_groups')}`} ${groups.map(g => html` - ${g.name} + <${GroupName} name=${g.name} owner=${g.owner_username} /> ${g.visibility} ${g.member_count} ${g.status} diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-name.js b/packages/meshbay-hub/src/meshbay_hub/static/group-name.js new file mode 100644 index 0000000..af8879c --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/group-name.js @@ -0,0 +1,22 @@ +import { html } from './vendor/htm-preact.js'; + +/** + * A group's name with the `@owner` handle under it. + * + * Group names are unique only per owner account (the hub enforces that), so the + * `@handle` is what tells two groups called "photos" apart. `owner` is the + * owner's username for a local group, or the source hub for a federated one + * (decision 5 in ~/next/groupnames.md); the caller decides which. + * + * `inline` renders "name@owner" on one line, for places that cannot take a + * block — a badge, a `confirm()` string built elsewhere. + */ +export function GroupName({ name, owner, inline = false }) { + if (inline) return owner ? `${name}@${owner}` : name; + return html` + + ${name} + ${owner && html`@${owner}`} + + `; +} diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-page.js b/packages/meshbay-hub/src/meshbay_hub/static/group-page.js index 470f169..4ebe5a7 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/group-page.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/group-page.js @@ -9,6 +9,7 @@ import { HUB, session, cacheGroupIndex, hubFetch, ensureFreshToken, _loadBundleKey, } from './hub-client.js'; import { visibleApps } from './apps.js'; +import { GroupName } from './group-name.js'; import { FilePreview } from './files-app.js'; import { VideoPlayer } from './video-player.js'; import { MusicPlayerBar } from './music-player.js'; @@ -160,7 +161,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, setEntries(fresh); if (indexMsg.dirs) setNodeDirs(indexMsg.dirs); if (indexMsg.roots) setNodeRoots(indexMsg.roots); - cacheGroupIndex(groupId, group ? group.name : groupId, fresh); + cacheGroupIndex(groupId, group ? group.name : groupId, + group ? group.owner_username : null, fresh); }, [groupId, group]); // additions/deletions/updates (daemon.py _broadcast_index_change, once @@ -181,7 +183,8 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs, const keptIds = new Set(updated.map((e) => e.id)); const additions = (deltaMsg.additions || []).filter((e) => !keptIds.has(e.id)); const fresh = updated.concat(additions); - cacheGroupIndex(groupId, group ? group.name : groupId, fresh); + cacheGroupIndex(groupId, group ? group.name : groupId, + group ? group.owner_username : null, fresh); return fresh; }); }, [groupId, group]); @@ -493,7 +496,9 @@ function GroupPage({ groupId, group, token, username, userId, userPrefs,

- ${group ? group.name : t('group.default_name')} + ${group + ? html`<${GroupName} name=${group.name} owner=${group.owner_username} />` + : t('group.default_name')}

${editingDesc ? html` diff --git a/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js b/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js index 60b0184..59d1456 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/group-settings.js @@ -1244,7 +1244,9 @@ function GroupSettingsPanel({ groupId, group, token, transportRef, gekRef, ${isOwner ? html`