Skip to content

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

The new gateway shell: workspace switcher in the top bar, settings at the rail's foot (CHOO-4074) (#1837)

Christian McDermott491a3c7270a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c0e0bbc9..229ed7fef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -69,8 +69,15 @@ version of their own to them without also giving them a release of their own.
`alerted` or `errored`. A message Switch Trust left alone has no `trust`
field, so its result is as before. Until now an agent whose words were
redacted had no way to know.
+- **How many users and agents each workspace has.** `GET /gateway/tenants/counts`
+ answers for every workspace the caller may enter, counting people as the
+ workspace's members list shows them: its members, and its organization's
+ admins who are not one. The dashboard's new workspace switcher reads it.
#### Changed
+- **The dashboard no longer claims the system is healthy.** The "System
+ healthy" indicator in its top bar was hard-coded and never checked anything,
+ so it is gone.
- **`GATEWAY_ADMIN_PASSWORD` is optional when password login is off.** With
`GATEWAY_PASSWORD_LOGIN_ENABLED=false` the admin account is seeded without a
password, and the first OIDC sign-in with `GATEWAY_ADMIN_EMAIL` links to it.
diff --git a/console/tooling-e2e/src/clients/switch-client.ts b/console/tooling-e2e/src/clients/switch-client.ts
index aeebe3d4f..1b76479b4 100644
--- a/console/tooling-e2e/src/clients/switch-client.ts
+++ b/console/tooling-e2e/src/clients/switch-client.ts
@@ -555,6 +555,11 @@ export class SwitchClient {
return this.gateway<OrganizationSummary[]>("GET", "/organizations");
}
+ /** `GET /gateway/tenants/counts` — how many users and agents each workspace the caller may enter has. */
+ async workspaceCounts(): Promise<{ id: string; users: number; agents: number }[]> {
+ return this.gateway("GET", "/tenants/counts");
+ }
+
/** `GET /gateway/organizations/current/workspaces` — the current organization's workspaces the caller may enter. */
async organizationWorkspaces(): Promise<WorkspaceMembership[]> {
return this.gateway<WorkspaceMembership[]>(
diff --git a/console/tooling-e2e/src/fast/organizations.ts b/console/tooling-e2e/src/fast/organizations.ts
index 5859c865f..644be7a73 100644
--- a/console/tooling-e2e/src/fast/organizations.ts
+++ b/console/tooling-e2e/src/fast/organizations.ts
@@ -7,8 +7,8 @@ import type { FastScenario } from './scenario.ts';
* it: a new user, in the default workspace, creates an organization and lands
* in its first workspace, adds a second, and sees both, in an organization
* listed beside those they were already in, with nothing left for its admin
- * to fix. A plain member of the default
- * workspace may not add one there.
+ * to fix, and each new workspace counted with its one user and no agents. A
+ * plain member of the default workspace may not add one there.
*
* Users and workspaces cannot be deleted, so this runs only on a stack thrown
* away after the run.
@@ -23,6 +23,7 @@ export const organizations: FastScenario = {
'GET /gateway/organizations/current/issues',
'GET /gateway/organizations/current/workspaces',
'POST /gateway/organizations/current/workspaces',
+ 'GET /gateway/tenants/counts',
],
lane: 'fast',
environments: ['ephemeral'],
@@ -84,6 +85,17 @@ export const organizations: FastScenario = {
expect(await founder.organizationIssues(), 'nothing to fix in a new organization').toEqual([]);
+ const counts = await founder.workspaceCounts();
+ for (const id of [workspace.id, second.id]) {
+ expect(
+ counts.find((row) => row.id === id),
+ 'a new workspace counts its admin and nothing else'
+ ).toEqual({ id, users: 1, agents: 0 });
+ }
+ expect(counts.map((row) => row.id), 'the default workspace is counted too').toContain(
+ defaultWorkspace
+ );
+
const listed = await founder.organizations();
expect(listed.find((row) => row.id === organization.id)?.role).toBe('org_admin');
expect(listed.map((row) => row.id).sort(), 'the new one beside the rest').toEqual(
diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.json
index bb54da3f4..79d5123da 100644
--- a/console/tooling-e2e/surface/server-surface.json
+++ b/console/tooling-e2e/surface/server-surface.json
@@ -918,6 +918,11 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "GET /gateway/tenants/counts",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "GET /gateway/tenants/current",
"auth": "session",
diff --git a/core/switch_core/db/stores/agent_store.py b/core/switch_core/db/stores/agent_store.py
index 94522d19d..fda91bd2c 100644
--- a/core/switch_core/db/stores/agent_store.py
+++ b/core/switch_core/db/stores/agent_store.py
@@ -119,6 +119,17 @@ class AgentStore:
result = await session.execute(select(Agent))
return list(result.scalars().all())
+ async def count(self, session: AsyncSession) -> int:
+ """How many agents the bound tenant has, children included, as
+ `get_all` lists them."""
+ return (
+ await session.scalar(
+ select(func.count())
+ .select_from(Agent)
+ .where(Agent.tenant_id == require_tenant_id())
+ )
+ ) or 0
+
async def get_by_owner(self, session: AsyncSession, owner_id: str) -> list[Agent]:
"""Every agent `owner_id` owns in the bound tenant.
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index c6f0bfbdd..e57e14508 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -11,6 +11,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.authz import (
+ ORGANIZATION_ADMIN_ROLE,
TENANT_ADMIN_ROLES,
administers_tenant,
effective_tenant_role,
@@ -648,6 +649,26 @@ class UserStore:
)
return [(row[0], row[1]) for row in result.all()]
+ async def count_people(self, session: AsyncSession, tenant: Tenant) -> int:
+ """How many people `tenant`'s roster lists: its members, and the
+ `org_admin`s of its organization who are not one, each once."""
+ members = select(TenantMember.user_id).where(
+ TenantMember.tenant_id == tenant.id
+ )
+ people = (
+ members
+ if tenant.organization_id is None
+ else members.union(
+ select(OrganizationMember.user_id).where(
+ OrganizationMember.organization_id == tenant.organization_id,
+ OrganizationMember.role == ORGANIZATION_ADMIN_ROLE,
+ )
+ )
+ )
+ return (
+ await session.scalar(select(func.count()).select_from(people.subquery()))
+ ) or 0
+
async def count_admins(self, session: AsyncSession) -> int:
"""How many `admin` memberships the session's bound tenant has, locking
nothing. For reporting how things stand; a write that must keep an admin
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 7466d27c5..3b1d816b5 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1144,6 +1144,16 @@ class TenantMembershipResponse(BaseModel):
organization_id: str | None
+class WorkspaceCountsResponse(BaseModel):
+ """How many people and agents one workspace the caller may enter has, as
+ its members list and agents list show them. The body of
+ `GET /tenants/counts`, one per workspace."""
+
+ id: str
+ users: int
+ agents: int
+
+
class OperatorWorkspaceResponse(BaseModel):
"""One workspace on the server, as the platform operator's list shows it."""
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 98db37504..e6c670363 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -80,8 +80,10 @@ from switch_core.db.stores.usage_store import UsageStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.auth import (
AuthenticatedCaller,
+ AuthenticatedSession,
all_workspaces,
get_authenticated_caller,
+ get_authenticated_session,
get_authenticated_user_id,
get_current_user,
get_tenant_is_admin,
@@ -94,6 +96,7 @@ from switch_core.gateway.auth import (
session_auth_time,
set_session_cookie,
tenant_of_invitation_token,
+ tenants_bindable_by,
tenants_open_to,
tenants_with_invitations_for,
)
@@ -157,6 +160,7 @@ from switch_core.gateway.schemas import (
TenantDeleteRequest,
TenantMembershipResponse,
UsageTotalResponse,
+ WorkspaceCountsResponse,
)
from switch_core.gateway.service_connections import service_refusal
from switch_core.gateway.workspace_creation import (
@@ -324,6 +328,53 @@ async def list_tenants(
return await list_tenant_memberships(session_factory, user_store, user_id)
[email protected]("/tenants/counts")
+async def workspace_counts(
+ auth: Annotated[AuthenticatedSession, Depends(get_authenticated_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],
+) -> list[WorkspaceCountsResponse]:
+ """How many people and agents each workspace the caller may enter has:
+ those of `GET /tenants`, and the one the platform operator entered on the
+ operator flag alone, which their session is in without being one of them.
+
+ For the dashboard's workspace switcher, which asks when it opens rather
+ than on every page: each workspace is read on its own short session, as
+ `GET /tenants` reads them, so this costs as much again.
+ """
+ tenant_ids = await tenants_bindable_by(session_factory, auth.user_id)
+ claim = auth.tenant_claim
+ if (
+ claim is not None
+ and claim not in tenant_ids
+ and await may_bind_tenant(session_factory, user_store, auth.user_id, claim)
+ ):
+ tenant_ids.append(claim)
+ counts: list[WorkspaceCountsResponse] = []
+ for tenant_id in tenant_ids:
+ async with tenant_session(session_factory, tenant_id) as session:
+ tenant = await session.get(Tenant, tenant_id)
+ if tenant is None:
+ logger.warning(
+ "User %s may enter workspace %s, but it was gone by the "
+ "time its counts were read",
+ auth.user_id,
+ tenant_id,
+ )
+ continue
+ counts.append(
+ WorkspaceCountsResponse(
+ id=tenant_id,
+ users=await user_store.count_people(session, tenant),
+ agents=await agent_store.count(session),
+ )
+ )
+ return counts
+
+
@router.get("/tenants/current")
async def current_tenant(
request: Request,
diff --git a/core/tests/switch_core/gateway/role_matrix/routes.py b/core/tests/switch_core/gateway/role_matrix/routes.py
index 68914c389..30d49135b 100644
--- a/core/tests/switch_core/gateway/role_matrix/routes.py
+++ b/core/tests/switch_core/gateway/role_matrix/routes.py
@@ -200,6 +200,7 @@ ROUTES: dict[str, Case] = {
),
# ── Workspaces ───────────────────────────────────────────────────────
"GET /gateway/tenants": get(f"{G}/tenants", SELF),
+ "GET /gateway/tenants/counts": get(f"{G}/tenants/counts", SELF),
"GET /gateway/tenants/current": get(f"{G}/tenants/current", SELF),
"POST /gateway/tenants": post(f"{G}/tenants", SELF, json={"name": "{tag}-ws"}),
"POST /gateway/tenants/{tenant_id}/switch": post(f"{W}/switch", SELF),
diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.py
index 79b1ace13..4a9703c19 100644
--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py
+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py
@@ -119,6 +119,11 @@ _ROUTES_THAT_NEVER_BIND_A_TENANT = {
("GET", "/tenants"),
("POST", "/tenants"),
("POST", "/tenants/{tenant_id}/switch"),
+ # What the workspace switcher shows beside each of those workspaces. It
+ # opens a `tenant_session` per tenant `tenants_bindable_by` names, and
+ # around the operator's claim only once `may_bind_tenant` admits it — see
+ # `workspace_counts`.
+ ("GET", "/tenants/counts"),
# The same for organizations: list the caller's, make one.
("GET", "/organizations"),
("POST", "/organizations"),
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 de5a7be86..fd858956f 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -2233,6 +2233,168 @@ class TestWorkspaceDeletionFlag:
assert response.json()["can_delete"] is False
+class TestWorkspaceCountsRoute:
+ """`GET /tenants/counts`: people and agents for each workspace the caller
+ may enter, for the dashboard's workspace switcher."""
+
+ async def _organization_of(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ *tenant_ids: str,
+ members: dict[str, str],
+ ) -> None:
+ organization_id = f"org-{uuid.uuid4().hex[:8]}"
+ async with session_factory() as session:
+ session.add(
+ Organization(id=organization_id, slug=organization_id, name="Acme")
+ )
+ await session.flush()
+ for tenant_id in tenant_ids:
+ session.add(
+ Tenant(
+ id=tenant_id,
+ slug=tenant_id,
+ name=tenant_id,
+ organization_id=organization_id,
+ )
+ )
+ for user_id, role in members.items():
+ session.add(
+ OrganizationMember(
+ organization_id=organization_id, user_id=user_id, role=role
+ )
+ )
+ await session.commit()
+
+ async def test_counts_each_workspace_of_a_member_on_its_own(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ await _make_tenant(session_factory, TENANT_B)
+ member_id = await _make_member(
+ session_factory, name="both", tenant_id=TENANT_A, role="member"
+ )
+ async with session_factory() as session:
+ session.add(
+ TenantMember(tenant_id=TENANT_B, user_id=member_id, role="admin")
+ )
+ await session.commit()
+ other_id = await _make_member(
+ session_factory, name="a-only", tenant_id=TENANT_A, role="admin"
+ )
+ for _ in range(2):
+ await _make_agent_with_key(
+ session_factory, tenant_id=TENANT_A, owner_id=other_id
+ )
+ await _make_agent_with_key(
+ session_factory, tenant_id=TENANT_B, owner_id=member_id
+ )
+ token = _token(member_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/counts")
+
+ assert response.status_code == 200, response.text
+ assert sorted(response.json(), key=lambda row: row["id"]) == [
+ {"id": TENANT_A, "users": 2, "agents": 2},
+ {"id": TENANT_B, "users": 1, "agents": 1},
+ ]
+
+ async def test_counts_an_org_admin_once_whether_or_not_they_are_a_member(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ admin_id = await _make_unaffiliated_user(
+ session_factory, name="org-admin", role="user"
+ )
+ await self._organization_of(
+ session_factory, TENANT_A, TENANT_B, members={admin_id: "org_admin"}
+ )
+ async with session_factory() as session:
+ session.add(
+ TenantMember(tenant_id=TENANT_A, user_id=admin_id, role="admin")
+ )
+ await session.commit()
+ await _make_member(
+ session_factory, name="b-member", tenant_id=TENANT_B, role="member"
+ )
+ token = _token(admin_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/counts")
+
+ assert response.status_code == 200, response.text
+ assert sorted(response.json(), key=lambda row: row["id"]) == [
+ {"id": TENANT_A, "users": 1, "agents": 0},
+ {"id": TENANT_B, "users": 2, "agents": 0},
+ ]
+
+ async def test_an_org_member_who_is_no_admin_counts_only_where_they_are_a_member(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ member_id = await _make_unaffiliated_user(
+ session_factory, name="org-member", role="user"
+ )
+ bystander_id = await _make_unaffiliated_user(
+ session_factory, name="bystander", role="user"
+ )
+ await self._organization_of(
+ session_factory,
+ TENANT_A,
+ members={member_id: "member", bystander_id: "member"},
+ )
+ async with session_factory() as session:
+ session.add(
+ TenantMember(tenant_id=TENANT_A, user_id=member_id, role="member")
+ )
+ await session.commit()
+ token = _token(member_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/counts")
+
+ assert response.status_code == 200, response.text
+ assert response.json() == [{"id": TENANT_A, "users": 1, "agents": 0}]
+
+ async def test_the_operator_is_told_about_a_workspace_they_entered(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ await _make_member(
+ session_factory, name="a-admin", tenant_id=TENANT_A, role="admin"
+ )
+ operator_id = await _make_member(
+ session_factory,
+ name="operator",
+ tenant_id=TENANT_ZERO_ID,
+ role="admin",
+ user_role="admin",
+ )
+ token = _token(operator_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/counts")
+
+ assert response.status_code == 200, response.text
+ assert {row["id"] for row in response.json()} == {TENANT_ZERO_ID, TENANT_A}
+ assert {row["id"]: row["users"] for row in response.json()}[TENANT_A] == 1
+
+ async def test_a_workspace_named_by_someone_elses_claim_is_left_out(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ await _make_tenant(session_factory, TENANT_B)
+ member_id = await _make_member(
+ session_factory, name="member", tenant_id=TENANT_A, role="member"
+ )
+ token = _token(member_id, "[email protected]", TENANT_B)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/counts")
+
+ assert response.status_code == 200, response.text
+ assert [row["id"] for row in response.json()] == [TENANT_A]
+
+
class TestUsageRoute:
async def _spend(
self,
diff --git a/gateway/src/App.test.tsx b/gateway/src/App.test.tsx
index cf9df7167..d38b9b80f 100644
--- a/gateway/src/App.test.tsx
+++ b/gateway/src/App.test.tsx
@@ -87,6 +87,20 @@ function signedInAs(
}),
],
"/feature-flags": [200, { flags: flags.map((key) => ({ key, enabled: true })) }],
+ "/organizations": [
+ 200,
+ [
+ { id: "o1", slug: "acme-group", name: "Acme Group", role: tenant.organization_role },
+ { id: "o2", slug: "beta-holdings", name: "Beta Holdings", role: "member" },
+ ],
+ ],
+ "/tenants/counts": [
+ 200,
+ [
+ { id: "t1", users: 3, agents: 2 },
+ { id: "t2", users: 1, agents: 0 },
+ ],
+ ],
"/tenants/current": [
200,
{
@@ -365,6 +379,15 @@ describe("today's layout", () => {
renderAt("/");
await landsOn("/rooms");
});
+
+ it("keeps switching workspace in the account menu, and claims nothing about the system's health", async () => {
+ mockFetch(signedInAs("member", { tenants: [beta] }));
+ renderAt("/rooms");
+ fireEvent.click(await screen.findByRole("button", { name: "Account menu" }));
+ expect(await screen.findByText("Switch to Beta Co")).toBeTruthy();
+ expect(screen.queryByText("System healthy")).toBeNull();
+ expect(screen.queryByRole("link", { name: "Help" })).toBeNull();
+ });
});
describe("deleting the workspace", () => {
@@ -624,6 +647,189 @@ describe("the new layout (gateway_v2)", () => {
});
});
+ describe("the top bar", () => {
+ async function openSwitcher() {
+ fireEvent.click(await screen.findByRole("button", { name: /Acme Group\s*\/\s*Acme/ }));
+ return screen.findByRole("menu", { name: "Workspaces" });
+ }
+
+ it("names the organization, the workspace and the page", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/rooms");
+ expect(await screen.findByRole("button", { name: /Acme Group\s*\/\s*Acme/ })).toBeTruthy();
+ expect(screen.getByText("Rooms", { selector: "span" })).toBeTruthy();
+ });
+
+ it("names only the workspace where it belongs to no organization", async () => {
+ mockFetch(signedInAs("member", { flags: V2, inOrganization: false }));
+ renderAt("/rooms");
+ const crumb = await screen.findByRole("button", { name: "Acme" });
+ expect(crumb.getAttribute("aria-haspopup")).toBe("menu");
+ });
+
+ it("lists the workspaces by organization, with their users and agents", async () => {
+ mockFetch(signedInAs("member", { flags: V2, tenants: [beta] }));
+ renderAt("/rooms");
+ const menu = await openSwitcher();
+ expect(within(menu).getByText("Acme Group")).toBeTruthy();
+ expect(within(menu).getByText("Beta Holdings")).toBeTruthy();
+ expect(await within(menu).findByText("3 users · 2 agents")).toBeTruthy();
+ expect(within(menu).getByText("1 user · 0 agents")).toBeTruthy();
+ const current = within(menu).getByRole("menuitem", { current: true });
+ expect(current.textContent).toContain("Acme");
+ });
+
+ it("names the organization of a workspace the operator entered on the operator flag alone", async () => {
+ const entered: TenantMembership = {
+ id: "t9",
+ slug: "gamma",
+ name: "Gamma",
+ role: "admin",
+ organization_role: null,
+ organization_id: "o9",
+ };
+ const operator = signedInAs("operator", { flags: V2, tenants: [beta] });
+ mockFetch({
+ ...operator,
+ "/auth/session": [
+ 200,
+ session({
+ state: "ready",
+ tenant: entered,
+ tenants: [acme, beta],
+ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: true },
+ }),
+ ],
+ "/tenants/current": [
+ 200,
+ { ...entered, administers: true, can_delete: false, can_manage_data_protection: false },
+ ],
+ "/organizations/current": [
+ 200,
+ {
+ id: "o9",
+ slug: "gamma-corp",
+ name: "Gamma Corp",
+ role: null,
+ members_from_directory: false,
+ directory_takes_changes: false,
+ administers: false,
+ can_manage_members: false,
+ },
+ ],
+ });
+ renderAt("/rooms");
+ fireEvent.click(await screen.findByRole("button", { name: /Gamma Corp\s*\/\s*Gamma/ }));
+ const menu = await screen.findByRole("menu", { name: "Workspaces" });
+ for (const heading of ["Acme Group", "Beta Holdings", "Gamma Corp"]) {
+ expect(within(menu).getByText(heading)).toBeTruthy();
+ }
+ expect(within(menu).getByRole("menuitem", { current: true }).textContent).toContain("Gamma");
+ });
+
+ it("says so when the counts cannot be read, and still lists the workspaces", async () => {
+ mockFetch({
+ ...signedInAs("member", { flags: V2, tenants: [beta] }),
+ "/tenants/counts": [500, { detail: "counts unavailable" }],
+ });
+ renderAt("/rooms");
+ const menu = await openSwitcher();
+ expect(
+ await within(menu).findByText(/Could not load how many users and agents.*counts unavailable/),
+ ).toBeTruthy();
+ expect(within(menu).getByText("Beta Co")).toBeTruthy();
+ });
+
+ it("switches to the workspace chosen", async () => {
+ const assign = vi.fn();
+ const originalLocation = window.location;
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: { ...originalLocation, assign, pathname: "/rooms" },
+ });
+ try {
+ mockFetch({
+ ...signedInAs("member", { flags: V2, tenants: [beta] }),
+ "/tenants/t2/switch": [200, { ok: true }],
+ });
+ renderAt("/rooms");
+ const menu = await openSwitcher();
+ fireEvent.click(within(menu).getByText("Beta Co"));
+ await waitFor(() => expect(assign).toHaveBeenCalledWith("/"));
+ expect(
+ vi.mocked(fetch).mock.calls.some(([input]) => String(input).endsWith("/tenants/t2/switch")),
+ ).toBe(true);
+ } finally {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+ }
+ });
+
+ it("lets a workspace admin or an organization admin invite people", async () => {
+ for (const role of ["workspace_admin", "org_admin"] as const) {
+ mockFetch(signedInAs(role, { flags: V2 }));
+ renderAt("/rooms");
+ const menu = await openSwitcher();
+ fireEvent.click(within(menu).getByRole("menuitem", { name: "Invite people to Acme" }));
+ expect(await screen.findByRole("dialog", { name: "Invite to workspace" })).toBeTruthy();
+ cleanup();
+ }
+ });
+
+ it("does not offer a member to invite people", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/rooms");
+ const menu = await openSwitcher();
+ expect(within(menu).queryByRole("menuitem", { name: /Invite people/ })).toBeNull();
+ });
+
+ it("links to help and the docs, and claims nothing about the system's health", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/rooms");
+ const help = await screen.findByRole("link", { name: "Help" });
+ expect(help.getAttribute("href")).toBe(
+ "https://docs.switchagents.ai/switch-rooms/resources/troubleshooting",
+ );
+ expect(screen.getByRole("link", { name: "Docs" })).toBeTruthy();
+ expect(screen.queryByText("System healthy")).toBeNull();
+ });
+ });
+
+ describe("the account menu", () => {
+ it("leads to your account, and leaves switching workspace to the top bar", async () => {
+ mockFetch(signedInAs("member", { flags: V2, tenants: [beta] }));
+ renderAt("/rooms");
+ fireEvent.click(await screen.findByRole("button", { name: "Account menu" }));
+ const account = await screen.findByRole("menuitem", { name: "Your account" });
+ expect(account.getAttribute("href")).toBe("/settings/account");
+ expect(screen.queryByText("Switch to Beta Co")).toBeNull();
+ expect(screen.getByRole("menuitem", { name: "Change password" })).toBeTruthy();
+ expect(screen.getByRole("menuitem", { name: "Create organization" })).toBeTruthy();
+ expect(screen.getByRole("menuitem", { name: "Sign out" })).toBeTruthy();
+ });
+ });
+
+ describe("in organization settings", () => {
+ it("hides the rail and leads back to the workspace", async () => {
+ mockFetch(signedInAs("org_admin", { flags: V2 }));
+ renderAt("/settings/org/general");
+ const back = await screen.findByRole("link", { name: "Back to workspace" });
+ expect(back.getAttribute("href")).toBe("/");
+ expect(screen.queryByRole("navigation", { name: "Main" })).toBeNull();
+ expect(screen.queryByRole("button", { name: /Acme Group/ })).toBeNull();
+ });
+
+ it("keeps the rail everywhere else in settings", async () => {
+ mockFetch(signedInAs("org_admin", { flags: V2 }));
+ renderAt("/settings/general");
+ expect(await screen.findByRole("navigation", { name: "Main" })).toBeTruthy();
+ });
+ });
+
it("shows a page that is not built yet as such", async () => {
mockFetch(signedInAs("member", { flags: V2 }));
renderAt("/settings/guardrails");
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index a36867c88..11c7a0f42 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1279,6 +1279,29 @@ export async function createTenant(name: string): Promise<TenantMembership> {
return created.workspace;
}
+export interface OrganizationSummary {
+ id: string;
+ slug: string;
+ name: string;
+ role: OrganizationRole;
+}
+
+/** The organizations of the workspaces the caller may enter. */
+export async function fetchOrganizations(): Promise<OrganizationSummary[]> {
+ return jsonRequest<OrganizationSummary[]>("/organizations", "GET");
+}
+
+export interface WorkspaceCounts {
+ id: string;
+ users: number;
+ agents: number;
+}
+
+/** How many people and agents each workspace the caller may enter has. */
+export async function fetchWorkspaceCounts(): Promise<WorkspaceCounts[]> {
+ return jsonRequest<WorkspaceCounts[]>("/tenants/counts", "GET");
+}
+
export async function switchTenant(tenantId: string): Promise<void> {
await jsonRequest(`/tenants/${encodeURIComponent(tenantId)}/switch`, "POST");
}
diff --git a/gateway/src/data/workspaceSwitcher.test.ts b/gateway/src/data/workspaceSwitcher.test.ts
new file mode 100644
index 000000000..dcab27ffa
--- /dev/null
+++ b/gateway/src/data/workspaceSwitcher.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+import type { TenantMembership } from "./api";
+import {
+ type OrganizationName,
+ countsLabel,
+ organizationName,
+ switcherSections,
+ switcherWorkspaces,
+} from "./workspaceSwitcher";
+
+function workspace(id: string, name: string, organizationId: string | null): TenantMembership {
+ return {
+ id,
+ slug: id,
+ name,
+ role: "member",
+ organization_role: organizationId === null ? null : "member",
+ organization_id: organizationId,
+ };
+}
+
+function organization(id: string, name: string): OrganizationName {
+ return { id, name };
+}
+
+const names = (workspaces: TenantMembership[]) => workspaces.map((w) => w.name);
+
+describe("switcherWorkspaces", () => {
+ it("lists the session's workspaces", () => {
+ const a = workspace("a", "A", "o1");
+ const b = workspace("b", "B", "o1");
+ expect(switcherWorkspaces(a, [a, b])).toEqual([a, b]);
+ });
+
+ it("adds the current workspace where it is none of them, as the operator's entered one", () => {
+ const a = workspace("a", "A", "o1");
+ const entered = workspace("x", "Elsewhere", "o9");
+ expect(switcherWorkspaces(entered, [a])).toEqual([entered, a]);
+ });
+});
+
+describe("switcherSections", () => {
+ it("heads each organization with its name, in name order", () => {
+ const { sections, headed } = switcherSections(
+ [
+ workspace("1", "Zeta", "o2"),
+ workspace("2", "Beta", "o1"),
+ workspace("3", "Alpha", "o2"),
+ ],
+ [organization("o1", "Umbrella"), organization("o2", "Acme")],
+ );
+ expect(headed).toBe(true);
+ expect(sections.map((s) => s.name)).toEqual(["Acme", "Umbrella"]);
+ expect(names(sections[0].workspaces)).toEqual(["Alpha", "Zeta"]);
+ });
+
+ it("puts the workspaces of no organization last", () => {
+ const { sections, headed } = switcherSections(
+ [workspace("1", "Loose", null), workspace("2", "Kept", "o1")],
+ [organization("o1", "Acme")],
+ );
+ expect(headed).toBe(true);
+ expect(sections.map((s) => s.organizationId)).toEqual(["o1", null]);
+ });
+
+ it("leaves one organization unheaded", () => {
+ const { sections, headed } = switcherSections(
+ [workspace("1", "B", "o1"), workspace("2", "A", "o1")],
+ [organization("o1", "Acme")],
+ );
+ expect(headed).toBe(false);
+ expect(names(sections[0].workspaces)).toEqual(["A", "B"]);
+ });
+
+ it("lists everything in one unheaded section when an organization has no name to show", () => {
+ const { sections, headed } = switcherSections(
+ [workspace("1", "B", "o1"), workspace("2", "A", "o2")],
+ [organization("o1", "Acme")],
+ );
+ expect(headed).toBe(false);
+ expect(sections).toHaveLength(1);
+ expect(names(sections[0].workspaces)).toEqual(["A", "B"]);
+ });
+});
+
+describe("organizationName", () => {
+ it("names a known organization, and nothing else", () => {
+ const organizations = [organization("o1", "Acme")];
+ expect(organizationName("o1", organizations)).toBe("Acme");
+ expect(organizationName("o2", organizations)).toBeNull();
+ expect(organizationName(null, organizations)).toBeNull();
+ });
+});
+
+describe("countsLabel", () => {
+ it("matches each noun to its number", () => {
+ expect(countsLabel({ id: "a", users: 1, agents: 3 })).toBe("1 user · 3 agents");
+ expect(countsLabel({ id: "a", users: 2, agents: 0 })).toBe("2 users · 0 agents");
+ });
+});
diff --git a/gateway/src/data/workspaceSwitcher.ts b/gateway/src/data/workspaceSwitcher.ts
new file mode 100644
index 000000000..a4654c56a
--- /dev/null
+++ b/gateway/src/data/workspaceSwitcher.ts
@@ -0,0 +1,105 @@
+import {
+ type TenantMembership,
+ type WorkspaceCounts,
+ fetchCurrentOrganization,
+ fetchOrganizations,
+} from "./api";
+
+/** An organization the switcher can name. */
+export interface OrganizationName {
+ id: string;
+ name: string;
+}
+
+/** The organizations the switcher names: those of the workspaces the caller
+ * may enter, and the current workspace's where it is none of those, as when
+ * the platform operator entered it on the operator flag alone. Left out, it
+ * would leave the breadcrumb without its organization and the switcher
+ * without headings. */
+export async function loadOrganizationNames(
+ currentOrganizationId: string | null,
+): Promise<OrganizationName[]> {
+ const listed: OrganizationName[] = await fetchOrganizations();
+ if (currentOrganizationId === null || listed.some((o) => o.id === currentOrganizationId)) {
+ return listed;
+ }
+ const current = await fetchCurrentOrganization();
+ return [...listed, { id: current.id, name: current.name }];
+}
+
+/** The workspaces of one organization, as the switcher lists them. */
+export interface WorkspaceGroup {
+ /** Null for the workspaces that name no organization. */
+ organizationId: string | null;
+ /** Null where the organization could not be named. */
+ name: string | null;
+ workspaces: TenantMembership[];
+}
+
+/** What the switcher lists: every workspace the session may enter, and the
+ * current one where it is none of those, as when the platform operator
+ * entered it on the operator flag alone. */
+export function switcherWorkspaces(
+ current: TenantMembership | null,
+ tenants: TenantMembership[],
+): TenantMembership[] {
+ if (current === null || tenants.some((t) => t.id === current.id)) return tenants;
+ return [current, ...tenants];
+}
+
+/** The name of `organizationId` among `organizations`, or null. */
+export function organizationName(
+ organizationId: string | null,
+ organizations: OrganizationName[],
+): string | null {
+ if (organizationId === null) return null;
+ return organizations.find((o) => o.id === organizationId)?.name ?? null;
+}
+
+function byName(a: string | null, b: string | null): number {
+ if (a === b) return 0;
+ if (a === null) return 1;
+ if (b === null) return -1;
+ return a.localeCompare(b);
+}
+
+/** `workspaces` in one section per organization, each headed with its name,
+ * where there is more than one organization and every one of them has a
+ * name to show. Otherwise one unheaded section: headings without names would
+ * read as several identical ones. Sections and the workspaces in each are in
+ * name order, the workspaces of no organization last. As Console's switcher
+ * decides it (`organization-groups.ts`). */
+export function switcherSections(
+ workspaces: TenantMembership[],
+ organizations: OrganizationName[],
+): { sections: WorkspaceGroup[]; headed: boolean } {
+ const sorted = [...workspaces].sort((a, b) => byName(a.name, b.name));
+ const groups = new Map<string | null, WorkspaceGroup>();
+ for (const workspace of sorted) {
+ const key = workspace.organization_id;
+ let group = groups.get(key);
+ if (group === undefined) {
+ group = { organizationId: key, name: organizationName(key, organizations), workspaces: [] };
+ groups.set(key, group);
+ }
+ group.workspaces.push(workspace);
+ }
+ const sections = [...groups.values()].sort((a, b) => {
+ if (a.organizationId === null) return 1;
+ if (b.organizationId === null) return -1;
+ return byName(a.name, b.name);
+ });
+ if (sections.length <= 1) return { sections, headed: false };
+ const named = sections.every((s) => s.organizationId === null || s.name !== null);
+ if (named) return { sections, headed: true };
+ return { sections: [{ organizationId: null, name: null, workspaces: sorted }], headed: false };
+}
+
+function counted(count: number, noun: string): string {
+ return `${count.toLocaleString("en-US")} ${noun}${count === 1 ? "" : "s"}`;
+}
+
+/** "3 users · 2 agents", for a workspace's line in the switcher. */
+export function countsLabel(counts: WorkspaceCounts): string {
+ return `${counted(counts.users, "user")} · ${counted(counts.agents, "agent")}`;
+}
diff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsx
index 9d4718141..0775eaa17 100644
--- a/gateway/src/layout/NavRail.tsx
+++ b/gateway/src/layout/NavRail.tsx
@@ -1,3 +1,4 @@
+import AccountCircleOutlined from "@mui/icons-material/AccountCircleOutlined";
import AddOutlined from "@mui/icons-material/AddOutlined";
import LockOutlined from "@mui/icons-material/LockOutlined";
import LogoutOutlined from "@mui/icons-material/LogoutOutlined";
@@ -16,7 +17,7 @@ import {
Typography,
} from "@mui/material";
import { memo, useState } from "react";
-import { NavLink, useLocation } from "react-router";
+import { NavLink, Link as RouterLink, useLocation } from "react-router";
import type { MouseEvent } from "react";
import { useAuth } from "../data/AuthContext";
import CreateWorkspaceForm from "../pages/onboarding/CreateWorkspaceForm";
@@ -102,8 +103,12 @@ export default memo(function NavRail({ layout }: { layout: Layout }) {
};
const items = railFor(layout, capabilities);
+ const isActive = (item: RailItemDefinition) =>
+ item.activeFor.some((prefix) => location.pathname.startsWith(prefix));
const current = session?.tenant ?? null;
- const others = (session?.tenants ?? []).filter((t) => t.id !== current?.id);
+ // The new layout switches workspace from the top bar's breadcrumb.
+ const others =
+ layout === "v2" ? [] : (session?.tenants ?? []).filter((t) => t.id !== current?.id);
const initial = (user?.email ?? "?").charAt(0).toUpperCase();
return (
@@ -159,30 +164,37 @@ export default memo(function NavRail({ layout }: { layout: Layout }) {
<Divider sx={{ my: 1.5, width: 29 }} />
- <Stack
- component="nav"
- aria-label="Main"
- sx={{
- width: "100%",
- alignItems: "center",
- gap: ITEM_GAP,
- // On a window shorter still, the items scroll and the account
- // button stays put; the rail is too narrow for a scrollbar.
- flex: 1,
- minHeight: 0,
- overflowY: "auto",
- overflowX: "hidden",
- scrollbarWidth: "none",
- "&::-webkit-scrollbar": { display: "none" },
- }}
- >
- {items.map((item) => (
- <RailItem
- key={item.to}
- item={item}
- active={item.activeFor.some((prefix) => location.pathname.startsWith(prefix))}
- />
- ))}
+ <Stack component="nav" aria-label="Main" sx={{ width: "100%", flex: 1, minHeight: 0 }}>
+ <Stack
+ sx={{
+ width: "100%",
+ alignItems: "center",
+ gap: ITEM_GAP,
+ // On a window shorter still, the items scroll and the account
+ // button stays put; the rail is too narrow for a scrollbar.
+ flex: 1,
+ minHeight: 0,
+ overflowY: "auto",
+ overflowX: "hidden",
+ scrollbarWidth: "none",
+ "&::-webkit-scrollbar": { display: "none" },
+ }}
+ >
+ {items
+ .filter((item) => !item.bottom)
+ .map((item) => (
+ <RailItem key={item.to} item={item} active={isActive(item)} />
+ ))}
+ </Stack>
+ {items.some((item) => item.bottom) && (
+ <Stack sx={{ width: "100%", alignItems: "center", gap: ITEM_GAP, pt: 2 }}>
+ {items
+ .filter((item) => item.bottom)
+ .map((item) => (
+ <RailItem key={item.to} item={item} active={isActive(item)} />
+ ))}
+ </Stack>
+ )}
</Stack>
<Stack sx={{ width: "100%", alignItems: "center", gap: 2, pt: 2 }}>
@@ -228,14 +240,26 @@ export default memo(function NavRail({ layout }: { layout: Layout }) {
)}
</Box>
<Divider sx={{ my: 0.5 }} />
- <Box sx={{ px: 1.5, pt: 0.5, pb: 0.25 }}>
- <Typography variant="caption" sx={{ color: "text.secondary" }}>
- Workspace
- </Typography>
- <Typography variant="body2" sx={{ fontWeight: 500 }} noWrap>
- {current?.name}
- </Typography>
- </Box>
+ {layout === "v2" ? (
+ <MenuItem
+ component={RouterLink}
+ to="/settings/account"
+ onClick={() => setAnchor(null)}
+ sx={{ gap: 1 }}
+ >
+ <AccountCircleOutlined sx={{ fontSize: 16 }} />
+ Your account
+ </MenuItem>
+ ) : (
+ <Box sx={{ px: 1.5, pt: 0.5, pb: 0.25 }}>
+ <Typography variant="caption" sx={{ color: "text.secondary" }}>
+ Workspace
+ </Typography>
+ <Typography variant="body2" sx={{ fontWeight: 500 }} noWrap>
+ {current?.name}
+ </Typography>
+ </Box>
+ )}
{others.map((tenant) => (
<MenuItem
key={tenant.id}
diff --git a/gateway/src/layout/PageShell.tsx b/gateway/src/layout/PageShell.tsx
index 5cde7be3b..7a0afef1e 100644
--- a/gateway/src/layout/PageShell.tsx
+++ b/gateway/src/layout/PageShell.tsx
@@ -1,14 +1,18 @@
import { Alert, Box, Button, Stack } from "@mui/material";
-import { Outlet } from "react-router";
+import { Outlet, useLocation } from "react-router";
import { useAuth } from "../data/AuthContext";
-import type { Layout } from "../routes/routeTable";
+import { type Layout, areaOf } from "../routes/routeTable";
import NavRail from "./NavRail";
import TopBar from "./TopBar";
/** Hoot's signature shell: a narrow icon rail and a slim top bar sitting bare on
* the warm canvas, framing a single rounded content surface. Chrome recedes so
- * the content is the hero — an "app within a surface", not edge-to-edge chrome. */
+ * the content is the hero — an "app within a surface", not edge-to-edge chrome.
+ * The new layout's organization settings are a place of their own, outside
+ * the workspace: no rail there, and the top bar leads back. */
export default function PageShell({ layout }: { layout: Layout }) {
+ const { pathname } = useLocation();
+ const withRail = areaOf(pathname, layout) !== "organization";
return (
<Box
sx={{
@@ -18,9 +22,18 @@ export default function PageShell({ layout }: { layout: Layout }) {
backgroundColor: "var(--hoot-canvas)",
}}
>
- <NavRail layout={layout} />
- <Stack sx={{ flex: 1, minWidth: 0, overflow: "hidden", pr: "var(--surface-gutter)", pb: "var(--surface-gutter)" }}>
- <TopBar />
+ {withRail && <NavRail layout={layout} />}
+ <Stack
+ sx={{
+ flex: 1,
+ minWidth: 0,
+ overflow: "hidden",
+ pl: withRail ? 0 : "var(--surface-gutter)",
+ pr: "var(--surface-gutter)",
+ pb: "var(--surface-gutter)",
+ }}
+ >
+ <TopBar layout={layout} />
<Stack
component="main"
sx={{
diff --git a/gateway/src/layout/TopBar.tsx b/gateway/src/layout/TopBar.tsx
index ef5632e61..623a469d8 100644
--- a/gateway/src/layout/TopBar.tsx
+++ b/gateway/src/layout/TopBar.tsx
@@ -1,7 +1,20 @@
+import ChevronLeftOutlined from "@mui/icons-material/ChevronLeftOutlined";
+import ExpandMoreOutlined from "@mui/icons-material/ExpandMoreOutlined";
+import HelpOutlineOutlined from "@mui/icons-material/HelpOutlineOutlined";
import MenuBookOutlined from "@mui/icons-material/MenuBookOutlined";
-import { Box, Button, Stack, Tooltip, Typography } from "@mui/material";
-import { useLocation } from "react-router";
+import { Alert, Box, Button, Snackbar, Stack, Typography } from "@mui/material";
+import { useEffect, useState } from "react";
+import type { MouseEvent, ReactNode } from "react";
+import { Link as RouterLink, useLocation } from "react-router";
import { useAuth } from "../data/AuthContext";
+import {
+ type OrganizationName,
+ loadOrganizationNames,
+ organizationName,
+} from "../data/workspaceSwitcher";
+import CreateInvitationDialog from "../pages/workspace/CreateInvitationDialog";
+import { type Layout, areaOf } from "../routes/routeTable";
+import WorkspaceMenu from "./WorkspaceMenu";
const SECTION_LABELS: [prefix: string, label: string][] = [
["/ecosystem", "Ecosystem"],
@@ -26,14 +39,192 @@ const SECTION_LABELS: [prefix: string, label: string][] = [
];
const DOCS_URL = "https://docs.switchagents.ai/switch-rooms/getting-started";
+const HELP_URL = "https://docs.switchagents.ai/switch-rooms/resources/troubleshooting";
-export default function TopBar() {
- const { pathname } = useLocation();
+const CRUMB_TEXT = { fontSize: "0.9375rem", fontWeight: 500, letterSpacing: "-0.02em" };
+
+function Separator() {
+ return (
+ <Box component="span" sx={{ opacity: 0.4, mx: 1 }}>
+ /
+ </Box>
+ );
+}
+
+function PageLabel({ label }: { label: string | undefined }) {
+ if (label === undefined) return null;
+ return (
+ <>
+ <Separator />
+ <Box component="span" sx={{ fontWeight: 700 }}>
+ {label}
+ </Box>
+ </>
+ );
+}
+
+/** Today's breadcrumb: Switch, the workspace, the page. */
+function CurrentCrumbs({ section }: { section: string | undefined }) {
const { session } = useAuth();
- const section = SECTION_LABELS.find(([prefix]) => pathname.startsWith(prefix))?.[1];
const crumbs = [session?.tenant?.name, section].filter(
(crumb): crumb is string => Boolean(crumb),
);
+ return (
+ <Typography sx={{ ...CRUMB_TEXT, px: 2 }}>
+ Switch
+ {crumbs.map((crumb, i) => (
+ <Box component="span" key={i}>
+ <Separator />
+ <Box component="span" sx={{ fontWeight: i === crumbs.length - 1 ? 700 : 500 }}>
+ {crumb}
+ </Box>
+ </Box>
+ ))}
+ </Typography>
+ );
+}
+
+/** The new layout's breadcrumb: "Organization / Workspace", which opens the
+ * workspace switcher, then the page. In organization settings, the way back
+ * to the workspace instead. */
+function WorkspaceCrumbs({
+ section,
+ inOrganizationSettings,
+}: {
+ section: string | undefined;
+ inOrganizationSettings: boolean;
+}) {
+ const { session, switchTo } = useAuth();
+ const [organizations, setOrganizations] = useState<OrganizationName[]>([]);
+ const [organizationsError, setOrganizationsError] = useState<string | null>(null);
+ const [anchor, setAnchor] = useState<HTMLElement | null>(null);
+ const [inviteOpen, setInviteOpen] = useState(false);
+ const [switchError, setSwitchError] = useState<string | null>(null);
+
+ const tenant = session?.tenant ?? null;
+ const currentOrganizationId = tenant?.organization_id ?? null;
+ useEffect(() => {
+ let cancelled = false;
+ loadOrganizationNames(currentOrganizationId).then(
+ (rows) => {
+ if (!cancelled) setOrganizations(rows);
+ },
+ (err: unknown) => {
+ if (!cancelled) {
+ setOrganizationsError(err instanceof Error ? err.message : "Could not load them");
+ }
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [currentOrganizationId]);
+
+ const switchWorkspace = async (tenantId: string) => {
+ setAnchor(null);
+ try {
+ await switchTo(tenantId);
+ } catch (err) {
+ setSwitchError(err instanceof Error ? err.message : "Could not switch workspace");
+ }
+ };
+
+ const organization = organizationName(currentOrganizationId, organizations);
+
+ let crumbs: ReactNode;
+ if (inOrganizationSettings) {
+ crumbs = (
+ <Button
+ component={RouterLink}
+ to="/"
+ color="inherit"
+ startIcon={<ChevronLeftOutlined sx={{ fontSize: 18 }} />}
+ sx={{ ...CRUMB_TEXT, px: 1 }}
+ >
+ Back to workspace
+ </Button>
+ );
+ } else {
+ crumbs = (
+ <Button
+ color="inherit"
+ aria-haspopup="menu"
+ aria-expanded={anchor !== null}
+ onClick={(e: MouseEvent<HTMLElement>) => setAnchor(e.currentTarget)}
+ endIcon={<ExpandMoreOutlined sx={{ fontSize: 18 }} />}
+ sx={{ ...CRUMB_TEXT, px: 1, textTransform: "none", minWidth: 0 }}
+ >
+ {organization !== null && (
+ <>
+ <Box component="span" sx={{ color: "text.secondary" }}>
+ {organization}
+ </Box>
+ <Separator />
+ </>
+ )}
+ {tenant?.name}
+ </Button>
+ );
+ }
+
+ return (
+ <Stack direction="row" sx={{ alignItems: "center", px: 1, minWidth: 0 }}>
+ {crumbs}
+ <Typography component="span" sx={CRUMB_TEXT}>
+ <PageLabel label={section} />
+ </Typography>
+
+ <WorkspaceMenu
+ anchor={anchor}
+ onClose={() => setAnchor(null)}
+ organizations={organizations}
+ organizationsError={organizationsError}
+ onSwitch={switchWorkspace}
+ onInvite={() => {
+ setAnchor(null);
+ setInviteOpen(true);
+ }}
+ />
+ {tenant !== null && (
+ <CreateInvitationDialog
+ open={inviteOpen}
+ tenantId={tenant.id}
+ emailEnabled={session?.invite_email_enabled ?? false}
+ onClose={() => setInviteOpen(false)}
+ onCreated={() => {}}
+ />
+ )}
+ <Snackbar
+ open={switchError !== null}
+ onClose={() => setSwitchError(null)}
+ anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
+ >
+ <Alert severity="error" onClose={() => setSwitchError(null)}>
+ {switchError}
+ </Alert>
+ </Snackbar>
+ </Stack>
+ );
+}
+
+function LinkButton({ href, icon, children }: { href: string; icon: ReactNode; children: string }) {
+ return (
+ <Button
+ color="inherit"
+ href={href}
+ target="_blank"
+ rel="noreferrer"
+ startIcon={icon}
+ sx={{ fontWeight: 500 }}
+ >
+ {children}
+ </Button>
+ );
+}
+
+export default function TopBar({ layout }: { layout: Layout }) {
+ const { pathname } = useLocation();
+ const section = SECTION_LABELS.find(([prefix]) => pathname.startsWith(prefix))?.[1];
return (
<Stack
@@ -46,46 +237,24 @@ export default function TopBar() {
pr: 1,
}}
>
- <Typography sx={{ fontSize: "0.9375rem", fontWeight: 500, letterSpacing: "-0.02em", px: 2 }}>
- Switch
- {crumbs.map((crumb, i) => (
- <Box component="span" key={i}>
- <Box component="span" sx={{ opacity: 0.4, mx: 1 }}>
- /
- </Box>
- <Box component="span" sx={{ fontWeight: i === crumbs.length - 1 ? 700 : 500 }}>
- {crumb}
- </Box>
- </Box>
- ))}
- </Typography>
+ {layout === "v2" ? (
+ <WorkspaceCrumbs
+ section={section}
+ inOrganizationSettings={areaOf(pathname, layout) === "organization"}
+ />
+ ) : (
+ <CurrentCrumbs section={section} />
+ )}
<Stack direction="row" sx={{ alignItems: "center", gap: 1 }}>
- <Tooltip title="All Switch services are reachable">
- <Stack direction="row" sx={{ alignItems: "center", gap: 0.75, px: 1 }}>
- <Box
- sx={{
- width: 6,
- height: 6,
- borderRadius: "50%",
- backgroundColor: "var(--hoot-success)",
- }}
- />
- <Typography variant="body2" sx={{ color: "text.secondary" }}>
- System healthy
- </Typography>
- </Stack>
- </Tooltip>
- <Button
- color="inherit"
- href={DOCS_URL}
- target="_blank"
- rel="noreferrer"
- startIcon={<MenuBookOutlined sx={{ fontSize: 18 }} />}
- sx={{ fontWeight: 500 }}
- >
+ {layout === "v2" && (
+ <LinkButton href={HELP_URL} icon={<HelpOutlineOutlined sx={{ fontSize: 18 }} />}>
+ Help
+ </LinkButton>
+ )}
+ <LinkButton href={DOCS_URL} icon={<MenuBookOutlined sx={{ fontSize: 18 }} />}>
Docs
- </Button>
+ </LinkButton>
</Stack>
</Stack>
);
diff --git a/gateway/src/layout/WorkspaceMenu.tsx b/gateway/src/layout/WorkspaceMenu.tsx
new file mode 100644
index 000000000..17f3f8887
--- /dev/null
+++ b/gateway/src/layout/WorkspaceMenu.tsx
@@ -0,0 +1,147 @@
+import CheckOutlined from "@mui/icons-material/CheckOutlined";
+import PersonAddOutlined from "@mui/icons-material/PersonAddOutlined";
+import {
+ Alert,
+ Box,
+ Divider,
+ ListSubheader,
+ Menu,
+ MenuItem,
+ Typography,
+} from "@mui/material";
+import { useEffect, useState } from "react";
+import { type WorkspaceCounts, fetchWorkspaceCounts } from "../data/api";
+import { useAuth } from "../data/AuthContext";
+import {
+ type OrganizationName,
+ countsLabel,
+ switcherSections,
+ switcherWorkspaces,
+} from "../data/workspaceSwitcher";
+
+type CountsState =
+ | { status: "loading" }
+ | { status: "loaded"; byId: Map<string, WorkspaceCounts> }
+ | { status: "failed"; message: string };
+
+/** The workspace switcher the top bar's breadcrumb opens: the workspaces this
+ * person may enter, by organization, with how many users and agents each
+ * has, read when it opens. An admin of the current workspace may invite
+ * people to it from here. */
+export default function WorkspaceMenu({
+ anchor,
+ onClose,
+ organizations,
+ organizationsError,
+ onSwitch,
+ onInvite,
+}: {
+ anchor: HTMLElement | null;
+ onClose: () => void;
+ organizations: OrganizationName[];
+ organizationsError: string | null;
+ onSwitch: (tenantId: string) => void;
+ onInvite: () => void;
+}) {
+ const { session, capabilities } = useAuth();
+ const open = anchor !== null;
+ const [counts, setCounts] = useState<CountsState>({ status: "loading" });
+
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ setCounts({ status: "loading" });
+ fetchWorkspaceCounts().then(
+ (rows) => {
+ if (!cancelled) setCounts({ status: "loaded", byId: new Map(rows.map((r) => [r.id, r])) });
+ },
+ (err: unknown) => {
+ if (!cancelled) {
+ setCounts({
+ status: "failed",
+ message: err instanceof Error ? err.message : "Could not load the counts",
+ });
+ }
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [open]);
+
+ const current = session?.tenant ?? null;
+ const { sections, headed } = switcherSections(
+ switcherWorkspaces(current, session?.tenants ?? []),
+ organizations,
+ );
+
+ const countsOf = (id: string): string => {
+ if (counts.status === "loading") return "…";
+ if (counts.status === "failed") return "";
+ const found = counts.byId.get(id);
+ return found === undefined ? "" : countsLabel(found);
+ };
+
+ return (
+ <Menu
+ anchorEl={anchor}
+ open={open}
+ onClose={onClose}
+ anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
+ transformOrigin={{ vertical: "top", horizontal: "left" }}
+ slotProps={{ paper: { sx: { width: 300, p: 0.5 } }, list: { "aria-label": "Workspaces" } }}
+ >
+ {organizationsError !== null && (
+ <Alert severity="warning" sx={{ mx: 0.5, mb: 0.5 }}>
+ Could not load the organizations' names: {organizationsError}
+ </Alert>
+ )}
+ {counts.status === "failed" && (
+ <Alert severity="warning" sx={{ mx: 0.5, mb: 0.5 }}>
+ Could not load how many users and agents each workspace has: {counts.message}
+ </Alert>
+ )}
+ {sections.flatMap((section) => [
+ ...(headed
+ ? [
+ <ListSubheader
+ key={`organization:${section.organizationId ?? "none"}`}
+ sx={{ lineHeight: "32px", backgroundColor: "transparent" }}
+ >
+ {section.name ?? "No organization"}
+ </ListSubheader>,
+ ]
+ : []),
+ ...section.workspaces.map((workspace) => {
+ const isCurrent = workspace.id === current?.id;
+ return (
+ <MenuItem
+ key={workspace.id}
+ selected={isCurrent}
+ aria-current={isCurrent ? "true" : undefined}
+ onClick={() => (isCurrent ? onClose() : onSwitch(workspace.id))}
+ sx={{ gap: 1, borderRadius: 1 }}
+ >
+ <Box sx={{ flex: 1, minWidth: 0 }}>
+ <Typography variant="body2" sx={{ fontWeight: 500 }} noWrap>
+ {workspace.name}
+ </Typography>
+ <Typography variant="caption" sx={{ color: "text.secondary" }} noWrap>
+ {countsOf(workspace.id)}
+ </Typography>
+ </Box>
+ {isCurrent && <CheckOutlined sx={{ fontSize: 16 }} />}
+ </MenuItem>
+ );
+ }),
+ ])}
+ {capabilities.administersWorkspace && current !== null && [
+ <Divider key="divider" sx={{ my: 0.5 }} />,
+ <MenuItem key="invite" onClick={onInvite} sx={{ gap: 1, borderRadius: 1 }}>
+ <PersonAddOutlined sx={{ fontSize: 16 }} />
+ Invite people to {current.name}
+ </MenuItem>,
+ ]}
+ </Menu>
+ );
+}
diff --git a/gateway/src/routes/routeTable.test.ts b/gateway/src/routes/routeTable.test.ts
new file mode 100644
index 000000000..95d0b3d1f
--- /dev/null
+++ b/gateway/src/routes/routeTable.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import { RAIL, areaOf, routesFor } from "./routeTable";
+
+describe("the new layout's reach", () => {
+ it("answers every URL of today's layout, with a page or a redirect", () => {
+ const v2 = new Set(routesFor("v2").map((route) => route.path));
+ const missing = routesFor("current")
+ .filter((route) => route.kind === "page")
+ .map((route) => route.path)
+ .filter((path) => !v2.has(path));
+ expect(missing).toEqual([]);
+ });
+
+ it("keeps only the settings areas at the foot of the rail", () => {
+ expect(RAIL.v2.filter((item) => item.bottom).map((item) => item.to)).toEqual([
+ "/settings",
+ "/platform",
+ ]);
+ expect(RAIL.current.some((item) => item.bottom)).toBe(false);
+ });
+});
+
+describe("areaOf", () => {
+ it("names the settings area a page is in", () => {
+ expect(areaOf("/settings/org/users", "v2")).toBe("organization");
+ expect(areaOf("/settings/org", "v2")).toBe("organization");
+ expect(areaOf("/usage", "v2")).toBe("workspace");
+ expect(areaOf("/platform/users", "v2")).toBe("platform");
+ });
+
+ it("names none for a page outside them, or a URL that only redirects", () => {
+ expect(areaOf("/rooms", "v2")).toBeNull();
+ expect(areaOf("/usage", "current")).toBeNull();
+ expect(areaOf("/settings/org", "current")).toBeNull();
+ });
+});
diff --git a/gateway/src/routes/routeTable.tsx b/gateway/src/routes/routeTable.tsx
index 4298c53fa..ac9579485 100644
--- a/gateway/src/routes/routeTable.tsx
+++ b/gateway/src/routes/routeTable.tsx
@@ -343,6 +343,16 @@ export function accessTo(path: string, layout: Layout, caps: Capabilities): Acce
: allOf(AREAS[route.area].access, route.access)(caps);
}
+/** The settings area `pathname` (a page's own URL) is in, in `layout`, or
+ * null when it is in none. */
+export function areaOf(pathname: string, layout: Layout): SettingsArea | null {
+ for (const route of routesFor(layout)) {
+ if (route.kind === "redirect" || route.path !== pathname) continue;
+ return route.area ?? null;
+ }
+ return null;
+}
+
/** The pages of `area`'s menu that `caps` may open, in order. */
export function menuOf(
area: SettingsArea,
@@ -364,15 +374,18 @@ export interface RailItem {
icon: ComponentType<{ sx?: object }>;
/** The paths under which the item shows as the current one. */
activeFor: readonly string[];
+ /** Kept at the foot of the rail, beside the account button: an area for
+ * settings rather than for work. */
+ bottom: boolean;
}
function railItem(
label: string,
to: string,
icon: ComponentType<{ sx?: object }>,
- activeFor: readonly string[] = [to],
+ { activeFor = [to], bottom = false }: { activeFor?: readonly string[]; bottom?: boolean } = {},
): RailItem {
- return { label, to, icon, activeFor };
+ return { label, to, icon, activeFor, bottom };
}
/** The rail, in order, for each layout. An item shows only to someone who may
@@ -402,8 +415,11 @@ export const RAIL: Record<Layout, readonly RailItem[]> = {
railItem("Connectors", "/connectors", PowerOutlined),
railItem("Resources", "/resources", FolderOutlined),
railItem("Ecosystem", "/ecosystem", AccountTreeOutlined),
- railItem("Settings", "/settings", SettingsOutlined, ["/settings", "/usage"]),
- railItem("Platform", "/platform", AdminPanelSettingsOutlined),
+ railItem("Settings", "/settings", SettingsOutlined, {
+ activeFor: ["/settings", "/usage"],
+ bottom: true,
+ }),
+ railItem("Platform", "/platform", AdminPanelSettingsOutlined, { bottom: true }),
],
};