Skip to content

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

Gate the gateway's pages and actions on capabilities, with the new layout behind gateway_v2, and Switch's own words (CHOO-4073, CHOO-4076) (#1567)

Christian McDermottc74f496bcb7b
diff --git a/.env.example b/.env.example
index 6c6d09552..3184f10a3 100644
--- a/.env.example
+++ b/.env.example
@@ -188,6 +188,8 @@ CONTROLLER_TOKEN_SECRET=
# buddy_slack_handoff switch-buddy's welcome moves to a private
# channel on the team's chat app (turn on only
# once every switch-core process has it)
+# gateway_v2 the dashboard's new layout (still being built:
+# turn on for development and staging only)
FEATURE_FLAGS_ENABLED=
# ── Service connections ──────────────────────────────────────────────────────
diff --git a/.github/workflows/agent-controller-release.yml b/.github/workflows/agent-controller-release.yml
index 56fcac383..ca3049647 100644
--- a/.github/workflows/agent-controller-release.yml
+++ b/.github/workflows/agent-controller-release.yml
@@ -113,5 +113,5 @@ jobs:
--title "switch-agent-controller $VERSION" \
--notes "The Switch agent controller $VERSION, for running managed agents on your own Linux or macOS machines.
- Install (Node 22.13 or later) with \`install.sh\`, which checks the package's signature (\`switch-agent-controller-$VERSION.tgz.sig\`) before installing it. Then enroll with a code from the Machines page and run \`switch-agent-controller install-service\`. An installed controller updates with \`switch-agent-controller update\`." \
+ Install (Node 22.13 or later) with \`install.sh\`, which checks the package's signature (\`switch-agent-controller-$VERSION.tgz.sig\`) before installing it. Then enroll with a code from the Devices page and run \`switch-agent-controller install-service\`. An installed controller updates with \`switch-agent-controller update\`." \
--latest=false
diff --git a/.github/workflows/switch-release.yml b/.github/workflows/switch-release.yml
index 98d9fb28b..79995451b 100644
--- a/.github/workflows/switch-release.yml
+++ b/.github/workflows/switch-release.yml
@@ -502,7 +502,7 @@ jobs:
SHA-256: \`$SHA256\`
- Install (Node 22.13 or later) with \`install.sh\`, which checks the package's signature (\`switch-agent-controller-$VERSION.tgz.sig\`) before installing it. Then enroll with a code from the Machines page and run \`switch-agent-controller install-service\`. A controller connected to Switch $VERSION updates to this release on its own once it is idle." \
+ Install (Node 22.13 or later) with \`install.sh\`, which checks the package's signature (\`switch-agent-controller-$VERSION.tgz.sig\`) before installing it. Then enroll with a code from the Devices page and run \`switch-agent-controller install-service\`. A controller connected to Switch $VERSION updates to this release on its own once it is idle." \
--latest=false
chart:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8b1a5e8e..07854ff2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -245,6 +245,14 @@ version of their own to them without also giving them a release of their own.
still only needs write access to the room.
#### Added
+- **The dashboard's new layout, behind the `gateway_v2` flag.** Overview,
+ Templates and Connectors on the rail; Workspace and Organization settings
+ as areas of their own, each with a menu of only the pages you may open,
+ reopening the page you last used; and the operator's pages under Platform.
+ Today's pages move into it, and their old URLs lead there. It is still
+ being built, so turn it on for development and staging only. With it off,
+ the dashboard is laid out as before, and the new URLs lead back to today's
+ pages.
- **The gateway says what the caller may do with every object it shows**, so
no page works a permission out for itself. Alongside the room, template and
agent flags already there:
@@ -471,6 +479,20 @@ version of their own to them without also giving them a release of their own.
compares it only when someone signs in.
#### Changed
+- **The dashboard, and what Switch tells people, use Switch's own words.** A
+ computer that runs agents is a device, not a machine; an outside service is
+ a connector, and a chat app a messaging app, not a connection; a person is a
+ user, with "member" kept for the role; and nothing calls Switch a server.
+ Dashboard labels are in sentence case. **Register Agent** is now **Add
+ agent**, **Register messaging app** is **Add messaging app**, and the API
+ keys page lists **Keys for adding agents** and **Agent keys**. The same
+ words reach the errors, refusals and status the server sends to the
+ dashboard, Switch Console and chat, and messages that sent people to
+ "Settings, Connections" in Switch Console now point to **Connectors**, where
+ that page is. Text written for agents still names their tools, such as
+ `list_machines`, and Switch Console's own cloud-machine messages are
+ unchanged for now. A dashboard test fails on the old words, naming what to
+ write instead.
- **Admins step down and leave from their own row.** The workspace and
organization members pages offer changing your own role and leaving, while
another admin remains; the last one is refused, as before. Leaving the
@@ -818,6 +840,34 @@ version of their own to them without also giving them a release of their own.
token again; revocation is still checked on every request.
#### Fixed
+- **The dashboard's addressing policy editor judges rules as the server
+ does.** A rule letting in only the agent's owner, or its owner's agents,
+ was taken for one that lets in nobody, and Save was held; the editor now
+ shows both choices, and says why a rule can never let anyone in in the
+ server's own words. A restricted policy with no rules lets anyone address
+ the agent, as documented, though the editor said it let in nobody:
+ choosing Restricted now starts with an owner-only rule, the last rule
+ cannot be removed, and a policy saved with no rules shows as Open.
+- **A dashboard page someone may not open says so instead of loading.**
+ Typing the address of a page they may not open, or one the server does
+ not run, loaded it into a column of refusals; it now says why. A member
+ could open the operator's Users page; it is refused now.
+- **The dashboard offers each action only where the server would allow it.**
+ Every action follows the server's own answer for that thing, rather than
+ the dashboard's guess from someone's role or ownership. An organization
+ admin was offered Delete workspace in a workspace they are not an admin
+ member of, and was refused. Anyone may edit a publicly writable
+ reference, document or package, but only its owner and admins were
+ offered the fields. An agent that cannot be handed over now says why
+ beside a disabled Transfer.
+- **A bridged room's description can be edited.** It was locked, though
+ nothing sets it from the channel; whoever may write to the room can now
+ edit it, as on any other room.
+- **The dashboard reads the server's feature flags instead of guessing.**
+ Agent management, connectors and organization connector apps were taken
+ to be off when a page answered "not found"; they are now read from the
+ server's flags, and if those cannot be read the dashboard says so rather
+ than hiding pages.
- **Two organization admins demoting or removing each other at once** could
leave the refused one without their keys and connections in the workspaces
they reached as an organization admin: those were taken away before the
@@ -4965,6 +5015,9 @@ tags; see RELEASING.md.
can run (16 by default).
#### Changed
+- **Points to the dashboard's Devices page.** Its messages, installer and
+ README sent people to the Machines page, which the dashboard now calls
+ Devices.
- **Agents' operations go to Switch on the controller's socket.** Every
operation an agent host calls through the relay
(`POST /agents/{id}/ops/{operation}`) is sent as a call on the socket the
diff --git a/console/packages/agent-controller/README.md b/console/packages/agent-controller/README.md
index a54d29682..9a47a51cf 100644
--- a/console/packages/agent-controller/README.md
+++ b/console/packages/agent-controller/README.md
@@ -46,7 +46,7 @@ relay accepts.
Each `switch-agent-controller-v*` release on GitHub carries one npm package, the CLI
and the shared-host bundle it runs agents with, with no dependencies. The gateway's
-Machines page shows the one command that installs it, enrolls the machine and starts
+Devices page shows the one command that installs it, enrolls the machine and starts
it as a service:
```bash
@@ -99,7 +99,7 @@ switch-agent-controller update [--check]
through the controller's relay.
- `--name` defaults to the host name.
- `--description` says what the machine is for (optional, at most 500
- characters). Its owner sees it in the gateway's Machines page, where both the
+ characters). Its owner sees it in the gateway's Devices page, where both the
name and the description can be changed later, and so do the agents allowed
to manage agents for that owner.
- `set-info` changes the machine's name and/or description on the server after
diff --git a/console/packages/agent-controller/install.sh b/console/packages/agent-controller/install.sh
index 7966f8551..36d699bd9 100755
--- a/console/packages/agent-controller/install.sh
+++ b/console/packages/agent-controller/install.sh
@@ -7,9 +7,9 @@
# curl -fsSL <url of this file> | sh -s -- --server <Switch API URL> --code <code> [--name <name>] [--description <text>]
#
# Options:
-# --server <url> --code <code> Enroll with a one-time code from the Machines page.
+# --server <url> --code <code> Enroll with a one-time code from the Devices page.
# --name <name> The machine's name in Switch (default: the host name).
-# --description <text> What the machine is for, shown on the Machines page.
+# --description <text> What the machine is for, shown on the Devices page.
# --data-dir <dir> Keep the controller's state here rather than in the default folder.
# --no-service Enroll, but do not install the service.
# --version <x.y.z> Install this release rather than the newest.
@@ -183,7 +183,7 @@ path_note() {
if [ -z "$SERVER" ]; then
echo
- echo "Installed $("$BIN" --version). Next, with a code from the Machines page in Switch:"
+ echo "Installed $("$BIN" --version). Next, with a code from the Devices page in Switch:"
echo " switch-agent-controller enroll --server <Switch API URL> --code <code>"
echo " switch-agent-controller install-service"
echo "Check this machine with: switch-agent-controller doctor"
diff --git a/console/packages/agent-controller/src/api.ts b/console/packages/agent-controller/src/api.ts
index bd564f50c..c90b132d2 100644
--- a/console/packages/agent-controller/src/api.ts
+++ b/console/packages/agent-controller/src/api.ts
@@ -391,7 +391,7 @@ export class ControllerClient {
throw new ControllerApiError(
error.status,
'not_supported',
- "This Switch server cannot rename a machine from its controller. Change the name and description in the gateway's Machines page instead.",
+ "This Switch server cannot rename a machine from its controller. Change the name and description in the gateway's Devices page instead.",
false,
null
);
diff --git a/console/packages/agent-controller/src/doctor.ts b/console/packages/agent-controller/src/doctor.ts
index b0868f580..6cd7d8abb 100644
--- a/console/packages/agent-controller/src/doctor.ts
+++ b/console/packages/agent-controller/src/doctor.ts
@@ -53,7 +53,7 @@ async function serverChecks(inputs: DoctorInputs): Promise<Check[]> {
{
name: 'Enrollment',
status: 'fail',
- detail: `${inputs.dataDir} is not enrolled. Run: switch-agent-controller enroll --server <url> --code <code>, with a code from the Machines page.`,
+ detail: `${inputs.dataDir} is not enrolled. Run: switch-agent-controller enroll --server <url> --code <code>, with a code from the Devices page.`,
},
];
const { identity } = inputs;
diff --git a/console/packages/agent-controller/src/main.ts b/console/packages/agent-controller/src/main.ts
index b56ad047a..498d4e4f3 100644
--- a/console/packages/agent-controller/src/main.ts
+++ b/console/packages/agent-controller/src/main.ts
@@ -359,7 +359,7 @@ async function setInfoCommand(args: string[]): Promise<number> {
const credential = await secrets.get(CONTROLLER_CREDENTIAL);
if (!credential)
throw new ConfigurationError(
- `${dataDir} holds no controller credential (it is handed over at run time, or was removed). Change the name and description in the gateway's Machines page instead.`
+ `${dataDir} holds no controller credential (it is handed over at run time, or was removed). Change the name and description in the gateway's Devices page instead.`
);
const log = createLogger({
level: process.env.SWITCH_CONTROLLER_LOG_LEVEL,
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.py
index c010259ce..4c8f71952 100644
--- a/core/switch_core/accounts/deletion.py
+++ b/core/switch_core/accounts/deletion.py
@@ -317,8 +317,8 @@ class AccountDeletion:
"""Why the account cannot be deleted now, or None when it can."""
if is_server_administrator(user, self.admin_email):
return (
- "This is the server's administrator account, which can't be "
- "deleted. The server recreates it every time it starts."
+ "This is Switch's administrator account, which can't be "
+ "deleted. Switch recreates it every time it starts."
)
machine = await session.scalar(
select(CloudMachine.id).where(
@@ -357,7 +357,7 @@ class AccountDeletion:
):
return (
f"You're the only admin of {workspace.name}, which has other "
- "members. Make one of them an admin first."
+ "users. Make one of them an admin first."
)
if alone:
platform = await session.scalar(
@@ -399,7 +399,7 @@ class AccountDeletion:
return None
return (
f"You're the only organization admin of {organization.name}, which "
- "has other members. Make one of them an organization admin first."
+ "has other users. Make one of them an organization admin first."
)
async def delete(
@@ -493,7 +493,7 @@ class AccountDeletion:
assert organization is not None
raise AccountDeletionRefused(
f"You're the only organization admin of {organization.name}, "
- "which has other members. Make one of them an "
+ "which has other users. Make one of them an "
"organization admin first."
)
for organization_id, session in held:
diff --git a/core/switch_core/accounts/transfer.py b/core/switch_core/accounts/transfer.py
index b1dbfb251..7d6904a08 100644
--- a/core/switch_core/accounts/transfer.py
+++ b/core/switch_core/accounts/transfer.py
@@ -220,18 +220,18 @@ def agent_transfer_refusal(facts: AgentTransferFacts, *, to_owner: bool) -> str
if facts.granted_services:
if to_owner:
return (
- "This agent uses your own connections to "
+ "This agent uses your own connectors for "
f"{', '.join(facts.granted_services)}. Remove its service access "
"first; the new owner can then grant their own."
)
return (
- "This agent uses its owner's own connections. Its owner has to "
+ "This agent uses its owner's own connectors. Its owner has to "
"remove its service access first; the new owner can then grant "
"their own."
)
if facts.managed:
return (
- "This agent is managed on its owner's machine, with their sign-ins, "
+ "This agent is managed on its owner's device, with their sign-ins, "
"and can't be transferred."
)
if facts.may_manage_agents:
@@ -247,8 +247,8 @@ def agent_transfer_refusal(facts: AgentTransferFacts, *, to_owner: bool) -> str
)
if facts.run_by_server_connector:
return (
- "This agent is run by a server connector, which registers it again "
- "under its own owner whenever the server starts, so it can't be "
+ "This agent is run by Switch itself, which registers it again "
+ "under its own owner whenever Switch starts, so it can't be "
"transferred."
)
return None
diff --git a/core/switch_core/accounts/workspace_deletion.py b/core/switch_core/accounts/workspace_deletion.py
index bf664872e..3dbbb541e 100644
--- a/core/switch_core/accounts/workspace_deletion.py
+++ b/core/switch_core/accounts/workspace_deletion.py
@@ -161,13 +161,13 @@ REFUSED: dict[str, tuple[str, str]] = {
"documents": ("document", "documents"),
"templates": ("template", "templates"),
"room_groups": ("room group", "room groups"),
- "messaging_installs": ("messaging app connection", "messaging app connections"),
- "collaboration_bridges": ("messaging bridge", "messaging bridges"),
- "machine_workspaces": ("cloud machine", "cloud machines"),
- "agent_controllers": ("machine", "machines"),
- "server_connectors": ("server connector", "server connectors"),
+ "messaging_installs": ("installed app", "installed apps"),
+ "collaboration_bridges": ("messaging app", "messaging apps"),
+ "machine_workspaces": ("cloud device", "cloud devices"),
+ "agent_controllers": ("device", "devices"),
+ "server_connectors": ("agent run by Switch", "agents run by Switch"),
"skills": ("skill", "skills"),
- "service_connections": ("service connection", "service connections"),
+ "service_connections": ("connector", "connectors"),
}
@@ -252,7 +252,7 @@ async def remaining(session: AsyncSession, tenant_id: str, owner_id: str) -> lis
.where(members.c.tenant_id == tenant_id, members.c.user_id != owner_id)
)
if others:
- left.append(_counted(others, ("other member", "other members")))
+ left.append(_counted(others, ("other user", "other users")))
return left
@@ -260,7 +260,7 @@ async def refusal(session: AsyncSession, tenant_id: str, owner_id: str) -> str |
"""Why the workspace cannot be deleted now, or None when it can."""
if tenant_id == TENANT_ZERO_ID:
return (
- "This is the server's default workspace, where new accounts start. "
+ "This is Switch's default workspace, where new accounts start. "
"It can't be deleted."
)
left = await remaining(session, tenant_id, owner_id)
diff --git a/core/switch_core/agent_icon.py b/core/switch_core/agent_icon.py
index b36588b7f..11926405e 100644
--- a/core/switch_core/agent_icon.py
+++ b/core/switch_core/agent_icon.py
@@ -259,7 +259,7 @@ def refuse_third_party_avatar(
"""
if url is not None and not third_party_avatars and is_third_party_avatar(url):
_reject(
- "this server has third-party avatars turned off, so an icon from "
+ "third-party avatars are turned off here, so an icon from "
"dicebear.com or ui-avatars.com would never be shown; link an image "
"on another host"
)
diff --git a/core/switch_core/agent_template_ops.py b/core/switch_core/agent_template_ops.py
index 651b34d77..42e487954 100644
--- a/core/switch_core/agent_template_ops.py
+++ b/core/switch_core/agent_template_ops.py
@@ -212,8 +212,7 @@ class AgentTemplates:
if size > self._max_bytes:
raise AgentRefused(
"too_large",
- f"The template is {size} bytes, over this server's limit of "
- f"{self._max_bytes}.",
+ f"The template is {size} bytes, over the limit of {self._max_bytes}.",
)
lint = lint_template(content)
if lint.blocked:
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.py
index 2ff7432cd..82fb91d26 100644
--- a/core/switch_core/bridges/agent/commands.py
+++ b/core/switch_core/bridges/agent/commands.py
@@ -853,7 +853,7 @@ async def _cmd_list_room_agents(
_FOLLOW_THE_CONVERSATION_OFF = (
- "Following the conversation isn't switched on for this Switch server, so "
+ "Following the conversation isn't switched on in Switch, so "
"`!follow-ups` and `!assign-agent` have no effect here. Agents only get "
"messages that mention them."
)
@@ -918,7 +918,7 @@ async def _cmd_follow_ups(
_AUTO_ROUTE_FLAG_OFF = (
- "Automatic routing isn't switched on for this Switch server, so "
+ "Automatic routing isn't switched on in Switch, so "
"`!auto-route` has no effect here. Agents only get messages that mention "
"them, follow-ups, or every message when they are the room's assigned agent."
)
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 41337794d..2ba6a7021 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -2601,7 +2601,7 @@ class DiscordAdapter(PlatformAdapter):
):
raise ChannelNotBindable(
f"Discord channel {channel_id} is a direct message, which this "
- "connection does not carry."
+ "messaging app does not carry."
)
async def get_channel_type(self, channel_id: str) -> ChannelType:
@@ -3697,7 +3697,7 @@ class DiscordAdapter(PlatformAdapter):
guild = getattr(channel, "guild", None)
if guild is not None and guild.id != self._guild_id:
raise ChannelNotBindable(
- f"Discord channel {channel_id} is not in this connection's server."
+ f"Discord channel {channel_id} is not in this messaging app's server."
)
return channel
diff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.py
index 4373fe576..1669ae769 100644
--- a/core/switch_core/bridges/collaboration/install_service.py
+++ b/core/switch_core/bridges/collaboration/install_service.py
@@ -690,7 +690,7 @@ class MessagingInstallService:
grant.external_workspace_id,
)
raise MessagingInstallError(
- "Switch recorded the approval, but the connection could not "
+ "Switch recorded the approval, but the messaging app could not "
f"restart to use it ({error}). It is stopped until Switch "
"restarts or the approval is given again."
) from error
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index e0e61453c..a2af6eebe 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -576,7 +576,7 @@ class CollaborationBridgeLifecycleService:
if adapter is None or not self.is_connected(bridge_id):
if self.editable_config_keys(bridge_type, current) is not None:
raise BridgeNotRunning(
- "The connection is not running, so Switch cannot check this "
+ "The messaging app is not running, so Switch cannot check this "
"change with the platform; try again in a moment."
)
return
@@ -958,7 +958,7 @@ class CollaborationBridgeLifecycleService:
if channel_creation_enabled and not adapter_cls.supports_channel_creation:
raise ValueError(
f"{bridge_type} cannot create channels from Switch, so this "
- "connection cannot be allowed to. Create the chat on the "
+ "messaging app cannot be allowed to. Create the chat on the "
"platform and add the bot to it; Switch adopts it as a room."
)
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
index 956b56774..97451b060 100644
--- a/core/switch_core/bridges/collaboration/teams/adapter.py
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -729,7 +729,7 @@ class TeamsConnectionConfig(BridgeConnectionConfig):
raise ValueError(
f"{', '.join(foreign)} must not be set on a bridge on the "
"distributed Teams app; its credentials, keys and listener are "
- "the deployment's, not this connection's."
+ "the deployment's, not this messaging app's."
)
return self
@@ -1513,7 +1513,7 @@ class TeamsAdapter(PlatformAdapter):
if left_behind:
raise BridgeOperationError(
- "Removing the Teams connection left behind: "
+ "Removing the Teams messaging app left behind: "
+ "; ".join(left_behind)
+ ". Subscriptions run out on their own within the hour."
)
@@ -2628,9 +2628,9 @@ class TeamsAdapter(PlatformAdapter):
team_id = self._config.team_id
if not team_id:
raise BridgeOperationError(
- "No default team is set for this Teams connection, so Switch "
+ "No default team is set for this Teams messaging app, so Switch "
"does not know which team to create the channel in. Choose one "
- "in the connection's Microsoft Teams settings."
+ "in the messaging app's Microsoft Teams settings."
)
membership_type = "private" if channel_type == "channel_private" else "standard"
channel = await self._graph.create_channel(
@@ -3309,7 +3309,7 @@ class TeamsAdapter(PlatformAdapter):
def _require_shared(self) -> GraphClient:
if not self._me.shared:
raise BridgeOperationError(
- "Only a connection on the distributed Teams app places itself "
+ "Only a messaging app on the distributed Teams app places itself "
"in teams from Switch; a bring-your-own app is added in Teams."
)
if self._graph is None:
diff --git a/core/switch_core/bridges/collaboration/telegram/app_client.py b/core/switch_core/bridges/collaboration/telegram/app_client.py
index d92c6ea4e..c30fbac95 100644
--- a/core/switch_core/bridges/collaboration/telegram/app_client.py
+++ b/core/switch_core/bridges/collaboration/telegram/app_client.py
@@ -149,7 +149,7 @@ class TelegramAppClient:
if self._username is None:
raise TelegramAppNotReady(
"the Switch Telegram bot has not connected yet, so there is no "
- "link to offer. Try again shortly; the server log says why if "
+ "link to offer. Try again shortly; Switch's log says why if "
"it keeps failing."
)
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 4c8e87ef4..7a3ea140e 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -290,7 +290,7 @@ class ChatService:
that turned it off (or never on) says so rather than half-serving it."""
if not self.group_chats_enabled:
raise ChatError(
- 409, "GROUP_CHATS_OFF", "Group chats are not turned on for this server."
+ 409, "GROUP_CHATS_OFF", "Group chats are not turned on here."
)
def _lock(self, *key: str) -> asyncio.Lock:
@@ -1414,7 +1414,7 @@ class ChatService:
raise ChatError(
409,
"BUDDY_SLACK_HANDOFF_OFF",
- "Chats on a bridge are not turned on for this server.",
+ "Chats on a messaging app are not turned on here.",
)
if bridge_id is not None and not direct:
raise ChatError(
diff --git a/core/switch_core/connections/adapters/github.py b/core/switch_core/connections/adapters/github.py
index b298c3133..b06405b13 100644
--- a/core/switch_core/connections/adapters/github.py
+++ b/core/switch_core/connections/adapters/github.py
@@ -216,7 +216,7 @@ class GitHubAdapter:
raise ServiceAdapterError("GitHub grants name App permissions.")
if self._signer is None:
raise ServiceAdapterError(
- "GitHub cannot be granted on this server: no signing key is configured."
+ "GitHub cannot be granted here: no signing key is configured."
)
try:
token = await self._signer.mint(
diff --git a/core/switch_core/connections/adapters/oauth.py b/core/switch_core/connections/adapters/oauth.py
index d4c10d8e5..357f7988f 100644
--- a/core/switch_core/connections/adapters/oauth.py
+++ b/core/switch_core/connections/adapters/oauth.py
@@ -422,7 +422,7 @@ class OAuthAdapter:
if not isinstance(refresh_token, str) or not refresh_token:
raise ServiceAdapterError(
f"{self._name} returned no refresh token, so Switch could not keep "
- "the connection signed in."
+ "the connector signed in."
)
values = {
**previous,
@@ -524,7 +524,7 @@ class OAuthAdapter:
refresh_token = secret.values.get("refresh_token")
if not isinstance(refresh_token, str) or not refresh_token:
raise ReauthorizationRequiredError(
- f"The {self._name} connection holds no refresh token."
+ f"The {self._name} connector holds no refresh token."
)
answer = await self._token_request(
{"grant_type": "refresh_token", "refresh_token": refresh_token}
@@ -536,7 +536,7 @@ class OAuthAdapter:
) -> dict[str, Any]:
if request.resources:
raise ServiceAdapterError(
- f"A {self._name} grant reaches the whole connection; it names "
+ f"A {self._name} grant reaches the whole connector; it names "
"no resources."
)
return {}
diff --git a/core/switch_core/connections/app_credentials.py b/core/switch_core/connections/app_credentials.py
index 4722e6563..3a15af386 100644
--- a/core/switch_core/connections/app_credentials.py
+++ b/core/switch_core/connections/app_credentials.py
@@ -121,26 +121,23 @@ def github_needs_https(kind: AppKind | None, public_url: str | None) -> bool:
def not_set_up(name: str) -> str:
"""What members are told about a service whose app is not set up here."""
return (
- f"{name} is not set up on this server. Whoever runs your Switch server "
- "can set it up in Switch Console, under Admin → Connector apps."
+ f"{name} is not set up here. Whoever runs Switch can set it up in "
+ "Switch Console, under Admin → Connector apps."
)
def cannot_work_here(name: str) -> str:
"""What members are told about a service whose app this server can't
have: GitHub's, on a server without an https address."""
- return (
- f"{name} can't be used on this server: it needs the server to have an "
- "https address."
- )
+ return f"{name} can't be used here: it needs Switch to have an https address."
def needs_public_url(name: str) -> str:
"""What members are told about a service whose sign-ins return only to
the server, on a server without a public address."""
return (
- f"{name} can't be connected on this server: it needs the server's "
- "public address (GATEWAY_PUBLIC_URL)."
+ f"{name} can't be connected here: it needs Switch's public address "
+ "(GATEWAY_PUBLIC_URL)."
)
diff --git a/core/switch_core/connections/broker.py b/core/switch_core/connections/broker.py
index eed030546..2947851b2 100644
--- a/core/switch_core/connections/broker.py
+++ b/core/switch_core/connections/broker.py
@@ -140,7 +140,7 @@ UNREVOCABLE_UNKNOWN = (
"Some access already given to agents cannot be taken back and may keep "
"working until it expires."
)
-SWITCHED_OFF = "Switched off on this server."
+SWITCHED_OFF = "Switched off here."
# Why a connection needs reconnecting: the operator replaced the app it
# signed in through.
CLIENT_REPLACED = "client_replaced"
@@ -657,8 +657,7 @@ class ServiceBroker:
503,
INTERNAL,
choice.problem
- or f"{self._entry(service).definition.name} is not available on "
- "this server.",
+ or f"{self._entry(service).definition.name} is not available here.",
retryable=False,
)
return choice.adapter
@@ -722,7 +721,7 @@ class ServiceBroker:
403,
GRANT_MISSING,
f"Agent {agent.name} has no {name} grant. Its owner can grant "
- f"{name} to it under the agent's Connections.",
+ f"{name} to it from the agent's page.",
retryable=False,
)
if grant.owner_id != owner_id:
@@ -761,8 +760,8 @@ class ServiceBroker:
raise ServiceError(
404,
CONNECTOR_NOT_CONNECTED,
- f"The agent's owner has not connected {name}. Connect it under "
- "Settings, Connections.",
+ f"The agent's owner has not connected {name}. Connect it in "
+ "Switch Console, under Connectors.",
retryable=False,
)
if connection.status != "active":
@@ -770,16 +769,17 @@ class ServiceBroker:
409,
CONNECTOR_REVOKED,
f"The agent's owner must reconnect {name}: its sign-in was "
- "revoked or has lapsed. Reconnect it under Settings, Connections.",
+ "revoked or has lapsed. Reconnect it in Switch Console, under "
+ "Connectors.",
retryable=False,
)
if _scopes_changed(connection, entry):
raise ServiceError(
409,
CONNECTOR_REVOKED,
- f"The agent's owner must reconnect {name}: this server now asks "
+ f"The agent's owner must reconnect {name}: Switch now asks "
f"for other {name} access than the sign-in granted. Reconnect it "
- "under Settings, Connections.",
+ "in Switch Console, under Connectors.",
retryable=False,
)
if grant.account_id != connection.account_id:
@@ -804,7 +804,7 @@ class ServiceBroker:
raise ServiceError(
403,
FORBIDDEN,
- f"This grant asks for write access, but the {name} connection "
+ f"This grant asks for write access, but the {name} connector "
"allows only reading. Reconnect with write access, or make the "
"grant read-only.",
retryable=False,
@@ -1171,8 +1171,8 @@ class ServiceBroker:
raise ServiceError(
409,
CONNECTOR_REVOKED,
- f"The agent's owner must reconnect {name} under Settings, "
- "Connections.",
+ f"The agent's owner must reconnect {name} in Switch Console, "
+ "under Connectors.",
retryable=False,
)
if _client_replaced(connection, adapter):
@@ -1183,8 +1183,7 @@ class ServiceBroker:
raise self._revoked(
service,
ReauthorizationRequiredError(
- f"{name} was connected through an app this server no "
- "longer uses."
+ f"{name} was connected through an app Switch no longer uses."
),
)
secret = self._secret(connection)
@@ -1195,7 +1194,7 @@ class ServiceBroker:
raise ServiceError(
500,
INTERNAL,
- f"The {name} connection holds no token.",
+ f"The {name} connector holds no token.",
retryable=False,
)
await session.commit()
@@ -1235,8 +1234,8 @@ class ServiceBroker:
return ServiceError(
409,
CONNECTOR_REVOKED,
- f"{error} The agent's owner must reconnect {name} under Settings, "
- "Connections.",
+ f"{error} The agent's owner must reconnect {name} in Switch Console, "
+ "under Connectors.",
retryable=False,
)
@@ -1303,7 +1302,7 @@ class ServiceBroker:
server = self._adapters.get(service)
if here is None and server is None:
raise ServiceUnavailableError(
- f"{name} is not set up on this server, so Switch could not "
+ f"{name} is not set up here, so Switch could not "
f"revoke the sign-in. Revoke it at {name}."
)
# A sign-in from before clients were recorded predates organizations'
@@ -1455,11 +1454,7 @@ class ServiceBroker:
def _reason(self, service: str, choice: _Choice) -> str:
"""Why `service` cannot be used through `choice`, in a sentence."""
unavailable = self._unavailable(service, choice)
- return (
- "Not available on this server."
- if unavailable is None
- else unavailable.reason
- )
+ return "Not available here." if unavailable is None else unavailable.reason
def server_serves(self, service: str) -> bool:
"""Whether a workspace that goes through the server's app for
@@ -1499,11 +1494,11 @@ class ServiceBroker:
return Unavailable("organization_app_unusable", choice.problem)
if kind is not None:
return Unavailable("app_not_set_up", not_set_up(name))
- return Unavailable("not_set_up", f"{name} is not set up on this server.")
+ return Unavailable("not_set_up", f"{name} is not set up here.")
if not adapter.can_issue:
return Unavailable(
"not_fully_set_up",
- f"{name} can be connected on this server but not granted to "
+ f"{name} can be connected here but not granted to "
"agents: it is not fully set up.",
)
return None
@@ -1550,14 +1545,14 @@ class ServiceBroker:
raise ServiceError(
409,
CONNECTOR_NOT_CONNECTED,
- f"Connect {name} under Settings, Connections first.",
+ f"Connect {name} in Switch Console, under Connectors, first.",
retryable=False,
)
if connection.status != "active" or _scopes_changed(connection, entry):
raise ServiceError(
409,
CONNECTOR_REVOKED,
- f"Reconnect {name} under Settings, Connections first.",
+ f"Reconnect {name} in Switch Console, under Connectors, first.",
retryable=False,
)
if _passes_through(entry):
@@ -1566,7 +1561,7 @@ class ServiceBroker:
422,
VALIDATION_ERROR,
f"A {name} grant is on or off: the agent reaches what your "
- f"{name} connection does. Leave out access and tools.",
+ f"{name} connector does. Leave out access and tools.",
retryable=False,
)
access = _consent(connection)
@@ -1575,7 +1570,7 @@ class ServiceBroker:
raise ServiceError(
422,
VALIDATION_ERROR,
- f"Your {name} connection allows only reading. Reconnect with "
+ f"Your {name} connector allows only reading. Reconnect with "
"write access to grant writing.",
retryable=False,
)
@@ -1738,7 +1733,7 @@ class ServiceBroker:
raise ServiceError(
409,
CONNECTOR_REVOKED,
- f"Your {name} connection changed. Please retry.",
+ f"Your {name} connector changed. Please retry.",
retryable=True,
)
previous = await self._store.get_grant(session, agent.id, service)
@@ -2327,9 +2322,7 @@ class ServiceBroker:
adapter = adapters[service]
try:
if adapter is None or encrypted is None:
- raise ServiceUnavailableError(
- f"{service} is not available on this server."
- )
+ raise ServiceUnavailableError(f"{service} is not available here.")
async with asyncio.timeout(VENDOR_CALL_SECONDS):
await adapter.revoke_issued(self._keyring.decrypt(encrypted))
return row_id
diff --git a/core/switch_core/connections/flows.py b/core/switch_core/connections/flows.py
index a8a5f15ab..086e41a8c 100644
--- a/core/switch_core/connections/flows.py
+++ b/core/switch_core/connections/flows.py
@@ -61,7 +61,7 @@ INTERRUPTED = "Sign-in was interrupted. Start it again from Switch Console."
def client_changed(name: str) -> str:
- return f"This server's {name} app changed during your sign-in. Start it again."
+ return f"Switch's {name} app changed during your sign-in. Start it again."
class FlowError(Exception):
@@ -164,8 +164,8 @@ class ServiceFlows:
mode = self.mode(definition)
if mode is None:
raise FlowError(
- f"{definition.name} can return a sign-in only to this server, "
- "which has no public address (GATEWAY_PUBLIC_URL)."
+ f"{definition.name} can return a sign-in only to Switch's public "
+ "address, and none is set (GATEWAY_PUBLIC_URL)."
)
assert definition.auth.oauth is not None
ports = definition.auth.oauth.loopback_ports
diff --git a/core/switch_core/connections/oauth_clients.py b/core/switch_core/connections/oauth_clients.py
index d3036687f..506604a5b 100644
--- a/core/switch_core/connections/oauth_clients.py
+++ b/core/switch_core/connections/oauth_clients.py
@@ -104,7 +104,7 @@ class RegisteredClient:
scopes: list[str],
) -> None:
if not redirect_uris:
- raise ValueError(f"{service} has no redirect this server can register.")
+ raise ValueError(f"{service} has no redirect Switch can register.")
self._service = service
self._name = name
self._session_factory = session_factory
diff --git a/core/switch_core/db/stores/service_connection_store.py b/core/switch_core/db/stores/service_connection_store.py
index bda962736..a05c8f4c3 100644
--- a/core/switch_core/db/stores/service_connection_store.py
+++ b/core/switch_core/db/stores/service_connection_store.py
@@ -56,7 +56,7 @@ class ServiceConnectionStore:
except DBAPIError as error:
if getattr(error.orig, "sqlstate", None) == "55P03":
raise ServiceConnectionBusy(
- "The connection is busy. Please retry."
+ "The connector is busy. Please retry."
) from None
raise
@@ -164,7 +164,7 @@ class ServiceConnectionStore:
)
if updated is None:
raise ServiceConnectionChanged(
- f"The {service} connection changed while its secret was refreshed."
+ f"The {service} connector changed while its secret was refreshed."
)
return updated
diff --git a/core/switch_core/decision/client.py b/core/switch_core/decision/client.py
index 19b9dbd51..7b6a47577 100644
--- a/core/switch_core/decision/client.py
+++ b/core/switch_core/decision/client.py
@@ -215,7 +215,7 @@ def decision_target(
headers = {"Content-Type": "application/json"}
if source == "server_default":
if server.endpoint_url is None:
- raise ValueError("The server has no decision service configured.")
+ raise ValueError("Switch has no decision service configured.")
if server.api_key is not None:
headers["Authorization"] = f"Bearer {server.api_key}"
return DecisionTarget(
@@ -236,7 +236,7 @@ def decision_target(
if backend in ("haiku_anthropic", "haiku_bedrock"):
if server.endpoint_url is None:
raise ValueError(
- "Haiku runs in the server's decision service, and this server has none."
+ "Haiku runs in Switch's decision service, and none is set up here."
)
if server.api_key is not None:
headers["Authorization"] = f"Bearer {server.api_key}"
@@ -282,7 +282,7 @@ async def post_decision(
except OutboundURLRefused as error:
raise DecisionServiceError(
"endpoint_refused",
- f"POST {url} refused by the server's outbound policy: {error}",
+ f"POST {url} refused by Switch's outbound policy: {error}",
) from error
except httpx.TimeoutException as error:
raise DecisionServiceError(
@@ -508,8 +508,8 @@ class DynamicDecisionClient:
room_id,
label,
"key_unreadable",
- "the workspace's decision key is encrypted under a secret this "
- "server no longer holds; a workspace admin has to save it again",
+ "the workspace's decision key is encrypted under a secret Switch "
+ "no longer holds; a workspace admin has to save it again",
)
target = decision_target(
server=self.server,
@@ -599,8 +599,8 @@ class DynamicDecisionClient:
if backend == "haiku_bedrock" and not self.server.haiku_bedrock:
return error(
"backend_unavailable",
- "Haiku on Bedrock isn't offered on this server: it needs the "
- "server's decision service and DECISION_BEDROCK_ENABLED.",
+ "Haiku on Bedrock isn't offered here: it needs Switch's "
+ "decision service and DECISION_BEDROCK_ENABLED.",
)
try:
target = (
@@ -667,7 +667,7 @@ def _test_error_message(code: str, failure: DecisionServiceError) -> str:
"unauthorized": f"The decision service refused the key. {failure}",
"refused": (
"Switch won't connect to that address: a workspace's endpoint must "
- "be a public address, or a private host the server's operator lists "
+ "be a public address, or a private host whoever runs Switch lists "
f"in OUTBOUND_ALLOWED_PRIVATE_HOSTS. {failure}"
),
"key_refused": f"The Anthropic API refused the key. {failure}",
diff --git a/core/switch_core/decision/settings.py b/core/switch_core/decision/settings.py
index 021d4f572..44f33d515 100644
--- a/core/switch_core/decision/settings.py
+++ b/core/switch_core/decision/settings.py
@@ -38,8 +38,8 @@ Backend = Literal["none", "endpoint", "haiku_anthropic", "haiku_bedrock"]
Source = Literal["workspace", "server_default"]
FLAG_OFF_REASON = (
- "Auto-route isn't switched on for this Switch server. Whoever runs the "
- "server turns it on with the decision_routing feature flag."
+ "Auto-route isn't switched on here. Whoever runs Switch turns it on "
+ "with the decision_routing feature flag."
)
NO_BACKEND_REASON = (
"Auto-route needs a decision service. A workspace admin can set one up in "
diff --git a/core/switch_core/deeplinks.py b/core/switch_core/deeplinks.py
index 3dbaee9ab..d84a7c1e9 100644
--- a/core/switch_core/deeplinks.py
+++ b/core/switch_core/deeplinks.py
@@ -173,7 +173,7 @@ CONSOLE_PAGES: Mapping[str, ConsolePage] = {
has_id=True,
tabs={
"chats": "your agent's chats",
- "connections": "your agent's connections",
+ "connections": "your agent's connectors",
"settings": "your agent's settings",
},
),
@@ -184,7 +184,7 @@ CONSOLE_PAGES: Mapping[str, ConsolePage] = {
"switch-buddy's page",
tabs={
"chats": "switch-buddy's chats",
- "connections": "switch-buddy's connections",
+ "connections": "switch-buddy's connectors",
"settings": "switch-buddy's settings",
},
),
diff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.py
index 09219f079..6ded885fa 100644
--- a/core/switch_core/delivery/recipient.py
+++ b/core/switch_core/delivery/recipient.py
@@ -344,7 +344,7 @@ def _start_from_console_message(
console = f"opening **{agent_name}** in Switch Console"
sign_in = (
"If Switch Console says I'm signed out, sign me in first with "
- f"`{sign_in_command}` on the machine I run on."
+ f"`{sign_in_command}` on the device I run on."
)
if connected_not_live:
return (
@@ -392,7 +392,7 @@ def _machine_offline_message(machine: str, owner_handle: str | None) -> str:
"""A managed agent whose controller's stream is down: Core restarted, the
machine lost its network, or it is switched off."""
return (
- f"My machine, **{machine}**, is offline or reconnecting to Switch, so "
+ f"My device, **{machine}**, is offline or reconnecting to Switch, so "
"I can't answer right now. If I haven't answered once it's back, address "
f"me again. If it stays offline, {_owner_ref(owner_handle)} needs to "
"check it."
@@ -420,7 +420,7 @@ def _cloud_machine_waking_message(machine: str) -> str:
"""A managed agent whose Switch cloud machine was asleep, and is starting
for this message: Switch keeps the message until the machine is back."""
return (
- f"My machine, **{machine}**, was asleep and is starting now. I'll pick "
+ f"My device, **{machine}**, was asleep and is starting now. I'll pick "
"this up as soon as it's back, usually within a few minutes."
)
@@ -429,15 +429,15 @@ def _cloud_machine_stopped_message(machine: str, owner_handle: str | None) -> st
"""A managed agent whose Switch cloud machine its owner stopped: a message
does not start it again."""
return (
- f"My machine, **{machine}**, is stopped, so I can't answer. "
+ f"My device, **{machine}**, is stopped, so I can't answer. "
f"{_owner_ref(owner_handle).capitalize()} can start it again in Switch Console."
)
def _machine_removed_message(machine: str, owner_handle: str | None) -> str:
removed = (
- f"my machine, **{machine}**, has been removed from Switch, so nothing "
- "runs me. My owner has to move me to another machine to bring me back."
+ f"my device, **{machine}**, has been removed from Switch, so nothing "
+ "runs me. My owner has to move me to another device to bring me back."
)
if owner_handle:
return f"@{owner_handle} — {removed}"
diff --git a/core/switch_core/feature_flags.py b/core/switch_core/feature_flags.py
index 09b93d52c..b2e0144ee 100644
--- a/core/switch_core/feature_flags.py
+++ b/core/switch_core/feature_flags.py
@@ -95,6 +95,14 @@ BUDDY_SLACK_HANDOFF = "buddy_slack_handoff"
# server's apps, as before organizations.
ORGANIZATION_CONNECTOR_APPS = "organization_connector_apps"
+# The dashboard's new layout: Overview, Templates and Connectors on the rail,
+# Workspace and Organization settings as their own areas, and the operator's
+# pages in a Platform area. Today's pages move into it and their old URLs
+# redirect. Core has nothing of its own behind it; the dashboard reads it. It
+# stays off until every page of the new layout is built, and on a server with
+# it off the dashboard is laid out as before.
+GATEWAY_V2 = "gateway_v2"
+
# Flags that need another flag on: the server refuses a configuration with
# the key on and any of its values off, and tools that turn flags off one at a
# time (scripts/e2e_surface.py) turn the dependants off with it.
@@ -131,5 +139,6 @@ KNOWN_FEATURE_FLAGS: frozenset[str] = frozenset(
GROUP_CHATS,
BUDDY_SLACK_HANDOFF,
ORGANIZATION_CONNECTOR_APPS,
+ GATEWAY_V2,
}
)
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 94be099cd..9a26d57be 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -935,7 +935,7 @@ def workspace_creation_refusal(
return None
if new_organization and config.gateway_signup_mode == "invite_only":
return (
- "Creating organizations is turned off on this server. Ask a "
+ "Creating organizations is turned off here. Ask a "
"workspace admin for an invitation."
)
limit = config.gateway_max_workspaces_per_user
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 64f49ff9f..d9d85db49 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -227,7 +227,7 @@ async def _refuse_signup(
emit_safely(current_telemetry(), "signup_refused", {"reason": "rate_limited"})
raise HTTPException(
status_code=429,
- detail="Too many sign-ups on this server in the last hour. Try again later.",
+ detail="Too many sign-ups in the last hour. Try again later.",
headers={"Retry-After": str(retry_after)},
)
if await user_store.get_by_email(session, email) is not None:
@@ -257,9 +257,7 @@ async def signup(
"""
if not config.gateway_signup_open:
emit_safely(current_telemetry(), "signup_refused", {"reason": "disabled"})
- raise HTTPException(
- status_code=403, detail="Sign-up is disabled on this server"
- )
+ raise HTTPException(status_code=403, detail="Sign-up is turned off here")
with tenant_scope(TENANT_ZERO_ID):
# Checked before the hash so a refusal stays cheap, and again under the
diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py
index 8ed838e2c..39bb70227 100644
--- a/core/switch_core/gateway/collaborations.py
+++ b/core/switch_core/gateway/collaborations.py
@@ -201,25 +201,25 @@ def _installed_refusal(installs: list[MessagingInstall]) -> str:
them = "it" if len(installs) == 1 else "them"
if platform == "telegram":
return (
- f"The Switch bot is still in {where} through this connection. "
+ f"The Switch bot is still in {where} through this messaging app. "
f"Disconnect {them} under Installed apps first, then delete the "
- "connection here."
+ "messaging app here."
)
if platform == "discord":
return (
- f"This connection was created by adding the Switch bot to {where}. "
+ f"This messaging app was created by adding the Switch bot to {where}. "
f"Disconnect {them} under Installed apps instead: that stops Switch "
- "using the server and removes this connection. The bot stays in the "
+ "using the Discord server and removes this messaging app. The bot stays in the "
"server until you remove it in Discord."
)
if platform == "slack":
- effect = "revokes Switch's token at Slack and removes this connection"
+ effect = "revokes Switch's token at Slack and removes this messaging app"
elif platform == "teams":
- effect = "takes the app out of every team and removes this connection"
+ effect = "takes the app out of every team and removes this messaging app"
else:
- effect = "removes this connection"
+ effect = "removes this messaging app"
return (
- f"This connection was created by installing the Switch app into "
+ f"This messaging app was created by installing the Switch app into "
f"{where}. Disconnect {them} under Installed apps instead: that "
f"{effect}."
)
@@ -354,10 +354,7 @@ async def create_bridge(
if req.connection_config.get("event_delivery") == "shared":
raise HTTPException(
status_code=422,
- detail=(
- "A shared connection is created by installing the app, not "
- "registered here."
- ),
+ detail=("A shared messaging app is added by installing the app, not here."),
)
try:
bridge = await collab_lifecycle.register(
@@ -494,7 +491,7 @@ async def update_bridge(
status_code=400,
detail=(
f"{bridge.type} cannot create channels from Switch, so this "
- "connection cannot be allowed to. Create the chat on the "
+ "messaging app cannot be allowed to. Create the chat on the "
"platform and add the bot to it; Switch adopts it as a room."
),
)
@@ -508,7 +505,7 @@ async def update_bridge(
if merged.get("event_delivery") != current.get("event_delivery"):
raise HTTPException(
status_code=422,
- detail="event_delivery cannot be changed on an existing connection.",
+ detail="event_delivery cannot be changed on an existing messaging app.",
)
# A connection on an app the deployment owns may hold settings that
# decide where the deployment's credential is pointed; only the ones
@@ -525,7 +522,7 @@ async def update_bridge(
status_code=422,
detail=(
f"{', '.join(locked)} cannot be changed on this "
- "connection: Switch manages it for the installed app."
+ "messaging app: Switch manages it for the installed app."
),
)
# Not held across the platform's credential check; nothing is written
diff --git a/core/switch_core/gateway/connector_apps.py b/core/switch_core/gateway/connector_apps.py
index 633676676..96105dadf 100644
--- a/core/switch_core/gateway/connector_apps.py
+++ b/core/switch_core/gateway/connector_apps.py
@@ -199,7 +199,7 @@ async def _usages(
def app_spec(apps: ConnectorApps, service: str) -> AppSpec:
spec = apps.specs.get(service)
if spec is None:
- raise HTTPException(404, f"{service} has no app to set up on this server.")
+ raise HTTPException(404, f"{service} has no app to set up here.")
return spec
diff --git a/core/switch_core/gateway/decision_settings.py b/core/switch_core/gateway/decision_settings.py
index 92e2b9727..47c0925e1 100644
--- a/core/switch_core/gateway/decision_settings.py
+++ b/core/switch_core/gateway/decision_settings.py
@@ -113,14 +113,13 @@ def _refuse_unoffered(
if req.backend == "haiku_anthropic" and not server.haiku_anthropic:
raise HTTPException(
status_code=422,
- detail="Haiku runs in the server's decision service, and this server "
- "has none configured.",
+ detail="Haiku runs in Switch's decision service, and none is set up here.",
)
if req.backend == "haiku_bedrock" and not server.haiku_bedrock:
raise HTTPException(
status_code=422,
- detail="Haiku on Bedrock isn't offered on this server: it needs the "
- "server's decision service and DECISION_BEDROCK_ENABLED.",
+ detail="Haiku on Bedrock isn't offered here: it needs Switch's "
+ "decision service and DECISION_BEDROCK_ENABLED.",
)
@@ -134,7 +133,7 @@ async def _refuse_unreachable(endpoint: str, policy: OutboundPolicy) -> None:
raise HTTPException(
status_code=422,
detail=f"{refused} A workspace's decision endpoint must be a public "
- "address, or a private host the server's operator lists in "
+ "address, or a private host whoever runs Switch lists in "
"OUTBOUND_ALLOWED_PRIVATE_HOSTS.",
) from refused
@@ -292,7 +291,7 @@ async def test_decision_settings(
backend=req.backend,
error=DecisionTestError(
code="not_configured",
- message="The stored key can't be decrypted by this server; "
+ message="The stored key can't be decrypted here; "
"enter it again.",
),
)
diff --git a/core/switch_core/gateway/github_connections.py b/core/switch_core/gateway/github_connections.py
index b0abf2914..28214a86c 100644
--- a/core/switch_core/gateway/github_connections.py
+++ b/core/switch_core/gateway/github_connections.py
@@ -59,7 +59,7 @@ def service(request: Request) -> GitHubConnections:
"""The server's own GitHub App."""
value = request.app.state.github_connections
if value is None:
- raise HTTPException(503, "GitHub connections are not enabled on this server.")
+ raise HTTPException(503, "GitHub connectors are not turned on here.")
return cast(GitHubConnections, value)
@@ -181,7 +181,7 @@ async def start(
) from None
except FlowsBusyError:
raise HTTPException(
- 503, "GitHub connection is busy. Please try again shortly."
+ 503, "The GitHub connector is busy. Please try again shortly."
) from None
return {
"id": body.state,
@@ -467,7 +467,7 @@ async def connection_status(
raise HTTPException(502, str(error)) from None
row = await STORE.get_connection(session, user_id, "github")
if row is None:
- raise HTTPException(409, "GitHub connection changed. Please retry.")
+ raise HTTPException(409, "The GitHub connector changed. Please retry.")
await session.commit()
return {
"status": "connected",
diff --git a/core/switch_core/gateway/messaging_installs.py b/core/switch_core/gateway/messaging_installs.py
index 0e0403d74..2ad423c89 100644
--- a/core/switch_core/gateway/messaging_installs.py
+++ b/core/switch_core/gateway/messaging_installs.py
@@ -124,7 +124,7 @@ def _require_installs(
status_code=501,
detail=(
"This Switch deployment has no messaging app of its own to "
- "install. Register a bridge with your own app's credentials "
+ "install. Add a messaging app with your own app's credentials "
"instead."
),
)
diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.py
index 11caac357..3060a4ed4 100644
--- a/core/switch_core/gateway/oidc_routes.py
+++ b/core/switch_core/gateway/oidc_routes.py
@@ -383,7 +383,7 @@ async def oidc_callback(
status_code=503,
detail=(
"Sign-in is misconfigured: the identity provider's issuer "
- "does not match this server's configuration"
+ "does not match Switch's configuration"
),
)
# A first sign-in provisions the account just in time. Where it lands is
diff --git a/core/switch_core/gateway/teams_placements.py b/core/switch_core/gateway/teams_placements.py
index a5b40baf4..87941a105 100644
--- a/core/switch_core/gateway/teams_placements.py
+++ b/core/switch_core/gateway/teams_placements.py
@@ -83,7 +83,7 @@ async def _connection(
if bridge is None or install is None or bridge.type != "teams":
raise HTTPException(
status_code=404,
- detail="No connection on the distributed Teams app has that id.",
+ detail="No messaging app on the distributed Teams app has that id.",
)
# Connected, not merely registered: a bridge restarting — as it does after
# its default team changes — is registered before it has a Graph client.
@@ -93,7 +93,7 @@ async def _connection(
):
raise HTTPException(
status_code=503,
- detail="The Teams connection is not running; try again in a moment.",
+ detail="The Teams messaging app is not running; try again in a moment.",
)
return adapter, install
@@ -255,7 +255,7 @@ async def remove_from_team(
status_code=503,
detail=(
"Switch left the team, and channel creation is off until "
- "another default team is chosen, but the connection did "
+ "another default team is chosen, but the messaging app did "
f"not restart ({error}). It is stopped until it is "
"restarted."
),
diff --git a/core/switch_core/gateway/templates.py b/core/switch_core/gateway/templates.py
index 011613ee0..f01d755e6 100644
--- a/core/switch_core/gateway/templates.py
+++ b/core/switch_core/gateway/templates.py
@@ -237,7 +237,7 @@ def _require_within_size_limit(content: str, config: SwitchConfig) -> None:
status_code=413,
detail=(
f"Template is {size} bytes, over the {config.template_max_bytes}-byte "
- "limit for this server."
+ "limit."
),
)
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index ba63192f0..98db37504 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -201,7 +201,7 @@ def _require_bound_tenant(tenant_id: str) -> None:
codebase follows refuses to do.
"""
if current_tenant_id() != tenant_id:
- raise HTTPException(status_code=403, detail="Not authorized for this tenant")
+ raise HTTPException(status_code=403, detail="Not allowed in this workspace")
def _invitation_fields(invitation: Invitation) -> dict[str, object]:
@@ -264,9 +264,9 @@ async def _refuse_organization_admin(
raise HTTPException(
status_code=409,
detail=(
- "This member administers the workspace's organization, which "
+ "This user administers the workspace's organization, which "
"gives them admin rights in every one of its workspaces. Change "
- "their role in the organization's members first."
+ "their role in the organization's users first."
),
)
@@ -507,7 +507,7 @@ async def switch_tenant(
workspace (`initial_tenant_claim`), so every visit starts here.
"""
if not await may_bind_tenant(session_factory, user_store, user_id, tenant_id):
- raise HTTPException(status_code=403, detail="Not a member of this tenant")
+ raise HTTPException(status_code=403, detail="Not a member of this workspace")
user = await user_store.get(session, user_id)
if user is None:
@@ -1790,7 +1790,7 @@ async def update_member_role(
membership = await session.get(TenantMember, (tenant_id, user_id))
if membership is None:
- raise HTTPException(status_code=404, detail="Not a member of this tenant")
+ raise HTTPException(status_code=404, detail="Not a member of this workspace")
await _refuse_organization_admin(session, user_store, tenant_id, user_id)
if membership.role == "admin" and role != "admin":
@@ -1885,7 +1885,7 @@ async def remove_member(
populate_existing=True,
)
if membership is None:
- raise HTTPException(status_code=404, detail="Not a member of this tenant")
+ raise HTTPException(status_code=404, detail="Not a member of this workspace")
await _refuse_organization_admin(session, user_store, tenant_id, user_id)
if membership.role == "admin":
@@ -1898,7 +1898,7 @@ async def remove_member(
raise HTTPException(
status_code=409,
detail=(
- "Cannot remove: this member owns agents in this workspace. "
+ "Cannot remove: this user owns agents in this workspace. "
f"Transfer or delete them first: {names}"
),
)
diff --git a/core/switch_core/gateway/ui.py b/core/switch_core/gateway/ui.py
index ff9be03eb..3819506ad 100644
--- a/core/switch_core/gateway/ui.py
+++ b/core/switch_core/gateway/ui.py
@@ -8,7 +8,7 @@ origin and the dashboard on another.
It answers ahead of the bearer middleware, because a person loading a page
holds a cookie rather than an agent key. So what it answers is an exact list
and never a fallback: the built files by name, and the dashboard's page paths,
-which `test_gateway_ui.py` holds equal to the routes in `gateway/src/App.tsx`.
+which `test_gateway_ui.py` holds equal to the routes the dashboard declares.
Everything else passes through untouched.
The API wins any path both could answer. `/agents` is where they meet: the
@@ -35,7 +35,8 @@ from switch_core.observability.http import GATEWAY_UI_SCOPE_KEY
logger = logging.getLogger(__name__)
-# The dashboard's page routes, as `gateway/src/App.tsx` declares them.
+# The dashboard's page routes, as `gateway/src/App.tsx` and its route table
+# (`gateway/src/routes/routeTable.tsx`) declare them, in both of its layouts.
PAGE_PATHS: tuple[str, ...] = (
"/",
"/login",
@@ -63,6 +64,32 @@ PAGE_PATHS: tuple[str, ...] = (
"/workspace",
"/organization",
"/operator/workspaces",
+ # The new layout's (`gateway_v2`). With it off they redirect to today's.
+ "/overview",
+ "/templates",
+ "/templates/{id}",
+ "/connectors/{connector_id}",
+ "/settings",
+ "/settings/general",
+ "/settings/users",
+ "/settings/messaging-apps",
+ "/settings/connectors",
+ "/settings/api-keys",
+ "/settings/guardrails",
+ "/settings/devices",
+ "/settings/account",
+ "/settings/org",
+ "/settings/org/general",
+ "/settings/org/workspaces",
+ "/settings/org/users",
+ "/settings/org/connectors",
+ "/settings/org/guardrails",
+ "/settings/org/devices",
+ "/settings/org/audit-log",
+ "/platform",
+ "/platform/workspaces",
+ "/platform/users",
+ "/platform/connectors",
)
_PARAM = re.compile(r"\{[^/}]+\}")
diff --git a/core/switch_core/management/controller_routes.py b/core/switch_core/management/controller_routes.py
index 030ce385e..af7006e15 100644
--- a/core/switch_core/management/controller_routes.py
+++ b/core/switch_core/management/controller_routes.py
@@ -101,7 +101,7 @@ class ControllerRoute(ManagementRoute):
error_body(
reason_codes.PROTOCOL_UNSUPPORTED,
f"Controller protocol {requested!r} is not supported; "
- f"this server accepts {SUPPORTED_PROTOCOLS}.",
+ f"Switch accepts {SUPPORTED_PROTOCOLS}.",
retryable=False,
),
status_code=426,
@@ -681,7 +681,7 @@ def _socket_principal(websocket: WebSocket, controller_id: str) -> ControllerPri
426,
reason_codes.PROTOCOL_UNSUPPORTED,
f"Controller protocol {requested!r} is not supported; "
- f"this server accepts {SUPPORTED_PROTOCOLS}.",
+ f"Switch accepts {SUPPORTED_PROTOCOLS}.",
)
return require_controller(controller_id, get_controller_principal(websocket))
diff --git a/core/switch_core/management/schemas.py b/core/switch_core/management/schemas.py
index 0897c54a9..50e4eee30 100644
--- a/core/switch_core/management/schemas.py
+++ b/core/switch_core/management/schemas.py
@@ -124,7 +124,7 @@ def _controller_name(value: str) -> str:
"""A machine's name, trimmed, and refused when nothing is left."""
trimmed = value.strip()
if not trimmed:
- raise ValueError("a machine's name must not be blank")
+ raise ValueError("a device's name must not be blank")
return trimmed
@@ -364,7 +364,7 @@ class _ControllerDetailsChange(BaseModel):
@classmethod
def _name_is_not_blank(cls, value: str | None) -> str | None:
if value is None:
- raise ValueError("a machine's name cannot be cleared")
+ raise ValueError("a device's name cannot be cleared")
return _controller_name(value)
@field_validator("description")
diff --git a/core/switch_core/management/service.py b/core/switch_core/management/service.py
index f9684d09d..9c3f08ff5 100644
--- a/core/switch_core/management/service.py
+++ b/core/switch_core/management/service.py
@@ -853,7 +853,7 @@ class ManagementService:
409,
reason_codes.VALIDATION_ERROR,
"This controller already has a different public key. Enroll "
- "the machine again to give it a new one.",
+ "the device again to give it a new one.",
)
if not details:
leases = await self.leases(session)
@@ -1005,15 +1005,15 @@ class ManagementService:
raise ManagementError(
409,
reason_codes.VALIDATION_ERROR,
- "This machine has no key to seal a login to yet. Update its "
+ "This device has no key to seal a login to yet. Update its "
"controller, which registers one when it next runs.",
)
if sealed.key_id != key_id(public_key["key"]):
raise ManagementError(
409,
reason_codes.VALIDATION_ERROR,
- "The login was sealed to a key this machine no longer has. Seal "
- "it again to the key the machine shows now.",
+ "The login was sealed to a key this device no longer has. Seal "
+ "it again to the key the device shows now.",
)
row = await self.controllers.put_sealed_login(
session,
@@ -1120,7 +1120,7 @@ class ManagementService:
raise ManagementError(
404,
reason_codes.PROVIDER_LOGIN_MISSING,
- f"No {provider} login has been given to this machine.",
+ f"No {provider} login has been given to this device.",
)
return {
"provider": row.provider,
diff --git a/core/switch_core/open_gate.py b/core/switch_core/open_gate.py
index ede82e8d0..56dddb749 100644
--- a/core/switch_core/open_gate.py
+++ b/core/switch_core/open_gate.py
@@ -291,7 +291,7 @@ async def _refuse(
# Rounded up to the millisecond clients wait in, so none comes back early.
seconds = math.ceil(retry_after_s * 1000) / 1000
message = (
- "This server is opening as many connections as it can take right now. "
+ "Switch is opening as many connections as it can take right now. "
f"Open again in {seconds:g} s."
)
path = scope.get("path", "")
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index 07e314ee3..787217a2b 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -511,9 +511,9 @@ class RoomService:
return
raise ChannelCreationUnsupported(
f"Creating channels is turned off for the '{bridge.display_name}' "
- "connection. Create the channel on the platform and add the Switch "
+ "messaging app. Create the channel on the platform and add the Switch "
"app to it — Switch adopts it as a room — or ask an administrator to "
- "allow channel creation for this connection."
+ "allow channel creation for this messaging app."
)
@staticmethod
@@ -1013,7 +1013,7 @@ class RoomService:
collaboration_core = self._collab_lifecycle.get(bridge_id)
if collaboration_core is None:
outcome = RetireOutcome.failed(
- "The messaging connection is not running, so Switch could not "
+ "The messaging app is not running, so Switch could not "
"reach the channel"
)
else:
diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.py
index 8fb79027c..399642018 100644
--- a/core/switch_core/rooms_yaml.py
+++ b/core/switch_core/rooms_yaml.py
@@ -297,7 +297,7 @@ def resolve_params(
+ ", ".join(missing)
+ " (none of the candidates listed for "
+ ", ".join(chains)
- + " is set up on this server)"
+ + " is set up here)"
)
raise ValueError(f"Missing required param(s): {', '.join(missing)}")
return resolved
@@ -794,7 +794,7 @@ class RoomYamlService:
for param, value in wanted["agent"]:
if value not in known:
raise ValueError(
- f"param {param!r}: no agent named {value!r} on this server"
+ f"param {param!r}: no agent named {value!r} here"
)
if "bridge" in wanted:
bridges = {
@@ -804,8 +804,7 @@ class RoomYamlService:
bridge = bridges.get(value)
if bridge is None:
raise ValueError(
- f"param {param!r}: no messaging app named {value!r} "
- "on this server"
+ f"param {param!r}: no messaging app named {value!r} here"
)
if bridge.status != "active":
raise ValueError(
@@ -816,7 +815,7 @@ class RoomYamlService:
for param, value in wanted["room"]:
if value not in rooms:
raise ValueError(
- f"param {param!r}: no room named {value!r} on this server"
+ f"param {param!r}: no room named {value!r} here"
)
if "user" in wanted:
@@ -1242,7 +1241,7 @@ class RoomYamlService:
if spec.users and bridge_id is None:
raise ValueError(
f"Room {spec.name!r} names users ({', '.join(spec.users)}), and "
- "it is on no messaging app: this server has none set up. Leave "
+ "it is on no messaging app: none is set up here. Leave "
"users out, or make them depend on a bridge."
)
@@ -1437,7 +1436,7 @@ class RoomYamlService:
failures.append({"kind": "kickoff", "id": "kickoff", "error": error})
if self._client_lifecycle is None:
- fail("kickoff posting is not configured on this server")
+ fail("kickoff posting is not configured here")
return
admins = self._client_lifecycle.get_by_type("admin", room.tenant_id)
admin = next((c for c in admins if isinstance(c, SystemActor)), None)
diff --git a/core/switch_core/template_lint.py b/core/switch_core/template_lint.py
index db0f0fb30..23e3fcb1a 100644
--- a/core/switch_core/template_lint.py
+++ b/core/switch_core/template_lint.py
@@ -190,7 +190,7 @@ def _check_params(raw: Any, errors: list[Finding], warnings: list[Finding]) -> s
warnings.append(
Finding(
"unknown_param_field",
- f"Parameter '{name}' sets '{where}', which this server "
+ f"Parameter '{name}' sets '{where}', which this Switch "
"does not know. It may be from a newer Switch, or a typo.",
name,
)
@@ -445,8 +445,8 @@ def _lint_v2(
warnings.append(
Finding(
"unknown_builtin",
- f"'{{{name}}}' looks like a server-provided value, but this "
- f"server provides only {', '.join(sorted(_BUILTINS))}.",
+ f"'{{{name}}}' looks like a value Switch provides, but it "
+ f"provides only {', '.join(sorted(_BUILTINS))}.",
name,
)
)
@@ -523,7 +523,7 @@ def lint_template(text: str) -> LintResult:
warnings.append(
Finding(
"unknown_top_level_key",
- f"'{key}' is not a key this server recognises. It will be "
+ f"'{key}' is not a key Switch recognises. It will be "
"stored as-is, but check it is not a typo.",
key,
)
@@ -592,8 +592,8 @@ def lint_template(text: str) -> LintResult:
warnings.append(
Finding(
"unknown_builtin",
- f"'{{{name}}}' looks like a server-provided value, but this "
- f"server provides only {', '.join(sorted(_BUILTINS))}.",
+ f"'{{{name}}}' looks like a value Switch provides, but it "
+ f"provides only {', '.join(sorted(_BUILTINS))}.",
name,
)
)
diff --git a/core/switch_core/template_runs.py b/core/switch_core/template_runs.py
index 191b87000..6616901c7 100644
--- a/core/switch_core/template_runs.py
+++ b/core/switch_core/template_runs.py
@@ -240,8 +240,8 @@ class TemplateAgents:
Problem(
plan.slot,
"agent_management_off",
- "agent management is not enabled on this Switch server, "
- "so it cannot create agents on a machine.",
+ "agent management is not turned on here, "
+ "so it cannot create agents on a device.",
)
for plan in plans
]
@@ -397,7 +397,7 @@ class TemplateAgents:
Problem(
plan.slot,
"connections_off",
- "connections are not enabled on this Switch server, so it "
+ "connectors are not turned on here, so it "
f"cannot be granted {', '.join(c.service for c in plan.connections)}.",
)
]
diff --git a/core/tests/switch_core/accounts/test_ownership_transfer.py b/core/tests/switch_core/accounts/test_ownership_transfer.py
index 6924218f9..41b7359d9 100644
--- a/core/tests/switch_core/accounts/test_ownership_transfer.py
+++ b/core/tests/switch_core/accounts/test_ownership_transfer.py
@@ -431,7 +431,7 @@ async def test_a_server_connectors_agent_is_refused(
session, "agent", agent.id, member, Principal(owner.id, False)
)
assert refused.value.status == 409
- assert "server connector" in str(refused.value)
+ assert "run by Switch itself" in str(refused.value)
async def test_an_agents_connection_rows_go_with_its_old_key(
@@ -653,11 +653,11 @@ class TestAgentTransferRefusal:
("fact", "value", "says"),
[
("granted_services", ("github",), "service access"),
- ("managed", True, "managed on its owner's machine"),
+ ("managed", True, "managed on its owner's device"),
("may_manage_agents", True, "manage its owner's agents"),
("in_family", True, "family of sub-agents"),
("has_oauth_client", True, "OAuth client of its own"),
- ("run_by_server_connector", True, "server connector"),
+ ("run_by_server_connector", True, "run by Switch itself"),
],
)
def test_each_tie_to_its_owner_refuses_on_its_own(
diff --git a/core/tests/switch_core/accounts/test_workspace_deletion.py b/core/tests/switch_core/accounts/test_workspace_deletion.py
index 126457bac..95c92380b 100644
--- a/core/tests/switch_core/accounts/test_workspace_deletion.py
+++ b/core/tests/switch_core/accounts/test_workspace_deletion.py
@@ -108,7 +108,7 @@ async def test_the_refusal_lists_what_is_left_by_kind_and_count(
assert reason is not None
assert "2 rooms (1 archived)" in reason
assert "1 agent" in reason
- assert "1 other member" in reason
+ assert "1 other user" in reason
async def test_the_default_workspace_is_refused(
@@ -256,9 +256,9 @@ async def test_what_is_still_in_use_blocks_beside_what_has_ended(
await _ended_and_live(session, tenant_id, owner_id, live=True)
reason = await refusal(session, tenant_id, owner_id)
assert reason is not None
- assert "1 machine" in reason
- assert "1 messaging app connection" in reason
- assert "1 cloud machine" in reason
+ assert "1 device" in reason
+ assert "1 installed app" in reason
+ assert "1 cloud device" in reason
async def test_a_workspace_deleted_meanwhile_is_not_found(
@@ -353,4 +353,4 @@ async def test_a_workspace_with_others_in_it_is_refused_with_what_is_left(
"DELETE", f"/tenants/{TENANT}", json={"name": TENANT}
)
assert response.status_code == 409, response.text
- assert "1 other member" in response.json()["detail"]
+ assert "1 other user" in response.json()["detail"]
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
index 600caa8ec..62f65ec83 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
@@ -452,7 +452,7 @@ class TestUpdateAgentDetail:
self,
) -> None:
dicebear = generated_icon_url("target")
- with pytest.raises(InvalidIconUrl, match="third-party avatars turned off"):
+ with pytest.raises(InvalidIconUrl, match="third-party avatars are turned off"):
_profile(icon_url=dicebear, third_party_avatars=False)
assert _profile(icon_url=dicebear).columns == {"icon_url": dicebear}
other = "https://example.com/r.png"
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.py b/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.py
index 368777dd6..b6b1414e8 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_controller_presence.py
@@ -405,7 +405,7 @@ class TestTheAgentClientsReplies:
assert reply is None
assert lapsed is not None
assert lapsed.startswith(
- "My machine, **machine**, is offline or reconnecting to Switch"
+ "My device, **machine**, is offline or reconnecting to Switch"
)
assert "Switch Console" not in lapsed
assert auto._agent_session_store.asked == []
@@ -511,7 +511,7 @@ class TestTheAgentClientsReplies:
again = await client._reply_when_unavailable_here(object(), agent, meta, "u")
assert first == (
- "My machine, **machine**, was asleep and is starting now. I'll pick "
+ "My device, **machine**, was asleep and is starting now. I'll pick "
"this up as soon as it's back, usually within a few minutes."
)
assert again is None
@@ -531,7 +531,7 @@ class TestTheAgentClientsReplies:
object(), _agent("auto", "auto_session"), meta, "u"
)
assert reply == (
- "My machine, **machine**, is stopped, so I can't answer. My owner "
+ "My device, **machine**, is stopped, so I can't answer. My owner "
"(@owner) can start it again in Switch Console."
)
@@ -553,15 +553,15 @@ class TestTheAgentClientsReplies:
removed = await client._reply_when_unavailable_here(object(), agent, meta, "u")
assert never_connected == (
- "My machine, **machine**, is offline or reconnecting to Switch, so "
+ "My device, **machine**, is offline or reconnecting to Switch, so "
"I can't answer right now. If I haven't answered once it's back, "
"address me again. If it stays offline, my owner (@owner) needs to "
"check it."
)
assert removed.startswith(
- "@owner — my machine, **machine**, has been removed from Switch"
+ "@owner — my device, **machine**, has been removed from Switch"
)
- assert "move me to another machine" in removed
+ assert "move me to another device" in removed
async def test_an_always_on_agent_is_available_while_its_controller_is(
self,
@@ -693,9 +693,9 @@ class TestAddressingAControllerBackedAgent:
async def test_a_disconnected_agent_gets_the_not_connected_reply(self) -> None:
cases = {
- "offline": "My machine, **machine**, is offline or reconnecting",
+ "offline": "My device, **machine**, is offline or reconnecting",
"stopped": "@owner — you've stopped me",
- "removed": "@owner — my machine, **machine**, has been removed",
+ "removed": "@owner — my device, **machine**, has been removed",
}
for case, expected in cases.items():
registry = AgentConnectionRegistry()
diff --git a/core/tests/switch_core/bridges/agent/test_commands_auto_route.py b/core/tests/switch_core/bridges/agent/test_commands_auto_route.py
index bee3544da..8755877f1 100644
--- a/core/tests/switch_core/bridges/agent/test_commands_auto_route.py
+++ b/core/tests/switch_core/bridges/agent/test_commands_auto_route.py
@@ -207,9 +207,7 @@ class TestAutoRouteCommand:
await _run(host, args)
- assert (
- "Automatic routing isn't switched on for this Switch server" in (posted[-1])
- )
+ assert "Automatic routing isn't switched on in Switch" in (posted[-1])
assert not await _on(session_factory, room_id)
async def test_on_without_a_decision_service_says_who_can_fix_it(
diff --git a/core/tests/switch_core/bridges/agent/test_service_tokens.py b/core/tests/switch_core/bridges/agent/test_service_tokens.py
index a24dd0ced..4477407e1 100644
--- a/core/tests/switch_core/bridges/agent/test_service_tokens.py
+++ b/core/tests/switch_core/bridges/agent/test_service_tokens.py
@@ -206,7 +206,7 @@ class TestRefusals:
response = await _fetch(harness, agent_id, bearer(key))
assert code(response) == (409, "connector_revoked")
- assert "Settings, Connections" in response.json()["error"]["message"]
+ assert "Switch Console, under Connectors" in response.json()["error"]["message"]
async def test_another_owners_controller_bound_to_the_agent(
self, harness: Harness
@@ -307,7 +307,7 @@ class TestAccessChanges:
response = await _fetch(harness, agent_id, bearer(key))
assert code(response) == (403, "grant_missing")
- assert "Connections" in response.json()["error"]["message"]
+ assert "from the agent's page" in response.json()["error"]["message"]
assert vendor.revoked == [issued]
async def test_relinking_another_account_needs_a_new_grant_and_the_same_does_not(
diff --git a/core/tests/switch_core/connections/test_broker.py b/core/tests/switch_core/connections/test_broker.py
index 88360c0fc..de74c8309 100644
--- a/core/tests/switch_core/connections/test_broker.py
+++ b/core/tests/switch_core/connections/test_broker.py
@@ -358,7 +358,7 @@ class TestIssue:
)
again = await _refused(broker, session_factory, world.agent.id)
assert again.code == "connector_revoked"
- assert "Settings, Connections" in again.message
+ assert "Switch Console, under Connectors" in again.message
assert vendor.refreshes == 1
assert vendor.issued == []
@@ -472,7 +472,7 @@ class TestChecks:
"internal",
False,
)
- assert "not available on this server" in refused.message
+ assert "not available here" in refused.message
assert await connectable(broker, "github") is False
async def test_an_owner_no_longer_in_the_workspace_is_forbidden(
@@ -496,7 +496,7 @@ class TestChecks:
await session.commit()
refused = await _refused(broker, session_factory, world.agent.id)
assert (refused.status_code, refused.code) == (403, "grant_missing")
- assert "builder" in refused.message and "Connections" in refused.message
+ assert "builder" in refused.message and "the agent's page" in refused.message
async def test_a_grant_made_on_someone_elses_connection_is_forbidden(
self, broker, session_factory
@@ -899,7 +899,7 @@ class TestSwitchedOff:
self, session_factory, vendor
) -> None:
broker = _switched_off(session_factory, vendor, {"github": ""})
- assert await availability(broker, "github") == "Switched off on this server."
+ assert await availability(broker, "github") == "Switched off here."
async def test_a_service_outside_the_catalog_stops_the_server(
self, session_factory, vendor
@@ -1313,7 +1313,7 @@ class TestPassThrough:
[("unset", SignIn(ConnectionSecret({}), None))],
)
assert warning is not None
- assert "unset is not set up on this server" in warning
+ assert "unset is not set up here" in warning
assert "Example access" not in warning
@@ -1714,7 +1714,7 @@ class TestReplacedClient:
refused = await _refused(broker, session_factory, world.agent.id)
assert refused.code == CONNECTOR_REVOKED
- assert "an app this server no longer uses" in refused.message
+ assert "an app Switch no longer uses" in refused.message
assert vendor.refreshes == 0 and vendor.issued == []
connection = await _connection(session_factory, world.owner.id)
assert connection is not None
@@ -1741,7 +1741,7 @@ class TestReplacedClient:
async with session_factory() as session:
warning = await broker.disconnect(session, world.owner.id, "github")
assert warning == (
- "GitHub is not set up on this server, so Switch could not revoke "
+ "GitHub is not set up here, so Switch could not revoke "
"the sign-in. Revoke it at GitHub."
)
assert vendor.connections_revoked == []
diff --git a/core/tests/switch_core/connections/test_registry.py b/core/tests/switch_core/connections/test_registry.py
index fc62839cd..7ef214c39 100644
--- a/core/tests/switch_core/connections/test_registry.py
+++ b/core/tests/switch_core/connections/test_registry.py
@@ -217,8 +217,8 @@ async def test_an_app_not_set_up_here_says_who_sets_it_up(
) -> None:
broker = _broker(_catalog(tmp_path, STATIC), session_factory, {}, None)
reason = (
- "{} is not set up on this server. Whoever runs your Switch server can "
- "set it up in Switch Console, under Admin → Connector apps."
+ "{} is not set up here. Whoever runs Switch can set it up in "
+ "Switch Console, under Admin → Connector apps."
)
assert await availability(broker, "example") == reason.format("Example")
assert await availability(broker, "github") == reason.format("GitHub")
@@ -238,8 +238,8 @@ async def test_a_service_signing_in_only_through_the_server_needs_its_public_url
assert example is not None
assert example.code == "needs_public_url"
assert example.reason == (
- "Example can't be connected on this server: it needs the server's "
- "public address (GATEWAY_PUBLIC_URL)."
+ "Example can't be connected here: it needs Switch's public address "
+ "(GATEWAY_PUBLIC_URL)."
)
assert (await standing(broker, "example")).server_setup_needed is False
# GitHub's App names its own callback, so it isn't held up the same way.
@@ -264,8 +264,7 @@ async def test_github_cannot_work_on_a_server_without_an_https_address(
assert github is not None
assert github.code == "needs_https"
assert github.reason == (
- "GitHub can't be used on this server: it needs the server to have an "
- "https address."
+ "GitHub can't be used here: it needs Switch to have an https address."
)
assert (await standing(broker, "github")).server_setup_needed is False
# Google and the like take an http address back, so their app still can be.
@@ -285,7 +284,7 @@ async def test_a_service_with_no_app_to_set_up_is_just_not_set_up(
assert atlassian is not None
assert (atlassian.code, atlassian.reason) == (
"not_set_up",
- "Atlassian is not set up on this server.",
+ "Atlassian is not set up here.",
)
assert (await standing(broker, "atlassian")).server_setup_needed is False
asana = (await standing(broker, "asana")).unavailable
diff --git a/core/tests/switch_core/delivery/test_conversation_journeys.py b/core/tests/switch_core/delivery/test_conversation_journeys.py
index b4af850bf..9f52608d8 100644
--- a/core/tests/switch_core/delivery/test_conversation_journeys.py
+++ b/core/tests/switch_core/delivery/test_conversation_journeys.py
@@ -804,7 +804,7 @@ class TestCommandsWhileTheFlagIsOff:
) # type: ignore[arg-type]
assert len(replies) == 3
- assert all("isn't switched on for this Switch server" in r for r in replies)
+ assert all("isn't switched on" in r for r in replies)
async with world.session_factory() as session:
assert await RoomStore().main_agent_id(session, world.room_id) is None
assert await RoomStore().follow_ups_enabled(session, world.room_id)
diff --git a/core/tests/switch_core/delivery/test_decision_routing.py b/core/tests/switch_core/delivery/test_decision_routing.py
index 2062e2354..3e89bbf06 100644
--- a/core/tests/switch_core/delivery/test_decision_routing.py
+++ b/core/tests/switch_core/delivery/test_decision_routing.py
@@ -298,7 +298,7 @@ class TestWhichMessagesAreAsked:
assert await room.reached(told) == set()
assert await room.reached(in_thread) == {"helper"}
- assert "isn't switched on for this Switch server" in reply
+ assert "isn't switched on" in reply
class TestWhatTheServiceIsSent:
@@ -1114,7 +1114,7 @@ class TestAWorkspaceWithNoBackend:
assert service.requests == []
assert await room.reached(told) == set()
assert room.room_notices == [DECISION_NOTICE]
- assert "refused by the server's outbound policy" in caplog.text
+ assert "refused by Switch's outbound policy" in caplog.text
def test_a_claim_lasts_the_decision_timeout_plus_a_margin():
diff --git a/core/tests/switch_core/delivery/test_offline_owner_reply.py b/core/tests/switch_core/delivery/test_offline_owner_reply.py
index 66843beab..1281370c7 100644
--- a/core/tests/switch_core/delivery/test_offline_owner_reply.py
+++ b/core/tests/switch_core/delivery/test_offline_owner_reply.py
@@ -301,7 +301,7 @@ class TestStartFromConsoleMessage:
"I don't have a session connected to this room. "
"@cmcd can start one connected to **Payments** by opening "
"**worker.test** in Switch Console. If Switch Console says I'm "
- "signed out, sign me in first with `agent login` on the machine I "
+ "signed out, sign me in first with `agent login` on the device I "
"run on."
)
diff --git a/core/tests/switch_core/gateway/test_agent_icon_route.py b/core/tests/switch_core/gateway/test_agent_icon_route.py
index 9d773d143..4f4ce69d1 100644
--- a/core/tests/switch_core/gateway/test_agent_icon_route.py
+++ b/core/tests/switch_core/gateway/test_agent_icon_route.py
@@ -314,7 +314,7 @@ class TestWithThirdPartyAvatarsOff:
)
assert refused.value.status_code == 400
- assert "third-party avatars turned off" in str(refused.value.detail)
+ assert "third-party avatars are turned off" in str(refused.value.detail)
stored = await _AGENT_STORE.get(session, agent.id)
assert stored is not None
assert stored.icon_url is None
diff --git a/core/tests/switch_core/gateway/test_bridge_delete_guard.py b/core/tests/switch_core/gateway/test_bridge_delete_guard.py
index f72d88f7e..e21ec042a 100644
--- a/core/tests/switch_core/gateway/test_bridge_delete_guard.py
+++ b/core/tests/switch_core/gateway/test_bridge_delete_guard.py
@@ -296,7 +296,7 @@ async def test_a_bridge_serving_several_installs_is_refused_for_all_of_them(
("slack", "revokes Switch's token at Slack", "then delete"),
("discord", "remove it in Discord", "token"),
("teams", "out of every team", "token"),
- ("telegram", "then delete the connection here", "token"),
+ ("telegram", "then delete the messaging app here", "token"),
],
)
def test_the_refusal_says_what_disconnecting_does_on_each_platform(
diff --git a/core/tests/switch_core/gateway/test_connector_apps.py b/core/tests/switch_core/gateway/test_connector_apps.py
index 2507d1270..4e968918f 100644
--- a/core/tests/switch_core/gateway/test_connector_apps.py
+++ b/core/tests/switch_core/gateway/test_connector_apps.py
@@ -643,8 +643,7 @@ class TestGitHubNeedsHttps:
services = {entry["slug"]: entry for entry in listed.json()["connections"]}
assert services["github"]["unavailable_code"] == "needs_https"
assert services["github"]["unavailable_reason"] == (
- "GitHub can't be used on this server: it needs the server to have an "
- "https address."
+ "GitHub can't be used here: it needs Switch to have an https address."
)
assert services["github"]["server_setup_needed"] is False
assert services[GOOGLE]["unavailable_code"] == "app_not_set_up"
@@ -822,7 +821,7 @@ class TestImportAndRemove:
assert google["server_setup_needed"] is True
assert google["unavailable_code"] == "app_not_set_up"
assert google["unavailable_reason"].startswith(
- "Google Workspace is not set up on this server."
+ "Google Workspace is not set up here."
)
assert [event.action for event in await _audit(session_factory)] == [
"connector_app.saved",
diff --git a/core/tests/switch_core/gateway/test_gateway_ui.py b/core/tests/switch_core/gateway/test_gateway_ui.py
index 7e1303996..8ab94ca63 100644
--- a/core/tests/switch_core/gateway/test_gateway_ui.py
+++ b/core/tests/switch_core/gateway/test_gateway_ui.py
@@ -31,7 +31,9 @@ from switch_core.observability.metrics import MetricsRegistry, install, uninstal
from switch_core.trust.client import NullTrustClient
from tests.db_buffer import QuietRooms
-_APP_TSX = Path(__file__).resolve().parents[4] / "gateway/src/App.tsx"
+_GATEWAY_SRC = Path(__file__).resolve().parents[4] / "gateway/src"
+_APP_TSX = _GATEWAY_SRC / "App.tsx"
+_ROUTE_TABLE = _GATEWAY_SRC / "routes/routeTable.tsx"
_INDEX = "<!doctype html><title>dashboard</title>"
_SCRIPT = "console.log('dashboard')"
@@ -89,25 +91,40 @@ def _normalized(path: str) -> str:
return re.sub(r"\{[^}]+\}", "{}", path)
-def _app_tsx_routes() -> set[str]:
- """Every page route `gateway/src/App.tsx` declares, as an absolute template."""
- source = _APP_TSX.read_text()
- routes = {"/"} if re.search(r"<Route\s+index\b", source) else set()
- for path in re.findall(r'<Route\b[^>]*?\bpath="([^"]+)"', source, re.DOTALL):
- if path == "*":
- continue
- absolute = path if path.startswith("/") else f"/{path}"
- routes.add(re.sub(r":[A-Za-z_]+", "{}", absolute))
+def _template(path: str) -> str:
+ absolute = path if path.startswith("/") else f"/{path}"
+ return re.sub(r":[A-Za-z_]+", "{}", absolute)
+
+
+def _dashboard_routes() -> set[str]:
+ """Every page route the dashboard declares, as an absolute template: the
+ signed-out and onboarding screens in `App.tsx`, and every page, settings
+ area and redirect of the signed-in dashboard in its route table, in both
+ layouts. A redirect's old URL is served too, or a reload of it would 404
+ instead of being sent on."""
+ app = _APP_TSX.read_text()
+ routes = {"/"} if re.search(r"<Route\s+index\b", app) else set()
+ for path in re.findall(r'<Route\b[^>]*?\bpath="([^"]+)"', app, re.DOTALL):
+ if path != "*":
+ routes.add(_template(path))
+ table = _ROUTE_TABLE.read_text()
+ for path in re.findall(
+ r'\b(?:page|settingsPage|areaIndex|redirect)\(\s*"([^"]+)"', table
+ ):
+ routes.add(_template(path))
return routes
def test_the_page_list_is_exactly_the_dashboards_routes() -> None:
- declared = _app_tsx_routes()
+ declared = _dashboard_routes()
listed = {_normalized(path) for path in PAGE_PATHS}
- assert declared, "found no routes in gateway/src/App.tsx; has it moved?"
+ assert declared, (
+ "found no routes in gateway/src; have App.tsx or the route table moved?"
+ )
assert listed == declared, (
"PAGE_PATHS in switch_core/gateway/ui.py must match the routes in "
- f"gateway/src/App.tsx. Missing: {sorted(declared - listed)}; "
+ "gateway/src/App.tsx and gateway/src/routes/routeTable.tsx. "
+ f"Missing: {sorted(declared - listed)}; "
f"not in the dashboard: {sorted(listed - declared)}."
)
diff --git a/core/tests/switch_core/gateway/test_github_connections.py b/core/tests/switch_core/gateway/test_github_connections.py
index 8ce48c269..34a23c56c 100644
--- a/core/tests/switch_core/gateway/test_github_connections.py
+++ b/core/tests/switch_core/gateway/test_github_connections.py
@@ -529,7 +529,7 @@ async def test_disconnect_works_once_the_app_is_removed(github_app):
result = await client.delete(BASE)
assert result.status_code == 200
assert result.json()["warning"] == (
- "GitHub is not set up on this server, so Switch could not revoke the "
+ "GitHub is not set up here, so Switch could not revoke the "
"sign-in. Revoke it at GitHub."
)
github.revoke.assert_not_called()
diff --git a/core/tests/switch_core/gateway/test_google_workspace.py b/core/tests/switch_core/gateway/test_google_workspace.py
index 898bba59e..031c1c59d 100644
--- a/core/tests/switch_core/gateway/test_google_workspace.py
+++ b/core/tests/switch_core/gateway/test_google_workspace.py
@@ -243,8 +243,7 @@ class TestTheClientSignedInThrough:
)
assert completed.status_code == 400
assert completed.json()["detail"] == (
- "This server's Google Workspace app changed during your sign-in. "
- "Start it again."
+ "Switch's Google Workspace app changed during your sign-in. Start it again."
)
assert [
request
@@ -452,12 +451,12 @@ class TestTheProfileChanging:
for refused in (issuing.value, granting.value):
assert (refused.status_code, refused.code) == (409, "connector_revoked")
assert issuing.value.message == (
- "The agent's owner must reconnect Google Workspace: this server now "
+ "The agent's owner must reconnect Google Workspace: Switch now "
"asks for other Google Workspace access than the sign-in granted. "
- "Reconnect it under Settings, Connections."
+ "Reconnect it in Switch Console, under Connectors."
)
assert granting.value.message == (
- "Reconnect Google Workspace under Settings, Connections first."
+ "Reconnect Google Workspace in Switch Console, under Connectors, first."
)
assert later.google.token_requests == []
@@ -693,9 +692,8 @@ class TestAvailability:
(
False,
{},
- "Google Workspace is not set up on this server. Whoever runs your "
- "Switch server can set it up in Switch Console, under Admin → "
- "Connector apps.",
+ "Google Workspace is not set up here. Whoever runs Switch can set "
+ "it up in Switch Console, under Admin → Connector apps.",
"app_not_set_up",
),
(
diff --git a/core/tests/switch_core/gateway/test_service_connections.py b/core/tests/switch_core/gateway/test_service_connections.py
index 0a7a00765..197838b76 100644
--- a/core/tests/switch_core/gateway/test_service_connections.py
+++ b/core/tests/switch_core/gateway/test_service_connections.py
@@ -282,7 +282,7 @@ class TestGrants:
response = await _put(harness, owner, agent_id, {"resources": RESOURCES})
assert response.status_code == 409
- assert "Settings, Connections" in response.json()["detail"]
+ assert "Switch Console, under Connectors" in response.json()["detail"]
async def test_write_on_a_read_only_connection(self, harness: Harness) -> None:
owner = await add_member(harness.session_factory, "ada")
diff --git a/core/tests/switch_core/gateway/test_signup.py b/core/tests/switch_core/gateway/test_signup.py
index ff36d6f68..5396666d5 100644
--- a/core/tests/switch_core/gateway/test_signup.py
+++ b/core/tests/switch_core/gateway/test_signup.py
@@ -498,7 +498,7 @@ async def test_signup_is_refused_once_the_hourly_cap_is_reached(signup_app, capl
response = await _signup(app, email="[email protected]")
assert response.status_code == 429, response.text
assert response.json()["detail"] == (
- "Too many sign-ups on this server in the last hour. Try again later."
+ "Too many sign-ups in the last hour. Try again later."
)
assert 1 <= int(response.headers["Retry-After"]) <= 3600
assert "2 users created in the last hour (cap 2)" in caplog.text
diff --git a/core/tests/switch_core/test_agent_icon.py b/core/tests/switch_core/test_agent_icon.py
index e7938d63c..ea0813525 100644
--- a/core/tests/switch_core/test_agent_icon.py
+++ b/core/tests/switch_core/test_agent_icon.py
@@ -325,7 +325,7 @@ def test_a_stored_host_clients_read_differently_counts_as_an_avatar_service(
def test_setting_an_avatar_service_icon_is_refused_only_with_them_off() -> None:
dicebear = generated_icon_url("pm-agent")
- with pytest.raises(InvalidIconUrl, match="third-party avatars turned off"):
+ with pytest.raises(InvalidIconUrl, match="third-party avatars are turned off"):
refuse_third_party_avatar(dicebear, third_party_avatars=False)
assert refuse_third_party_avatar(dicebear, third_party_avatars=True) == dicebear
other = "https://cdn.example.com/a.png"
diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yaml
index 720474c07..a1dc84162 100644
--- a/deploy/remote/helm/switch/values.yaml
+++ b/deploy/remote/helm/switch/values.yaml
@@ -499,7 +499,8 @@ switchCore:
# them while the server runs. An unknown flag stops switch-core at startup.
# Known flags: ecosystem.show_owners, agent_management, switch_cloud,
# hosted_agents, service_connections, agent_chats, follow_the_conversation,
- # switch_buddy, buddy_slack_handoff, decision_routing.
+ # switch_buddy, buddy_slack_handoff, decision_routing, gateway_v2
+ # (development and staging only until the new dashboard layout is finished).
featureFlags:
enabled: []
# Catalog services turned off on this server, each with the reason people
diff --git a/gateway/src/App.test.tsx b/gateway/src/App.test.tsx
index 5d70b5af2..cf9df7167 100644
--- a/gateway/src/App.test.tsx
+++ b/gateway/src/App.test.tsx
@@ -1,9 +1,10 @@
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { MemoryRouter } from "react-router";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { MemoryRouter, useLocation } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AppRoutes } from "./App";
import type { Session, TenantMembership } from "./data/api";
import { AuthProvider } from "./data/AuthContext";
+import type { FeatureFlagKey } from "./data/featureFlags";
import { clearPendingInvite, storePendingInvite } from "./data/sessionState";
const acme: TenantMembership = {
@@ -36,9 +37,11 @@ function session(overrides: Partial<Session>): Session {
};
}
+type Routes = Record<string, [number, unknown]>;
+
/** Every request answers from `routes` by path; anything else is a 404 so an
* unexpected call shows up as a failure rather than hanging. */
-function mockFetch(routes: Record<string, [number, unknown]>) {
+function mockFetch(routes: Routes) {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
@@ -49,16 +52,90 @@ function mockFetch(routes: Record<string, [number, unknown]>) {
);
}
+type Role = "member" | "workspace_admin" | "org_admin" | "operator";
+
+/** What the server answers for someone signed in to Acme as `role`: the
+ * session, the deployment's flags, and the workspace with its `administers`. */
+function signedInAs(
+ role: Role,
+ {
+ flags = [],
+ inOrganization = true,
+ tenants = [],
+ canDelete = false,
+ }: {
+ flags?: FeatureFlagKey[];
+ inOrganization?: boolean;
+ tenants?: TenantMembership[];
+ canDelete?: boolean;
+ } = {},
+): Routes {
+ const tenant: TenantMembership = {
+ ...acme,
+ role: role === "member" ? "member" : "admin",
+ organization_role: !inOrganization ? null : role === "org_admin" ? "org_admin" : "member",
+ organization_id: inOrganization ? "o1" : null,
+ };
+ return {
+ "/auth/session": [
+ 200,
+ session({
+ state: "ready",
+ tenant,
+ tenants: [tenant, ...tenants],
+ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: role === "operator" },
+ }),
+ ],
+ "/feature-flags": [200, { flags: flags.map((key) => ({ key, enabled: true })) }],
+ "/tenants/current": [
+ 200,
+ {
+ id: "t1",
+ slug: "acme",
+ name: "Acme",
+ role: tenant.role,
+ administers: role !== "member",
+ can_delete: canDelete,
+ can_manage_data_protection: canDelete,
+ },
+ ],
+ };
+}
+
+function LocationProbe() {
+ const { pathname, search, hash } = useLocation();
+ return <output data-testid="location">{`${pathname}${search}${hash}`}</output>;
+}
+
function renderAt(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<AuthProvider>
<AppRoutes />
+ <LocationProbe />
</AuthProvider>
</MemoryRouter>,
);
}
+async function railLabels(): Promise<string[]> {
+ const rail = await screen.findByRole("navigation", { name: "Main" });
+ return within(rail)
+ .getAllByRole("link")
+ .map((link) => link.textContent ?? "");
+}
+
+async function menuLabels(area: string): Promise<string[]> {
+ const menu = await screen.findByRole("navigation", { name: area });
+ return within(menu)
+ .getAllByRole("link")
+ .map((link) => link.textContent ?? "");
+}
+
+async function landsOn(path: string) {
+ await waitFor(() => expect(screen.getByTestId("location").textContent).toBe(path));
+}
+
const authConfig = {
oidc_enabled: true,
oidc_provider_label: "Example SSO",
@@ -66,13 +143,15 @@ const authConfig = {
signup_mode: "open",
};
-describe("AppRoutes", () => {
- afterEach(() => {
- cleanup();
- clearPendingInvite();
- vi.unstubAllGlobals();
- });
+afterEach(() => {
+ cleanup();
+ clearPendingInvite();
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ vi.unstubAllGlobals();
+});
+describe("AppRoutes", () => {
it("sends a signed-out visitor to sign in", async () => {
mockFetch({ "/auth/session": [401, { detail: "Not authenticated" }], "/auth/config": [200, authConfig] });
renderAt("/rooms");
@@ -90,14 +169,17 @@ describe("AppRoutes", () => {
});
it("offers to create a workspace to someone in none", async () => {
- mockFetch({ "/auth/session": [200, session({})] });
+ mockFetch({ "/auth/session": [200, session({})], "/feature-flags": [200, { flags: [] }] });
renderAt("/");
expect(await screen.findByText("Welcome to Switch")).toBeTruthy();
expect(screen.getByRole("button", { name: "Create organization" })).toBeTruthy();
});
it("only offers an invite when workspaces cannot be created", async () => {
- mockFetch({ "/auth/session": [200, session({ can_create_workspace: false })] });
+ mockFetch({
+ "/auth/session": [200, session({ can_create_workspace: false })],
+ "/feature-flags": [200, { flags: [] }],
+ });
renderAt("/");
expect(await screen.findByText(/Ask a workspace admin for an invite link/)).toBeTruthy();
expect(screen.queryByRole("button", { name: "Create organization" })).toBeNull();
@@ -106,6 +188,7 @@ describe("AppRoutes", () => {
it("asks someone in several workspaces to choose", async () => {
mockFetch({
"/auth/session": [200, session({ state: "needs_selection", tenants: [acme, beta] })],
+ "/feature-flags": [200, { flags: [] }],
});
renderAt("/rooms");
expect(await screen.findByText("Choose a workspace")).toBeTruthy();
@@ -114,9 +197,7 @@ describe("AppRoutes", () => {
});
it("opens the app in the current workspace", async () => {
- mockFetch({
- "/auth/session": [200, session({ state: "ready", tenant: acme, tenants: [acme, beta] })],
- });
+ mockFetch(signedInAs("org_admin", { tenants: [beta] }));
renderAt("/workspace");
expect(await screen.findByRole("heading", { name: "Acme" })).toBeTruthy();
expect(screen.getByRole("link", { name: /Workspace/ })).toBeTruthy();
@@ -126,15 +207,7 @@ describe("AppRoutes", () => {
it("gives the server's operator Connectors beside Users", async () => {
mockFetch({
- "/auth/session": [
- 200,
- session({
- state: "ready",
- tenant: acme,
- tenants: [acme],
- user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: true },
- }),
- ],
+ ...signedInAs("operator", { flags: ["service_connections"] }),
"/connector-apps": [200, { public_url: "https://switch.example.test", apps: [] }],
});
renderAt("/connectors");
@@ -145,9 +218,7 @@ describe("AppRoutes", () => {
it("puts a pending invite before everything else", async () => {
storePendingInvite("abc");
- mockFetch({
- "/auth/session": [200, session({ state: "ready", tenant: acme, tenants: [acme] })],
- });
+ mockFetch(signedInAs("org_admin"));
renderAt("/rooms");
expect(await screen.findByText("Join a workspace")).toBeTruthy();
});
@@ -155,7 +226,7 @@ describe("AppRoutes", () => {
it("drops a pending invite on sign-out, so the next person does not inherit it", async () => {
storePendingInvite("abc");
mockFetch({
- "/auth/session": [200, session({ state: "ready", tenant: acme, tenants: [acme] })],
+ ...signedInAs("org_admin"),
"/auth/logout": [200, { ok: true }],
"/auth/config": [200, authConfig],
});
@@ -173,9 +244,396 @@ describe("AppRoutes", () => {
).toBeTruthy();
expect(screen.queryByText("Switch Gateway")).toBeNull();
});
+
+ it("says so when the deployment's flags cannot be read, rather than hiding pages", async () => {
+ mockFetch({
+ ...signedInAs("member"),
+ "/feature-flags": [500, { detail: "flags unavailable" }],
+ });
+ renderAt("/rooms");
+ expect(await screen.findByText(/Could not load your session: flags unavailable/)).toBeTruthy();
+ });
+
+ it("says so when the workspace cannot be read, rather than treating everyone as a member", async () => {
+ mockFetch({
+ ...signedInAs("workspace_admin"),
+ "/tenants/current": [500, { detail: "workspace unavailable" }],
+ });
+ renderAt("/rooms");
+ expect(
+ await screen.findByText(/Could not load your session: workspace unavailable/),
+ ).toBeTruthy();
+ });
+
+ it("says there is no page at an address that is none", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/no-such-page");
+ expect(await screen.findByText("There's no page here")).toBeTruthy();
+ });
+});
+
+describe("today's layout", () => {
+ it("shows a member the pages anyone in the workspace may open", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/rooms");
+ expect(await railLabels()).toEqual([
+ "Ecosystem",
+ "Rooms",
+ "Resources",
+ "Agents",
+ "Apps",
+ "API keys",
+ "Workspace",
+ "Organization",
+ ]);
+ });
+
+ it("leaves Organization off the rail outside an organization", async () => {
+ mockFetch(signedInAs("member", { inOrganization: false }));
+ renderAt("/rooms");
+ expect(await railLabels()).not.toContain("Organization");
+ });
+
+ it("gives a workspace admin Usage, and Machines where agent management runs", async () => {
+ mockFetch(signedInAs("workspace_admin", { flags: ["agent_management"] }));
+ renderAt("/rooms");
+ const labels = await railLabels();
+ expect(labels).toContain("Usage");
+ expect(labels).toContain("Devices");
+ expect(labels).not.toContain("All workspaces");
+ });
+
+ it("gives the operator the platform's pages", async () => {
+ mockFetch(signedInAs("operator"));
+ renderAt("/rooms");
+ expect((await railLabels()).slice(-4)).toEqual(["Usage", "All workspaces", "Users", "Connectors"]);
+ });
+
+ it("refuses a page by its URL to someone who may not open it, and says why", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/usage");
+ expect(await screen.findByText("You don't have access to this page")).toBeTruthy();
+ expect(screen.getByText("Only this workspace's admins can open this page.")).toBeTruthy();
+ });
+
+ it("keeps the operator's pages from everyone else", async () => {
+ for (const path of ["/users", "/connectors", "/operator/workspaces"]) {
+ mockFetch(signedInAs("org_admin"));
+ renderAt(path);
+ expect(await screen.findByText("Only the platform operator can open this page.")).toBeTruthy();
+ cleanup();
+ }
+ });
+
+ it("says a page is not turned on, and tells the operator how", async () => {
+ mockFetch(signedInAs("operator"));
+ renderAt("/machines");
+ expect(await screen.findByText("Not turned on")).toBeTruthy();
+ expect(screen.getByText("Agent management isn't turned on here.")).toBeTruthy();
+ expect(
+ screen.getByText("An operator turns it on by adding agent_management to FEATURE_FLAGS_ENABLED."),
+ ).toBeTruthy();
+ });
+
+ it("does not tell anyone but the operator how to turn a page on", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/machines");
+ expect(await screen.findByText("Not turned on")).toBeTruthy();
+ expect(screen.queryByText(/FEATURE_FLAGS_ENABLED/)).toBeNull();
+ });
+
+ it("sends the new layout's URLs back to today's pages, keeping the query and fragment", async () => {
+ mockFetch(signedInAs("workspace_admin"));
+ renderAt("/settings/api-keys?q=ci#top");
+ await landsOn("/registration-keys?q=ci#top");
+ });
+
+ it("sends a template's new URL back to it under Resources", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/templates/tpl-1");
+ await landsOn("/resources/templates/tpl-1");
+ });
+
+ it("has no page at a URL only the new layout has", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/settings/account");
+ expect(await screen.findByText("There's no page here")).toBeTruthy();
+ });
+
+ it("opens on Rooms", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/");
+ await landsOn("/rooms");
+ });
+});
+
+describe("deleting the workspace", () => {
+ it("is offered where the server says the caller may delete it", async () => {
+ mockFetch(signedInAs("workspace_admin", { canDelete: true }));
+ renderAt("/workspace");
+ expect(await screen.findByRole("button", { name: "Delete workspace" })).toBeTruthy();
+ });
+
+ it("is not offered to an admin the server will not let delete it, such as an org admin", async () => {
+ mockFetch(signedInAs("org_admin", { canDelete: false }));
+ renderAt("/workspace");
+ expect(await screen.findByRole("heading", { name: "Acme" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Delete workspace" })).toBeNull();
+ });
+});
+
+describe("the new layout (gateway_v2)", () => {
+ const V2: FeatureFlagKey[] = ["gateway_v2"];
+
+ it("opens on Overview", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/");
+ await landsOn("/overview");
+ });
+
+ it("shows a member the new rail", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/overview");
+ expect(await railLabels()).toEqual([
+ "Overview",
+ "Agents",
+ "Rooms",
+ "Templates",
+ "Resources",
+ "Ecosystem",
+ "Settings",
+ ]);
+ });
+
+ it("puts Connectors on the rail where connectors run, and Platform for the operator", async () => {
+ mockFetch(signedInAs("operator", { flags: [...V2, "service_connections"] }));
+ renderAt("/overview");
+ const labels = await railLabels();
+ expect(labels).toContain("Connectors");
+ expect(labels.at(-1)).toBe("Platform");
+ });
+
+ it("moves today's pages, keeping the query and fragment", async () => {
+ const moves: [string, string][] = [
+ ["/collaborations?bridge=b1#teams", "/settings/messaging-apps?bridge=b1#teams"],
+ ["/registration-keys", "/settings/api-keys"],
+ ["/workspace", "/settings/users"],
+ ["/resources/templates/tpl-1", "/templates/tpl-1"],
+ ["/resources?tab=templates&q=ci#top", "/templates?q=ci#top"],
+ ];
+ for (const [from, to] of moves) {
+ mockFetch(signedInAs("workspace_admin", { flags: V2 }));
+ renderAt(from);
+ await landsOn(to);
+ cleanup();
+ }
+ });
+
+ it("moves the operator's pages to Platform", async () => {
+ for (const [from, to] of [
+ ["/operator/workspaces", "/platform/workspaces"],
+ ["/users", "/platform/users"],
+ ]) {
+ mockFetch(signedInAs("operator", { flags: V2 }));
+ renderAt(from);
+ await landsOn(to);
+ cleanup();
+ }
+ });
+
+ it("keeps Templates out of Resources", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/resources");
+ expect(await screen.findByRole("tab", { name: "References" })).toBeTruthy();
+ expect(screen.queryByRole("tab", { name: "Templates" })).toBeNull();
+ });
+
+ describe("workspace settings", () => {
+ it("shows a member the pages they may open, with nothing an admin's", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/settings/general");
+ expect(await menuLabels("Workspace settings")).toEqual([
+ "General",
+ "Users",
+ "Messaging apps",
+ "API keys",
+ "Guardrails",
+ "Your account",
+ ]);
+ });
+
+ it("gives a workspace admin Usage & budget, and Devices and Connectors where they run", async () => {
+ mockFetch(
+ signedInAs("workspace_admin", {
+ flags: [...V2, "agent_management", "service_connections"],
+ }),
+ );
+ renderAt("/settings/general");
+ expect(await menuLabels("Workspace settings")).toEqual([
+ "General",
+ "Users",
+ "Messaging apps",
+ "Connectors",
+ "API keys",
+ "Guardrails",
+ "Devices",
+ "Usage & budget",
+ "Your account",
+ ]);
+ });
+
+ it("leads an organization admin on to Organization settings", async () => {
+ mockFetch(signedInAs("org_admin", { flags: V2 }));
+ renderAt("/settings/general");
+ expect(await menuLabels("Workspace settings")).toContain("Organization settings ›");
+ });
+
+ it("keeps Usage & budget at its own URL, inside the area", async () => {
+ mockFetch(signedInAs("workspace_admin", { flags: V2 }));
+ renderAt("/usage");
+ expect(await menuLabels("Workspace settings")).toContain("Usage & budget");
+ });
+
+ it("refuses a settings page named in the URL, and says why", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/usage");
+ expect(await screen.findByText("Only this workspace's admins can open this page.")).toBeTruthy();
+ });
+
+ it("opens on the page last used there", async () => {
+ window.localStorage.setItem("switch.settings.lastPage.workspace", "/settings/api-keys");
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/settings");
+ await landsOn("/settings/api-keys");
+ });
+
+ it("opens on General when the page last used there may no longer be opened", async () => {
+ window.localStorage.setItem("switch.settings.lastPage.workspace", "/usage");
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/settings");
+ await landsOn("/settings/general");
+ });
+
+ it("remembers the page someone opens", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/settings/users");
+ await screen.findByRole("navigation", { name: "Workspace settings" });
+ await waitFor(() =>
+ expect(window.localStorage.getItem("switch.settings.lastPage.workspace")).toBe(
+ "/settings/users",
+ ),
+ );
+ });
+
+ it("carries a settings page across a workspace switch", async () => {
+ window.sessionStorage.setItem("switch.settings.afterSwitch", "/settings/api-keys");
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/settings");
+ await landsOn("/settings/api-keys");
+ expect(window.sessionStorage.getItem("switch.settings.afterSwitch")).toBeNull();
+ });
+
+ it("carries an organization settings page across to an organization admin", async () => {
+ window.sessionStorage.setItem("switch.settings.afterSwitch", "/settings/org/users");
+ mockFetch(signedInAs("org_admin", { flags: V2 }));
+ renderAt("/settings");
+ await landsOn("/settings/org/users");
+ });
+
+ it("lands on General after a switch to a workspace where the page may not be opened", async () => {
+ window.sessionStorage.setItem("switch.settings.afterSwitch", "/settings/org/users");
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/settings");
+ await landsOn("/settings/general");
+ });
+ });
+
+ describe("organization settings", () => {
+ it("lets an organization admin in, on General", async () => {
+ mockFetch(signedInAs("org_admin", { flags: V2 }));
+ renderAt("/organization");
+ await landsOn("/settings/org/general");
+ expect(await menuLabels("Organization settings")).toEqual([
+ "General",
+ "Workspaces",
+ "Users",
+ "Guardrails",
+ "Devices",
+ "Audit log",
+ "‹ Workspace settings",
+ ]);
+ });
+
+ it("lists Connectors and apps where the server lets organizations have them", async () => {
+ mockFetch(
+ signedInAs("org_admin", {
+ flags: [...V2, "service_connections", "organization_connector_apps"],
+ }),
+ );
+ renderAt("/settings/org/general");
+ expect(await menuLabels("Organization settings")).toContain("Connectors and apps");
+ });
+
+ it("lets the operator in, to restore an organization's admin, and no further", async () => {
+ mockFetch(signedInAs("operator", { flags: V2 }));
+ renderAt("/settings/org/users");
+ expect(await menuLabels("Organization settings")).toEqual([
+ "General",
+ "Workspaces",
+ "Users",
+ "‹ Workspace settings",
+ ]);
+ cleanup();
+
+ mockFetch(signedInAs("operator", { flags: V2 }));
+ renderAt("/settings/org/audit-log");
+ expect(await screen.findByText("Only the organization's admins can open this page.")).toBeTruthy();
+ });
+
+ it("keeps workspace admins and members out, showing no menu", async () => {
+ for (const role of ["workspace_admin", "member"] as const) {
+ mockFetch(signedInAs(role, { flags: V2 }));
+ renderAt("/settings/org/users");
+ expect(
+ await screen.findByText("Only the organization's admins can open this page."),
+ ).toBeTruthy();
+ expect(screen.queryByRole("navigation", { name: "Organization settings" })).toBeNull();
+ cleanup();
+ }
+ });
+
+ it("is not offered to a workspace admin", async () => {
+ mockFetch(signedInAs("workspace_admin", { flags: V2 }));
+ renderAt("/settings/general");
+ expect(await menuLabels("Workspace settings")).not.toContain("Organization settings ›");
+ });
+ });
+
+ describe("platform", () => {
+ it("gives the operator their pages", async () => {
+ mockFetch(signedInAs("operator", { flags: V2 }));
+ renderAt("/platform");
+ await landsOn("/platform/workspaces");
+ expect(await menuLabels("Platform")).toEqual(["All workspaces", "Users", "Connectors"]);
+ });
+
+ it("keeps everyone else out", async () => {
+ mockFetch(signedInAs("org_admin", { flags: V2 }));
+ renderAt("/platform/users");
+ expect(await screen.findByText("Only the platform operator can open this page.")).toBeTruthy();
+ });
+ });
+
+ it("shows a page that is not built yet as such", async () => {
+ mockFetch(signedInAs("member", { flags: V2 }));
+ renderAt("/settings/guardrails");
+ expect(
+ await screen.findByText("This page is part of the new layout and isn't built yet."),
+ ).toBeTruthy();
+ });
});
-describe("a page restored by back or forward", () => {
+describe("a page that falls behind the server", () => {
const originalLocation = window.location;
const reload = vi.fn();
@@ -188,23 +646,20 @@ describe("a page restored by back or forward", () => {
});
afterEach(() => {
- cleanup();
- vi.unstubAllGlobals();
reload.mockClear();
Object.defineProperty(window, "location", {
configurable: true,
writable: true,
value: originalLocation,
});
+ Reflect.deleteProperty(document, "visibilityState");
});
async function restoreAfter(serverSession: Session) {
- mockFetch({
- "/auth/session": [200, session({ state: "ready", tenant: acme, tenants: [acme, beta] })],
- });
+ mockFetch(signedInAs("org_admin", { tenants: [beta] }));
renderAt("/workspace");
expect(await screen.findByRole("heading", { name: "Acme" })).toBeTruthy();
- mockFetch({ "/auth/session": [200, serverSession] });
+ mockFetch({ ...signedInAs("org_admin"), "/auth/session": [200, serverSession] });
window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }));
await waitFor(() => expect(fetch).toHaveBeenCalled());
}
@@ -219,4 +674,65 @@ describe("a page restored by back or forward", () => {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(reload).not.toHaveBeenCalled();
});
+
+ function comeBackToTheTab() {
+ Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" });
+ document.dispatchEvent(new Event("visibilitychange"));
+ }
+
+ it("reads the session once when a restore and a tab coming back arrive together", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/rooms");
+ await railLabels();
+ mockFetch(signedInAs("member"));
+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }));
+ comeBackToTheTab();
+ await waitFor(() => expect(fetch).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const sessionReads = vi
+ .mocked(fetch)
+ .mock.calls.filter(([input]) => String(input).endsWith("/auth/session"));
+ expect(sessionReads).toHaveLength(1);
+ });
+
+ it("warns, keeping the page, when the session cannot be read on coming back to the tab", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/rooms");
+ await railLabels();
+ mockFetch({ ...signedInAs("member"), "/auth/session": [503, { detail: "server restarting" }] });
+ comeBackToTheTab();
+ expect(
+ await screen.findByText(/Could not check your session with Switch: server restarting/),
+ ).toBeTruthy();
+ expect(await railLabels()).toContain("Rooms");
+
+ mockFetch(signedInAs("member"));
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await waitFor(() =>
+ expect(screen.queryByText(/Could not check your session with the server/)).toBeNull(),
+ );
+ });
+
+ it("fails loud when a restored page cannot be checked, since it may be another workspace's", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/rooms");
+ await railLabels();
+ mockFetch({ ...signedInAs("member"), "/auth/session": [503, { detail: "server restarting" }] });
+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }));
+ expect(
+ await screen.findByText(/Could not load your session: server restarting/),
+ ).toBeTruthy();
+ });
+
+ it("follows a change of role when the tab comes back", async () => {
+ mockFetch(signedInAs("member"));
+ renderAt("/rooms");
+ expect(await railLabels()).not.toContain("Usage");
+
+ mockFetch(signedInAs("workspace_admin"));
+ comeBackToTheTab();
+
+ await waitFor(async () => expect(await railLabels()).toContain("Usage"));
+ expect(reload).not.toHaveBeenCalled();
+ });
});
diff --git a/gateway/src/App.tsx b/gateway/src/App.tsx
index 2e1e57e7c..7e3205ba8 100644
--- a/gateway/src/App.tsx
+++ b/gateway/src/App.tsx
@@ -3,34 +3,13 @@ import { BrowserRouter, Navigate, Route, Routes } from "react-router";
import { AuthProvider, useAuth } from "./data/AuthContext";
import { appView, readPendingInvite } from "./data/sessionState";
import PageShell from "./layout/PageShell";
-import AgentDetailPage from "./pages/agents/AgentDetailPage";
-import AgentsPage from "./pages/agents/AgentsPage";
+import { renderRoutes } from "./routes/renderRoutes";
+import { NotFoundPage } from "./routes/StatusPages";
import LoginPage from "./pages/auth/LoginPage";
-import CollaborationsPage from "./pages/collaborations/CollaborationsPage";
-import ConnectorAppsPage from "./pages/connector-apps/ConnectorAppsPage";
-import EcosystemGraphPage from "./pages/ecosystem/EcosystemGraphPage";
-import MachinesPage from "./pages/machines/MachinesPage";
-import RegistrationKeysPage from "./pages/registration-keys/RegistrationKeysPage";
-import DocumentDetailPage from "./pages/resources/DocumentDetailPage";
-import PackageDetailPage from "./pages/resources/PackageDetailPage";
-import ReferenceDetailPage from "./pages/resources/ReferenceDetailPage";
-import ResourcesPage from "./pages/resources/ResourcesPage";
-import TemplateDetailPage from "./pages/resources/TemplateDetailPage";
-import CreateRoomPage from "./pages/rooms/CreateRoomPage";
-import GroupsPage from "./pages/rooms/GroupsPage";
-import RoomDetailPage from "./pages/rooms/RoomDetailPage";
-import RoomScopedDocumentView from "./pages/rooms/RoomScopedDocumentView";
-import RoomsGraphPage from "./pages/rooms/RoomsGraphPage";
-import RoomsPage from "./pages/rooms/RoomsPage";
import AcceptInvitePage from "./pages/onboarding/AcceptInvitePage";
import InviteCapture from "./pages/onboarding/InviteCapture";
import OnboardingPage from "./pages/onboarding/OnboardingPage";
import WorkspacePickerPage from "./pages/onboarding/WorkspacePickerPage";
-import OperatorWorkspacesPage from "./pages/operator/OperatorWorkspacesPage";
-import OrganizationPage from "./pages/organization/OrganizationPage";
-import UsagePage from "./pages/usage/UsagePage";
-import UsersPage from "./pages/users/UsersPage";
-import WorkspacePage from "./pages/workspace/WorkspacePage";
function FullScreen({ children }: { children: React.ReactNode }) {
return (
@@ -48,7 +27,7 @@ function FullScreen({ children }: { children: React.ReactNode }) {
}
export function AppRoutes() {
- const { session, loading, loadError } = useAuth();
+ const { session, loading, loadError, capabilities } = useAuth();
if (loading) {
return (
@@ -106,48 +85,12 @@ export function AppRoutes() {
);
}
+ const layout = capabilities.features.gateway_v2 ? "v2" : "current";
return (
<Routes>
- <Route element={<PageShell />}>
- <Route index element={<Navigate to="/rooms" replace />} />
- <Route path="ecosystem" element={<EcosystemGraphPage />} />
- <Route path="rooms" element={<RoomsPage />} />
- <Route path="rooms/new" element={<CreateRoomPage />} />
- <Route path="rooms/groups" element={<GroupsPage />} />
- <Route path="rooms/graph" element={<RoomsGraphPage />} />
- <Route path="rooms/:roomId" element={<RoomDetailPage />} />
- <Route
- path="rooms/:roomId/documents/:documentId"
- element={<RoomScopedDocumentView />}
- />
- <Route path="resources" element={<ResourcesPage />} />
- <Route
- path="resources/references/:id"
- element={<ReferenceDetailPage />}
- />
- <Route
- path="resources/documents/:id"
- element={<DocumentDetailPage />}
- />
- <Route
- path="resources/packages/:id"
- element={<PackageDetailPage />}
- />
- <Route
- path="resources/templates/:id"
- element={<TemplateDetailPage />}
- />
- <Route path="agents" element={<AgentsPage />} />
- <Route path="agents/:agentId" element={<AgentDetailPage />} />
- <Route path="machines" element={<MachinesPage />} />
- <Route path="collaborations" element={<CollaborationsPage />} />
- <Route path="registration-keys" element={<RegistrationKeysPage />} />
- <Route path="usage" element={<UsagePage />} />
- <Route path="users" element={<UsersPage />} />
- <Route path="connectors" element={<ConnectorAppsPage />} />
- <Route path="workspace" element={<WorkspacePage />} />
- <Route path="organization" element={<OrganizationPage />} />
- <Route path="operator/workspaces" element={<OperatorWorkspacesPage />} />
+ <Route element={<PageShell layout={layout} />}>
+ {renderRoutes(layout)}
+ <Route path="*" element={<NotFoundPage />} />
</Route>
<Route path="/invite" element={<InviteCapture />} />
<Route path="/login" element={<Navigate to="/" replace />} />
diff --git a/gateway/src/components/TransferOwnershipSection.test.ts b/gateway/src/components/TransferOwnershipSection.test.ts
index 7c09bd05e..f7ed1e434 100644
--- a/gateway/src/components/TransferOwnershipSection.test.ts
+++ b/gateway/src/components/TransferOwnershipSection.test.ts
@@ -2,19 +2,17 @@ import { describe, expect, it } from "vitest";
import type { Member } from "../data/api";
import { transferCandidates } from "./TransferOwnershipSection";
-const member = (user_id: string): Member => ({ user_id }) as Member;
+const member = (user_id: string, can_receive_transfer = true): Member =>
+ ({ user_id, can_receive_transfer }) as Member;
describe("transferCandidates", () => {
- const members = [member("owner"), member("admin"), member("other")];
-
- it("leaves out the owner when the owner transfers", () => {
- expect(transferCandidates(members, "owner", "owner").map((m) => m.user_id)).toEqual([
- "admin",
- "other",
- ]);
- });
-
- it("leaves out an admin transferring someone else's thing", () => {
- expect(transferCandidates(members, "owner", "admin").map((m) => m.user_id)).toEqual(["other"]);
+ it("offers whoever the server says may receive it, but its owner", () => {
+ const members = [
+ member("owner"),
+ member("caller", false),
+ member("org-admin-through-the-organization", false),
+ member("other"),
+ ];
+ expect(transferCandidates(members, "owner").map((m) => m.user_id)).toEqual(["other"]);
});
});
diff --git a/gateway/src/components/TransferOwnershipSection.tsx b/gateway/src/components/TransferOwnershipSection.tsx
index d49c7443f..6397c29ab 100644
--- a/gateway/src/components/TransferOwnershipSection.tsx
+++ b/gateway/src/components/TransferOwnershipSection.tsx
@@ -22,6 +22,9 @@ interface Props {
resourceId: string;
resourceLabel: string;
ownerId: string | null;
+ // Why the server would refuse to move it, which disables the button and is
+ // shown beside it; null when it can be moved.
+ blockedReason: string | null;
onTransferred: () => void;
}
@@ -35,15 +38,11 @@ const LABELS: Record<OwnershipKind, string> = {
template: "template",
};
-/** Who the thing can go to: anyone in the workspace but its owner and the
- * caller. An admin handing over someone else's thing can't take it for
- * themselves; the server refuses that too. */
-export function transferCandidates(
- members: Member[],
- ownerId: string | null,
- callerId: string | null,
-): Member[] {
- return members.filter((m) => m.user_id !== ownerId && m.user_id !== callerId);
+/** Who the thing can go to: whoever the server says may receive it (a
+ * member of this workspace other than the caller, and not an organization
+ * admin listed through the organization), but the owner it already has. */
+export function transferCandidates(members: Member[], ownerId: string | null): Member[] {
+ return members.filter((m) => m.can_receive_transfer && m.user_id !== ownerId);
}
/** Hands the thing to another member of this workspace. The server decides
@@ -53,6 +52,7 @@ export default function TransferOwnershipSection({
resourceId,
resourceLabel,
ownerId,
+ blockedReason,
onTransferred,
}: Props) {
const [open, setOpen] = useState(false);
@@ -66,10 +66,16 @@ export default function TransferOwnershipSection({
variant="outlined"
startIcon={<SwapHoriz />}
onClick={() => setOpen(true)}
+ disabled={blockedReason !== null}
sx={{ alignSelf: "flex-start" }}
>
Transfer ownership
</Button>
+ {blockedReason !== null && (
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
+ {blockedReason}
+ </Typography>
+ )}
{open && (
<TransferOwnershipDialog
kind={kind}
@@ -106,7 +112,7 @@ export function TransferOwnershipDialog({
onClose,
onTransferred,
}: DialogProps) {
- const { session, user } = useAuth();
+ const { session } = useAuth();
const tenantId = session?.tenant?.id;
const [members, setMembers] = useState<Member[] | null>(null);
const [recipient, setRecipient] = useState("");
@@ -122,7 +128,7 @@ export function TransferOwnershipDialog({
if (!cancelled) setMembers(found);
})
.catch((e) => {
- if (!cancelled) setError(e instanceof Error ? e.message : "Could not load members");
+ if (!cancelled) setError(e instanceof Error ? e.message : "Could not load users");
});
return () => {
cancelled = true;
@@ -147,7 +153,7 @@ export function TransferOwnershipDialog({
}
};
- const candidates = transferCandidates(members ?? [], ownerId, user?.id ?? null);
+ const candidates = transferCandidates(members ?? [], ownerId);
return (
<Dialog open onClose={close} fullWidth maxWidth="xs">
@@ -174,7 +180,7 @@ export function TransferOwnershipDialog({
aria-label="New owner"
>
<MenuItem value="" disabled>
- Choose a member
+ Choose a user
</MenuItem>
{candidates.map((m) => (
<MenuItem key={m.user_id} value={m.user_id}>
diff --git a/gateway/src/data/AuthContext.tsx b/gateway/src/data/AuthContext.tsx
index 7ea33d690..37c39366d 100644
--- a/gateway/src/data/AuthContext.tsx
+++ b/gateway/src/data/AuthContext.tsx
@@ -1,15 +1,21 @@
import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import {
+ type CurrentTenant,
type Session,
type SessionUser,
+ fetchFeatureFlags,
fetchSession,
+ loadCurrentTenant,
login as apiLogin,
logout as apiLogout,
signOutEverywhere,
switchTenant,
} from "./api";
-import { canAdminTenant as sessionCanAdminTenant, clearPendingInvite } from "./sessionState";
+import { type Capabilities, capabilitiesOf } from "./capabilities";
+import { ALL_OFF, type FeatureFlags, GATEWAY_V2 } from "./featureFlags";
+import { landingAfterSwitch } from "./settingsLanding";
+import { clearPendingInvite } from "./sessionState";
interface AuthState {
session: Session | null;
@@ -20,6 +26,11 @@ interface AuthState {
loadError: string | null;
isOperator: boolean;
canAdminTenant: boolean;
+ capabilities: Capabilities;
+ // Set when the session could not be read again on coming back to the tab:
+ // what the page shows may be out of date, and it says so.
+ staleError: string | null;
+ recheck: () => void;
refresh: () => Promise<void>;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
@@ -27,19 +38,45 @@ interface AuthState {
switchTo: (tenantId: string) => Promise<void>;
}
+interface Loaded {
+ session: Session | null;
+ tenant: CurrentTenant | null;
+ flags: FeatureFlags;
+}
+
+/** The session, and with it what the dashboard needs before it can decide
+ * what anyone may open: the deployment's flags, and the current workspace as
+ * the server sees the caller in it. All three or an error, never a partial
+ * answer that would hide pages for the wrong reason. */
+async function loadAll(): Promise<Loaded> {
+ const session = await fetchSession();
+ if (session === null) return { session: null, tenant: null, flags: ALL_OFF };
+ const [flags, tenant] = await Promise.all([
+ fetchFeatureFlags(),
+ session.state === "ready" ? loadCurrentTenant() : Promise.resolve(null),
+ ]);
+ return { session, tenant, flags };
+}
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : "Could not load your session";
+}
+
const AuthContext = createContext<AuthState | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
- const [session, setSession] = useState<Session | null>(null);
+ const [loaded, setLoaded] = useState<Loaded>({ session: null, tenant: null, flags: ALL_OFF });
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState<string | null>(null);
+ const [staleError, setStaleError] = useState<string | null>(null);
const refresh = useCallback(async () => {
try {
- setSession(await fetchSession());
+ setLoaded(await loadAll());
setLoadError(null);
+ setStaleError(null);
} catch (err) {
- setLoadError(err instanceof Error ? err.message : "Could not load your session");
+ setLoadError(errorMessage(err));
}
}, []);
@@ -47,33 +84,65 @@ export function AuthProvider({ children }: { children: ReactNode }) {
refresh().finally(() => setLoading(false));
}, [refresh]);
- // Back or forward can restore this page from the browser's cache, as it was
- // left. Switching workspace leaves it by a full load (see `switchTo`), so a
- // restored page may hold another workspace's session and data, and every
- // request it makes would name that workspace. Reload it when the session it
- // holds is no longer the server's.
- const heldSession = useRef<Session | null>(null);
+ // What this page holds can fall behind the server. Back or forward can
+ // restore it from the browser's cache as it was left, and switching
+ // workspace leaves it by a full load (see `switchTo`), so a restored page
+ // may hold another workspace's session and data, and every request it
+ // makes would name that workspace: reload it. A role can change while the
+ // page sits in a background tab, so it is read again whenever the tab comes
+ // back, and the route guards and rail follow what the server now says.
+ //
+ // One read at a time: a restore fires both events at once. Not being able
+ // to read it is loud for a restored page, which may belong to another
+ // workspace, and a warning for a tab coming back, which holds this one's.
+ const held = useRef<Session | null>(null);
useEffect(() => {
- heldSession.current = session;
- }, [session]);
- useEffect(() => {
- const onPageShow = async (event: PageTransitionEvent) => {
- if (!event.persisted) return;
- let current: Session | null;
+ held.current = loaded.session;
+ }, [loaded.session]);
+ const reading = useRef<Promise<void> | null>(null);
+ const restoredWhileReading = useRef(false);
+ const revalidate = useCallback((restored: boolean) => {
+ restoredWhileReading.current ||= restored;
+ if (reading.current !== null) return;
+ reading.current = (async () => {
+ let current: Loaded;
try {
- current = await fetchSession();
+ current = await loadAll();
} catch (err) {
- setLoadError(err instanceof Error ? err.message : "Could not load your session");
+ if (restoredWhileReading.current) setLoadError(errorMessage(err));
+ else setStaleError(errorMessage(err));
return;
}
- const held = heldSession.current;
- if (current?.user.id !== held?.user.id || current?.tenant?.id !== held?.tenant?.id) {
+ const before = held.current;
+ if (
+ current.session?.user.id !== before?.user.id ||
+ current.session?.tenant?.id !== before?.tenant?.id
+ ) {
window.location.reload();
+ return;
}
+ setStaleError(null);
+ setLoaded(current);
+ })().finally(() => {
+ reading.current = null;
+ restoredWhileReading.current = false;
+ });
+ }, []);
+ useEffect(() => {
+ const onPageShow = (event: PageTransitionEvent) => {
+ if (event.persisted) revalidate(true);
+ };
+ const onVisibilityChange = () => {
+ if (document.visibilityState === "visible") revalidate(false);
};
window.addEventListener("pageshow", onPageShow);
- return () => window.removeEventListener("pageshow", onPageShow);
- }, []);
+ document.addEventListener("visibilitychange", onVisibilityChange);
+ return () => {
+ window.removeEventListener("pageshow", onPageShow);
+ document.removeEventListener("visibilitychange", onVisibilityChange);
+ };
+ }, [revalidate]);
+ const recheck = useCallback(() => revalidate(false), [revalidate]);
const login = useCallback(
async (email: string, password: string) => {
@@ -88,29 +157,37 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// they never followed.
clearPendingInvite();
await apiLogout();
- setSession(null);
+ setLoaded({ session: null, tenant: null, flags: ALL_OFF });
}, []);
const logoutEverywhere = useCallback(async () => {
clearPendingInvite();
await signOutEverywhere();
- setSession(null);
+ setLoaded({ session: null, tenant: null, flags: ALL_OFF });
}, []);
// A full reload rather than a state update: every page holds data fetched
// for the workspace it was opened in, and none of it is valid in the next.
- const switchTo = useCallback(async (tenantId: string) => {
- await switchTenant(tenantId);
- window.location.assign("/");
- }, []);
+ const newLayout = loaded.flags[GATEWAY_V2];
+ const switchTo = useCallback(
+ async (tenantId: string) => {
+ await switchTenant(tenantId);
+ window.location.assign(landingAfterSwitch(window.location.pathname, newLayout));
+ },
+ [newLayout],
+ );
+ const capabilities = capabilitiesOf(loaded.session, loaded.tenant, loaded.flags);
const value: AuthState = {
- session,
- user: session?.user ?? null,
+ session: loaded.session,
+ user: loaded.session?.user ?? null,
loading,
loadError,
- isOperator: session?.user.is_operator ?? false,
- canAdminTenant: sessionCanAdminTenant(session),
+ isOperator: capabilities.isOperator,
+ canAdminTenant: capabilities.administersWorkspace,
+ capabilities,
+ staleError,
+ recheck,
refresh,
login,
logout,
diff --git a/gateway/src/data/api.test.ts b/gateway/src/data/api.test.ts
index 17aa12a62..3c47de2a8 100644
--- a/gateway/src/data/api.test.ts
+++ b/gateway/src/data/api.test.ts
@@ -99,12 +99,12 @@ describe("fetchTeamPlacements", () => {
});
it("throws the server's own words on a connection that is not running", async () => {
- respond(409, { detail: "The Teams connection is not running; try again in a moment." });
+ respond(409, { detail: "The Teams messaging app is not running; try again in a moment." });
const err = await fetchTeamPlacements("b1").catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect((err as ApiError).status).toBe(409);
expect((err as ApiError).message).toBe(
- "The Teams connection is not running; try again in a moment.",
+ "The Teams messaging app is not running; try again in a moment.",
);
});
});
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index d953d80b9..a36867c88 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1,3 +1,5 @@
+import { type FeatureFlagState, type FeatureFlags, featureFlagsFrom } from "./featureFlags";
+
const BASE = "/gateway";
async function fetchJson<T>(path: string, init?: RequestInit): Promise<T | null> {
@@ -36,13 +38,18 @@ export interface RoomSummary {
created_at: string;
archived: boolean;
// What the viewer may do, as the server decides it. `can_write` covers the
- // room's settings, roles, participants, links and attaching resources;
+ // room's settings, roles, links and attaching resources;
+ // `can_change_members` covers adding and removing its agents and people,
+ // which a direct or group chat takes from its platform instead;
// `can_manage` (owner or workspace admin) covers its access and deleting it;
// `can_unlink` (taking part in it, or workspace admin) covers unlinking a
- // reference, document or package from it.
+ // reference, document or package from it; `can_transfer` (managing it,
+ // and never for a chat) covers handing it to someone else.
can_write: boolean;
+ can_change_members: boolean;
can_manage: boolean;
can_unlink: boolean;
+ can_transfer: boolean;
}
export interface AgentSummary {
@@ -63,9 +70,19 @@ export interface AgentSummary {
parent_agent_id: string | null;
known_agent_type: string | null;
known_agent_options: Record<string, unknown> | null;
- // Whether the caller may rename the agent and edit its options and who may
- // address it, as the server decides it: its owner or a workspace admin.
+ // What the caller may do to the agent, as the server decides it.
+ // `can_manage` (its owner or a workspace admin) covers its options, icon,
+ // display name, description, who may address it, and deleting it.
can_manage: boolean;
+ // Renaming it: managing it, and neither a sub-agent nor a parent of one.
+ can_rename: boolean;
+ // Editing its options: managing it, and Switch Console running it from an
+ // agent type it knows, which is where its options come from.
+ can_edit_options: boolean;
+ can_transfer: boolean;
+ // Why it cannot be handed to someone else, for whoever manages it; null
+ // when it can, or when they could not anyway.
+ transfer_blocked_reason: string | null;
}
export interface AgentToolSummary {
@@ -113,6 +130,12 @@ export interface AgentDetail extends AgentSummary {
* Only the owner changes it.
*/
can_manage_agents: boolean;
+ // Its owner's alone: letting it manage their agents, and granting it their
+ // service connections (only where the server runs them, and only to an
+ // agent run from a known agent type). Seeing and removing the grants it
+ // has needs only ownership.
+ can_change_manage_agents: boolean;
+ can_grant_services: boolean;
}
// Scoped agent-addressing permissions (CHOO-1585). Each dimension is "*" (any)
@@ -177,6 +200,10 @@ export interface BridgeDetail {
// connection's app is in (the distributed Teams app). False while the
// bridge is not running.
team_placement_supported: boolean;
+ // What the caller may do to the connection: change it, and delete it. A
+ // connection an install holds is refused at the time, with the reason.
+ can_manage: boolean;
+ can_delete: boolean;
}
export interface ExternalUserSummary {
@@ -796,6 +823,10 @@ export interface ApiKeyDetail {
created_at: string;
/** `null` for a key that never expires. */
expires_at: string | null;
+ // Copying the key, and deleting it: never a key an agent still signs in
+ // with, though one a deleted agent left behind can go.
+ can_reveal: boolean;
+ can_delete: boolean;
}
export interface CreateApiKeyResult {
@@ -1071,6 +1102,7 @@ export interface InstalledApp {
bridge_id: string | null;
installed_at: string;
ended_at: string | null;
+ can_disconnect: boolean;
}
// A platform installed by claiming a chat (Telegram) rather than by OAuth, and
@@ -1152,6 +1184,12 @@ export interface UserInfo {
created_at: string;
}
+/** A user on the operator's list. */
+export interface ListedUser extends UserInfo {
+ // Deleting the account: never your own, nor another operator's.
+ can_delete: boolean;
+}
+
export async function login(email: string, password: string): Promise<UserInfo> {
return jsonRequest<UserInfo>("/auth/login", "POST", { email, password });
}
@@ -1366,6 +1404,11 @@ export interface CurrentOrganization {
// Changes made here to those members are made in that directory too, so
// they last; the admin may first be sent to sign in there.
directory_takes_changes: boolean;
+ // Whether the caller is one of its admins, and whether they may manage its
+ // members and read what needs their attention: its admins, or the
+ // operator while it has none.
+ administers: boolean;
+ can_manage_members: boolean;
}
export interface OperatorWorkspace {
@@ -1420,17 +1463,6 @@ export interface OrganizationServices {
services: OrganizationService[];
}
-interface FeatureFlagsResponse {
- flags: { key: string; enabled: boolean }[];
-}
-
-/** The deployment's feature flags, each on or off. Any signed-in caller may
- * read them; they decide which routes the server mounts. */
-export async function fetchFeatureFlags(): Promise<Record<string, boolean>> {
- const { flags } = await jsonRequest<FeatureFlagsResponse>("/feature-flags", "GET");
- return Object.fromEntries(flags.map((flag) => [flag.key, flag.enabled]));
-}
-
export async function fetchOrganizationServices(): Promise<OrganizationServices> {
return jsonRequest<OrganizationServices>("/organizations/current/services", "GET");
}
@@ -1727,8 +1759,8 @@ export async function changePassword(
});
}
-export async function fetchUsers(): Promise<UserInfo[] | null> {
- return fetchJson<UserInfo[]>("/users");
+export async function fetchUsers(): Promise<ListedUser[] | null> {
+ return fetchJson<ListedUser[]>("/users");
}
// The roles `POST /users` accepts; `admin` makes a deployment operator.
@@ -1778,6 +1810,11 @@ export interface ReferenceTypeDetail {
write_visibility: "public" | "private";
shadowed_by_builtin: boolean;
created_at: string;
+ // What the caller may do to it, as the server decides it. `can_edit` is
+ // writing it; `can_manage` is deleting it, changing who may see or change
+ // it, and handing it to someone else.
+ can_edit: boolean;
+ can_manage: boolean;
}
export interface ReferenceTypeCreateInput {
@@ -1821,6 +1858,11 @@ export interface ReferenceDetail {
// Resolved server-side and unfiltered by the type's visibility. Null when
// the slug resolves to no type at all.
type_display_name: string | null;
+ // What the caller may do to it, as the server decides it. `can_edit` is
+ // writing it; `can_manage` is deleting it, changing who may see or change
+ // it, and handing it to someone else.
+ can_edit: boolean;
+ can_manage: boolean;
}
export interface ReferenceCreateInput {
@@ -1861,6 +1903,13 @@ export interface DocumentSummary {
created_by_agent_id: string | null;
created_by_agent_name: string | null;
created_at: string;
+ // What the caller may do to it, as the server decides it. `can_edit` is
+ // writing it; `can_manage` is deleting it, changing who may see or change
+ // it, and handing it to someone else.
+ can_edit: boolean;
+ can_manage: boolean;
+ // Handing it to someone else: never for a document scoped to one room.
+ can_transfer: boolean;
}
export interface DocumentDetail extends DocumentSummary {
@@ -2215,6 +2264,11 @@ export interface PackageDetail {
// Whether the caller may open the package. Only a room's package list
// includes packages the caller cannot read.
can_read: boolean;
+ // What the caller may do to it, as the server decides it. `can_edit` is
+ // writing it; `can_manage` is deleting it, changing who may see or change
+ // it, and handing it to someone else.
+ can_edit: boolean;
+ can_manage: boolean;
}
export interface PackageCreateInput {
@@ -2510,6 +2564,13 @@ export interface CurrentTenant {
// Whether the caller may manage the workspace: an admin membership,
// `org_admin` of its organization, or the operator bit.
administers: boolean;
+ // Whether they may delete it: an admin membership of their own, which the
+ // organization admin's and the operator's reach do not count as, and never
+ // the server's default workspace.
+ can_delete: boolean;
+ // Whether they may set a retention window and erase people's data: their
+ // own admin membership, as for deleting it.
+ can_manage_data_protection: boolean;
}
export type UsageMetric =
@@ -2585,6 +2646,18 @@ export async function fetchCurrentTenant(): Promise<CurrentTenant | null> {
return fetchJson<CurrentTenant>("/tenants/current");
}
+/** The current workspace as the server sees the caller in it. Throws rather
+ * than answering null: what the dashboard lets someone open is worked out
+ * from it, so a failed read must not look like "not an admin". */
+export async function loadCurrentTenant(): Promise<CurrentTenant> {
+ return jsonRequest<CurrentTenant>("/tenants/current", "GET");
+}
+
+export async function fetchFeatureFlags(): Promise<FeatureFlags> {
+ const { flags } = await jsonRequest<{ flags: FeatureFlagState[] }>("/feature-flags", "GET");
+ return featureFlagsFrom(flags);
+}
+
export async function fetchUsage(
tenantId: string,
since: Date,
@@ -2858,7 +2931,7 @@ export class ConnectorAppRefusal extends ApiError {
/** What the operator reads when the server has no connector-apps routes:
* they are mounted only with the `service_connections` flag. */
export const CONNECTORS_NOT_ENABLED =
- "Connectors are not enabled on this server. An operator turns them on by adding service_connections to FEATURE_FLAGS_ENABLED.";
+ "Connectors aren't turned on here. An operator turns them on by adding service_connections to FEATURE_FLAGS_ENABLED.";
/** Whose apps a page manages: the server's, its operator's alone, or the
* current workspace's organization's, its org admins'. */
diff --git a/gateway/src/data/capabilities.test.ts b/gateway/src/data/capabilities.test.ts
new file mode 100644
index 000000000..a14ea7512
--- /dev/null
+++ b/gateway/src/data/capabilities.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, it } from "vitest";
+import type { CurrentTenant, Session, TenantMembership } from "./api";
+import {
+ agentManagement,
+ allOf,
+ capabilitiesOf,
+ everyone,
+ operators,
+ organizationAdmins,
+ serviceConnections,
+ workspaceAdmins,
+} from "./capabilities";
+import { ALL_OFF, featureFlagsFrom } from "./featureFlags";
+
+const membership: TenantMembership = {
+ id: "t1",
+ slug: "acme",
+ name: "Acme",
+ role: "member",
+ organization_role: "member",
+ organization_id: "o1",
+};
+
+function session(tenant: Partial<TenantMembership> = {}, isOperator = false): Session {
+ const current = { ...membership, ...tenant };
+ return {
+ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: isOperator },
+ tenant: current,
+ tenants: [current],
+ state: "ready",
+ can_create_workspace: false,
+ can_add_workspace: false,
+ invite_email_enabled: false,
+ };
+}
+
+function tenant(administers: boolean): CurrentTenant {
+ return { id: "t1", slug: "acme", name: "Acme", role: "member", administers, can_delete: false, can_manage_data_protection: false };
+}
+
+describe("featureFlagsFrom", () => {
+ it("keeps the flags the dashboard knows, and treats any it was not sent as off", () => {
+ const flags = featureFlagsFrom([
+ { key: "agent_management", enabled: true },
+ { key: "gateway_v2", enabled: false },
+ { key: "something_newer", enabled: true },
+ ]);
+ expect(flags).toEqual({
+ agent_management: true,
+ service_connections: false,
+ organization_connector_apps: false,
+ gateway_v2: false,
+ });
+ });
+});
+
+describe("capabilitiesOf", () => {
+ it("takes workspace admin from the server's answer, not the role name", () => {
+ expect(capabilitiesOf(session({ role: "admin" }), tenant(false), ALL_OFF).administersWorkspace).toBe(
+ false,
+ );
+ expect(capabilitiesOf(session({ role: "member" }), tenant(true), ALL_OFF).administersWorkspace).toBe(
+ true,
+ );
+ });
+
+ it("is no admin of anything with no workspace", () => {
+ const caps = capabilitiesOf(null, null, ALL_OFF);
+ expect(caps.administersWorkspace).toBe(false);
+ expect(caps.administersOrganization).toBe(false);
+ expect(caps.isOperator).toBe(false);
+ });
+
+ it("takes organization admin from the organization role, not the operator bit", () => {
+ expect(
+ capabilitiesOf(session({ organization_role: "org_admin" }), tenant(true), ALL_OFF)
+ .administersOrganization,
+ ).toBe(true);
+ expect(capabilitiesOf(session({}, true), tenant(true), ALL_OFF).administersOrganization).toBe(false);
+ });
+});
+
+describe("rules", () => {
+ const member = capabilitiesOf(session(), tenant(false), ALL_OFF);
+ const workspaceAdmin = capabilitiesOf(session({ role: "admin" }), tenant(true), ALL_OFF);
+ const orgAdmin = capabilitiesOf(session({ organization_role: "org_admin" }), tenant(true), ALL_OFF);
+ const operator = capabilitiesOf(session({}, true), tenant(true), ALL_OFF);
+ const outsideAnyOrganization = capabilitiesOf(
+ session({ organization_role: null, organization_id: null }),
+ tenant(true),
+ ALL_OFF,
+ );
+
+ it("lets everyone in", () => {
+ expect(everyone(member).allowed).toBe(true);
+ });
+
+ it("lets workspace admins in, whatever made them one", () => {
+ expect(workspaceAdmins(member)).toMatchObject({ allowed: false, reason: "not_permitted" });
+ for (const caps of [workspaceAdmin, orgAdmin, operator]) {
+ expect(workspaceAdmins(caps).allowed).toBe(true);
+ }
+ });
+
+ it("lets only the operator into operator pages", () => {
+ for (const caps of [member, workspaceAdmin, orgAdmin]) {
+ expect(operators(caps).allowed).toBe(false);
+ }
+ expect(operators(operator).allowed).toBe(true);
+ });
+
+ it("lets organization admins and the operator into organization settings", () => {
+ expect(organizationAdmins(orgAdmin).allowed).toBe(true);
+ expect(organizationAdmins(operator).allowed).toBe(true);
+ expect(organizationAdmins(workspaceAdmin)).toMatchObject({
+ allowed: false,
+ message: "Only the organization's admins can open this page.",
+ });
+ expect(organizationAdmins(member).allowed).toBe(false);
+ expect(organizationAdmins(outsideAnyOrganization)).toMatchObject({
+ allowed: false,
+ message: "This workspace belongs to no organization.",
+ });
+ });
+
+ it("refuses a page whose feature is off, naming the flag", () => {
+ expect(agentManagement(member)).toEqual({
+ allowed: false,
+ reason: "not_enabled",
+ flag: "agent_management",
+ message: "Agent management isn't turned on here.",
+ });
+ const on = capabilitiesOf(session(), tenant(false), { ...ALL_OFF, agent_management: true });
+ expect(agentManagement(on).allowed).toBe(true);
+ });
+
+ it("answers with the first refusal when several rules apply", () => {
+ const rule = allOf(serviceConnections, workspaceAdmins);
+ expect(rule(member)).toMatchObject({ reason: "not_enabled", flag: "service_connections" });
+ const on = capabilitiesOf(session(), tenant(false), { ...ALL_OFF, service_connections: true });
+ expect(rule(on)).toMatchObject({ reason: "not_permitted" });
+ });
+});
diff --git a/gateway/src/data/capabilities.ts b/gateway/src/data/capabilities.ts
new file mode 100644
index 000000000..4e21d96ca
--- /dev/null
+++ b/gateway/src/data/capabilities.ts
@@ -0,0 +1,118 @@
+import type { CurrentTenant, Session } from "./api";
+import {
+ AGENT_MANAGEMENT,
+ type FeatureFlagKey,
+ type FeatureFlags,
+ ORGANIZATION_CONNECTOR_APPS,
+ SERVICE_CONNECTIONS,
+} from "./featureFlags";
+
+/** What the signed-in person may do across the dashboard, from the server's
+ * own answers: the session, the current workspace and the deployment's
+ * flags. This is the one place a role is read. Pages, the rail and the route
+ * guards ask these, never the role; what someone may do to one object comes
+ * from that object's own `can_*` flags. */
+export interface Capabilities {
+ isOperator: boolean;
+ /** The server's `administers` for the current workspace: an admin
+ * membership, `org_admin` of its organization, or the operator bit. */
+ administersWorkspace: boolean;
+ /** `org_admin` of the current workspace's organization. The operator is
+ * not one by the operator bit alone. */
+ administersOrganization: boolean;
+ inOrganization: boolean;
+ /** The current workspace's own `can_delete`: an admin membership of the
+ * caller's, which the reach of an organization admin or the operator does
+ * not count as, and never the server's default workspace. */
+ canDeleteWorkspace: boolean;
+ /** The current workspace's own `can_manage_data_protection`: setting a
+ * retention window and erasing people's data, which take an admin
+ * membership of the caller's, as deleting it does. */
+ canManageDataProtection: boolean;
+ features: FeatureFlags;
+}
+
+export function capabilitiesOf(
+ session: Session | null,
+ tenant: CurrentTenant | null,
+ features: FeatureFlags,
+): Capabilities {
+ return {
+ isOperator: session?.user.is_operator ?? false,
+ administersWorkspace: tenant?.administers ?? false,
+ administersOrganization: session?.tenant?.organization_role === "org_admin",
+ inOrganization: (session?.tenant?.organization_id ?? null) !== null,
+ canDeleteWorkspace: tenant?.can_delete ?? false,
+ canManageDataProtection: tenant?.can_manage_data_protection ?? false,
+ features,
+ };
+}
+
+export type Access =
+ | { allowed: true }
+ | { allowed: false; reason: "not_permitted"; message: string }
+ | { allowed: false; reason: "not_enabled"; flag: FeatureFlagKey; message: string };
+
+/** Who may open a page, answered from capabilities alone. */
+export type Rule = (caps: Capabilities) => Access;
+
+const ALLOWED: Access = { allowed: true };
+
+function notPermitted(message: string): Access {
+ return { allowed: false, reason: "not_permitted", message };
+}
+
+export const everyone: Rule = () => ALLOWED;
+
+export const workspaceAdmins: Rule = (caps) =>
+ caps.administersWorkspace
+ ? ALLOWED
+ : notPermitted("Only this workspace's admins can open this page.");
+
+export const operators: Rule = (caps) =>
+ caps.isOperator ? ALLOWED : notPermitted("Only the platform operator can open this page.");
+
+export const inOrganization: Rule = (caps) =>
+ caps.inOrganization ? ALLOWED : notPermitted("This workspace belongs to no organization.");
+
+const ONLY_ORGANIZATION_ADMINS = "Only the organization's admins can open this page.";
+
+/** The organization's admins, and the operator, who may need to restore one. */
+export const organizationAdmins: Rule = (caps) => {
+ if (!caps.inOrganization) return inOrganization(caps);
+ return caps.administersOrganization || caps.isOperator
+ ? ALLOWED
+ : notPermitted(ONLY_ORGANIZATION_ADMINS);
+};
+
+/** The organization's admins alone: the operator restores an admin, and
+ * goes no further. */
+export const organizationAdminsOnly: Rule = (caps) => {
+ if (!caps.inOrganization) return inOrganization(caps);
+ return caps.administersOrganization ? ALLOWED : notPermitted(ONLY_ORGANIZATION_ADMINS);
+};
+
+function feature(flag: FeatureFlagKey, what: string): Rule {
+ return (caps) =>
+ caps.features[flag]
+ ? ALLOWED
+ : { allowed: false, reason: "not_enabled", flag, message: `${what} turned on here.` };
+}
+
+export const agentManagement = feature(AGENT_MANAGEMENT, "Agent management isn't");
+export const serviceConnections = feature(SERVICE_CONNECTIONS, "Connectors aren't");
+export const organizationConnectorApps = feature(
+ ORGANIZATION_CONNECTOR_APPS,
+ "Organization connector apps aren't",
+);
+
+/** Allowed when every rule allows; otherwise the first refusal. */
+export function allOf(...rules: Rule[]): Rule {
+ return (caps) => {
+ for (const rule of rules) {
+ const access = rule(caps);
+ if (!access.allowed) return access;
+ }
+ return ALLOWED;
+ };
+}
diff --git a/gateway/src/data/featureFlags.ts b/gateway/src/data/featureFlags.ts
new file mode 100644
index 000000000..ef2d39215
--- /dev/null
+++ b/gateway/src/data/featureFlags.ts
@@ -0,0 +1,42 @@
+/** The deployment's feature flags the dashboard acts on. The server sends
+ * every flag it knows (`GET /gateway/feature-flags`); the dashboard keeps its
+ * own list, and a key it does not know, or one the server did not send, is
+ * off. Flags are set when the server is deployed, so they are read once per
+ * page load. */
+
+export const AGENT_MANAGEMENT = "agent_management";
+export const SERVICE_CONNECTIONS = "service_connections";
+export const ORGANIZATION_CONNECTOR_APPS = "organization_connector_apps";
+export const GATEWAY_V2 = "gateway_v2";
+
+const KNOWN = [
+ AGENT_MANAGEMENT,
+ SERVICE_CONNECTIONS,
+ ORGANIZATION_CONNECTOR_APPS,
+ GATEWAY_V2,
+] as const;
+
+export type FeatureFlagKey = (typeof KNOWN)[number];
+
+export type FeatureFlags = Readonly<Record<FeatureFlagKey, boolean>>;
+
+export interface FeatureFlagState {
+ key: string;
+ enabled: boolean;
+}
+
+export const ALL_OFF: FeatureFlags = Object.fromEntries(
+ KNOWN.map((key) => [key, false]),
+) as Record<FeatureFlagKey, boolean>;
+
+export function featureFlagsFrom(states: FeatureFlagState[]): FeatureFlags {
+ const sent = new Map(states.map((s) => [s.key, s.enabled]));
+ return Object.fromEntries(
+ KNOWN.map((key) => [key, sent.get(key) === true]),
+ ) as Record<FeatureFlagKey, boolean>;
+}
+
+/** What an operator adds to the deployment to turn `key` on. */
+export function howToTurnOn(key: FeatureFlagKey): string {
+ return `An operator turns it on by adding ${key} to FEATURE_FLAGS_ENABLED.`;
+}
diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.ts
index 79cbf0706..7be0a1bc0 100644
--- a/gateway/src/data/hooks.ts
+++ b/gateway/src/data/hooks.ts
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useState } from "react";
import {
- ApiError,
type ConnectorAppScope,
type ConnectorApps,
fetchConnectorApps,
@@ -32,7 +31,7 @@ import {
type RoomGroupDetail,
type RoomSummary,
type TemplateSummary,
- type UserInfo,
+ type ListedUser,
fetchAgent,
fetchAgents,
fetchApiKeys,
@@ -185,12 +184,8 @@ export function useKnownAgentTypes(): UseQueryResult<KnownAgentType[]> {
}
/** The connector apps of `scope`: the server's, which only its operator
- * reads, or the current organization's, which only its org admins do. A 404
- * is the routes not being mounted: `notEnabled` says so. */
-export function useConnectorApps(
- scope: ConnectorAppScope,
- notEnabled: string,
-): UseQueryResult<ConnectorApps> {
+ * reads, or the current organization's, which only its org admins do. */
+export function useConnectorApps(scope: ConnectorAppScope): UseQueryResult<ConnectorApps> {
const [data, setData] = useState<ConnectorApps | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -209,25 +204,19 @@ export function useConnectorApps(
},
(err: unknown) => {
if (cancelled) return;
- setError(
- err instanceof ApiError && err.status === 404
- ? notEnabled
- : err instanceof Error
- ? err.message
- : String(err),
- );
+ setError(err instanceof Error ? err.message : String(err));
setLoading(false);
},
);
return () => {
cancelled = true;
};
- }, [scope, notEnabled, tick]);
+ }, [scope, tick]);
return { data, loading, error, refetch };
}
-export function useUsers(): UseQueryResult<UserInfo[]> {
+export function useUsers(): UseQueryResult<ListedUser[]> {
return useQuery(fetchUsers);
}
diff --git a/gateway/src/data/management.test.ts b/gateway/src/data/management.test.ts
index 0fc4bad23..774c7ad6e 100644
--- a/gateway/src/data/management.test.ts
+++ b/gateway/src/data/management.test.ts
@@ -3,7 +3,6 @@ import {
ManagementApiError,
createManagedAgent,
enrollCommand,
- fetchManagementAvailable,
fetchProviders,
managementError,
providerLabel,
@@ -48,25 +47,6 @@ describe("managementError", () => {
});
});
-describe("fetchManagementAvailable", () => {
- afterEach(() => vi.unstubAllGlobals());
-
- it("is true when the controllers list answers", async () => {
- respond(200, []);
- await expect(fetchManagementAvailable()).resolves.toBe(true);
- });
-
- it("is false when the routes are not mounted", async () => {
- respond(404, { detail: "Not Found" });
- await expect(fetchManagementAvailable()).resolves.toBe(false);
- });
-
- it("throws on any other failure rather than hiding the page", async () => {
- respond(500, { detail: "boom" });
- await expect(fetchManagementAvailable()).rejects.toBeInstanceOf(ManagementApiError);
- });
-});
-
describe("createManagedAgent", () => {
afterEach(() => vi.unstubAllGlobals());
diff --git a/gateway/src/data/management.ts b/gateway/src/data/management.ts
index ad0114459..a8d3305ed 100644
--- a/gateway/src/data/management.ts
+++ b/gateway/src/data/management.ts
@@ -140,6 +140,10 @@ export interface Controller {
assignment_revision: number;
created_at: string;
revoked_at: string | null;
+ /** What the caller may do to it: rename, describe and ask it to re-check
+ * its providers; and revoke it. */
+ can_edit: boolean;
+ can_remove: boolean;
}
export interface Definition {
@@ -170,6 +174,10 @@ export interface ManagedAgent {
status: AgentStatus | null;
created_at: string;
updated_at: string;
+ /** What the caller may do to it: start, stop, restart and edit it; and
+ * stop managing it. */
+ can_edit: boolean;
+ can_delete: boolean;
}
export interface Operation {
@@ -234,19 +242,6 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
return (await res.json()) as T;
}
-/**
- * Whether this server has agent management turned on. With it off the routes
- * are not mounted at all, so the probe sees the framework's own 404 (no error
- * envelope) rather than a management refusal.
- */
-export async function fetchManagementAvailable(): Promise<boolean> {
- const res = await fetch(`${BASE}/controllers`, { credentials: "include" });
- if (res.ok) return true;
- const error = await managementError(res);
- if (res.status === 404 && error.code === "http_error") return false;
- throw error;
-}
-
export function fetchControllers(): Promise<Controller[]> {
return request<Controller[]>("/controllers");
}
diff --git a/gateway/src/data/sessionState.test.ts b/gateway/src/data/sessionState.test.ts
index 1a94a5dca..149b43f4b 100644
--- a/gateway/src/data/sessionState.test.ts
+++ b/gateway/src/data/sessionState.test.ts
@@ -1,9 +1,7 @@
import { afterEach, describe, expect, it } from "vitest";
import type { Session, TenantMembership } from "./api";
import {
- administersOrganization,
appView,
- canAdminTenant,
clearPendingInvite,
deliveryNotice,
inviteTokenFrom,
@@ -57,25 +55,6 @@ describe("appView", () => {
});
});
-describe("canAdminTenant", () => {
- it("follows the workspace role", () => {
- expect(canAdminTenant(session())).toBe(false);
- expect(canAdminTenant(session({ tenant: { ...acme, role: "admin" } }))).toBe(true);
- });
-
- it("is granted to an operator whatever the role", () => {
- const operator = session({
- user: { id: "u1", name: "Op", email: "[email protected]", is_operator: true },
- });
- expect(canAdminTenant(operator)).toBe(true);
- });
-
- it("is not granted with no session or no workspace", () => {
- expect(canAdminTenant(null)).toBe(false);
- expect(canAdminTenant(session({ tenant: null, state: "needs_workspace" }))).toBe(false);
- });
-});
-
describe("invite tokens", () => {
afterEach(() => clearPendingInvite());
@@ -130,17 +109,3 @@ describe("deliveryNotice", () => {
expect(notice.text).not.toContain("null");
});
});
-
-describe("administersOrganization", () => {
- it("follows the organization role, not the operator bit", () => {
- expect(administersOrganization(session())).toBe(false);
- expect(
- administersOrganization(session({ tenant: { ...acme, organization_role: "org_admin" } })),
- ).toBe(true);
- expect(
- administersOrganization(
- session({ user: { id: "u1", name: "Ada", email: "[email protected]", is_operator: true } }),
- ),
- ).toBe(false);
- });
-});
diff --git a/gateway/src/data/sessionState.ts b/gateway/src/data/sessionState.ts
index 35d90aa8d..7d9f4cb0c 100644
--- a/gateway/src/data/sessionState.ts
+++ b/gateway/src/data/sessionState.ts
@@ -18,22 +18,6 @@ export function appView(session: Session | null, pendingInvite: string | null):
return session.state;
}
-/** May this session administer the workspace it is in? The operator bit, or
- * admin of the current workspace — the same rule the server applies
- * (`require_tenant_admin`). */
-export function canAdminTenant(session: Session | null): boolean {
- if (session === null) return false;
- if (session.user.is_operator) return true;
- const role = session.tenant?.role;
- return role === "admin";
-}
-
-/** Is this session an admin of the current workspace's organization? The
- * platform operator is not, by the operator bit alone. */
-export function administersOrganization(session: Session | null): boolean {
- return session?.tenant?.organization_role === "org_admin";
-}
-
const INVITE_KEY = "switch.pendingInvite";
/** Session storage, not local: an invite token is a bearer credential, and
@@ -92,7 +76,7 @@ export function deliveryNotice(delivery: EmailDelivery, email: string | null): D
case "not_configured":
return {
severity: "warning",
- text: `No e-mail was sent — this server has no mail set up. Send this link to ${email} yourself; it is shown only once.`,
+ text: `No e-mail was sent — e-mail isn't set up here. Send this link to ${email} yourself; it is shown only once.`,
};
case "failed":
return {
diff --git a/gateway/src/data/settingsLanding.ts b/gateway/src/data/settingsLanding.ts
new file mode 100644
index 000000000..7891a0cbc
--- /dev/null
+++ b/gateway/src/data/settingsLanding.ts
@@ -0,0 +1,44 @@
+/** Where the settings areas send someone who arrives without naming a page:
+ * back to the page they last had open, or, after switching workspace from a
+ * settings page, to that same page in the new workspace. Either way the area
+ * checks the page against what they may open there, and falls back to its
+ * first page; see `SettingsIndex`. */
+
+export type SettingsArea = "workspace" | "organization" | "platform";
+
+const AFTER_SWITCH_KEY = "switch.settings.afterSwitch";
+const LAST_PAGE_KEY = "switch.settings.lastPage";
+
+// `/usage` stays where it is until Usage & budget is rebuilt, but sits in
+// Workspace settings in the new layout.
+function inSettings(pathname: string): boolean {
+ return pathname === "/settings" || pathname.startsWith("/settings/") || pathname === "/usage";
+}
+
+/** Where to load after switching workspace from `pathname`. A settings page
+ * is carried across; anything else starts again from the landing page,
+ * because what it showed belonged to the workspace being left. */
+export function landingAfterSwitch(pathname: string, newLayout: boolean): string {
+ if (!newLayout || !inSettings(pathname)) return "/";
+ window.sessionStorage.setItem(AFTER_SWITCH_KEY, pathname);
+ return "/settings";
+}
+
+/** The settings page a workspace switch carried across. Read while
+ * rendering, and cleared once the area has opened (`clearLandingAfterSwitch`)
+ * rather than on the read, which React may repeat. */
+export function landingCarriedAcross(): string | null {
+ return window.sessionStorage.getItem(AFTER_SWITCH_KEY);
+}
+
+export function clearLandingAfterSwitch(): void {
+ window.sessionStorage.removeItem(AFTER_SWITCH_KEY);
+}
+
+export function rememberSettingsPage(area: SettingsArea, path: string): void {
+ window.localStorage.setItem(`${LAST_PAGE_KEY}.${area}`, path);
+}
+
+export function rememberedSettingsPage(area: SettingsArea): string | null {
+ return window.localStorage.getItem(`${LAST_PAGE_KEY}.${area}`);
+}
diff --git a/gateway/src/data/visibility.ts b/gateway/src/data/visibility.ts
index 131296d55..05e44ae26 100644
--- a/gateway/src/data/visibility.ts
+++ b/gateway/src/data/visibility.ts
@@ -60,3 +60,13 @@ export const ACCESS_META: Record<AccessLevel, AccessLevelMeta> = {
color: "default",
},
};
+
+/** The access levels as someone sees them who may not change them: the
+ * shared wording speaks to the owner ("only you"), and the access setting is
+ * shown to others disabled, so this says whose it is to change. */
+export const ACCESS_HELPERS_FOR_OTHERS: Record<AccessLevel, string> = {
+ private: "Only its owner and admins can see or change it.",
+ read_only: "Anyone can see and attach it. Only its owner and admins can change it.",
+ public:
+ "Anyone can see, attach and change it. Only its owner and admins can change who may.",
+};
diff --git a/gateway/src/layout/ChangePasswordDialog.tsx b/gateway/src/layout/ChangePasswordDialog.tsx
index 919148804..4cb91dea0 100644
--- a/gateway/src/layout/ChangePasswordDialog.tsx
+++ b/gateway/src/layout/ChangePasswordDialog.tsx
@@ -65,7 +65,7 @@ export default function ChangePasswordDialog({ open, onClose }: Props) {
return (
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
- <DialogTitle>Change Password</DialogTitle>
+ <DialogTitle>Change password</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
{error && <Alert severity="error">{error}</Alert>}
@@ -104,7 +104,7 @@ export default function ChangePasswordDialog({ open, onClose }: Props) {
disabled={submitting || !currentPassword || !newPassword || !confirmPassword}
startIcon={submitting ? <CircularProgress size={16} /> : undefined}
>
- Change Password
+ Change password
</Button>
</DialogActions>
</Dialog>
diff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsx
index d70b7cae0..9d4718141 100644
--- a/gateway/src/layout/NavRail.tsx
+++ b/gateway/src/layout/NavRail.tsx
@@ -1,19 +1,6 @@
import AddOutlined from "@mui/icons-material/AddOutlined";
-import AccountTreeOutlined from "@mui/icons-material/AccountTreeOutlined";
-import ApartmentOutlined from "@mui/icons-material/ApartmentOutlined";
-import DnsOutlined from "@mui/icons-material/DnsOutlined";
-import ChatBubbleOutlineOutlined from "@mui/icons-material/ChatBubbleOutlineOutlined";
-import ComputerOutlined from "@mui/icons-material/ComputerOutlined";
-import DataUsageOutlined from "@mui/icons-material/DataUsageOutlined";
-import PowerOutlined from "@mui/icons-material/PowerOutlined";
-import FolderOutlined from "@mui/icons-material/FolderOutlined";
import LockOutlined from "@mui/icons-material/LockOutlined";
import LogoutOutlined from "@mui/icons-material/LogoutOutlined";
-import MeetingRoomOutlined from "@mui/icons-material/MeetingRoomOutlined";
-import PeopleOutlined from "@mui/icons-material/PeopleOutlined";
-import SmartToyOutlined from "@mui/icons-material/SmartToyOutlined";
-import VpnKeyOutlined from "@mui/icons-material/VpnKeyOutlined";
-import WorkspacesOutlined from "@mui/icons-material/WorkspacesOutlined";
import {
Alert,
Box,
@@ -28,52 +15,15 @@ import {
Tooltip,
Typography,
} from "@mui/material";
-import { memo, useEffect, useState } from "react";
+import { memo, useState } from "react";
import { NavLink, useLocation } from "react-router";
-import type { ComponentType, MouseEvent } from "react";
+import type { MouseEvent } from "react";
import { useAuth } from "../data/AuthContext";
-import { useCurrentTenant } from "../data/hooks";
-import { fetchManagementAvailable } from "../data/management";
import CreateWorkspaceForm from "../pages/onboarding/CreateWorkspaceForm";
+import { type Layout, type RailItem as RailItemDefinition, railFor } from "../routes/routeTable";
import ChangePasswordDialog from "./ChangePasswordDialog";
import ThemeModeToggle from "./ThemeModeToggle";
-interface NavItem {
- label: string;
- path: string;
- icon: ComponentType<{ sx?: object }>;
-}
-
-const NAV_ITEMS: NavItem[] = [
- { label: "Ecosystem", path: "/ecosystem", icon: AccountTreeOutlined },
- { label: "Rooms", path: "/rooms", icon: MeetingRoomOutlined },
- { label: "Resources", path: "/resources", icon: FolderOutlined },
- { label: "Agents", path: "/agents", icon: SmartToyOutlined },
- { label: "Apps", path: "/collaborations", icon: ChatBubbleOutlineOutlined },
- { label: "API Keys", path: "/registration-keys", icon: VpnKeyOutlined },
- { label: "Workspace", path: "/workspace", icon: WorkspacesOutlined },
-];
-
-// Shown when the current workspace belongs to an organization.
-const ORGANIZATION_ITEMS: NavItem[] = [
- { label: "Organization", path: "/organization", icon: ApartmentOutlined },
-];
-
-// Shown only when the server runs with agent management enabled.
-const MANAGEMENT_ITEMS: NavItem[] = [
- { label: "Machines", path: "/machines", icon: ComputerOutlined },
-];
-
-const WORKSPACE_ADMIN_ITEMS: NavItem[] = [
- { label: "Usage", path: "/usage", icon: DataUsageOutlined },
-];
-
-const ADMIN_ITEMS: NavItem[] = [
- { label: "All workspaces", path: "/operator/workspaces", icon: DnsOutlined },
- { label: "Users", path: "/users", icon: PeopleOutlined },
- { label: "Connectors", path: "/connectors", icon: PowerOutlined },
-];
-
// The rail follows the window's height: at a laptop's it is sized so an
// operator's eleven labelled items and the account button fit, and it grows
// with the window up to its full size. Shorter still, the items scroll.
@@ -85,11 +35,11 @@ const LABEL = "clamp(0.6875rem, 1.05vh, 0.75rem)";
// against thin-stroke icons, so matching the container would read as heavier.
const LOGO = "clamp(24px, 2.6vh, 28px)";
-function RailItem({ item, active }: { item: NavItem; active: boolean }) {
+function RailItem({ item, active }: { item: RailItemDefinition; active: boolean }) {
return (
<Box
component={NavLink}
- to={item.path}
+ to={item.to}
aria-current={active ? "page" : undefined}
sx={{
display: "flex",
@@ -133,9 +83,10 @@ function RailItem({ item, active }: { item: NavItem; active: boolean }) {
);
}
-export default memo(function NavRail() {
+export default memo(function NavRail({ layout }: { layout: Layout }) {
const location = useLocation();
- const { user, session, isOperator, logout, logoutEverywhere, switchTo } = useAuth();
+ const { user, session, isOperator, capabilities, logout, logoutEverywhere, switchTo } =
+ useAuth();
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
@@ -150,30 +101,7 @@ export default memo(function NavRail() {
}
};
- const { data: tenant } = useCurrentTenant();
- const [managementAvailable, setManagementAvailable] = useState(false);
-
- useEffect(() => {
- let cancelled = false;
- fetchManagementAvailable()
- .then((available) => {
- if (!cancelled) setManagementAvailable(available);
- })
- .catch((err: unknown) => {
- console.error("Could not tell whether agent management is enabled:", err);
- });
- return () => {
- cancelled = true;
- };
- }, []);
-
- const items = [
- ...NAV_ITEMS,
- ...(session?.tenant?.organization_id ? ORGANIZATION_ITEMS : []),
- ...(managementAvailable ? MANAGEMENT_ITEMS : []),
- ...(tenant?.administers ? WORKSPACE_ADMIN_ITEMS : []),
- ...(isOperator ? ADMIN_ITEMS : []),
- ];
+ const items = railFor(layout, capabilities);
const current = session?.tenant ?? null;
const others = (session?.tenants ?? []).filter((t) => t.id !== current?.id);
const initial = (user?.email ?? "?").charAt(0).toUpperCase();
@@ -250,9 +178,9 @@ export default memo(function NavRail() {
>
{items.map((item) => (
<RailItem
- key={item.path}
+ key={item.to}
item={item}
- active={location.pathname.startsWith(item.path)}
+ active={item.activeFor.some((prefix) => location.pathname.startsWith(prefix))}
/>
))}
</Stack>
diff --git a/gateway/src/layout/PageShell.tsx b/gateway/src/layout/PageShell.tsx
index cc3d6e9ae..5cde7be3b 100644
--- a/gateway/src/layout/PageShell.tsx
+++ b/gateway/src/layout/PageShell.tsx
@@ -1,12 +1,14 @@
-import { Box, Stack } from "@mui/material";
+import { Alert, Box, Button, Stack } from "@mui/material";
import { Outlet } from "react-router";
+import { useAuth } from "../data/AuthContext";
+import type { Layout } 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. */
-export default function PageShell() {
+export default function PageShell({ layout }: { layout: Layout }) {
return (
<Box
sx={{
@@ -16,7 +18,7 @@ export default function PageShell() {
backgroundColor: "var(--hoot-canvas)",
}}
>
- <NavRail />
+ <NavRail layout={layout} />
<Stack sx={{ flex: 1, minWidth: 0, overflow: "hidden", pr: "var(--surface-gutter)", pb: "var(--surface-gutter)" }}>
<TopBar />
<Stack
@@ -32,9 +34,30 @@ export default function PageShell() {
p: 4,
}}
>
+ <StaleSessionBanner />
<Outlet />
</Stack>
</Stack>
</Box>
);
}
+
+/** Says so when the session could not be read again on coming back to the
+ * tab, rather than carrying on as if what the page shows were current. */
+function StaleSessionBanner() {
+ const { staleError, recheck } = useAuth();
+ if (staleError === null) return null;
+ return (
+ <Alert
+ severity="warning"
+ sx={{ mb: 2 }}
+ action={
+ <Button color="inherit" size="small" onClick={recheck}>
+ Retry
+ </Button>
+ }
+ >
+ Could not check your session with Switch: {staleError}. This page may be out of date.
+ </Alert>
+ );
+}
diff --git a/gateway/src/layout/TopBar.tsx b/gateway/src/layout/TopBar.tsx
index b81362975..ef5632e61 100644
--- a/gateway/src/layout/TopBar.tsx
+++ b/gateway/src/layout/TopBar.tsx
@@ -8,12 +8,21 @@ const SECTION_LABELS: [prefix: string, label: string][] = [
["/rooms", "Rooms"],
["/resources", "Resources"],
["/agents", "Agents"],
- ["/collaborations", "Messaging Apps"],
- ["/registration-keys", "API Keys"],
+ ["/collaborations", "Messaging apps"],
+ ["/registration-keys", "API keys"],
+ ["/machines", "Devices"],
+ ["/connectors", "Connectors"],
["/users", "Users"],
["/workspace", "Workspace"],
["/organization", "Organization"],
["/operator/workspaces", "All workspaces"],
+ ["/usage", "Usage"],
+ // The new layout's own (`gateway_v2`).
+ ["/overview", "Overview"],
+ ["/templates", "Templates"],
+ ["/settings/org", "Organization settings"],
+ ["/settings", "Settings"],
+ ["/platform", "Platform"],
];
const DOCS_URL = "https://docs.switchagents.ai/switch-rooms/getting-started";
diff --git a/gateway/src/pages/agents/AddressingPolicySection.test.tsx b/gateway/src/pages/agents/AddressingPolicySection.test.tsx
new file mode 100644
index 000000000..48d3b9860
--- /dev/null
+++ b/gateway/src/pages/agents/AddressingPolicySection.test.tsx
@@ -0,0 +1,102 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { type AddressingPolicy, type AgentDetail, OWNER_ONLY_POLICY } from "../../data/api";
+import AddressingPolicySection from "./AddressingPolicySection";
+
+const agent = {
+ id: "a1",
+ name: "helper",
+ addressing_policy: null,
+} as unknown as AgentDetail;
+
+/** The section for an agent saved with `policy`. Reads answer empty; the
+ * save answers `saveAnswer`, and what was sent is recorded. */
+function show(policy: AddressingPolicy | null, saveAnswer: [number, unknown] = [200, agent]) {
+ const sent: unknown[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.method === "PUT") {
+ sent.push(JSON.parse(String(init.body)));
+ return new Response(JSON.stringify(saveAnswer[1]), { status: saveAnswer[0] });
+ }
+ return new Response(JSON.stringify([]), { status: 200 });
+ }),
+ );
+ const onUpdated = vi.fn();
+ render(
+ <AddressingPolicySection
+ agent={{ ...agent, addressing_policy: policy }}
+ canEdit
+ onUpdated={onUpdated}
+ />,
+ );
+ return { sent, onUpdated };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("AddressingPolicySection", () => {
+ it("does not take a rule that lets in the owner for one that lets in nobody", () => {
+ show(OWNER_ONLY_POLICY);
+ expect(screen.getByRole("checkbox", { name: "Its owner" })).toHaveProperty("checked", true);
+ expect(screen.queryByText(/can never let anyone in/)).toBeNull();
+ });
+
+ it("does not take a field the server spells out for a change", () => {
+ show({ rules: [{ ...OWNER_ONLY_POLICY.rules[0]!, platform: false }] });
+ expect(screen.getByRole("button", { name: "Save policy" })).toHaveProperty("disabled", true);
+ });
+
+ it("names why a rule can never let anyone in, as the server would, and holds Save", () => {
+ show(OWNER_ONLY_POLICY);
+ fireEvent.click(screen.getByRole("checkbox", { name: "Its owner" }));
+ fireEvent.click(screen.getByRole("checkbox", { name: "Its owner's other agents" }));
+ expect(
+ screen.getByText(
+ /can never let anyone in: it lets in no people, no agents, not the owner and not the platform/,
+ ),
+ ).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Save policy" })).toHaveProperty("disabled", true);
+ });
+
+ it("starts a restricted policy with an owner-only rule, never with none", async () => {
+ const { sent } = show(null);
+ fireEvent.click(screen.getByRole("radio", { name: /Restricted/ }));
+ expect(screen.getByText("Rule 1")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Save policy" }));
+ await waitFor(() => expect(sent).toHaveLength(1));
+ expect(sent[0]).toEqual({ policy: OWNER_ONLY_POLICY });
+ });
+
+ it("keeps the last rule, saying how to let anyone in instead", () => {
+ show(OWNER_ONLY_POLICY);
+ expect(screen.getByRole("button", { name: "Remove rule" })).toHaveProperty("disabled", true);
+ expect(
+ screen.getByLabelText(
+ "A restricted policy needs a rule. To let anyone address this agent, choose Open.",
+ ),
+ ).toBeTruthy();
+ });
+
+ it("shows a policy saved with no rules as Open, since anyone can address it, and records it so", async () => {
+ const { sent } = show({ rules: [] });
+ expect(screen.getByRole("radio", { name: /Open/ })).toHaveProperty("checked", true);
+ expect(screen.getByText(/has no rules, so anyone can address it/)).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Save policy" }));
+ await waitFor(() => expect(sent).toHaveLength(1));
+ expect(sent[0]).toEqual({ policy: null });
+ });
+
+ it("shows the server's reason when it refuses a save", async () => {
+ show(null, [422, { detail: "These rules can never let anyone in: rule 1: it names no rooms." }]);
+ fireEvent.click(screen.getByRole("radio", { name: /Restricted/ }));
+ fireEvent.click(screen.getByRole("button", { name: "Save policy" }));
+ expect(
+ await screen.findByText("These rules can never let anyone in: rule 1: it names no rooms."),
+ ).toBeTruthy();
+ });
+});
diff --git a/gateway/src/pages/agents/AddressingPolicySection.tsx b/gateway/src/pages/agents/AddressingPolicySection.tsx
index 344b47857..53706592e 100644
--- a/gateway/src/pages/agents/AddressingPolicySection.tsx
+++ b/gateway/src/pages/agents/AddressingPolicySection.tsx
@@ -14,6 +14,7 @@ import {
TextField,
ToggleButton,
ToggleButtonGroup,
+ Tooltip,
Typography,
} from "@mui/material";
import DeleteOutline from "@mui/icons-material/DeleteOutline";
@@ -23,6 +24,7 @@ import {
type AddressingPolicy,
type AddressingRule,
type AgentDetail,
+ OWNER_ONLY_POLICY,
updateAgentAddressingPolicy,
} from "../../data/api";
import {
@@ -52,9 +54,8 @@ interface RuleState {
room_groups: DimState;
users: DimState;
agents: DimState;
- // The owner and owner-agents subjects and the platform opt-in are carried
- // through untouched: this editor does not offer them, and saving must not
- // strip what another surface set.
+ // The owner and owner-agents subjects are kept absent rather than false
+ // unless changed here, so saving does not rewrite what another surface set.
owner?: boolean;
owner_agents?: boolean;
platform: boolean;
@@ -99,17 +100,23 @@ function fromRuleState(state: RuleState): AddressingRule {
return rule;
}
-// A rule that can never match (so it would silently never apply): a context
-// dimension set to Specific-but-empty, or both sender dimensions matching nobody.
+// Why a rule can never let anyone in, as the server decides it and refuses
+// it on save: no rooms, no room groups, or no sender at all (no people, no
+// agents, not the owner, not the owner's agents, not the platform). Null for
+// a rule that can.
function dimMatchesNobody(state: DimState): boolean {
return state.mode === "none" || (state.mode === "specific" && state.ids.length === 0);
}
-function ruleIsDead(rule: RuleState): boolean {
- return (
- dimMatchesNobody(rule.rooms) ||
- dimMatchesNobody(rule.room_groups) ||
- (dimMatchesNobody(rule.users) && dimMatchesNobody(rule.agents))
- );
+function deadRuleReason(rule: RuleState): string | null {
+ if (dimMatchesNobody(rule.rooms)) return "it names no rooms";
+ if (dimMatchesNobody(rule.room_groups)) return "it names no room groups";
+ const noSender =
+ dimMatchesNobody(rule.users) &&
+ dimMatchesNobody(rule.agents) &&
+ !rule.owner &&
+ !rule.owner_agents &&
+ !rule.platform;
+ return noSender ? "it lets in no people, no agents, not the owner and not the platform" : null;
}
const EMPTY_RULE: RuleState = {
@@ -120,6 +127,9 @@ const EMPTY_RULE: RuleState = {
platform: false,
};
+// What choosing Restricted starts from: the owner, and the agents they run.
+const OWNER_ONLY_RULES: RuleState[] = OWNER_ONLY_POLICY.rules.map(toRuleState);
+
function DimensionField({
label,
help,
@@ -205,10 +215,11 @@ export default function AddressingPolicySection({
canEdit: boolean;
onUpdated: () => void;
}) {
- const initialRestricted = !!agent.addressing_policy;
- const initialRules: RuleState[] = (agent.addressing_policy?.rules ?? []).map(
- toRuleState,
- );
+ // A policy with no rules lets anyone in, so it is shown as Open, which is
+ // what the server treats it as.
+ const savedRules = agent.addressing_policy?.rules ?? [];
+ const initialRestricted = savedRules.length > 0;
+ const initialRules: RuleState[] = savedRules.map(toRuleState);
const [restricted, setRestricted] = useState(initialRestricted);
const [rules, setRules] = useState<RuleState[]>(initialRules);
@@ -240,10 +251,16 @@ export default function AddressingPolicySection({
const desired: AddressingPolicy | null = restricted
? { rules: rules.map(fromRuleState) }
: null;
- const dirty =
- JSON.stringify(desired) !==
- JSON.stringify(agent.addressing_policy ?? null);
- const hasDeadRule = restricted && rules.some(ruleIsDead);
+ // Against the saved policy as this editor would write it back, so a field
+ // the server spells out (`platform: false`) is not taken for a change. A
+ // policy saved with no rules stays a change: saving records it as Open.
+ const saved: AddressingPolicy | null =
+ agent.addressing_policy === null
+ ? null
+ : { rules: initialRules.map(fromRuleState) };
+ const dirty = JSON.stringify(desired) !== JSON.stringify(saved);
+ const hasDeadRule = restricted && rules.some((rule) => deadRuleReason(rule) !== null);
+ const savedEmpty = agent.addressing_policy !== null && savedRules.length === 0;
const handleSave = async () => {
setSaving(true);
@@ -276,7 +293,13 @@ export default function AddressingPolicySection({
<RadioGroup
value={restricted ? "restricted" : "open"}
- onChange={(e) => setRestricted(e.target.value === "restricted")}
+ onChange={(e) => {
+ const next = e.target.value === "restricted";
+ // A restricted policy with no rules would let anyone in, so it
+ // never starts empty.
+ if (next && rules.length === 0) setRules(OWNER_ONLY_RULES);
+ setRestricted(next);
+ }}
>
<FormControlLabel
value="open"
@@ -292,14 +315,15 @@ export default function AddressingPolicySection({
/>
</RadioGroup>
+ {savedEmpty && !restricted && (
+ <Alert severity="info">
+ This agent&apos;s policy has no rules, so anyone can address it.
+ {canEdit && " Saving records it as Open."}
+ </Alert>
+ )}
+
{restricted && (
<Stack spacing={2}>
- {rules.length === 0 && (
- <Alert severity="warning">
- No rules — with a restricted policy and no rules, nobody can address
- this agent. Add a rule or switch back to Open.
- </Alert>
- )}
{rules.map((rule, index) => (
<Paper key={index} variant="outlined" sx={{ p: 2, borderRadius: 2 }}>
<Stack direction="row" alignItems="center" mb={1}>
@@ -307,15 +331,26 @@ export default function AddressingPolicySection({
Rule {index + 1}
</Typography>
{canEdit && (
- <IconButton
- size="small"
- onClick={() =>
- setRules((prev) => prev.filter((_r, i) => i !== index))
+ <Tooltip
+ title={
+ rules.length === 1
+ ? "A restricted policy needs a rule. To let anyone address this agent, choose Open."
+ : "Remove rule"
}
- aria-label="Remove rule"
>
- <DeleteOutline fontSize="small" />
- </IconButton>
+ <span>
+ <IconButton
+ size="small"
+ disabled={rules.length === 1}
+ onClick={() =>
+ setRules((prev) => prev.filter((_r, i) => i !== index))
+ }
+ aria-label="Remove rule"
+ >
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ </span>
+ </Tooltip>
)}
</Stack>
<Stack spacing={1.5}>
@@ -357,6 +392,32 @@ export default function AddressingPolicySection({
disabled={!canEdit}
onChange={(agents) => updateRule(index, { ...rule, agents })}
/>
+ <FormControlLabel
+ control={
+ <Checkbox
+ size="small"
+ checked={rule.owner === true}
+ disabled={!canEdit}
+ onChange={(e) =>
+ updateRule(index, { ...rule, owner: e.target.checked })
+ }
+ />
+ }
+ label="Its owner"
+ />
+ <FormControlLabel
+ control={
+ <Checkbox
+ size="small"
+ checked={rule.owner_agents === true}
+ disabled={!canEdit}
+ onChange={(e) =>
+ updateRule(index, { ...rule, owner_agents: e.target.checked })
+ }
+ />
+ }
+ label="Its owner's other agents"
+ />
<FormControlLabel
control={
<Checkbox
@@ -370,10 +431,10 @@ export default function AddressingPolicySection({
}
label="Switch itself: let the platform address this agent on its own account. A message it sends for a person, such as a template kickoff, is judged as that person and needs no opt-in."
/>
- {ruleIsDead(rule) && (
+ {deadRuleReason(rule) !== null && (
<Alert severity="warning">
- This rule can never match (an empty Specific/None dimension
- excludes everyone), so it will never apply.
+ This rule can never let anyone in: {deadRuleReason(rule)}. Change it or
+ remove it to save.
</Alert>
)}
</Stack>
diff --git a/gateway/src/pages/agents/AgentDetailPage.tsx b/gateway/src/pages/agents/AgentDetailPage.tsx
index ec1c25304..d16248894 100644
--- a/gateway/src/pages/agents/AgentDetailPage.tsx
+++ b/gateway/src/pages/agents/AgentDetailPage.tsx
@@ -29,14 +29,14 @@ import {
renameAgent,
updateAgentOptions,
} from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import { useAgent, useKnownAgentTypes } from "../../data/hooks";
import {
EM_DASH,
MONO_SX,
formatDateTime,
- titleCase,
+ sentenceCase,
} from "../../theme/hootFormat";
+import { useAuth } from "../../data/AuthContext";
import AddressingPolicySection from "./AddressingPolicySection";
import AgentManagementSection from "./AgentManagementSection";
import ServiceAccessSection from "./ServiceAccessSection";
@@ -79,7 +79,7 @@ function StatusDot({ color, title }: { color: string; title?: string }) {
export default function AgentDetailPage() {
const { agentId } = useParams<{ agentId: string }>();
const navigate = useNavigate();
- const { user, canAdminTenant } = useAuth();
+ const { capabilities } = useAuth();
const { data: agent, loading, error, refetch } = useAgent(agentId);
const [renameOpen, setRenameOpen] = useState(false);
const [renameNotice, setRenameNotice] = useState<{
@@ -108,11 +108,12 @@ export default function AgentDetailPage() {
);
}
- const isOwner = !!user && user.id === agent.owner_id;
- // Renaming and editing options are open to whoever the server says may
- // manage the agent (its owner or an admin); agent management and service
- // access stay with the owner alone, because the agent then acts on the
- // owner's own machines and credentials.
+ // Every control follows the server's answer for this agent. Who may address
+ // it is open to whoever may manage it (its owner or an admin); agent
+ // management and service access stay with the owner alone, because the
+ // agent then acts on the owner's own machines and credentials. Service
+ // access shows only to its owner: the server answers anyone else's request
+ // for its grants as not found.
const canManage = agent.can_manage;
return (
@@ -122,7 +123,7 @@ export default function AgentDetailPage() {
<ArrowBack />
</IconButton>
<Typography variant="h5">{agent.name}</Typography>
- {canManage && !agent.parent_agent_id && agent.children.length === 0 && (
+ {agent.can_rename && (
<Tooltip title="Rename agent">
<IconButton
size="small"
@@ -137,7 +138,7 @@ export default function AgentDetailPage() {
<Chip label={agent.connector_type} size="small" variant="outlined" />
{agent.connection_model && (
<Chip
- label={titleCase(agent.connection_model)}
+ label={sentenceCase(agent.connection_model)}
size="small"
variant="outlined"
/>
@@ -176,7 +177,7 @@ export default function AgentDetailPage() {
<Divider />
<OptionsSection
agent={agent}
- canEdit={canManage}
+ canEdit={agent.can_edit_options}
onUpdated={refetch}
/>
</>
@@ -189,11 +190,17 @@ export default function AgentDetailPage() {
/>
<AgentManagementSection
agent={agent}
- canEdit={isOwner}
+ canEdit={agent.can_change_manage_agents}
onUpdated={refetch}
/>
- {isOwner && <ServiceAccessSection agent={agent} onAgentUpdated={refetch} />}
- {(isOwner || canAdminTenant) && (
+ {capabilities.features.service_connections && (
+ <ServiceAccessSection
+ agent={agent}
+ canGrant={agent.can_grant_services}
+ onAgentUpdated={refetch}
+ />
+ )}
+ {(agent.can_transfer || agent.transfer_blocked_reason !== null) && (
<>
<Divider />
<TransferOwnershipSection
@@ -201,6 +208,7 @@ export default function AgentDetailPage() {
resourceId={agent.id}
resourceLabel={agent.name}
ownerId={agent.owner_id}
+ blockedReason={agent.can_transfer ? null : agent.transfer_blocked_reason}
onTransferred={refetch}
/>
</>
@@ -426,8 +434,8 @@ function InfoSection({ agent }: { agent: AgentDetail }) {
)}
<InfoLine label="Agent type" value={agent.connector_type} />
<InfoLine
- label="Connection type"
- value={agent.connection_model ? titleCase(agent.connection_model) : null}
+ label="Availability"
+ value={agent.connection_model ? sentenceCase(agent.connection_model) : null}
/>
<InfoLine label="OAuth client" value={agent.oauth_client_id} mono />
<InfoLine label="Created" value={formatDateTime(agent.created_at)} />
@@ -510,8 +518,8 @@ function OptionsSection({
</Typography>
{!spec ? (
<Alert severity="warning">
- Unknown agent type "{agent.known_agent_type}" — its schema is no
- longer registered on this server.
+ Unknown agent type "{agent.known_agent_type}" — Switch no longer
+ describes its options.
</Alert>
) : (
<>
@@ -575,7 +583,7 @@ export function SessionsSection({ sessions }: { sessions: AgentSessionDetail[] }
function SessionRow({ session }: { session: AgentSessionDetail }) {
const navigate = useNavigate();
const meta = SESSION_STATE_META[session.state] ?? {
- label: titleCase(session.state),
+ label: sentenceCase(session.state),
color: NEUTRAL_STATUS_COLOR,
};
const isLive = session.state === "live";
@@ -660,7 +668,7 @@ function RoomsSection({ rooms }: { rooms: AgentRoomMembership[] }) {
</Typography>
{rooms.length === 0 ? (
<Typography variant="body2" color="text.secondary">
- Not a member of any room.
+ Not in any room.
</Typography>
) : (
<Stack spacing={0.5}>
@@ -676,7 +684,7 @@ function RoomsSection({ rooms }: { rooms: AgentRoomMembership[] }) {
function RoomRow({ room }: { room: AgentRoomMembership }) {
const navigate = useNavigate();
const meta = ROOM_STATUS_META[room.status] ?? {
- label: titleCase(room.status),
+ label: sentenceCase(room.status),
color: NEUTRAL_STATUS_COLOR,
};
return (
diff --git a/gateway/src/pages/agents/AgentManagementSection.test.tsx b/gateway/src/pages/agents/AgentManagementSection.test.tsx
index 3cb67ab17..f91ccd2f3 100644
--- a/gateway/src/pages/agents/AgentManagementSection.test.tsx
+++ b/gateway/src/pages/agents/AgentManagementSection.test.tsx
@@ -1,8 +1,11 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentDetail } from "../../data/api";
+import { useAuth } from "../../data/AuthContext";
import AgentManagementSection from "./AgentManagementSection";
+vi.mock("../../data/AuthContext", () => ({ useAuth: vi.fn() }));
+
const agent: AgentDetail = {
id: "a1",
name: "helper",
@@ -29,11 +32,20 @@ const agent: AgentDetail = {
addressing_policy: null,
can_manage_agents: false,
can_manage: true,
+ can_rename: true,
+ can_edit_options: true,
+ can_transfer: true,
+ transfer_blocked_reason: null,
+ can_change_manage_agents: true,
+ can_grant_services: true,
};
type Call = { path: string; method: string; body: unknown };
function mockServer({ management }: { management: boolean }) {
+ vi.mocked(useAuth).mockReturnValue({
+ capabilities: { features: { agent_management: management } },
+ } as ReturnType<typeof useAuth>);
const calls: Call[] = [];
vi.stubGlobal(
"fetch",
@@ -41,10 +53,6 @@ function mockServer({ management }: { management: boolean }) {
const path = String(input);
const method = init?.method ?? "GET";
calls.push({ path, method, body: init?.body ? JSON.parse(String(init.body)) : null });
- if (path === "/gateway/management/controllers")
- return management
- ? new Response("[]", { status: 200 })
- : new Response(JSON.stringify({ detail: "Not Found" }), { status: 404 });
if (path === "/gateway/agents/a1/can-manage-agents" && method === "PUT")
return new Response(JSON.stringify({ ...agent, can_manage_agents: true }), {
status: 200,
@@ -91,10 +99,10 @@ describe("AgentManagementSection", () => {
expect(screen.getByText(/Only the agent's owner can change this/)).toBeTruthy();
});
- it("is not shown where agent management does not run", async () => {
+ it("is not shown where agent management does not run", () => {
const calls = mockServer({ management: false });
render(<AgentManagementSection agent={agent} canEdit onUpdated={() => {}} />);
- await waitFor(() => expect(calls.length).toBe(1));
expect(screen.queryByText("Can manage agents")).toBeNull();
+ expect(calls).toEqual([]);
});
});
diff --git a/gateway/src/pages/agents/AgentManagementSection.tsx b/gateway/src/pages/agents/AgentManagementSection.tsx
index db14ff2db..f4a34a5f3 100644
--- a/gateway/src/pages/agents/AgentManagementSection.tsx
+++ b/gateway/src/pages/agents/AgentManagementSection.tsx
@@ -6,9 +6,9 @@ import {
Switch,
Typography,
} from "@mui/material";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { type AgentDetail, updateAgentCanManageAgents } from "../../data/api";
-import { fetchManagementAvailable } from "../../data/management";
+import { useAuth } from "../../data/AuthContext";
/**
* The agent's "can manage agents" capability: with it on, the agent may list
@@ -26,25 +26,11 @@ export default function AgentManagementSection({
canEdit: boolean;
onUpdated: () => void;
}) {
- const [available, setAvailable] = useState(false);
+ const { capabilities } = useAuth();
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
- useEffect(() => {
- let cancelled = false;
- fetchManagementAvailable()
- .then((value) => {
- if (!cancelled) setAvailable(value);
- })
- .catch((err: unknown) => {
- console.error("Could not tell whether agent management is enabled:", err);
- });
- return () => {
- cancelled = true;
- };
- }, []);
-
- if (!available) return null;
+ if (!capabilities.features.agent_management) return null;
const toggle = async (enabled: boolean) => {
setSaving(true);
@@ -78,8 +64,8 @@ export default function AgentManagementSection({
label="Can manage agents"
/>
<Typography variant="body2" color="text.secondary">
- Lets this agent see your machines and managed agents, and create new agents that run on
- your machines and belong to you. Agents it creates do not get this permission.
+ Lets this agent see your devices and managed agents, and create new agents that run on
+ your devices and belong to you. Agents it creates do not get this permission.
{!canEdit && " Only the agent's owner can change this."}
</Typography>
</Stack>
diff --git a/gateway/src/pages/agents/AgentRenameDialog.test.tsx b/gateway/src/pages/agents/AgentRenameDialog.test.tsx
index 0b239ac4a..e57974bb5 100644
--- a/gateway/src/pages/agents/AgentRenameDialog.test.tsx
+++ b/gateway/src/pages/agents/AgentRenameDialog.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentDetail, AgentSummary } from "../../data/api";
import * as api from "../../data/api";
import { useAuth } from "../../data/AuthContext";
+import { ALL_OFF } from "../../data/featureFlags";
import * as hooks from "../../data/hooks";
import AgentDetailPage, { labelFromName } from "./AgentDetailPage";
@@ -67,6 +68,12 @@ const agent: AgentDetail = {
addressing_policy: null,
can_manage_agents: false,
can_manage: true,
+ can_rename: true,
+ can_edit_options: true,
+ can_transfer: true,
+ transfer_blocked_reason: null,
+ can_change_manage_agents: true,
+ can_grant_services: true,
};
function showPage(detail: AgentDetail) {
@@ -94,6 +101,7 @@ describe("RenameAgentDialog", () => {
beforeEach(() => {
vi.mocked(useAuth).mockReturnValue({
user: { id: "u1" },
+ capabilities: { features: ALL_OFF },
} as unknown as ReturnType<typeof useAuth>);
vi.stubGlobal(
"fetch",
diff --git a/gateway/src/pages/agents/AgentsPage.tsx b/gateway/src/pages/agents/AgentsPage.tsx
index d09aaf48f..895151955 100644
--- a/gateway/src/pages/agents/AgentsPage.tsx
+++ b/gateway/src/pages/agents/AgentsPage.tsx
@@ -26,7 +26,7 @@ import { useNavigate } from "react-router";
import DataTable from "../../components/DataTable";
import { type AgentSummary, deleteAgent } from "../../data/api";
import { useAgents } from "../../data/hooks";
-import { EM_DASH, formatDate, titleCase } from "../../theme/hootFormat";
+import { EM_DASH, formatDate, sentenceCase } from "../../theme/hootFormat";
import RegisterAgentDialog from "./RegisterAgentDialog";
// Connector type is a category, not a status. Colour here would compete with
@@ -157,7 +157,7 @@ export default function AgentsPage() {
{ field: "name", headerName: "Name", flex: 1, minWidth: 200 },
{
field: "connector_type",
- headerName: "Agent Type",
+ headerName: "Agent type",
width: 150,
renderCell: ({ value }) =>
value ? (
@@ -170,9 +170,9 @@ export default function AgentsPage() {
},
{
field: "connection_model",
- headerName: "Connection Type",
+ headerName: "Availability",
width: 170,
- valueFormatter: (value) => (value ? titleCase(value as string) : EM_DASH),
+ valueFormatter: (value) => (value ? sentenceCase(value as string) : EM_DASH),
},
{
field: "parent_agent_id",
@@ -233,7 +233,7 @@ export default function AgentsPage() {
startIcon={<AddCircleOutline />}
onClick={() => setRegisterOpen(true)}
>
- Register Agent
+ Add agent
</Button>
</Stack>
diff --git a/gateway/src/pages/agents/RegisterAgentDialog.tsx b/gateway/src/pages/agents/RegisterAgentDialog.tsx
index ce57e412c..a3c7a4896 100644
--- a/gateway/src/pages/agents/RegisterAgentDialog.tsx
+++ b/gateway/src/pages/agents/RegisterAgentDialog.tsx
@@ -113,7 +113,7 @@ export default function RegisterAgentDialog({
: await registerOtherAgent(name, description);
setAgentResult(res);
} catch (err) {
- setError(err instanceof Error ? err.message : "Registration failed.");
+ setError(err instanceof Error ? err.message : "Could not add the agent.");
} finally {
setSubmitting(false);
}
@@ -160,7 +160,7 @@ export default function RegisterAgentDialog({
return (
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
<DialogTitle>
- {hasResult ? "Registration Complete" : "Register Agent"}
+ {hasResult ? "Agent added" : "Add agent"}
</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
@@ -170,16 +170,16 @@ export default function RegisterAgentDialog({
Copy these credentials now. They will not be shown again.
</Alert>
<TextField
- label="API Key"
+ label="API key"
value={agentResult.api_key}
fullWidth
slotProps={{
input: {
readOnly: true,
- endAdornment: copyAdornment(agentResult.api_key, "API Key"),
+ endAdornment: copyAdornment(agentResult.api_key, "API key"),
},
}}
- helperText={copied === "API Key" ? "Copied!" : undefined}
+ helperText={copied === "API key" ? "Copied!" : undefined}
/>
<TextField
label="Agent ID"
@@ -189,30 +189,30 @@ export default function RegisterAgentDialog({
/>
{agentResult.oauth_client_id && (
<TextField
- label="OAuth Client ID"
+ label="OAuth client ID"
value={agentResult.oauth_client_id}
fullWidth
slotProps={{
input: {
readOnly: true,
- endAdornment: copyAdornment(agentResult.oauth_client_id, "OAuth Client ID"),
+ endAdornment: copyAdornment(agentResult.oauth_client_id, "OAuth client ID"),
},
}}
- helperText={copied === "OAuth Client ID" ? "Copied!" : undefined}
+ helperText={copied === "OAuth client ID" ? "Copied!" : undefined}
/>
)}
{agentResult.oauth_client_secret && (
<TextField
- label="OAuth Client Secret"
+ label="OAuth client secret"
value={agentResult.oauth_client_secret}
fullWidth
slotProps={{
input: {
readOnly: true,
- endAdornment: copyAdornment(agentResult.oauth_client_secret, "OAuth Client Secret"),
+ endAdornment: copyAdornment(agentResult.oauth_client_secret, "OAuth client secret"),
},
}}
- helperText={copied === "OAuth Client Secret" ? "Copied!" : undefined}
+ helperText={copied === "OAuth client secret" ? "Copied!" : undefined}
/>
)}
</>
@@ -233,7 +233,7 @@ export default function RegisterAgentDialog({
}
>
{hasKnown && (
- <ListSubheader>Known Agents</ListSubheader>
+ <ListSubheader>Known agents</ListSubheader>
)}
{(knownTypes ?? []).map((t: KnownAgentType) => (
<MenuItem key={t.key} value={t.key}>
@@ -292,7 +292,7 @@ export default function RegisterAgentDialog({
submitting ? <CircularProgress size={16} /> : undefined
}
>
- Register
+ Add
</Button>
</>
)}
diff --git a/gateway/src/pages/agents/ServiceAccessSection.test.tsx b/gateway/src/pages/agents/ServiceAccessSection.test.tsx
index 7eb3fb1d3..3625281f6 100644
--- a/gateway/src/pages/agents/ServiceAccessSection.test.tsx
+++ b/gateway/src/pages/agents/ServiceAccessSection.test.tsx
@@ -11,7 +11,7 @@ import { useAuth } from "../../data/AuthContext";
import ServiceAccessSection from "./ServiceAccessSection";
vi.mock("../../data/AuthContext", () => ({
- useAuth: vi.fn(() => ({ isOperator: false })),
+ useAuth: vi.fn(() => ({ isOperator: false, capabilities: { features: { gateway_v2: false } } })),
}));
const agent: AgentDetail = {
@@ -40,6 +40,12 @@ const agent: AgentDetail = {
addressing_policy: null,
can_manage_agents: false,
can_manage: true,
+ can_rename: true,
+ can_edit_options: true,
+ can_transfer: true,
+ transfer_blocked_reason: null,
+ can_change_manage_agents: true,
+ can_grant_services: true,
};
const GITHUB = {
@@ -114,7 +120,7 @@ describe("ServiceAccessSection", () => {
it("shows each grant with its repositories, and offers owner-only when anyone can address the agent", async () => {
const calls = mockServer(GRANTED);
const updated = vi.fn();
- render(<ServiceAccessSection agent={agent} onAgentUpdated={updated} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={updated} />);
expect(await screen.findByText(GRANTED.grants[0]!.summary)).toBeTruthy();
expect(await screen.findByText("example-org/project")).toBeTruthy();
expect(screen.getByText(/show as the Switch GitHub App/)).toBeTruthy();
@@ -131,9 +137,9 @@ describe("ServiceAccessSection", () => {
it("says what removing a grant does, and does not, on the agent's own machine", async () => {
const calls = mockServer(GRANTED);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
const remove = await screen.findByRole("button", { name: "Remove" });
- expect(remove.getAttribute("title")).toMatch(/may still use the machine's own sign-in/);
+ expect(remove.getAttribute("title")).toMatch(/may still use the device's own sign-in/);
fireEvent.click(remove);
expect(await screen.findByText(/Removing a grant stops Switch giving this access/)).toBeTruthy();
@@ -146,7 +152,7 @@ describe("ServiceAccessSection", () => {
it("grants GitHub on the repositories picked, for reading unless asked", async () => {
const calls = mockServer({ grants: [], addressing_open: false });
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
const account = await screen.findByLabelText("GitHub account");
fireEvent.mouseDown(account);
fireEvent.click(await screen.findByText("example-org"));
@@ -162,12 +168,13 @@ describe("ServiceAccessSection", () => {
);
});
- it("shows nothing to someone who does not own the agent", async () => {
- mockServer(null);
+ it("shows nothing to someone who does not own the agent, and reads none of their own connections", async () => {
+ const calls = mockServer(null);
const { container } = render(
- <ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />,
+ <ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />,
);
await waitFor(() => expect(container.textContent).toBe(""));
+ expect(calls.map((c) => c.path)).toEqual(["/gateway/agents/a1/service-grants"]);
});
const onOff = (
@@ -193,7 +200,7 @@ describe("ServiceAccessSection", () => {
it("turns a connected on/off service on with no level to choose", async () => {
const calls = mockServer(NONE, [onOff("active")]);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
const toggle = await screen.findByLabelText("Example for helper");
expect(screen.getByText(/helper acts as you at Example/)).toBeTruthy();
expect(screen.getByText(/within a minute/)).toBeTruthy();
@@ -226,7 +233,7 @@ describe("ServiceAccessSection", () => {
},
[onOff("active", { token_lifetime: 24 * 3600 })],
);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
expect(await screen.findByText("helper reads and writes Example as you.")).toBeTruthy();
expect(screen.getByText(/stays valid at Example until it expires/)).toBeTruthy();
expect(screen.queryByRole("button", { name: "Remove" })).toBeNull();
@@ -249,7 +256,7 @@ describe("ServiceAccessSection", () => {
onOff("active", { key, token_lifetime: 24 * 3600 }),
onOff("not_connected", { slug: "other", name: "Other", key }),
]);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
await screen.findByLabelText("Example for helper");
expect(
screen.getByText(
@@ -258,7 +265,7 @@ describe("ServiceAccessSection", () => {
).toBeTruthy();
expect(screen.queryByText(/stays valid/)).toBeNull();
expect((screen.getByLabelText("Other for helper") as HTMLInputElement).disabled).toBe(true);
- expect(screen.getByText(/To turn Other on, first connect it from Switch Console/)).toBeTruthy();
+ expect(screen.getByText(/To turn Other on, first connect it in Switch Console/)).toBeTruthy();
});
it("says why a service cannot be turned on: not connected, or not available here", async () => {
@@ -267,21 +274,21 @@ describe("ServiceAccessSection", () => {
onOff("active", {
slug: "other",
name: "Other",
- unavailable_reason: "Coming to this server soon.",
+ unavailable_reason: "Coming here soon.",
}),
]);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
const example = await screen.findByLabelText("Example for helper");
expect((example as HTMLInputElement).disabled).toBe(true);
- expect(screen.getByText(/first connect it from Switch Console/)).toBeTruthy();
- expect(screen.getByText("Coming to this server soon.")).toBeTruthy();
+ expect(screen.getByText(/first connect it in Switch Console/)).toBeTruthy();
+ expect(screen.getByText("Coming here soon.")).toBeTruthy();
expect((screen.getByLabelText("Other for helper") as HTMLInputElement).disabled).toBe(true);
});
it("says a service signs in through the organization's app only while that app works", async () => {
const through = "Signs in through your organization's Example app.";
mockServer(NONE, [onOff("active", { app_source: "organization" })]);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
expect(await screen.findByText(through)).toBeTruthy();
cleanup();
@@ -289,39 +296,62 @@ describe("ServiceAccessSection", () => {
mockServer(NONE, [
onOff("active", { app_source: "organization", unavailable_reason: broken }),
]);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
expect(await screen.findByText(broken)).toBeTruthy();
expect(screen.queryByText(through)).toBeNull();
});
const NOT_SET_UP =
- "Example is not set up on this server. Ask whoever runs your Switch server to add it under Connectors in the Switch dashboard.";
+ "Example is not set up here. Whoever runs Switch can set it up in Switch Console, under Admin → Connector apps.";
it("offers the operator Set up for a service waiting on its app, and nobody else", async () => {
const services = [
onOff("not_connected", { unavailable_reason: NOT_SET_UP, server_setup_needed: true }),
];
mockServer(NONE, services);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
expect(await screen.findByText(NOT_SET_UP)).toBeTruthy();
expect(screen.queryByRole("link", { name: "Set up" })).toBeNull();
cleanup();
- vi.mocked(useAuth).mockReturnValue({ isOperator: true } as ReturnType<typeof useAuth>);
- mockServer(NONE, services);
- render(
- <MemoryRouter>
- <ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />
- </MemoryRouter>,
- );
- const setUp = await screen.findByRole("link", { name: "Set up" });
- expect(setUp.getAttribute("href")).toBe("/connectors");
- vi.mocked(useAuth).mockReturnValue({ isOperator: false } as ReturnType<typeof useAuth>);
+ for (const [newLayout, where] of [
+ [false, "/connectors"],
+ [true, "/platform/connectors"],
+ ] as const) {
+ vi.mocked(useAuth).mockReturnValue({
+ isOperator: true,
+ capabilities: { features: { gateway_v2: newLayout } },
+ } as ReturnType<typeof useAuth>);
+ mockServer(NONE, services);
+ render(
+ <MemoryRouter>
+ <ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />
+ </MemoryRouter>,
+ );
+ const setUp = await screen.findByRole("link", { name: "Set up" });
+ expect(setUp.getAttribute("href")).toBe(where);
+ cleanup();
+ }
+ vi.mocked(useAuth).mockReturnValue({
+ isOperator: false,
+ capabilities: { features: { gateway_v2: false } },
+ } as ReturnType<typeof useAuth>);
+ });
+
+ it("keeps what an agent was granted removable where it may be granted nothing more", async () => {
+ mockServer(GRANTED, [onOff("active")]);
+ render(<ServiceAccessSection agent={agent} canGrant={false} onAgentUpdated={vi.fn()} />);
+ expect(await screen.findByText(GRANTED.grants[0]!.summary)).toBeTruthy();
+ expect(screen.getByText(/New grants are only for an agent Switch Console runs/)).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Remove" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Change" })).toBeNull();
+ expect(screen.queryByLabelText("GitHub account")).toBeNull();
+ expect(screen.getByRole("switch", { name: /for helper/ })).toHaveProperty("disabled", true);
});
it("says GitHub is not set up, rather than an error, when its App is not", async () => {
const reason =
- "GitHub is not set up on this server. Ask whoever runs your Switch server to add it under Connectors in the Switch dashboard.";
+ "GitHub is not set up here. Whoever runs Switch can set it up in Switch Console, under Admin → Connector apps.";
mockServer(NONE, [
onOff("not_connected", {
slug: "github",
@@ -331,7 +361,7 @@ describe("ServiceAccessSection", () => {
server_setup_needed: true,
}),
]);
- render(<ServiceAccessSection agent={agent} onAgentUpdated={vi.fn()} />);
+ render(<ServiceAccessSection agent={agent} canGrant onAgentUpdated={vi.fn()} />);
expect(await screen.findByText(reason)).toBeTruthy();
});
});
diff --git a/gateway/src/pages/agents/ServiceAccessSection.tsx b/gateway/src/pages/agents/ServiceAccessSection.tsx
index 306058613..224ae2787 100644
--- a/gateway/src/pages/agents/ServiceAccessSection.tsx
+++ b/gateway/src/pages/agents/ServiceAccessSection.tsx
@@ -73,9 +73,13 @@ function repositoryNames(github: GitHubConnection | null, grant: ServiceGrant):
*/
export default function ServiceAccessSection({
agent,
+ canGrant,
onAgentUpdated,
}: {
agent: AgentDetail;
+ // Granting it more: refused for an agent not run from a known agent type.
+ // The grants it has can be seen and removed regardless.
+ canGrant: boolean;
onAgentUpdated: () => void;
}) {
const [grants, setGrants] = useState<ServiceGrants | null>(null);
@@ -90,13 +94,16 @@ export default function ServiceAccessSection({
const [busy, setBusy] = useState(false);
const { isOperator } = useAuth();
- const load = useCallback(async () => {
+ // Whether the grants could be read: they cannot for someone else's agent,
+ // whose grants are its owner's business, and the section then hides.
+ const load = useCallback(async (): Promise<boolean> => {
try {
setGrants(await fetchServiceGrants(agent.id));
+ return true;
} catch (err) {
- // Someone else's agent: its grants are its owner's business.
if (err instanceof ApiError && err.status === 404) setHidden(true);
else setError(errorText(err));
+ return false;
}
}, [agent.id]);
@@ -108,10 +115,14 @@ export default function ServiceAccessSection({
}
}, []);
+ // The viewer's own connections are read only once the grants show this is
+ // their agent.
useEffect(() => {
- void load();
- void loadServices();
- fetchGitHubConnection().then(setGitHub, (err: unknown) => setGitHubError(errorText(err)));
+ void load().then((own) => {
+ if (!own) return;
+ void loadServices();
+ fetchGitHubConnection().then(setGitHub, (err: unknown) => setGitHubError(errorText(err)));
+ });
}, [load, loadServices]);
if (hidden) return null;
@@ -145,12 +156,18 @@ export default function ServiceAccessSection({
Service access
</Typography>
<Typography variant="body2" color="text.secondary">
- What this agent may use of your own connections. Its sessions are given
+ What this agent may use of your own connectors. Its sessions are given
short-lived access for what you grant, and nothing else.
</Typography>
{error && <Alert severity="error">{error}</Alert>}
{notice && <Alert severity="info">{notice}</Alert>}
{grants === null && !error && <CircularProgress size={20} />}
+ {grants !== null && !canGrant && (
+ <Alert severity="info">
+ New grants are only for an agent Switch Console runs from a known agent type. What it
+ has been granted can still be removed.
+ </Alert>
+ )}
{grants?.addressing_open && grants.grants.length > 0 && (
<Alert
@@ -189,7 +206,7 @@ export default function ServiceAccessSection({
variant="outlined"
label={grant.access === "write" ? "Read and write" : "Read"}
/>
- {grant.service === "github" && (
+ {canGrant && grant.service === "github" && (
<Button size="small" disabled={busy} onClick={() => setEditing(true)}>
Change
</Button>
@@ -229,6 +246,7 @@ export default function ServiceAccessSection({
grant={grants.grants.find((grant) => grant.service === service.slug) ?? null}
agentName={agent.name}
busy={busy}
+ canTurnOn={canGrant}
canSetUp={isOperator}
onTurnOn={() =>
void act(() => setServiceGrant(agent.id, service.slug, { access: null, resources: {} }))
@@ -237,7 +255,7 @@ export default function ServiceAccessSection({
/>
))}
- {grants && (editing || !githubGrant) && (
+ {grants && canGrant && (editing || !githubGrant) && (
<GitHubGrantForm
github={github}
githubError={githubError}
@@ -277,16 +295,23 @@ export function onOffGrantNote(
const off = `Turning it off stops its sessions using ${name} within a minute.`;
if (service.key)
return `On, ${agentName} uses ${name} with your key, as far as the key allows. ${off}`;
- const note = `On, ${agentName} acts as you at ${name}, with everything your ${name} connection allows. ${off}`;
+ const note = `On, ${agentName} acts as you at ${name}, with everything your ${name} connector allows. ${off}`;
return service.token_lifetime !== null && service.token_lifetime > 3600
? `${note} A token already handed out stays valid at ${name} until it expires or you disconnect.`
: note;
}
-/** The operator's way from a service that is not set up to where it is set up. */
+/** The operator's way from a service that is not set up to where it is set
+ * up: their server-wide connector apps, under Platform in the new layout. */
function SetUpLink() {
+ const { capabilities } = useAuth();
return (
- <Button component={RouterLink} to="/connectors" size="small" sx={{ ml: 1 }}>
+ <Button
+ component={RouterLink}
+ to={capabilities.features.gateway_v2 ? "/platform/connectors" : "/connectors"}
+ size="small"
+ sx={{ ml: 1 }}
+ >
Set up
</Button>
);
@@ -298,6 +323,7 @@ function OnOffGrant({
grant,
agentName,
busy,
+ canTurnOn,
canSetUp,
onTurnOn,
onTurnOff,
@@ -306,13 +332,15 @@ function OnOffGrant({
grant: ServiceGrant | null;
agentName: string;
busy: boolean;
+ canTurnOn: boolean;
canSetUp: boolean;
onTurnOn: () => void;
onTurnOff: () => void;
}) {
const connected = service.status === "active";
// A grant can be turned off whatever the server's state; on needs a usable connection.
- const blocked = grant === null && (!connected || service.unavailable_reason !== null);
+ const blocked =
+ grant === null && (!canTurnOn || !connected || service.unavailable_reason !== null);
return (
<Paper variant="outlined" sx={{ p: 1.5 }}>
<Stack direction="row" alignItems="center" spacing={1}>
@@ -346,7 +374,7 @@ function OnOffGrant({
)}
{!grant && !connected && !service.unavailable_reason && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
- To turn {service.name} on, first connect it from Switch Console&apos;s connections.
+ To turn {service.name} on, first connect it in Switch Console, under Connectors.
</Typography>
)}
<Typography variant="caption" color="text.secondary" sx={{ display: "block", mt: 0.5 }}>
@@ -398,8 +426,8 @@ function GitHubGrantForm({
if (github.status === "not_connected")
return (
<Typography variant="body2" color="text.secondary">
- To grant GitHub, first connect your GitHub account from Switch Console&apos;s
- connections.
+ To grant GitHub, first connect your GitHub account in Switch Console, under
+ Connectors.
</Typography>
);
@@ -469,7 +497,7 @@ function GitHubGrantForm({
/** What removing a grant does, and what it does not. */
export const REMOVED_NOTE =
- "Removing a grant stops Switch giving this access. On a laptop or server, the agent may still use the machine's own sign-in, and the session says so when it does.";
+ "Removing a grant stops Switch giving this access. On a device, the agent may still use the device's own sign-in, and the session says so when it does.";
/** What a GitHub grant changes on the machine the agent runs on, and what it does not. */
export function GitHubNotes() {
diff --git a/gateway/src/pages/agents/agentManageControls.test.tsx b/gateway/src/pages/agents/agentManageControls.test.tsx
index 2d0feee32..d3956b734 100644
--- a/gateway/src/pages/agents/agentManageControls.test.tsx
+++ b/gateway/src/pages/agents/agentManageControls.test.tsx
@@ -2,6 +2,7 @@ import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentDetail } from "../../data/api";
import { useAuth } from "../../data/AuthContext";
+import { ALL_OFF } from "../../data/featureFlags";
import * as hooks from "../../data/hooks";
import AgentDetailPage from "./AgentDetailPage";
@@ -48,12 +49,39 @@ const agent = {
children: [],
} as unknown as AgentDetail;
-function showPageAs(userId: string, canManage: boolean) {
+type AgentFlags = Pick<
+ AgentDetail,
+ "can_manage" | "can_rename" | "can_edit_options" | "can_transfer" | "transfer_blocked_reason"
+>;
+
+const MANAGER: AgentFlags = {
+ can_manage: true,
+ can_rename: true,
+ can_edit_options: true,
+ can_transfer: true,
+ transfer_blocked_reason: null,
+};
+const OUTSIDER: AgentFlags = {
+ can_manage: false,
+ can_rename: false,
+ can_edit_options: false,
+ can_transfer: false,
+ transfer_blocked_reason: null,
+};
+
+/** The page as the server describes the agent to this viewer. Who they are
+ * does not matter to the page: every control follows these flags. */
+function showPageWith(flags: AgentFlags) {
vi.mocked(useAuth).mockReturnValue({
- user: { id: userId },
+ capabilities: { features: ALL_OFF },
} as unknown as ReturnType<typeof useAuth>);
vi.mocked(hooks.useAgent).mockReturnValue({
- data: { ...agent, can_manage: canManage },
+ data: {
+ ...agent,
+ ...flags,
+ can_change_manage_agents: false,
+ can_grant_services: false,
+ },
loading: false,
error: null,
refetch: vi.fn(),
@@ -77,23 +105,16 @@ function showPageAs(userId: string, canManage: boolean) {
afterEach(cleanup);
describe("agent rename and options", () => {
- it("are offered to someone else the server says may manage it, such as an admin", () => {
- showPageAs("u2", true);
+ it("are offered to whoever the server says may manage it", () => {
+ showPageWith(MANAGER);
expect(screen.getByRole("button", { name: "Rename agent" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Save" })).toBeTruthy();
expect(screen.queryByText(/can edit these options/)).toBeNull();
});
- it("are offered to the owner", () => {
- showPageAs("u1", true);
-
- expect(screen.getByRole("button", { name: "Rename agent" })).toBeTruthy();
- expect(screen.getByRole("button", { name: "Save" })).toBeTruthy();
- });
-
it("are not offered to anyone else", () => {
- showPageAs("u2", false);
+ showPageWith(OUTSIDER);
expect(screen.queryByRole("button", { name: "Rename agent" })).toBeNull();
expect(screen.queryByRole("button", { name: "Save" })).toBeNull();
@@ -101,4 +122,47 @@ describe("agent rename and options", () => {
screen.getByText("Only the agent's owner and admins can edit these options."),
).toBeTruthy();
});
+
+ it("keeps rename from an agent the server will not rename, leaving its options", () => {
+ showPageWith({ ...MANAGER, can_rename: false });
+
+ expect(screen.queryByRole("button", { name: "Rename agent" })).toBeNull();
+ expect(screen.getByRole("button", { name: "Save" })).toBeTruthy();
+ });
+});
+
+describe("agent options", () => {
+ it("are not offered where the server will not edit them, though the agent is managed", () => {
+ showPageWith({ ...MANAGER, can_edit_options: false });
+
+ expect(screen.getByRole("button", { name: "Rename agent" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Save" })).toBeNull();
+ });
+});
+
+describe("agent transfer", () => {
+ it("is offered where the server would move it", () => {
+ showPageWith(MANAGER);
+
+ const transfer = screen.getByRole("button", { name: "Transfer ownership" });
+ expect((transfer as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it("is shown disabled, with the server's reason, where it would refuse", () => {
+ showPageWith({
+ ...MANAGER,
+ can_transfer: false,
+ transfer_blocked_reason: "Revoke its service grants before handing it over.",
+ });
+
+ const transfer = screen.getByRole("button", { name: "Transfer ownership" });
+ expect((transfer as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.getByText("Revoke its service grants before handing it over.")).toBeTruthy();
+ });
+
+ it("is not shown to someone who may not manage it", () => {
+ showPageWith(OUTSIDER);
+
+ expect(screen.queryByRole("button", { name: "Transfer ownership" })).toBeNull();
+ });
});
diff --git a/gateway/src/pages/agents/sessionLabels.test.tsx b/gateway/src/pages/agents/sessionLabels.test.tsx
index 29dc9b15a..280138c6a 100644
--- a/gateway/src/pages/agents/sessionLabels.test.tsx
+++ b/gateway/src/pages/agents/sessionLabels.test.tsx
@@ -22,16 +22,16 @@ describe("sessionRunner", () => {
expect(
sessionRunner(session({ lifecycle: "controller", controller_id: "ctrl-1" })),
).toEqual({
- label: "Run by a machine",
+ label: "Run by a device",
detail:
- "Run by agent controller ctrl-1 on the machine the agent is placed on, working in this room.",
+ "Run by agent controller ctrl-1 on the device the agent is placed on, working in this room.",
});
expect(
sessionRunner(
session({ lifecycle: "controller", controller_id: "ctrl-1", room_id: null, room_name: null }),
)?.detail,
).toBe(
- "Run by agent controller ctrl-1 on the machine the agent is placed on, running, with no session working in a room yet.",
+ "Run by agent controller ctrl-1 on the device the agent is placed on, running, with no session working in a room yet.",
);
});
@@ -75,10 +75,10 @@ describe("SessionsSection", () => {
expect(screen.getByText("design")).toBeTruthy();
expect(screen.getByText("triage")).toBeTruthy();
- expect(screen.getAllByText("Run by a machine")).toHaveLength(1);
+ expect(screen.getAllByText("Run by a device")).toHaveLength(1);
expect(screen.queryByText("controller")).toBeNull();
- fireEvent.click(screen.getByText("Run by a machine"));
+ fireEvent.click(screen.getByText("Run by a device"));
expect(screen.getByText("Machines page")).toBeTruthy();
});
@@ -87,7 +87,7 @@ describe("SessionsSection", () => {
session({ lifecycle: "controller", controller_id: "ctrl-1", room_id: null, room_name: null }),
]);
expect(screen.getByText("Not in a room yet")).toBeTruthy();
- expect(screen.getByText("Run by a machine")).toBeTruthy();
+ expect(screen.getByText("Run by a device")).toBeTruthy();
expect(screen.queryByText("Room-agnostic")).toBeNull();
});
});
diff --git a/gateway/src/pages/agents/sessionLabels.ts b/gateway/src/pages/agents/sessionLabels.ts
index 380a6adeb..c87234847 100644
--- a/gateway/src/pages/agents/sessionLabels.ts
+++ b/gateway/src/pages/agents/sessionLabels.ts
@@ -18,10 +18,10 @@ export function sessionRunner(session: AgentSessionDetail): SessionRunner | null
? "working in this room"
: "running, with no session working in a room yet";
return {
- label: "Run by a machine",
+ label: "Run by a device",
detail: session.controller_id
- ? `Run by agent controller ${session.controller_id} on the machine the agent is placed on, ${place}.`
- : `Run by the agent controller of the machine the agent is placed on, ${place}.`,
+ ? `Run by agent controller ${session.controller_id} on the device the agent is placed on, ${place}.`
+ : `Run by the agent controller of the device the agent is placed on, ${place}.`,
};
}
diff --git a/gateway/src/pages/collaborations/CollaborationsPage.test.tsx b/gateway/src/pages/collaborations/CollaborationsPage.test.tsx
index 99c21950e..7e560478c 100644
--- a/gateway/src/pages/collaborations/CollaborationsPage.test.tsx
+++ b/gateway/src/pages/collaborations/CollaborationsPage.test.tsx
@@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/re
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BridgeDetail } from "../../data/api";
import * as api from "../../data/api";
+import { ALL_OFF } from "../../data/featureFlags";
import { useAuth } from "../../data/AuthContext";
import * as hooks from "../../data/hooks";
import type { UseQueryResult } from "../../data/hooks";
@@ -34,6 +35,17 @@ function authState(canAdminTenant: boolean) {
loadError: null,
isOperator: false,
canAdminTenant,
+ capabilities: {
+ isOperator: false,
+ administersWorkspace: canAdminTenant,
+ administersOrganization: false,
+ inOrganization: false,
+ canDeleteWorkspace: false,
+ canManageDataProtection: false,
+ features: ALL_OFF,
+ },
+ staleError: null,
+ recheck: vi.fn(),
refresh: vi.fn(async () => {}),
login: vi.fn(async () => {}),
logout: vi.fn(async () => {}),
@@ -59,6 +71,8 @@ function bridge(overrides: Partial<BridgeDetail> = {}): BridgeDetail {
created_at: "2026-01-01",
attention: null,
team_placement_supported: false,
+ can_manage: true,
+ can_delete: true,
...overrides,
};
}
@@ -73,7 +87,10 @@ function setup({
installablePlatforms?: string[];
} = {}) {
vi.mocked(useAuth).mockReturnValue(authState(isAdmin));
- vi.mocked(hooks.useBridges).mockReturnValue(queryResult(bridges));
+ // The server answers whether this person may change or delete each one.
+ vi.mocked(hooks.useBridges).mockReturnValue(
+ queryResult(isAdmin ? bridges : bridges.map((b) => ({ ...b, can_manage: false, can_delete: false }))),
+ );
vi.mocked(hooks.useInstallablePlatforms).mockReturnValue(
queryResult(installablePlatforms),
);
@@ -275,6 +292,34 @@ describe("CollaborationsPage", () => {
);
});
+ it("offers delete only on a connection the server says may be deleted", () => {
+ setup({
+ bridges: [
+ bridge({ bridge_id: "b1", display_name: "Deletable" }),
+ bridge({ bridge_id: "b2", display_name: "Kept", can_delete: false }),
+ ],
+ });
+ render(<CollaborationsPage />);
+
+ expect(screen.getByRole("button", { name: "Delete Deletable" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Delete Kept" })).toBeNull();
+ });
+
+ it("lets someone who may not change a connection see it, with nothing to act on", () => {
+ setup({
+ isAdmin: false,
+ bridges: [bridge({ bridge_id: "b1", display_name: "Acme Corp", team_placement_supported: true })],
+ });
+ render(<CollaborationsPage />);
+
+ expect(screen.getByText("Acme Corp")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Delete Acme Corp" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Choose which teams this app is in" })).toBeNull();
+ for (const toggle of screen.getAllByRole("switch")) {
+ expect((toggle as HTMLInputElement).disabled).toBe(true);
+ }
+ });
+
it("labels the type column with the platform's own name", () => {
setup({ bridges: [bridge({ bridge_type: "teams" })] });
render(<CollaborationsPage />);
diff --git a/gateway/src/pages/collaborations/CollaborationsPage.tsx b/gateway/src/pages/collaborations/CollaborationsPage.tsx
index 8d1a57836..7e618b276 100644
--- a/gateway/src/pages/collaborations/CollaborationsPage.tsx
+++ b/gateway/src/pages/collaborations/CollaborationsPage.tsx
@@ -28,7 +28,7 @@ import {
} from "../../data/api";
import { useAuth } from "../../data/AuthContext";
import { useBridges, useInstallablePlatforms } from "../../data/hooks";
-import { formatDate, platformLabel, titleCase } from "../../theme/hootFormat";
+import { formatDate, platformLabel, sentenceCase } from "../../theme/hootFormat";
import AddToChatDialog from "./AddToChatDialog";
import AttentionBanner from "./AttentionBanner";
import DeleteConnectionText from "./DeleteConnectionText";
@@ -117,6 +117,11 @@ export default function CollaborationsPage() {
}
}, []);
+ const rows = useMemo<BridgeRow[]>(
+ () => (bridges ?? []).map((b) => ({ ...b, id: b.bridge_id })),
+ [bridges],
+ );
+
const columns = useMemo<GridColDef<BridgeRow>[]>(
() => [
{
@@ -139,7 +144,7 @@ export default function CollaborationsPage() {
width: 130,
renderCell: ({ value }) => (
<Chip
- label={titleCase(String(value))}
+ label={sentenceCase(String(value))}
size="small"
color={STATUS_COLOR[value as string] ?? "default"}
/>
@@ -155,7 +160,7 @@ export default function CollaborationsPage() {
<Switch
size="small"
checked={row.agent_greetings_enabled}
- disabled={!isAdmin || savingId === row.bridge_id}
+ disabled={!row.can_manage || savingId === row.bridge_id}
onChange={(e) =>
handleToggleGreetings(row.bridge_id, e.target.checked)
}
@@ -173,7 +178,7 @@ export default function CollaborationsPage() {
size="small"
checked={row.channel_creation_supported && row.channel_creation_enabled}
disabled={
- !isAdmin || savingId === row.bridge_id || !row.channel_creation_supported
+ !row.can_manage || savingId === row.bridge_id || !row.channel_creation_supported
}
onChange={(e) =>
handleToggleChannelCreation(row.bridge_id, e.target.checked)
@@ -194,7 +199,7 @@ export default function CollaborationsPage() {
width: 140,
valueFormatter: (value) => formatDate(value as string),
},
- ...(isAdmin
+ ...(rows.some((row) => row.can_manage || row.can_delete)
? [
{
field: "actions" as const,
@@ -215,14 +220,14 @@ export default function CollaborationsPage() {
justifyContent="flex-end"
height="100%"
>
- {row.team_placement_supported && (
+ {row.can_manage && row.team_placement_supported && (
<Tooltip title="Choose which teams this app is in">
<IconButton size="small" onClick={() => setTeamsTarget(row)}>
<GroupsOutlined fontSize="small" />
</IconButton>
</Tooltip>
)}
- {(row.install_links ?? []).length > 0 && (
+ {row.can_manage && (row.install_links ?? []).length > 0 && (
<Tooltip title="Add this app to a chat">
<IconButton
size="small"
@@ -232,21 +237,22 @@ export default function CollaborationsPage() {
</IconButton>
</Tooltip>
)}
- <IconButton size="small" onClick={() => setDeleteTarget(row)}>
- <DeleteOutline fontSize="small" />
- </IconButton>
+ {row.can_delete && (
+ <IconButton
+ size="small"
+ onClick={() => setDeleteTarget(row)}
+ aria-label={`Delete ${row.display_name}`}
+ >
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ )}
</Stack>
),
},
]
: []),
],
- [isAdmin, savingId, handleToggleGreetings, handleToggleChannelCreation],
- );
-
- const rows = useMemo<BridgeRow[]>(
- () => (bridges ?? []).map((b) => ({ ...b, id: b.bridge_id })),
- [bridges],
+ [rows, savingId, handleToggleGreetings, handleToggleChannelCreation],
);
const needsAttention = useMemo(
@@ -257,7 +263,7 @@ export default function CollaborationsPage() {
return (
<Box>
<Stack direction="row" alignItems="center" mb={2}>
- <Typography variant="h5">Messaging Apps</Typography>
+ <Typography variant="h5">Messaging apps</Typography>
{isAdmin && (
<Button
variant="contained"
@@ -265,7 +271,7 @@ export default function CollaborationsPage() {
sx={{ ml: "auto" }}
onClick={() => setRegisterOpen(true)}
>
- Register messaging app
+ Add messaging app
</Button>
)}
</Stack>
@@ -282,7 +288,7 @@ export default function CollaborationsPage() {
displayName={b.display_name}
message={b.attention ?? ""}
canApproveAgain={
- isAdmin &&
+ b.can_manage &&
b.team_placement_supported &&
(installablePlatforms ?? []).includes(b.bridge_type)
}
@@ -297,11 +303,7 @@ export default function CollaborationsPage() {
<DataTable rows={rows} columns={columns} />
)}
- <InstalledAppsSection
- key={installsVersion}
- isAdmin={isAdmin}
- onConnectionsChanged={refetch}
- />
+ <InstalledAppsSection key={installsVersion} onConnectionsChanged={refetch} />
<RegisterMessagingAppDialog
open={registerOpen}
diff --git a/gateway/src/pages/collaborations/DeleteConnectionText.tsx b/gateway/src/pages/collaborations/DeleteConnectionText.tsx
index 2e040f20a..d847668b5 100644
--- a/gateway/src/pages/collaborations/DeleteConnectionText.tsx
+++ b/gateway/src/pages/collaborations/DeleteConnectionText.tsx
@@ -65,7 +65,7 @@ export default function DeleteConnectionText({ bridge }: { bridge: BridgeDetail
&quot;{bridge.display_name}&quot;. Deleting it disconnects{" "}
{chats === 1 ? "it" : "each of them"} first: the bot leaves, and the
chat&apos;s room is kept as an internal-only room, reachable only from
- inside Switch. Then the connection is deleted, which turns Telegram off
+ inside Switch. Then the messaging app is deleted, which turns Telegram off
for this organisation.
</DialogContentText>
);
diff --git a/gateway/src/pages/collaborations/DisconnectAppDialog.test.tsx b/gateway/src/pages/collaborations/DisconnectAppDialog.test.tsx
index fded96e70..6bd254030 100644
--- a/gateway/src/pages/collaborations/DisconnectAppDialog.test.tsx
+++ b/gateway/src/pages/collaborations/DisconnectAppDialog.test.tsx
@@ -12,6 +12,7 @@ const install: InstalledApp = {
bridge_id: "b1",
installed_at: "2026-01-01",
ended_at: null,
+ can_disconnect: true,
};
describe("DisconnectAppDialog", () => {
diff --git a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx b/gateway/src/pages/collaborations/DisconnectAppDialog.tsx
index bcb1d7b0d..407fb248a 100644
--- a/gateway/src/pages/collaborations/DisconnectAppDialog.tsx
+++ b/gateway/src/pages/collaborations/DisconnectAppDialog.tsx
@@ -46,16 +46,16 @@ interface Copy {
}
const CONNECTION_ROOMS = (noun: string) =>
- "Rooms that used this connection are kept, but become internal-only: they " +
- `stop mirroring to the ${noun}, and installing again creates a new ` +
- "connection rather than reattaching them.";
+ "Rooms that used it are kept, but become internal-only: they " +
+ `stop mirroring to the ${noun}, and installing again does not ` +
+ "reattach them.";
const PLATFORM_COPY: Record<string, Copy> = {
discord: {
noun: "server",
effect:
"Switch will stop mirroring messages to and from it. The bot stays in " +
- "the server until you remove it in Discord — disconnecting here does " +
+ "the Discord server until you remove it there — disconnecting here does " +
"not remove it.",
rooms: CONNECTION_ROOMS("server"),
},
@@ -86,8 +86,8 @@ const PLATFORM_COPY: Record<string, Copy> = {
const DEFAULT_COPY: Copy = {
noun: "workspace",
effect:
- "Switch's access token is revoked at the platform and the connection it " +
- "created is removed.",
+ "Switch's access token is revoked at the platform and the messaging app " +
+ "it added is removed.",
rooms: CONNECTION_ROOMS("workspace"),
};
diff --git a/gateway/src/pages/collaborations/InstalledAppsSection.test.tsx b/gateway/src/pages/collaborations/InstalledAppsSection.test.tsx
index 977f0e7e0..3cc3ffd5d 100644
--- a/gateway/src/pages/collaborations/InstalledAppsSection.test.tsx
+++ b/gateway/src/pages/collaborations/InstalledAppsSection.test.tsx
@@ -12,6 +12,7 @@ const teamsInstall: InstalledApp = {
bridge_id: "b1",
installed_at: "2026-01-01",
ended_at: null,
+ can_disconnect: true,
};
function mockFetch(installs: InstalledApp[] = []) {
@@ -37,7 +38,7 @@ describe("InstalledAppsSection", () => {
it("names the Microsoft Teams app rather than a bare title-cased 'Teams'", async () => {
mockFetch();
- render(<InstalledAppsSection isAdmin onConnectionsChanged={() => {}} />);
+ render(<InstalledAppsSection onConnectionsChanged={() => {}} />);
expect(
await screen.findByRole("button", { name: "Add to Microsoft Teams" }),
@@ -46,7 +47,7 @@ describe("InstalledAppsSection", () => {
it("shows the platform column's own name, not a bare title-cased key", async () => {
mockFetch([teamsInstall]);
- render(<InstalledAppsSection isAdmin onConnectionsChanged={() => {}} />);
+ render(<InstalledAppsSection onConnectionsChanged={() => {}} />);
expect(await screen.findByText("org-123")).toBeTruthy();
// The row's platform chip renders Microsoft's own name, same as the
diff --git a/gateway/src/pages/collaborations/InstalledAppsSection.tsx b/gateway/src/pages/collaborations/InstalledAppsSection.tsx
index c50440e3d..70d01a169 100644
--- a/gateway/src/pages/collaborations/InstalledAppsSection.tsx
+++ b/gateway/src/pages/collaborations/InstalledAppsSection.tsx
@@ -24,7 +24,7 @@ import {
formatDate,
pluralize,
platformLabel,
- titleCase,
+ sentenceCase,
} from "../../theme/hootFormat";
import discordIcon from "../../assets/bridges/discord.svg";
import slackIcon from "../../assets/bridges/slack.svg";
@@ -75,16 +75,12 @@ const ENDED_COLOR: Record<string, "warning" | "default"> = {
};
interface Props {
- isAdmin: boolean;
// Disconnecting removes the connection the install created, so the list of
// connections above this section is stale once it succeeds.
onConnectionsChanged: () => void;
}
-export default function InstalledAppsSection({
- isAdmin,
- onConnectionsChanged,
-}: Props) {
+export default function InstalledAppsSection({ onConnectionsChanged }: Props) {
const { data: offered, refetch: refetchOffered } = useInstallablePlatforms();
const { data: installs, loading, refetch } = useInstalledApps();
const [starting, setStarting] = useState<string | null>(null);
@@ -103,13 +99,14 @@ export default function InstalledAppsSection({
// Every platform this organisation can add to, or has anything recorded
// for — a platform whose app was since removed still shows its history.
+ // The server offers the OAuth platforms to its admins alone.
const platforms = useMemo(() => {
const seen = new Set<string>();
for (const c of claimable) seen.add(c.platform);
- if (isAdmin) for (const p of installable) seen.add(p);
+ for (const p of installable) seen.add(p);
for (const row of rows) seen.add(row.platform);
return [...seen];
- }, [claimable, installable, rows, isAdmin]);
+ }, [claimable, installable, rows]);
const handleInstall = useCallback(async (platform: string) => {
setStarting(platform);
@@ -167,7 +164,7 @@ export default function InstalledAppsSection({
</Typography>
<Typography variant="body2" color="text.secondary" mb={2}>
This deployment&apos;s own apps, using credentials only the deployment
- holds. Disconnect what an app is installed in here: a connection above
+ holds. Disconnect what an app is installed in here: a messaging app above
cannot be deleted while an app is still installed through it.
</Typography>
@@ -189,8 +186,7 @@ export default function InstalledAppsSection({
platform={platform}
installs={rows.filter((row) => row.platform === platform)}
claimable={claimed}
- canInstall={isAdmin && installable.includes(platform)}
- canDisconnect={isAdmin || claimed !== undefined}
+ canInstall={installable.includes(platform)}
starting={starting}
onAdd={() =>
claimed ? handleClaim(platform) : handleInstall(platform)
@@ -222,7 +218,6 @@ interface CardProps {
// Set for a claim-based platform, with what this caller may do on it.
claimable: ClaimablePlatform | undefined;
canInstall: boolean;
- canDisconnect: boolean;
starting: string | null;
onAdd: () => void;
onDisconnect: (install: InstalledApp) => void;
@@ -233,7 +228,6 @@ function PlatformCard({
installs,
claimable,
canInstall,
- canDisconnect,
starting,
onAdd,
onDisconnect,
@@ -262,7 +256,7 @@ function PlatformCard({
{active.length > 0
? `${pluralize(active.length, noun)} connected`
: claimable?.connected
- ? `No ${noun}s connected. The connection stays until an admin deletes it above.`
+ ? `No ${noun}s connected. The messaging app stays until an admin deletes it above.`
: "Not connected"}
</Typography>
</Box>
@@ -293,7 +287,7 @@ function PlatformCard({
<InstallRow
key={install.id}
install={install}
- onDisconnect={canDisconnect ? () => onDisconnect(install) : undefined}
+ onDisconnect={install.can_disconnect ? () => onDisconnect(install) : undefined}
/>
))}
@@ -369,7 +363,7 @@ function InstallRow({
</Box>
{!live && (
<Chip
- label={titleCase(install.status)}
+ label={sentenceCase(install.status)}
size="small"
color={ENDED_COLOR[install.status] ?? "default"}
/>
diff --git a/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx b/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx
index 28de38081..4ff2340ac 100644
--- a/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx
+++ b/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx
@@ -123,7 +123,7 @@ export default function RegisterMessagingAppDialog({
return (
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
- <DialogTitle>Register messaging app</DialogTitle>
+ <DialogTitle>Add messaging app</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
{error && <Alert severity="error">{error}</Alert>}
@@ -151,7 +151,7 @@ export default function RegisterMessagingAppDialog({
{selectedType && (
<>
<TextField
- label="Display Name"
+ label="Display name"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
fullWidth
@@ -171,7 +171,7 @@ export default function RegisterMessagingAppDialog({
{!channelCreationSupported && (
<Typography variant="caption" color="text.secondary">
{humanize(selectedType)} has no way to create channels from
- Switch, so this connection can only be used with existing
+ Switch, so this messaging app can only be used with existing
channels.
</Typography>
)}
@@ -196,7 +196,7 @@ export default function RegisterMessagingAppDialog({
disabled={!canSubmit || submitting}
startIcon={submitting ? <CircularProgress size={16} /> : undefined}
>
- Register
+ Add
</Button>
</DialogActions>
</Dialog>
diff --git a/gateway/src/pages/collaborations/TeamsPlacementDialog.test.tsx b/gateway/src/pages/collaborations/TeamsPlacementDialog.test.tsx
index 2c436e015..62ba21aaf 100644
--- a/gateway/src/pages/collaborations/TeamsPlacementDialog.test.tsx
+++ b/gateway/src/pages/collaborations/TeamsPlacementDialog.test.tsx
@@ -15,6 +15,8 @@ const bridge: BridgeDetail = {
created_at: "2026-01-01",
attention: null,
team_placement_supported: true,
+ can_manage: true,
+ can_delete: true,
};
function placements(
@@ -190,7 +192,7 @@ describe("TeamsPlacementDialog", () => {
if (reads === 1) return jsonResponse(200, before);
if (reads === 2) {
return jsonResponse(503, {
- detail: "The Teams connection is not running; try again in a moment.",
+ detail: "The Teams messaging app is not running; try again in a moment.",
});
}
return jsonResponse(200, after);
@@ -203,7 +205,7 @@ describe("TeamsPlacementDialog", () => {
fireEvent.click(screen.getAllByRole("radio")[1]);
expect(
- await screen.findByText("The connection is restarting with your change…"),
+ await screen.findByText("Switch is reconnecting to Teams with your change…"),
).toBeTruthy();
expect(screen.queryByText(/not running/)).toBeNull();
await vi.advanceTimersByTimeAsync(1500);
@@ -220,19 +222,19 @@ describe("TeamsPlacementDialog", () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
mockFetch(() =>
jsonResponse(503, {
- detail: "The Teams connection is not running; try again in a moment.",
+ detail: "The Teams messaging app is not running; try again in a moment.",
}),
);
render(
<TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,
);
- await screen.findByText("The connection is restarting with your change…");
+ await screen.findByText("Switch is reconnecting to Teams with your change…");
await vi.advanceTimersByTimeAsync(1500 * 21);
expect(
await screen.findByText(
- "The Teams connection is not running; try again in a moment.",
+ "The Teams messaging app is not running; try again in a moment.",
),
).toBeTruthy();
vi.useRealTimers();
@@ -241,12 +243,12 @@ describe("TeamsPlacementDialog", () => {
it("stops waiting for a restart once the dialog is closed", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
const fetchMock = mockFetch(() =>
- jsonResponse(503, { detail: "The Teams connection is not running." }),
+ jsonResponse(503, { detail: "The Teams messaging app is not running." }),
);
const { rerender } = render(
<TeamsPlacementDialog bridge={bridge} onClose={() => {}} onChanged={() => {}} />,
);
- await screen.findByText("The connection is restarting with your change…");
+ await screen.findByText("Switch is reconnecting to Teams with your change…");
rerender(<TeamsPlacementDialog bridge={null} onClose={() => {}} onChanged={() => {}} />);
const callsWhenClosed = fetchMock.mock.calls.length;
@@ -335,7 +337,7 @@ describe("TeamsPlacementDialog", () => {
mockFetch((_url, init) =>
init?.method === "DELETE"
? jsonResponse(503, {
- detail: "The Teams connection is not running; try again in a moment.",
+ detail: "The Teams messaging app is not running; try again in a moment.",
})
: jsonResponse(200, placements()),
);
@@ -348,7 +350,7 @@ describe("TeamsPlacementDialog", () => {
fireEvent.click(switches[0]); // Engineering already has Switch -> DELETE, which fails
expect(
- await screen.findByText("The Teams connection is not running; try again in a moment."),
+ await screen.findByText("The Teams messaging app is not running; try again in a moment."),
).toBeTruthy();
});
diff --git a/gateway/src/pages/collaborations/TeamsPlacementDialog.tsx b/gateway/src/pages/collaborations/TeamsPlacementDialog.tsx
index 265fbfc97..ba48a240a 100644
--- a/gateway/src/pages/collaborations/TeamsPlacementDialog.tsx
+++ b/gateway/src/pages/collaborations/TeamsPlacementDialog.tsx
@@ -210,7 +210,7 @@ export default function TeamsPlacementDialog({ bridge, onClose, onChanged }: Pro
<CircularProgress size={28} />
{restarting && (
<Typography variant="body2" color="text.secondary">
- The connection is restarting with your change…
+ Switch is reconnecting to Teams with your change…
</Typography>
)}
</Stack>
diff --git a/gateway/src/pages/collaborations/deleteConnection.test.tsx b/gateway/src/pages/collaborations/deleteConnection.test.tsx
index 02b69117f..dfb2b7065 100644
--- a/gateway/src/pages/collaborations/deleteConnection.test.tsx
+++ b/gateway/src/pages/collaborations/deleteConnection.test.tsx
@@ -25,6 +25,7 @@ function chat(id: string, overrides: Partial<InstalledApp> = {}): InstalledApp {
bridge_id: "b1",
installed_at: "2026-01-01",
ended_at: null,
+ can_disconnect: true,
...overrides,
};
}
diff --git a/gateway/src/pages/connector-apps/ConnectorAppsPage.test.tsx b/gateway/src/pages/connector-apps/ConnectorAppsPage.test.tsx
index 8b5a9e3f5..3fae16e5a 100644
--- a/gateway/src/pages/connector-apps/ConnectorAppsPage.test.tsx
+++ b/gateway/src/pages/connector-apps/ConnectorAppsPage.test.tsx
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CONNECTORS_NOT_ENABLED, type ConnectorApp, type ConnectorApps } from "../../data/api";
import { useAuth } from "../../data/AuthContext";
import ConnectorAppsPage from "./ConnectorAppsPage";
-import { audienceText, ONLY_THE_OPERATOR, PUBLIC_URL_BANNER } from "./connectorApps";
+import { audienceText, PUBLIC_URL_BANNER } from "./connectorApps";
import { app } from "./testFixtures";
vi.mock("../../data/AuthContext", () => ({ useAuth: vi.fn() }));
@@ -63,8 +63,12 @@ function listOf(...apps: ConnectorApp[]): ConnectorApps {
};
}
-function operator(isOperator = true) {
- vi.mocked(useAuth).mockReturnValue({ isOperator } as ReturnType<typeof useAuth>);
+// Only the operator reaches this page (the route table guards it); what it
+// reads is whether the server runs connectors at all.
+function connectors(enabled = true) {
+ vi.mocked(useAuth).mockReturnValue({
+ capabilities: { features: { service_connections: enabled } },
+ } as ReturnType<typeof useAuth>);
}
function card(slug: string) {
@@ -72,25 +76,19 @@ function card(slug: string) {
}
describe("ConnectorAppsPage", () => {
- beforeEach(() => operator());
+ beforeEach(() => connectors());
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
- it("tells anyone but the operator whose page it is, and asks nothing of the server", () => {
- operator(false);
+ it("says what to turn on where the server has no connectors, and asks nothing of it", () => {
+ connectors(false);
const calls = serve(listOf());
render(<ConnectorAppsPage />);
- expect(screen.getByText(ONLY_THE_OPERATOR)).toBeTruthy();
- expect(calls).toEqual([]);
- });
-
- it("says what to turn on where the server has no connectors at all", async () => {
- serve(listOf(), { "GET /gateway/connector-apps": [404, { detail: "Not Found" }] });
- render(<ConnectorAppsPage />);
- expect(await screen.findByText(CONNECTORS_NOT_ENABLED)).toBeTruthy();
+ expect(screen.getByText(CONNECTORS_NOT_ENABLED)).toBeTruthy();
expect(screen.queryAllByTestId(/connector-app-/)).toEqual([]);
+ expect(calls).toEqual([]);
});
it("lists every app, what needs setting up first, and who sets themselves up", async () => {
@@ -366,7 +364,7 @@ describe("ConnectorAppsPage", () => {
},
});
render(<ConnectorAppsPage />);
- const chip = (await screen.findByText("Set on the server")).closest(".MuiChip-root")!;
+ const chip = (await screen.findByText("Set in configuration")).closest(".MuiChip-root")!;
expect(chip.className).toContain("MuiChip-colorSuccess");
expect(chip.className).toContain("MuiChip-filled");
expect(
diff --git a/gateway/src/pages/connector-apps/ConnectorAppsPage.tsx b/gateway/src/pages/connector-apps/ConnectorAppsPage.tsx
index d3c37c1cd..3fad20038 100644
--- a/gateway/src/pages/connector-apps/ConnectorAppsPage.tsx
+++ b/gateway/src/pages/connector-apps/ConnectorAppsPage.tsx
@@ -7,7 +7,6 @@ import ConnectorAppCard from "./ConnectorAppCard";
import {
cardOrder,
missingPublicUrl,
- ONLY_THE_OPERATOR,
PUBLIC_URL_BANNER,
sentBackTo,
} from "./connectorApps";
@@ -19,26 +18,24 @@ function Heading({ publicUrl }: { publicUrl: string | null }) {
<Typography variant="h5">Connectors</Typography>
<Typography variant="body2" color="text.secondary">
Some connectors sign in through an app you register at the vendor. Set each up once,
- for the whole server, before anyone can connect it.
+ for all of Switch, before anyone can connect it.
{publicUrl !== null && ` ${sentBackTo(publicUrl)}`}
</Typography>
</Box>
);
}
-/** Every app of `scope`, a card each, under `heading`. A 404 means the
- * routes are not mounted, and shows `notEnabled`. Parents must check the
- * server's feature flags before rendering it. */
+/** Every app of `scope`, a card each, under `heading`. Render it only where
+ * the server mounts the routes it reads: `service_connections`, and for an
+ * organization's apps `organization_connector_apps` too. */
export function ConnectorAppsList({
scope,
- notEnabled,
heading: headingOf,
}: {
scope: ConnectorAppScope;
- notEnabled: string;
heading: (publicUrl: string | null) => ReactNode;
}) {
- const { data, loading, error, refetch } = useConnectorApps(scope, notEnabled);
+ const { data, loading, error, refetch } = useConnectorApps(scope);
const [checkFailures, setCheckFailures] = useState<Record<string, string>>({});
const [toast, setToast] = useState<string | null>(null);
@@ -54,7 +51,7 @@ export function ConnectorAppsList({
return (
<>
{heading}
- <Alert severity={error === notEnabled ? "info" : "error"}>{error}</Alert>
+ <Alert severity="error">{error}</Alert>
</>
);
if (data === null) return heading;
@@ -96,21 +93,20 @@ export function ConnectorAppsList({
);
}
-/** The server operator's page; anyone else is told whose it is, and nothing is asked of the server. */
+/** The server operator's page: the route table lets no one else in. */
export default function ConnectorAppsPage() {
- const { isOperator } = useAuth();
+ const { capabilities } = useAuth();
return (
<Box>
- {isOperator ? (
+ {capabilities.features.service_connections ? (
<ConnectorAppsList
scope="server"
- notEnabled={CONNECTORS_NOT_ENABLED}
heading={(publicUrl) => <Heading publicUrl={publicUrl} />}
/>
) : (
<>
<Heading publicUrl={null} />
- <Alert severity="info">{ONLY_THE_OPERATOR}</Alert>
+ <Alert severity="info">{CONNECTORS_NOT_ENABLED}</Alert>
</>
)}
</Box>
diff --git a/gateway/src/pages/connector-apps/connectorApps.test.ts b/gateway/src/pages/connector-apps/connectorApps.test.ts
index 190aa4629..7809fc839 100644
--- a/gateway/src/pages/connector-apps/connectorApps.test.ts
+++ b/gateway/src/pages/connector-apps/connectorApps.test.ts
@@ -56,7 +56,7 @@ describe("card state", () => {
expect(["ready", "not_set_up", "configured", "attention"].map((s) => stateLabel(s as never))).toEqual([
"Ready",
"Not set up",
- "Set on the server",
+ "Set in configuration",
"Needs attention",
]);
});
@@ -349,7 +349,7 @@ describe("Airtable, and an app that sends people back to Switch Console", () =>
it("names Airtable's Helm value when moving off configuration", () => {
const steps = moveChecklist(app({ ...AIRTABLE, source: "configuration" }));
expect(steps[1]!.text).toBe(
- "Remove AIRTABLE_CLIENT_CONFIG_PATH from the server's configuration. For Helm, that is switchCore.airtableClientSecret.",
+ "Remove AIRTABLE_CLIENT_CONFIG_PATH from Switch's configuration. For Helm, that is switchCore.airtableClientSecret.",
);
});
@@ -365,7 +365,7 @@ describe("moving off configuration", () => {
const before = moveChecklist(CONFIGURED);
expect(before.map((item) => item.done)).toEqual([false, false, false]);
expect(before[1]!.text).toBe(
- "Remove GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH from the server's configuration. For Helm, that is switchCore.googleWorkspaceClientSecret.",
+ "Remove GOOGLE_WORKSPACE_CLIENT_CONFIG_PATH from Switch's configuration. For Helm, that is switchCore.googleWorkspaceClientSecret.",
);
const after = moveChecklist(app({ source: "configuration", saved_ignored: true }));
expect(after.map((item) => item.done)).toEqual([true, false, false]);
@@ -377,7 +377,7 @@ describe("an organization's apps", () => {
it("says whether its workspaces fall back to the server's app", () => {
expect(notSetUpSentence(app({ ...none, server_app: true }))).toBe(
- "Your workspaces use the server's Google client. Add your organization's own to use that instead.",
+ "Your workspaces use Switch's Google client. Add your organization's own to use that instead.",
);
expect(notSetUpSentence(app({ ...none, server_app: false }))).toBe(
"People in your organization can't connect Google Workspace until you add your organization's Google client.",
@@ -386,7 +386,7 @@ describe("an organization's apps", () => {
it("warns that removing one sends its workspaces back to the server's", () => {
expect(removeWarning(app({ server_app: true, connected_members: 1 }))).toBe(
- "Your workspaces go back to the server's Google Workspace app. The 1 person connected now must reconnect.",
+ "Your workspaces go back to Switch's Google Workspace app. The 1 person connected now must reconnect.",
);
expect(removeWarning(app({ server_app: false, connected_members: 0 }))).toBe(
"Nobody will be able to connect Google Workspace.",
diff --git a/gateway/src/pages/connector-apps/connectorApps.ts b/gateway/src/pages/connector-apps/connectorApps.ts
index c234a070f..291393a97 100644
--- a/gateway/src/pages/connector-apps/connectorApps.ts
+++ b/gateway/src/pages/connector-apps/connectorApps.ts
@@ -124,7 +124,7 @@ export function stateLabel(state: CardState): string {
case "not_set_up":
return "Not set up";
case "configured":
- return "Set on the server";
+ return "Set in configuration";
case "attention":
return "Needs attention";
}
@@ -153,7 +153,7 @@ export function notSetUpSentence(app: ConnectorApp): string {
const what = app.kind === "github_app" ? "GitHub App" : `${vendorName(app)} client`;
// An organization's page: its workspaces may use the server's app meanwhile.
if (app.server_app === true)
- return `Your workspaces use the server's ${what}. Add your organization's own to use that instead.`;
+ return `Your workspaces use Switch's ${what}. Add your organization's own to use that instead.`;
if (app.server_app === false)
return `People in your organization can't connect ${app.name} until you add your organization's ${what}.`;
return app.kind === "github_app"
@@ -316,7 +316,7 @@ export function setupInstructions(
if (app.slug === AIRTABLE)
return [
{
- text: "In Airtable's Builder Hub, under OAuth integrations, register a new OAuth integration. Use an Airtable account your organization owns: whoever owns the integration can delete it, and that stops every connection.",
+ text: "In Airtable's Builder Hub, under OAuth integrations, register a new OAuth integration. Use an Airtable account your organization owns: whoever owns the integration can delete it, and that disconnects everyone.",
copy: [],
link: { label: "Open Builder Hub", href: "https://airtable.com/create/oauth" },
items: [],
@@ -415,7 +415,7 @@ export function switchWarning(app: ConnectorApp, impact: ConnectorAppImpact): st
export function removeWarning(app: ConnectorApp): string {
const name = app.name;
if (app.server_app === true) {
- const back = `Your workspaces go back to the server's ${name} app.`;
+ const back = `Your workspaces go back to Switch's ${name} app.`;
if (app.connected_members === 0) return back;
const people =
app.connected_members === 1 ? "The 1 person" : `The ${app.connected_members} people`;
@@ -459,7 +459,7 @@ export function moveChecklist(app: ConnectorApp): ChecklistItem[] {
return [
{ text: "Copy into Switch. Nothing is retyped.", done: waitingForRestart(app) },
{
- text: `Remove ${variables(app)} from the server's configuration.${helm ? ` For Helm, that is ${helm}.` : ""}`,
+ text: `Remove ${variables(app)} from Switch's configuration.${helm ? ` For Helm, that is ${helm}.` : ""}`,
done: false,
},
{ text: "Restart Switch.", done: false },
@@ -480,6 +480,3 @@ export function changeBlocked(app: ConnectorApp, publicUrl: string | null): bool
export const PUBLIC_URL_BANNER =
"Set GATEWAY_PUBLIC_URL first: Google and GitHub need to know where to send people back to Switch.";
-
-export const ONLY_THE_OPERATOR =
- "Only the person who runs this Switch server can set up connectors.";
diff --git a/gateway/src/pages/machines/AddMachineDialog.tsx b/gateway/src/pages/machines/AddMachineDialog.tsx
index 433a4c252..7ef439d76 100644
--- a/gateway/src/pages/machines/AddMachineDialog.tsx
+++ b/gateway/src/pages/machines/AddMachineDialog.tsx
@@ -100,11 +100,11 @@ export default function AddMachineDialog({
return (
<Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
- <DialogTitle>Add a machine</DialogTitle>
+ <DialogTitle>Add a device</DialogTitle>
<DialogContent>
<DialogContentText sx={{ mb: 2 }}>
- Run the agent controller on the machine that should run your agents (a laptop, your
- own VM or a server). Enroll it once with the code below; it then runs whatever agents
+ Run the agent controller on the device that should run your agents (a laptop, a
+ desktop or your own VM). Enroll it once with the code below; it then runs whatever agents
you place on it here. It needs Linux or macOS with Node 22.13 or later, and the CLI of
each provider your agents use (such as <code>claude</code> or <code>codex</code>),
signed in as the user the controller runs as.
@@ -119,7 +119,7 @@ export default function AddMachineDialog({
value={name}
onChange={(e) => setName(e.target.value)}
error={nameError !== null}
- helperText={nameError ?? "Defaults to the machine's host name."}
+ helperText={nameError ?? "Defaults to the device's host name."}
size="small"
fullWidth
/>
@@ -128,7 +128,7 @@ export default function AddMachineDialog({
value={description}
onChange={(e) => setDescription(e.target.value)}
error={descriptionError !== null}
- helperText={descriptionError ?? "What the machine is for, e.g. the build box in the office."}
+ helperText={descriptionError ?? "What the device is for, e.g. the build box in the office."}
size="small"
fullWidth
/>
@@ -147,9 +147,9 @@ export default function AddMachineDialog({
label="Copy install command"
/>
<Typography variant="caption" color="text.secondary">
- Installs the newest controller with npm, enrolls this machine, and runs the
+ Installs the newest controller with npm, enrolls this device, and runs the
controller as a service of your user. <code>--server</code> is this Switch's
- API address. If the machine reaches Switch at a different address, change it
+ API address. If the device reaches Switch at a different address, change it
to that one.
</Typography>
</Box>
@@ -168,8 +168,8 @@ export default function AddMachineDialog({
</Stack>
) : (
<Alert severity="warning">
- This server does not say where its Switch API is, so no enrollment command
- can be shown. Set <code>GATEWAY_PUBLIC_URL</code> on the Switch server to its
+ Switch does not say where its API is, so no enrollment command can be
+ shown. Set <code>GATEWAY_PUBLIC_URL</code> in Switch&apos;s configuration to its
API address, or enroll with{" "}
<code>switch-agent-controller enroll --server &lt;Switch API URL&gt; --code</code>{" "}
and the code below. This page's address is not it.
@@ -183,7 +183,7 @@ export default function AddMachineDialog({
<CopyBlock text={enrollment.code} label="Copy code" />
</Box>
<Alert severity="info">
- Single use, valid until {formatDate(enrollment.expires_at)}. The machine appears in
+ Single use, valid until {formatDate(enrollment.expires_at)}. The device appears in
the list once its controller reports. If it does not, run{" "}
<code>switch-agent-controller doctor</code> on it to see what is missing.
</Alert>
diff --git a/gateway/src/pages/machines/EditMachineDialog.tsx b/gateway/src/pages/machines/EditMachineDialog.tsx
index a47cb9234..3833f2e4b 100644
--- a/gateway/src/pages/machines/EditMachineDialog.tsx
+++ b/gateway/src/pages/machines/EditMachineDialog.tsx
@@ -46,7 +46,7 @@ export default function EditMachineDialog({
const trimmedDescription = description.trim();
const nameError =
trimmedName.length === 0
- ? "A machine needs a name."
+ ? "A device needs a name."
: trimmedName.length > MAX_MACHINE_NAME
? `At most ${MAX_MACHINE_NAME} characters.`
: null;
@@ -100,7 +100,7 @@ export default function EditMachineDialog({
error={descriptionError !== null}
helperText={
descriptionError ??
- "What the machine is for. Agents you allow to manage agents see it when they pick a machine."
+ "What the device is for. Agents you allow to manage agents see it when they pick a device."
}
multiline
minRows={2}
diff --git a/gateway/src/pages/machines/MachinesPage.test.tsx b/gateway/src/pages/machines/MachinesPage.test.tsx
index 523a5c55c..22e4b92a6 100644
--- a/gateway/src/pages/machines/MachinesPage.test.tsx
+++ b/gateway/src/pages/machines/MachinesPage.test.tsx
@@ -21,6 +21,8 @@ const laptop: Controller = {
created_at: "2026-10-01T00:00:00Z",
revoked_at: null,
release: null,
+ can_edit: true,
+ can_remove: true,
status: {
seq: 1,
observed_at: new Date().toISOString(),
@@ -94,6 +96,8 @@ const pmAgent: ManagedAgent = {
status: laptop.status!.agents[0],
created_at: "2026-10-01T00:00:00Z",
updated_at: "2026-10-01T00:00:00Z",
+ can_edit: true,
+ can_delete: true,
};
const servedProviders: ProviderInfo[] = [
@@ -139,6 +143,49 @@ describe("MachinesPage", () => {
expect(screen.getByText("failed: invalid_credential")).toBeTruthy();
});
+ it("offers each action on a device only where the server says it may be taken", async () => {
+ mockManagement({
+ "GET /controllers": [
+ 200,
+ [
+ laptop,
+ { ...laptop, id: "c2", name: "theirs", can_edit: false, can_remove: false },
+ ],
+ ],
+ "GET /agents": [
+ 200,
+ [pmAgent, { ...pmAgent, agent_id: "a2", name: "their-agent", can_edit: false, can_delete: false }],
+ ],
+ "GET /operations": [200, []],
+ });
+ render(<MachinesPage />);
+ expect(await screen.findByRole("button", { name: "Edit device laptop" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Revoke laptop" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Edit device theirs" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Revoke theirs" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Re-check providers on theirs" })).toBeNull();
+
+ expect(screen.getByRole("button", { name: "Edit pm-agent" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Stop managing pm-agent" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Edit their-agent" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Stop their-agent" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Stop managing their-agent" })).toBeNull();
+ });
+
+ it("says why an agent on no machine cannot be started", async () => {
+ mockManagement({
+ "GET /controllers": [200, []],
+ "GET /agents": [200, [{ ...pmAgent, controller_id: null, controller_state: null }]],
+ "GET /operations": [200, []],
+ });
+ render(<MachinesPage />);
+ const start = await screen.findByRole("button", { name: "Stop pm-agent" });
+ expect((start as HTMLButtonElement).disabled).toBe(true);
+ expect(
+ screen.getByLabelText("Not on a device: move it to one to start or stop it"),
+ ).toBeTruthy();
+ });
+
it("shows the controller's version against the release Switch names", async () => {
const wanted = { wanted: "0.31.0", running: "0.1.0", current: false };
const machines: Controller[] = [
@@ -186,7 +233,7 @@ describe("MachinesPage", () => {
});
render(<MachinesPage />);
expect(await screen.findByText("None (revoked)")).toBeTruthy();
- expect(screen.getByText("not running: machine revoked")).toBeTruthy();
+ expect(screen.getByText("not running: device revoked")).toBeTruthy();
expect(screen.queryByText("1 / 1")).toBeNull();
// Only what is wanted says running; nothing claims the agent actually is.
expect(screen.getAllByText("running")).toHaveLength(1);
@@ -210,7 +257,7 @@ describe("MachinesPage", () => {
render(<MachinesPage />);
expect(await screen.findByText("offline")).toBeTruthy();
expect(screen.getByText("Not connected")).toBeTruthy();
- expect(screen.getByText("machine offline")).toBeTruthy();
+ expect(screen.getByText("device offline")).toBeTruthy();
expect(screen.queryByText("failed: invalid_credential")).toBeNull();
});
@@ -238,14 +285,6 @@ describe("MachinesPage", () => {
expect(text).toMatch(/stay placed, and offline, until you move them/);
});
- it("says when agent management is off instead of showing an empty page", async () => {
- mockManagement({});
- render(<MachinesPage />);
- expect(
- await screen.findByText(/Agent management is not enabled on this server/),
- ).toBeTruthy();
- });
-
it("stops a running agent by changing what is wanted", async () => {
const calls = mockManagement({
"GET /controllers": [200, [laptop]],
@@ -275,7 +314,7 @@ describe("MachinesPage", () => {
],
});
render(<MachinesPage />);
- fireEvent.click(await screen.findByLabelText("Edit machine laptop"));
+ fireEvent.click(await screen.findByLabelText("Edit device laptop"));
const name = await screen.findByLabelText(/^Name/);
fireEvent.change(name, { target: { value: " build-box " } });
fireEvent.change(screen.getByLabelText("Description"), {
@@ -300,9 +339,9 @@ describe("MachinesPage", () => {
});
render(<MachinesPage />);
expect(await screen.findByText("Old note")).toBeTruthy();
- fireEvent.click(await screen.findByLabelText("Edit machine laptop"));
+ fireEvent.click(await screen.findByLabelText("Edit device laptop"));
fireEvent.change(await screen.findByLabelText(/^Name/), { target: { value: " " } });
- expect(screen.getByText("A machine needs a name.")).toBeTruthy();
+ expect(screen.getByText("A device needs a name.")).toBeTruthy();
expect((screen.getByRole("button", { name: "Save" }) as HTMLButtonElement).disabled).toBe(
true,
);
@@ -418,7 +457,7 @@ describe("MachinesPage", () => {
"GET /operations": [200, []],
});
render(<MachinesPage />);
- expect(await screen.findByText(/Could not load the providers this server runs/)).toBeTruthy();
+ expect(await screen.findByText(/Could not load the list of providers/)).toBeTruthy();
expect(await screen.findByText("codex: login expired")).toBeTruthy();
});
});
diff --git a/gateway/src/pages/machines/MachinesPage.tsx b/gateway/src/pages/machines/MachinesPage.tsx
index 654e8af65..38b31fcd6 100644
--- a/gateway/src/pages/machines/MachinesPage.tsx
+++ b/gateway/src/pages/machines/MachinesPage.tsx
@@ -33,7 +33,6 @@ import {
fetchManagedAgents,
fetchOperations,
type ManagedAgent,
- ManagementApiError,
type Operation,
fetchProviders,
type ProviderInfo,
@@ -60,8 +59,8 @@ const STATE_COLOR: Record<ControllerState, "success" | "warning" | "default"> =
const DISCONNECT_REASON: Record<string, string> = {
socket_closed: "its controller stopped or lost its connection",
heartbeat_lapsed: "its connection stopped responding",
- server_shutdown: "the Switch server it was connected to restarted",
- server_lost: "the Switch server it was connected to stopped responding",
+ server_shutdown: "Switch restarted",
+ server_lost: "Switch stopped responding",
taken_over: "another instance of its controller took over",
revoked: "it was removed",
};
@@ -146,7 +145,7 @@ function controllerVersion(row: Controller) {
? `Runs ${release.wanted}, the release Switch names.`
: row.kind === "console" || row.status?.controller.updated_by === "console"
? "Updates with Switch Console, which runs it."
- : "Switch names no controller release for this machine."
+ : "Switch names no controller release for this device."
}
>
<span>{running ?? EM_DASH}</span>
@@ -161,7 +160,7 @@ function controllerVersion(row: Controller) {
color: "warning",
why:
row.state === "online"
- ? "It has said nothing about moving to it: a controller older than self-update never does. Reinstall it once on the machine, or, if Switch Console runs it on an SSH host, update Console."
+ ? "It has said nothing about moving to it: a controller older than self-update never does. Reinstall it once on the device, or, if Switch Console runs it on an SSH host, update Console."
: "It moves to it once it is connected again.",
};
else if (update.state === "waiting_idle")
@@ -223,11 +222,7 @@ export default function MachinesPage() {
setOperations(o);
setLoadError(null);
} catch (err) {
- setLoadError(
- err instanceof ManagementApiError && err.status === 404 && err.code === "http_error"
- ? "Agent management is not enabled on this server. An operator turns it on by adding agent_management to FEATURE_FLAGS_ENABLED."
- : `Could not load machines and managed agents: ${errorMessage(err)}`,
- );
+ setLoadError(`Could not load devices and managed agents: ${errorMessage(err)}`);
}
}, []);
@@ -240,7 +235,7 @@ export default function MachinesPage() {
useEffect(() => {
fetchProviders().then(setProviders, (err) =>
setProvidersError(
- `Could not load the providers this server runs, so providers show by id: ${errorMessage(err)}`,
+ `Could not load the list of providers, so providers show by id: ${errorMessage(err)}`,
),
);
}, []);
@@ -276,7 +271,7 @@ export default function MachinesPage() {
() => [
{
field: "name",
- headerName: "Machine",
+ headerName: "Device",
flex: 1,
minWidth: 160,
renderCell: ({ row }) =>
@@ -385,54 +380,60 @@ export default function MachinesPage() {
const live = row.state !== "revoked";
return (
<>
- <Tooltip title="Re-check providers">
- <span>
- <IconButton
- size="small"
- aria-label={`Re-check providers on ${row.name}`}
- disabled={!live || providers.length === 0 || busy}
- onClick={() =>
- act(
- `Asked ${row.name} to re-check ${providers.length} provider(s)`,
- () =>
- Promise.all(
- providers.map((p) =>
- createOperation({
- controller_id: row.id,
- agent_id: null,
- kind: "provider.recheck",
- params: { provider: p.provider },
- }),
- ),
- ),
- )
- }
- >
- <RefreshOutlined fontSize="small" />
- </IconButton>
- </span>
- </Tooltip>
- <Tooltip title="Rename or describe">
- <IconButton
- size="small"
- aria-label={`Edit machine ${row.name}`}
- onClick={() => setMachineTarget(row)}
- >
- <EditOutlined fontSize="small" />
- </IconButton>
- </Tooltip>
- <Tooltip title="Revoke">
- <span>
- <IconButton
- size="small"
- aria-label={`Revoke ${row.name}`}
- disabled={!live || busy}
- onClick={() => setRevokeTarget(row)}
- >
- <DeleteOutline fontSize="small" />
- </IconButton>
- </span>
- </Tooltip>
+ {row.can_edit && (
+ <>
+ <Tooltip title="Re-check providers">
+ <span>
+ <IconButton
+ size="small"
+ aria-label={`Re-check providers on ${row.name}`}
+ disabled={!live || providers.length === 0 || busy}
+ onClick={() =>
+ act(
+ `Asked ${row.name} to re-check ${providers.length} provider(s)`,
+ () =>
+ Promise.all(
+ providers.map((p) =>
+ createOperation({
+ controller_id: row.id,
+ agent_id: null,
+ kind: "provider.recheck",
+ params: { provider: p.provider },
+ }),
+ ),
+ ),
+ )
+ }
+ >
+ <RefreshOutlined fontSize="small" />
+ </IconButton>
+ </span>
+ </Tooltip>
+ <Tooltip title="Rename or describe">
+ <IconButton
+ size="small"
+ aria-label={`Edit device ${row.name}`}
+ onClick={() => setMachineTarget(row)}
+ >
+ <EditOutlined fontSize="small" />
+ </IconButton>
+ </Tooltip>
+ </>
+ )}
+ {row.can_remove && (
+ <Tooltip title="Revoke">
+ <span>
+ <IconButton
+ size="small"
+ aria-label={`Revoke ${row.name}`}
+ disabled={!live || busy}
+ onClick={() => setRevokeTarget(row)}
+ >
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ </span>
+ </Tooltip>
+ )}
</>
);
},
@@ -452,7 +453,7 @@ export default function MachinesPage() {
},
{
field: "controller_id",
- headerName: "Machine",
+ headerName: "Device",
flex: 1,
minWidth: 140,
valueGetter: (_value, row) => controllerName(row.controller_id) ?? "Not placed",
@@ -481,19 +482,19 @@ export default function MachinesPage() {
return <Typography variant="body2" color="text.secondary">{EM_DASH}</Typography>;
if (row.controller_state === "revoked")
return (
- <Tooltip title="Its machine was revoked, so nothing runs this agent. Move it to another machine to run it again.">
- <Chip size="small" label="not running: machine revoked" />
+ <Tooltip title="Its device was revoked, so nothing runs this agent. Move it to another device to run it again.">
+ <Chip size="small" label="not running: device revoked" />
</Tooltip>
);
if (row.controller_state === "offline")
return (
- <Tooltip title="Its machine is not connected to Switch, so this agent is not reachable. It runs again once the machine's controller is back.">
- <Chip size="small" color="warning" label="machine offline" />
+ <Tooltip title="Its device is not connected to Switch, so this agent is not reachable. It runs again once the device's controller is back.">
+ <Chip size="small" color="warning" label="device offline" />
</Tooltip>
);
if (row.controller_state === "unknown")
return (
- <Tooltip title="Its machine has never connected to Switch; this agent's state is not known.">
+ <Tooltip title="Its device has never connected to Switch; this agent's state is not known.">
<Chip size="small" label="unknown" />
</Tooltip>
);
@@ -515,7 +516,7 @@ export default function MachinesPage() {
/>
</Tooltip>
{stale && (
- <Tooltip title={`Machine is on revision ${row.status.applied_revision ?? "none"}, latest is ${row.revision}`}>
+ <Tooltip title={`Device is on revision ${row.status.applied_revision ?? "none"}, latest is ${row.revision}`}>
<Chip size="small" variant="outlined" label="updating" />
</Tooltip>
)}
@@ -533,70 +534,90 @@ export default function MachinesPage() {
const running = row.desired_state === "running";
return (
<>
- <Tooltip title={running ? "Stop" : "Start"}>
- <span>
- <IconButton
- size="small"
- aria-label={`${running ? "Stop" : "Start"} ${row.name}`}
- disabled={busy || row.controller_id === null}
- onClick={() =>
- act(`${running ? "Stopping" : "Starting"} ${row.name}`, () =>
- updateManagedAgent(row.agent_id, {
- desired_state: running ? "stopped" : "running",
- }),
- )
+ {row.can_edit && (
+ <>
+ <Tooltip
+ title={
+ row.controller_id === null
+ ? "Not on a device: move it to one to start or stop it"
+ : running
+ ? "Stop"
+ : "Start"
}
>
- {running ? (
- <PauseCircleOutline fontSize="small" />
- ) : (
- <PlayCircleOutline fontSize="small" />
- )}
- </IconButton>
- </span>
- </Tooltip>
- <Tooltip title="Restart">
- <span>
- <IconButton
- size="small"
- aria-label={`Restart ${row.name}`}
- disabled={busy || row.controller_id === null || !running}
- onClick={() =>
- act(`Asked to restart ${row.name}`, () =>
- createOperation({
- controller_id: row.controller_id as string,
- agent_id: row.agent_id,
- kind: "agent.restart",
- params: {},
- }),
- )
+ <span>
+ <IconButton
+ size="small"
+ aria-label={`${running ? "Stop" : "Start"} ${row.name}`}
+ disabled={busy || row.controller_id === null}
+ onClick={() =>
+ act(`${running ? "Stopping" : "Starting"} ${row.name}`, () =>
+ updateManagedAgent(row.agent_id, {
+ desired_state: running ? "stopped" : "running",
+ }),
+ )
+ }
+ >
+ {running ? (
+ <PauseCircleOutline fontSize="small" />
+ ) : (
+ <PlayCircleOutline fontSize="small" />
+ )}
+ </IconButton>
+ </span>
+ </Tooltip>
+ <Tooltip
+ title={
+ row.controller_id === null
+ ? "Not on a device: move it to one to restart it"
+ : "Restart"
}
>
- <RestartAltOutlined fontSize="small" />
- </IconButton>
- </span>
- </Tooltip>
- <Tooltip title="Edit">
- <IconButton
- size="small"
- aria-label={`Edit ${row.name}`}
- onClick={() => setEditing(row)}
- >
- <EditOutlined fontSize="small" />
- </IconButton>
- </Tooltip>
- <Tooltip title="Stop managing">
- <span>
- <IconButton
- size="small"
- aria-label={`Stop managing ${row.name}`}
- disabled={busy}
- onClick={() => setUnmanageTarget(row)}
- >
- <DeleteOutline fontSize="small" />
- </IconButton>
- </span>
- </Tooltip>
+ <span>
+ <IconButton
+ size="small"
+ aria-label={`Restart ${row.name}`}
+ disabled={busy || row.controller_id === null || !running}
+ onClick={() =>
+ act(`Asked to restart ${row.name}`, () =>
+ createOperation({
+ controller_id: row.controller_id as string,
+ agent_id: row.agent_id,
+ kind: "agent.restart",
+ params: {},
+ }),
+ )
+ }
+ >
+ <RestartAltOutlined fontSize="small" />
+ </IconButton>
+ </span>
+ </Tooltip>
+ <Tooltip title="Edit">
+ <IconButton
+ size="small"
+ aria-label={`Edit ${row.name}`}
+ onClick={() => setEditing(row)}
+ >
+ <EditOutlined fontSize="small" />
+ </IconButton>
+ </Tooltip>
+ </>
+ )}
+ {row.can_delete && (
+ <Tooltip title="Stop managing">
+ <span>
+ <IconButton
+ size="small"
+ aria-label={`Stop managing ${row.name}`}
+ disabled={busy}
+ onClick={() => setUnmanageTarget(row)}
+ >
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ </span>
+ </Tooltip>
+ )}
</>
);
},
@@ -666,7 +687,7 @@ export default function MachinesPage() {
<Box>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={1}>
<Box>
- <Typography variant="h5">Machines</Typography>
+ <Typography variant="h5">Devices</Typography>
<Typography variant="body2" color="text.secondary">
Computers running an agent controller. Each one runs the agents you place on it
and reports what it sees.
@@ -677,7 +698,7 @@ export default function MachinesPage() {
startIcon={<AddCircleOutline />}
onClick={() => setAddOpen(true)}
>
- Add machine
+ Add device
</Button>
</Stack>
<DataTable rows={controllers ?? []} columns={machineColumns} height={320} pageSize={10} />
@@ -688,8 +709,8 @@ export default function MachinesPage() {
<Box>
<Typography variant="h6">Managed agents</Typography>
<Typography variant="body2" color="text.secondary">
- Agents defined here and run by a machine. "Wanted" is what you asked for;
- "Actual" is what the machine last reported.
+ Agents defined here and run by a device. "Wanted" is what you asked for;
+ "Actual" is what the device last reported.
</Typography>
</Box>
<Button
@@ -739,9 +760,9 @@ export default function MachinesPage() {
<DialogTitle>Revoke {revokeTarget?.name}?</DialogTitle>
<DialogContent>
<DialogContentText>
- The machine's controller loses access to Switch immediately, and if it is online
+ The device's controller loses access to Switch immediately, and if it is online
it stops every agent it runs. Agents placed on it stay placed, and offline, until
- you move them to another machine or stop managing them. Enrolling the machine again
+ you move them to another device or stop managing them. Enrolling the device again
needs a new code.
</DialogContentText>
</DialogContent>
@@ -766,7 +787,7 @@ export default function MachinesPage() {
<DialogTitle>Stop managing {unmanageTarget?.name}?</DialogTitle>
<DialogContent>
<DialogContentText>
- Its machine stops running it the next time it hears from Switch. The agent itself is
+ Its device stops running it the next time it hears from Switch. The agent itself is
not deleted: it stays registered, with its rooms, and can be managed again later.
</DialogContentText>
</DialogContent>
diff --git a/gateway/src/pages/machines/ManagedAgentDialog.tsx b/gateway/src/pages/machines/ManagedAgentDialog.tsx
index 1efb85922..b7bb31239 100644
--- a/gateway/src/pages/machines/ManagedAgentDialog.tsx
+++ b/gateway/src/pages/machines/ManagedAgentDialog.tsx
@@ -202,12 +202,12 @@ export default function ManagedAgentDialog({
)}
<TextField
select
- label="Machine"
+ label="Device"
value={form.controllerId}
onChange={(e) => set("controllerId", e.target.value)}
helperText={
placeable.length === 0
- ? "No machine yet: add one first, or save the agent unplaced."
+ ? "No device yet: add one first, or save the agent unplaced."
: "Where the agent runs."
}
>
@@ -225,7 +225,7 @@ export default function ManagedAgentDialog({
label="Provider"
value={form.provider}
onChange={(e) => set("provider", e.target.value as Provider)}
- helperText={providers.length === 0 ? "Loading the providers this server runs…" : undefined}
+ helperText={providers.length === 0 ? "Loading providers…" : undefined}
>
{providerChoices.map((p) => (
<MenuItem key={p.id} value={p.id}>
@@ -250,16 +250,16 @@ export default function ManagedAgentDialog({
label="Working directory"
value={form.directory}
onChange={(e) => set("directory", e.target.value)}
- helperText="An absolute path that exists on the machine. Empty uses a workspace the controller creates."
+ helperText="An absolute path that exists on the device. Empty uses a workspace the controller creates."
/>
<TextField
select
label="Isolation"
value={form.isolation}
onChange={(e) => set("isolation", e.target.value as Isolation)}
- helperText="Cloud machines run every agent isolated."
+ helperText="Cloud devices run every agent isolated."
>
- <MenuItem value="shared">Shared: runs inside the machine's controller</MenuItem>
+ <MenuItem value="shared">Shared: runs inside the device's controller</MenuItem>
<MenuItem value="isolated">Isolated: runs as a process of its own</MenuItem>
</TextField>
<FormControlLabel
diff --git a/gateway/src/pages/organization/OrganizationAuditSection.tsx b/gateway/src/pages/organization/OrganizationAuditSection.tsx
index e5041c6fe..98e9aca2d 100644
--- a/gateway/src/pages/organization/OrganizationAuditSection.tsx
+++ b/gateway/src/pages/organization/OrganizationAuditSection.tsx
@@ -13,15 +13,15 @@ const ACTION_LABELS: Record<string, string> = {
"organization.created": "Organization created",
"organization.workspace_created": "Workspace added",
"organization.role_changed": "Organization role changed",
- "organization.member_removed": "Member removed",
+ "organization.member_removed": "User removed",
"organization.connector_app_saved": "Connector app saved",
"organization.connector_app_removed": "Connector app removed",
"organization.service_set": "Service switched",
"organization.service_cleared": "Service left to workspaces",
- "organization.member_added_from_directory": "Member added from WorkOS",
- "organization.member_promoted_from_directory": "Member made Org Admin from WorkOS",
- "organization.member_demoted_from_directory": "Org Admin made Member from WorkOS",
- "organization.member_removed_from_directory": "Member removed from WorkOS",
+ "organization.member_added_from_directory": "User added from WorkOS",
+ "organization.member_promoted_from_directory": "Promoted to org admin from WorkOS",
+ "organization.member_demoted_from_directory": "Demoted to member from WorkOS",
+ "organization.member_removed_from_directory": "User removed from WorkOS",
"organization.directory_conflict": "WorkOS change broke a Switch rule",
"organization.linked_to_directory": "Linked to WorkOS",
};
diff --git a/gateway/src/pages/organization/OrganizationConnectorsSection.tsx b/gateway/src/pages/organization/OrganizationConnectorsSection.tsx
index 3597aa93f..7fb59ecd0 100644
--- a/gateway/src/pages/organization/OrganizationConnectorsSection.tsx
+++ b/gateway/src/pages/organization/OrganizationConnectorsSection.tsx
@@ -8,24 +8,20 @@ function Heading({ publicUrl }: { publicUrl: string | null }) {
<Typography variant="h6">Connectors</Typography>
<Typography variant="body2" color="text.secondary">
Your organization can register its own app at a vendor, and every workspace in it signs
- in through that one instead of the server&apos;s.
+ in through that one instead of Switch&apos;s.
{publicUrl !== null && ` ${sentBackTo(publicUrl)}`}
</Typography>
</Box>
);
}
-/** What an org admin reads if the routes are missing all the same. */
-const ORGANIZATION_APPS_NOT_ENABLED =
- "Organizations' own connector apps are not enabled on this server.";
-
/** The apps the organization's workspaces sign in through, for its admins.
- * The page shows it only where the server lets organizations save their own. */
+ * Shown only where the server lets organizations save their own
+ * (`organization_connector_apps`). */
export default function OrganizationConnectorsSection() {
return (
<ConnectorAppsList
scope="organization"
- notEnabled={ORGANIZATION_APPS_NOT_ENABLED}
heading={(publicUrl) => <Heading publicUrl={publicUrl} />}
/>
);
diff --git a/gateway/src/pages/organization/OrganizationIssuesNotice.tsx b/gateway/src/pages/organization/OrganizationIssuesNotice.tsx
index 36c8458e1..1e230cf03 100644
--- a/gateway/src/pages/organization/OrganizationIssuesNotice.tsx
+++ b/gateway/src/pages/organization/OrganizationIssuesNotice.tsx
@@ -7,9 +7,9 @@ function describe(issue: OrganizationIssue): string {
const workspace = issue.workspace_name ?? "";
switch (issue.kind) {
case "no_org_admin":
- return "Nobody is an admin of this organization. Make one of its members an organization admin below.";
+ return "Nobody is an admin of this organization. Make one of its users an organization admin below.";
case "workspace_without_admin":
- return `${workspace} has no admin. Make one of its members an admin in that workspace's members.`;
+ return `${workspace} has no admin. Make one of its users an admin in that workspace's settings.`;
case "agents_without_acting_owner":
return (
`In ${workspace}, these agents are owned by someone who is no longer in the ` +
@@ -18,8 +18,8 @@ function describe(issue: OrganizationIssue): string {
);
case "directory_organization_deleted":
return (
- "The WorkOS organization this organization follows was deleted. Its members are " +
- "left as they were; ask whoever runs your Switch server to link it again or remove it."
+ "The WorkOS organization this organization follows was deleted. Its users are " +
+ "left as they were; ask whoever runs Switch to link it again or remove it."
);
}
}
diff --git a/gateway/src/pages/organization/OrganizationMembersSection.tsx b/gateway/src/pages/organization/OrganizationMembersSection.tsx
index 8b7f7e34b..5e4a7f3de 100644
--- a/gateway/src/pages/organization/OrganizationMembersSection.tsx
+++ b/gateway/src/pages/organization/OrganizationMembersSection.tsx
@@ -31,7 +31,7 @@ import { useLoad } from "../workspace/useLoad";
type MemberRow = OrganizationMember & { id: string };
const ROLE_LABELS: Record<OrganizationRole, string> = {
- org_admin: "Org Admin",
+ org_admin: "Org admin",
member: "Member",
};
@@ -252,14 +252,14 @@ export default function OrganizationMembersSection({
return (
<Stack spacing={1.5}>
- <Typography variant="h6">Members</Typography>
+ <Typography variant="h6">Users</Typography>
<Typography variant="body2" sx={{ color: "text.secondary" }}>
Organization admins administer every workspace in the organization. Someone is removed
from each workspace before they can be removed from the organization.
</Typography>
{asOperator && errorStatus === 403 ? (
<Alert severity="info">
- As platform operator you can manage this organization's members only while it has no
+ As platform operator you can manage this organization's users only while it has no
admin, to make someone one.
</Alert>
) : (
@@ -271,12 +271,12 @@ export default function OrganizationMembersSection({
? "This organization has no admin. Its admins come from its account settings, so " +
"someone has to be made an organization admin there."
: "This organization has no admin. As platform operator you can make one of its " +
- "members an admin; the change is recorded in its audit log, marked as yours."}
+ "users an admin; the change is recorded in its audit log, marked as yours."}
</Alert>
)}
{fromDirectory && directoryTakesChanges && !asOperator && (
<Alert severity="info">
- This organization's members, and who is its admin, come from your organization's
+ This organization's users, and who is its admin, come from your organization's
account settings. Changes you make here are made there too; you may be asked to
confirm your sign-in there first. New people can't be added from here yet: add them
there.
@@ -284,7 +284,7 @@ export default function OrganizationMembersSection({
)}
{fromDirectory && !directoryTakesChanges && !asOperator && (
<Alert severity="info">
- This organization's members, and who is its admin, come from your organization's
+ This organization's users, and who is its admin, come from your organization's
account settings. Add people and make someone an organization admin there; the change
shows here shortly. Removing someone here, or making an admin a member, takes effect at
once but lasts only while the account settings agree: they are read again at the
diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsx
index df3c12e2a..d31573f60 100644
--- a/gateway/src/pages/organization/OrganizationPage.test.tsx
+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx
@@ -2,6 +2,8 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-li
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Session } from "../../data/api";
import { useAuth } from "../../data/AuthContext";
+import { capabilitiesOf } from "../../data/capabilities";
+import { ALL_OFF, type FeatureFlags } from "../../data/featureFlags";
import { app } from "../connector-apps/testFixtures";
import OrganizationPage from "./OrganizationPage";
@@ -42,7 +44,14 @@ function answer(routes: Record<string, unknown>) {
if (!(key in routes)) {
return new Response(JSON.stringify({ detail: `unmocked ${key}` }), { status: 404 });
}
- const answered = routes[key];
+ let answered = routes[key];
+ // The organization's own answers, as the server gives them to someone
+ // holding that role, unless the test says otherwise.
+ if (key === "GET /organizations/current" && !(answered instanceof Refusal)) {
+ const organization = answered as Record<string, unknown>;
+ const admin = organization.role === "org_admin";
+ answered = { administers: admin, can_manage_members: admin, ...organization };
+ }
if (answered instanceof Refusal) {
return new Response(JSON.stringify({ detail: answered.detail }), {
status: answered.status,
@@ -61,24 +70,36 @@ class Refusal {
) {}
}
-function signedInAs(current: Session) {
+const CONNECTORS_ON: FeatureFlags = {
+ ...ALL_OFF,
+ service_connections: true,
+ organization_connector_apps: true,
+};
+
+function signedInAs(current: Session, features: FeatureFlags = CONNECTORS_ON) {
const refresh = vi.fn();
+ const administers = current.tenant?.role === "admin" || current.user.is_operator;
vi.mocked(useAuth).mockReturnValue({
session: current,
+ capabilities: capabilitiesOf(
+ current,
+ {
+ id: "t1",
+ slug: "acme",
+ name: "Acme",
+ role: current.tenant?.role ?? "member",
+ administers,
+ can_delete: false,
+ can_manage_data_protection: false,
+ },
+ features,
+ ),
switchTo: vi.fn(),
refresh,
} as unknown as ReturnType<typeof useAuth>);
return refresh;
}
-/** `GET /feature-flags`, with organizations' own apps on or off. */
-const flags = (organizationApps: boolean) => ({
- flags: [
- { key: "service_connections", enabled: true },
- { key: "organization_connector_apps", enabled: organizationApps },
- ],
-});
-
const workspace = (id: string, name: string) => ({
id,
slug: id,
@@ -122,7 +143,7 @@ describe("OrganizationPage", () => {
expect(await screen.findByText("Acme Inc")).toBeTruthy();
expect(await screen.findByText("Acme (current)")).toBeTruthy();
- expect(screen.getByRole("heading", { name: "Members" })).toBeTruthy();
+ expect(screen.getByRole("heading", { name: "Users" })).toBeTruthy();
expect(await screen.findByText("Organization role changed")).toBeTruthy();
expect(screen.getByText("Olga (platform operator)")).toBeTruthy();
});
@@ -134,7 +155,6 @@ describe("OrganizationPage", () => {
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
"GET /organizations/current/members": [],
"GET /organizations/current/audit-events": [],
- "GET /feature-flags": flags(true),
"GET /organizations/current/services": { workspaces: 1, services: [] },
"GET /organizations/current/connector-apps": {
public_url: "https://switch.example.test",
@@ -161,7 +181,7 @@ describe("OrganizationPage", () => {
expect(await screen.findByRole("heading", { name: "Connectors" })).toBeTruthy();
expect(
await screen.findByText(
- "Your workspaces use the server's Airtable client. Add your organization's own to use that instead.",
+ "Your workspaces use Switch's Airtable client. Add your organization's own to use that instead.",
),
).toBeTruthy();
const google = screen.getByTestId("connector-app-google-workspace");
@@ -192,7 +212,6 @@ describe("OrganizationPage", () => {
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
"GET /organizations/current/members": [],
"GET /organizations/current/audit-events": [],
- "GET /feature-flags": flags(true),
"GET /organizations/current/connector-apps": { public_url: null, apps: [] },
"GET /organizations/current/services": { workspaces: 3, services: [github] },
"PUT /organizations/current/services/github": { warning: null },
@@ -216,45 +235,27 @@ describe("OrganizationPage", () => {
);
});
- it("neither shows nor asks for services or connectors where the server keeps them to itself", async () => {
- signedInAs(session("org_admin", true));
+ it("shows no connectors where the server keeps them to itself, and asks nothing of it", async () => {
+ signedInAs(session("org_admin", true), { ...ALL_OFF, service_connections: true });
const fetchMock = answer({
"GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin" },
"GET /organizations/current/workspaces": [workspace("t1", "Acme")],
"GET /organizations/current/members": [],
"GET /organizations/current/audit-events": [],
"GET /organizations/current/issues": [],
- "GET /feature-flags": flags(false),
});
render(<OrganizationPage />);
- expect(await screen.findByRole("heading", { name: "Members" })).toBeTruthy();
- await waitFor(() =>
- expect(fetchMock).toHaveBeenCalledWith("/gateway/feature-flags", expect.anything()),
- );
+ expect(await screen.findByRole("heading", { name: "Users" })).toBeTruthy();
await waitFor(() => expect(screen.queryByRole("progressbar")).toBeNull());
expect(screen.queryByRole("heading", { name: "Connectors" })).toBeNull();
expect(screen.queryByRole("heading", { name: "Services" })).toBeNull();
const asked = fetchMock.mock.calls.map(([input]) => String(input));
- expect(asked.filter((url) => /current\/(services|connector-apps)/.test(url))).toEqual([]);
+ expect(asked.filter((url) => /current\/(services|connector-apps)|feature-flags/.test(url))).toEqual([]);
expect(screen.queryByText(/unmocked/)).toBeNull();
});
- it("asks a member nothing about the server's flags", async () => {
- signedInAs(session("member", false));
- const fetchMock = answer({
- "GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "member" },
- "GET /organizations/current/workspaces": [workspace("t1", "Acme")],
- });
-
- render(<OrganizationPage />);
-
- expect(await screen.findByText("Acme (current)")).toBeTruthy();
- const asked = fetchMock.mock.calls.map(([input]) => String(input));
- expect(asked.filter((url) => url.includes("feature-flags"))).toEqual([]);
- });
-
it("shows what a demotion could not revoke at a vendor", async () => {
signedInAs(session("org_admin", true));
const bob = {
@@ -300,7 +301,7 @@ describe("OrganizationPage", () => {
render(<OrganizationPage />);
expect(await screen.findByText("Acme (current)")).toBeTruthy();
- expect(screen.queryByRole("heading", { name: "Members" })).toBeNull();
+ expect(screen.queryByRole("heading", { name: "Users" })).toBeNull();
expect(screen.queryByRole("heading", { name: "Audit log" })).toBeNull();
expect(screen.queryByRole("button", { name: "Add workspace" })).toBeNull();
});
@@ -374,18 +375,20 @@ describe("OrganizationPage", () => {
expect(await screen.findByText(/someone has to be made an organization admin there/)).toBeTruthy();
fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
- const orgAdmin = await screen.findByRole("option", { name: "Org Admin" });
+ const orgAdmin = await screen.findByRole("option", { name: "Org admin" });
expect(orgAdmin.getAttribute("aria-disabled")).toBe("true");
});
it("tells the operator why where the organization has an admin", async () => {
signedInAs(session(null, false, true));
- answer(operatorRoutes(new Refusal(403, "Only an organization admin may do this")));
+ const fetchMock = answer(operatorRoutes(new Refusal(403, "Only an organization admin may do this")));
render(<OrganizationPage />);
expect(await screen.findByText(/only while it has no admin/)).toBeTruthy();
expect(screen.queryByText("Only an organization admin may do this")).toBeNull();
+ const asked = fetchMock.mock.calls.map(([input]) => String(input));
+ expect(asked.filter((path) => path.endsWith("/issues"))).toEqual([]);
});
it("shows the operator a failure as a failure", async () => {
@@ -421,7 +424,7 @@ describe("OrganizationPage", () => {
expect(await screen.findByText(/come from your organization's account settings/)).toBeTruthy();
fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
- const promote = await screen.findByRole("option", { name: "Org Admin" });
+ const promote = await screen.findByRole("option", { name: "Org admin" });
expect(promote.getAttribute("aria-disabled")).toBe("true");
fireEvent.keyDown(promote, { key: "Escape" });
fireEvent.mouseDown(within(screen.getByTestId("row-u3")).getByRole("combobox"));
@@ -486,7 +489,7 @@ describe("OrganizationPage", () => {
expect(await screen.findByText(/Changes you make here are made there too/)).toBeTruthy();
fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
- const promote = await screen.findByRole("option", { name: "Org Admin" });
+ const promote = await screen.findByRole("option", { name: "Org admin" });
expect(promote.getAttribute("aria-disabled")).toBeNull();
});
@@ -497,7 +500,7 @@ describe("OrganizationPage", () => {
render(<OrganizationPage />);
fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
- fireEvent.click(await screen.findByRole("option", { name: "Org Admin" }));
+ fireEvent.click(await screen.findByRole("option", { name: "Org admin" }));
await waitFor(() =>
expect(window.location.href).toBe(
@@ -517,7 +520,7 @@ describe("OrganizationPage", () => {
render(<OrganizationPage />);
fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
- fireEvent.click(await screen.findByRole("option", { name: "Org Admin" }));
+ fireEvent.click(await screen.findByRole("option", { name: "Org admin" }));
await waitFor(() =>
expect(window.location.href).toBe(
@@ -537,7 +540,7 @@ describe("OrganizationPage", () => {
render(<OrganizationPage />);
fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
- fireEvent.click(await screen.findByRole("option", { name: "Org Admin" }));
+ fireEvent.click(await screen.findByRole("option", { name: "Org admin" }));
expect(
await screen.findByText("Your sign-in has ended. Access was already taken away."),
@@ -621,7 +624,7 @@ describe("OrganizationPage", () => {
render(<OrganizationPage />);
fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
- const promote = await screen.findByRole("option", { name: "Org Admin" });
+ const promote = await screen.findByRole("option", { name: "Org admin" });
expect(promote.getAttribute("aria-disabled")).toBeNull();
expect(screen.queryByText(/account settings/)).toBeNull();
});
diff --git a/gateway/src/pages/organization/OrganizationPage.tsx b/gateway/src/pages/organization/OrganizationPage.tsx
index 5a6033f4c..92081723d 100644
--- a/gateway/src/pages/organization/OrganizationPage.tsx
+++ b/gateway/src/pages/organization/OrganizationPage.tsx
@@ -1,8 +1,8 @@
import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";
import { useCallback, useState } from "react";
+import type { CurrentOrganization, Session } from "../../data/api";
import { useAuth } from "../../data/AuthContext";
-import { fetchCurrentOrganization, fetchFeatureFlags } from "../../data/api";
-import { administersOrganization } from "../../data/sessionState";
+import { fetchCurrentOrganization } from "../../data/api";
import { useLoad } from "../workspace/useLoad";
import OrganizationAuditSection from "./OrganizationAuditSection";
import OrganizationConnectorsSection from "./OrganizationConnectorsSection";
@@ -11,24 +11,75 @@ import OrganizationIssuesNotice from "./OrganizationIssuesNotice";
import OrganizationMembersSection from "./OrganizationMembersSection";
import WorkspacesSection from "./WorkspacesSection";
+function useOrganization() {
+ const load = useCallback(() => fetchCurrentOrganization(), []);
+ return useLoad(load);
+}
+
+function OrganizationHeading({
+ organization,
+ isAdmin,
+}: {
+ organization: CurrentOrganization | null;
+ isAdmin: boolean;
+}) {
+ return (
+ <Stack spacing={0.5} mb={3}>
+ <Typography variant="h5">{organization?.name ?? ""}</Typography>
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
+ {isAdmin
+ ? "You are an admin of this organization, and so of every workspace in it."
+ : organization === null
+ ? ""
+ : organization.role === "member"
+ ? "You are a member of this organization."
+ : "You are here as platform operator, not as a member of this organization."}
+ </Typography>
+ </Stack>
+ );
+}
+
+function MembersSection({
+ session,
+ organizationId,
+ organization,
+ isAdmin,
+ onChanged,
+}: {
+ session: Session;
+ organizationId: string;
+ organization: CurrentOrganization | null;
+ isAdmin: boolean;
+ onChanged: () => void;
+}) {
+ return (
+ <OrganizationMembersSection
+ selfId={session.user.id}
+ organizationId={organizationId}
+ asOperator={!isAdmin}
+ fromDirectory={organization?.members_from_directory === true}
+ directoryTakesChanges={organization?.directory_takes_changes === true}
+ onChanged={onChanged}
+ />
+ );
+}
+
+/** Where the server runs organization connector apps, which mounts the
+ * routes both sections read. */
+function useOrganizationConnectorsEnabled(): boolean {
+ const { capabilities } = useAuth();
+ return (
+ capabilities.features.service_connections && capabilities.features.organization_connector_apps
+ );
+}
+
/** The organization the current workspace belongs to. Its workspaces are
* listed to anyone in it; its members and audit log to its admins, the only
* ones the server answers. */
export default function OrganizationPage() {
- const { session } = useAuth();
- const load = useCallback(() => fetchCurrentOrganization(), []);
- const { data: organization, error } = useLoad(load);
- const isAdmin = session ? administersOrganization(session) : false;
- // Only an org admin sees the sections the flags decide, so only they ask.
- const loadFlags = useCallback(
- () => (isAdmin ? fetchFeatureFlags() : Promise.resolve(null)),
- [isAdmin],
- );
- const { data: flags, error: flagsError } = useLoad(loadFlags);
- // The server mounts the routes behind Services and Connectors only with
- // both flags on; asking a server without them would only be refused.
- const organizationApps =
- flags?.service_connections === true && flags?.organization_connector_apps === true;
+ const { session, capabilities } = useAuth();
+ const { data: organization, error } = useOrganization();
+ const connectorsEnabled = useOrganizationConnectorsEnabled();
// A change to the members can make an issue or settle one; the notice is
// read again, from scratch, after each.
const [membersChanged, setMembersChanged] = useState(0);
@@ -38,44 +89,88 @@ export default function OrganizationPage() {
if (tenant.organization_id === null) {
return <Alert severity="info">This workspace belongs to no organization.</Alert>;
}
+ const isAdmin = organization?.administers === true;
return (
<Box>
- <Stack spacing={0.5} mb={3}>
- <Typography variant="h5">{organization?.name ?? ""}</Typography>
- <Typography variant="body2" sx={{ color: "text.secondary" }}>
- {isAdmin
- ? "You are an admin of this organization, and so of every workspace in it."
- : organization === null
- ? ""
- : organization.role === "member"
- ? "You are a member of this organization."
- : "You are here as platform operator, not as a member of this organization."}
- </Typography>
- </Stack>
+ <OrganizationHeading organization={organization} isAdmin={isAdmin} />
{error && <Alert severity="error">{error}</Alert>}
- {flagsError && (
- <Alert severity="error" sx={{ mb: 2 }}>
- Could not tell whether Services and Connectors are available: {flagsError}
- </Alert>
- )}
<Stack spacing={4}>
- {(isAdmin || session.user.is_operator) && <OrganizationIssuesNotice key={membersChanged} />}
+ {organization?.can_manage_members && <OrganizationIssuesNotice key={membersChanged} />}
<WorkspacesSection currentId={tenant.id} canAdd={session.can_add_workspace} />
- {(isAdmin || session.user.is_operator) && (
- <OrganizationMembersSection
- selfId={session.user.id}
+ {organization !== null && (isAdmin || capabilities.isOperator) && (
+ <MembersSection
+ session={session}
organizationId={tenant.organization_id}
- asOperator={!isAdmin}
- fromDirectory={organization?.members_from_directory === true}
- directoryTakesChanges={organization?.directory_takes_changes === true}
+ organization={organization}
+ isAdmin={isAdmin}
onChanged={onMembersChanged}
/>
)}
- {isAdmin && organizationApps && <OrganizationServicesSection />}
- {isAdmin && organizationApps && <OrganizationConnectorsSection />}
+ {isAdmin && connectorsEnabled && <OrganizationServicesSection />}
+ {isAdmin && connectorsEnabled && <OrganizationConnectorsSection />}
{isAdmin && <OrganizationAuditSection />}
</Stack>
</Box>
);
}
+
+// The new layout's Organization settings. The route table admits the
+// organization's admins, and the operator to General, Workspaces and Users.
+
+export function OrganizationGeneralPage() {
+ const { data: organization, error } = useOrganization();
+ return (
+ <Box>
+ <OrganizationHeading organization={organization} isAdmin={organization?.administers === true} />
+ {error && <Alert severity="error">{error}</Alert>}
+ <Stack spacing={4}>
+ {organization?.can_manage_members && <OrganizationIssuesNotice />}
+ </Stack>
+ </Box>
+ );
+}
+
+export function OrganizationWorkspacesPage() {
+ const { session } = useAuth();
+ const tenant = session?.tenant;
+ if (!session || !tenant) return <CircularProgress />;
+ return <WorkspacesSection currentId={tenant.id} canAdd={session.can_add_workspace} />;
+}
+
+export function OrganizationUsersPage() {
+ const { session } = useAuth();
+ const { data: organization, error } = useOrganization();
+ // As on the organization page: a change to the members can make an issue
+ // or settle one.
+ const [membersChanged, setMembersChanged] = useState(0);
+ const onMembersChanged = useCallback(() => setMembersChanged((n) => n + 1), []);
+ const tenant = session?.tenant;
+ if (error) return <Alert severity="error">{error}</Alert>;
+ if (!session || !tenant?.organization_id || organization === null) return <CircularProgress />;
+ return (
+ <Stack spacing={4}>
+ {organization.can_manage_members && <OrganizationIssuesNotice key={membersChanged} />}
+ <MembersSection
+ session={session}
+ organizationId={tenant.organization_id}
+ organization={organization}
+ isAdmin={organization.administers}
+ onChanged={onMembersChanged}
+ />
+ </Stack>
+ );
+}
+
+export function OrganizationConnectorsPage() {
+ return (
+ <Stack spacing={4}>
+ <OrganizationServicesSection />
+ <OrganizationConnectorsSection />
+ </Stack>
+ );
+}
+
+export function OrganizationAuditLogPage() {
+ return <OrganizationAuditSection />;
+}
diff --git a/gateway/src/pages/organization/OrganizationServicesSection.tsx b/gateway/src/pages/organization/OrganizationServicesSection.tsx
index 2970589aa..af05d0883 100644
--- a/gateway/src/pages/organization/OrganizationServicesSection.tsx
+++ b/gateway/src/pages/organization/OrganizationServicesSection.tsx
@@ -55,7 +55,8 @@ export function reachText(service: OrganizationService, workspaces: number): str
/** Each catalog service, on or off for every workspace in the organization,
* and whether workspace admins may change it. Unlocked, the setting is the
* default each workspace may override; locked, it is out of their reach.
- * The page shows it only where the server lets organizations have this say. */
+ * Shown only where the server lets organizations have this say
+ * (`organization_connector_apps`), which mounts the routes it reads. */
export default function OrganizationServicesSection() {
const load = useCallback(() => fetchOrganizationServices(), []);
const { data, error, loading, refetch } = useLoad(load);
diff --git a/gateway/src/pages/organization/WorkspacesSection.tsx b/gateway/src/pages/organization/WorkspacesSection.tsx
index 8ab2fd9c7..8ea1867ce 100644
--- a/gateway/src/pages/organization/WorkspacesSection.tsx
+++ b/gateway/src/pages/organization/WorkspacesSection.tsx
@@ -20,7 +20,7 @@ import {
createOrganizationWorkspace,
fetchOrganizationWorkspaces,
} from "../../data/api";
-import { titleCase } from "../../theme/hootFormat";
+import { sentenceCase } from "../../theme/hootFormat";
import { useLoad } from "../workspace/useLoad";
interface Props {
@@ -51,7 +51,7 @@ export default function WorkspacesSection({ currentId, canAdd }: Props) {
field: "role",
headerName: "Your role",
width: 140,
- valueFormatter: (value) => titleCase(String(value)),
+ valueFormatter: (value) => sentenceCase(String(value)),
},
{
field: "actions",
diff --git a/gateway/src/pages/registration-keys/CreateKeyDialog.tsx b/gateway/src/pages/registration-keys/CreateKeyDialog.tsx
index 85124abd3..098474bab 100644
--- a/gateway/src/pages/registration-keys/CreateKeyDialog.tsx
+++ b/gateway/src/pages/registration-keys/CreateKeyDialog.tsx
@@ -89,7 +89,7 @@ export default function CreateKeyDialog({ open, onClose, onCreated }: Props) {
return (
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
- <DialogTitle>{result ? "Key Created" : "Create API Key"}</DialogTitle>
+ <DialogTitle>{result ? "Key created" : "Create API key"}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
{result ? (
@@ -98,7 +98,7 @@ export default function CreateKeyDialog({ open, onClose, onCreated }: Props) {
Copy the key now. It will not be shown again.
</Alert>
<TextField
- label="Registration Key"
+ label="API key"
value={result.key}
fullWidth
slotProps={{
diff --git a/gateway/src/pages/registration-keys/RegistrationKeysPage.test.tsx b/gateway/src/pages/registration-keys/RegistrationKeysPage.test.tsx
new file mode 100644
index 000000000..3b8e4969c
--- /dev/null
+++ b/gateway/src/pages/registration-keys/RegistrationKeysPage.test.tsx
@@ -0,0 +1,59 @@
+import { cleanup, render, screen, within } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ApiKeyDetail } from "../../data/api";
+import RegistrationKeysPage from "./RegistrationKeysPage";
+
+vi.mock("../../components/DataTable", () => import("../../test/FakeDataTable"));
+
+function key(id: string, overrides: Partial<ApiKeyDetail>): ApiKeyDetail {
+ return {
+ id,
+ label: id,
+ type: "registration",
+ key_prefix: `sk_${id}`,
+ created_at: "2026-10-01T00:00:00Z",
+ expires_at: null,
+ can_reveal: true,
+ can_delete: true,
+ ...overrides,
+ };
+}
+
+function serve(keys: ApiKeyDetail[]) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response(JSON.stringify(keys), { status: 200 })),
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("RegistrationKeysPage", () => {
+ it("offers copy and delete only where the server says each may be done", async () => {
+ serve([
+ key("mine", {}),
+ key("bootstrap", { type: "bootstrap" }),
+ key("active", { type: "agent", label: "helper", can_delete: false }),
+ key("leftover", { type: "agent", label: "deleted-helper" }),
+ key("hidden", { type: "agent", label: "theirs", can_reveal: false, can_delete: false }),
+ ]);
+ render(<RegistrationKeysPage />);
+
+ const mine = within(await screen.findByTestId("row-mine"));
+ expect(mine.getByRole("button", { name: "Delete mine" })).toBeTruthy();
+ expect(mine.getAllByRole("button")).toHaveLength(2);
+ expect(within(screen.getByTestId("row-bootstrap")).getAllByRole("button")).toHaveLength(2);
+
+ const active = within(screen.getByTestId("row-active"));
+ expect(active.queryByRole("button", { name: "Delete helper" })).toBeNull();
+ expect(active.getAllByRole("button")).toHaveLength(1);
+
+ const leftover = within(screen.getByTestId("row-leftover"));
+ expect(leftover.getByRole("button", { name: "Delete deleted-helper" })).toBeTruthy();
+
+ expect(within(screen.getByTestId("row-hidden")).queryAllByRole("button")).toHaveLength(0);
+ });
+});
diff --git a/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx b/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
index 6a25e9baa..0c26f76dc 100644
--- a/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
+++ b/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
@@ -90,7 +90,7 @@ export default function RegistrationKeysPage() {
{ field: "label", headerName: "Label", flex: 1, minWidth: 200 },
{
field: "key_prefix",
- headerName: "Key Prefix",
+ headerName: "Key prefix",
width: 180,
renderCell: ({ value }) => (
<Typography component="span" sx={MONO_SX}>
@@ -120,18 +120,26 @@ export default function RegistrationKeysPage() {
filterable: false,
renderCell: ({ row }) => (
<>
- <Tooltip title={copiedId === row.id ? "Copied!" : "Copy key"}>
- <IconButton size="small" onClick={() => handleCopy(row.id)}>
- {copiedId === row.id ? (
- <DoneOutline fontSize="small" color="success" />
- ) : (
- <ContentCopy fontSize="small" />
- )}
+ {row.can_reveal && (
+ <Tooltip title={copiedId === row.id ? "Copied!" : "Copy key"}>
+ <IconButton size="small" onClick={() => handleCopy(row.id)}>
+ {copiedId === row.id ? (
+ <DoneOutline fontSize="small" color="success" />
+ ) : (
+ <ContentCopy fontSize="small" />
+ )}
+ </IconButton>
+ </Tooltip>
+ )}
+ {row.can_delete && (
+ <IconButton
+ size="small"
+ onClick={() => setDeleteTarget(row)}
+ aria-label={`Delete ${row.label}`}
+ >
+ <DeleteOutline fontSize="small" />
</IconButton>
- </Tooltip>
- <IconButton size="small" onClick={() => setDeleteTarget(row)}>
- <DeleteOutline fontSize="small" />
- </IconButton>
+ )}
</>
),
},
@@ -144,7 +152,7 @@ export default function RegistrationKeysPage() {
{ field: "label", headerName: "Agent", flex: 1, minWidth: 200 },
{
field: "key_prefix",
- headerName: "Key Prefix",
+ headerName: "Key prefix",
width: 180,
renderCell: ({ value }) => (
<Typography component="span" sx={MONO_SX}>
@@ -169,19 +177,34 @@ export default function RegistrationKeysPage() {
{
field: "actions",
headerName: "",
- width: 60,
+ width: 100,
sortable: false,
filterable: false,
+ // An agent's key cannot be deleted while the agent signs in with it;
+ // one left behind by a deleted agent can.
renderCell: ({ row }) => (
- <Tooltip title={copiedId === row.id ? "Copied!" : "Copy key"}>
- <IconButton size="small" onClick={() => handleCopy(row.id)}>
- {copiedId === row.id ? (
- <DoneOutline fontSize="small" color="success" />
- ) : (
- <ContentCopy fontSize="small" />
- )}
- </IconButton>
- </Tooltip>
+ <>
+ {row.can_reveal && (
+ <Tooltip title={copiedId === row.id ? "Copied!" : "Copy key"}>
+ <IconButton size="small" onClick={() => handleCopy(row.id)}>
+ {copiedId === row.id ? (
+ <DoneOutline fontSize="small" color="success" />
+ ) : (
+ <ContentCopy fontSize="small" />
+ )}
+ </IconButton>
+ </Tooltip>
+ )}
+ {row.can_delete && (
+ <IconButton
+ size="small"
+ onClick={() => setDeleteTarget(row)}
+ aria-label={`Delete ${row.label}`}
+ >
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ )}
+ </>
),
},
],
@@ -191,18 +214,18 @@ export default function RegistrationKeysPage() {
return (
<Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={2}>
- <Typography variant="h5">API Keys</Typography>
+ <Typography variant="h5">API keys</Typography>
<Button
variant="contained"
startIcon={<AddCircleOutline />}
onClick={() => setCreateOpen(true)}
>
- Create Registration Key
+ Create API key
</Button>
</Stack>
<Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 1 }}>
- Registration Keys
+ Keys for adding agents
</Typography>
{loading ? (
<CircularProgress />
@@ -231,7 +254,7 @@ export default function RegistrationKeysPage() {
sx={{ mt: 3, mb: 1 }}
>
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
- Agent Keys
+ Agent keys
</Typography>
<TextField
size="small"
@@ -260,8 +283,10 @@ export default function RegistrationKeysPage() {
<DialogTitle>Delete API key</DialogTitle>
<DialogContent>
<DialogContentText>
- Are you sure you want to delete key &quot;{deleteTarget?.label}&quot;? Agents
- using this key will no longer be able to register.
+ Are you sure you want to delete key &quot;{deleteTarget?.label}&quot;?{" "}
+ {deleteTarget?.type === "agent"
+ ? "Its agent has been deleted, so nothing signs in with it."
+ : "Agents using this key will no longer be able to register."}
</DialogContentText>
</DialogContent>
<DialogActions>
diff --git a/gateway/src/pages/resources/DocumentDetailPage.test.tsx b/gateway/src/pages/resources/DocumentDetailPage.test.tsx
new file mode 100644
index 000000000..69149fe14
--- /dev/null
+++ b/gateway/src/pages/resources/DocumentDetailPage.test.tsx
@@ -0,0 +1,129 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter, Route, Routes } from "react-router";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { DocumentDetail } from "../../data/api";
+import { useAuth } from "../../data/AuthContext";
+import DocumentDetailPage from "./DocumentDetailPage";
+
+vi.mock("../../data/AuthContext", () => ({ useAuth: vi.fn() }));
+
+const doc: DocumentDetail = {
+ id: "d1",
+ owner_id: "u2",
+ owner_name: "Bob",
+ read_visibility: "public",
+ write_visibility: "public",
+ name: "Runbook",
+ description: "How we deploy",
+ instructions: "",
+ attached_rooms_count: 0,
+ hidden_rooms_count: 0,
+ packages: [],
+ scope: "global",
+ room_id: null,
+ created_by_agent_id: null,
+ created_by_agent_name: null,
+ created_at: "2026-10-01T00:00:00Z",
+ content: "Step one",
+ can_edit: false,
+ can_manage: false,
+ can_transfer: false,
+};
+
+type Flags = Pick<DocumentDetail, "can_edit" | "can_manage" | "can_transfer">;
+
+/** The page for a document the server describes with `flags`; every other
+ * read answers empty, and each write is recorded. */
+function showWith(flags: Flags) {
+ vi.mocked(useAuth).mockReturnValue({
+ user: { id: "u1" },
+ session: null,
+ } as unknown as ReturnType<typeof useAuth>);
+ const writes: { method: string; body: unknown }[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const path = String(input).split("?")[0];
+ const method = init?.method ?? "GET";
+ if (path === "/gateway/documents/d1" && method === "GET") {
+ return new Response(JSON.stringify({ ...doc, ...flags }), { status: 200 });
+ }
+ if (path === "/gateway/documents/d1") {
+ writes.push({ method, body: init?.body ? JSON.parse(String(init.body)) : null });
+ return new Response(JSON.stringify({ ...doc, ...flags }), { status: 200 });
+ }
+ return new Response(JSON.stringify([]), { status: 200 });
+ }),
+ );
+ render(
+ <MemoryRouter initialEntries={["/resources/documents/d1"]}>
+ <Routes>
+ <Route path="/resources/documents/:id" element={<DocumentDetailPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ return writes;
+}
+
+function field(label: string): HTMLInputElement | HTMLTextAreaElement {
+ return screen.getByLabelText(label) as HTMLInputElement | HTMLTextAreaElement;
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("DocumentDetailPage", () => {
+ it("is read-only to someone the server lets do nothing", async () => {
+ showWith({ can_edit: false, can_manage: false, can_transfer: false });
+ await screen.findByDisplayValue("Runbook");
+ expect(field("Name").disabled).toBe(true);
+ expect(screen.queryByRole("button", { name: "Transfer ownership" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Delete document" })).toBeNull();
+ });
+
+ it("lets someone who may write it edit it, but not who may see it, hand it over or delete it", async () => {
+ showWith({ can_edit: true, can_manage: false, can_transfer: false });
+ await screen.findByDisplayValue("Runbook");
+ expect(field("Name").disabled).toBe(false);
+ expect(screen.getByLabelText("Access").getAttribute("aria-disabled")).toBe("true");
+ expect(
+ screen.getByText(
+ "Anyone can see, attach and change it. Only its owner and admins can change who may.",
+ ),
+ ).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Transfer ownership" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Delete document" })).toBeNull();
+ });
+
+ it("does not send who may see it when that was not changed", async () => {
+ const writes = showWith({ can_edit: true, can_manage: false, can_transfer: false });
+ fireEvent.change(await screen.findByDisplayValue("Runbook"), {
+ target: { value: "Deploy runbook" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(writes).toHaveLength(1));
+ expect(writes[0].body).toEqual({
+ name: "Deploy runbook",
+ description: "How we deploy",
+ instructions: "",
+ content: "Step one",
+ });
+ });
+
+ it("offers delete, but not a hand-over, for a document the server will not move", async () => {
+ showWith({ can_edit: true, can_manage: true, can_transfer: false });
+ await screen.findByDisplayValue("Runbook");
+ expect(screen.getByRole("button", { name: "Delete document" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Transfer ownership" })).toBeNull();
+ });
+
+ it("offers everything to someone who may manage it", async () => {
+ showWith({ can_edit: true, can_manage: true, can_transfer: true });
+ await screen.findByDisplayValue("Runbook");
+ expect(screen.getByLabelText("Access").getAttribute("aria-disabled")).toBeNull();
+ expect(screen.getByRole("button", { name: "Delete document" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Transfer ownership" })).toBeTruthy();
+ });
+});
diff --git a/gateway/src/pages/resources/DocumentDetailPage.tsx b/gateway/src/pages/resources/DocumentDetailPage.tsx
index 4aa6d4c6c..ec7a0f2a5 100644
--- a/gateway/src/pages/resources/DocumentDetailPage.tsx
+++ b/gateway/src/pages/resources/DocumentDetailPage.tsx
@@ -20,9 +20,9 @@ import {
fetchDocument,
updateDocument,
} from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import { AccessChip, AccessSelect } from "../../components/AccessControls";
import {
+ ACCESS_HELPERS_FOR_OTHERS,
type AccessLevel,
fromAccessLevel,
toAccessLevel,
@@ -35,7 +35,6 @@ import ResourceAttachmentsSection from "./ResourceAttachmentsSection";
export default function DocumentDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
- const { user, canAdminTenant } = useAuth();
const [doc, setDoc] = useState<DocumentDetail | null>(null);
const [loading, setLoading] = useState(true);
const [fetchError, setFetchError] = useState<string | null>(null);
@@ -77,9 +76,6 @@ export default function DocumentDetailPage() {
);
}
- const canMutate =
- !!user && (user.id === doc.owner_id || canAdminTenant);
-
return (
<Box>
<Stack direction="row" alignItems="center" spacing={1} mb={2}>
@@ -100,7 +96,8 @@ export default function DocumentDetailPage() {
<Divider />
<EditFieldsSection
doc={doc}
- canMutate={canMutate}
+ canEdit={doc.can_edit}
+ canChangeAccess={doc.can_manage}
onSaved={(updated) => setDoc(updated)}
/>
<Divider />
@@ -111,7 +108,7 @@ export default function DocumentDetailPage() {
resourceId={id}
hiddenRoomsCount={doc.hidden_rooms_count}
/>
- {canMutate && (
+ {doc.can_transfer && (
<>
<Divider />
<TransferOwnershipSection
@@ -119,8 +116,13 @@ export default function DocumentDetailPage() {
resourceId={id}
resourceLabel={doc.name || id}
ownerId={doc.owner_id}
+ blockedReason={null}
onTransferred={() => navigate(0)}
/>
+ </>
+ )}
+ {doc.can_manage && (
+ <>
<Divider />
<DangerSection onDelete={() => setDeleteOpen(true)} />
</>
@@ -183,11 +185,13 @@ function InfoLine({
function EditFieldsSection({
doc,
- canMutate,
+ canEdit,
+ canChangeAccess,
onSaved,
}: {
doc: DocumentDetail;
- canMutate: boolean;
+ canEdit: boolean;
+ canChangeAccess: boolean;
onSaved: (updated: DocumentDetail) => void;
}) {
const [name, setName] = useState(doc.name);
@@ -217,7 +221,8 @@ function EditFieldsSection({
description,
instructions,
content,
- ...fromAccessLevel(access),
+ // Changing who may see or change it is the manager's alone.
+ ...(access !== toAccessLevel(doc) ? fromAccessLevel(access) : {}),
});
onSaved(updated);
} catch (e) {
@@ -236,13 +241,13 @@ function EditFieldsSection({
label="Name"
value={name}
onChange={(e) => setName(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
/>
<TextField
label="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={2}
helperText="Short, human-readable summary. Shown in lists."
@@ -251,7 +256,7 @@ function EditFieldsSection({
label="Instructions"
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={4}
helperText="Sent to agents on connect. Not shown in lists."
@@ -260,7 +265,7 @@ function EditFieldsSection({
label="Content"
value={content}
onChange={(e) => setContent(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={12}
slotProps={{ input: { sx: { fontFamily: "monospace" } } }}
@@ -268,7 +273,8 @@ function EditFieldsSection({
<AccessSelect
value={access}
onChange={setAccess}
- disabled={!canMutate || saving}
+ disabled={!canChangeAccess || saving}
+ helpers={canChangeAccess ? undefined : ACCESS_HELPERS_FOR_OTHERS}
sx={{ maxWidth: 320 }}
/>
{error && <Alert severity="error">{error}</Alert>}
@@ -276,7 +282,7 @@ function EditFieldsSection({
<Button
variant="contained"
onClick={handleSave}
- disabled={!canMutate || !dirty || saving}
+ disabled={!(canEdit || canChangeAccess) || !dirty || saving}
startIcon={saving ? <CircularProgress size={16} /> : undefined}
>
Save
diff --git a/gateway/src/pages/resources/PackageDetailPage.tsx b/gateway/src/pages/resources/PackageDetailPage.tsx
index 74957ed88..0f0faefdb 100644
--- a/gateway/src/pages/resources/PackageDetailPage.tsx
+++ b/gateway/src/pages/resources/PackageDetailPage.tsx
@@ -19,9 +19,9 @@ import {
fetchPackage,
updatePackage,
} from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import { AccessChip, AccessSelect } from "../../components/AccessControls";
import {
+ ACCESS_HELPERS_FOR_OTHERS,
type AccessLevel,
fromAccessLevel,
toAccessLevel,
@@ -34,7 +34,6 @@ import ResourceAttachmentsSection from "./ResourceAttachmentsSection";
export default function PackageDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
- const { user, canAdminTenant } = useAuth();
const [pkg, setPkg] = useState<PackageDetail | null>(null);
const [loading, setLoading] = useState(true);
const [fetchError, setFetchError] = useState<string | null>(null);
@@ -76,9 +75,6 @@ export default function PackageDetailPage() {
);
}
- const canMutate =
- !!user && (user.id === pkg.owner_id || canAdminTenant);
-
return (
<Box>
<Stack direction="row" alignItems="center" spacing={1} mb={2}>
@@ -99,18 +95,19 @@ export default function PackageDetailPage() {
<Divider />
<EditFieldsSection
pkg={pkg}
- canMutate={canMutate}
+ canEdit={pkg.can_edit}
+ canChangeAccess={pkg.can_manage}
onSaved={(updated) => setPkg(updated)}
/>
<Divider />
- <PackageMembersSection packageId={id} canMutate={canMutate} />
+ <PackageMembersSection packageId={id} canMutate={pkg.can_edit} />
<Divider />
<ResourceAttachmentsSection
kind="package"
resourceId={id}
hiddenRoomsCount={pkg.hidden_rooms_count}
/>
- {canMutate && (
+ {pkg.can_manage && (
<>
<Divider />
<TransferOwnershipSection
@@ -118,8 +115,13 @@ export default function PackageDetailPage() {
resourceId={id}
resourceLabel={pkg.name || id}
ownerId={pkg.owner_id}
+ blockedReason={null}
onTransferred={() => navigate(0)}
/>
+ </>
+ )}
+ {pkg.can_manage && (
+ <>
<Divider />
<DangerSection onDelete={() => setDeleteOpen(true)} />
</>
@@ -168,11 +170,13 @@ function InfoSection({ pkg }: { pkg: PackageDetail }) {
function EditFieldsSection({
pkg,
- canMutate,
+ canEdit,
+ canChangeAccess,
onSaved,
}: {
pkg: PackageDetail;
- canMutate: boolean;
+ canEdit: boolean;
+ canChangeAccess: boolean;
onSaved: (updated: PackageDetail) => void;
}) {
const [name, setName] = useState(pkg.name);
@@ -199,7 +203,8 @@ function EditFieldsSection({
name,
description,
instructions,
- ...fromAccessLevel(access),
+ // Changing who may see or change it is the manager's alone.
+ ...(access !== toAccessLevel(pkg) ? fromAccessLevel(access) : {}),
});
onSaved(updated);
} catch (e) {
@@ -218,13 +223,13 @@ function EditFieldsSection({
label="Name"
value={name}
onChange={(e) => setName(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
/>
<TextField
label="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={2}
helperText="Short summary. Shown in lists."
@@ -233,7 +238,7 @@ function EditFieldsSection({
label="Instructions"
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={6}
helperText="Sent to agents on connect. Not shown in lists."
@@ -241,7 +246,8 @@ function EditFieldsSection({
<AccessSelect
value={access}
onChange={setAccess}
- disabled={!canMutate || saving}
+ disabled={!canChangeAccess || saving}
+ helpers={canChangeAccess ? undefined : ACCESS_HELPERS_FOR_OTHERS}
sx={{ maxWidth: 320 }}
/>
{error && <Alert severity="error">{error}</Alert>}
@@ -249,7 +255,7 @@ function EditFieldsSection({
<Button
variant="contained"
onClick={handleSave}
- disabled={!canMutate || !dirty || saving}
+ disabled={!(canEdit || canChangeAccess) || !dirty || saving}
startIcon={saving ? <CircularProgress size={16} /> : undefined}
>
Save
diff --git a/gateway/src/pages/resources/ReferenceDetailPage.tsx b/gateway/src/pages/resources/ReferenceDetailPage.tsx
index fca3b9698..e3ceff9a6 100644
--- a/gateway/src/pages/resources/ReferenceDetailPage.tsx
+++ b/gateway/src/pages/resources/ReferenceDetailPage.tsx
@@ -20,9 +20,9 @@ import {
fetchReference,
updateReference,
} from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
import { AccessChip, AccessSelect } from "../../components/AccessControls";
import {
+ ACCESS_HELPERS_FOR_OTHERS,
type AccessLevel,
fromAccessLevel,
toAccessLevel,
@@ -37,7 +37,6 @@ import UrlsValueForm from "./value_forms/UrlsValueForm";
export default function ReferenceDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
- const { user, canAdminTenant } = useAuth();
const { data: types } = useReferenceTypes();
const [ref, setRef] = useState<ReferenceDetail | null>(null);
const [loading, setLoading] = useState(true);
@@ -83,9 +82,6 @@ export default function ReferenceDetailPage() {
// Visibility-filtered, so it may miss a type this reference legitimately
// has. Its only job is the value hint; every label comes from the server.
const visibleTypeSpec = (types ?? []).find((t) => t.type === ref.type);
- const canMutate =
- !!user && (user.id === ref.owner_id || canAdminTenant);
-
return (
<Box>
<Stack direction="row" alignItems="center" spacing={1} mb={2}>
@@ -110,7 +106,8 @@ export default function ReferenceDetailPage() {
<Divider />
<EditFieldsSection
ref_={ref}
- canMutate={canMutate}
+ canEdit={ref.can_edit}
+ canChangeAccess={ref.can_manage}
valueHint={visibleTypeSpec?.value_hint}
onSaved={(updated) => setRef(updated)}
/>
@@ -122,7 +119,7 @@ export default function ReferenceDetailPage() {
resourceId={id}
hiddenRoomsCount={ref.hidden_rooms_count}
/>
- {canMutate && (
+ {ref.can_manage && (
<>
<Divider />
<TransferOwnershipSection
@@ -130,8 +127,13 @@ export default function ReferenceDetailPage() {
resourceId={id}
resourceLabel={ref.name || id}
ownerId={ref.owner_id}
+ blockedReason={null}
onTransferred={() => navigate(0)}
/>
+ </>
+ )}
+ {ref.can_manage && (
+ <>
<Divider />
<DangerSection onDelete={() => setDeleteOpen(true)} />
</>
@@ -198,12 +200,14 @@ function InfoLine({
function EditFieldsSection({
ref_,
- canMutate,
+ canEdit,
+ canChangeAccess,
valueHint,
onSaved,
}: {
ref_: ReferenceDetail;
- canMutate: boolean;
+ canEdit: boolean;
+ canChangeAccess: boolean;
valueHint: string | undefined;
onSaved: (updated: ReferenceDetail) => void;
}) {
@@ -234,7 +238,8 @@ function EditFieldsSection({
name,
description,
instructions,
- ...fromAccessLevel(access),
+ // Changing who may see or change it is the manager's alone.
+ ...(access !== toAccessLevel(ref_) ? fromAccessLevel(access) : {}),
value,
});
onSaved(updated);
@@ -260,13 +265,13 @@ function EditFieldsSection({
label="Name"
value={name}
onChange={(e) => setName(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
/>
<TextField
label="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={2}
helperText="Short, human-readable summary. Shown in lists."
@@ -275,7 +280,7 @@ function EditFieldsSection({
label="Instructions"
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={6}
helperText="Sent to agents on connect. Not shown in lists."
@@ -284,7 +289,7 @@ function EditFieldsSection({
<UrlsValueForm
value={value}
onChange={setValue}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
helperText={
valueHint ??
"This reference's type is not visible to you. Enter one URL per line."
@@ -294,14 +299,15 @@ function EditFieldsSection({
<JsonValueForm
value={value}
onChange={setValue}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
onValidityChange={setValueValid}
/>
)}
<AccessSelect
value={access}
onChange={setAccess}
- disabled={!canMutate || saving}
+ disabled={!canChangeAccess || saving}
+ helpers={canChangeAccess ? undefined : ACCESS_HELPERS_FOR_OTHERS}
sx={{ maxWidth: 320 }}
/>
{error && <Alert severity="error">{error}</Alert>}
@@ -309,7 +315,7 @@ function EditFieldsSection({
<Button
variant="contained"
onClick={handleSave}
- disabled={!canMutate || !dirty || saving || !valueValid}
+ disabled={!(canEdit || canChangeAccess) || !dirty || saving || !valueValid}
startIcon={saving ? <CircularProgress size={16} /> : undefined}
>
Save
diff --git a/gateway/src/pages/resources/ReferenceTypesTab.tsx b/gateway/src/pages/resources/ReferenceTypesTab.tsx
index bbf4a7516..1deaf38b0 100644
--- a/gateway/src/pages/resources/ReferenceTypesTab.tsx
+++ b/gateway/src/pages/resources/ReferenceTypesTab.tsx
@@ -28,6 +28,7 @@ import {
} from "../../data/api";
import { useOwnedReferenceTypes, useReferenceTypes } from "../../data/hooks";
import {
+ ACCESS_HELPERS_FOR_OTHERS,
type AccessLevel,
fromAccessLevel,
toAccessLevel,
@@ -156,27 +157,33 @@ export default function ReferenceTypesTab({ refreshKey }: Props) {
renderCell: ({ row }) =>
row.detail ? (
<>
- <IconButton
- size="small"
- onClick={() => setEditing(row.detail)}
- aria-label={`Edit ${row.display_name}`}
- >
- <EditOutlined fontSize="small" />
- </IconButton>
- <IconButton
- size="small"
- onClick={() => setTransferring(row.detail)}
- aria-label={`Transfer ${row.display_name}`}
- >
- <SwapHoriz fontSize="small" />
- </IconButton>
- <IconButton
- size="small"
- onClick={() => setDeleting(row.detail)}
- aria-label={`Delete ${row.display_name}`}
- >
- <DeleteOutline fontSize="small" />
- </IconButton>
+ {row.detail.can_edit && (
+ <IconButton
+ size="small"
+ onClick={() => setEditing(row.detail)}
+ aria-label={`Edit ${row.display_name}`}
+ >
+ <EditOutlined fontSize="small" />
+ </IconButton>
+ )}
+ {row.detail.can_manage && (
+ <>
+ <IconButton
+ size="small"
+ onClick={() => setTransferring(row.detail)}
+ aria-label={`Transfer ${row.display_name}`}
+ >
+ <SwapHoriz fontSize="small" />
+ </IconButton>
+ <IconButton
+ size="small"
+ onClick={() => setDeleting(row.detail)}
+ aria-label={`Delete ${row.display_name}`}
+ >
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ </>
+ )}
</>
) : null,
},
@@ -266,7 +273,8 @@ function EditReferenceTypeDialog({
display_name: displayName,
instructions,
value_hint: valueHint,
- ...fromAccessLevel(access),
+ // Changing who may see or change it is the manager's alone.
+ ...(access !== toAccessLevel(referenceType) ? fromAccessLevel(access) : {}),
});
onSaved();
} catch (e) {
@@ -317,7 +325,12 @@ function EditReferenceTypeDialog({
disabled={submitting}
helperText="Shown under the URL box when someone creates a reference of this type — say what those URLs should point at."
/>
- <AccessSelect value={access} onChange={setAccess} disabled={submitting} />
+ <AccessSelect
+ value={access}
+ onChange={setAccess}
+ disabled={submitting || !referenceType.can_manage}
+ helpers={referenceType.can_manage ? undefined : ACCESS_HELPERS_FOR_OTHERS}
+ />
{referenceType.shadowed_by_builtin && (
<Alert severity="warning">
A built-in type now uses this slug, and the built-in wins: agents
diff --git a/gateway/src/pages/resources/ResourcesPage.tsx b/gateway/src/pages/resources/ResourcesPage.tsx
index 67a7f16d6..8f5211357 100644
--- a/gateway/src/pages/resources/ResourcesPage.tsx
+++ b/gateway/src/pages/resources/ResourcesPage.tsx
@@ -1,7 +1,7 @@
import AddIcon from "@mui/icons-material/Add";
import { Box, Button, Stack, Tab, Tabs, Typography } from "@mui/material";
import { useState } from "react";
-import { useNavigate, useSearchParams } from "react-router";
+import { Navigate, useLocation, useNavigate, useSearchParams } from "react-router";
import CreateDocumentDialog from "./CreateDocumentDialog";
import CreatePackageDialog from "./CreatePackageDialog";
import CreateReferenceDialog from "./CreateReferenceDialog";
@@ -27,11 +27,15 @@ const TABS = [
type ResourceTab = (typeof TABS)[number]["value"];
-export default function ResourcesPage() {
+/** `withTemplates` is false in the new layout, where Templates is a page of
+ * its own; a link to the old tab is sent there. */
+export default function ResourcesPage({ withTemplates }: { withTemplates: boolean }) {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
+ const { hash } = useLocation();
const tabParam = searchParams.get("tab");
- const active = TABS.find((t) => t.value === tabParam) ?? TABS[0];
+ const tabs = TABS.filter((t) => withTemplates || t.value !== "templates");
+ const active = tabs.find((t) => t.value === tabParam) ?? tabs[0];
const tab: ResourceTab = active.value;
const [createOpen, setCreateOpen] = useState(false);
const [refreshKey, setRefreshKey] = useState(0);
@@ -71,6 +75,18 @@ export default function ResourcesPage() {
setRefreshKey((k) => k + 1);
};
+ if (!withTemplates && tabParam === "templates") {
+ const rest = new URLSearchParams(searchParams);
+ rest.delete("tab");
+ const search = rest.toString();
+ return (
+ <Navigate
+ to={{ pathname: "/templates", search: search === "" ? "" : `?${search}`, hash }}
+ replace
+ />
+ );
+ }
+
return (
<Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={2}>
@@ -89,7 +105,7 @@ export default function ResourcesPage() {
onChange={(_, v) => setTab(v as ResourceTab)}
sx={{ mb: 2, borderBottom: 1, borderColor: "divider" }}
>
- {TABS.map((t) => (
+ {tabs.map((t) => (
<Tab key={t.value} label={t.label} value={t.value} />
))}
</Tabs>
diff --git a/gateway/src/pages/resources/TemplateDetailPage.tsx b/gateway/src/pages/resources/TemplateDetailPage.tsx
index 24413e388..027995ab9 100644
--- a/gateway/src/pages/resources/TemplateDetailPage.tsx
+++ b/gateway/src/pages/resources/TemplateDetailPage.tsx
@@ -125,6 +125,7 @@ export default function TemplateDetailPage() {
resourceId={id}
resourceLabel={template.name || id}
ownerId={template.owner_id}
+ blockedReason={null}
onTransferred={() => navigate(0)}
/>
<Divider />
diff --git a/gateway/src/pages/rooms/GroupsPage.test.tsx b/gateway/src/pages/rooms/GroupsPage.test.tsx
index 2c5ac505b..7346948f3 100644
--- a/gateway/src/pages/rooms/GroupsPage.test.tsx
+++ b/gateway/src/pages/rooms/GroupsPage.test.tsx
@@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { RoomGroupDetail, RoomSummary } from "../../data/api";
+import { ALL_OFF } from "../../data/featureFlags";
import { useAuth } from "../../data/AuthContext";
import * as hooks from "../../data/hooks";
import type { UseQueryResult } from "../../data/hooks";
@@ -24,6 +25,17 @@ function authState(canAdminTenant: boolean) {
loadError: null,
isOperator: false,
canAdminTenant,
+ capabilities: {
+ isOperator: false,
+ administersWorkspace: canAdminTenant,
+ administersOrganization: false,
+ inOrganization: false,
+ canDeleteWorkspace: false,
+ canManageDataProtection: false,
+ features: ALL_OFF,
+ },
+ staleError: null,
+ recheck: vi.fn(),
refresh: vi.fn(async () => {}),
login: vi.fn(async () => {}),
logout: vi.fn(async () => {}),
diff --git a/gateway/src/pages/rooms/RoomAutoRouteSection.test.tsx b/gateway/src/pages/rooms/RoomAutoRouteSection.test.tsx
index bc518848e..b3130d4cf 100644
--- a/gateway/src/pages/rooms/RoomAutoRouteSection.test.tsx
+++ b/gateway/src/pages/rooms/RoomAutoRouteSection.test.tsx
@@ -24,6 +24,10 @@ function agent(id: string, name: string): AgentSummary {
known_agent_type: "claude-code",
known_agent_options: null,
can_manage: false,
+ can_rename: false,
+ can_edit_options: false,
+ can_transfer: false,
+ transfer_blocked_reason: null,
};
}
diff --git a/gateway/src/pages/rooms/RoomCreateFormBody.tsx b/gateway/src/pages/rooms/RoomCreateFormBody.tsx
index f697e96a6..7eaf00569 100644
--- a/gateway/src/pages/rooms/RoomCreateFormBody.tsx
+++ b/gateway/src/pages/rooms/RoomCreateFormBody.tsx
@@ -91,7 +91,7 @@ export default function RoomCreateFormBody() {
if (!selectedBridge.channel_creation_supported) {
return `${selectedBridge.display_name} cannot create channels from Switch. Create the channel on the platform, then add the app to it.`;
}
- return "Channel creation is turned off for this connection. An admin can turn it on in Messaging Apps.";
+ return "Channel creation is turned off for this messaging app. An admin can turn it on in the workspace's messaging apps.";
}, [selectedBridge, channelCreationBlocked]);
// If the user had "Create new channel" selected and then picks a bridge
diff --git a/gateway/src/pages/rooms/RoomDetailPage.test.tsx b/gateway/src/pages/rooms/RoomDetailPage.test.tsx
index 7a2cc331d..ba2190551 100644
--- a/gateway/src/pages/rooms/RoomDetailPage.test.tsx
+++ b/gateway/src/pages/rooms/RoomDetailPage.test.tsx
@@ -79,13 +79,19 @@ const room = {
can_write: true,
can_manage: false,
can_unlink: false,
+ can_transfer: false,
+ can_change_members: true,
} as RoomDetail;
const agent = { id: "a1", name: "planner", parent_agent_id: null } as AgentSummary;
-function viewAs(can: { can_write: boolean; can_manage: boolean; can_unlink: boolean }) {
+// Members can be changed by whoever may write to the room, as the server
+// says, unless a test sets otherwise.
+function viewAs(
+ can: { can_write: boolean; can_manage: boolean; can_unlink: boolean } & Partial<RoomDetail>,
+) {
vi.mocked(hooks.useRoom).mockReturnValue({
- data: { ...room, ...can },
+ data: { ...room, can_change_members: can.can_write, ...can },
loading: false,
error: null,
refetch: vi.fn(),
@@ -161,6 +167,35 @@ describe("RoomDetailPage permissions", () => {
expect(sent).not.toHaveProperty("write_visibility");
});
+ it("lets someone who may write edit a bridged room's description like any other room's", async () => {
+ viewAs({ can_write: true, can_manage: false, can_unlink: false });
+
+ fireEvent.change(screen.getByLabelText("Description"), {
+ target: { value: "Retro and planning" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => expect(api.updateRoom).toHaveBeenCalledTimes(1));
+ expect(vi.mocked(api.updateRoom).mock.calls[0][1]).toMatchObject({
+ description: "Retro and planning",
+ });
+ });
+
+ it("leaves a chat's members to its platform, keeping its settings editable", () => {
+ viewAs({
+ can_write: true,
+ can_manage: false,
+ can_unlink: false,
+ can_change_members: false,
+ channel_type: "group",
+ });
+
+ expect(screen.queryByRole("button", { name: "Add agent" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Remove planner" })).toBeNull();
+ expect(screen.getByText(/rooms is managed from the messaging platform/)).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Save" })).toBeTruthy();
+ });
+
it("lets someone who may manage the room change its access and delete it", async () => {
viewAs({ can_write: true, can_manage: true, can_unlink: false });
diff --git a/gateway/src/pages/rooms/RoomDetailPage.tsx b/gateway/src/pages/rooms/RoomDetailPage.tsx
index 4b1f823cd..aae23b76d 100644
--- a/gateway/src/pages/rooms/RoomDetailPage.tsx
+++ b/gateway/src/pages/rooms/RoomDetailPage.tsx
@@ -55,7 +55,7 @@ import {
MONO_SX,
channelTypeLabel,
formatDateTime,
- titleCase,
+ sentenceCase,
} from "../../theme/hootFormat";
import RoomAutoRouteSection from "./RoomAutoRouteSection";
import RoomGroupSection from "./RoomGroupSection";
@@ -172,7 +172,7 @@ export default function RoomDetailPage() {
<ArchiveSection room={room} onChanged={refetch} />
</>
)}
- {canManage && (
+ {room.can_transfer && (
<>
<Divider />
<TransferOwnershipSection
@@ -180,8 +180,13 @@ export default function RoomDetailPage() {
resourceId={room.id}
resourceLabel={room.name}
ownerId={room.owner_id}
+ blockedReason={null}
onTransferred={refetch}
/>
+ </>
+ )}
+ {canManage && (
+ <>
<Divider />
<DangerSection room={room} onDeleted={() => navigate("/rooms")} />
</>
@@ -582,8 +587,7 @@ function EditableFieldsSection({
try {
await updateRoom(room.id, {
name: name !== room.name ? name : undefined,
- description:
- !isBridged && description !== room.description ? description : undefined,
+ description: description !== room.description ? description : undefined,
instructions:
instructions !== (room.instructions ?? "") ? instructions : undefined,
...(canManage && access !== toAccessLevel(room) ? fromAccessLevel(access) : {}),
@@ -594,7 +598,7 @@ function EditableFieldsSection({
} finally {
setSaving(false);
}
- }, [room, name, description, instructions, access, isBridged, canManage, onSaved]);
+ }, [room, name, description, instructions, access, canManage, onSaved]);
return (
<Stack spacing={2}>
@@ -626,7 +630,6 @@ function EditableFieldsSection({
disabled={!canWrite || saving}
multiline
rows={2}
- slotProps={{ input: { readOnly: isBridged } }}
/>
<TextField
label="Instructions"
@@ -774,7 +777,10 @@ function ParticipantsSection({
[room.id, onChanged],
);
- const isFixedMembership = room.channel_type === "group" || room.channel_type === "direct";
+ // A direct or group chat takes its members from its platform: the server
+ // refuses changing them, and the page says where they are changed.
+ const platformMembership = room.channel_type === "group" || room.channel_type === "direct";
+ const canChangeMembers = room.can_change_members;
return (
<Stack spacing={3}>
@@ -801,9 +807,7 @@ function ParticipantsSection({
: (next) => handleToggleJoinEvents(id, next)
}
onRemove={
- !canWrite || isFixedMembership || working
- ? undefined
- : () => handleRemoveAgent(id)
+ !canChangeMembers || working ? undefined : () => handleRemoveAgent(id)
}
/>
))}
@@ -813,7 +817,7 @@ function ParticipantsSection({
</Typography>
)}
</Stack>
- {canWrite && !isFixedMembership && (
+ {canChangeMembers && (
<>
<Button
size="small"
@@ -838,14 +842,14 @@ function ParticipantsSection({
/>
</>
)}
- {isFixedMembership && (
+ {platformMembership && (
<Typography variant="caption" color="text.secondary">
Membership for {channelTypeLabel(room.channel_type)} rooms is managed from the messaging platform.
</Typography>
)}
</Box>
- {room.bridge_id && !isFixedMembership && (
+ {room.bridge_id && !platformMembership && (
<Box>
<Typography variant="body2" gutterBottom>
Connected users ({room.connected_user_names.length})
@@ -860,7 +864,7 @@ function ParticipantsSection({
</Typography>
)}
</Stack>
- {canWrite && (
+ {canChangeMembers && (
<>
<Button
size="small"
@@ -973,7 +977,7 @@ function AgentRow({
}) {
const navigate = useNavigate();
const meta = (status && STATUS_META[status]) || {
- label: status ? titleCase(status) : "Unknown",
+ label: status ? sentenceCase(status) : "Unknown",
color: "var(--hoot-muted-foreground)",
description: "",
};
@@ -1119,7 +1123,7 @@ function ArchiveSection({
<Typography variant="body2" color="text.secondary">
{room.archived
? "This room is archived: hidden from the active room list but fully intact and retrievable. Unarchive it to restore it to the active list."
- : "Archiving hides this room from the active room list while keeping it fully intact — the Matrix room, members, and any bridge channel are untouched. It's reversible at any time."}
+ : "Archiving hides this room from the active room list while keeping it fully intact — its messages, who is in it and any linked channel are untouched. It's reversible at any time."}
</Typography>
<Box>
<Button
@@ -1189,8 +1193,8 @@ function DangerSection({
<DialogContent>
<DialogContentText>
Are you sure you want to delete <b>{room.name}</b>? This removes the
- Matrix room, all client memberships, and any bridge mapping. This
- cannot be undone.
+ room, takes everyone out of it, and unlinks any messaging app channel.
+ This cannot be undone.
</DialogContentText>
</DialogContent>
<DialogActions>
diff --git a/gateway/src/pages/rooms/roomFilters.tsx b/gateway/src/pages/rooms/roomFilters.tsx
index 3b91b5f53..8db5134d5 100644
--- a/gateway/src/pages/rooms/roomFilters.tsx
+++ b/gateway/src/pages/rooms/roomFilters.tsx
@@ -217,7 +217,7 @@ export function RoomFilters({
<TextField
size="small"
select
- label="Connected User"
+ label="Connected user"
value={state.userFilter}
onChange={(e) => state.setUserFilter(e.target.value)}
sx={{ width: 200 }}
diff --git a/gateway/src/pages/templates/TemplatesPage.tsx b/gateway/src/pages/templates/TemplatesPage.tsx
new file mode 100644
index 000000000..a7b3baa5f
--- /dev/null
+++ b/gateway/src/pages/templates/TemplatesPage.tsx
@@ -0,0 +1,37 @@
+import AddIcon from "@mui/icons-material/Add";
+import { Box, Button, Stack, Typography } from "@mui/material";
+import { useState } from "react";
+import { useNavigate } from "react-router";
+import CreateTemplateDialog from "../resources/CreateTemplateDialog";
+import TemplatesTab from "../resources/TemplatesTab";
+
+/** Templates as a page of its own, in the new layout: today's list and
+ * upload, out of the Resources tabs. */
+export default function TemplatesPage() {
+ const navigate = useNavigate();
+ const [createOpen, setCreateOpen] = useState(false);
+ const [refreshKey, setRefreshKey] = useState(0);
+
+ return (
+ <Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}>
+ <Stack direction="row" alignItems="center" justifyContent="space-between" mb={2}>
+ <Typography variant="h5">Templates</Typography>
+ <Button variant="contained" startIcon={<AddIcon />} onClick={() => setCreateOpen(true)}>
+ Upload template
+ </Button>
+ </Stack>
+ <Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}>
+ <TemplatesTab refreshKey={refreshKey} />
+ </Box>
+ <CreateTemplateDialog
+ open={createOpen}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(id) => {
+ setCreateOpen(false);
+ setRefreshKey((k) => k + 1);
+ navigate(`/templates/${id}`);
+ }}
+ />
+ </Box>
+ );
+}
diff --git a/gateway/src/pages/users/CreateUserDialog.tsx b/gateway/src/pages/users/CreateUserDialog.tsx
index 096cb6749..509ecb142 100644
--- a/gateway/src/pages/users/CreateUserDialog.tsx
+++ b/gateway/src/pages/users/CreateUserDialog.tsx
@@ -57,7 +57,7 @@ export default function CreateUserDialog({ open, onClose, onCreated }: Props) {
return (
<Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
- <DialogTitle>Add User</DialogTitle>
+ <DialogTitle>Add user</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
{error && <Alert severity="error">{error}</Alert>}
diff --git a/gateway/src/pages/users/UsersPage.test.tsx b/gateway/src/pages/users/UsersPage.test.tsx
new file mode 100644
index 000000000..05e0dff41
--- /dev/null
+++ b/gateway/src/pages/users/UsersPage.test.tsx
@@ -0,0 +1,38 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ListedUser } from "../../data/api";
+import UsersPage from "./UsersPage";
+
+vi.mock("../../components/DataTable", () => import("../../test/FakeDataTable"));
+
+function user(id: string, can_delete: boolean): ListedUser {
+ return {
+ id,
+ name: id,
+ email: `${id}@example.com`,
+ role: "user",
+ created_at: "2026-10-01T00:00:00Z",
+ can_delete,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("UsersPage", () => {
+ it("offers to delete only the accounts the server says may be deleted", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(JSON.stringify([user("ada", true), user("op", false)]), { status: 200 }),
+ ),
+ );
+ render(<UsersPage />);
+
+ expect(await screen.findByRole("button", { name: "Delete [email protected]" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Delete [email protected]" })).toBeNull();
+ });
+});
diff --git a/gateway/src/pages/users/UsersPage.tsx b/gateway/src/pages/users/UsersPage.tsx
index 17fff13be..0785f1207 100644
--- a/gateway/src/pages/users/UsersPage.tsx
+++ b/gateway/src/pages/users/UsersPage.tsx
@@ -13,8 +13,7 @@ import {
import type { GridColDef } from "@mui/x-data-grid";
import { useMemo, useState } from "react";
import DataTable from "../../components/DataTable";
-import { useAuth } from "../../data/AuthContext";
-import type { UserInfo } from "../../data/api";
+import type { ListedUser } from "../../data/api";
import { useUsers } from "../../data/hooks";
import { formatDate } from "../../theme/hootFormat";
import CreateUserDialog from "./CreateUserDialog";
@@ -23,11 +22,9 @@ import DeleteUserDialog from "./DeleteUserDialog";
export default function UsersPage() {
const { data: users, loading, refetch } = useUsers();
const [createOpen, setCreateOpen] = useState(false);
- const [deleting, setDeleting] = useState<UserInfo | null>(null);
- const { user: self } = useAuth();
- const selfId = self?.id;
+ const [deleting, setDeleting] = useState<ListedUser | null>(null);
- const columns = useMemo<GridColDef<UserInfo>[]>(
+ const columns = useMemo<GridColDef<ListedUser>[]>(
() => [
{ field: "name", headerName: "Name", flex: 1, minWidth: 140 },
{ field: "email", headerName: "Email", flex: 1.5, minWidth: 200 },
@@ -54,10 +51,11 @@ export default function UsersPage() {
headerName: "",
width: 60,
sortable: false,
- // The server refuses administrator accounts and your own, so neither
- // is offered. You delete your own account from your account settings.
+ // The server refuses administrator accounts and your own, and says
+ // which rows it would refuse. You delete your own account from your
+ // account settings.
renderCell: ({ row }) =>
- row.role !== "admin" && row.id !== selfId ? (
+ row.can_delete ? (
<Tooltip title="Delete account">
<IconButton
size="small"
@@ -70,7 +68,7 @@ export default function UsersPage() {
) : null,
},
],
- [selfId],
+ [],
);
return (
@@ -82,7 +80,7 @@ export default function UsersPage() {
startIcon={<AddCircleOutline />}
onClick={() => setCreateOpen(true)}
>
- Add User
+ Add user
</Button>
</Stack>
diff --git a/gateway/src/pages/workspace/CreateInvitationDialog.tsx b/gateway/src/pages/workspace/CreateInvitationDialog.tsx
index 4c0b0fd88..cea2cce6a 100644
--- a/gateway/src/pages/workspace/CreateInvitationDialog.tsx
+++ b/gateway/src/pages/workspace/CreateInvitationDialog.tsx
@@ -142,7 +142,7 @@ export default function CreateInvitationDialog({
helperText={
emailEnabled
? "We'll e-mail them the link. Only someone signed in with this address can accept. Leave empty for anyone with the link."
- : "E-mail isn't set up on this server, so you'll get a link to send yourself. Only someone signed in with this address can accept. Leave empty for anyone with the link."
+ : "E-mail isn't set up here, so you'll get a link to send yourself. Only someone signed in with this address can accept. Leave empty for anyone with the link."
}
/>
<Stack direction="row" spacing={2}>
diff --git a/gateway/src/pages/workspace/DeleteWorkspaceSection.tsx b/gateway/src/pages/workspace/DeleteWorkspaceSection.tsx
index 967930c8d..80bf93e39 100644
--- a/gateway/src/pages/workspace/DeleteWorkspaceSection.tsx
+++ b/gateway/src/pages/workspace/DeleteWorkspaceSection.tsx
@@ -71,8 +71,8 @@ export default function DeleteWorkspaceSection({ tenantId, tenantName }: Props)
<DialogContent>
<DialogContentText sx={{ mb: 2 }}>
This deletes <b>{tenantName}</b> for good. Only an empty workspace can be
- deleted: remove its rooms, agents, resources, machines, connections and
- other members first. Type the workspace name to confirm.
+ deleted: remove its rooms, agents, resources, devices, connectors, messaging
+ apps and other users first. Type the workspace name to confirm.
</DialogContentText>
<TextField
fullWidth
diff --git a/gateway/src/pages/workspace/InvitationsSection.tsx b/gateway/src/pages/workspace/InvitationsSection.tsx
index 135eb0523..8a9bf0bfa 100644
--- a/gateway/src/pages/workspace/InvitationsSection.tsx
+++ b/gateway/src/pages/workspace/InvitationsSection.tsx
@@ -16,7 +16,7 @@ import {
fetchInvitations,
revokeInvitation,
} from "../../data/api";
-import { formatDate, titleCase } from "../../theme/hootFormat";
+import { formatDate, sentenceCase } from "../../theme/hootFormat";
import CreateInvitationDialog from "./CreateInvitationDialog";
import { useLoad } from "./useLoad";
@@ -81,7 +81,7 @@ export default function InvitationsSection({
field: "role",
headerName: "Role",
width: 110,
- valueFormatter: (value) => titleCase(String(value)),
+ valueFormatter: (value) => sentenceCase(String(value)),
},
{
field: "status",
@@ -128,7 +128,7 @@ export default function InvitationsSection({
</Stack>
{organization?.members_from_directory && (
<Alert severity="info">
- This organization's members come from your organization's account settings, so only
+ This organization's users come from your organization's account settings, so only
people already in the organization can accept an invitation. Add anyone new there
first.
</Alert>
diff --git a/gateway/src/pages/workspace/MembersSection.test.tsx b/gateway/src/pages/workspace/MembersSection.test.tsx
index 7afa51f01..6d9fea83c 100644
--- a/gateway/src/pages/workspace/MembersSection.test.tsx
+++ b/gateway/src/pages/workspace/MembersSection.test.tsx
@@ -121,8 +121,8 @@ describe("MembersSection", () => {
render(<MembersSection tenantId="t1" selfId="u1" />);
- expect(await screen.findByText("Org Admin, via organization")).toBeTruthy();
- expect(screen.getByText("Admin · Org Admin")).toBeTruthy();
+ expect(await screen.findByText("Org admin, via organization")).toBeTruthy();
+ expect(screen.getByText("Admin · Org admin")).toBeTruthy();
expect(screen.queryByLabelText("Remove [email protected]")).toBeNull();
expect(screen.queryByLabelText("Role for [email protected]")).toBeNull();
expect(screen.queryByLabelText("Remove [email protected]")).toBeNull();
diff --git a/gateway/src/pages/workspace/MembersSection.tsx b/gateway/src/pages/workspace/MembersSection.tsx
index 99cfd3cd2..6e86f5d83 100644
--- a/gateway/src/pages/workspace/MembersSection.tsx
+++ b/gateway/src/pages/workspace/MembersSection.tsx
@@ -21,7 +21,7 @@ import {
removeMember,
updateMemberRole,
} from "../../data/api";
-import { formatDate, titleCase } from "../../theme/hootFormat";
+import { formatDate, sentenceCase } from "../../theme/hootFormat";
import { useLoad } from "./useLoad";
type MemberRow = Member & { id: string };
@@ -100,7 +100,7 @@ export default function MembersSection({ tenantId, selfId }: Props) {
>
{roles.map((role) => (
<MenuItem key={role} value={role}>
- {titleCase(role)}
+ {sentenceCase(role)}
</MenuItem>
))}
</Select>
@@ -108,15 +108,15 @@ export default function MembersSection({ tenantId, selfId }: Props) {
<Tooltip
title={
row.via_organization
- ? "Administers this workspace through the organization. Change it on the Organization page."
- : "An organization admin, and so an admin of every workspace in it. Change it on the Organization page."
+ ? "Administers this workspace through the organization. Change it in the organization's settings."
+ : "An organization admin, and so an admin of every workspace in it. Change it in the organization's settings."
}
>
<Chip
label={
row.via_organization
- ? "Org Admin, via organization"
- : `${titleCase(row.role)} · Org Admin`
+ ? "Org admin, via organization"
+ : `${sentenceCase(row.role)} · Org admin`
}
size="small"
color="primary"
@@ -125,7 +125,7 @@ export default function MembersSection({ tenantId, selfId }: Props) {
</Tooltip>
) : (
<Chip
- label={titleCase(row.role)}
+ label={sentenceCase(row.role)}
size="small"
color={row.role === "member" ? "default" : "primary"}
/>
@@ -169,7 +169,7 @@ export default function MembersSection({ tenantId, selfId }: Props) {
return (
<Stack spacing={1.5}>
- <Typography variant="h6">Members</Typography>
+ <Typography variant="h6">Users</Typography>
{error && <Alert severity="error">{error}</Alert>}
{actionError && (
<Alert severity="error" onClose={() => setActionError(null)}>
diff --git a/gateway/src/pages/workspace/PeopleSection.tsx b/gateway/src/pages/workspace/PeopleSection.tsx
index c8d5a62e5..1fc35ca30 100644
--- a/gateway/src/pages/workspace/PeopleSection.tsx
+++ b/gateway/src/pages/workspace/PeopleSection.tsx
@@ -11,7 +11,7 @@ import type { GridColDef } from "@mui/x-data-grid";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import DataTable from "../../components/DataTable";
import { type Erasure, type Person, fetchErasures, fetchPeople } from "../../data/api";
-import { formatDate, titleCase } from "../../theme/hootFormat";
+import { formatDate, sentenceCase, titleCase } from "../../theme/hootFormat";
import EraseDialog from "./EraseDialog";
import { useLoad } from "./useLoad";
@@ -133,7 +133,7 @@ export default function PeopleSection({ tenantId }: { tenantId: string }) {
<Stack key={erasure.id} direction="row" spacing={1} alignItems="center">
<Chip
size="small"
- label={titleCase(erasure.state)}
+ label={sentenceCase(erasure.state)}
color={STATE_COLORS[erasure.state]}
/>
<Typography variant="body2">
diff --git a/gateway/src/pages/workspace/RetentionSection.test.tsx b/gateway/src/pages/workspace/RetentionSection.test.tsx
index 6a9ef648a..7533a47b7 100644
--- a/gateway/src/pages/workspace/RetentionSection.test.tsx
+++ b/gateway/src/pages/workspace/RetentionSection.test.tsx
@@ -46,7 +46,7 @@ describe("RetentionSection", () => {
"fetch",
vi.fn(async () => new Response(JSON.stringify({ detail: "boom" }), { status: 500 })),
);
- render(<RetentionSection tenantId="t1" />);
+ render(<RetentionSection tenantId="t1" canSetWindow />);
await screen.findByText("boom");
expect(screen.queryByText(/kept forever/)).toBeNull();
@@ -60,7 +60,7 @@ describe("RetentionSection", () => {
it("asks for confirmation with the number of messages before turning retention on", async () => {
const calls = serve(null, 1234);
- render(<RetentionSection tenantId="t1" />);
+ render(<RetentionSection tenantId="t1" canSetWindow />);
await screen.findByText(/Messages are kept forever/);
fireEvent.click(screen.getByLabelText("Delete messages older than"));
@@ -77,7 +77,7 @@ describe("RetentionSection", () => {
it("goes back to keeping forever without a confirmation", async () => {
const calls = serve(30);
- render(<RetentionSection tenantId="t1" />);
+ render(<RetentionSection tenantId="t1" canSetWindow />);
await screen.findByText(/Messages older than 30 days are deleted/);
fireEvent.click(screen.getByLabelText("Keep forever"));
@@ -90,7 +90,7 @@ describe("RetentionSection", () => {
it("does not save a custom window out of range", async () => {
serve(45);
- render(<RetentionSection tenantId="t1" />);
+ render(<RetentionSection tenantId="t1" canSetWindow />);
await screen.findByText(/Messages older than 45 days are deleted/);
const days = screen.getByLabelText("Days");
@@ -101,4 +101,17 @@ describe("RetentionSection", () => {
expect(screen.getByRole("button", { name: "Save" }).hasAttribute("disabled")).toBe(true),
);
});
+
+ it("lets an admin without their own membership turn retention off, but not on", async () => {
+ const calls = serve(30);
+ render(<RetentionSection tenantId="t1" canSetWindow={false} />);
+ await screen.findByText(/Messages older than 30 days are deleted/);
+
+ expect(screen.getByLabelText("Delete messages older than")).toHaveProperty("disabled", true);
+ expect(screen.getByText(/Only this workspace's own admins can turn retention on/)).toBeTruthy();
+
+ fireEvent.click(screen.getByLabelText("Keep forever"));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(calls.some((c) => c.method === "DELETE")).toBe(true));
+ });
});
diff --git a/gateway/src/pages/workspace/RetentionSection.tsx b/gateway/src/pages/workspace/RetentionSection.tsx
index 9315d522b..77048f8fa 100644
--- a/gateway/src/pages/workspace/RetentionSection.tsx
+++ b/gateway/src/pages/workspace/RetentionSection.tsx
@@ -37,7 +37,16 @@ export function describeRetention(days: number | null): string {
return `Messages older than ${days} ${days === 1 ? "day" : "days"} are deleted.`;
}
-export default function RetentionSection({ tenantId }: { tenantId: string }) {
+/** `canSetWindow` is the server's answer for turning retention on or changing
+ * its window, which takes an admin's own membership of the workspace; any
+ * admin may read it and turn it off. */
+export default function RetentionSection({
+ tenantId,
+ canSetWindow,
+}: {
+ tenantId: string;
+ canSetWindow: boolean;
+}) {
const load = useCallback(() => fetchRetentionPolicy(tenantId), [tenantId]);
const { data: policy, error, loading, refetch } = useLoad(load);
const current = policy?.message_retention_days ?? null;
@@ -139,13 +148,14 @@ export default function RetentionSection({ tenantId }: { tenantId: string }) {
value="window"
control={<Radio />}
label="Delete messages older than"
+ disabled={!canSetWindow}
sx={{ mr: 0 }}
/>
<TextField
select
size="small"
value={preset}
- disabled={mode !== "window"}
+ disabled={mode !== "window" || !canSetWindow}
onChange={(event) => setPreset(event.target.value)}
sx={{ minWidth: 140 }}
inputProps={{ "aria-label": "Retention window" }}
@@ -162,7 +172,7 @@ export default function RetentionSection({ tenantId }: { tenantId: string }) {
size="small"
label="Days"
value={customDays}
- disabled={mode !== "window"}
+ disabled={mode !== "window" || !canSetWindow}
onChange={(event) => setCustomDays(event.target.value)}
error={mode === "window" && invalid && customDays !== ""}
helperText={`1 to ${MAX_MESSAGE_RETENTION_DAYS}`}
@@ -171,6 +181,12 @@ export default function RetentionSection({ tenantId }: { tenantId: string }) {
)}
</Stack>
</RadioGroup>
+ {!canSetWindow && (
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
+ Only this workspace&apos;s own admins can turn retention on or change its
+ window. You can turn it off.
+ </Typography>
+ )}
<Stack direction="row" spacing={1} justifyContent="flex-end">
<Button disabled={unchanged || saving} onClick={resetToCurrent}>
Cancel
diff --git a/gateway/src/pages/workspace/WorkspacePage.tsx b/gateway/src/pages/workspace/WorkspacePage.tsx
index ac3e54118..4ad83eabf 100644
--- a/gateway/src/pages/workspace/WorkspacePage.tsx
+++ b/gateway/src/pages/workspace/WorkspacePage.tsx
@@ -1,4 +1,5 @@
import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";
+import type { Session, TenantMembership } from "../../data/api";
import { useAuth } from "../../data/AuthContext";
import DeleteWorkspaceSection from "./DeleteWorkspaceSection";
import InvitationsSection from "./InvitationsSection";
@@ -6,6 +7,65 @@ import MembersSection from "./MembersSection";
import PeopleSection from "./PeopleSection";
import RetentionSection from "./RetentionSection";
+function WorkspaceHeading({ tenant }: { tenant: TenantMembership }) {
+ return (
+ <Stack spacing={0.5} mb={3}>
+ <Typography variant="h5">{tenant.name}</Typography>
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
+ You are {tenant.role === "admin" ? "an admin" : `a ${tenant.role}`} of this workspace.
+ </Typography>
+ </Stack>
+ );
+}
+
+function UsersSections({
+ session,
+ tenant,
+ canAdmin,
+}: {
+ session: Session;
+ tenant: TenantMembership;
+ canAdmin: boolean;
+}) {
+ return (
+ <>
+ <MembersSection tenantId={tenant.id} selfId={session.user.id} />
+ {canAdmin ? (
+ <InvitationsSection
+ tenantId={tenant.id}
+ inOrganization={tenant.organization_id !== null}
+ emailEnabled={session.invite_email_enabled}
+ />
+ ) : (
+ <Alert severity="info">Ask a workspace admin to invite someone.</Alert>
+ )}
+ </>
+ );
+}
+
+/** Retention, for any admin, and erasing people's data, which like setting a
+ * retention window takes an admin's own membership. */
+function DataProtectionSections({ tenant }: { tenant: TenantMembership }) {
+ const { capabilities } = useAuth();
+ return (
+ <>
+ {capabilities.administersWorkspace && (
+ <RetentionSection
+ tenantId={tenant.id}
+ canSetWindow={capabilities.canManageDataProtection}
+ />
+ )}
+ {capabilities.canManageDataProtection && <PeopleSection tenantId={tenant.id} />}
+ </>
+ );
+}
+
+function DeleteSection({ tenant }: { tenant: TenantMembership }) {
+ const { capabilities } = useAuth();
+ if (!capabilities.canDeleteWorkspace) return null;
+ return <DeleteWorkspaceSection tenantId={tenant.id} tenantName={tenant.name} />;
+}
+
export default function WorkspacePage() {
const { session, canAdminTenant } = useAuth();
const tenant = session?.tenant;
@@ -13,31 +73,46 @@ export default function WorkspacePage() {
return (
<Box>
- <Stack spacing={0.5} mb={3}>
- <Typography variant="h5">{tenant.name}</Typography>
- <Typography variant="body2" sx={{ color: "text.secondary" }}>
- You are {tenant.role === "admin" ? "an admin" : `a ${tenant.role}`} of this workspace.
- </Typography>
+ <WorkspaceHeading tenant={tenant} />
+ <Stack spacing={4}>
+ <UsersSections session={session} tenant={tenant} canAdmin={canAdminTenant} />
+ <DataProtectionSections tenant={tenant} />
+ <DeleteSection tenant={tenant} />
+ </Stack>
+ </Box>
+ );
+}
+
+/** Workspace settings › General, in the new layout. */
+export function WorkspaceGeneralPage() {
+ const { session } = useAuth();
+ const tenant = session?.tenant;
+ if (!tenant) return <CircularProgress />;
+
+ return (
+ <Box>
+ <WorkspaceHeading tenant={tenant} />
+ <Stack spacing={4}>
+ <DataProtectionSections tenant={tenant} />
+ <DeleteSection tenant={tenant} />
</Stack>
+ </Box>
+ );
+}
+
+/** Workspace settings › Users, with the invite links, in the new layout. */
+export function WorkspaceUsersPage() {
+ const { session, canAdminTenant } = useAuth();
+ const tenant = session?.tenant;
+ if (!tenant) return <CircularProgress />;
+
+ return (
+ <Box>
+ <Typography variant="h5" mb={3}>
+ Users
+ </Typography>
<Stack spacing={4}>
- <MembersSection tenantId={tenant.id} selfId={session.user.id} />
- {canAdminTenant ? (
- <InvitationsSection
- tenantId={tenant.id}
- inOrganization={tenant.organization_id !== null}
- emailEnabled={session.invite_email_enabled}
- />
- ) : (
- <Alert severity="info">
- Ask a workspace admin to invite someone.
- </Alert>
- )}
- {canAdminTenant && <RetentionSection tenantId={tenant.id} />}
- {tenant.role === "admin" && <PeopleSection tenantId={tenant.id} />}
- {/* An admin membership, not the operator's bypass: the server checks the same. */}
- {tenant.role === "admin" && (
- <DeleteWorkspaceSection tenantId={tenant.id} tenantName={tenant.name} />
- )}
+ <UsersSections session={session} tenant={tenant} canAdmin={canAdminTenant} />
</Stack>
</Box>
);
diff --git a/gateway/src/routes/Guarded.tsx b/gateway/src/routes/Guarded.tsx
new file mode 100644
index 000000000..a6b01fd96
--- /dev/null
+++ b/gateway/src/routes/Guarded.tsx
@@ -0,0 +1,40 @@
+import type { ReactNode } from "react";
+import { Navigate, useLocation, useParams } from "react-router";
+import { useAuth } from "../data/AuthContext";
+import type { Rule } from "../data/capabilities";
+import { NoAccessPage } from "./StatusPages";
+
+/** Renders `children` only when `access` allows it for the signed-in person.
+ * The server refuses the page's requests either way; this keeps the page from
+ * loading into a column of errors, and says why. */
+export function Guarded({ access, children }: { access: Rule; children: ReactNode }) {
+ const { capabilities } = useAuth();
+ const answer = access(capabilities);
+ return answer.allowed ? <>{children}</> : <NoAccessPage access={answer} />;
+}
+
+/** `to` with `:name` filled from this route's parameters, keeping the query
+ * and the fragment, so a moved page's old links land on the same thing. What
+ * the target names itself, a query parameter or a fragment, wins over what is
+ * carried across. */
+export function RedirectTo({ to }: { to: string }) {
+ const params = useParams();
+ const { search, hash } = useLocation();
+ const filled = to.replace(/:([A-Za-z_]+)/g, (_, name: string) =>
+ encodeURIComponent(params[name] ?? ""),
+ );
+ const target = new URL(filled, "http://dashboard.invalid");
+ const query = new URLSearchParams(search);
+ target.searchParams.forEach((value, key) => query.set(key, value));
+ const merged = query.toString();
+ return (
+ <Navigate
+ replace
+ to={{
+ pathname: target.pathname,
+ search: merged === "" ? "" : `?${merged}`,
+ hash: target.hash !== "" ? target.hash : hash,
+ }}
+ />
+ );
+}
diff --git a/gateway/src/routes/SettingsLayout.tsx b/gateway/src/routes/SettingsLayout.tsx
new file mode 100644
index 000000000..e15876c6d
--- /dev/null
+++ b/gateway/src/routes/SettingsLayout.tsx
@@ -0,0 +1,98 @@
+import { Box, List, ListItemButton, ListItemText, Stack, Typography } from "@mui/material";
+import { useEffect } from "react";
+import { Navigate, NavLink, Outlet, useLocation } from "react-router";
+import { useAuth } from "../data/AuthContext";
+import {
+ type SettingsArea,
+ clearLandingAfterSwitch,
+ landingCarriedAcross,
+ rememberedSettingsPage,
+ rememberSettingsPage,
+} from "../data/settingsLanding";
+import { AREAS, type Layout, accessTo, menuOf } from "./routeTable";
+import { NoAccessPage } from "./StatusPages";
+
+/** A settings area: its section menu beside the page. The menu lists only the
+ * pages this person may open; the area remembers the page they were on. Who
+ * may enter the area at all is checked here, so a refused area shows no menu
+ * of pages they cannot use. */
+export function SettingsLayout({ area, layout }: { area: SettingsArea; layout: Layout }) {
+ const { capabilities } = useAuth();
+ const { pathname } = useLocation();
+ const definition = AREAS[area];
+ const entry = definition.access(capabilities);
+ const allowedHere = accessTo(pathname, layout, capabilities)?.allowed === true;
+
+ useEffect(() => {
+ if (entry.allowed && allowedHere) rememberSettingsPage(area, pathname);
+ }, [area, pathname, entry.allowed, allowedHere]);
+
+ if (!entry.allowed) return <NoAccessPage access={entry} />;
+
+ const menu = menuOf(area, layout, capabilities);
+ const organization = accessTo("/settings/org", layout, capabilities)?.allowed === true;
+ const otherArea =
+ area === "workspace" && organization
+ ? { label: "Organization settings ›", path: "/settings/org" }
+ : area === "organization"
+ ? { label: "‹ Workspace settings", path: "/settings" }
+ : null;
+
+ return (
+ <Stack direction="row" spacing={4} sx={{ minHeight: 0, flexGrow: 1 }}>
+ <Box component="nav" aria-label={definition.title} sx={{ width: 220, flexShrink: 0 }}>
+ <Typography variant="overline" sx={{ color: "text.secondary", px: 2 }}>
+ {definition.title}
+ </Typography>
+ <List dense>
+ {menu.map((item) => (
+ <ListItemButton
+ key={item.path}
+ component={NavLink}
+ to={item.path}
+ selected={pathname === item.path}
+ sx={{ borderRadius: 1 }}
+ >
+ <ListItemText primary={item.label} />
+ </ListItemButton>
+ ))}
+ {otherArea !== null && (
+ <ListItemButton component={NavLink} to={otherArea.path} sx={{ borderRadius: 1, mt: 1 }}>
+ <ListItemText primary={otherArea.label} />
+ </ListItemButton>
+ )}
+ </List>
+ </Box>
+ <Box sx={{ flexGrow: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
+ <Outlet />
+ </Box>
+ </Stack>
+ );
+}
+
+/** An area opened without naming a page. After a workspace switch from a
+ * settings page, that page; otherwise the page last open in the area. Either
+ * only when this person may open it in this workspace, and the area's first
+ * page when not, so a switch or a change of role never lands someone on a
+ * page they cannot use. A page named in the URL is different: it shows why it
+ * is refused (`Guarded`). */
+export function SettingsIndex({ area, layout }: { area: SettingsArea; layout: Layout }) {
+ const { capabilities } = useAuth();
+ const definition = AREAS[area];
+ const entry = definition.access(capabilities);
+ // Only the workspace area is where a switch lands.
+ const carried = area === "workspace" ? landingCarriedAcross() : null;
+ useEffect(() => {
+ if (area === "workspace") clearLandingAfterSwitch();
+ }, [area]);
+
+ if (!entry.allowed) return <NoAccessPage access={entry} />;
+
+ const candidates = [carried, rememberedSettingsPage(area)].filter(
+ (path): path is string => path !== null,
+ );
+ const landing =
+ candidates.find((path) => accessTo(path, layout, capabilities)?.allowed === true) ??
+ definition.first;
+ return <Navigate to={landing} replace />;
+}
diff --git a/gateway/src/routes/StatusPages.tsx b/gateway/src/routes/StatusPages.tsx
new file mode 100644
index 000000000..df48824b2
--- /dev/null
+++ b/gateway/src/routes/StatusPages.tsx
@@ -0,0 +1,58 @@
+import { Alert, Button, Stack, Typography } from "@mui/material";
+import { Link as RouterLink } from "react-router";
+import type { Access } from "../data/capabilities";
+import { useAuth } from "../data/AuthContext";
+import { howToTurnOn } from "../data/featureFlags";
+
+type Refusal = Exclude<Access, { allowed: true }>;
+
+/** What someone sees in place of a page they may not open, or one this
+ * server does not run, instead of the page loading and the API refusing it
+ * piece by piece. */
+export function NoAccessPage({ access }: { access: Refusal }) {
+ const { isOperator } = useAuth();
+ return (
+ <Stack spacing={2} sx={{ maxWidth: 560 }}>
+ <Typography variant="h5">
+ {access.reason === "not_enabled" ? "Not turned on" : "You don't have access to this page"}
+ </Typography>
+ <Typography>{access.message}</Typography>
+ {access.reason === "not_enabled" && isOperator && (
+ <Typography variant="body2" sx={{ color: "text.secondary" }}>
+ {howToTurnOn(access.flag)}
+ </Typography>
+ )}
+ <div>
+ <Button component={RouterLink} to="/" variant="outlined">
+ Go to the start page
+ </Button>
+ </div>
+ </Stack>
+ );
+}
+
+export function NotFoundPage() {
+ return (
+ <Stack spacing={2} sx={{ maxWidth: 560 }}>
+ <Typography variant="h5">There's no page here</Typography>
+ <Typography>The address may be mistyped, or the page may have moved.</Typography>
+ <div>
+ <Button component={RouterLink} to="/" variant="outlined">
+ Go to the start page
+ </Button>
+ </div>
+ </Stack>
+ );
+}
+
+/** A page of the new layout that is not built yet. Only a server with the
+ * new layout turned on shows it, and that is meant for development and
+ * staging until every page is in. */
+export function PlannedPage({ title }: { title: string }) {
+ return (
+ <Stack spacing={2}>
+ <Typography variant="h5">{title}</Typography>
+ <Alert severity="info">This page is part of the new layout and isn't built yet.</Alert>
+ </Stack>
+ );
+}
diff --git a/gateway/src/routes/renderRoutes.tsx b/gateway/src/routes/renderRoutes.tsx
new file mode 100644
index 000000000..1f24da7dd
--- /dev/null
+++ b/gateway/src/routes/renderRoutes.tsx
@@ -0,0 +1,58 @@
+import type { ReactNode } from "react";
+import { Route } from "react-router";
+import type { SettingsArea } from "../data/settingsLanding";
+import { Guarded, RedirectTo } from "./Guarded";
+import { type AppRoute, type Layout, routesFor } from "./routeTable";
+import { SettingsIndex, SettingsLayout } from "./SettingsLayout";
+
+function routePath(path: string): { index: true } | { path: string } {
+ return path === "/" ? { index: true } : { path: path.slice(1) };
+}
+
+function routeElement(route: AppRoute, layout: Layout): ReactNode {
+ const key = `${route.kind}:${route.path}`;
+ switch (route.kind) {
+ case "page":
+ return (
+ <Route
+ key={key}
+ {...routePath(route.path)}
+ element={<Guarded access={route.access}>{route.element}</Guarded>}
+ />
+ );
+ case "area":
+ return (
+ <Route
+ key={key}
+ {...routePath(route.path)}
+ element={<SettingsIndex area={route.area} layout={layout} />}
+ />
+ );
+ case "redirect":
+ return <Route key={key} {...routePath(route.path)} element={<RedirectTo to={route.to} />} />;
+ }
+}
+
+/** The signed-in dashboard's routes for `layout`, from the route table. A
+ * settings area's pages share its layout route, which draws the area's menu. */
+export function renderRoutes(layout: Layout): ReactNode[] {
+ const top: ReactNode[] = [];
+ const byArea = new Map<SettingsArea, ReactNode[]>();
+ for (const route of routesFor(layout)) {
+ if (route.kind === "page" && route.area !== undefined) {
+ const pages = byArea.get(route.area) ?? [];
+ pages.push(routeElement(route, layout));
+ byArea.set(route.area, pages);
+ } else {
+ top.push(routeElement(route, layout));
+ }
+ }
+ for (const [area, pages] of byArea) {
+ top.push(
+ <Route key={`area-layout:${area}`} element={<SettingsLayout area={area} layout={layout} />}>
+ {pages}
+ </Route>,
+ );
+ }
+ return top;
+}
diff --git a/gateway/src/routes/routeTable.tsx b/gateway/src/routes/routeTable.tsx
new file mode 100644
index 000000000..4298c53fa
--- /dev/null
+++ b/gateway/src/routes/routeTable.tsx
@@ -0,0 +1,412 @@
+import AccountTreeOutlined from "@mui/icons-material/AccountTreeOutlined";
+import AdminPanelSettingsOutlined from "@mui/icons-material/AdminPanelSettingsOutlined";
+import ApartmentOutlined from "@mui/icons-material/ApartmentOutlined";
+import ChatBubbleOutlineOutlined from "@mui/icons-material/ChatBubbleOutlineOutlined";
+import ComputerOutlined from "@mui/icons-material/ComputerOutlined";
+import DashboardOutlined from "@mui/icons-material/DashboardOutlined";
+import DataUsageOutlined from "@mui/icons-material/DataUsageOutlined";
+import DescriptionOutlined from "@mui/icons-material/DescriptionOutlined";
+import DnsOutlined from "@mui/icons-material/DnsOutlined";
+import FolderOutlined from "@mui/icons-material/FolderOutlined";
+import MeetingRoomOutlined from "@mui/icons-material/MeetingRoomOutlined";
+import PeopleOutlined from "@mui/icons-material/PeopleOutlined";
+import PowerOutlined from "@mui/icons-material/PowerOutlined";
+import SettingsOutlined from "@mui/icons-material/SettingsOutlined";
+import SmartToyOutlined from "@mui/icons-material/SmartToyOutlined";
+import VpnKeyOutlined from "@mui/icons-material/VpnKeyOutlined";
+import WorkspacesOutlined from "@mui/icons-material/WorkspacesOutlined";
+import type { ComponentType, ReactNode } from "react";
+import {
+ type Access,
+ type Capabilities,
+ type Rule,
+ agentManagement,
+ allOf,
+ everyone,
+ inOrganization,
+ operators,
+ organizationAdmins,
+ organizationAdminsOnly,
+ organizationConnectorApps,
+ serviceConnections,
+ workspaceAdmins,
+} from "../data/capabilities";
+import type { SettingsArea } from "../data/settingsLanding";
+import AgentDetailPage from "../pages/agents/AgentDetailPage";
+import AgentsPage from "../pages/agents/AgentsPage";
+import CollaborationsPage from "../pages/collaborations/CollaborationsPage";
+import ConnectorAppsPage from "../pages/connector-apps/ConnectorAppsPage";
+import EcosystemGraphPage from "../pages/ecosystem/EcosystemGraphPage";
+import MachinesPage from "../pages/machines/MachinesPage";
+import OperatorWorkspacesPage from "../pages/operator/OperatorWorkspacesPage";
+import OrganizationPage, {
+ OrganizationAuditLogPage,
+ OrganizationConnectorsPage,
+ OrganizationGeneralPage,
+ OrganizationUsersPage,
+ OrganizationWorkspacesPage,
+} from "../pages/organization/OrganizationPage";
+import RegistrationKeysPage from "../pages/registration-keys/RegistrationKeysPage";
+import DocumentDetailPage from "../pages/resources/DocumentDetailPage";
+import PackageDetailPage from "../pages/resources/PackageDetailPage";
+import ReferenceDetailPage from "../pages/resources/ReferenceDetailPage";
+import ResourcesPage from "../pages/resources/ResourcesPage";
+import TemplateDetailPage from "../pages/resources/TemplateDetailPage";
+import CreateRoomPage from "../pages/rooms/CreateRoomPage";
+import GroupsPage from "../pages/rooms/GroupsPage";
+import RoomDetailPage from "../pages/rooms/RoomDetailPage";
+import RoomScopedDocumentView from "../pages/rooms/RoomScopedDocumentView";
+import RoomsGraphPage from "../pages/rooms/RoomsGraphPage";
+import RoomsPage from "../pages/rooms/RoomsPage";
+import TemplatesPage from "../pages/templates/TemplatesPage";
+import UsagePage from "../pages/usage/UsagePage";
+import UsersPage from "../pages/users/UsersPage";
+import WorkspacePage, {
+ WorkspaceGeneralPage,
+ WorkspaceUsersPage,
+} from "../pages/workspace/WorkspacePage";
+import { PlannedPage } from "./StatusPages";
+
+/** Every page the signed-in dashboard has, in one table: its URL, who may
+ * open it, and which layout it belongs to. The routes, their guards, the
+ * rail and the settings menus are all built from it, so a page cannot be
+ * reachable by URL and hidden from the nav, or the other way round.
+ *
+ * Two layouts live side by side while the new one is built: `current`, what
+ * a server shows today, and `v2`, behind the `gateway_v2` flag. A page that
+ * moved has a redirect in each: from its old URL in `v2`, and back from its
+ * new one in `current`, so a link from Console or the docs works on a server
+ * with the flag either way.
+ *
+ * Every `path` here must also be in `PAGE_PATHS` (`core/switch_core/gateway/
+ * ui.py`), which says what switch-core serves the dashboard for on a reload;
+ * `test_gateway_ui.py` holds the two equal. */
+
+export type Layout = "current" | "v2";
+
+const BOTH: readonly Layout[] = ["current", "v2"];
+const CURRENT: readonly Layout[] = ["current"];
+const V2: readonly Layout[] = ["v2"];
+
+export interface PageRoute {
+ kind: "page";
+ path: string;
+ layouts: readonly Layout[];
+ access: Rule;
+ element: ReactNode;
+ /** The settings area the page sits in, with its label in that area's menu. */
+ area?: SettingsArea;
+ menu?: string;
+}
+
+/** An area's own URL, which opens the page last used there. */
+export interface AreaRoute {
+ kind: "area";
+ path: string;
+ layouts: readonly Layout[];
+ area: SettingsArea;
+}
+
+export interface RedirectRoute {
+ kind: "redirect";
+ path: string;
+ layouts: readonly Layout[];
+ to: string;
+}
+
+export type AppRoute = PageRoute | AreaRoute | RedirectRoute;
+
+export interface AreaDefinition {
+ title: string;
+ access: Rule;
+ /** Where the area opens when no remembered page may be used. */
+ first: string;
+}
+
+export const AREAS: Record<SettingsArea, AreaDefinition> = {
+ workspace: { title: "Workspace settings", access: everyone, first: "/settings/general" },
+ organization: {
+ title: "Organization settings",
+ access: organizationAdmins,
+ first: "/settings/org/general",
+ },
+ platform: { title: "Platform", access: operators, first: "/platform/workspaces" },
+};
+
+function page(
+ path: string,
+ layouts: readonly Layout[],
+ access: Rule,
+ element: ReactNode,
+): PageRoute {
+ return { kind: "page", path, layouts, access, element };
+}
+
+function settingsPage(
+ path: string,
+ area: SettingsArea,
+ menu: string,
+ access: Rule,
+ element: ReactNode,
+): PageRoute {
+ return { kind: "page", path, layouts: V2, access, element, area, menu };
+}
+
+function areaIndex(path: string, area: SettingsArea): AreaRoute {
+ return { kind: "area", path, layouts: V2, area };
+}
+
+function redirect(path: string, layouts: readonly Layout[], to: string): RedirectRoute {
+ return { kind: "redirect", path, layouts, to };
+}
+
+const orgConnectors = allOf(organizationAdminsOnly, serviceConnections, organizationConnectorApps);
+
+export const ROUTES: readonly AppRoute[] = [
+ redirect("/", CURRENT, "/rooms"),
+ redirect("/", V2, "/overview"),
+ page("/overview", V2, everyone, <PlannedPage title="Overview" />),
+ redirect("/overview", CURRENT, "/"),
+
+ page("/ecosystem", BOTH, everyone, <EcosystemGraphPage />),
+ page("/rooms", BOTH, everyone, <RoomsPage />),
+ page("/rooms/new", BOTH, everyone, <CreateRoomPage />),
+ page("/rooms/groups", BOTH, everyone, <GroupsPage />),
+ page("/rooms/graph", BOTH, everyone, <RoomsGraphPage />),
+ page("/rooms/:roomId", BOTH, everyone, <RoomDetailPage />),
+ page("/rooms/:roomId/documents/:documentId", BOTH, everyone, <RoomScopedDocumentView />),
+
+ page("/resources", CURRENT, everyone, <ResourcesPage withTemplates />),
+ page("/resources", V2, everyone, <ResourcesPage withTemplates={false} />),
+ page("/resources/references/:id", BOTH, everyone, <ReferenceDetailPage />),
+ page("/resources/documents/:id", BOTH, everyone, <DocumentDetailPage />),
+ page("/resources/packages/:id", BOTH, everyone, <PackageDetailPage />),
+ page("/resources/templates/:id", CURRENT, everyone, <TemplateDetailPage />),
+ redirect("/resources/templates/:id", V2, "/templates/:id"),
+ page("/templates", V2, everyone, <TemplatesPage />),
+ redirect("/templates", CURRENT, "/resources?tab=templates"),
+ page("/templates/:id", V2, everyone, <TemplateDetailPage />),
+ redirect("/templates/:id", CURRENT, "/resources/templates/:id"),
+
+ page("/agents", BOTH, everyone, <AgentsPage />),
+ page("/agents/:agentId", BOTH, everyone, <AgentDetailPage />),
+
+ // Today `/connectors` is the operator's server-wide connector apps. In the
+ // new layout it is everyone's connector catalogue, and the operator's page
+ // moves to the Platform area.
+ page("/connectors", CURRENT, operators, <ConnectorAppsPage />),
+ page("/connectors", V2, serviceConnections, <PlannedPage title="Connectors" />),
+ page("/connectors/:connectorId", V2, serviceConnections, <PlannedPage title="Connector" />),
+
+ page("/machines", CURRENT, agentManagement, <MachinesPage />),
+ redirect("/machines", V2, "/settings/devices"),
+ page("/collaborations", CURRENT, everyone, <CollaborationsPage />),
+ redirect("/collaborations", V2, "/settings/messaging-apps"),
+ page("/registration-keys", CURRENT, everyone, <RegistrationKeysPage />),
+ redirect("/registration-keys", V2, "/settings/api-keys"),
+ page("/workspace", CURRENT, everyone, <WorkspacePage />),
+ redirect("/workspace", V2, "/settings/users"),
+ page("/organization", CURRENT, inOrganization, <OrganizationPage />),
+ redirect("/organization", V2, "/settings/org"),
+ page("/usage", CURRENT, workspaceAdmins, <UsagePage />),
+ page("/users", CURRENT, operators, <UsersPage />),
+ redirect("/users", V2, "/platform/users"),
+ page("/operator/workspaces", CURRENT, operators, <OperatorWorkspacesPage />),
+ redirect("/operator/workspaces", V2, "/platform/workspaces"),
+
+ // Workspace settings. `/usage` keeps its URL until Usage & budget is
+ // rebuilt, and sits here in the meantime.
+ areaIndex("/settings", "workspace"),
+ redirect("/settings", CURRENT, "/workspace"),
+ settingsPage("/settings/general", "workspace", "General", everyone, <WorkspaceGeneralPage />),
+ redirect("/settings/general", CURRENT, "/workspace"),
+ settingsPage("/settings/users", "workspace", "Users", everyone, <WorkspaceUsersPage />),
+ redirect("/settings/users", CURRENT, "/workspace"),
+ settingsPage(
+ "/settings/messaging-apps",
+ "workspace",
+ "Messaging apps",
+ everyone,
+ <CollaborationsPage />,
+ ),
+ redirect("/settings/messaging-apps", CURRENT, "/collaborations"),
+ settingsPage(
+ "/settings/connectors",
+ "workspace",
+ "Connectors",
+ serviceConnections,
+ <PlannedPage title="Connectors" />,
+ ),
+ settingsPage("/settings/api-keys", "workspace", "API keys", everyone, <RegistrationKeysPage />),
+ redirect("/settings/api-keys", CURRENT, "/registration-keys"),
+ settingsPage(
+ "/settings/guardrails",
+ "workspace",
+ "Guardrails",
+ everyone,
+ <PlannedPage title="Guardrails" />,
+ ),
+ settingsPage("/settings/devices", "workspace", "Devices", agentManagement, <MachinesPage />),
+ redirect("/settings/devices", CURRENT, "/machines"),
+ settingsPage("/usage", "workspace", "Usage & budget", workspaceAdmins, <UsagePage />),
+ settingsPage(
+ "/settings/account",
+ "workspace",
+ "Your account",
+ everyone,
+ <PlannedPage title="Your account" />,
+ ),
+
+ // Organization settings: the area admits the organization's admins, and
+ // the operator to restore one; its pages beyond that are the admins' alone.
+ areaIndex("/settings/org", "organization"),
+ redirect("/settings/org", CURRENT, "/organization"),
+ settingsPage(
+ "/settings/org/general",
+ "organization",
+ "General",
+ everyone,
+ <OrganizationGeneralPage />,
+ ),
+ redirect("/settings/org/general", CURRENT, "/organization"),
+ settingsPage(
+ "/settings/org/workspaces",
+ "organization",
+ "Workspaces",
+ everyone,
+ <OrganizationWorkspacesPage />,
+ ),
+ redirect("/settings/org/workspaces", CURRENT, "/organization"),
+ settingsPage("/settings/org/users", "organization", "Users", everyone, <OrganizationUsersPage />),
+ redirect("/settings/org/users", CURRENT, "/organization"),
+ settingsPage(
+ "/settings/org/connectors",
+ "organization",
+ "Connectors and apps",
+ orgConnectors,
+ <OrganizationConnectorsPage />,
+ ),
+ redirect("/settings/org/connectors", CURRENT, "/organization"),
+ settingsPage(
+ "/settings/org/guardrails",
+ "organization",
+ "Guardrails",
+ organizationAdminsOnly,
+ <PlannedPage title="Guardrails" />,
+ ),
+ settingsPage(
+ "/settings/org/devices",
+ "organization",
+ "Devices",
+ organizationAdminsOnly,
+ <PlannedPage title="Devices" />,
+ ),
+ settingsPage(
+ "/settings/org/audit-log",
+ "organization",
+ "Audit log",
+ organizationAdminsOnly,
+ <OrganizationAuditLogPage />,
+ ),
+ redirect("/settings/org/audit-log", CURRENT, "/organization"),
+
+ // The platform operator's pages.
+ areaIndex("/platform", "platform"),
+ redirect("/platform", CURRENT, "/operator/workspaces"),
+ settingsPage(
+ "/platform/workspaces",
+ "platform",
+ "All workspaces",
+ everyone,
+ <OperatorWorkspacesPage />,
+ ),
+ redirect("/platform/workspaces", CURRENT, "/operator/workspaces"),
+ settingsPage("/platform/users", "platform", "Users", everyone, <UsersPage />),
+ redirect("/platform/users", CURRENT, "/users"),
+ settingsPage("/platform/connectors", "platform", "Connectors", everyone, <ConnectorAppsPage />),
+ redirect("/platform/connectors", CURRENT, "/connectors"),
+];
+
+export function routesFor(layout: Layout): AppRoute[] {
+ return ROUTES.filter((route) => route.layouts.includes(layout));
+}
+
+/** Whether `path` (a page's own URL, not a pattern) may be opened in
+ * `layout`: its area's rule and its own. A URL that is no page there, or only
+ * a redirect, is not. */
+export function accessTo(path: string, layout: Layout, caps: Capabilities): Access | null {
+ const route = routesFor(layout).find((r) => r.path === path && r.kind !== "redirect");
+ if (route === undefined || route.kind === "redirect") return null;
+ if (route.kind === "area") return AREAS[route.area].access(caps);
+ return route.area === undefined
+ ? route.access(caps)
+ : allOf(AREAS[route.area].access, route.access)(caps);
+}
+
+/** The pages of `area`'s menu that `caps` may open, in order. */
+export function menuOf(
+ area: SettingsArea,
+ layout: Layout,
+ caps: Capabilities,
+): { label: string; path: string }[] {
+ return routesFor(layout)
+ .filter(
+ (r): r is PageRoute & { menu: string } =>
+ r.kind === "page" && r.area === area && r.menu !== undefined,
+ )
+ .filter((r) => r.access(caps).allowed)
+ .map((r) => ({ label: r.menu, path: r.path }));
+}
+
+export interface RailItem {
+ label: string;
+ to: string;
+ icon: ComponentType<{ sx?: object }>;
+ /** The paths under which the item shows as the current one. */
+ activeFor: readonly string[];
+}
+
+function railItem(
+ label: string,
+ to: string,
+ icon: ComponentType<{ sx?: object }>,
+ activeFor: readonly string[] = [to],
+): RailItem {
+ return { label, to, icon, activeFor };
+}
+
+/** The rail, in order, for each layout. An item shows only to someone who may
+ * open the page it leads to (`accessTo`). */
+export const RAIL: Record<Layout, readonly RailItem[]> = {
+ current: [
+ railItem("Ecosystem", "/ecosystem", AccountTreeOutlined),
+ railItem("Rooms", "/rooms", MeetingRoomOutlined),
+ railItem("Resources", "/resources", FolderOutlined),
+ railItem("Agents", "/agents", SmartToyOutlined),
+ railItem("Apps", "/collaborations", ChatBubbleOutlineOutlined),
+ railItem("API keys", "/registration-keys", VpnKeyOutlined),
+ railItem("Workspace", "/workspace", WorkspacesOutlined),
+ railItem("Organization", "/organization", ApartmentOutlined),
+ railItem("Devices", "/machines", ComputerOutlined),
+ railItem("Usage", "/usage", DataUsageOutlined),
+ railItem("All workspaces", "/operator/workspaces", DnsOutlined),
+ railItem("Users", "/users", PeopleOutlined),
+ railItem("Connectors", "/connectors", PowerOutlined),
+ ],
+ // Ecosystem keeps a rail item until Overview links to the graph.
+ v2: [
+ railItem("Overview", "/overview", DashboardOutlined),
+ railItem("Agents", "/agents", SmartToyOutlined),
+ railItem("Rooms", "/rooms", MeetingRoomOutlined),
+ railItem("Templates", "/templates", DescriptionOutlined),
+ railItem("Connectors", "/connectors", PowerOutlined),
+ railItem("Resources", "/resources", FolderOutlined),
+ railItem("Ecosystem", "/ecosystem", AccountTreeOutlined),
+ railItem("Settings", "/settings", SettingsOutlined, ["/settings", "/usage"]),
+ railItem("Platform", "/platform", AdminPanelSettingsOutlined),
+ ],
+};
+
+export function railFor(layout: Layout, caps: Capabilities): RailItem[] {
+ return RAIL[layout].filter((item) => accessTo(item.to, layout, caps)?.allowed === true);
+}
diff --git a/gateway/src/theme/hootFormat.ts b/gateway/src/theme/hootFormat.ts
index 0ebd1f357..eb9d279f2 100644
--- a/gateway/src/theme/hootFormat.ts
+++ b/gateway/src/theme/hootFormat.ts
@@ -81,9 +81,10 @@ export const CHANNEL_TYPE_LABELS: Record<string, string> = {
};
export const channelTypeLabel = (value: string | null | undefined): string =>
- value ? (CHANNEL_TYPE_LABELS[value] ?? titleCase(value)) : EM_DASH;
+ value ? (CHANNEL_TYPE_LABELS[value] ?? sentenceCase(value)) : EM_DASH;
-/** `session_addressable` -> `Session Addressable`. Status labels are Title Case. */
+/** `session_addressable` -> `Session Addressable`, for names, such as a
+ * platform's where it has no label of its own. */
export function titleCase(value: string): string {
return value
.replace(/[_-]+/g, " ")
@@ -91,6 +92,13 @@ export function titleCase(value: string): string {
.replace(/\b\w/g, (c) => c.toUpperCase());
}
+/** `session_addressable` -> `Session addressable`, for states, roles and
+ * kinds: labels are sentence case. */
+export function sentenceCase(value: string): string {
+ const words = value.replace(/[_-]+/g, " ").trim().toLowerCase();
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
/** A messaging platform's own name for itself, where title-casing its key
* gets it wrong — `teams` is Microsoft's own app, not a generic "Teams".
* Falls back to title case for any platform with no name of its own to get
diff --git a/gateway/src/vocabulary.test.ts b/gateway/src/vocabulary.test.ts
new file mode 100644
index 000000000..f50d80c0d
--- /dev/null
+++ b/gateway/src/vocabulary.test.ts
@@ -0,0 +1,94 @@
+import ts from "typescript";
+import { describe, expect, it } from "vitest";
+
+/** Every source file's text, tests left out: what the dashboard can show.
+ * Vitest's module cache can keep an older list of files on a developer's
+ * machine, so a file added since is checked once that cache clears; CI
+ * always starts without one. */
+const SOURCES = import.meta.glob<string>(["./**/*.{ts,tsx}", "!./**/*.test.{ts,tsx}"], {
+ query: "?raw",
+ import: "default",
+ eager: true,
+});
+
+/** Words the dashboard no longer uses, each with what to write instead.
+ * `alone` says whether a literal holding only the word counts: "server" on
+ * its own is a value the server sends (a connector app's scope), and
+ * Discord's name for a guild. */
+const RETIRED: { word: RegExp; instead: string; alone: boolean }[] = [
+ { word: /\bmachines?\b/i, instead: "device", alone: true },
+ { word: /\bregistration keys?\b/i, instead: "API key", alone: true },
+ { word: /\bregister agents?\b/i, instead: "Add agent", alone: true },
+ {
+ word: /(?<!\b(?:Discord|Mattermost) )\bservers?\b/i,
+ instead: '"here", "Switch" or "Switch\'s configuration"',
+ alone: false,
+ },
+ {
+ word: /\bconnections?\b/i,
+ instead: '"connector", or "messaging app" for a chat app',
+ alone: true,
+ },
+ { word: /\bMatrix\b/, instead: "nothing: Switch no longer runs on Matrix", alone: true },
+];
+
+/** Uses of a retired word that mean something else, removed before checking. */
+const ALLOWED = [
+ // A network connection, not a connector.
+ "secure connection",
+ "lost its connection",
+ "its connection stopped responding",
+ // The controller's own command-line flag.
+ "--server",
+];
+
+/** Text a person could read: JSX text, and string and template literals.
+ * A literal holding one lowercase word is `alone`: often a key or a value
+ * the server sends rather than copy, so only some words count there. One
+ * lowercase token that is not a plain word is a path or a key, not copy. */
+function copyIn(
+ source: string,
+ fileName: string,
+): { line: number; text: string; alone: boolean }[] {
+ const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const found: { line: number; text: string; alone: boolean }[] = [];
+ const add = (node: ts.Node, text: string, isJsxText: boolean) => {
+ const trimmed = text.trim();
+ if (trimmed === "") return;
+ const alone = !isJsxText && !/\s/.test(trimmed) && !/^[A-Z]/.test(trimmed);
+ if (alone && !/^[a-z]+$/.test(trimmed)) return;
+ found.push({ line: file.getLineAndCharacterOfPosition(node.getStart()).line + 1, text: trimmed, alone });
+ };
+ const visit = (node: ts.Node) => {
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) return;
+ if (ts.isJsxText(node)) add(node, node.text, true);
+ else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) add(node, node.text, false);
+ else if (ts.isTemplateExpression(node)) {
+ add(node, [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join("…"), false);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ return found;
+}
+
+describe("dashboard vocabulary", () => {
+ it("reads every source file", () => {
+ expect(Object.keys(SOURCES).length).toBeGreaterThan(100);
+ });
+
+ it("uses none of the retired words", () => {
+ const problems: string[] = [];
+ for (const [path, source] of Object.entries(SOURCES)) {
+ for (const { line, text, alone } of copyIn(source, path)) {
+ const checked = ALLOWED.reduce((rest, allowed) => rest.split(allowed).join(" "), text);
+ for (const { word, instead, alone: countsAlone } of RETIRED) {
+ if (alone && !countsAlone) continue;
+ const match = checked.match(word);
+ if (match) problems.push(`${path}:${line} "${match[0]}" → ${instead}: ${text}`);
+ }
+ }
+ }
+ expect(problems).toEqual([]);
+ });
+});